diff --git a/.gitattributes b/.gitattributes index 6b5ce8f9331e4bb26cef57fad623a9c673f2988f..49c3306d1882d1c8a228ead8e55ed769c57fded2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,10 @@ *.7z filter=lfs diff=lfs merge=lfs -text +*.pdf filter=lfs diff=lfs merge=lfs -text +*.exe filter=lfs diff=lfs merge=lfs -text +*.pfb filter=lfs diff=lfs merge=lfs -text +*.bcmap filter=lfs diff=lfs merge=lfs -text +*.bcmap filter=lfs diff=lfs merge=lfs -text +*.ttf filter=lfs diff=lfs merge=lfs -text *.woff2 filter=lfs diff=lfs merge=lfs -text *.icns filter=lfs diff=lfs merge=lfs -text *.arrow filter=lfs diff=lfs merge=lfs -text diff --git a/apps/readest-app/src/__tests__/utils/paragraph.test.ts b/apps/readest-app/src/__tests__/utils/paragraph.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..55d74ded9ec22329c7544fcf28bb3960f247932a --- /dev/null +++ b/apps/readest-app/src/__tests__/utils/paragraph.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect } from 'vitest'; +import { ParagraphIterator } from '@/utils/paragraph'; + +const createDoc = (body: string): Document => + new DOMParser().parseFromString(`${body}`, 'text/html'); + +describe('ParagraphIterator', () => { + it('skips whitespace-only paragraphs', async () => { + const doc = createDoc(` +

First

+

+

 

+

\u200b

+

\u00a0

+


+

Second

+ `); + + const iterator = await ParagraphIterator.createAsync(doc, 1000); + + expect(iterator.length).toBe(2); + expect(iterator.first()?.toString()).toContain('First'); + expect(iterator.next()?.toString()).toContain('Second'); + }); + + it('keeps paragraphs with non-text content', async () => { + const doc = createDoc(` +

Intro

+

+

Outro

+ `); + + const iterator = await ParagraphIterator.createAsync(doc, 1000); + + expect(iterator.length).toBe(3); + + iterator.first(); + expect(iterator.current()?.toString()).toContain('Intro'); + + const imageRange = iterator.next(); + const fragment = imageRange?.cloneContents(); + expect(fragment?.querySelector('img')).not.toBeNull(); + + expect(iterator.next()?.toString()).toContain('Outro'); + }); +}); diff --git a/apps/readest-app/src/utils/paragraph.ts b/apps/readest-app/src/utils/paragraph.ts index 65c8c8625b3e76a6d75457adf56e1e83cb0bceab..8ad801090946f23c6cfaa65e46a250c4f4650c0e 100644 --- a/apps/readest-app/src/utils/paragraph.ts +++ b/apps/readest-app/src/utils/paragraph.ts @@ -31,16 +31,19 @@ const blockTags = new Set([ const MAX_BLOCKS = 5000; +const INVISIBLE_TEXT_PATTERN = + /[\s\u00a0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\u200b-\u200d\u2060\ufeff]/g; +const MEDIA_SELECTOR = 'img, svg, video, audio, canvas, math, iframe, object, embed, hr'; + +const hasMeaningfulText = (text?: string | null): boolean => + (text ?? '').replace(INVISIBLE_TEXT_PATTERN, '').length > 0; + const rangeHasContent = (range: Range): boolean => { try { - const container = range.commonAncestorContainer; - if (container.nodeType === Node.TEXT_NODE) { - return (container.textContent?.trim().length ?? 0) > 0; - } - if (container.nodeType === Node.ELEMENT_NODE) { - return (container as Element).textContent?.trim().length !== 0; - } - return true; + const text = range.toString(); + if (hasMeaningfulText(text)) return true; + const fragment = range.cloneContents(); + return !!fragment.querySelector?.(MEDIA_SELECTOR); } catch { return false; } @@ -48,7 +51,7 @@ const rangeHasContent = (range: Range): boolean => { const hasDirectText = (node: Element): boolean => Array.from(node.childNodes).some( - (child) => child.nodeType === Node.TEXT_NODE && child.textContent?.trim(), + (child) => child.nodeType === Node.TEXT_NODE && hasMeaningfulText(child.textContent), ); const hasBlockChild = (node: Element): boolean => diff --git a/apps/readest-app/src/utils/style.ts b/apps/readest-app/src/utils/style.ts index 5a8c036f76f12e3d82a363376674dfc31727edbb..d9ea27589146c1eae019a1fe353535484bf92b8a 100644 --- a/apps/readest-app/src/utils/style.ts +++ b/apps/readest-app/src/utils/style.ts @@ -867,10 +867,16 @@ export const applyTableStyle = (document: Document) => { table.style.width = `calc(min(${computedWidth}, var(--available-width)))`; } } + const parentWidth = window.getComputedStyle(parent as Element).width; + const parentContainerWidth = parseFloat(parentWidth) || 0; if (totalTableWidth > 0) { const scale = `calc(min(1, var(--available-width) / ${totalTableWidth}))`; table.style.transformOrigin = 'left top'; table.style.transform = `scale(${scale})`; + } else if (parentContainerWidth > 0) { + const scale = `calc(min(1, var(--available-width) / ${parentContainerWidth}))`; + table.style.transformOrigin = 'center top'; + table.style.transform = `scale(${scale})`; } }); }; diff --git a/packages/foliate-js/.gitattributes b/packages/foliate-js/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..50f960ce7feb5cd9616f9c23014c9637015c162d --- /dev/null +++ b/packages/foliate-js/.gitattributes @@ -0,0 +1 @@ +vendor/** linguist-vendored=true diff --git a/packages/foliate-js/.github/FUNDING.yml b/packages/foliate-js/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e1fc87959c97007ff9e71681f7f7c5e338c0330 --- /dev/null +++ b/packages/foliate-js/.github/FUNDING.yml @@ -0,0 +1 @@ +buy_me_a_coffee: johnfactotum diff --git a/packages/foliate-js/.github/workflows/eslint.yml b/packages/foliate-js/.github/workflows/eslint.yml new file mode 100644 index 0000000000000000000000000000000000000000..2333777cbee0276b334826144dd77cf5f1121dd1 --- /dev/null +++ b/packages/foliate-js/.github/workflows/eslint.yml @@ -0,0 +1,50 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# ESLint is a tool for identifying and reporting on patterns +# found in ECMAScript/JavaScript code. +# More details at https://github.com/eslint/eslint +# and https://eslint.org + +name: ESLint + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '27 12 * * 1' + +jobs: + eslint: + name: Run eslint scanning + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write + actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install ESLint + run: | + npm install eslint@9.28.0 + npm install @microsoft/eslint-formatter-sarif@3.1.0 + + - name: Run ESLint + env: + SARIF_ESLINT_IGNORE_SUPPRESSED: "true" + run: npx eslint . + --format @microsoft/eslint-formatter-sarif + --output-file eslint-results.sarif + continue-on-error: true + + - name: Upload analysis results to GitHub + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: eslint-results.sarif + wait-for-processing: true diff --git a/packages/foliate-js/.gitignore b/packages/foliate-js/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c2658d7d1b31848c3b71960543cb0368e56cd4c7 --- /dev/null +++ b/packages/foliate-js/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/packages/foliate-js/LICENSE b/packages/foliate-js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5930571b73151702a913179ef5f96313ad7d25d3 --- /dev/null +++ b/packages/foliate-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 John Factotum + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/foliate-js/README.md b/packages/foliate-js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a3fe2d51104c4de6b4d116138c72ea0376f2176f --- /dev/null +++ b/packages/foliate-js/README.md @@ -0,0 +1,374 @@ +# foliate-js + +Library for rendering e-books in the browser. + +Features: +- Supports EPUB, MOBI, KF8 (AZW3), FB2, CBZ, PDF (experimental; requires PDF.js) +- Add support for other formats yourself by implementing the book interface +- Pure JavaScript +- Small and modular +- No hard dependencies +- Does not require loading whole file into memory +- Does not care about older browsers + +## Demo + +The repo includes a demo viewer that can be used to open local files. To use it, serve the files with a server, and navigate to `reader.html`. Or visit the [online demo](https://johnfactotum.github.io/foliate-js/reader.html) hosted on GitHub. Note that it is very incomplete at the moment, and lacks many basic features such as keyboard shortcuts. + +Also note that deobfuscating fonts with the IDPF algorithm requires a SHA-1 function. By default it uses Web Crypto, which is only available in secure contexts. Without HTTPS, you will need to modify `reader.js` and pass your own SHA-1 implementation. + +## Current Status + +It works reasonably well, and has been used in several stable releases of [Foliate](https://github.com/johnfactotum/foliate). This library itself is, however, *not* stable. Expect it to break and the API to change at any time. Use it at your own risk. + +If you do decide to use it, since there's no release yet, it is recommended that you include the library as a git submodule in your project so that you can easily update it. + +## Documentation + +### Overview + +This project uses native ES modules. There's no build step, and you can import them directly. + +There are mainly three kinds of modules: + +- Modules that parse and load books, implementing the "book" interface + - `comic-book.js`, for comic book archives (CBZ) + - `epub.js` and `epubcfi.js`, for EPUB + - `fb2.js`, for FictionBook 2 + - `mobi.js`, for both Mobipocket files and KF8 (commonly known as AZW3) files +- Modules that handle pagination, implementing the "renderer" interface + - `fixed-layout.js`, for fixed layout books + - `paginator.js`, for reflowable books +- Auxiliary modules used to add additional functionalities + - `overlayer.js`, for rendering annotations + - `progress.js`, for getting reading progress + - `search.js`, for searching + +The modules are designed to be modular. In general, they don't directly depend on each other. Instead they depend on certain interfaces, detailed below. The exception is `view.js`. It is the higher level renderer that strings most of the things together, and you can think of it as the main entry point of the library. See "Basic Usage" below. + +The repo also includes a still higher level reader, though strictly speaking, `reader.html` (along with `reader.js` and its associated files in `ui/`) is not considered part of the library itself. It's akin to [Epub.js Reader](https://github.com/futurepress/epubjs-reader). You are expected to modify it or replace it with your own code. + +### Basic Usage + +To get started, clone the repo and import `view.js`: + +```js +import './foliate-js/view.js' + +const view = document.createElement('foliate-view') +document.body.append(view) + +view.addEventListener('relocate', e => { + console.log('location changed') + console.log(e.detail) +}) + +// can open a File/Blob object or a URL +// or any object that implements the "book" interface +await view.open('example.epub') +await view.goTo(/* path, section index, or CFI */) +``` + +See the [online demo](https://johnfactotum.github.io/foliate-js/reader.html) for a more advanced example. + +### Security + +EPUB books can contain [scripted content](https://www.w3.org/TR/epub/#sec-scripted-content) (i.e. JavaScript in the e-book), which is potentially dangerous, and is not supported by this library because + +- It is currently impossible to do so securely due to the content being served from the same origin (using `blob:` URLs). +- Due to [WebKit Bug 218086](https://bugs.webkit.org/show_bug.cgi?id=218086), the `allow-scripts` attribute is required on iframes, which renders iframe sandbox useless. + +It is therefore imperative that you use [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to block all scripts except `'self'`. An EPUB file for testing can be found at https://github.com/johnfactotum/epub-test. + +> [!CAUTION] +> Do NOT use this library (or any other e-book library, for that matter) without CSP unless you completely trust the content you're rendering or can block scripts by other means. + +### The Main Interface for Books + +Processors for each book format return an object that implements the following interface: +- `.sections`: an array of sections in the book. Each item has the following properties: + - `.load()`: returns a string containing the URL that will be rendered. May be async. + - `.unload()`: returns nothing. If present, can be used to free the section. + - `.createDocument()`: returns a `Document` object of the section. Used for searching. May be async. + - `.size`: a number, the byte size of the section. Used for showing reading progress. + - `.linear`: a string. If it is `"no"`, the section is not part of the linear reading sequence (see the [`linear`](https://www.w3.org/publishing/epub32/epub-packages.html#attrdef-itemref-linear) attribute in EPUB). + - `.cfi`: base CFI string of the section. The part that goes before the `!` in CFIs. + - `.id`: an identifier for the section, used for getting TOC item (see below). Can be anything, as long as they can be used as keys in a `Map`. +- `.dir`: a string representing the page progression direction of the book (`"rtl"` or `"ltr"`). +- `.toc`: an array representing the table of contents of the book. Each item has + - `.label`: a string label for the item + - `.href`: a string representing the destination of the item. Does not have to be a valid URL. + - `.subitems`: a array that contains TOC items +- `.pageList`: same as the TOC, but for the [page list](https://www.w3.org/publishing/epub32/epub-packages.html#sec-nav-pagelist). +- `.metadata`: an object representing the metadata of the book. Currently, it follows more or less the metadata schema of [Readium's webpub manifest](https://github.com/readium/webpub-manifest). Note that titles and names can be a string or an object like `{ ja: "草枕", en: 'Kusamakura' }`, and authors, etc. can be a string, an object, or an array of strings or objects. +- `.rendition`: an object that contains properties that correspond to the [rendition properties](https://www.w3.org/publishing/epub32/epub-packages.html#sec-package-metadata-rendering) in EPUB. If `.layout` is `"pre-paginated"`, the book is rendered with the fixed layout renderer. +- `.resolveHref(href)`: given an href string, returns an object representing the destination referenced by the href, which has the following properties: + - `.index`: the index of the referenced section in the `.section` array + - `.anchor(doc)`: given a `Document` object, returns the document fragment referred to by the href (can either be an `Element` or a `Range`), or `null` +- `.resolveCFI(cfi)`: same as above, but with a CFI string instead of href +- `.isExternal(href)`: returns a boolean. If `true`, the link should be opened externally. + +The following methods are consumed by `progress.js`, for getting the correct TOC and page list item when navigating: +- `.splitTOCHref(href)`: given an href string (from the TOC), returns an array, the first element of which is the `id` of the section (see above), and the second element is the fragment identifier (can be any type; see below). May be async. +- `.getTOCFragment(doc, id)`: given a `Document` object and a fragment identifier (the one provided by `.splitTOCHref()`; see above), returns a `Node` representing the target linked by the TOC item + +In addition, the `.transformTarget`, if present, can be used to transform the contents of the book as it loads. It is an `EventTarget` with a custom event `"data"`, whose `.detail` is `{ data, type, name }`, where `.data` is either a string or `Blob`, or a `Promise` thereof, `.type` the content type string, and `.name` the identifier of the resource. Event handlers should mutate `.data` to transform the data. + +Almost all of the properties and methods are optional. At minimum it needs `.sections` and the `.load()` method for the sections, as otherwise there won't be anything to render. + +### Archived Files + +Reading Zip-based formats requires adapting an external library. Both `epub.js` and `comic-book.js` expect a `loader` object that implements the following interface: + +- `.entries`: (only used by `comic-book.js`) an array, each element of which has a `filename` property, which is a string containing the filename (the full path). +- `.loadText(filename)`: given the path, returns the contents of the file as string. May be async. +- `.loadBlob(filename)`: given the path, returns the file as a `Blob` object. May be async. +- `.getSize(filename)`: returns the file size in bytes. Used to set the `.size` property for `.sections` (see above). + +In `view.js`, this is implemented using [zip.js](https://github.com/gildas-lormeau/zip.js), which is highly recommended because it seems to be the only library that supports random access for `File` objects (as well as HTTP range requests). + +One advantage of having such an interface is that one can easily use it for reading unarchived files as well. For example, `view.js` has a loader that allows you to open unpacked EPUBs as directories. + +### Mobipocket and Kindle Files + +It can read both MOBI and KF8 (.azw3, and combo .mobi files) from a `File` (or `Blob`) object. For MOBI files, it decompresses all text at once and splits the raw markup into sections at every ``, instead of outputting one long page for the whole book, which drastically improves rendering performance. For KF8 files, it tries to decompress as little text as possible when loading a section, but it can still be quite slow due to the slowness of the current HUFF/CDIC decompressor implementation. In all cases, images and other resources are not loaded until they are needed. + +Note that KF8 files can contain fonts that are zlib-compressed. They need to be decompressed with an external library. `view.js` uses [fflate](https://github.com/101arrowz/fflate) to decompress them. + +### PDF and Other Fixed-Layout Formats + +There is a proof-of-concept, highly experimental adapter for [PDF.js](https://mozilla.github.io/pdf.js/), with which you can show PDFs using the same fixed-layout renderer for EPUBs. + +CBZs are similarly handled like fixed-layout EPUBs. + +### The Renderers + +To simplify things, it has two separate renderers, one for reflowable books, and one for fixed layout books (as such there's no support for mixed layout books). These renderers are custom elements (web components). + +A renderer's interface is currently mainly: +- `.open(book)`: open a book object. +- `.goTo({ index, anchor })`: navigate to a destination. The argument has the same type as the one returned by `.resolveHref()` in the book object. +- `.prev()`: go to previous page. +- `.next()`: go to next page. + +It has the following custom events: +- `load`, when a section is loaded. Its `event.detail` has two properties, `doc`, the `Document` object, and `index`, the index of the section. +- `relocate`, when the location changes. Its `event.detail` has the properties `range`, `index`, and `fraction`, where `range` is a `Range` object containing the current visible area, and `fraction` is a number between 0 and 1, representing the reading progress within the section. +- `create-overlayer`, which allows adding an overlay to the page. The `event.detail` has the properties `doc`, `index`, and a function `attach(overlay)`, which should be called with an overlayer object (see the description for `overlayer.js` below). + +Both renderers have the [`part`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/part) named `filter`, which you can apply CSS filters to, to e.g. invert colors or adjust brightness: + +```css +foliate-view::part(filter) { + filter: invert(1) hue-rotate(180deg); +} +``` + +The filter only applies to the book itself, leaving overlaid elements such as highlights unaffected. + +### The Paginator + +The paginator uses the same pagination strategy as [Epub.js](https://github.com/futurepress/epub.js): it uses CSS multi-column. As such it shares much of the same limitations (it's slow, some CSS styles do not work as expected, and other bugs). There are a few differences: +- It is a totally standalone module. You can use it to paginate any content. +- It is much simpler, but currently there's no support for continuous scrolling. +- It has no concept of CFIs and operates on `Range` objects directly. +- It uses bisecting to find the current visible range, which is more accurate than what Epub.js does. +- It has an internal `#anchor` property, which can be a `Range`, `Element`, or a fraction that represents the current location. The view is *anchored* to it no matter how you resize the window. +- It supports more than two columns. +- It supports switching between scrolled and paginated mode without reloading (I can't figure out how to do this in Epub.js). + +The layout can be configured by setting the following attributes: +- `animated`: a [boolean attribute](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML). If present, adds a sliding transition effect. +- `flow`: either `paginated` or `scrolled`. +- `margin`: a CSS ``. The unit must be `px`. The height of the header and footer. +- `gap`: a CSS ``. The size of the space between columns, relative to page size. +- `max-inline-size`: a CSS ``. The unit must be `px`. The maximum inline size of the text (column width in paginated mode). +- `max-block-size`: same as above, but for the size in the block direction. +- `max-column-count`: integer. The maximum number of columns. Has no effect in scrolled mode, or when the orientation of the renderer element is `portrait` (or, for vertical writing, `landscape`). + +(Note: there's no JS property API. You must use `.setAttribute()`.) + +It has built-in header and footer regions accessible via the `.heads` and `.feet` properties of the paginator instance. These can be used to display running heads and reading progress. They are only available in paginated mode, and there will be one element for each column. They are styleable with `::part(head)` and `::part(foot)`. E.g., to add a border under the running heads, + +```css +foliate-view::part(head) { + padding-bottom: 4px; + border-bottom: 1px solid graytext; +} +``` + +### EPUB CFI + +Parsed CFIs are represented as a plain array or object. The basic type is called a "part", which is an object with the following structure: `{ index, id, offset, temporal, spatial, text, side }`, corresponding to a step + offset in the CFI. + +A collapsed, non-range CFI is represented as an array whose elements are arrays of parts, each corresponding to a full path. That is, `/6/4!/4` is turned into + +```json +[ + [ + { "index": 6 }, + { "index": 4 } + ], + [ + { "index": 4 } + ] +] +``` + +A range CFI is an object `{ parent, start, end }`, each property being the same type as a collapsed CFI. For example, `/6/4!/2,/2,/4` is represented as + +```json +{ + "parent": [ + [ + { "index": 6 }, + { "index": 4 } + ], + [ + { "index": 2 } + ] + ], + "start": [ + [ + { "index": 2 } + ] + ], + "end": [ + [ + { "index": 4 } + ] + ] +} +``` + +The parser uses a state machine rather than regex, and should handle assertions that contain escaped characters correctly (see tests for examples of this). + +It has the ability ignore nodes, which is needed if you want to inject your own nodes into the document without affecting CFIs. To do this, you need to pass the optional filter function that works similarly to the filter function of [`TreeWalker`s](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker): + +```js +const filter = node => node.nodeType !== 1 ? NodeFilter.FILTER_ACCEPT + : node.matches('.reject') ? NodeFilter.FILTER_REJECT + : node.matches('.skip') ? NodeFilter.FILTER_SKIP + : NodeFilter.FILTER_ACCEPT + +CFI.toRange(doc, 'epubcfi(...)', filter) +CFI.fromRange(range, filter) +``` + +It can parse and stringify spatial and temporal offsets, as well as text location assertions and side bias, but there's no support for employing them when rendering yet. + +### Highlighting Text + +There is a generic module for overlaying arbitrary SVG elements, `overlayer.js`. It can be used to implement highlighting text for annotations. It's the same technique used by [marks-pane](https://github.com/fchasen/marks), used by Epub.js, but it's designed to be easily extensible. You can return any SVG element in the `draw` function, making it possible to add custom styles such as squiggly lines or even free hand drawings. + +The overlay has no event listeners by default. It only provides a `.hitTest(event)` method, that can be used to do hit tests. Currently it does this with the client rects of `Range`s, not the element returned by `draw()`. + +An overlayer object implements the following interface for the consumption of renderers: +- `.element`: the DOM element of the overlayer. This element will be inserted, resized, and positioned automatically by the renderer on top of the page. +- `.redraw()`: called by the renderer when the overlay needs to be redrawn. + +### The Text Walker + +Not a particularly descriptive name, but essentially, `text-walker.js` is a small DOM utility that allows you to + +1. Gather all text nodes in a `Range`, `Document` or `DocumentFragment` into an array of strings. +2. Perform splitting or matching on the strings. +3. Get back the results of these string operations as `Range`s. + +E.g. you can join all the text nodes together, use `Intl.Segmenter` to segment the string into words, and get the results in DOM Ranges, so you can mark up those words in the original document. + +In foliate-js, this is used for searching and TTS. + +### Searching + +It provides a search module, which can in fact be used as a standalone module for searching across any array of strings. There's no limit on the number of strings a match is allowed to span. It's based on `Intl.Collator` and `Intl.Segmenter`, to support ignoring diacritics and matching whole words only. It's extrenely slow, and you'd probably want to load results incrementally. + +### Text-to-Speech (TTS) + +The TTS module doesn't directly handle speech output. Rather, its methods return SSML documents (as strings), which you can then feed to your speech synthesizer. + +The SSML attributes `ssml:ph` and `ssml:alphabet` are supported. There's no support for PLS and CSS Speech. + +### Offline Dictionaries + +The `dict.js` module can be used to load dictd and StarDict dictionaries. Usage: + +```js +import { StarDict } from './dict.js' +import { inflate } from 'your inflate implementation' + +const { ifo, dz, idx, syn } = { /* `File` (or `Blob`) objects */ } +const dict = new StarDict() +await dict.loadIfo(ifo) +await dict.loadDict(dz, inflate) +await dict.loadIdx(idx) +await dict.loadSyn(syn) + +// look up words +const query = '...' +await dictionary.lookup(query) +await dictionary.synonyms(query) +``` + +Note that you must supply your own `inflate` function. Here is an example using [fflate](https://github.com/101arrowz/fflate): +```js +const inflate = data => new Promise(resolve => { + const inflate = new fflate.Inflate() + inflate.ondata = data => resolve(data) + inflate.push(data) +}) +``` + +### OPDS + +The `opds.js` module can be used to implement OPDS clients. It can convert OPDS 1.x documents to OPDS 2.0: + +- `getFeed(doc)`: converts an OPDS 1.x feed to OPDS 2.0. The argument must be a DOM Document object. You need to use a `DOMParser` to obtain a Document first if you have a string. +- `getPublication(entry)`: converts a OPDS 1.x entry in acquisition feeds to an OPDS 2.0 publication. The argument must be a DOM Element object. + +It exports the following symbols for properties unsupported by OPDS 2.0: +- `SYMBOL.SUMMARY`: used on navigation links to represent the summary/content (see https://github.com/opds-community/drafts/issues/51) +- `SYMBOL.CONTENT`: used on publications to represent the content/description and its type. This is mainly for preserving the type info for XHTML. The value of this property is an object whose properties are: + - `.type`: either "text", "html", or "xhtml" + - `.value`: the value of the content + +There are also two functions that can be used to implement search forms: + +- `getOpenSearch(doc)`: for OpenSearch. The argument is a DOM Document object of an OpenSearch search document. +- `getSearch(link)` for templated search in OPDS 2.0. The argument must be an OPDS 2.0 Link object. Note that this function will import `uri-template.js`. + +These two functions return an object that implements the following interface: +- `.metadata`: an object with the string properties `title` and `description` +- `.params`: an array, representing the search parameters, whose elements are objects whose properties are + - `ns`: a string; the namespace of the parameter + - `name`: a string; the name of the parameter + - `required`: a boolean, whether the parameter is required + - `value`: a string; the default value of the parameter +- `.search(map)`: a function, whose argument is a `Map` whose values are `Map`s (i.e. a two-dimensional map). The first key is the namespace of the search parameter. For non-namespaced parameters, the first key must be `null`. The second key is the parameter's name. Returns a string representing the URL of the search results. + +### Generating Images for Quotes + +With `quote-image.js`, one can generate shareable images for quotes: + +```js +document.querySelector('foliate-quoteimage').getBlob({ + title: 'The Time Machine', + author: 'H. G. Wells', + text: 'Can an instantaneous cube exist?', +}) +``` + +### Supported Browsers + +It aims to support the latest version of WebKitGTK, Firefox, and Chromium. Older browsers like Firefox ESR are not supported. + +Although it's mainly indeded for rendering e-books in the browser, some features can be used in non-browser environments as well. In particular, `epubcfi.js` can be used as is in any environment if you only need to parse or sort CFIs. Most other features depend on having the global objects `Blob`, `TextDecoder`, `TextEncoder`, `DOMParser`, `XMLSerializer`, and `URL`, and should work if you polyfill them. + +## License + +MIT. + +Vendored libraries: +- [zip.js](https://github.com/gildas-lormeau/zip.js) is licensed under the BSD-3-Clause license. +- [fflate](https://github.com/101arrowz/fflate) is MIT licensed. +- [PDF.js](https://mozilla.github.io/pdf.js/) is licensed under Apache. diff --git a/packages/foliate-js/comic-book.js b/packages/foliate-js/comic-book.js new file mode 100644 index 0000000000000000000000000000000000000000..f4ec7ce34ef5633555d041d84cd122f4122650ea --- /dev/null +++ b/packages/foliate-js/comic-book.js @@ -0,0 +1,64 @@ +export const makeComicBook = async ({ entries, loadBlob, getSize, getComment }, file) => { + const cache = new Map() + const urls = new Map() + const load = async name => { + if (cache.has(name)) return cache.get(name) + const src = URL.createObjectURL(await loadBlob(name)) + const page = URL.createObjectURL( + new Blob([``], { type: 'text/html' })) + urls.set(name, [src, page]) + cache.set(name, page) + return page + } + const unload = name => { + urls.get(name)?.forEach?.(url => URL.revokeObjectURL(url)) + urls.delete(name) + cache.delete(name) + } + + const exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.jxl', '.avif'] + const files = entries + .map(entry => entry.filename) + .filter(name => exts.some(ext => name.endsWith(ext))) + .sort() + if (!files.length) throw new Error('No supported image files in archive') + + const book = {} + try { + const jsonComment = JSON.parse(await getComment() || '') + const info = jsonComment['ComicBookInfo/1.0'] + if (info) { + const year = info.publicationYear + const month = info.publicationMonth + const mm = month && month >= 1 && month <= 12 ? String(month).padStart(2, '0') : null + book.metadata = { + title: info.title || file.name, + publisher: info.publisher, + language: info.language || info.lang, + author: info.credits ? info.credits.map(c => `${c.person} (${c.role})`).join(', ') : '', + published: year && month ? `${year}-${mm}` : undefined, + } + } else { + book.metadata = { title: file.name } + } + } catch { + book.metadata = { title: file.name } + } + book.getCover = () => loadBlob(files[0]) + book.sections = files.map(name => ({ + id: name, + load: () => load(name), + unload: () => unload(name), + size: getSize(name), + })) + book.toc = files.map(name => ({ label: name, href: name })) + book.rendition = { layout: 'pre-paginated' } + book.resolveHref = href => ({ index: book.sections.findIndex(s => s.id === href) }) + book.splitTOCHref = href => [href, null] + book.getTOCFragment = doc => doc.documentElement + book.destroy = () => { + for (const arr of urls.values()) + for (const url of arr) URL.revokeObjectURL(url) + } + return book +} diff --git a/packages/foliate-js/dict.js b/packages/foliate-js/dict.js new file mode 100644 index 0000000000000000000000000000000000000000..9afa7ea1ebe11ed9787eec6f36176dda8651cb37 --- /dev/null +++ b/packages/foliate-js/dict.js @@ -0,0 +1,241 @@ +const decoder = new TextDecoder() +const decode = decoder.decode.bind(decoder) + +const concatTypedArray = (a, b) => { + const result = new a.constructor(a.length + b.length) + result.set(a) + result.set(b, a.length) + return result +} + +const strcmp = (a, b) => { + a = a.toLowerCase(), b = b.toLowerCase() + return a < b ? -1 : a > b ? 1 : 0 +} + +class DictZip { + #chlen + #chunks + #compressed + inflate + async load(file) { + const header = new DataView(await file.slice(0, 12).arrayBuffer()) + if (header.getUint8(0) !== 31 || header.getUint8(1) !== 139 + || header.getUint8(2) !== 8) throw new Error('Not a DictZip file') + const flg = header.getUint8(3) + if (!flg & 0b100) throw new Error('Missing FEXTRA flag') + + const xlen = header.getUint16(10, true) + const extra = new DataView(await file.slice(12, 12 + xlen).arrayBuffer()) + if (extra.getUint8(0) !== 82 || extra.getUint8(1) !== 65) + throw new Error('Subfield ID should be RA') + if (extra.getUint16(4, true) !== 1) throw new Error('Unsupported version') + + this.#chlen = extra.getUint16(6, true) + const chcnt = extra.getUint16(8, true) + this.#chunks = [] + for (let i = 0, chunkOffset = 0; i < chcnt; i++) { + const chunkSize = extra.getUint16(10 + 2 * i, true) + this.#chunks.push([chunkOffset, chunkSize]) + chunkOffset = chunkOffset + chunkSize + } + + // skip to compressed data + let offset = 12 + xlen + const max = Math.min(offset + 512, file.size) + const strArr = new Uint8Array(await file.slice(0, max).arrayBuffer()) + if (flg & 0b1000) { // fname + const i = strArr.indexOf(0, offset) + if (i < 0) throw new Error('Header too long') + offset = i + 1 + } + if (flg & 0b10000) { // fcomment + const i = strArr.indexOf(0, offset) + if (i < 0) throw new Error('Header too long') + offset = i + 1 + } + if (flg & 0b10) offset += 2 // fhcrc + this.#compressed = file.slice(offset) + } + async read(offset, size) { + const chunks = this.#chunks + const startIndex = Math.trunc(offset / this.#chlen) + const endIndex = Math.trunc((offset + size) / this.#chlen) + const buf = await this.#compressed.slice(chunks[startIndex][0], + chunks[endIndex][0] + chunks[endIndex][1]).arrayBuffer() + let arr = new Uint8Array() + for (let pos = 0, i = startIndex; i <= endIndex; i++) { + const data = new Uint8Array(buf, pos, chunks[i][1]) + arr = concatTypedArray(arr, await this.inflate(data)) + pos += chunks[i][1] + } + const startOffset = offset - startIndex * this.#chlen + return arr.subarray(startOffset, startOffset + size) + } +} + +class Index { + strcmp = strcmp + // binary search + bisect(query, start = 0, end = this.words.length - 1) { + if (end - start === 1) { + if (!this.strcmp(query, this.getWord(start))) return start + if (!this.strcmp(query, this.getWord(end))) return end + return null + } + const mid = Math.floor(start + (end - start) / 2) + const cmp = this.strcmp(query, this.getWord(mid)) + if (cmp < 0) return this.bisect(query, start, mid) + if (cmp > 0) return this.bisect(query, mid, end) + return mid + } + // check for multiple definitions + checkAdjacent(query, i) { + if (i == null) return [] + let j = i + const equals = i => { + const word = this.getWord(i) + return word ? this.strcmp(query, word) === 0 : false + } + while (equals(j - 1)) j-- + let k = i + while (equals(k + 1)) k++ + return j === k ? [i] : Array.from({ length: k + 1 - j }, (_, i) => j + i) + } + lookup(query) { + return this.checkAdjacent(query, this.bisect(query)) + } +} + +const decodeBase64Number = str => { + const { length } = str + let n = 0 + for (let i = 0; i < length; i++) { + const c = str.charCodeAt(i) + n += (c === 43 ? 62 // "+" + : c === 47 ? 63 // "/" + : c < 58 ? c + 4 // 0-9 -> 52-61 + : c < 91 ? c - 65 // A-Z -> 0-25 + : c - 71 // a-z -> 26-51 + ) * 64 ** (length - 1 - i) + } + return n +} + +class DictdIndex extends Index { + getWord(i) { + return this.words[i] + } + async load(file) { + const words = [] + const offsets = [] + const sizes = [] + for (const line of decode(await file.arrayBuffer()).split('\n')) { + const a = line.split('\t') + words.push(a[0]) + offsets.push(decodeBase64Number(a[1])) + sizes.push(decodeBase64Number(a[2])) + } + this.words = words + this.offsets = offsets + this.sizes = sizes + } +} + +export class DictdDict { + #dict = new DictZip() + #idx = new DictdIndex() + loadDict(file, inflate) { + this.#dict.inflate = inflate + return this.#dict.load(file) + } + async #readWord(i) { + const word = this.#idx.getWord(i) + const offset = this.#idx.offsets[i] + const size = this.#idx.sizes[i] + return { word, data: ['m', this.#dict.read(offset, size)] } + } + #readWords(arr) { + return Promise.all(arr.map(this.#readWord.bind(this))) + } + lookup(query) { + return this.#readWords(this.#idx.lookup(query)) + } +} + +class StarDictIndex extends Index { + isSyn + #arr + getWord(i) { + const word = this.words[i] + if (!word) return + return decode(this.#arr.subarray(word[0], word[1])) + } + async load(file) { + const { isSyn } = this + const buf = await file.arrayBuffer() + const arr = new Uint8Array(buf) + this.#arr = arr + const view = new DataView(buf) + const words = [] + const offsets = [] + const sizes = [] + for (let i = 0; i < arr.length;) { + const newI = arr.subarray(0, i + 256).indexOf(0, i) + if (newI < 0) throw new Error('Word too big') + words.push([i, newI]) + offsets.push(view.getUint32(newI + 1)) + if (isSyn) i = newI + 5 + else { + sizes.push(view.getUint32(newI + 5)) + i = newI + 9 + } + } + this.words = words + this.offsets = offsets + this.sizes = sizes + } +} + +export class StarDict { + #dict = new DictZip() + #idx = new StarDictIndex() + #syn = Object.assign(new StarDictIndex(), { isSyn: true }) + async loadIfo(file) { + const str = decode(await file.arrayBuffer()) + this.ifo = Object.fromEntries(str.split('\n').map(line => { + const sep = line.indexOf('=') + if (sep < 0) return + return [line.slice(0, sep), line.slice(sep + 1)] + }).filter(x => x)) + } + loadDict(file, inflate) { + this.#dict.inflate = inflate + return this.#dict.load(file) + } + loadIdx(file) { + return this.#idx.load(file) + } + loadSyn(file) { + if (file) return this.#syn.load(file) + } + async #readWord(i) { + const word = this.#idx.getWord(i) + const offset = this.#idx.offsets[i] + const size = this.#idx.sizes[i] + const data = await this.#dict.read(offset, size) + const seq = this.ifo.sametypesequence + if (!seq) throw new Error('TODO') + if (seq.length === 1) return { word, data: [[seq[0], data]] } + throw new Error('TODO') + } + #readWords(arr) { + return Promise.all(arr.map(this.#readWord.bind(this))) + } + lookup(query) { + return this.#readWords(this.#idx.lookup(query)) + } + synonyms(query) { + return this.#readWords(this.#syn.lookup(query).map(i => this.#syn.offsets[i])) + } +} diff --git a/packages/foliate-js/epub.js b/packages/foliate-js/epub.js new file mode 100644 index 0000000000000000000000000000000000000000..f727464d06d5a9f3e2dbe39e1ce0944f60f97116 --- /dev/null +++ b/packages/foliate-js/epub.js @@ -0,0 +1,1374 @@ +import * as CFI from './epubcfi.js' + +const NS = { + CONTAINER: 'urn:oasis:names:tc:opendocument:xmlns:container', + XHTML: 'http://www.w3.org/1999/xhtml', + OPF: 'http://www.idpf.org/2007/opf', + EPUB: 'http://www.idpf.org/2007/ops', + DC: 'http://purl.org/dc/elements/1.1/', + DCTERMS: 'http://purl.org/dc/terms/', + ENC: 'http://www.w3.org/2001/04/xmlenc#', + NCX: 'http://www.daisy.org/z3986/2005/ncx/', + XLINK: 'http://www.w3.org/1999/xlink', + SMIL: 'http://www.w3.org/ns/SMIL', +} + +const MIME = { + XML: 'application/xml', + NCX: 'application/x-dtbncx+xml', + XHTML: 'application/xhtml+xml', + HTML: 'text/html', + CSS: 'text/css', + SVG: 'image/svg+xml', + JS: /\/(x-)?(javascript|ecmascript)/, +} + +// https://www.w3.org/TR/epub-33/#sec-reserved-prefixes +const PREFIX = { + a11y: 'http://www.idpf.org/epub/vocab/package/a11y/#', + dcterms: 'http://purl.org/dc/terms/', + marc: 'http://id.loc.gov/vocabulary/', + media: 'http://www.idpf.org/epub/vocab/overlays/#', + onix: 'http://www.editeur.org/ONIX/book/codelists/current.html#', + rendition: 'http://www.idpf.org/vocab/rendition/#', + schema: 'http://schema.org/', + xsd: 'http://www.w3.org/2001/XMLSchema#', + msv: 'http://www.idpf.org/epub/vocab/structure/magazine/#', + prism: 'http://www.prismstandard.org/specifications/3.0/PRISM_CV_Spec_3.0.htm#', +} + +const RELATORS = { + art: 'artist', + aut: 'author', + clr: 'colorist', + edt: 'editor', + ill: 'illustrator', + nrt: 'narrator', + trl: 'translator', + pbl: 'publisher', +} + +const ONIX5 = { + '02': 'isbn', + '06': 'doi', + '15': 'isbn', + '26': 'doi', + '34': 'issn', +} + +// convert to camel case +const camel = x => x.toLowerCase().replace(/[-:](.)/g, (_, g) => g.toUpperCase()) + +// strip and collapse ASCII whitespace +// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace +const normalizeWhitespace = str => str ? str + .replace(/[\t\n\f\r ]+/g, ' ') + .replace(/^[\t\n\f\r ]+/, '') + .replace(/[\t\n\f\r ]+$/, '') : '' + +const filterAttribute = (attr, value, isList) => isList + ? el => el.getAttribute(attr)?.split(/\s/)?.includes(value) + : typeof value === 'function' + ? el => value(el.getAttribute(attr)) + : el => el.getAttribute(attr) === value + +const getAttributes = (...xs) => el => + el ? Object.fromEntries(xs.map(x => [camel(x), el.getAttribute(x)])) : null + +const getElementText = el => normalizeWhitespace(el?.textContent) + +const childGetter = (doc, ns) => { + // ignore the namespace if it doesn't appear in document at all + const useNS = doc.lookupNamespaceURI(null) === ns || doc.lookupPrefix(ns) + const f = useNS + ? (el, name) => el => el.namespaceURI === ns && el.localName === name + : (el, name) => el => el.localName === name + return { + $: (el, name) => [...el.children].find(f(el, name)), + $$: (el, name) => [...el.children].filter(f(el, name)), + $$$: useNS + ? (el, name) => [...el.getElementsByTagNameNS(ns, name)] + : (el, name) => [...el.getElementsByTagName(name)], + } +} + +const resolveURL = (url, relativeTo) => { + try { + // replace %2c in the url with a comma, this might be introduced by calibre + url = url.replace(/%2c/gi, ',').replace(/%3a/gi, ':') + if (relativeTo.includes(':') && !relativeTo.startsWith('OEBPS')) return new URL(url, relativeTo) + // the base needs to be a valid URL, so set a base URL and then remove it + const root = 'https://invalid.invalid/' + const obj = new URL(url, root + relativeTo) + obj.search = '' + return decodeURI(obj.href.replace(root, '')) + } catch(e) { + console.warn(e) + return url + } +} + +const isExternal = uri => /^(?!blob)\w+:/i.test(uri) + +// like `path.relative()` in Node.js +const pathRelative = (from, to) => { + if (!from) return to + const as = from.replace(/\/$/, '').split('/') + const bs = to.replace(/\/$/, '').split('/') + const i = (as.length > bs.length ? as : bs).findIndex((_, i) => as[i] !== bs[i]) + return i < 0 ? '' : Array(as.length - i).fill('..').concat(bs.slice(i)).join('/') +} + +const pathDirname = str => str.slice(0, str.lastIndexOf('/') + 1) + +// replace asynchronously and sequentially +// same technique as https://stackoverflow.com/a/48032528 +const replaceSeries = async (str, regex, f) => { + const matches = [] + str.replace(regex, (...args) => (matches.push(args), null)) + const results = [] + for (const args of matches) results.push(await f(...args)) + return str.replace(regex, () => results.shift()) +} + +const regexEscape = str => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') + +const tidy = obj => { + for (const [key, val] of Object.entries(obj)) + if (val == null) delete obj[key] + else if (Array.isArray(val)) { + obj[key] = val.filter(x => x).map(x => + typeof x === 'object' && !Array.isArray(x) ? tidy(x) : x) + if (!obj[key].length) delete obj[key] + else if (obj[key].length === 1) obj[key] = obj[key][0] + } + else if (typeof val === 'object') { + obj[key] = tidy(val) + if (!Object.keys(val).length) delete obj[key] + } + const keys = Object.keys(obj) + if (keys.length === 1 && keys[0] === 'name') return obj[keys[0]] + return obj +} + +// https://www.w3.org/TR/epub/#sec-prefix-attr +const getPrefixes = doc => { + const map = new Map(Object.entries(PREFIX)) + const value = doc.documentElement.getAttributeNS(NS.EPUB, 'prefix') + || doc.documentElement.getAttribute('prefix') + if (value) for (const [, prefix, url] of value + .matchAll(/(.+): +(.+)[ \t\r\n]*/g)) map.set(prefix, url) + return map +} + +// https://www.w3.org/TR/epub-rs/#sec-property-values +// but ignoring the case where the prefix is omitted +const getPropertyURL = (value, prefixes) => { + if (!value) return null + const [a, b] = value.split(':') + const prefix = b ? a : null + const reference = b ? b : a + const baseURL = prefixes.get(prefix) + return baseURL ? baseURL + reference : null +} + +const getMetadata = opf => { + const { $ } = childGetter(opf, NS.OPF) + const $metadata = $(opf.documentElement, 'metadata') + + // first pass: convert to JS objects + const els = Object.groupBy($metadata.children, el => + el.namespaceURI === NS.DC ? 'dc' + : el.namespaceURI === NS.OPF && el.localName === 'meta' ? + (el.hasAttribute('name') ? 'legacyMeta' : 'meta') : '') + const baseLang = $metadata.getAttribute('xml:lang') + ?? opf.documentElement.getAttribute('xml:lang') ?? 'und' + const prefixes = getPrefixes(opf) + const parse = el => { + const property = el.getAttribute('property') + const scheme = el.getAttribute('scheme') + return { + property: getPropertyURL(property, prefixes) ?? property, + scheme: getPropertyURL(scheme, prefixes) ?? scheme, + lang: el.getAttribute('xml:lang'), + value: getElementText(el), + props: getProperties(el), + // `opf:` attributes from EPUB 2 & EPUB 3.1 (removed in EPUB 3.2) + attrs: Object.fromEntries(Array.from(el.attributes) + .filter(attr => attr.namespaceURI === NS.OPF) + .map(attr => [attr.localName, attr.value])), + } + } + const refines = Map.groupBy(els.meta ?? [], el => el.getAttribute('refines')) + const getProperties = el => { + const els = refines.get(el ? '#' + el.getAttribute('id') : null) + if (!els) return null + return Object.groupBy(els.map(parse), x => x.property) + } + const dc = Object.fromEntries(Object.entries(Object.groupBy(els.dc || [], el => el.localName)) + .map(([name, els]) => [name, els.map(parse)])) + const properties = getProperties() ?? {} + const legacyMeta = Object.fromEntries(els.legacyMeta?.map(el => + [el.getAttribute('name'), el.getAttribute('content')]) ?? []) + + // second pass: map to webpub + const one = x => x?.[0]?.value + const prop = (x, p) => one(x?.props?.[p]) + const makeLanguageMap = x => { + if (!x) return null + const alts = x.props?.['alternate-script'] ?? [] + const altRep = x.attrs['alt-rep'] + if (!alts.length && (!x.lang || x.lang === baseLang) && !altRep) return x.value + const map = { [x.lang ?? baseLang]: x.value } + if (altRep) map[x.attrs['alt-rep-lang']] = altRep + for (const y of alts) map[y.lang] ??= y.value + return map + } + const makeContributor = x => x ? ({ + name: makeLanguageMap(x), + sortAs: makeLanguageMap(x.props?.['file-as']?.[0]) ?? x.attrs['file-as'], + role: x.props?.role?.filter(x => x.scheme === PREFIX.marc + 'relators') + ?.map(x => x.value) ?? [x.attrs.role], + code: prop(x, 'term') ?? x.attrs.term, + scheme: prop(x, 'authority') ?? x.attrs.authority, + }) : null + const makeCollection = x => ({ + name: makeLanguageMap(x), + // NOTE: webpub requires number but EPUB allows values like "2.2.1" + position: one(x.props?.['group-position']), + }) + const makeSeries = x => ({ + name: x.value, + position: one(x.props?.['group-position']), + }) + const makeAltIdentifier = x => { + const { value } = x + if (/^urn:/i.test(value)) return value + if (/^doi:/i.test(value)) return `urn:${value}` + const type = x.props?.['identifier-type'] + if (!type) { + const scheme = x.attrs.scheme + if (!scheme) return value + // https://idpf.github.io/epub-registries/identifiers/ + // but no "jdcn", which isn't a registered URN namespace + if (/^(doi|isbn|uuid)$/i.test(scheme)) return `urn:${scheme}:${value}` + // NOTE: webpub requires scheme to be a URI; EPUB allows anything + return { scheme, value } + } + if (type.scheme === PREFIX.onix + 'codelist5') { + const nid = ONIX5[type.value] + if (nid) return `urn:${nid}:${value}` + } + return value + } + const belongsTo = Object.groupBy(properties['belongs-to-collection'] ?? [], + x => prop(x, 'collection-type') === 'series' ? 'series' : 'collection') + const mainTitle = dc.title?.find(x => prop(x, 'title-type') === 'main') ?? dc.title?.[0] + const metadata = { + identifier: getIdentifier(opf), + title: makeLanguageMap(mainTitle), + sortAs: makeLanguageMap(mainTitle?.props?.['file-as']?.[0]) + ?? mainTitle?.attrs?.['file-as'] + ?? legacyMeta?.['calibre:title_sort'], + subtitle: dc.title?.find(x => prop(x, 'title-type') === 'subtitle')?.value, + language: dc.language?.map(x => x.value), + description: one(dc.description), + publisher: makeContributor(dc.publisher?.[0]), + published: dc.date?.find(x => x.attrs.event === 'publication')?.value + ?? one(dc.date), + modified: one(properties[PREFIX.dcterms + 'modified']) + ?? dc.date?.find(x => x.attrs.event === 'modification')?.value, + subject: dc.subject?.map(makeContributor), + belongsTo: { + collection: belongsTo.collection?.map(makeCollection), + series: belongsTo.series?.map(makeSeries) + ?? (legacyMeta?.['calibre:series'] ? { + name: legacyMeta?.['calibre:series'], + position: parseFloat(legacyMeta?.['calibre:series_index']), + } : null), + }, + altIdentifier: dc.identifier?.map(makeAltIdentifier), + source: dc.source?.map(makeAltIdentifier), // NOTE: not in webpub schema + rights: one(dc.rights), // NOTE: not in webpub schema + } + const remapContributor = defaultKey => x => { + const keys = new Set(x.role?.map(role => RELATORS[role] ?? defaultKey)) + return [keys.size ? keys : [defaultKey], x] + } + for (const [keys, val] of [].concat( + dc.creator?.map(makeContributor)?.map(remapContributor('author')) ?? [], + dc.contributor?.map(makeContributor)?.map(remapContributor('contributor')) ?? [])) + for (const key of keys) { + // if already parsed publisher don't remap it from author/contributor again + if (key === 'publisher' && metadata.publisher) continue + if (metadata[key]) metadata[key].push(val) + else metadata[key] = [val] + } + tidy(metadata) + if (metadata.altIdentifier === metadata.identifier) + delete metadata.altIdentifier + + const rendition = {} + const media = {} + for (const [key, val] of Object.entries(properties)) { + if (key.startsWith(PREFIX.rendition)) + rendition[camel(key.replace(PREFIX.rendition, ''))] = one(val) + else if (key.startsWith(PREFIX.media)) + media[camel(key.replace(PREFIX.media, ''))] = one(val) + } + if (media.duration) media.duration = parseClock(media.duration) + return { metadata, rendition, media } +} + +const parseNav = (doc, resolve = f => f) => { + const { $, $$, $$$ } = childGetter(doc, NS.XHTML) + const resolveHref = href => href ? decodeURI(resolve(href)) : null + const parseLI = getType => $li => { + const $a = $($li, 'a') ?? $($li, 'span') + const $ol = $($li, 'ol') + const href = resolveHref($a?.getAttribute('href')) + const label = getElementText($a) || $a?.getAttribute('title') + // TODO: get and concat alt/title texts in content + const result = { label, href, subitems: parseOL($ol) } + if (getType) result.type = $a?.getAttributeNS(NS.EPUB, 'type')?.split(/\s/) + return result + } + const parseOL = ($ol, getType) => $ol ? $$($ol, 'li').map(parseLI(getType)) : null + const parseNav = ($nav, getType) => parseOL($($nav, 'ol'), getType) + + const $$nav = $$$(doc, 'nav') + let toc = null, pageList = null, landmarks = null, others = [] + for (const $nav of $$nav) { + const type = $nav.getAttributeNS(NS.EPUB, 'type')?.split(/\s/) ?? [] + if (type.includes('toc')) toc ??= parseNav($nav) + else if (type.includes('page-list')) pageList ??= parseNav($nav) + else if (type.includes('landmarks')) landmarks ??= parseNav($nav, true) + else others.push({ + label: getElementText($nav.firstElementChild), type, + list: parseNav($nav), + }) + } + return { toc, pageList, landmarks, others } +} + +const parseNCX = (doc, resolve = f => f) => { + const { $, $$ } = childGetter(doc, NS.NCX) + const resolveHref = href => href ? decodeURI(resolve(href)) : null + const parseItem = el => { + const $label = $(el, 'navLabel') + const $content = $(el, 'content') + const label = getElementText($label) + const href = resolveHref($content.getAttribute('src')) + if (el.localName === 'navPoint') { + const els = $$(el, 'navPoint') + return { label, href, subitems: els.length ? els.map(parseItem) : null } + } + return { label, href } + } + const parseList = (el, itemName) => $$(el, itemName).map(parseItem) + const getSingle = (container, itemName) => { + const $container = $(doc.documentElement, container) + return $container ? parseList($container, itemName) : null + } + return { + toc: getSingle('navMap', 'navPoint'), + pageList: getSingle('pageList', 'pageTarget'), + others: $$(doc.documentElement, 'navList').map(el => ({ + label: getElementText($(el, 'navLabel')), + list: parseList(el, 'navTarget'), + })), + } +} + +const parseClock = str => { + if (!str) return + const parts = str.split(':').map(x => parseFloat(x)) + if (parts.length === 3) { + const [h, m, s] = parts + return h * 60 * 60 + m * 60 + s + } + if (parts.length === 2) { + const [m, s] = parts + return m * 60 + s + } + const [x, unit] = str.split(/(?=[^\d.])/) + const n = parseFloat(x) + const f = unit === 'h' ? 60 * 60 + : unit === 'min' ? 60 + : unit === 'ms' ? .001 + : 1 + return n * f +} + +const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp'] + +const getImageMediaType = (path) => { + const extension = path.toLowerCase().split('.').pop() + const mediaTypeMap = { + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'png': 'image/png', + 'gif': 'image/gif', + 'webp': 'image/webp', + } + return mediaTypeMap[extension] || 'image/jpeg' +} + +class MediaOverlay extends EventTarget { + #entries + #lastMediaOverlayItem + #sectionIndex + #audioIndex + #itemIndex + #audio + #volume = 1 + #rate = 1 + #state + constructor(book, loadXML) { + super() + this.book = book + this.loadXML = loadXML + } + async #loadSMIL(item) { + if (this.#lastMediaOverlayItem === item) return + const doc = await this.loadXML(item.href) + const resolve = href => href ? resolveURL(href, item.href) : null + const { $, $$$ } = childGetter(doc, NS.SMIL) + this.#audioIndex = -1 + this.#itemIndex = -1 + this.#entries = $$$(doc, 'par').reduce((arr, $par) => { + const text = resolve($($par, 'text')?.getAttribute('src')) + const $audio = $($par, 'audio') + if (!text || !$audio) return arr + const src = resolve($audio.getAttribute('src')) + const begin = parseClock($audio.getAttribute('clipBegin')) + const end = parseClock($audio.getAttribute('clipEnd')) + const last = arr.at(-1) + if (last?.src === src) last.items.push({ text, begin, end }) + else arr.push({ src, items: [{ text, begin, end }] }) + return arr + }, []) + this.#lastMediaOverlayItem = item + } + get #activeAudio() { + return this.#entries[this.#audioIndex] + } + get #activeItem() { + return this.#activeAudio?.items?.[this.#itemIndex] + } + #error(e) { + console.error(e) + this.dispatchEvent(new CustomEvent('error', { detail: e })) + } + #highlight() { + this.dispatchEvent(new CustomEvent('highlight', { detail: this.#activeItem })) + } + #unhighlight() { + this.dispatchEvent(new CustomEvent('unhighlight', { detail: this.#activeItem })) + } + async #play(audioIndex, itemIndex) { + this.#stop() + this.#audioIndex = audioIndex + this.#itemIndex = itemIndex + const src = this.#activeAudio?.src + if (!src || !this.#activeItem) return this.start(this.#sectionIndex + 1) + + const url = URL.createObjectURL(await this.book.loadBlob(src)) + const audio = new Audio(url) + this.#audio = audio + audio.volume = this.#volume + audio.playbackRate = this.#rate + audio.addEventListener('timeupdate', () => { + if (audio.paused) return + const t = audio.currentTime + const { items } = this.#activeAudio + if (t > this.#activeItem?.end) { + this.#unhighlight() + if (this.#itemIndex === items.length - 1) { + this.#play(this.#audioIndex + 1, 0).catch(e => this.#error(e)) + return + } + } + const oldIndex = this.#itemIndex + while (items[this.#itemIndex + 1]?.begin <= t) this.#itemIndex++ + if (this.#itemIndex !== oldIndex) this.#highlight() + }) + audio.addEventListener('error', () => + this.#error(new Error(`Failed to load ${src}`))) + audio.addEventListener('playing', () => this.#highlight()) + audio.addEventListener('ended', () => { + this.#unhighlight() + URL.revokeObjectURL(url) + this.#audio = null + this.#play(audioIndex + 1, 0).catch(e => this.#error(e)) + }) + if (this.#state === 'paused') { + this.#highlight() + audio.currentTime = this.#activeItem.begin ?? 0 + } + else audio.addEventListener('canplaythrough', () => { + // for some reason need to seek in `canplaythrough` + // or it won't play when skipping in WebKit + audio.currentTime = this.#activeItem.begin ?? 0 + this.#state = 'playing' + audio.play().catch(e => this.#error(e)) + }, { once: true }) + } + async start(sectionIndex, filter = () => true) { + this.#audio?.pause() + const section = this.book.sections[sectionIndex] + const href = section?.id + if (!href) return + + const { mediaOverlay } = section + if (!mediaOverlay) return this.start(sectionIndex + 1) + this.#sectionIndex = sectionIndex + await this.#loadSMIL(mediaOverlay) + + for (let i = 0; i < this.#entries.length; i++) { + const { items } = this.#entries[i] + for (let j = 0; j < items.length; j++) { + if (items[j].text.split('#')[0] === href && filter(items[j], j, items)) + return this.#play(i, j).catch(e => this.#error(e)) + } + } + } + pause() { + this.#state = 'paused' + this.#audio?.pause() + } + resume() { + this.#state = 'playing' + this.#audio?.play().catch(e => this.#error(e)) + } + #stop() { + if (this.#audio) { + this.#audio.pause() + URL.revokeObjectURL(this.#audio.src) + this.#audio = null + this.#unhighlight() + } + } + stop() { + this.#state = 'stopped' + this.#stop() + } + prev() { + if (this.#itemIndex > 0) this.#play(this.#audioIndex, this.#itemIndex - 1) + else if (this.#audioIndex > 0) this.#play(this.#audioIndex - 1, + this.#entries[this.#audioIndex - 1].items.length - 1) + else if (this.#sectionIndex > 0) + this.start(this.#sectionIndex - 1, (_, i, items) => i === items.length - 1) + } + next() { + this.#play(this.#audioIndex, this.#itemIndex + 1) + } + setVolume(volume) { + this.#volume = volume + if (this.#audio) this.#audio.volume = volume + } + setRate(rate) { + this.#rate = rate + if (this.#audio) this.#audio.playbackRate = rate + } +} + +const isUUID = /([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/ + +const getUUID = opf => { + for (const el of opf.getElementsByTagNameNS(NS.DC, 'identifier')) { + const [id] = getElementText(el).split(':').slice(-1) + if (isUUID.test(id)) return id + } + return '' +} + +const getIdentifier = opf => getElementText( + opf.getElementById(opf.documentElement.getAttribute('unique-identifier')) + ?? opf.getElementsByTagNameNS(NS.DC, 'identifier')[0]) + +// https://www.w3.org/publishing/epub32/epub-ocf.html#sec-resource-obfuscation +const deobfuscate = async (key, length, blob) => { + const array = new Uint8Array(await blob.slice(0, length).arrayBuffer()) + length = Math.min(length, array.length) + for (var i = 0; i < length; i++) array[i] = array[i] ^ key[i % key.length] + return new Blob([array, blob.slice(length)], { type: blob.type }) +} + +const WebCryptoSHA1 = async str => { + const data = new TextEncoder().encode(str) + const buffer = await globalThis.crypto.subtle.digest('SHA-1', data) + return new Uint8Array(buffer) +} + +const deobfuscators = (sha1 = WebCryptoSHA1) => ({ + 'http://www.idpf.org/2008/embedding': { + key: opf => sha1(getIdentifier(opf) + // eslint-disable-next-line no-control-regex + .replaceAll(/[\u0020\u0009\u000d\u000a]/g, '')), + decode: (key, blob) => deobfuscate(key, 1040, blob), + }, + 'http://ns.adobe.com/pdf/enc#RC': { + key: opf => { + const uuid = getUUID(opf).replaceAll('-', '') + return Uint8Array.from({ length: 16 }, (_, i) => + parseInt(uuid.slice(i * 2, i * 2 + 2), 16)) + }, + decode: (key, blob) => deobfuscate(key, 1024, blob), + }, +}) + +class Encryption { + #uris = new Map() + #decoders = new Map() + #algorithms + constructor(algorithms) { + this.#algorithms = algorithms + } + async init(encryption, opf) { + if (!encryption) return + const data = Array.from( + encryption.getElementsByTagNameNS(NS.ENC, 'EncryptedData'), el => ({ + algorithm: el.getElementsByTagNameNS(NS.ENC, 'EncryptionMethod')[0] + ?.getAttribute('Algorithm'), + uri: el.getElementsByTagNameNS(NS.ENC, 'CipherReference')[0] + ?.getAttribute('URI'), + })) + for (const { algorithm, uri } of data) { + if (!this.#decoders.has(algorithm)) { + const algo = this.#algorithms[algorithm] + if (!algo) { + console.warn('Unknown encryption algorithm') + continue + } + const key = await algo.key(opf) + this.#decoders.set(algorithm, blob => algo.decode(key, blob)) + } + this.#uris.set(uri, algorithm) + } + } + getDecoder(uri) { + return this.#decoders.get(this.#uris.get(uri)) ?? (x => x) + } +} + +class Resources { + constructor({ opf, resolveHref }) { + this.opf = opf + const { $, $$, $$$ } = childGetter(opf, NS.OPF) + + const $manifest = $(opf.documentElement, 'manifest') + const $spine = $(opf.documentElement, 'spine') + const $$itemref = $$($spine, 'itemref') + + this.manifest = $$($manifest, 'item') + .map(getAttributes('href', 'id', 'media-type', 'properties', 'media-overlay')) + .map(item => { + item.href = resolveHref(item.href) + item.properties = item.properties?.split(/\s/) + return item + }) + this.manifestById = new Map(this.manifest.map(item => [item.id, item])) + this.spine = $$itemref + .map(getAttributes('idref', 'id', 'linear', 'properties')) + .map(item => (item.properties = item.properties?.split(/\s/), item)) + this.pageProgressionDirection = $spine + .getAttribute('page-progression-direction') + + this.navPath = this.getItemByProperty('nav')?.href + this.ncxPath = (this.getItemByID($spine.getAttribute('toc')) + ?? this.manifest.find(item => item.mediaType === MIME.NCX))?.href + + const $guide = $(opf.documentElement, 'guide') + if ($guide) this.guide = $$($guide, 'reference') + .map(getAttributes('type', 'title', 'href')) + .map(({ type, title, href }) => ({ + label: title, + type: type.split(/\s/), + href: resolveHref(href), + })) + + this.cover = this.getItemByProperty('cover-image') + // EPUB 2 compat + ?? this.getItemByID($$$(opf, 'meta') + .find(filterAttribute('name', 'cover')) + ?.getAttribute('content')) + ?? this.manifest.find(item => item.id === 'cover' + && item.mediaType.startsWith('image')) + ?? this.manifest.find(item => item.href.includes('cover') + && item.mediaType.startsWith('image')) + ?? this.getItemByHref(this.guide + ?.find(ref => ref.type.includes('cover'))?.href) + // last resort: first image in manifest + ?? this.manifest.find(item => item.mediaType.startsWith('image')) + + this.cfis = CFI.fromElements($$itemref) + } + getItemByID(id) { + return this.manifestById.get(id) + } + getItemByHref(href) { + return this.manifest.find(item => item.href === href) + } + getItemByProperty(prop) { + return this.manifest.find(item => item.properties?.includes(prop)) + } + resolveCFI(cfi) { + const parts = CFI.parse(cfi) + const top = (parts.parent ?? parts).shift() + let $itemref = CFI.toElement(this.opf, top) + // make sure it's an idref; if not, try again without the ID assertion + // mainly because Epub.js used to generate wrong ID assertions + // https://github.com/futurepress/epub.js/issues/1236 + if ($itemref && $itemref.nodeName !== 'idref') { + top.at(-1).id = null + $itemref = CFI.toElement(this.opf, top) + } + const idref = $itemref?.getAttribute('idref') + const index = this.spine.findIndex(item => item.idref === idref) + const anchor = doc => CFI.toRange(doc, parts) + return { index, anchor } + } +} + +class Loader { + #cache = new Map() + #cacheXHTMLContent = new Map() + #children = new Map() + #refCount = new Map() + eventTarget = new EventTarget() + constructor({ loadText, loadBlob, resources, entries }) { + this.loadText = loadText + this.loadBlob = loadBlob + this.manifest = resources.manifest + this.assets = resources.manifest + this.entries = entries + // needed only when replacing in (X)HTML w/o parsing (see below) + //.filter(({ mediaType }) => ![MIME.XHTML, MIME.HTML].includes(mediaType)) + } + async createURL(href, data, type, parent) { + if (!data) return '' + const detail = { data, type } + Object.defineProperty(detail, 'name', { value: href }) // readonly + const event = new CustomEvent('data', { detail }) + this.eventTarget.dispatchEvent(event) + const newData = await event.detail.data + const newType = await event.detail.type + const url = URL.createObjectURL(new Blob([newData], { type: newType })) + this.#cache.set(href, url) + this.#refCount.set(href, 1) + if (newType === MIME.XHTML || newType === MIME.HTML) { + this.#cacheXHTMLContent.set(url, {href, type: newType, data: newData}) + } + if (parent) { + const childList = this.#children.get(parent) + if (childList) childList.push(href) + else this.#children.set(parent, [href]) + } + return url + } + ref(href, parent) { + const childList = this.#children.get(parent) + if (!childList?.includes(href)) { + this.#refCount.set(href, this.#refCount.get(href) + 1) + //console.log(`referencing ${href}, now ${this.#refCount.get(href)}`) + if (childList) childList.push(href) + else this.#children.set(parent, [href]) + } + return this.#cache.get(href) + } + unref(href) { + if (!this.#refCount.has(href)) return + const count = this.#refCount.get(href) - 1 + //console.log(`unreferencing ${href}, now ${count}`) + if (count < 1) { + //console.log(`unloading ${href}`) + const url = this.#cache.get(href) + URL.revokeObjectURL(url) + this.#cache.delete(href) + this.#cacheXHTMLContent.delete(url) + this.#refCount.delete(href) + // unref children + const childList = this.#children.get(href) + if (childList) while (childList.length) this.unref(childList.pop()) + this.#children.delete(href) + } else this.#refCount.set(href, count) + } + // load manifest item, recursively loading all resources as needed + async loadItem(item, parents = []) { + if (!item) return null + const { href, mediaType } = item + + const isScript = MIME.JS.test(item.mediaType) + const detail = { type: mediaType, isScript, allow: true} + const event = new CustomEvent('load', { detail }) + this.eventTarget.dispatchEvent(event) + const allow = await event.detail.allow + if (!allow) return null + + const parent = parents.at(-1) + if (this.#cache.has(href)) return this.ref(href, parent) + + const shouldReplace = + (isScript || [MIME.XHTML, MIME.HTML, MIME.CSS, MIME.SVG].includes(mediaType)) + // prevent circular references + && parents.every(p => p !== href) + if (shouldReplace) return this.loadReplaced(item, parents) + // NOTE: this can be replaced with `Promise.try()` + const tryLoadBlob = Promise.resolve().then(() => this.loadBlob(href)) + return this.createURL(href, tryLoadBlob, mediaType, parent) + } + async loadItemXHTMLContent(item, parents = []) { + const url = await this.loadItem(item, parents) + if (url) return this.#cacheXHTMLContent.get(url)?.data + } + tryImageEntryItem(path) { + if (!IMAGE_EXTENSIONS.some(ext => path.toLowerCase().endsWith(`.${ext}`))) { + return null + } + if (!this.entries.get(path)) { + return null + } + return { + href: path, + mediaType: getImageMediaType(path), + } + } + async loadHref(href, base, parents = []) { + if (isExternal(href)) return href + const path = resolveURL(href, base) + let item = this.manifest.find(item => item.href === path) + if (!item) { + item = this.tryImageEntryItem(path) + if (!item) { + return href + } + } + return this.loadItem(item, parents.concat(base)) + } + async loadReplaced(item, parents = []) { + const { href, mediaType } = item + const parent = parents.at(-1) + let str = '' + try { + str = await this.loadText(href) + } catch (e) { + return this.createURL(href, Promise.reject(e), mediaType, parent) + } + if (!str) return null + + // note that one can also just use `replaceString` for everything: + // ``` + // const replaced = await this.replaceString(str, href, parents) + // return this.createURL(href, replaced, mediaType, parent) + // ``` + // which is basically what Epub.js does, which is simpler, but will + // break things like iframes (because you don't want to replace links) + // or text that just happen to be paths + + // parse and replace in HTML + if ([MIME.XHTML, MIME.HTML, MIME.SVG].includes(mediaType)) { + let doc = new DOMParser().parseFromString(str, mediaType) + // change to HTML if it's not valid XHTML + if (mediaType === MIME.XHTML && (doc.querySelector('parsererror') + || !doc.documentElement?.namespaceURI)) { + console.warn(doc.querySelector('parsererror')?.innerText ?? 'Invalid XHTML') + item.mediaType = MIME.HTML + doc = new DOMParser().parseFromString(str, item.mediaType) + } + // replace hrefs in XML processing instructions + // this is mainly for SVGs that use xml-stylesheet + if ([MIME.XHTML, MIME.SVG].includes(item.mediaType)) { + let child = doc.firstChild + while (child instanceof ProcessingInstruction) { + if (child.data) { + const replacedData = await replaceSeries(child.data, + /(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i, + (_, p1, p2, p3) => this.loadHref(p2, href, parents) + .then(p2 => `${p1}${p2}${p3}`)) + child.replaceWith(doc.createProcessingInstruction( + child.target, replacedData)) + } + child = child.nextSibling + } + } + // replace hrefs (excluding anchors) + const replace = async (el, attr) => el.setAttribute(attr, + await this.loadHref(el.getAttribute(attr), href, parents)) + for (const el of doc.querySelectorAll('link[href]')) await replace(el, 'href') + for (const el of doc.querySelectorAll('[src]')) await replace(el, 'src') + for (const el of doc.querySelectorAll('[poster]')) await replace(el, 'poster') + for (const el of doc.querySelectorAll('object[data]')) await replace(el, 'data') + for (const el of doc.querySelectorAll('[*|href]:not([href])')) + el.setAttributeNS(NS.XLINK, 'href', await this.loadHref( + el.getAttributeNS(NS.XLINK, 'href'), href, parents)) + for (const el of doc.querySelectorAll('[srcset]')) + el.setAttribute('srcset', await replaceSeries(el.getAttribute('srcset'), + /(\s*)(.+?)\s*((?:\s[\d.]+[wx])+\s*(?:,|$)|,\s+|$)/g, + (_, p1, p2, p3) => this.loadHref(p2, href, parents) + .then(p2 => `${p1}${p2}${p3}`))) + // replace inline styles + for (const el of doc.querySelectorAll('style')) + if (el.textContent) el.textContent = + await this.replaceCSS(el.textContent, href, parents) + for (const el of doc.querySelectorAll('[style]')) + el.setAttribute('style', + await this.replaceCSS(el.getAttribute('style'), href, parents)) + // TODO: replace inline scripts? probably not worth the trouble + const result = new XMLSerializer().serializeToString(doc) + return this.createURL(href, result, item.mediaType, parent) + } + + const result = mediaType === MIME.CSS + ? await this.replaceCSS(str, href, parents) + : await this.replaceString(str, href, parents) + return this.createURL(href, result, mediaType, parent) + } + async replaceCSS(str, href, parents = []) { + const replacedUrls = await replaceSeries(str, + /url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi, + (_, url) => this.loadHref(url, href, parents) + .then(url => `url("${url}")`)) + // apart from `url()`, strings can be used for `@import` (but why?!) + return replaceSeries(replacedUrls, + /@import\s*["']([^"'\n]*?)["']/gi, + (_, url) => this.loadHref(url, href, parents) + .then(url => `@import "${url}"`)) + } + // find & replace all possible relative paths for all assets without parsing + replaceString(str, href, parents = []) { + const assetMap = new Map() + const urls = this.assets.map(asset => { + // do not replace references to the file itself + if (asset.href === href) return + // href was decoded and resolved when parsing the manifest + const relative = pathRelative(pathDirname(href), asset.href) + const relativeEnc = encodeURI(relative) + const rootRelative = '/' + asset.href + const rootRelativeEnc = encodeURI(rootRelative) + const set = new Set([relative, relativeEnc, rootRelative, rootRelativeEnc]) + for (const url of set) assetMap.set(url, asset) + return Array.from(set) + }).flat().filter(x => x) + if (!urls.length) return str + const regex = new RegExp(urls.map(regexEscape).join('|'), 'g') + return replaceSeries(str, regex, async match => + this.loadItem(assetMap.get(match.replace(/^\//, '')), + parents.concat(href))) + } + unloadItem(item) { + this.unref(item?.href) + } + destroy() { + for (const url of this.#cache.values()) URL.revokeObjectURL(url) + } +} + +const getHTMLFragment = (doc, id) => doc.getElementById(id) + ?? doc.querySelector(`[name="${CSS.escape(id)}"]`) + +const getPageSpread = properties => { + for (const p of properties) { + if (p === 'page-spread-left' || p === 'rendition:page-spread-left') + return 'left' + if (p === 'page-spread-right' || p === 'rendition:page-spread-right') + return 'right' + if (p === 'rendition:page-spread-center') return 'center' + } +} + +const getDisplayOptions = doc => { + if (!doc) return null + return { + fixedLayout: getElementText(doc.querySelector('option[name="fixed-layout"]')), + openToSpread: getElementText(doc.querySelector('option[name="open-to-spread"]')), + } +} + +export class EPUB { + parser = new DOMParser() + #loader + #encryption + constructor({ entries, loadText, loadBlob, getSize, sha1 }) { + this.entries = entries.reduce((map, entry) => { + map.set(entry.filename, entry) + return map + }, new Map()) + this.loadText = loadText + this.loadBlob = loadBlob + this.getSize = getSize + this.#encryption = new Encryption(deobfuscators(sha1)) + } + #sanitizeXMLEntities(str) { + // Common HTML entities that aren't valid in XML + const entityMap = { + 'nbsp': ' ', + 'mdash': '—', + 'ndash': '–', + 'ldquo': '“', + 'rdquo': '”', + 'lsquo': '‘', + 'rsquo': '’', + 'hellip': '…', + 'copy': '©', + 'reg': '®', + 'trade': '™', + 'bull': '•', + 'middot': '·', + } + return str.replace(/&([a-z]+);/gi, (match, entity) => { + return entityMap[entity.toLowerCase()] || match + }) + } + async #loadXML(uri) { + const str = await this.loadText(uri) + if (!str) return null + const sanitized = this.#sanitizeXMLEntities(str) + const doc = this.parser.parseFromString(sanitized, MIME.XML) + if (doc.querySelector('parsererror')) + throw new Error(`XML parsing error: ${uri} +${doc.querySelector('parsererror').innerText}`) + return doc + } + async init() { + const $container = await this.#loadXML('META-INF/container.xml') + if (!$container) throw new Error('Failed to load container file') + + const opfs = Array.from( + $container.getElementsByTagNameNS(NS.CONTAINER, 'rootfile'), + getAttributes('full-path', 'media-type')) + .filter(file => file.mediaType === 'application/oebps-package+xml') + + if (!opfs.length) throw new Error('No package document defined in container') + const opfPath = opfs[0].fullPath + const opf = await this.#loadXML(opfPath) + if (!opf) throw new Error('Failed to load package document') + + const $encryption = await this.#loadXML('META-INF/encryption.xml') + await this.#encryption.init($encryption, opf) + + this.resources = new Resources({ + opf, + resolveHref: url => resolveURL(url, opfPath), + }) + this.#loader = new Loader({ + loadText: this.loadText, + loadBlob: uri => Promise.resolve(this.loadBlob(uri)) + .then(this.#encryption.getDecoder(uri)), + resources: this.resources, + entries: this.entries, + }) + this.transformTarget = this.#loader.eventTarget + this.sections = this.resources.spine.map((spineItem, index) => { + const { idref, linear, properties = [] } = spineItem + const item = this.resources.getItemByID(idref) + if (!item) { + console.warn(`Could not find item with ID "${idref}" in manifest`) + return null + } + return { + id: item.href, + load: () => this.#loader.loadItem(item), + unload: () => this.#loader.unloadItem(item), + loadText: () => this.#loader.loadText(item.href), + loadContent: () => this.#loader.loadItemXHTMLContent(item), + createDocument: () => this.loadDocument(item), + size: this.getSize(item.href), + cfi: this.resources.cfis[index], + linear, + pageSpread: getPageSpread(properties), + resolveHref: href => resolveURL(href, item.href), + mediaOverlay: item.mediaOverlay + ? this.resources.getItemByID(item.mediaOverlay) : null, + } + }).filter(s => s) + + const { navPath, ncxPath } = this.resources + if (navPath) try { + const resolve = url => resolveURL(url, navPath) + const nav = parseNav(await this.#loadXML(navPath), resolve) + this.toc = nav.toc + this.pageList = nav.pageList + this.landmarks = nav.landmarks + } catch(e) { + console.warn(e) + } + if (!this.toc && ncxPath) try { + const resolve = url => resolveURL(url, ncxPath) + const ncx = parseNCX(await this.#loadXML(ncxPath), resolve) + this.toc = ncx.toc + this.pageList = ncx.pageList + } catch(e) { + console.warn(e) + } + + await this.#updateSubItems() + + this.landmarks ??= this.resources.guide + + const { metadata, rendition, media } = getMetadata(opf) + this.metadata = metadata + this.rendition = rendition + this.media = media + this.dir = this.resources.pageProgressionDirection + const displayOptions = getDisplayOptions( + await this.#loadXML('META-INF/com.apple.ibooks.display-options.xml') + ?? await this.#loadXML('META-INF/com.kobobooks.display-options.xml')) + if (displayOptions) { + if (displayOptions.fixedLayout === 'true') + this.rendition.layout ??= 'pre-paginated' + if (displayOptions.openToSpread === 'false') this.sections + .find(section => section.linear !== 'no').pageSpread ??= + this.dir === 'rtl' ? 'left' : 'right' + } + return this + } + + #groupTocSubitems(items) { + // Helper: Group subitems by section ID + const groupBySection = (subitems) => { + const grouped = new Map() + for (const subitem of subitems) { + const [sectionId] = this.splitTOCHref(subitem.href) + if (!grouped.has(sectionId)) grouped.set(sectionId, []) + grouped.get(sectionId).push(subitem) + } + return grouped + } + + // Helper: Separate parent item from fragment items + const separateParentAndFragments = (sectionId, subitems) => { + let parent = null + const fragments = [] + + for (const subitem of subitems) { + const [, fragmentId] = this.splitTOCHref(subitem.href) + if (!fragmentId || subitem.href === sectionId) { + parent = subitem + } else { + fragments.push(subitem) + } + } + + return { parent, fragments } + } + + // Helper: Create grouped structure for multiple items in same section + const createGroupedItem = (sectionId, subitems) => { + const { parent, fragments } = separateParentAndFragments(sectionId, subitems) + + // Use existing parent or create new one + const parentItem = parent ?? { + label: subitems[0].label || sectionId, + href: sectionId, + } + + // Nest fragment items under parent + if (fragments.length > 0) { + parentItem.subitems = fragments + } + + return parentItem + } + + for (const item of items) { + if (!item.subitems?.length) continue + + const groupedBySection = groupBySection(item.subitems) + const newSubitems = [] + + for (const [sectionId, subitems] of groupedBySection.entries()) { + const groupedItem = subitems.length === 1 + ? subitems[0] // Single item, keep as-is + : createGroupedItem(sectionId, subitems) // Multiple items, group them + + newSubitems.push(groupedItem) + } + + item.subitems = newSubitems + } + } + + // Helper: Find position of fragment ID in HTML string + #findFragmentPosition(html, fragmentId) { + if (!fragmentId) return html.length + + const patterns = [ + new RegExp(`\\sid=["']${CSS.escape(fragmentId)}["']`, 'i'), + new RegExp(`\\sname=["']${CSS.escape(fragmentId)}["']`, 'i'), + ] + + for (const pattern of patterns) { + const match = html.match(pattern) + if (match) return match.index + } + + return -1 + } + + // Helper: Flatten nested TOC structure into single array + #collectAllTocItems(tocItems) { + const allItems = [] + const traverse = (items) => { + for (const item of items) { + allItems.push(item) + if (item.subitems?.length) traverse(item.subitems) + } + } + traverse(tocItems) + return allItems + } + + // Helper: Group TOC items by section ID (base + fragments) + #groupItemsBySection(allItems) { + const sectionGroups = new Map() + + for (const item of allItems) { + const [sectionId, fragmentId] = this.splitTOCHref(item.href) + + if (!sectionGroups.has(sectionId)) { + sectionGroups.set(sectionId, { base: null, fragments: [] }) + } + + const group = sectionGroups.get(sectionId) + const isBase = !fragmentId || item.href === sectionId + + if (isBase) group.base = item + else group.fragments.push(item) + } + + return sectionGroups + } + + // Helper: Calculate byte size of HTML between two fragments + #calculateFragmentSize(content, fragmentId, prevFragmentId) { + const endPos = this.#findFragmentPosition(content, fragmentId) + if (endPos < 0) return 0 + + const startPos = prevFragmentId + ? this.#findFragmentPosition(content, prevFragmentId) + : 0 + + const validStartPos = Math.max(0, startPos) + if (endPos < validStartPos) return 0 + + const htmlSubstring = content.substring(validStartPos, endPos) + return new Blob([htmlSubstring]).size + } + + // Helper: Load and cache section HTML content + async #loadSectionContent(section, contentCache) { + const cached = contentCache.get(section.id) + if (cached) return cached + + const content = await section.loadText() + if (content) contentCache.set(section.id, content) + + return content + } + + // Helper: Create section subitems from fragments + #createSectionSubitems(fragments, base, content, section) { + const subitems = [] + for (let i = 0; i < fragments.length; i++) { + const fragment = fragments[i] + const [, fragmentId] = this.splitTOCHref(fragment.href) + + const prevFragment = i > 0 ? fragments[i - 1] : base + const [, prevFragmentId] = prevFragment + ? this.splitTOCHref(prevFragment.href) + : [null, null] + + const size = this.#calculateFragmentSize(content, fragmentId, prevFragmentId) + + subitems.push({ + id: fragment.href, + href: fragment.href, + cfi: fragment.cfi, + size, + linear: section.linear, + }) + } + + return subitems + } + + // Update section subitems from TOC structure + async #updateSubItems() { + if (!this.toc || !this.sections) return + + // Step 1: Group TOC items by section + this.#groupTocSubitems(this.toc) + + // Step 2: Prepare section lookup and content cache + const sectionMap = new Map(this.sections.map(s => [s.id, s])) + const contentCache = new Map() + + // Step 3: Flatten TOC and group by section ID + const allTocItems = this.#collectAllTocItems(this.toc) + const sectionGroups = this.#groupItemsBySection(allTocItems) + + // Step 4: Process each section and create subitems + for (const [sectionId, { base, fragments }] of sectionGroups.entries()) { + const section = sectionMap.get(sectionId) + if (!section || fragments.length === 0) continue + + // Load HTML content for this section + const content = await this.#loadSectionContent(section, contentCache) + if (!content) continue + + // Create subitems from fragments + const subitems = this.#createSectionSubitems(fragments, base, content, section) + + // Assign to section + if (subitems.length > 0) { + section.subitems = subitems + } + } + } + async loadDocument(item) { + const str = await this.loadText(item.href) + return this.parser.parseFromString(str, item.mediaType) + } + getMediaOverlay() { + return new MediaOverlay(this, this.#loadXML.bind(this)) + } + resolveCFI(cfi) { + return this.resources.resolveCFI(cfi) + } + resolveHref(href) { + const [path, hash] = href.split('#') + const item = this.resources.getItemByHref(decodeURI(path)) + if (!item) return null + const index = this.resources.spine.findIndex(({ idref }) => idref === item.id) + const anchor = hash ? doc => getHTMLFragment(doc, hash) : () => 0 + return { index, anchor } + } + splitTOCHref(href) { + return href?.split('#') ?? [] + } + getTOCFragment(doc, id) { + return doc.getElementById(id) + ?? doc.querySelector(`[name="${CSS.escape(id)}"]`) + } + isExternal(uri) { + return isExternal(uri) + } + async getCover() { + const cover = this.resources?.cover + return cover?.href + ? new Blob([await this.loadBlob(cover.href)], { type: cover.mediaType }) + : null + } + async getCalibreBookmarks() { + const txt = await this.loadText('META-INF/calibre_bookmarks.txt') + const magic = 'encoding=json+base64:' + if (txt?.startsWith(magic)) { + const json = atob(txt.slice(magic.length)) + return JSON.parse(json) + } + } + destroy() { + this.#loader?.destroy() + } +} diff --git a/packages/foliate-js/epubcfi.js b/packages/foliate-js/epubcfi.js new file mode 100644 index 0000000000000000000000000000000000000000..173609128b014f169dadb1c5d8f64bbf327200ee --- /dev/null +++ b/packages/foliate-js/epubcfi.js @@ -0,0 +1,345 @@ +const findIndices = (arr, f) => arr + .map((x, i, a) => f(x, i, a) ? i : null).filter(x => x != null) +const splitAt = (arr, is) => [-1, ...is, arr.length].reduce(({ xs, a }, b) => + ({ xs: xs?.concat([arr.slice(a + 1, b)]) ?? [], a: b }), {}).xs +const concatArrays = (a, b) => + a.slice(0, -1).concat([a[a.length - 1].concat(b[0])]).concat(b.slice(1)) + +const isNumber = /\d/ +export const isCFI = /^epubcfi\((.*)\)$/ +const escapeCFI = str => str.replace(/[\^[\](),;=]/g, '^$&') + +const wrap = x => isCFI.test(x) ? x : `epubcfi(${x})` +const unwrap = x => x.match(isCFI)?.[1] ?? x +const lift = f => (...xs) => + `epubcfi(${f(...xs.map(x => x.match(isCFI)?.[1] ?? x))})` +export const joinIndir = lift((...xs) => xs.join('!')) + +const tokenizer = str => { + const tokens = [] + let state, escape, value = '' + const push = x => (tokens.push(x), state = null, value = '') + const cat = x => (value += x, escape = false) + for (const char of Array.from(str.trim()).concat('')) { + if (char === '^' && !escape) { + escape = true + continue + } + if (state === '!') push(['!']) + else if (state === ',') push([',']) + else if (state === '/' || state === ':') { + if (isNumber.test(char)) { + cat(char) + continue + } else push([state, parseInt(value)]) + } else if (state === '~') { + if (isNumber.test(char) || char === '.') { + cat(char) + continue + } else push(['~', parseFloat(value)]) + } else if (state === '@') { + if (char === ':') { + push(['@', parseFloat(value)]) + state = '@' + continue + } + if (isNumber.test(char) || char === '.') { + cat(char) + continue + } else push(['@', parseFloat(value)]) + } else if (state === '[') { + if (char === ';' && !escape) { + push(['[', value]) + state = ';' + } else if (char === ',' && !escape) { + push(['[', value]) + state = '[' + } else if (char === ']' && !escape) push(['[', value]) + else cat(char) + continue + } else if (state?.startsWith(';')) { + if (char === '=' && !escape) { + state = `;${value}` + value = '' + } else if (char === ';' && !escape) { + push([state, value]) + state = ';' + } else if (char === ']' && !escape) push([state, value]) + else cat(char) + continue + } + if (char === '/' || char === ':' || char === '~' || char === '@' + || char === '[' || char === '!' || char === ',') state = char + } + return tokens +} + +const findTokens = (tokens, x) => findIndices(tokens, ([t]) => t === x) + +const parser = tokens => { + const parts = [] + let state + for (const [type, val] of tokens) { + if (type === '/') parts.push({ index: val }) + else { + const last = parts[parts.length - 1] + if (type === ':') last.offset = val + else if (type === '~') last.temporal = val + else if (type === '@') last.spatial = (last.spatial ?? []).concat(val) + else if (type === ';s') last.side = val + else if (type === '[') { + if (state === '/' && val) last.id = val + else { + last.text = (last.text ?? []).concat(val) + continue + } + } + } + state = type + } + return parts +} + +// split at step indirections, then parse each part +const parserIndir = tokens => + splitAt(tokens, findTokens(tokens, '!')).map(parser) + +export const parse = cfi => { + const tokens = tokenizer(unwrap(cfi)) + const commas = findTokens(tokens, ',') + if (!commas.length) return parserIndir(tokens) + const [parent, start, end] = splitAt(tokens, commas).map(parserIndir) + return { parent, start, end } +} + +const partToString = ({ index, id, offset, temporal, spatial, text, side }) => { + const param = side ? `;s=${side}` : '' + return `/${index}` + + (id ? `[${escapeCFI(id)}${param}]` : '') + // "CFI expressions [..] SHOULD include an explicit character offset" + + (offset != null && index % 2 ? `:${offset}` : '') + + (temporal ? `~${temporal}` : '') + + (spatial ? `@${spatial.join(':')}` : '') + + (text || (!id && side) ? '[' + + (text?.map(escapeCFI)?.join(',') ?? '') + + param + ']' : '') +} + +const toInnerString = parsed => parsed.parent + ? [parsed.parent, parsed.start, parsed.end].map(toInnerString).join(',') + : parsed.map(parts => parts.map(partToString).join('')).join('!') + +const toString = parsed => wrap(toInnerString(parsed)) + +export const collapse = (x, toEnd) => typeof x === 'string' + ? toString(collapse(parse(x), toEnd)) + : x.parent ? concatArrays(x.parent, x[toEnd ? 'end' : 'start']) : x + +// create range CFI from two CFIs +const buildRange = (from, to) => { + if (typeof from === 'string') from = parse(from) + if (typeof to === 'string') to = parse(to) + from = collapse(from) + to = collapse(to, true) + // ranges across multiple documents are not allowed; handle local paths only + const localFrom = from[from.length - 1], localTo = to[to.length - 1] + const localParent = [], localStart = [], localEnd = [] + let pushToParent = true + const len = Math.max(localFrom.length, localTo.length) + for (let i = 0; i < len; i++) { + const a = localFrom[i], b = localTo[i] + pushToParent &&= a?.index === b?.index && !a?.offset && !b?.offset + if (pushToParent) localParent.push(a) + else { + if (a) localStart.push(a) + if (b) localEnd.push(b) + } + } + // copy non-local paths from `from` + const parent = from.slice(0, -1).concat([localParent]) + return toString({ parent, start: [localStart], end: [localEnd] }) +} + +export const compare = (a, b) => { + if (typeof a === 'string') a = parse(a) + if (typeof b === 'string') b = parse(b) + if (a.start || b.start) return compare(collapse(a), collapse(b)) + || compare(collapse(a, true), collapse(b, true)) + + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const p = a[i] ?? [], q = b[i] ?? [] + const maxIndex = Math.max(p.length, q.length) - 1 + for (let i = 0; i <= maxIndex; i++) { + const x = p[i], y = q[i] + if (!x) return -1 + if (!y) return 1 + if (x.index > y.index) return 1 + if (x.index < y.index) return -1 + if (i === maxIndex) { + // TODO: compare temporal & spatial offsets + if (x.offset > y.offset) return 1 + if (x.offset < y.offset) return -1 + } + } + } + return 0 +} + +const isTextNode = ({ nodeType }) => nodeType === 3 || nodeType === 4 +const isElementNode = ({ nodeType }) => nodeType === 1 + +const getChildNodes = (node, filter) => { + const nodes = Array.from(node.childNodes) + // "content other than element and character data is ignored" + .filter(node => isTextNode(node) || isElementNode(node)) + return filter ? nodes.map(node => { + const accept = filter(node) + if (accept === NodeFilter.FILTER_REJECT) return null + else if (accept === NodeFilter.FILTER_SKIP) return getChildNodes(node, filter) + else return node + }).flat().filter(x => x) : nodes +} + +// child nodes are organized such that the result is always +// [element, text, element, text, ..., element], +// regardless of the actual structure in the document; +// so multiple text nodes need to be combined, and nonexistent ones counted; +// see "Step Reference to Child Element or Character Data (/)" in EPUB CFI spec +const indexChildNodes = (node, filter) => { + const nodes = getChildNodes(node, filter) + .reduce((arr, node) => { + let last = arr[arr.length - 1] + if (!last) arr.push(node) + // "there is one chunk between each pair of child elements" + else if (isTextNode(node)) { + if (Array.isArray(last)) last.push(node) + else if (isTextNode(last)) arr[arr.length - 1] = [last, node] + else arr.push(node) + } else { + if (isElementNode(last)) arr.push(null, node) + else arr.push(node) + } + return arr + }, []) + // "the first chunk is located before the first child element" + if (isElementNode(nodes[0])) nodes.unshift('first') + // "the last chunk is located after the last child element" + if (isElementNode(nodes[nodes.length - 1])) nodes.push('last') + // "'virtual' elements" + nodes.unshift('before') // "0 is a valid index" + nodes.push('after') // "n+2 is a valid index" + return nodes +} + +const partsToNode = (node, parts, filter) => { + const { id } = parts[parts.length - 1] + if (id) { + const el = node.ownerDocument.getElementById(id) + if (el) return { node: el, offset: 0 } + } + for (const { index } of parts) { + const newNode = node ? indexChildNodes(node, filter)[index] : null + // handle non-existent nodes + if (newNode === 'first') return { node: node.firstChild ?? node } + if (newNode === 'last') return { node: node.lastChild ?? node } + if (newNode === 'before') return { node, before: true } + if (newNode === 'after') return { node, after: true } + node = newNode + } + const { offset } = parts[parts.length - 1] + if (!Array.isArray(node)) return { node, offset } + // get underlying text node and offset from the chunk + let sum = 0 + for (const n of node) { + const { length } = n.nodeValue + if (sum + length >= offset) return { node: n, offset: offset - sum } + sum += length + } +} + +const nodeToParts = (node, offset, filter) => { + const { parentNode, id } = node + const indexed = indexChildNodes(parentNode, filter) + const index = indexed.findIndex(x => + Array.isArray(x) ? x.some(x => x === node) : x === node) + // adjust offset as if merging the text nodes in the chunk + const chunk = indexed[index] + if (Array.isArray(chunk)) { + let sum = 0 + for (const x of chunk) { + if (x === node) { + sum += offset + break + } else sum += x.nodeValue.length + } + offset = sum + } + const part = { id, index, offset } + return (parentNode !== node.ownerDocument.documentElement + ? nodeToParts(parentNode, null, filter).concat(part) : [part]) + // remove ignored nodes + .filter(x => x.index !== -1) +} + +export const fromRange = (range, filter) => { + const { startContainer, startOffset, endContainer, endOffset } = range + const start = nodeToParts(startContainer, startOffset, filter) + if (range.collapsed) return toString([start]) + const end = nodeToParts(endContainer, endOffset, filter) + return buildRange([start], [end]) +} + +export const toRange = (doc, parts, filter) => { + const startParts = collapse(parts) + const endParts = collapse(parts, true) + + const root = doc.documentElement + const start = partsToNode(root, startParts[0], filter) + const end = partsToNode(root, endParts[0], filter) + + const range = doc.createRange() + + if (start.before) range.setStartBefore(start.node) + else if (start.after) range.setStartAfter(start.node) + else range.setStart(start.node, start.offset) + + if (end.before) range.setEndBefore(end.node) + else if (end.after) range.setEndAfter(end.node) + else range.setEnd(end.node, end.offset) + return range +} + +// faster way of getting CFIs for sorted elements in a single parent +export const fromElements = elements => { + const results = [] + const { parentNode } = elements[0] + const parts = nodeToParts(parentNode) + for (const [index, node] of indexChildNodes(parentNode).entries()) { + const el = elements[results.length] + if (node === el) + results.push(toString([parts.concat({ id: el.id, index })])) + } + return results +} + +export const toElement = (doc, parts) => + partsToNode(doc.documentElement, collapse(parts)).node + +// turn indices into standard CFIs when you don't have an actual package document +export const fake = { + fromIndex: index => wrap(`/6/${(index + 1) * 2}`), + toIndex: parts => parts?.at(-1).index / 2 - 1, +} + +// get CFI from Calibre bookmarks +// see https://github.com/johnfactotum/foliate/issues/849 +export const fromCalibrePos = pos => { + const [parts] = parse(pos) + const item = parts.shift() + parts.shift() + return toString([[{ index: 6 }, item], parts]) +} +export const fromCalibreHighlight = ({ spine_index, start_cfi, end_cfi }) => { + const pre = fake.fromIndex(spine_index) + '!' + return buildRange(pre + start_cfi.slice(2), pre + end_cfi.slice(2)) +} diff --git a/packages/foliate-js/eslint.config.js b/packages/foliate-js/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..5a60a62a48edc3ea67ac22dcb67eb0ef205291a8 --- /dev/null +++ b/packages/foliate-js/eslint.config.js @@ -0,0 +1,22 @@ +import js from '@eslint/js' +import globals from 'globals' + +export default [js.configs.recommended, { ignores: ['vendor'] }, { + languageOptions: { + globals: globals.browser, + }, + linterOptions: { + reportUnusedDisableDirectives: true, + }, + rules: { + semi: ['error', 'never'], + indent: ['warn', 4, { flatTernaryExpressions: true, SwitchCase: 1 }], + quotes: ['warn', 'single', { avoidEscape: true }], + 'comma-dangle': ['warn', 'always-multiline'], + 'no-trailing-spaces': 'warn', + 'no-unused-vars': 'warn', + 'no-console': ['warn', { allow: ['debug', 'warn', 'error', 'assert'] }], + 'no-constant-condition': ['error', { checkLoops: false }], + 'no-empty': ['error', { allowEmptyCatch: true }], + }, +}] diff --git a/packages/foliate-js/fb2.js b/packages/foliate-js/fb2.js new file mode 100644 index 0000000000000000000000000000000000000000..a1623c405d295aab26c121574990cac51b0035da --- /dev/null +++ b/packages/foliate-js/fb2.js @@ -0,0 +1,348 @@ +const normalizeWhitespace = str => str ? str + .replace(/[\t\n\f\r ]+/g, ' ') + .replace(/^[\t\n\f\r ]+/, '') + .replace(/[\t\n\f\r ]+$/, '') : '' +const getElementText = el => normalizeWhitespace(el?.textContent) + +const NS = { + XLINK: 'http://www.w3.org/1999/xlink', + EPUB: 'http://www.idpf.org/2007/ops', +} + +const MIME = { + XML: 'application/xml', + XHTML: 'application/xhtml+xml', +} + +const STYLE = { + 'strong': ['strong', 'self'], + 'emphasis': ['em', 'self'], + 'style': ['span', 'self'], + 'a': 'anchor', + 'strikethrough': ['s', 'self'], + 'sub': ['sub', 'self'], + 'sup': ['sup', 'self'], + 'code': ['code', 'self'], + 'image': 'image', +} + +const TABLE = { + 'tr': ['tr', { + 'th': ['th', STYLE, ['colspan', 'rowspan', 'align', 'valign']], + 'td': ['td', STYLE, ['colspan', 'rowspan', 'align', 'valign']], + }, ['align']], +} + +const POEM = { + 'epigraph': ['blockquote'], + 'subtitle': ['h2', STYLE], + 'text-author': ['p', STYLE], + 'date': ['p', STYLE], + 'stanza': ['div', 'self'], + 'v': ['div', STYLE], +} + +const SECTION = { + 'title': ['header', { + 'p': ['h1', STYLE], + 'empty-line': ['br'], + }], + 'epigraph': ['blockquote', 'self'], + 'image': 'image', + 'annotation': ['aside'], + 'section': ['section', 'self'], + 'p': ['p', STYLE], + 'poem': ['blockquote', POEM], + 'subtitle': ['h2', STYLE], + 'cite': ['blockquote', 'self'], + 'empty-line': ['br'], + 'table': ['table', TABLE], + 'text-author': ['p', STYLE], +} +POEM['epigraph'].push(SECTION) + +const BODY = { + 'image': 'image', + 'title': ['section', { + 'p': ['h1', STYLE], + 'empty-line': ['br'], + }], + 'epigraph': ['section', SECTION], + 'section': ['section', SECTION], +} + +class FB2Converter { + constructor(fb2) { + this.fb2 = fb2 + this.doc = document.implementation.createDocument(NS.XHTML, 'html') + // use this instead of `getElementById` to allow images like + // `` + this.bins = new Map(Array.from(this.fb2.getElementsByTagName('binary'), + el => [el.id, el])) + } + getImageSrc(el) { + const href = el.getAttributeNS(NS.XLINK, 'href') + if (!href) return 'data:,' + const [, id] = href.split('#') + if (!id) return href + const bin = this.bins.get(id) + return bin + ? `data:${bin.getAttribute('content-type')};base64,${bin.textContent}` + : href + } + image(node) { + const el = this.doc.createElement('img') + el.alt = node.getAttribute('alt') + el.title = node.getAttribute('title') + el.setAttribute('src', this.getImageSrc(node)) + return el + } + anchor(node) { + const el = this.convert(node, { 'a': ['a', STYLE] }) + el.setAttribute('href', node.getAttributeNS(NS.XLINK, 'href')) + if (node.getAttribute('type') === 'note') + el.setAttributeNS(NS.EPUB, 'epub:type', 'noteref') + return el + } + convert(node, def) { + // not an element; return text content + if (node.nodeType === 3) return this.doc.createTextNode(node.textContent) + if (node.nodeType === 4) return this.doc.createCDATASection(node.textContent) + if (node.nodeType === 8) return this.doc.createComment(node.textContent) + + const d = def?.[node.nodeName] + if (!d) return null + if (typeof d === 'string') return this[d](node) + + const [name, opts, attrs] = d + const el = this.doc.createElement(name) + + // copy the ID, and set class name from original element name + if (node.id) el.id = node.id + el.classList.add(node.nodeName) + + // copy attributes + if (Array.isArray(attrs)) for (const attr of attrs) { + const value = node.getAttribute(attr) + if (value) el.setAttribute(attr, value) + } + + // process child elements recursively + const childDef = opts === 'self' ? def : opts + let child = node.firstChild + while (child) { + const childEl = this.convert(child, childDef) + if (childEl) el.append(childEl) + child = child.nextSibling + } + return el + } +} + +const parseXML = async blob => { + const buffer = await blob.arrayBuffer() + const str = new TextDecoder('utf-8').decode(buffer) + const parser = new DOMParser() + const doc = parser.parseFromString(str, MIME.XML) + const encoding = doc.xmlEncoding + // `Document.xmlEncoding` is deprecated, and already removed in Firefox + // so parse the XML declaration manually + || str.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1] + if (encoding && encoding.toLowerCase() !== 'utf-8') { + const str = new TextDecoder(encoding).decode(buffer) + return parser.parseFromString(str, MIME.XML) + } + return doc +} + +const style = URL.createObjectURL(new Blob([` +@namespace epub "http://www.idpf.org/2007/ops"; +body > img, section > img { + display: block; + margin: auto; +} +.title h1 { + text-align: center; +} +body > section > .title, body.notesBodyType > .title { + margin: 3em 0; +} +body.notesBodyType > section .title h1 { + text-align: start; +} +body.notesBodyType > section .title { + margin: 1em 0; +} +p { + text-indent: 1em; + margin: 0; +} +:not(p) + p, p:first-child { + text-indent: 0; +} +.stanza { + text-indent: 0; + margin: 1em 0; +} +.text-author, .date { + text-align: end; +} +.text-author:before { + content: "—"; +} +table { + border-collapse: collapse; +} +td, th { + padding: .25em; +} +a[epub|type~="noteref"] { + font-size: .75em; + vertical-align: super; +} +body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph { + margin: 3em 0; +} +`], { type: 'text/css' })) + +const template = html => ` + + + ${html} +` + +// name of custom ID attribute for TOC items +const dataID = 'data-foliate-id' + +export const makeFB2 = async blob => { + const book = {} + const doc = await parseXML(blob) + const converter = new FB2Converter(doc) + + const $ = x => doc.querySelector(x) + const $$ = x => [...doc.querySelectorAll(x)] + const getPerson = el => { + const nick = getElementText(el.querySelector('nickname')) + if (nick) return nick + const first = getElementText(el.querySelector('first-name')) + const middle = getElementText(el.querySelector('middle-name')) + const last = getElementText(el.querySelector('last-name')) + const name = [first, middle, last].filter(x => x).join(' ') + const sortAs = last + ? [last, [first, middle].filter(x => x).join(' ')].join(', ') + : null + return { name, sortAs } + } + const getDate = el => el?.getAttribute('value') ?? getElementText(el) + const annotation = $('title-info annotation') + book.metadata = { + title: getElementText($('title-info book-title')), + identifier: getElementText($('document-info id')), + language: getElementText($('title-info lang')), + author: $$('title-info author').map(getPerson), + translator: $$('title-info translator').map(getPerson), + contributor: $$('document-info author').map(getPerson) + // techincially the program probably shouldn't get the `bkp` role + // but it has been so used by calibre, so ¯\_(ツ)_/¯ + .concat($$('document-info program-used').map(getElementText)) + .map(x => Object.assign(typeof x === 'string' ? { name: x } : x, + { role: 'bkp' })), + publisher: getElementText($('publish-info publisher')), + published: getDate($('title-info date')), + modified: getDate($('document-info date')), + description: annotation ? converter.convert(annotation, + { annotation: ['div', SECTION] }).innerHTML : null, + subject: $$('title-info genre').map(getElementText), + } + if ($('coverpage image')) { + const src = converter.getImageSrc($('coverpage image')) + book.getCover = () => fetch(src).then(res => res.blob()) + } else book.getCover = () => null + + // get convert each body + const bodyData = Array.from(doc.querySelectorAll('body'), body => { + const converted = converter.convert(body, { body: ['body', BODY] }) + return [Array.from(converted.children, el => { + // get list of IDs in the section + const ids = [el, ...el.querySelectorAll('[id]')].map(el => el.id) + return { el, ids } + }), converted] + }) + + const urls = [] + const sectionData = bodyData[0][0] + // make a separate section for each section in the first body + .map(({ el, ids }, id) => { + // set up titles for TOC + const titles = Array.from( + el.querySelectorAll(':scope > section > .title'), + (el, index) => { + el.setAttribute(dataID, index) + const section = el.closest('section') + const size = new TextEncoder().encode(section.innerHTML).length + - Array.from(section.querySelectorAll('[src]')) + .reduce((sum, el) => sum + (el.getAttribute('src')?.length ?? 0), 0) + return { title: getElementText(el), index, size, href: `${id}#${index}` } + }) + return { ids, titles, el } + }) + // for additional bodies, only make one section for each body + .concat(bodyData.slice(1).map(([sections, body]) => { + const ids = sections.map(s => s.ids).flat() + body.classList.add('notesBodyType') + return { ids, el: body, linear: 'no' } + })) + .map(({ ids, titles, el, linear }) => { + const str = template(el.outerHTML) + const blob = new Blob([str], { type: MIME.XHTML }) + const url = URL.createObjectURL(blob) + urls.push(url) + const title = normalizeWhitespace( + el.querySelector('.title, .subtitle, p')?.textContent + ?? (el.classList.contains('title') ? el.textContent : '')) + return { + ids, title, titles, load: () => url, + createDocument: () => new DOMParser().parseFromString(str, MIME.XHTML), + // doo't count image data as it'd skew the size too much + size: blob.size - Array.from(el.querySelectorAll('[src]'), + el => el.getAttribute('src')?.length ?? 0) + .reduce((a, b) => a + b, 0), + linear, + } + }) + + const idMap = new Map() + book.sections = sectionData.map((section, index) => { + const { ids, load, createDocument, size, linear, titles } = section + for (const id of ids) if (id) idMap.set(id, index) + return { id: index, load, createDocument, size, linear, subitems: titles } + }) + + book.toc = sectionData.map(({ title, titles }, index) => { + const id = index.toString() + return { + label: title, + href: id, + subitems: titles?.length ? titles.map(({ title, index }) => ({ + label: title, + href: `${id}#${index}`, + })) : null, + } + }).filter(item => item) + + book.resolveHref = href => { + const [a, b] = href.split('#') + return a + // the link is from the TOC + ? { index: Number(a), anchor: doc => doc.querySelector(`[${dataID}="${b}"]`) } + // link from within the page + : { index: idMap.get(b), anchor: doc => doc.getElementById(b) } + } + book.splitTOCHref = href => href?.split('#')?.map(x => Number(x)) ?? [] + book.getTOCFragment = (doc, id) => doc.querySelector(`[${dataID}="${id}"]`) + + book.destroy = () => { + for (const url of urls) URL.revokeObjectURL(url) + } + return book +} diff --git a/packages/foliate-js/fixed-layout.js b/packages/foliate-js/fixed-layout.js new file mode 100644 index 0000000000000000000000000000000000000000..48519fe595209feb6bef17f7041d1052bba248df --- /dev/null +++ b/packages/foliate-js/fixed-layout.js @@ -0,0 +1,618 @@ +import 'construct-style-sheets-polyfill' + +const parseViewport = str => str + ?.split(/[,;\s]/) // NOTE: technically, only the comma is valid + ?.filter(x => x) + ?.map(x => x.split('=').map(x => x.trim())) + +const getViewport = (doc, viewport) => { + // use `viewBox` for SVG + if (doc.documentElement.localName === 'svg') { + const [, , width, height] = doc.documentElement + .getAttribute('viewBox')?.split(/\s/) ?? [] + return { width, height } + } + + // get `viewport` `meta` element + const meta = parseViewport(doc.querySelector('meta[name="viewport"]') + ?.getAttribute('content')) + if (meta) return Object.fromEntries(meta) + + // fallback to book's viewport + if (typeof viewport === 'string') return parseViewport(viewport) + if (viewport?.width && viewport.height) return viewport + + // if no viewport (possibly with image directly in spine), get image size + const img = doc.querySelector('img') + if (img) return { width: img.naturalWidth, height: img.naturalHeight } + + // just show *something*, i guess... + console.warn(new Error('Missing viewport properties')) + return { width: 1000, height: 2000 } +} + +export class FixedLayout extends HTMLElement { + static observedAttributes = ['zoom', 'scale-factor', 'spread'] + #root = this.attachShadow({ mode: 'open' }) + #observer = new ResizeObserver(() => this.#render()) + #spreads + #index = -1 + defaultViewport + spread + #portrait = false + #left + #right + #center + #side + #zoom + #scaleFactor = 1.0 + #totalScaleFactor = 1.0 + #scrollLocked = false + #isOverflowX = false + #isOverflowY = false + #preloadCache = new Map() + #prerenderedSpreads = new Map() + #spreadAccessTime = new Map() + #maxConcurrentPreloads = 1 + #numPrerenderedSpreads = 1 + #maxCachedSpreads = 2 + #preloadQueue = [] + #activePreloads = 0 + constructor() { + super() + + const sheet = new CSSStyleSheet() + this.#root.adoptedStyleSheets = [sheet] + sheet.replaceSync(`:host { + width: 100%; + height: 100%; + display: flex; + justify-content: flex-start; + align-items: center; + overflow: auto; + } + @supports (justify-content: safe center) { + :host { + justify-content: safe center; + } + }`) + + this.#observer.observe(this) + } + attributeChangedCallback(name, _, value) { + switch (name) { + case 'zoom': + this.#zoom = value !== 'fit-width' && value !== 'fit-page' + ? parseFloat(value) : value + this.#render() + break + case 'scale-factor': + this.#scaleFactor = parseFloat(value) / 100 + this.#render() + break + case 'spread': + this.#respread(value) + break + } + } + async #createFrame({ index, src: srcOption, detached = false }) { + const srcOptionIsString = typeof srcOption === 'string' + const src = srcOptionIsString ? srcOption : srcOption?.src + const data = srcOptionIsString ? null : srcOption?.data + const onZoom = srcOptionIsString ? null : srcOption?.onZoom + const element = document.createElement('div') + element.setAttribute('dir', 'ltr') + const iframe = document.createElement('iframe') + element.append(iframe) + Object.assign(iframe.style, { + border: '0', + display: 'none', + overflow: 'hidden', + }) + // `allow-scripts` is needed for events because of WebKit bug + // https://bugs.webkit.org/show_bug.cgi?id=218086 + iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts') + iframe.setAttribute('scrolling', 'no') + iframe.setAttribute('part', 'filter') + this.#root.append(element) + + if (detached) { + Object.assign(element.style, { + position: 'absolute', + visibility: 'hidden', + pointerEvents: 'none', + }) + } + + if (!src) return { blank: true, element, iframe } + return new Promise(resolve => { + iframe.addEventListener('load', () => { + const doc = iframe.contentDocument + this.dispatchEvent(new CustomEvent('load', { detail: { doc, index } })) + const { width, height } = getViewport(doc, this.defaultViewport) + resolve({ + element, iframe, + width: parseFloat(width), + height: parseFloat(height), + onZoom, + detached, + }) + }, { once: true }) + if (data) { + iframe.srcdoc = data + } else { + iframe.src = src + } + }) + } + #render(side = this.#side) { + if (!side) return + const left = this.#left ?? {} + const right = this.#center ?? this.#right ?? {} + const target = side === 'left' ? left : right + const { width, height } = this.getBoundingClientRect() + // for unfolded devices with slightly taller height than width also use landscape layout + const portrait = this.spread !== 'both' && this.spread !== 'portrait' + && height > width * 1.2 + this.#portrait = portrait + const blankWidth = left.width ?? right.width ?? 0 + const blankHeight = left.height ?? right.height ?? 0 + + let scale = typeof this.#zoom === 'number' && !isNaN(this.#zoom) + ? this.#zoom + : (this.#zoom === 'fit-width' + ? (portrait || this.#center + ? width / (target.width ?? blankWidth) + : width / ((left.width ?? blankWidth) + (right.width ?? blankWidth))) + : (portrait || this.#center + ? Math.min( + width / (target.width ?? blankWidth), + height / (target.height ?? blankHeight)) + : Math.min( + width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)), + height / Math.max( + left.height ?? blankHeight, + right.height ?? blankHeight))) + ) || 1 + + scale *= this.#scaleFactor + this.#totalScaleFactor = scale + + const transform = ({frame, styles}) => { + let { element, iframe, width, height, blank, onZoom } = frame + if (!iframe) return + if (onZoom) onZoom({ doc: frame.iframe.contentDocument, scale }) + const iframeScale = onZoom ? scale : 1 + const zoomedOut = this.#scaleFactor < 1.0 + Object.assign(iframe.style, { + width: `${width * iframeScale}px`, + height: `${height * iframeScale}px`, + transform: onZoom ? 'none' : `scale(${scale})`, + transformOrigin: 'top left', + display: blank ? 'none' : 'block', + }) + Object.assign(element.style, { + width: `${(width ?? blankWidth) * scale}px`, + height: `${(height ?? blankHeight) * scale}px`, + flexShrink: '0', + display: zoomedOut ? 'flex' : 'block', + marginBlock: zoomedOut ? undefined : 'auto', + alignItems: zoomedOut ? 'center' : undefined, + justifyContent: zoomedOut ? 'center' : undefined, + ...styles, + }) + if (portrait && frame !== target) { + element.style.display = 'none' + } + + const container= element.parentNode.host + const containerWidth = container.clientWidth + const containerHeight = container.clientHeight + container.scrollLeft = (element.clientWidth - containerWidth) / 2 + + return { + width: element.clientWidth, + height: element.clientHeight, + containerWidth, + containerHeight, + } + } + if (this.#center) { + const dimensions = transform({frame: this.#center, styles: { marginInline: 'auto' }}) + const {width, height, containerWidth, containerHeight} = dimensions + this.#isOverflowX = width > containerWidth + this.#isOverflowY = height > containerHeight + } else { + const leftDimensions = transform({frame: left, styles: { marginInlineStart: 'auto' }}) + const rightDimensions = transform({frame: right, styles: { marginInlineEnd: 'auto' }}) + const {width: leftWidth, height: leftHeight, containerWidth, containerHeight} = leftDimensions + const {width: rightWidth, height: rightHeight} = rightDimensions + this.#isOverflowX = leftWidth + rightWidth > containerWidth + this.#isOverflowY = Math.max(leftHeight, rightHeight) > containerHeight + } + } + async #showSpread({ left, right, center, side, spreadIndex }) { + this.#left = null + this.#right = null + this.#center = null + + const cacheKey = spreadIndex !== undefined ? `spread-${spreadIndex}` : null + const prerendered = cacheKey ? this.#prerenderedSpreads.get(cacheKey) : null + + if (prerendered) { + this.#spreadAccessTime.set(cacheKey, Date.now()) + if (prerendered.center) { + this.#center = prerendered.center + } else { + this.#left = prerendered.left + this.#right = prerendered.right + } + } else { + if (center) { + this.#center = await this.#createFrame(center) + if (cacheKey) { + this.#prerenderedSpreads.set(cacheKey, { center: this.#center }) + this.#spreadAccessTime.set(cacheKey, Date.now()) + } + } else { + this.#left = await this.#createFrame(left) + this.#right = await this.#createFrame(right) + if (cacheKey) { + this.#prerenderedSpreads.set(cacheKey, { left: this.#left, right: this.#right }) + this.#spreadAccessTime.set(cacheKey, Date.now()) + } + } + } + + this.#side = center ? 'center' : this.#left.blank ? 'right' + : this.#right.blank ? 'left' : side + const visibleFrames = center + ? [this.#center?.element] + : [this.#left?.element, this.#right?.element] + + Array.from(this.#root.children).forEach(child => { + const isVisible = visibleFrames.includes(child) + Object.assign(child.style, { + position: isVisible ? 'relative' : 'absolute', + visibility: isVisible ? 'visible' : 'hidden', + pointerEvents: isVisible ? 'auto' : 'none', + }) + }) + this.#render() + } + #goLeft() { + if (this.#center || this.#left?.blank) return + if (this.#portrait && this.#left?.element?.style?.display === 'none') { + this.#side = 'left' + this.#render() + this.#reportLocation('page') + return true + } + } + #goRight() { + if (this.#center || this.#right?.blank) return + if (this.#portrait && this.#right?.element?.style?.display === 'none') { + this.#side = 'right' + this.#render() + this.#reportLocation('page') + return true + } + } + open(book) { + this.book = book + this.defaultViewport = book.rendition?.viewport + this.rtl = book.dir === 'rtl' + + this.#spread() + } + #spread(mode) { + const book = this.book + const { rendition } = book + const rtl = this.rtl + const ltr = !rtl + this.spread = mode || rendition?.spread + + if (this.spread === 'none') + this.#spreads = book.sections.map(section => ({ center: section })) + else this.#spreads = book.sections.reduce((arr, section, i) => { + const last = arr[arr.length - 1] + const { pageSpread } = section + const newSpread = () => { + const spread = {} + arr.push(spread) + return spread + } + if (pageSpread === 'center') { + const spread = last.left || last.right ? newSpread() : last + spread.center = section + } + else if (pageSpread === 'left') { + const spread = last.center || last.left || ltr && i ? newSpread() : last + spread.left = section + } + else if (pageSpread === 'right') { + const spread = last.center || last.right || rtl && i ? newSpread() : last + spread.right = section + } + else if (ltr) { + if (last.center || last.right) newSpread().left = section + else if (last.left || !i) last.right = section + else last.left = section + } + else { + if (last.center || last.left) newSpread().right = section + else if (last.right || !i) last.left = section + else last.right = section + } + return arr + }, [{}]) + } + #respread(spreadMode) { + if (this.#index === -1) return + const section = this.book.sections[this.index] + this.#spread(spreadMode) + const { index } = this.getSpreadOf(section) + this.#index = -1 + this.#preloadCache.clear() + for (const frames of this.#prerenderedSpreads.values()) { + if (frames.center) { + frames.center.element?.remove() + } else { + frames.left?.element?.remove() + frames.right?.element?.remove() + } + } + this.#prerenderedSpreads.clear() + this.#spreadAccessTime.clear() + this.goToSpread(index, this.rtl ? 'right' : 'left', 'page') + } + get index() { + const spread = this.#spreads[this.#index] + const section = spread?.center ?? (this.#side === 'left' + ? spread.left ?? spread.right : spread.right ?? spread.left) + return this.book.sections.indexOf(section) + } + get scrollLocked() { + return this.#scrollLocked + } + set scrollLocked(value) { + this.#scrollLocked = value + } + get isOverflowX() { + return this.#isOverflowX + } + get isOverflowY() { + return this.#isOverflowY + } + #reportLocation(reason) { + this.dispatchEvent(new CustomEvent('relocate', { detail: + { reason, range: null, index: this.index, fraction: 0, size: 1 } })) + } + getSpreadOf(section) { + const spreads = this.#spreads + for (let index = 0; index < spreads.length; index++) { + const { left, right, center } = spreads[index] + if (left === section) return { index, side: 'left' } + if (right === section) return { index, side: 'right' } + if (center === section) return { index, side: 'center' } + } + } + async goToSpread(index, side, reason) { + if (index < 0 || index > this.#spreads.length - 1) return + if (index === this.#index) { + this.#render(side) + return + } + this.#index = index + const spread = this.#spreads[index] + const cacheKey = `spread-${index}` + const cached = this.#preloadCache.get(cacheKey) + if (cached && cached !== 'loading') { + if (cached.center) { + const sectionIndex = this.book.sections.indexOf(spread.center) + await this.#showSpread({ center: { index: sectionIndex, src: cached.center }, spreadIndex: index, side }) + } else { + const indexL = this.book.sections.indexOf(spread.left) + const indexR = this.book.sections.indexOf(spread.right) + const left = { index: indexL, src: cached.left } + const right = { index: indexR, src: cached.right } + await this.#showSpread({ left, right, side, spreadIndex: index }) + } + } else { + if (spread.center) { + const sectionIndex = this.book.sections.indexOf(spread.center) + const src = await spread.center?.load?.() + await this.#showSpread({ center: { index: sectionIndex, src }, spreadIndex: index, side }) + } else { + const indexL = this.book.sections.indexOf(spread.left) + const indexR = this.book.sections.indexOf(spread.right) + const srcL = await spread.left?.load?.() + const srcR = await spread.right?.load?.() + const left = { index: indexL, src: srcL } + const right = { index: indexR, src: srcR } + await this.#showSpread({ left, right, side, spreadIndex: index }) + } + } + + this.#reportLocation(reason) + this.#preloadNextSpreads() + } + #preloadNextSpreads() { + this.#cleanupPreloadCache() + + if (this.#numPrerenderedSpreads <= 0) return + + const toPreload = [] + const forwardPreloadCount = Math.max(1, this.#numPrerenderedSpreads - 1) + const backwardPreloadCount = Math.max(0, this.#numPrerenderedSpreads - forwardPreloadCount) + for (let distance = 1; distance <= forwardPreloadCount; distance++) { + const forwardIndex = this.#index + distance + if (forwardIndex >= 0 && forwardIndex < this.#spreads.length) { + toPreload.push({ index: forwardIndex, direction: 'forward', distance }) + } + } + for (let distance = 1; distance <= backwardPreloadCount; distance++) { + const backwardIndex = this.#index - distance + if (backwardIndex >= 0 && backwardIndex < this.#spreads.length) { + toPreload.push({ index: backwardIndex, direction: 'backward', distance }) + } + } + for (const { index: targetIndex, direction } of toPreload) { + const cacheKey = `spread-${targetIndex}` + if (this.#prerenderedSpreads.has(cacheKey)) continue + const spread = this.#spreads[targetIndex] + if (!spread) continue + this.#preloadQueue.push({ targetIndex, direction, spread, cacheKey }) + } + + this.#processPreloadQueue() + } + + async #processPreloadQueue() { + while (this.#preloadQueue.length > 0 && this.#activePreloads < this.#maxConcurrentPreloads) { + const task = this.#preloadQueue.shift() + if (!task) break + + const { spread, cacheKey } = task + this.#preloadCache.set(cacheKey, 'loading') + this.#activePreloads++ + Promise.resolve().then(async () => { + try { + if (spread.center) { + const src = await spread.center?.load?.() + this.#preloadCache.set(cacheKey, { center: src }) + + const sectionIndex = this.book.sections.indexOf(spread.center) + const frame = await this.#createFrame({ index: sectionIndex, src, detached: true }) + + this.#prerenderedSpreads.set(cacheKey, { center: frame }) + this.#spreadAccessTime.set(cacheKey, Date.now()) + if (frame.onZoom) { + const doc = frame.iframe.contentDocument + frame.onZoom({ doc, scale: this.#totalScaleFactor }) + } + } else { + const srcL = await spread.left?.load?.() + const srcR = await spread.right?.load?.() + this.#preloadCache.set(cacheKey, { left: srcL, right: srcR }) + + const indexL = this.book.sections.indexOf(spread.left) + const indexR = this.book.sections.indexOf(spread.right) + const leftFrame = await this.#createFrame({ index: indexL, src: srcL, detached: true }) + const rightFrame = await this.#createFrame({ index: indexR, src: srcR, detached: true }) + + this.#prerenderedSpreads.set(cacheKey, { left: leftFrame, right: rightFrame }) + this.#spreadAccessTime.set(cacheKey, Date.now()) + + if (leftFrame.onZoom) { + const docL = leftFrame.iframe.contentDocument + leftFrame.onZoom({ doc: docL, scale: this.#totalScaleFactor }) + } + if (rightFrame.onZoom) { + const docR = rightFrame.iframe.contentDocument + rightFrame.onZoom({ doc: docR, scale: this.#totalScaleFactor }) + } + } + } catch { + this.#preloadCache.delete(cacheKey) + this.#prerenderedSpreads.delete(cacheKey) + } finally { + this.#activePreloads-- + this.#processPreloadQueue() + } + }) + } + } + #cleanupPreloadCache() { + const maxSpreads = this.#maxCachedSpreads + if (this.#prerenderedSpreads.size <= maxSpreads) { + return + } + + const framesByAge = Array.from(this.#prerenderedSpreads.keys()) + .map(key => ({ + key, + accessTime: this.#spreadAccessTime.get(key) || 0, + })) + .sort((a, b) => a.accessTime - b.accessTime) + + const numToRemove = this.#prerenderedSpreads.size - maxSpreads + const framesToDelete = framesByAge.slice(0, numToRemove).map(item => item.key) + + if (framesToDelete.length > 0) { + framesToDelete.forEach(key => { + const frames = this.#prerenderedSpreads.get(key) + if (frames) { + if (frames.center) { + frames.center.element?.remove() + } else { + frames.left?.element?.remove() + frames.right?.element?.remove() + } + } + + this.#prerenderedSpreads.delete(key) + this.#spreadAccessTime.delete(key) + this.#preloadCache.delete(key) + }) + } + } + async select(target) { + await this.goTo(target) + // TODO + } + async goTo(target) { + const { book } = this + const resolved = await target + const section = book.sections[resolved.index] + if (!section) return + const { index, side } = this.getSpreadOf(section) + await this.goToSpread(index, side) + } + async next() { + const s = this.rtl ? this.#goLeft() : this.#goRight() + if (!s) return this.goToSpread(this.#index + 1, this.rtl ? 'right' : 'left', 'page') + } + async prev() { + const s = this.rtl ? this.#goRight() : this.#goLeft() + if (!s) return this.goToSpread(this.#index - 1, this.rtl ? 'left' : 'right', 'page') + } + async pan(dx, dy) { + if (this.#scrollLocked) return + this.#scrollLocked = true + + const transform = frame => { + let { element, iframe } = frame + if (!iframe || !element) return + + const scrollableContainer = element.parentNode.host + scrollableContainer.scrollLeft += dx + scrollableContainer.scrollTop += dy + } + + transform(this.#center ?? this.#right ?? {}) + this.#scrollLocked = false + } + getContents() { + return Array.from(this.#root.querySelectorAll('iframe'), frame => ({ + doc: frame.contentDocument, + // TODO: index, overlayer + })) + } + destroy() { + this.#observer.unobserve(this) + for (const frames of this.#prerenderedSpreads.values()) { + if (frames.center) { + frames.center.element?.remove() + } else { + frames.left?.element?.remove() + frames.right?.element?.remove() + } + } + this.#prerenderedSpreads.clear() + this.#preloadCache.clear() + this.#spreadAccessTime.clear() + } +} + +customElements.define('foliate-fxl', FixedLayout) diff --git a/packages/foliate-js/footnotes.js b/packages/foliate-js/footnotes.js new file mode 100644 index 0000000000000000000000000000000000000000..a7bc11bc8dce051a9cc6fb3ee5f00619ca6d6b4b --- /dev/null +++ b/packages/foliate-js/footnotes.js @@ -0,0 +1,145 @@ +const getTypes = el => new Set([ + ...(el?.getAttributeNS?.('http://www.idpf.org/2007/ops', 'type')?.split(' ') ?? []), + ...(el?.attributes?.getNamedItem?.('epub:type')?.value?.split(' ') ?? []), +]) +const getRoles = el => new Set(el?.getAttribute?.('role')?.split(' ')) + +const isSuper = el => { + if (el.matches('sup')) return true + const { verticalAlign } = getComputedStyle(el) + return verticalAlign === 'super' + || verticalAlign === 'top' + || verticalAlign === 'text-top' + || /^\d/.test(verticalAlign) +} + +const refTypes = ['biblioref', 'glossref', 'noteref'] +const refRoles = ['doc-biblioref', 'doc-glossref', 'doc-noteref'] +const isFootnoteReference = a => { + const types = getTypes(a) + const roles = getRoles(a) + return { + yes: refRoles.some(r => roles.has(r)) || refTypes.some(t => types.has(t)), + maybe: () => !types.has('backlink') && !roles.has('doc-backlink') + && (isSuper(a) || a.children.length === 1 && isSuper(a.children[0]) + || isSuper(a.parentElement)), + } +} + +const getReferencedType = el => { + const types = getTypes(el) + const roles = getRoles(el) + return roles.has('doc-biblioentry') || types.has('biblioentry') ? 'biblioentry' + : roles.has('definition') || types.has('glossdef') ? 'definition' + : roles.has('doc-endnote') || types.has('endnote') || types.has('rearnote') ? 'endnote' + : roles.has('doc-footnote') || types.has('footnote') ? 'footnote' + : roles.has('note') || types.has('note') ? 'note' : null +} + +const isInline = 'a, span, sup, sub, em, strong, i, b, small, big' +const extractFootnote = (doc, anchor) => { + let el = anchor(doc) + const target = el + while (el.matches(isInline)) { + const parent = el.parentElement + if (!parent) break + el = parent + } + if (el === doc.body) { + const sibling = target.nextElementSibling + if (sibling && !sibling.matches(isInline)) return sibling + throw new Error('Failed to extract footnote') + } + return el +} + +export class FootnoteHandler extends EventTarget { + detectFootnotes = true + #showFragment(book, { index, anchor }, href) { + const view = document.createElement('foliate-view') + return new Promise((resolve, reject) => { + view.addEventListener('load', e => { + try { + const { doc } = e.detail + const el = anchor(doc) + const type = getReferencedType(el) + const hidden = el?.matches?.('aside') && type === 'footnote' + if (el) { + let range + if (el.startContainer) { + range = el + } else if (el.matches('li, aside')) { + range = doc.createRange() + range.selectNodeContents(el) + } else if (el.matches('dt')) { + range = doc.createRange() + range.setStartBefore(el) + let sibling = el.nextElementSibling + let lastDD = null + while (sibling && sibling.matches('dd')) { + lastDD = sibling + sibling = sibling.nextElementSibling + } + range.setEndAfter(lastDD || el) + } else if (el.closest('li')) { + range = doc.createRange() + range.selectNodeContents(el.closest('li')) + } else if (el.closest('.note')) { + range = doc.createRange() + range.selectNodeContents(el.closest('.note')) + } else if (el.querySelector('a')) { + range = doc.createRange() + range.setStartBefore(el) + let next = el.nextElementSibling + while (next) { + if (next.querySelector('a')) break + next = next.nextElementSibling + } + if (next) { + range.setEndBefore(next) + } else { + range.setEndAfter(el.parentNode.lastChild) + } + } else { + range = doc.createRange() + const hasContent = el.textContent?.trim() || el.children.length > 0 + if (!hasContent && el.parentElement) { + range.selectNodeContents(el.parentElement) + } else { + range.selectNode(el) + } + } + const frag = range.extractContents() + doc.body.replaceChildren() + doc.body.appendChild(frag) + } + const detail = { view, href, type, hidden, target: el } + this.dispatchEvent(new CustomEvent('render', { detail })) + resolve() + } catch (e) { + reject(e) + } + }) + view.open(book) + .then(() => this.dispatchEvent(new CustomEvent('before-render', { detail: { view } }))) + .then(() => view.goTo(index)) + .catch(reject) + }) + } + handle(book, e) { + const { a, href, follow } = e.detail + const { yes, maybe } = isFootnoteReference(a) + if (yes || follow) { + e.preventDefault() + return Promise.resolve(book.resolveHref(href)).then(target => + this.#showFragment(book, target, href)) + } + else if (this.detectFootnotes && maybe()) { + e.preventDefault() + return Promise.resolve(book.resolveHref(href)).then(({ index, anchor }) => { + const target = { index, anchor: doc => extractFootnote(doc, anchor) } + return this.#showFragment(book, target, href) + }) + } + } +} diff --git a/packages/foliate-js/mobi.js b/packages/foliate-js/mobi.js new file mode 100644 index 0000000000000000000000000000000000000000..811b0d3cd26687c2696aea6a53df96d5d8f8fb77 --- /dev/null +++ b/packages/foliate-js/mobi.js @@ -0,0 +1,1236 @@ +const unescapeHTML = str => { + if (!str) return '' + const textarea = document.createElement('textarea') + textarea.innerHTML = str + return textarea.value +} + +const MIME = { + XML: 'application/xml', + XHTML: 'application/xhtml+xml', + HTML: 'text/html', + CSS: 'text/css', + SVG: 'image/svg+xml', +} + +const PDB_HEADER = { + name: [0, 32, 'string'], + type: [60, 4, 'string'], + creator: [64, 4, 'string'], + numRecords: [76, 2, 'uint'], +} + +const PALMDOC_HEADER = { + compression: [0, 2, 'uint'], + numTextRecords: [8, 2, 'uint'], + recordSize: [10, 2, 'uint'], + encryption: [12, 2, 'uint'], +} + +const MOBI_HEADER = { + magic: [16, 4, 'string'], + length: [20, 4, 'uint'], + type: [24, 4, 'uint'], + encoding: [28, 4, 'uint'], + uid: [32, 4, 'uint'], + version: [36, 4, 'uint'], + titleOffset: [84, 4, 'uint'], + titleLength: [88, 4, 'uint'], + localeRegion: [94, 1, 'uint'], + localeLanguage: [95, 1, 'uint'], + resourceStart: [108, 4, 'uint'], + huffcdic: [112, 4, 'uint'], + numHuffcdic: [116, 4, 'uint'], + exthFlag: [128, 4, 'uint'], + trailingFlags: [240, 4, 'uint'], + indx: [244, 4, 'uint'], +} + +const KF8_HEADER = { + resourceStart: [108, 4, 'uint'], + fdst: [192, 4, 'uint'], + numFdst: [196, 4, 'uint'], + frag: [248, 4, 'uint'], + skel: [252, 4, 'uint'], + guide: [260, 4, 'uint'], +} + +const EXTH_HEADER = { + magic: [0, 4, 'string'], + length: [4, 4, 'uint'], + count: [8, 4, 'uint'], +} + +const INDX_HEADER = { + magic: [0, 4, 'string'], + length: [4, 4, 'uint'], + type: [8, 4, 'uint'], + idxt: [20, 4, 'uint'], + numRecords: [24, 4, 'uint'], + encoding: [28, 4, 'uint'], + language: [32, 4, 'uint'], + total: [36, 4, 'uint'], + ordt: [40, 4, 'uint'], + ligt: [44, 4, 'uint'], + numLigt: [48, 4, 'uint'], + numCncx: [52, 4, 'uint'], +} + +const TAGX_HEADER = { + magic: [0, 4, 'string'], + length: [4, 4, 'uint'], + numControlBytes: [8, 4, 'uint'], +} + +const HUFF_HEADER = { + magic: [0, 4, 'string'], + offset1: [8, 4, 'uint'], + offset2: [12, 4, 'uint'], +} + +const CDIC_HEADER = { + magic: [0, 4, 'string'], + length: [4, 4, 'uint'], + numEntries: [8, 4, 'uint'], + codeLength: [12, 4, 'uint'], +} + +const FDST_HEADER = { + magic: [0, 4, 'string'], + numEntries: [8, 4, 'uint'], +} + +const FONT_HEADER = { + flags: [8, 4, 'uint'], + dataStart: [12, 4, 'uint'], + keyLength: [16, 4, 'uint'], + keyStart: [20, 4, 'uint'], +} + +const MOBI_ENCODING = { + 1252: 'windows-1252', + 65001: 'utf-8', +} + +const EXTH_RECORD_TYPE = { + 100: ['creator', 'string', true], + 101: ['publisher'], + 103: ['description'], + 104: ['isbn'], + 105: ['subject', 'string', true], + 106: ['date'], + 108: ['contributor', 'string', true], + 109: ['rights'], + 110: ['subjectCode', 'string', true], + 112: ['source', 'string', true], + 113: ['asin'], + 121: ['boundary', 'uint'], + 122: ['fixedLayout'], + 125: ['numResources', 'uint'], + 126: ['originalResolution'], + 127: ['zeroGutter'], + 128: ['zeroMargin'], + 129: ['coverURI'], + 132: ['regionMagnification'], + 201: ['coverOffset', 'uint'], + 202: ['thumbnailOffset', 'uint'], + 503: ['title'], + 524: ['language', 'string', true], + 527: ['pageProgressionDirection'], +} + +const MOBI_LANG = { + 1: ['ar', 'ar-SA', 'ar-IQ', 'ar-EG', 'ar-LY', 'ar-DZ', 'ar-MA', 'ar-TN', 'ar-OM', + 'ar-YE', 'ar-SY', 'ar-JO', 'ar-LB', 'ar-KW', 'ar-AE', 'ar-BH', 'ar-QA'], + 2: ['bg'], 3: ['ca'], 4: ['zh', 'zh-TW', 'zh-CN', 'zh-HK', 'zh-SG'], 5: ['cs'], + 6: ['da'], 7: ['de', 'de-DE', 'de-CH', 'de-AT', 'de-LU', 'de-LI'], 8: ['el'], + 9: ['en', 'en-US', 'en-GB', 'en-AU', 'en-CA', 'en-NZ', 'en-IE', 'en-ZA', + 'en-JM', null, 'en-BZ', 'en-TT', 'en-ZW', 'en-PH'], + 10: ['es', 'es-ES', 'es-MX', null, 'es-GT', 'es-CR', 'es-PA', 'es-DO', + 'es-VE', 'es-CO', 'es-PE', 'es-AR', 'es-EC', 'es-CL', 'es-UY', 'es-PY', + 'es-BO', 'es-SV', 'es-HN', 'es-NI', 'es-PR'], + 11: ['fi'], 12: ['fr', 'fr-FR', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-LU', 'fr-MC'], + 13: ['he'], 14: ['hu'], 15: ['is'], 16: ['it', 'it-IT', 'it-CH'], + 17: ['ja'], 18: ['ko'], 19: ['nl', 'nl-NL', 'nl-BE'], 20: ['no', 'nb', 'nn'], + 21: ['pl'], 22: ['pt', 'pt-BR', 'pt-PT'], 23: ['rm'], 24: ['ro'], 25: ['ru'], + 26: ['hr', null, 'sr'], 27: ['sk'], 28: ['sq'], 29: ['sv', 'sv-SE', 'sv-FI'], + 30: ['th'], 31: ['tr'], 32: ['ur'], 33: ['id'], 34: ['uk'], 35: ['be'], + 36: ['sl'], 37: ['et'], 38: ['lv'], 39: ['lt'], 41: ['fa'], 42: ['vi'], + 43: ['hy'], 44: ['az'], 45: ['eu'], 46: ['hsb'], 47: ['mk'], 48: ['st'], + 49: ['ts'], 50: ['tn'], 52: ['xh'], 53: ['zu'], 54: ['af'], 55: ['ka'], + 56: ['fo'], 57: ['hi'], 58: ['mt'], 59: ['se'], 62: ['ms'], 63: ['kk'], + 65: ['sw'], 67: ['uz', null, 'uz-UZ'], 68: ['tt'], 69: ['bn'], 70: ['pa'], + 71: ['gu'], 72: ['or'], 73: ['ta'], 74: ['te'], 75: ['kn'], 76: ['ml'], + 77: ['as'], 78: ['mr'], 79: ['sa'], 82: ['cy', 'cy-GB'], 83: ['gl', 'gl-ES'], + 87: ['kok'], 97: ['ne'], 98: ['fy'], +} + +const concatTypedArray = (a, b) => { + const result = new a.constructor(a.length + b.length) + result.set(a) + result.set(b, a.length) + return result +} +const concatTypedArray3 = (a, b, c) => { + const result = new a.constructor(a.length + b.length + c.length) + result.set(a) + result.set(b, a.length) + result.set(c, a.length + b.length) + return result +} + +const decoder = new TextDecoder() +const getString = buffer => decoder.decode(buffer) +const getUint = buffer => { + if (!buffer) return + const l = buffer.byteLength + const func = l === 4 ? 'getUint32' : l === 2 ? 'getUint16' : 'getUint8' + return new DataView(buffer)[func](0) +} +const getStruct = (def, buffer) => Object.fromEntries(Array.from(Object.entries(def)) + .map(([key, [start, len, type]]) => [key, + (type === 'string' ? getString : getUint)(buffer.slice(start, start + len))])) + +const getDecoder = x => new TextDecoder(MOBI_ENCODING[x]) + +const getVarLen = (byteArray, i = 0) => { + let value = 0, length = 0 + for (const byte of byteArray.subarray(i, i + 4)) { + value = (value << 7) | (byte & 0b111_1111) >>> 0 + length++ + if (byte & 0b1000_0000) break + } + return { value, length } +} + +// variable-length quantity, but read from the end of data +const getVarLenFromEnd = byteArray => { + let value = 0 + for (const byte of byteArray.subarray(-4)) { + // `byte & 0b1000_0000` indicates the start of value + if (byte & 0b1000_0000) value = 0 + value = (value << 7) | (byte & 0b111_1111) + } + return value +} + +const countBitsSet = x => { + let count = 0 + for (; x > 0; x = x >> 1) if ((x & 1) === 1) count++ + return count +} + +const countUnsetEnd = x => { + let count = 0 + while ((x & 1) === 0) x = x >> 1, count++ + return count +} + +const decompressPalmDOC = array => { + let output = [] + for (let i = 0; i < array.length; i++) { + const byte = array[i] + if (byte === 0) output.push(0) // uncompressed literal, just copy it + else if (byte <= 8) // copy next 1-8 bytes + for (const x of array.subarray(i + 1, (i += byte) + 1)) + output.push(x) + else if (byte <= 0b0111_1111) output.push(byte) // uncompressed literal + else if (byte <= 0b1011_1111) { + // 1st and 2nd bits are 10, meaning this is a length-distance pair + // read next byte and combine it with current byte + const bytes = (byte << 8) | array[i++ + 1] + // the 3rd to 13th bits encode distance + const distance = (bytes & 0b0011_1111_1111_1111) >>> 3 + // the last 3 bits, plus 3, is the length to copy + const length = (bytes & 0b111) + 3 + for (let j = 0; j < length; j++) + output.push(output[output.length - distance]) + } + // compressed from space plus char + else output.push(32, byte ^ 0b1000_0000) + } + return Uint8Array.from(output) +} + +const read32Bits = (byteArray, from) => { + const startByte = from >> 3 + const end = from + 32 + const endByte = end >> 3 + let bits = 0n + for (let i = startByte; i <= endByte; i++) + bits = bits << 8n | BigInt(byteArray[i] ?? 0) + return (bits >> (8n - BigInt(end & 7))) & 0xffffffffn +} + +const huffcdic = async (mobi, loadRecord) => { + const huffRecord = await loadRecord(mobi.huffcdic) + const { magic, offset1, offset2 } = getStruct(HUFF_HEADER, huffRecord) + if (magic !== 'HUFF') throw new Error('Invalid HUFF record') + + // table1 is indexed by byte value + const table1 = Array.from({ length: 256 }, (_, i) => offset1 + i * 4) + .map(offset => getUint(huffRecord.slice(offset, offset + 4))) + .map(x => [x & 0b1000_0000, x & 0b1_1111, x >>> 8]) + + // table2 is indexed by code length + const table2 = [null].concat(Array.from({ length: 32 }, (_, i) => offset2 + i * 8) + .map(offset => [ + getUint(huffRecord.slice(offset, offset + 4)), + getUint(huffRecord.slice(offset + 4, offset + 8))])) + + const dictionary = [] + for (let i = 1; i < mobi.numHuffcdic; i++) { + const record = await loadRecord(mobi.huffcdic + i) + const cdic = getStruct(CDIC_HEADER, record) + if (cdic.magic !== 'CDIC') throw new Error('Invalid CDIC record') + // `numEntries` is the total number of dictionary data across CDIC records + // so `n` here is the number of entries in *this* record + const n = Math.min(1 << cdic.codeLength, cdic.numEntries - dictionary.length) + const buffer = record.slice(cdic.length) + for (let i = 0; i < n; i++) { + const offset = getUint(buffer.slice(i * 2, i * 2 + 2)) + const x = getUint(buffer.slice(offset, offset + 2)) + const length = x & 0x7fff + const decompressed = x & 0x8000 + const value = new Uint8Array( + buffer.slice(offset + 2, offset + 2 + length)) + dictionary.push([value, decompressed]) + } + } + + const decompress = byteArray => { + let output = new Uint8Array() + const bitLength = byteArray.byteLength * 8 + for (let i = 0; i < bitLength;) { + const bits = Number(read32Bits(byteArray, i)) + let [found, codeLength, value] = table1[bits >>> 24] + if (!found) { + while (bits >>> (32 - codeLength) < table2[codeLength][0]) + codeLength += 1 + value = table2[codeLength][1] + } + if ((i += codeLength) > bitLength) break + + const code = value - (bits >>> (32 - codeLength)) + let [result, decompressed] = dictionary[code] + if (!decompressed) { + // the result is itself compressed + result = decompress(result) + // cache the result for next time + dictionary[code] = [result, true] + } + output = concatTypedArray(output, result) + } + return output + } + return decompress +} + +const getIndexData = async (indxIndex, loadRecord) => { + const indxRecord = await loadRecord(indxIndex) + const indx = getStruct(INDX_HEADER, indxRecord) + if (indx.magic !== 'INDX') throw new Error('Invalid INDX record') + const decoder = getDecoder(indx.encoding) + + const tagxBuffer = indxRecord.slice(indx.length) + const tagx = getStruct(TAGX_HEADER, tagxBuffer) + if (tagx.magic !== 'TAGX') throw new Error('Invalid TAGX section') + const numTags = (tagx.length - 12) / 4 + const tagTable = Array.from({ length: numTags }, (_, i) => + new Uint8Array(tagxBuffer.slice(12 + i * 4, 12 + i * 4 + 4))) + + const cncx = {} + let cncxRecordOffset = 0 + for (let i = 0; i < indx.numCncx; i++) { + const record = await loadRecord(indxIndex + indx.numRecords + i + 1) + const array = new Uint8Array(record) + for (let pos = 0; pos < array.byteLength;) { + const index = pos + const { value, length } = getVarLen(array, pos) + pos += length + const result = record.slice(pos, pos + value) + pos += value + cncx[cncxRecordOffset + index] = decoder.decode(result) + } + cncxRecordOffset += 0x10000 + } + + const table = [] + for (let i = 0; i < indx.numRecords; i++) { + const record = await loadRecord(indxIndex + 1 + i) + const array = new Uint8Array(record) + const indx = getStruct(INDX_HEADER, record) + if (indx.magic !== 'INDX') throw new Error('Invalid INDX record') + for (let j = 0; j < indx.numRecords; j++) { + const offsetOffset = indx.idxt + 4 + 2 * j + const offset = getUint(record.slice(offsetOffset, offsetOffset + 2)) + + const length = getUint(record.slice(offset, offset + 1)) + const name = getString(record.slice(offset + 1, offset + 1 + length)) + + const tags = [] + const startPos = offset + 1 + length + let controlByteIndex = 0 + let pos = startPos + tagx.numControlBytes + for (const [tag, numValues, mask, end] of tagTable) { + if (end & 1) { + controlByteIndex++ + continue + } + const offset = startPos + controlByteIndex + const value = getUint(record.slice(offset, offset + 1)) & mask + if (value === mask) { + if (countBitsSet(mask) > 1) { + const { value, length } = getVarLen(array, pos) + tags.push([tag, null, value, numValues]) + pos += length + } else tags.push([tag, 1, null, numValues]) + } else tags.push([tag, value >> countUnsetEnd(mask), null, numValues]) + } + + const tagMap = {} + for (const [tag, valueCount, valueBytes, numValues] of tags) { + const values = [] + if (valueCount != null) { + for (let i = 0; i < valueCount * numValues; i++) { + const { value, length } = getVarLen(array, pos) + values.push(value) + pos += length + } + } else { + let count = 0 + while (count < valueBytes) { + const { value, length } = getVarLen(array, pos) + values.push(value) + pos += length + count += length + } + } + tagMap[tag] = values + } + table.push({ name, tagMap }) + } + } + return { table, cncx } +} + +const getNCX = async (indxIndex, loadRecord) => { + const { table, cncx } = await getIndexData(indxIndex, loadRecord) + const items = table.map(({ tagMap }, index) => ({ + index, + offset: tagMap[1]?.[0], + size: tagMap[2]?.[0], + label: cncx[tagMap[3]] ?? '', + headingLevel: tagMap[4]?.[0], + pos: tagMap[6], + parent: tagMap[21]?.[0], + firstChild: tagMap[22]?.[0], + lastChild: tagMap[23]?.[0], + })) + const getChildren = item => { + if (item.firstChild == null) return item + item.children = items.filter(x => x.parent === item.index).map(getChildren) + return item + } + return items.filter(item => item.headingLevel === 0).map(getChildren) +} + +const getEXTH = (buf, encoding) => { + const { magic, count } = getStruct(EXTH_HEADER, buf) + if (magic !== 'EXTH') throw new Error('Invalid EXTH header') + const decoder = getDecoder(encoding) + const results = {} + let offset = 12 + for (let i = 0; i < count; i++) { + const type = getUint(buf.slice(offset, offset + 4)) + const length = getUint(buf.slice(offset + 4, offset + 8)) + if (type in EXTH_RECORD_TYPE) { + const [name, typ, many] = EXTH_RECORD_TYPE[type] + const data = buf.slice(offset + 8, offset + length) + const value = typ === 'uint' ? getUint(data) : decoder.decode(data) + if (many) { + results[name] ??= [] + results[name].push(value) + } else results[name] = value + } + offset += length + } + return results +} + +const getFont = async (buf, unzlib) => { + const { flags, dataStart, keyLength, keyStart } = getStruct(FONT_HEADER, buf) + const array = new Uint8Array(buf.slice(dataStart)) + // deobfuscate font + if (flags & 0b10) { + const bytes = keyLength === 16 ? 1024 : 1040 + const key = new Uint8Array(buf.slice(keyStart, keyStart + keyLength)) + const length = Math.min(bytes, array.length) + for (var i = 0; i < length; i++) array[i] = array[i] ^ key[i % key.length] + } + // decompress font + if (flags & 1) try { + return await unzlib(array) + } catch (e) { + console.warn(e) + console.warn('Failed to decompress font') + } + return array +} + +export const isMOBI = async file => { + const magic = getString(await file.slice(60, 68).arrayBuffer()) + return magic === 'BOOKMOBI'// || magic === 'TEXtREAd' +} + +class PDB { + #file + #offsets + pdb + async open(file) { + this.#file = file + const pdb = getStruct(PDB_HEADER, await file.slice(0, 78).arrayBuffer()) + this.pdb = pdb + const buffer = await file.slice(78, 78 + pdb.numRecords * 8).arrayBuffer() + // get start and end offsets for each record + this.#offsets = Array.from({ length: pdb.numRecords }, + (_, i) => getUint(buffer.slice(i * 8, i * 8 + 4))) + .map((x, i, a) => [x, a[i + 1]]) + } + loadRecord(index) { + const offsets = this.#offsets[index] + if (!offsets) throw new RangeError('Record index out of bounds') + return this.#file.slice(...offsets).arrayBuffer() + } + async loadMagic(index) { + const start = this.#offsets[index][0] + return getString(await this.#file.slice(start, start + 4).arrayBuffer()) + } +} + +export class MOBI extends PDB { + #start = 0 + #resourceStart + #decoder + #encoder + #decompress + #removeTrailingEntries + constructor({ unzlib }) { + super() + this.unzlib = unzlib + } + async open(file) { + await super.open(file) + // TODO: if (this.pdb.type === 'TEXt') + this.headers = this.#getHeaders(await super.loadRecord(0)) + this.#resourceStart = this.headers.mobi.resourceStart + let isKF8 = this.headers.mobi.version >= 8 + if (!isKF8) { + const boundary = this.headers.exth?.boundary + if (boundary < 0xffffffff) try { + // it's a "combo" MOBI/KF8 file; try to open the KF8 part + this.headers = this.#getHeaders(await super.loadRecord(boundary)) + this.#start = boundary + isKF8 = true + } catch (e) { + console.warn(e) + console.warn('Failed to open KF8; falling back to MOBI') + } + } + await this.#setup() + return isKF8 ? new KF8(this).init() : new MOBI6(this).init() + } + #getHeaders(buf) { + const palmdoc = getStruct(PALMDOC_HEADER, buf) + const mobi = getStruct(MOBI_HEADER, buf) + if (mobi.magic !== 'MOBI') throw new Error('Missing MOBI header') + + const { titleOffset, titleLength, localeLanguage, localeRegion } = mobi + mobi.title = buf.slice(titleOffset, titleOffset + titleLength) + const lang = MOBI_LANG[localeLanguage] + mobi.language = lang?.[localeRegion >> 2] ?? lang?.[0] + + const exth = mobi.exthFlag & 0b100_0000 + ? getEXTH(buf.slice(mobi.length + 16), mobi.encoding) : null + const kf8 = mobi.version >= 8 ? getStruct(KF8_HEADER, buf) : null + return { palmdoc, mobi, exth, kf8 } + } + async #setup() { + const { palmdoc, mobi } = this.headers + this.#decoder = getDecoder(mobi.encoding) + // `TextEncoder` only supports UTF-8 + // we are only encoding ASCII anyway, so I think it's fine + this.#encoder = new TextEncoder() + + // set up decompressor + const { compression } = palmdoc + this.#decompress = compression === 1 ? f => f + : compression === 2 ? decompressPalmDOC + : compression === 17480 ? await huffcdic(mobi, this.loadRecord.bind(this)) + : null + if (!this.#decompress) throw new Error('Unknown compression type') + + // set up function for removing trailing bytes + const { trailingFlags } = mobi + const multibyte = trailingFlags & 1 + const numTrailingEntries = countBitsSet(trailingFlags >>> 1) + this.#removeTrailingEntries = array => { + for (let i = 0; i < numTrailingEntries; i++) { + const length = getVarLenFromEnd(array) + array = array.subarray(0, -length) + } + if (multibyte) { + const length = (array[array.length - 1] & 0b11) + 1 + array = array.subarray(0, -length) + } + return array + } + } + decode(...args) { + return this.#decoder.decode(...args) + } + encode(...args) { + return this.#encoder.encode(...args) + } + loadRecord(index) { + return super.loadRecord(this.#start + index) + } + loadMagic(index) { + return super.loadMagic(this.#start + index) + } + loadText(index) { + return this.loadRecord(index + 1) + .then(buf => new Uint8Array(buf)) + .then(this.#removeTrailingEntries) + .then(this.#decompress) + } + async loadResource(index) { + const buf = await super.loadRecord(this.#resourceStart + index) + const magic = getString(buf.slice(0, 4)) + if (magic === 'FONT') return getFont(buf, this.unzlib) + if (magic === 'VIDE' || magic === 'AUDI') return buf.slice(12) + return buf + } + getNCX() { + const index = this.headers.mobi.indx + if (index < 0xffffffff) return getNCX(index, this.loadRecord.bind(this)) + } + getMetadata() { + const { mobi, exth } = this.headers + return { + identifier: mobi.uid.toString(), + title: unescapeHTML(exth?.title || this.decode(mobi.title)), + author: exth?.creator?.map(unescapeHTML), + publisher: unescapeHTML(exth?.publisher), + language: exth?.language ?? mobi.language, + published: exth?.date, + description: unescapeHTML(exth?.description), + subject: exth?.subject?.map(unescapeHTML), + rights: unescapeHTML(exth?.rights), + contributor: exth?.contributor, + } + } + async getCover() { + const { exth } = this.headers + const offset = exth?.coverOffset < 0xffffffff ? exth?.coverOffset + : exth?.thumbnailOffset < 0xffffffff ? exth?.thumbnailOffset : null + if (offset != null) { + const buf = await this.loadResource(offset) + return new Blob([buf]) + } + } +} + +const mbpPagebreakRegex = /<\s*(?:mbp:)?pagebreak[^>]*>/gi +const fileposRegex = /<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi + +const getIndent = el => { + let x = 0 + while (el) { + const parent = el.parentElement + if (parent) { + const tag = parent.tagName.toLowerCase() + if (tag === 'p') x += 1.5 + else if (tag === 'blockquote') x += 2 + } + el = parent + } + return x +} + +function rawBytesToString(uint8Array) { + const chunkSize = 0x8000 + let result = '' + for (let i = 0; i < uint8Array.length; i += chunkSize) { + result += String.fromCharCode.apply(null, uint8Array.subarray(i, i + chunkSize)) + } + return result +} + +class MOBI6 { + parser = new DOMParser() + serializer = new XMLSerializer() + #resourceCache = new Map() + #textCache = new Map() + #cache = new Map() + #sections + #fileposList = [] + #type = MIME.HTML + constructor(mobi) { + this.mobi = mobi + } + async init() { + const recordBuffers = [] + for (let i = 0; i < this.mobi.headers.palmdoc.numTextRecords; i++) { + const buf = await this.mobi.loadText(i) + recordBuffers.push(buf) + } + const totalLength = recordBuffers.reduce((sum, buf) => sum + buf.byteLength, 0) + // load all text records in an array + const array = new Uint8Array(totalLength) + recordBuffers.reduce((offset, buf) => { + array.set(new Uint8Array(buf), offset) + return offset + buf.byteLength + }, 0) + // convert to string so we can use regex + // note that `filepos` are byte offsets + // so it needs to preserve each byte as a separate character + // (see https://stackoverflow.com/q/50198017) + const str = rawBytesToString(array) + + // split content into sections at each `` + this.#sections = [0] + .concat(Array.from(str.matchAll(mbpPagebreakRegex), m => m.index)) + .map((start, i, a) => { + const end = a[i + 1] ?? array.length + return { book: this, raw: array.subarray(start, end) } + }) + // get start and end filepos for each section + .map((section, i, arr) => { + section.start = arr[i - 1]?.end ?? 0 + section.end = section.start + section.raw.byteLength + return section + }) + + this.sections = this.#sections.map((section, index) => ({ + id: index, + load: () => this.loadSection(section), + createDocument: () => this.createDocument(section), + size: section.end - section.start, + })) + + try { + this.landmarks = await this.getGuide() + const tocHref = this.landmarks + .find(({ type }) => type?.includes('toc'))?.href + if (tocHref) { + const { index } = this.resolveHref(tocHref) + const doc = await this.sections[index].createDocument() + let lastItem + let lastLevel = 0 + let lastIndent = 0 + const lastLevelOfIndent = new Map() + const lastParentOfLevel = new Map() + this.toc = Array.from(doc.querySelectorAll('a[filepos]')) + .reduce((arr, a) => { + const indent = getIndent(a) + const item = { + label: a.innerText?.trim() ?? '', + href: `filepos:${a.getAttribute('filepos')}`, + } + const level = indent > lastIndent ? lastLevel + 1 + : indent === lastIndent ? lastLevel + : lastLevelOfIndent.get(indent) ?? Math.max(0, lastLevel - 1) + if (level > lastLevel) { + if (lastItem) { + lastItem.subitems ??= [] + lastItem.subitems.push(item) + lastParentOfLevel.set(level, lastItem) + } + else arr.push(item) + } + else { + const parent = lastParentOfLevel.get(level) + if (parent) parent.subitems.push(item) + else arr.push(item) + } + lastItem = item + lastLevel = level + lastIndent = indent + lastLevelOfIndent.set(indent, level) + return arr + }, []) + } + } catch(e) { + console.warn(e) + } + + // get list of all `filepos` references in the book, + // which will be used to insert anchor elements + // because only then can they be referenced in the DOM + this.#fileposList = [...new Set( + Array.from(str.matchAll(fileposRegex), m => m[1]))] + .map(filepos => ({ filepos, number: Number(filepos) })) + .sort((a, b) => a.number - b.number) + + this.metadata = this.mobi.getMetadata() + this.getCover = this.mobi.getCover.bind(this.mobi) + return this + } + async getGuide() { + const doc = await this.createDocument(this.#sections[0]) + return Array.from(doc.getElementsByTagName('reference'), ref => ({ + label: ref.getAttribute('title'), + type: ref.getAttribute('type')?.split(/\s/), + href: `filepos:${ref.getAttribute('filepos')}`, + })) + } + async loadResource(index) { + if (this.#resourceCache.has(index)) return this.#resourceCache.get(index) + const raw = await this.mobi.loadResource(index) + const url = URL.createObjectURL(new Blob([raw])) + this.#resourceCache.set(index, url) + return url + } + async loadRecindex(recindex) { + return this.loadResource(Number(recindex) - 1) + } + async replaceResources(doc) { + for (const img of doc.querySelectorAll('img[recindex]')) { + const recindex = img.getAttribute('recindex') + try { + img.src = await this.loadRecindex(recindex) + } catch { + console.warn(`Failed to load image ${recindex}`) + } + } + for (const media of doc.querySelectorAll('[mediarecindex]')) { + const mediarecindex = media.getAttribute('mediarecindex') + const recindex = media.getAttribute('recindex') + try { + media.src = await this.loadRecindex(mediarecindex) + if (recindex) media.poster = await this.loadRecindex(recindex) + } catch { + console.warn(`Failed to load media ${mediarecindex}`) + } + } + for (const a of doc.querySelectorAll('[filepos]')) { + const filepos = a.getAttribute('filepos') + a.href = `filepos:${filepos}` + } + } + async loadText(section) { + if (this.#textCache.has(section)) return this.#textCache.get(section) + const { raw } = section + + // insert anchor elements for each `filepos` + const fileposList = this.#fileposList + .filter(({ number }) => number >= section.start && number < section.end) + .map(obj => ({ ...obj, offset: obj.number - section.start })) + let arr = raw + if (fileposList.length) { + arr = raw.subarray(0, fileposList[0].offset) + fileposList.forEach(({ filepos, offset }, i) => { + const next = fileposList[i + 1] + const a = this.mobi.encode(``) + arr = concatTypedArray3(arr, a, raw.subarray(offset, next?.offset)) + }) + } + const str = this.mobi.decode(arr).replaceAll(mbpPagebreakRegex, '') + this.#textCache.set(section, str) + return str + } + async createDocument(section) { + const str = await this.loadText(section) + return this.parser.parseFromString(str, this.#type) + } + async loadSection(section) { + if (this.#cache.has(section)) return this.#cache.get(section) + const doc = await this.createDocument(section) + + // inject default stylesheet + const style = doc.createElement('style') + doc.head.append(style) + // blockquotes in MOBI seem to have only a small left margin by default + // many books seem to rely on this, as it's the only way to set margin + // (since there's no CSS) + style.append(doc.createTextNode(`blockquote { + margin-block-start: 0; + margin-block-end: 0; + margin-inline-start: 1em; + margin-inline-end: 0; + }`)) + + await this.replaceResources(doc) + const result = this.serializer.serializeToString(doc) + const url = URL.createObjectURL(new Blob([result], { type: this.#type })) + this.#cache.set(section, url) + return url + } + resolveHref(href) { + const filepos = href.match(/filepos:(.*)/)[1] + const number = Number(filepos) + const index = this.#sections.findIndex(section => section.end > number) + const anchor = doc => doc.getElementById(`filepos${filepos}`) + return { index, anchor } + } + splitTOCHref(href) { + const filepos = href.match(/filepos:(.*)/)[1] + const number = Number(filepos) + const index = this.#sections.findIndex(section => section.end > number) + return [index, `filepos${filepos}`] + } + getTOCFragment(doc, id) { + return doc.getElementById(id) + } + isExternal(uri) { + return /^(?!blob|filepos)\w+:/i.test(uri) + } + destroy() { + for (const url of this.#resourceCache.values()) URL.revokeObjectURL(url) + for (const url of this.#cache.values()) URL.revokeObjectURL(url) + } +} + +// handlers for `kindle:` uris +const kindleResourceRegex = /kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/ +const kindlePosRegex = /kindle:pos:fid:(\w+):off:(\w+)/ +const parseResourceURI = str => { + const [resourceType, id, type] = str.match(kindleResourceRegex).slice(1) + return { resourceType, id: parseInt(id, 32), type } +} +const parsePosURI = str => { + const [fid, off] = str.match(kindlePosRegex).slice(1) + return { fid: parseInt(fid, 32), off: parseInt(off, 32) } +} +const makePosURI = (fid = 0, off = 0) => + `kindle:pos:fid:${fid.toString(32).toUpperCase().padStart(4, '0') + }:off:${off.toString(32).toUpperCase().padStart(10, '0')}` + +// `kindle:pos:` links are originally links that contain fragments identifiers +// so there should exist an element with `id` or `name` +// otherwise try to find one with an `aid` attribute +const getFragmentSelector = str => { + const match = str.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i) + if (!match) return + const [, attr, value] = match + return `[${attr}="${CSS.escape(value)}"]` +} + +// replace asynchronously and sequentially +const replaceSeries = async (str, regex, f) => { + const matches = [] + str.replace(regex, (...args) => (matches.push(args), null)) + const results = [] + for (const args of matches) results.push(await f(...args)) + return str.replace(regex, () => results.shift()) +} + +const getPageSpread = properties => { + for (const p of properties) { + if (p === 'page-spread-left' || p === 'rendition:page-spread-left') + return 'left' + if (p === 'page-spread-right' || p === 'rendition:page-spread-right') + return 'right' + if (p === 'rendition:page-spread-center') return 'center' + } +} + +class KF8 { + parser = new DOMParser() + serializer = new XMLSerializer() + transformTarget = new EventTarget() + #cache = new Map() + #fragmentOffsets = new Map() + #fragmentSelectors = new Map() + #tables = {} + #sections + #fullRawLength + #rawHead = new Uint8Array() + #rawTail = new Uint8Array() + #lastLoadedHead = -1 + #lastLoadedTail = -1 + #type = MIME.XHTML + #inlineMap = new Map() + constructor(mobi) { + this.mobi = mobi + } + async init() { + const loadRecord = this.mobi.loadRecord.bind(this.mobi) + const { kf8 } = this.mobi.headers + + try { + const fdstBuffer = await loadRecord(kf8.fdst) + const fdst = getStruct(FDST_HEADER, fdstBuffer) + if (fdst.magic !== 'FDST') throw new Error('Missing FDST record') + const fdstTable = Array.from({ length: fdst.numEntries }, + (_, i) => 12 + i * 8) + .map(offset => [ + getUint(fdstBuffer.slice(offset, offset + 4)), + getUint(fdstBuffer.slice(offset + 4, offset + 8))]) + this.#tables.fdstTable = fdstTable + this.#fullRawLength = fdstTable[fdstTable.length - 1][1] + } catch {} + + const skelTable = (await getIndexData(kf8.skel, loadRecord)).table + .map(({ name, tagMap }, index) => ({ + index, name, + numFrag: tagMap[1][0], + offset: tagMap[6][0], + length: tagMap[6][1], + })) + const fragData = await getIndexData(kf8.frag, loadRecord) + const fragTable = fragData.table.map(({ name, tagMap }) => ({ + insertOffset: parseInt(name), + selector: fragData.cncx[tagMap[2][0]], + index: tagMap[4][0], + offset: tagMap[6][0], + length: tagMap[6][1], + })) + this.#tables.skelTable = skelTable + this.#tables.fragTable = fragTable + + this.#sections = skelTable.reduce((arr, skel) => { + const last = arr[arr.length - 1] + const fragStart = last?.fragEnd ?? 0, fragEnd = fragStart + skel.numFrag + const frags = fragTable.slice(fragStart, fragEnd) + const length = skel.length + frags.map(f => f.length).reduce((a, b) => a + b, 0) + const totalLength = (last?.totalLength ?? 0) + length + return arr.concat({ skel, frags, fragEnd, length, totalLength }) + }, []) + + const resources = await this.getResourcesByMagic(['RESC', 'PAGE']) + const pageSpreads = new Map() + if (resources.RESC) { + const buf = await this.mobi.loadRecord(resources.RESC) + const str = this.mobi.decode(buf.slice(16)).replace(/\0/g, '') + // the RESC record lacks the root `` element + // but seem to be otherwise valid XML + const index = str.search(/\?>/) + const xmlStr = `${str.slice(index)}` + const opf = this.parser.parseFromString(xmlStr, MIME.XML) + for (const $itemref of opf.querySelectorAll('spine > itemref')) { + const i = parseInt($itemref.getAttribute('skelid')) + pageSpreads.set(i, getPageSpread( + $itemref.getAttribute('properties')?.split(' ') ?? [])) + } + } + + this.sections = this.#sections.map((section, index) => + section.frags.length ? ({ + id: index, + load: () => this.loadSection(section), + createDocument: () => this.createDocument(section), + size: section.length, + pageSpread: pageSpreads.get(index), + }) : ({ linear: 'no' })) + + try { + const ncx = await this.mobi.getNCX() + const map = ({ label, pos, children }) => { + const [fid, off] = pos + const href = makePosURI(fid, off) + const arr = this.#fragmentOffsets.get(fid) + if (arr) arr.push(off) + else this.#fragmentOffsets.set(fid, [off]) + return { label: unescapeHTML(label), href, subitems: children?.map(map) } + } + this.toc = ncx?.map(map) + this.landmarks = await this.getGuide() + } catch(e) { + console.warn(e) + } + + const { exth } = this.mobi.headers + this.dir = exth.pageProgressionDirection + this.rendition = { + layout: exth.fixedLayout === 'true' ? 'pre-paginated' : 'reflowable', + viewport: Object.fromEntries(exth.originalResolution + ?.split('x')?.slice(0, 2) + ?.map((x, i) => [i ? 'height' : 'width', x]) ?? []), + } + + this.metadata = this.mobi.getMetadata() + this.getCover = this.mobi.getCover.bind(this.mobi) + return this + } + // is this really the only way of getting to RESC, PAGE, etc.? + async getResourcesByMagic(keys) { + const results = {} + const start = this.mobi.headers.kf8.resourceStart + const end = this.mobi.pdb.numRecords + for (let i = start; i < end; i++) { + try { + const magic = await this.mobi.loadMagic(i) + const match = keys.find(key => key === magic) + if (match) results[match] = i + } catch {} + } + return results + } + async getGuide() { + const index = this.mobi.headers.kf8.guide + if (index < 0xffffffff) { + const loadRecord = this.mobi.loadRecord.bind(this.mobi) + const { table, cncx } = await getIndexData(index, loadRecord) + return table.map(({ name, tagMap }) => ({ + label: cncx[tagMap[1][0]] ?? '', + type: name?.split(/\s/), + href: makePosURI(tagMap[6]?.[0] ?? tagMap[3]?.[0]), + })) + } + } + async loadResourceBlob(str) { + const { resourceType, id, type } = parseResourceURI(str) + const raw = resourceType === 'flow' ? await this.loadFlow(id) + : await this.mobi.loadResource(id - 1) + const result = [MIME.XHTML, MIME.HTML, MIME.CSS, MIME.SVG].includes(type) + ? await this.replaceResources(this.mobi.decode(raw)) : raw + const detail = { data: result, type } + const event = new CustomEvent('data', { detail }) + this.transformTarget.dispatchEvent(event) + const newData = await event.detail.data + const newType = await event.detail.type + const doc = newType === MIME.SVG ? this.parser.parseFromString(newData, newType) : null + return [new Blob([newData], { newType }), + // SVG wrappers need to be inlined + // as browsers don't allow external resources when loading SVG as an image + doc?.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')?.length + ? doc.documentElement : null] + } + async loadResource(str) { + if (this.#cache.has(str)) return this.#cache.get(str) + const [blob, inline] = await this.loadResourceBlob(str) + const url = inline ? str : URL.createObjectURL(blob) + if (inline) this.#inlineMap.set(url, inline) + this.#cache.set(str, url) + return url + } + replaceResources(str) { + const regex = new RegExp(kindleResourceRegex, 'g') + return replaceSeries(str, regex, this.loadResource.bind(this)) + } + // NOTE: there doesn't seem to be a way to access text randomly? + // how to know the decompressed size of the records without decompressing? + // 4096 is just the maximum size + async loadRaw(start, end) { + // here we load either from the front or back until we have reached the + // required offsets; at worst you'd have to load half the book at once + const distanceHead = end - this.#rawHead.length + const distanceEnd = this.#fullRawLength == null ? Infinity + : (this.#fullRawLength - this.#rawTail.length) - start + // load from the start + if (distanceHead < 0 || distanceHead < distanceEnd) { + while (this.#rawHead.length < end) { + const index = ++this.#lastLoadedHead + const data = await this.mobi.loadText(index) + this.#rawHead = concatTypedArray(this.#rawHead, data) + } + return this.#rawHead.slice(start, end) + } + // load from the end + while (this.#fullRawLength - this.#rawTail.length > start) { + const index = this.mobi.headers.palmdoc.numTextRecords - 1 + - (++this.#lastLoadedTail) + const data = await this.mobi.loadText(index) + this.#rawTail = concatTypedArray(data, this.#rawTail) + } + const rawTailStart = this.#fullRawLength - this.#rawTail.length + return this.#rawTail.slice(start - rawTailStart, end - rawTailStart) + } + loadFlow(index) { + if (index < 0xffffffff) + return this.loadRaw(...this.#tables.fdstTable[index]) + } + async loadText(section) { + const { skel, frags, length } = section + const raw = await this.loadRaw(skel.offset, skel.offset + length) + let skeleton = raw.slice(0, skel.length) + for (const frag of frags) { + const insertOffset = frag.insertOffset - skel.offset + const offset = skel.length + frag.offset + const fragRaw = raw.slice(offset, offset + frag.length) + skeleton = concatTypedArray3( + skeleton.slice(0, insertOffset), fragRaw, + skeleton.slice(insertOffset)) + + const offsets = this.#fragmentOffsets.get(frag.index) + if (offsets) for (const offset of offsets) { + const str = this.mobi.decode(fragRaw.slice(offset)) + const selector = getFragmentSelector(str) + this.#setFragmentSelector(frag.index, offset, selector) + } + } + return this.mobi.decode(skeleton) + } + async createDocument(section) { + const str = await this.loadText(section) + return this.parser.parseFromString(str, this.#type) + } + async loadSection(section) { + if (this.#cache.has(section)) return this.#cache.get(section) + const str = await this.loadText(section) + const replaced = await this.replaceResources(str) + + // by default, type is XHTML; change to HTML if it's not valid XHTML + let doc = this.parser.parseFromString(replaced, this.#type) + if (doc.querySelector('parsererror') || !doc.documentElement?.namespaceURI) { + this.#type = MIME.HTML + doc = this.parser.parseFromString(replaced, this.#type) + } + for (const [url, node] of this.#inlineMap) { + for (const el of doc.querySelectorAll(`img[src="${url}"]`)) + el.replaceWith(node) + } + const url = URL.createObjectURL( + new Blob([this.serializer.serializeToString(doc)], { type: this.#type })) + this.#cache.set(section, url) + return url + } + getIndexByFID(fid) { + return this.#sections.findIndex(section => + section.frags.some(frag => frag.index === fid)) + } + #setFragmentSelector(id, offset, selector) { + const map = this.#fragmentSelectors.get(id) + if (map) map.set(offset, selector) + else { + const map = new Map() + this.#fragmentSelectors.set(id, map) + map.set(offset, selector) + } + } + async resolveHref(href) { + const { fid, off } = parsePosURI(href) + const index = this.getIndexByFID(fid) + if (index < 0) return + + const saved = this.#fragmentSelectors.get(fid)?.get(off) + if (saved) return { index, anchor: doc => doc.querySelector(saved) } + + const { skel, frags } = this.#sections[index] + const frag = frags.find(frag => frag.index === fid) + const offset = skel.offset + skel.length + frag.offset + const fragRaw = await this.loadRaw(offset, offset + frag.length) + const str = this.mobi.decode(fragRaw.slice(off)) + const selector = getFragmentSelector(str) + this.#setFragmentSelector(fid, off, selector) + const anchor = doc => doc.querySelector(selector) + return { index, anchor } + } + splitTOCHref(href) { + const pos = parsePosURI(href) + const index = this.getIndexByFID(pos.fid) + return [index, pos] + } + getTOCFragment(doc, { fid, off }) { + const selector = this.#fragmentSelectors.get(fid)?.get(off) + return doc.querySelector(selector) + } + isExternal(uri) { + return /^(?!blob|kindle)\w+:/i.test(uri) + } + destroy() { + for (const url of this.#cache.values()) URL.revokeObjectURL(url) + } +} diff --git a/packages/foliate-js/opds.js b/packages/foliate-js/opds.js new file mode 100644 index 0000000000000000000000000000000000000000..0d6369f3cd0ff9e15359e3302890eb0c100431f1 --- /dev/null +++ b/packages/foliate-js/opds.js @@ -0,0 +1,294 @@ +const NS = { + ATOM: 'http://www.w3.org/2005/Atom', + OPDS: 'http://opds-spec.org/2010/catalog', + THR: 'http://purl.org/syndication/thread/1.0', + DC: 'http://purl.org/dc/elements/1.1/', + DCTERMS: 'http://purl.org/dc/terms/', +} + +const MIME = { + ATOM: 'application/atom+xml', + OPDS2: 'application/opds+json', +} + +export const REL = { + ACQ: 'http://opds-spec.org/acquisition', + FACET: 'http://opds-spec.org/facet', + GROUP: 'http://opds-spec.org/group', + COVER: [ + 'http://opds-spec.org/image', + 'http://opds-spec.org/cover', + ], + THUMBNAIL: [ + 'http://opds-spec.org/image/thumbnail', + 'http://opds-spec.org/thumbnail', + ], +} + +export const SYMBOL = { + SUMMARY: Symbol('summary'), + CONTENT: Symbol('content'), +} + +const FACET_GROUP = Symbol('facetGroup') + +const groupByArray = (arr, f) => { + const map = new Map() + if (arr) for (const el of arr) { + const keys = f(el) + for (const key of [keys].flat()) { + const group = map.get(key) + if (group) group.push(el) + else map.set(key, [el]) + } + } + return map +} + +// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.1 +const parseMediaType = str => { + if (!str) return null + const [mediaType, ...ps] = str.split(/ *; */) + return { + mediaType: mediaType.toLowerCase(), + parameters: Object.fromEntries(ps.map(p => { + const [name, val] = p.split('=') + return [name.toLowerCase(), val?.replace(/(^"|"$)/g, '')] + })), + } +} + +export const isOPDSCatalog = str => { + const parsed = parseMediaType(str) + if (!parsed) return false + const { mediaType, parameters } = parsed + if (mediaType === MIME.OPDS2) return true + return mediaType === MIME.ATOM && parameters.profile?.toLowerCase() === 'opds-catalog' +} + +export const isOPDSSearch = str => { + const parsed = parseMediaType(str) + if (!parsed) return false + const { mediaType } = parsed + return mediaType === MIME.ATOM +} + +// ignore the namespace if it doesn't appear in document at all +const useNS = (doc, ns) => + doc.lookupNamespaceURI(null) === ns || doc.lookupPrefix(ns) ? ns : null + +const filterNS = ns => ns + ? name => el => el.namespaceURI === ns && el.localName === name + : name => el => el.localName === name + +const getContent = el => { + if (!el) return + const type = el.getAttribute('type') ?? 'text' + const value = type === 'xhtml' ? el.innerHTML + : type === 'html' ? el.textContent + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('&', '&') + : el.textContent + return { value, type } +} + +const getTextContent = el => { + const content = getContent(el) + if (content?.type === 'text') return content?.value +} + +const getSummary = (a, b) => getTextContent(a) ?? getTextContent(b) + +const getPrice = link => { + const price = link.getElementsByTagNameNS(NS.OPDS, 'price')[0] + return price ? { + currency: price.getAttribute('currencycode'), + value: price.textContent, + } : null +} + +const getIndirectAcquisition = el => { + const ia = el.getElementsByTagNameNS(NS.OPDS, 'indirectAcquisition')[0] + if (!ia) return [] + return [{ type: ia.getAttribute('type') }, ...getIndirectAcquisition(ia)] +} + +const getLink = link => { + const obj = { + rel: link.getAttribute('rel')?.split(/ +/), + href: link.getAttribute('href'), + type: link.getAttribute('type'), + title: link.getAttribute('title'), + properties: { + price: getPrice(link), + indirectAcquisition: getIndirectAcquisition(link), + numberOfItems: link.getAttributeNS(NS.THR, 'count'), + }, + [FACET_GROUP]: link.getAttributeNS(NS.OPDS, 'facetGroup'), + } + if (link.getAttributeNS(NS.OPDS, 'activeFacet') === 'true') + obj.rel = [obj.rel ?? []].flat().concat('self') + return obj +} + +const getPerson = person => { + const NS = person.namespaceURI + const uri = person.getElementsByTagNameNS(NS, 'uri')[0]?.textContent + return { + name: person.getElementsByTagNameNS(NS, 'name')[0]?.textContent ?? '', + links: uri ? [{ href: uri }] : [], + } +} + +export const getPublication = entry => { + const filter = filterNS(useNS(entry.ownerDocument, NS.ATOM)) + const children = Array.from(entry.children) + const filterDCEL = filterNS(NS.DC) + const filterDCTERMS = filterNS(NS.DCTERMS) + const filterDC = x => { + const a = filterDCEL(x), b = filterDCTERMS(x) + return y => a(y) || b(y) + } + const links = children.filter(filter('link')).map(getLink) + const linksByRel = groupByArray(links, link => link.rel) + return { + metadata: { + title: children.find(filter('title'))?.textContent ?? '', + author: children.filter(filter('author')).map(getPerson), + contributor: children.filter(filter('contributor')).map(getPerson), + publisher: children.find(filterDC('publisher'))?.textContent, + published: (children.find(filterDCTERMS('issued')) + ?? children.find(filterDC('date')))?.textContent, + language: children.find(filterDC('language'))?.textContent, + identifier: children.find(filterDC('identifier'))?.textContent, + subject: children.filter(filter('category')).map(category => ({ + name: category.getAttribute('label'), + code: category.getAttribute('term'), + scheme: category.getAttribute('scheme'), + })), + rights: children.find(filter('rights'))?.textContent ?? '', + [SYMBOL.CONTENT]: getContent(children.find(filter('content')) + ?? children.find(filter('summary'))), + }, + links, + images: REL.COVER.concat(REL.THUMBNAIL) + .map(R => linksByRel.get(R)?.[0]).filter(x => x), + } +} + +export const getFeed = doc => { + const ns = useNS(doc, NS.ATOM) + const filter = filterNS(ns) + const children = Array.from(doc.documentElement.children) + const entries = children.filter(filter('entry')) + const links = children.filter(filter('link')).map(getLink) + const linksByRel = groupByArray(links, link => link.rel) + + const groupedItems = new Map([[null, []]]) + const groupLinkMap = new Map() + for (const entry of entries) { + const children = Array.from(entry.children) + const links = children.filter(filter('link')).map(getLink) + const linksByRel = groupByArray(links, link => link.rel) + const isPub = [...linksByRel.keys()] + .some(rel => rel?.startsWith(REL.ACQ) || rel === 'preview') + + const groupLinks = linksByRel.get(REL.GROUP) ?? linksByRel.get('collection') + const groupLink = groupLinks?.length + ? groupLinks.find(link => groupedItems.has(link.href)) ?? groupLinks[0] : null + if (groupLink && !groupLinkMap.has(groupLink.href)) + groupLinkMap.set(groupLink.href, groupLink) + + const item = isPub + ? getPublication(entry) + : Object.assign(links.find(link => isOPDSCatalog(link.type)) ?? links[0] ?? {}, { + title: children.find(filter('title'))?.textContent, + [SYMBOL.SUMMARY]: getSummary(children.find(filter('summary')), + children.find(filter('content'))), + }) + + const arr = groupedItems.get(groupLink?.href ?? null) + if (arr) arr.push(item) + else groupedItems.set(groupLink.href, [item]) + } + const [items, ...groups] = Array.from(groupedItems, ([key, items]) => { + const itemsKey = items[0]?.metadata ? 'publications' : 'navigation' + if (key == null) return { [itemsKey]: items } + const link = groupLinkMap.get(key) + return { + metadata: { + title: link.title, + numberOfItems: link.properties.numberOfItems, + }, + links: [{ rel: 'self', href: link.href, type: link.type }], + [itemsKey]: items, + } + }) + return { + metadata: { + title: children.find(filter('title'))?.textContent, + subtitle: children.find(filter('subtitle'))?.textContent, + }, + links, + ...items, + groups, + facets: Array.from( + groupByArray(linksByRel.get(REL.FACET) ?? [], link => link[FACET_GROUP]), + ([facet, links]) => ({ metadata: { title: facet }, links })), + } +} + +export const getSearch = async link => { + const { replace, getVariables } = await import('./uri-template.js') + return { + metadata: { + title: link.title, + }, + search: map => replace(link.href, map.get(null)), + params: Array.from(getVariables(link.href), name => ({ name })), + } +} + +export const getOpenSearch = doc => { + const defaultNS = doc.documentElement.namespaceURI + const filter = filterNS(defaultNS) + const children = Array.from(doc.documentElement.children) + + const $$urls = children.filter(filter('Url')) + const $url = $$urls.find(url => isOPDSCatalog(url.getAttribute('type'))) ?? $$urls.find(url => isOPDSSearch(url.getAttribute('type'))) ?? $$urls[0] + if (!$url) throw new Error('document must contain at least one Url element') + + const regex = /{(?:([^}]+?):)?(.+?)(\?)?}/g + const defaultMap = new Map([ + ['count', '100'], + ['startIndex', $url.getAttribute('indexOffset') ?? '0'], + ['startPage', $url.getAttribute('pageOffset') ?? '0'], + ['language', '*'], + ['inputEncoding', 'UTF-8'], + ['outputEncoding', 'UTF-8'], + ]) + + const template = $url.getAttribute('template') + return { + metadata: { + title: (children.find(filter('LongName')) ?? children.find(filter('ShortName')))?.textContent, + description: children.find(filter('Description'))?.textContent, + }, + search: map => template.replace(regex, (_, prefix, param) => { + const namespace = prefix ? $url.lookupNamespaceURI(prefix) : null + const ns = namespace === defaultNS ? null : namespace + const val = map.get(ns)?.get(param) + return encodeURIComponent(val ? val : (!ns ? defaultMap.get(param) ?? '' : '')) + }), + params: Array.from(template.matchAll(regex), ([, prefix, param, optional]) => { + const namespace = prefix ? $url.lookupNamespaceURI(prefix) : null + const ns = namespace === defaultNS ? null : namespace + return { + ns, name: param, + required: !optional, + value: ns && ns !== defaultNS ? '' : defaultMap.get(param) ?? '', + } + }), + } +} diff --git a/packages/foliate-js/overlayer.js b/packages/foliate-js/overlayer.js new file mode 100644 index 0000000000000000000000000000000000000000..8a256b602c5bfb0d146f7a6dd4925ddf3023da7d --- /dev/null +++ b/packages/foliate-js/overlayer.js @@ -0,0 +1,409 @@ +const createSVGElement = tag => + document.createElementNS('http://www.w3.org/2000/svg', tag) + +export class Overlayer { + #svg = createSVGElement('svg') + #map = new Map() + #doc = null + #clipPath = null + #clipPathPath = null + + constructor(doc) { + this.#doc = doc + Object.assign(this.#svg.style, { + position: 'absolute', top: '0', left: '0', + width: '100%', height: '100%', + pointerEvents: 'none', + }) + + // Create a clipPath to cut a hole for the loupe. + // We use clip-rule="evenodd" with a large outer rect and inner circle + // to create the hole effect efficiently without mask compositing. + const defs = createSVGElement('defs') + this.#clipPath = createSVGElement('clipPath') + this.#clipPath.setAttribute('id', 'foliate-loupe-clip') + this.#clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse') + + this.#clipPathPath = createSVGElement('path') + this.#clipPathPath.setAttribute('clip-rule', 'evenodd') + this.#clipPathPath.setAttribute('fill-rule', 'evenodd') // for older renderers + + this.#clipPath.append(this.#clipPathPath) + defs.append(this.#clipPath) + this.#svg.append(defs) + } + + setHole(x, y, r) { + // Define a path with a large outer rect and a circular hole + // "Infinite" outer rect coverage is safe for userSpaceOnUse + // (20,000px limit was too small for long scrolls; use 2,000,000px) + const outer = 'M -2000000 -2000000 H 4000000 V 4000000 H -2000000 Z' + const inner = `M ${x} ${y} m -${r} 0 a ${r} ${r} 0 1 0 ${2*r} 0 a ${r} ${r} 0 1 0 -${2*r} 0` + this.#clipPathPath.setAttribute('d', `${outer} ${inner}`) + + this.#svg.setAttribute('clip-path', 'url(#foliate-loupe-clip)') + this.#svg.style.webkitClipPath = 'url(#foliate-loupe-clip)' + } + + clearHole() { + this.#svg.removeAttribute('clip-path') + this.#svg.style.webkitClipPath = '' + this.#clipPathPath.removeAttribute('d') + } + + get element() { + return this.#svg + } + get #zoom() { + // Safari does not zoom the client rects, while Chrome, Edge and Firefox does + if (/^((?!chrome|android).)*AppleWebKit/i.test(navigator.userAgent) && !window.chrome) { + return window.getComputedStyle(this.#doc.body).zoom || 1.0 + } + return 1.0 + } + #splitRangeByParagraph(range) { + const ancestor = range.commonAncestorContainer + const paragraphs = Array.from(ancestor.querySelectorAll?.('p, h1, h2, h3, h4') || []) + + const splitRanges = [] + paragraphs.forEach((p) => { + const pRange = document.createRange() + if (range.intersectsNode(p)) { + pRange.selectNodeContents(p) + if (pRange.compareBoundaryPoints(Range.START_TO_START, range) < 0) { + pRange.setStart(range.startContainer, range.startOffset) + } + if (pRange.compareBoundaryPoints(Range.END_TO_END, range) > 0) { + pRange.setEnd(range.endContainer, range.endOffset) + } + splitRanges.push(pRange) + } + }) + return splitRanges.length === 0 ? [range] : splitRanges + } + add(key, range, draw, options) { + if (this.#map.has(key)) this.remove(key) + if (typeof range === 'function') range = range(this.#svg.getRootNode()) + const zoom = this.#zoom + let rects = [] + this.#splitRangeByParagraph(range).forEach((pRange) => { + const pRects = Array.from(pRange.getClientRects()).map(rect => ({ + left: rect.left * zoom, + top: rect.top * zoom, + right: rect.right * zoom, + bottom: rect.bottom * zoom, + width: rect.width * zoom, + height: rect.height * zoom, + })) + rects = rects.concat(pRects) + }) + const element = draw(rects, options) + this.#svg.append(element) + this.#map.set(key, { range, draw, options, element, rects }) + } + remove(key) { + if (!this.#map.has(key)) return + this.#svg.removeChild(this.#map.get(key).element) + this.#map.delete(key) + } + redraw() { + for (const obj of this.#map.values()) { + const { range, draw, options, element } = obj + this.#svg.removeChild(element) + const zoom = this.#zoom + let rects = [] + this.#splitRangeByParagraph(range).forEach((pRange) => { + const pRects = Array.from(pRange.getClientRects()).map(rect => ({ + left: rect.left * zoom, + top: rect.top * zoom, + right: rect.right * zoom, + bottom: rect.bottom * zoom, + width: rect.width * zoom, + height: rect.height * zoom, + })) + rects = rects.concat(pRects) + }) + const el = draw(rects, options) + this.#svg.append(el) + obj.element = el + obj.rects = rects + } + } + hitTest({ x, y }) { + const arr = Array.from(this.#map.entries()) + // loop in reverse to hit more recently added items first + for (let i = arr.length - 1; i >= 0; i--) { + const tolerance = 5 + const [key, obj] = arr[i] + for (const { left, top, right, bottom } of obj.rects) { + if ( + top <= y + tolerance && + left <= x + tolerance && + bottom > y - tolerance && + right > x - tolerance + ) { + return [key, obj.range, { left, top, right, bottom }] + } + } + } + return [] + } + static underline(rects, options = {}) { + const { color = 'red', width: strokeWidth = 2, padding = 0, writingMode } = options + const g = createSVGElement('g') + g.setAttribute('fill', color) + if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr') + for (const { right, top, height } of rects) { + const el = createSVGElement('rect') + el.setAttribute('x', right - strokeWidth / 2 + padding) + el.setAttribute('y', top) + el.setAttribute('height', height) + el.setAttribute('width', strokeWidth) + g.append(el) + } + else for (const { left, bottom, width } of rects) { + const el = createSVGElement('rect') + el.setAttribute('x', left) + el.setAttribute('y', bottom - strokeWidth / 2 + padding) + el.setAttribute('height', strokeWidth) + el.setAttribute('width', width) + g.append(el) + } + return g + } + static strikethrough(rects, options = {}) { + const { color = 'red', width: strokeWidth = 2, writingMode } = options + const g = createSVGElement('g') + g.setAttribute('fill', color) + if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr') + for (const { right, left, top, height } of rects) { + const el = createSVGElement('rect') + el.setAttribute('x', (right + left) / 2) + el.setAttribute('y', top) + el.setAttribute('height', height) + el.setAttribute('width', strokeWidth) + g.append(el) + } + else for (const { left, top, bottom, width } of rects) { + const el = createSVGElement('rect') + el.setAttribute('x', left) + el.setAttribute('y', (top + bottom) / 2) + el.setAttribute('height', strokeWidth) + el.setAttribute('width', width) + g.append(el) + } + return g + } + static squiggly(rects, options = {}) { + const { color = 'red', width: strokeWidth = 2, padding = 0, writingMode } = options + const g = createSVGElement('g') + g.setAttribute('fill', 'none') + g.setAttribute('stroke', color) + g.setAttribute('stroke-width', strokeWidth) + const block = strokeWidth * 1.5 + if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr') + for (const { right, top, height } of rects) { + const el = createSVGElement('path') + const n = Math.round(height / block / 1.5) + const inline = height / n + const ls = Array.from({ length: n }, + (_, i) => `l${i % 2 ? -block : block} ${inline}`).join('') + el.setAttribute('d', `M${right - strokeWidth / 2 + padding} ${top}${ls}`) + g.append(el) + } + else for (const { left, bottom, width } of rects) { + const el = createSVGElement('path') + const n = Math.round(width / block / 1.5) + const inline = width / n + const ls = Array.from({ length: n }, + (_, i) => `l${inline} ${i % 2 ? block : -block}`).join('') + el.setAttribute('d', `M${left} ${bottom + strokeWidth / 2 + padding}${ls}`) + g.append(el) + } + return g + } + static highlight(rects, options = {}) { + const { + color = 'red', + padding = 0, + radius = 4, + radiusPadding = 2, + vertical = false, + } = options + + const g = createSVGElement('g') + g.setAttribute('fill', color) + g.style.opacity = 'var(--overlayer-highlight-opacity, .3)' + g.style.mixBlendMode = 'var(--overlayer-highlight-blend-mode, normal)' + + for (const [index, { left, top, height, width }] of rects.entries()) { + const isFirst = index === 0 + const isLast = index === rects.length - 1 + + let x, y, w, h + + let radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft + + if (vertical) { + x = left - padding + y = top - padding - (isFirst ? radiusPadding : 0) + w = width + padding * 2 + h = height + padding * 2 + (isFirst ? radiusPadding : 0) + (isLast ? radiusPadding : 0) + radiusTopLeft = isFirst ? radius : 0 + radiusTopRight = isFirst ? radius : 0 + radiusBottomRight = isLast ? radius : 0 + radiusBottomLeft = isLast ? radius : 0 + } else { + x = left - padding - (isFirst ? radiusPadding : 0) + y = top - padding + w = width + padding * 2 + (isFirst ? radiusPadding : 0) + (isLast ? radiusPadding : 0) + h = height + padding * 2 + radiusTopLeft = isFirst ? radius : 0 + radiusTopRight = isLast ? radius : 0 + radiusBottomRight = isLast ? radius : 0 + radiusBottomLeft = isFirst ? radius : 0 + } + + const rtl = Math.min(radiusTopLeft, w / 2, h / 2) + const rtr = Math.min(radiusTopRight, w / 2, h / 2) + const rbr = Math.min(radiusBottomRight, w / 2, h / 2) + const rbl = Math.min(radiusBottomLeft, w / 2, h / 2) + + if (rtl === 0 && rtr === 0 && rbr === 0 && rbl === 0) { + const el = createSVGElement('rect') + el.setAttribute('x', x) + el.setAttribute('y', y) + el.setAttribute('height', h) + el.setAttribute('width', w) + g.append(el) + } else { + const el = createSVGElement('path') + const d = ` + M ${x + rtl} ${y} + L ${x + w - rtr} ${y} + ${rtr > 0 ? `Q ${x + w} ${y} ${x + w} ${y + rtr}` : `L ${x + w} ${y}`} + L ${x + w} ${y + h - rbr} + ${rbr > 0 ? `Q ${x + w} ${y + h} ${x + w - rbr} ${y + h}` : `L ${x + w} ${y + h}`} + L ${x + rbl} ${y + h} + ${rbl > 0 ? `Q ${x} ${y + h} ${x} ${y + h - rbl}` : `L ${x} ${y + h}`} + L ${x} ${y + rtl} + ${rtl > 0 ? `Q ${x} ${y} ${x + rtl} ${y}` : `L ${x} ${y}`} + Z + `.trim().replace(/\s+/g, ' ') + el.setAttribute('d', d) + g.append(el) + } + } + return g + } + static outline(rects, options = {}) { + const { color = 'red', width: strokeWidth = 3, padding = 0, radius = 3 } = options + const g = createSVGElement('g') + g.setAttribute('fill', 'none') + g.setAttribute('stroke', color) + g.setAttribute('stroke-width', strokeWidth) + for (const { left, top, height, width } of rects) { + const el = createSVGElement('rect') + el.setAttribute('x', left - padding) + el.setAttribute('y', top - padding) + el.setAttribute('height', height + padding * 2) + el.setAttribute('width', width + padding * 2) + el.setAttribute('rx', radius) + g.append(el) + } + return g + } + static bubble(rects, options = {}) { + const { color = '#fbbf24', writingMode, opacity = 0.85, size = 20, padding = 10 } = options + const isVertical = writingMode === 'vertical-rl' || writingMode === 'vertical-lr' + const g = createSVGElement('g') + g.style.opacity = opacity + if (rects.length === 0) return g + rects.splice(1) + const firstRect = rects[0] + const x = isVertical ? firstRect.right - size + padding : firstRect.right - size + padding + const y = isVertical ? firstRect.bottom - size + padding : firstRect.top - size + padding + firstRect.top = y - padding + firstRect.right = x + size + padding + firstRect.bottom = y + size + padding + firstRect.left = x - padding + const bubble = createSVGElement('path') + const s = size + const r = s * 0.15 + // Speech bubble shape with a small tail + // Main rounded rectangle body + const d = ` + M ${x + r} ${y} + h ${s - 2 * r} + a ${r} ${r} 0 0 1 ${r} ${r} + v ${s * 0.65 - 2 * r} + a ${r} ${r} 0 0 1 ${-r} ${r} + h ${-s * 0.3} + l ${-s * 0.15} ${s * 0.2} + l ${s * 0.05} ${-s * 0.2} + h ${-s * 0.6 + 2 * r} + a ${r} ${r} 0 0 1 ${-r} ${-r} + v ${-s * 0.65 + 2 * r} + a ${r} ${r} 0 0 1 ${r} ${-r} + z + `.replace(/\s+/g, ' ').trim() + + bubble.setAttribute('d', d) + bubble.setAttribute('fill', color) + bubble.setAttribute('stroke', 'rgba(0, 0, 0, 0.2)') + bubble.setAttribute('stroke-width', '1') + // Add horizontal lines inside to represent text + const lineGroup = createSVGElement('g') + lineGroup.setAttribute('stroke', 'rgba(0, 0, 0, 0.3)') + lineGroup.setAttribute('stroke-width', '1.5') + lineGroup.setAttribute('stroke-linecap', 'round') + const lineY1 = y + s * 0.18 + const lineY2 = y + s * 0.33 + const lineY3 = y + s * 0.48 + const lineX1 = x + s * 0.2 + const lineX2 = x + s * 0.8 + const line1 = createSVGElement('line') + line1.setAttribute('x1', lineX1) + line1.setAttribute('y1', lineY1) + line1.setAttribute('x2', lineX2) + line1.setAttribute('y2', lineY1) + const line2 = createSVGElement('line') + line2.setAttribute('x1', lineX1) + line2.setAttribute('y1', lineY2) + line2.setAttribute('x2', lineX2) + line2.setAttribute('y2', lineY2) + const line3 = createSVGElement('line') + line3.setAttribute('x1', lineX1) + line3.setAttribute('y1', lineY3) + line3.setAttribute('x2', x + s * 0.6) + line3.setAttribute('y2', lineY3) + lineGroup.append(line1, line2, line3) + + if (isVertical) { + const centerX = x + s / 2 + const centerY = y + s / 2 + bubble.setAttribute('transform', `rotate(90 ${centerX} ${centerY})`) + lineGroup.setAttribute('transform', `rotate(90 ${centerX} ${centerY})`) + } + + g.append(bubble) + g.append(lineGroup) + return g + } + // make an exact copy of an image in the overlay + // one can then apply filters to the entire element, without affecting them; + // it's a bit silly and probably better to just invert images twice + // (though the color will be off in that case if you do heu-rotate) + static copyImage([rect], options = {}) { + const { src } = options + const image = createSVGElement('image') + const { left, top, height, width } = rect + image.setAttribute('href', src) + image.setAttribute('x', left) + image.setAttribute('y', top) + image.setAttribute('height', height) + image.setAttribute('width', width) + return image + } +} + diff --git a/packages/foliate-js/package-lock.json b/packages/foliate-js/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..a4fc3c71b0d184419732ab6913146aa6c7081f78 --- /dev/null +++ b/packages/foliate-js/package-lock.json @@ -0,0 +1,1584 @@ +{ + "name": "foliate-js", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "foliate-js", + "version": "0.0.0", + "license": "MIT", + "dependencies": { + "construct-style-sheets-polyfill": "^3.1.0" + }, + "devDependencies": { + "@eslint/js": "^9.9.1", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-terser": "^0.4.4", + "@zip.js/zip.js": "^2.7.52", + "fflate": "^0.8.2", + "fs-extra": "^11.2.0", + "globals": "^15.9.0", + "pdfjs-dist": "^4.7.76", + "rollup": "^4.22.4" + } + }, + "node_modules/@eslint/js": { + "version": "9.12.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.12.0.tgz", + "integrity": "sha512-eohesHH8WFRUprDNyEREgqP6beG6htMeUYeCpkEgBCieCMme5r9zFWjzAJp//9S+Kub4rqE+jXe9Cp1a7IYIIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz", + "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", + "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.3.0.tgz", + "integrity": "sha512-9eO5McEICxMzJpDW9OnMYSv4Sta3hmt7VtBFz5zR9273suNOydOyq/FrGeGy+KsTRFm8w0SLVhzig2ILFT63Ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-terser": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz", + "integrity": "sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "serialize-javascript": "^6.0.1", + "smob": "^1.0.0", + "terser": "^5.17.4" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.2.tgz", + "integrity": "sha512-/FIdS3PyZ39bjZlwqFnWqCOVnW7o963LtKMwQOD0NhQqw22gSr2YY1afu3FxRip4ZCZNsD5jq6Aaz6QV3D/Njw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.24.0.tgz", + "integrity": "sha512-Q6HJd7Y6xdB48x8ZNVDOqsbh2uByBhgK8PiQgPhwkIw/HC/YX5Ghq2mQY5sRMZWHb3VsFkWooUVOZHKr7DmDIA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.24.0.tgz", + "integrity": "sha512-ijLnS1qFId8xhKjT81uBHuuJp2lU4x2yxa4ctFPtG+MqEE6+C5f/+X/bStmxapgmwLwiL3ih122xv8kVARNAZA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.24.0.tgz", + "integrity": "sha512-bIv+X9xeSs1XCk6DVvkO+S/z8/2AMt/2lMqdQbMrmVpgFvXlmde9mLcbQpztXm1tajC3raFDqegsH18HQPMYtA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.24.0.tgz", + "integrity": "sha512-X6/nOwoFN7RT2svEQWUsW/5C/fYMBe4fnLK9DQk4SX4mgVBiTA9h64kjUYPvGQ0F/9xwJ5U5UfTbl6BEjaQdBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.24.0.tgz", + "integrity": "sha512-0KXvIJQMOImLCVCz9uvvdPgfyWo93aHHp8ui3FrtOP57svqrF/roSSR5pjqL2hcMp0ljeGlU4q9o/rQaAQ3AYA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.24.0.tgz", + "integrity": "sha512-it2BW6kKFVh8xk/BnHfakEeoLPv8STIISekpoF+nBgWM4d55CZKc7T4Dx1pEbTnYm/xEKMgy1MNtYuoA8RFIWw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.24.0.tgz", + "integrity": "sha512-i0xTLXjqap2eRfulFVlSnM5dEbTVque/3Pi4g2y7cxrs7+a9De42z4XxKLYJ7+OhE3IgxvfQM7vQc43bwTgPwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.24.0.tgz", + "integrity": "sha512-9E6MKUJhDuDh604Qco5yP/3qn3y7SLXYuiC0Rpr89aMScS2UAmK1wHP2b7KAa1nSjWJc/f/Lc0Wl1L47qjiyQw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.24.0.tgz", + "integrity": "sha512-2XFFPJ2XMEiF5Zi2EBf4h73oR1V/lycirxZxHZNc93SqDN/IWhYYSYj8I9381ikUFXZrz2v7r2tOVk2NBwxrWw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.24.0.tgz", + "integrity": "sha512-M3Dg4hlwuntUCdzU7KjYqbbd+BLq3JMAOhCKdBE3TcMGMZbKkDdJ5ivNdehOssMCIokNHFOsv7DO4rlEOfyKpg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.24.0.tgz", + "integrity": "sha512-mjBaoo4ocxJppTorZVKWFpy1bfFj9FeCMJqzlMQGjpNPY9JwQi7OuS1axzNIk0nMX6jSgy6ZURDZ2w0QW6D56g==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.24.0.tgz", + "integrity": "sha512-ZXFk7M72R0YYFN5q13niV0B7G8/5dcQ9JDp8keJSfr3GoZeXEoMHP/HlvqROA3OMbMdfr19IjCeNAnPUG93b6A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.24.0.tgz", + "integrity": "sha512-w1i+L7kAXZNdYl+vFvzSZy8Y1arS7vMgIy8wusXJzRrPyof5LAb02KGr1PD2EkRcl73kHulIID0M501lN+vobQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.24.0.tgz", + "integrity": "sha512-VXBrnPWgBpVDCVY6XF3LEW0pOU51KbaHhccHw6AS6vBWIC60eqsH19DAeeObl+g8nKAz04QFdl/Cefta0xQtUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.24.0.tgz", + "integrity": "sha512-xrNcGDU0OxVcPTH/8n/ShH4UevZxKIO6HJFK0e15XItZP2UcaiLFd5kiX7hJnqCbSztUF8Qot+JWBC/QXRPYWQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.24.0.tgz", + "integrity": "sha512-fbMkAF7fufku0N2dE5TBXcNlg0pt0cJue4xBRE2Qc5Vqikxr4VCgKj/ht6SMdFcOacVA9rqF70APJ8RN/4vMJw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@zip.js/zip.js": { + "version": "2.7.52", + "resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.7.52.tgz", + "integrity": "sha512-+5g7FQswvrCHwYKNMd/KFxZSObctLSsQOgqBSi0LzwHo3li9Eh1w5cF5ndjQw9Zbr3ajVnd2+XyiX85gAetx1Q==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "bun": ">=0.7.0", + "deno": ">=1.0.0", + "node": ">=16.5.0" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "deprecated": "This package is no longer supported.", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/canvas": { + "version": "2.11.2", + "resolved": "https://registry.npmjs.org/canvas/-/canvas-2.11.2.tgz", + "integrity": "sha512-ItanGBMrmRV7Py2Z+Xhs7cT+FNt5K0vPL4p9EZ/UX/Mu7hFbkxSjKF2KVtPwX7UYWp7dRKnrTvReflgrItJbdw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.0", + "nan": "^2.17.0", + "simple-get": "^3.0.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "dev": true, + "license": "ISC", + "optional": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "dev": true, + "license": "ISC", + "optional": true, + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/construct-style-sheets-polyfill": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/construct-style-sheets-polyfill/-/construct-style-sheets-polyfill-3.1.0.tgz", + "integrity": "sha512-HBLKP0chz8BAY6rBdzda11c3wAZeCZ+kIG4weVC2NM3AXzxx09nhe8t0SQNdloAvg5GLuHwq/0SPOOSPvtCcKw==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-4.2.1.tgz", + "integrity": "sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "mimic-response": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/detect-libc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "dev": true, + "license": "MIT" + }, + "node_modules/fs-extra": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", + "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "deprecated": "This package is no longer supported.", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "15.11.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.11.0.tgz", + "integrity": "sha512-yeyNSjdbyVaWurlwCpcA6XNBrHTMIeDdj0/hnvX/OLJ9ekOXYbLsLinH/MucQyGvNnXhidTdNhTtJaffL2sMfw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/mimic-response": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-2.1.0.tgz", + "integrity": "sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "dev": true, + "license": "ISC", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true, + "license": "MIT", + "optional": true, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/nan": { + "version": "2.22.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.22.0.tgz", + "integrity": "sha512-nbajikzWTMwsW+eSsNm3QwlOs7het9gGJU5dDZzRTQGk03vyBOauxgI4VakDzE0PtsGTmXPsXTbbjVhRwR5mpw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "deprecated": "This package is no longer supported.", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path2d": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/path2d/-/path2d-0.2.1.tgz", + "integrity": "sha512-Fl2z/BHvkTNvkuBzYTpTuirHZg6wW9z8+4SND/3mDTEcYbbNKWAy21dz9D3ePNNwrrK8pqZO5vLPZ1hLF6T7XA==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pdfjs-dist": { + "version": "4.7.76", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-4.7.76.tgz", + "integrity": "sha512-8y6wUgC/Em35IumlGjaJOCm3wV4aY/6sqnIT3fVW/67mXsOZ9HWBn8GDKmJUK0GSzpbmX3gQqwfoFayp78Mtqw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "canvas": "^2.11.2", + "path2d": "^0.2.1" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rollup": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.24.0.tgz", + "integrity": "sha512-DOmrlGSXNk1DM0ljiQA+i+o0rSLhtii1je5wgk60j49d1jHT5YYttBv1iWOnYSTG+fZZESUOSNiAl89SIet+Cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.6" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.24.0", + "@rollup/rollup-android-arm64": "4.24.0", + "@rollup/rollup-darwin-arm64": "4.24.0", + "@rollup/rollup-darwin-x64": "4.24.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", + "@rollup/rollup-linux-arm-musleabihf": "4.24.0", + "@rollup/rollup-linux-arm64-gnu": "4.24.0", + "@rollup/rollup-linux-arm64-musl": "4.24.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", + "@rollup/rollup-linux-riscv64-gnu": "4.24.0", + "@rollup/rollup-linux-s390x-gnu": "4.24.0", + "@rollup/rollup-linux-x64-gnu": "4.24.0", + "@rollup/rollup-linux-x64-musl": "4.24.0", + "@rollup/rollup-win32-arm64-msvc": "4.24.0", + "@rollup/rollup-win32-ia32-msvc": "4.24.0", + "@rollup/rollup-win32-x64-msvc": "4.24.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "dev": true, + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/simple-get": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz", + "integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "decompress-response": "^4.2.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/smob": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.5.0.tgz", + "integrity": "sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==", + "dev": true, + "license": "MIT" + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser": { + "version": "5.34.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.34.1.tgz", + "integrity": "sha512-FsJZ7iZLd/BXkz+4xrRTGJ26o/6VTjQytUk8b8OxkwcD2I+79VPJlz7qss1+zE7h8GNIScFqXcDyJ/KqBYZFVA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC", + "optional": true + } + } +} diff --git a/packages/foliate-js/package.json b/packages/foliate-js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dc87561a7c0d230af7fc75fe4ffdd59c48c5a604 --- /dev/null +++ b/packages/foliate-js/package.json @@ -0,0 +1,50 @@ +{ + "name": "foliate-js", + "version": "0.0.0", + "description": "Render e-books in the browser", + "repository": { + "type": "git", + "url": "git+https://github.com/johnfactotum/foliate-js.git" + }, + "bugs": { + "url": "https://github.com/johnfactotum/foliate-js/issues" + }, + "homepage": "https://github.com/johnfactotum/foliate-js#readme", + "author": "John Factotum", + "license": "MIT", + "type": "module", + "exports": { + "./*.js": "./*.js" + }, + "devDependencies": { + "@eslint/js": "^9.9.1", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-terser": "^0.4.4", + "@zip.js/zip.js": "^2.7.52", + "fflate": "^0.8.2", + "fs-extra": "^11.2.0", + "globals": "^15.9.0", + "pdfjs-dist": "^5.4.530", + "rollup": "^4.22.4" + }, + "scripts": { + "build": "npx rollup -c" + }, + "keywords": [ + "ebook", + "reader", + "epub", + "cfi", + "mobi", + "azw", + "azw3", + "fb2", + "cbz", + "dictd", + "stardict", + "opds" + ], + "dependencies": { + "construct-style-sheets-polyfill": "^3.1.0" + } +} diff --git a/packages/foliate-js/paginator.js b/packages/foliate-js/paginator.js new file mode 100644 index 0000000000000000000000000000000000000000..f960a433be4c045a1e83b824d0c369e6accecb49 --- /dev/null +++ b/packages/foliate-js/paginator.js @@ -0,0 +1,1417 @@ +const wait = ms => new Promise(resolve => setTimeout(resolve, ms)) + +const debounce = (f, wait, immediate) => { + let timeout + return (...args) => { + const later = () => { + timeout = null + if (!immediate) f(...args) + } + const callNow = immediate && !timeout + if (timeout) clearTimeout(timeout) + timeout = setTimeout(later, wait) + if (callNow) f(...args) + } +} + +const lerp = (min, max, x) => x * (max - min) + min +const easeOutQuad = x => 1 - (1 - x) * (1 - x) +const animate = (a, b, duration, ease, render) => new Promise(resolve => { + let start + const step = now => { + if (document.hidden) { + render(lerp(a, b, 1)) + return resolve() + } + start ??= now + const fraction = Math.min(1, (now - start) / duration) + render(lerp(a, b, ease(fraction))) + if (fraction < 1) requestAnimationFrame(step) + else resolve() + } + if (document.hidden) { + render(lerp(a, b, 1)) + return resolve() + } + requestAnimationFrame(step) +}) + +// collapsed range doesn't return client rects sometimes (or always?) +// try make get a non-collapsed range or element +const uncollapse = range => { + if (!range?.collapsed) return range + const { endOffset, endContainer } = range + if (endContainer.nodeType === 1) { + const node = endContainer.childNodes[endOffset] + if (node?.nodeType === 1) return node + return endContainer + } + if (endOffset + 1 < endContainer.length) range.setEnd(endContainer, endOffset + 1) + else if (endOffset > 1) range.setStart(endContainer, endOffset - 1) + else return endContainer.parentNode + return range +} + +const makeRange = (doc, node, start, end = start) => { + const range = doc.createRange() + range.setStart(node, start) + range.setEnd(node, end) + return range +} + +// use binary search to find an offset value in a text node +const bisectNode = (doc, node, cb, start = 0, end = node.nodeValue.length) => { + if (end - start === 1) { + const result = cb(makeRange(doc, node, start), makeRange(doc, node, end)) + return result < 0 ? start : end + } + const mid = Math.floor(start + (end - start) / 2) + const result = cb(makeRange(doc, node, start, mid), makeRange(doc, node, mid, end)) + return result < 0 ? bisectNode(doc, node, cb, start, mid) + : result > 0 ? bisectNode(doc, node, cb, mid, end) : mid +} + +const { SHOW_ELEMENT, SHOW_TEXT, SHOW_CDATA_SECTION, + FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP } = NodeFilter + +const filter = SHOW_ELEMENT | SHOW_TEXT | SHOW_CDATA_SECTION + +// needed cause there seems to be a bug in `getBoundingClientRect()` in Firefox +// where it fails to include rects that have zero width and non-zero height +// (CSSOM spec says "rectangles [...] of which the height or width is not zero") +// which makes the visible range include an extra space at column boundaries +const getBoundingClientRect = target => { + let top = Infinity, right = -Infinity, left = Infinity, bottom = -Infinity + for (const rect of target.getClientRects()) { + left = Math.min(left, rect.left) + top = Math.min(top, rect.top) + right = Math.max(right, rect.right) + bottom = Math.max(bottom, rect.bottom) + } + return new DOMRect(left, top, right - left, bottom - top) +} + +const getVisibleRange = (doc, start, end, mapRect) => { + // first get all visible nodes + const acceptNode = node => { + const name = node.localName?.toLowerCase() + // ignore all scripts, styles, and their children + if (name === 'script' || name === 'style') return FILTER_REJECT + if (node.nodeType === 1) { + const { left, right } = mapRect(node.getBoundingClientRect()) + // no need to check child nodes if it's completely out of view + if (right < start || left > end) return FILTER_REJECT + // elements must be completely in view to be considered visible + // because you can't specify offsets for elements + if (left >= start && right <= end) return FILTER_ACCEPT + // TODO: it should probably allow elements that do not contain text + // because they can exceed the whole viewport in both directions + // especially in scrolled mode + } else { + // ignore empty text nodes + if (!node.nodeValue?.trim()) return FILTER_SKIP + // create range to get rect + const range = doc.createRange() + range.selectNodeContents(node) + const { left, right } = mapRect(range.getBoundingClientRect()) + // it's visible if any part of it is in view + if (right >= start && left <= end) return FILTER_ACCEPT + } + return FILTER_SKIP + } + const walker = doc.createTreeWalker(doc.body, filter, { acceptNode }) + const nodes = [] + for (let node = walker.nextNode(); node; node = walker.nextNode()) + nodes.push(node) + + // we're only interested in the first and last visible nodes + const from = nodes[0] ?? doc.body + const to = nodes[nodes.length - 1] ?? from + + // find the offset at which visibility changes + const startOffset = from.nodeType === 1 ? 0 + : bisectNode(doc, from, (a, b) => { + const p = mapRect(getBoundingClientRect(a)) + const q = mapRect(getBoundingClientRect(b)) + if (p.right < start && q.left > start) return 0 + return q.left > start ? -1 : 1 + }) + const endOffset = to.nodeType === 1 ? 0 + : bisectNode(doc, to, (a, b) => { + const p = mapRect(getBoundingClientRect(a)) + const q = mapRect(getBoundingClientRect(b)) + if (p.right < end && q.left > end) return 0 + return q.left > end ? -1 : 1 + }) + + const range = doc.createRange() + range.setStart(from, startOffset) + range.setEnd(to, endOffset) + return range +} + +const selectionIsBackward = sel => { + const range = document.createRange() + range.setStart(sel.anchorNode, sel.anchorOffset) + range.setEnd(sel.focusNode, sel.focusOffset) + return range.collapsed +} + +const setSelectionTo = (target, collapse) => { + let range + if (target.startContainer) range = target.cloneRange() + else if (target.nodeType) { + range = document.createRange() + range.selectNode(target) + } + if (range) { + const sel = range.startContainer.ownerDocument?.defaultView.getSelection() + if (sel) { + sel.removeAllRanges() + if (collapse === -1) range.collapse(true) + else if (collapse === 1) range.collapse() + sel.addRange(range) + } + } +} + +const getDirection = doc => { + const { defaultView } = doc + const { writingMode, direction } = defaultView.getComputedStyle(doc.body) + const vertical = writingMode === 'vertical-rl' + || writingMode === 'vertical-lr' + const rtl = doc.body.dir === 'rtl' + || direction === 'rtl' + || doc.documentElement.dir === 'rtl' + return { vertical, rtl } +} + +const getBackground = doc => { + const bodyStyle = doc.defaultView.getComputedStyle(doc.body) + return bodyStyle.backgroundColor === 'rgba(0, 0, 0, 0)' + && bodyStyle.backgroundImage === 'none' + ? doc.defaultView.getComputedStyle(doc.documentElement).background + : bodyStyle.background +} + +const makeMarginals = (length, part) => Array.from({ length }, () => { + const div = document.createElement('div') + const child = document.createElement('div') + div.append(child) + child.setAttribute('part', part) + return div +}) + +const setStyles = (el, styles) => { + const { style } = el + for (const [k, v] of Object.entries(styles)) style.setProperty(k, v) +} + +const setStylesImportant = (el, styles) => { + const { style } = el + for (const [k, v] of Object.entries(styles)) style.setProperty(k, v, 'important') +} + +class View { + #observer = new ResizeObserver(() => this.expand()) + #element = document.createElement('div') + #iframe = document.createElement('iframe') + #contentRange = document.createRange() + #overlayer + #vertical = false + #rtl = false + #column = true + #size + #layout = {} + constructor({ container, onExpand }) { + this.container = container + this.onExpand = onExpand + this.#iframe.setAttribute('part', 'filter') + this.#element.append(this.#iframe) + Object.assign(this.#element.style, { + boxSizing: 'content-box', + position: 'relative', + overflow: 'hidden', + flex: '0 0 auto', + width: '100%', height: '100%', + display: 'flex', + justifyContent: 'center', + alignItems: 'center', + }) + Object.assign(this.#iframe.style, { + overflow: 'hidden', + border: '0', + display: 'none', + width: '100%', height: '100%', + }) + // `allow-scripts` is needed for events because of WebKit bug + // https://bugs.webkit.org/show_bug.cgi?id=218086 + this.#iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts') + this.#iframe.setAttribute('scrolling', 'no') + } + get element() { + return this.#element + } + get document() { + return this.#iframe.contentDocument + } + async load(src, data, afterLoad, beforeRender) { + if (typeof src !== 'string') throw new Error(`${src} is not string`) + return new Promise(resolve => { + this.#iframe.addEventListener('load', () => { + const doc = this.document + afterLoad?.(doc) + + this.#iframe.setAttribute('aria-label', doc.title) + // it needs to be visible for Firefox to get computed style + this.#iframe.style.display = 'block' + const { vertical, rtl } = getDirection(doc) + this.docBackground = getBackground(doc) + doc.body.style.background = 'none' + const background = this.docBackground + this.#iframe.style.display = 'none' + + this.#vertical = vertical + this.#rtl = rtl + + this.#contentRange.selectNodeContents(doc.body) + const layout = beforeRender?.({ vertical, rtl, background }) + this.#iframe.style.display = 'block' + this.render(layout) + this.#observer.observe(doc.body) + + // the resize observer above doesn't work in Firefox + // (see https://bugzilla.mozilla.org/show_bug.cgi?id=1832939) + // until the bug is fixed we can at least account for font load + doc.fonts.ready.then(() => this.expand()) + + resolve() + }, { once: true }) + if (data) { + this.#iframe.srcdoc = data + } else { + this.#iframe.src = src + } + }) + } + render(layout) { + if (!layout || !this.document) return + this.#column = layout.flow !== 'scrolled' + this.#layout = layout + if (this.#column) this.columnize(layout) + else this.scrolled(layout) + } + scrolled({ marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }) { + const vertical = this.#vertical + const doc = this.document + setStylesImportant(doc.documentElement, { + 'box-sizing': 'border-box', + 'padding': vertical + ? `${marginTop * 1.5}px ${marginRight}px ${marginBottom * 1.5}px ${marginLeft}px` + : `${marginTop}px ${gap / 2 + marginRight / 2}px ${marginBottom}px ${gap / 2 + marginLeft / 2}px`, + 'column-width': 'auto', + 'height': 'auto', + 'width': 'auto', + }) + setStyles(doc.documentElement, { + '--page-margin-top': `${vertical ? marginTop * 1.5 : marginTop}px`, + '--page-margin-right': `${vertical ? marginRight : marginRight + gap /2}px`, + '--page-margin-bottom': `${vertical ? marginBottom * 1.5 : marginBottom}px`, + '--page-margin-left': `${vertical ? marginLeft : marginLeft + gap / 2}px`, + '--full-width': `${Math.trunc(window.innerWidth)}`, + '--full-height': `${Math.trunc(window.innerHeight)}`, + '--available-width': `${Math.trunc(Math.min(window.innerWidth, columnWidth) - marginLeft - marginRight - gap - 60)}`, + '--available-height': `${Math.trunc(window.innerHeight - marginTop - marginBottom)}`, + }) + setStylesImportant(doc.body, { + [vertical ? 'max-height' : 'max-width']: `${columnWidth}px`, + 'margin': 'auto', + }) + this.setImageSize() + this.expand() + } + columnize({ width, height, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }) { + const vertical = this.#vertical + this.#size = vertical ? height : width + + const doc = this.document + setStylesImportant(doc.documentElement, { + 'box-sizing': 'border-box', + 'column-width': `${Math.trunc(columnWidth)}px`, + 'column-gap': vertical ? `${(marginTop + marginBottom) * 1.5}px` : `${gap + marginRight / 2 + marginLeft / 2}px`, + 'column-fill': 'auto', + ...(vertical + ? { 'width': `${width}px` } + : { 'height': `${height}px` }), + 'padding': vertical + ? `${marginTop * 1.5}px ${marginRight}px ${marginBottom * 1.5}px ${marginLeft}px` + : `${marginTop}px ${gap / 2 + marginRight / 2}px ${marginBottom}px ${gap / 2 + marginLeft / 2}px`, + 'overflow': 'hidden', + // force wrap long words + 'overflow-wrap': 'break-word', + // reset some potentially problematic props + 'position': 'static', 'border': '0', 'margin': '0', + 'max-height': 'none', 'max-width': 'none', + 'min-height': 'none', 'min-width': 'none', + // fix glyph clipping in WebKit + '-webkit-line-box-contain': 'block glyphs replaced', + }) + setStyles(doc.documentElement, { + '--page-margin-top': `${vertical ? marginTop * 1.5 : marginTop}px`, + '--page-margin-right': `${vertical ? marginRight : marginRight / 2 + gap /2}px`, + '--page-margin-bottom': `${vertical ? marginBottom * 1.5 : marginBottom}px`, + '--page-margin-left': `${vertical ? marginLeft : marginLeft / 2 + gap / 2}px`, + '--full-width': `${Math.trunc(window.innerWidth)}`, + '--full-height': `${Math.trunc(window.innerHeight)}`, + '--available-width': `${Math.trunc(columnWidth - marginLeft - marginRight - gap)}`, + '--available-height': `${Math.trunc(height - marginTop - marginBottom)}`, + }) + setStylesImportant(doc.body, { + 'max-height': 'none', + 'max-width': 'none', + 'margin': '0', + }) + this.setImageSize() + this.expand() + } + setImageSize() { + const { width, height, marginTop, marginRight, marginBottom, marginLeft } = this.#layout + const vertical = this.#vertical + const doc = this.document + for (const el of doc.body.querySelectorAll('img, svg, video')) { + // preserve max size if they are already set + const { maxHeight, maxWidth } = doc.defaultView.getComputedStyle(el) + setStylesImportant(el, { + 'max-height': vertical + ? (maxHeight !== 'none' && maxHeight !== '0px' ? maxHeight : '100%') + : `${height - marginTop - marginBottom }px`, + 'max-width': vertical + ? `${width - marginLeft - marginRight }px` + : (maxWidth !== 'none' && maxWidth !== '0px' ? maxWidth : '100%'), + 'object-fit': 'contain', + 'page-break-inside': 'avoid', + 'break-inside': 'avoid', + 'box-sizing': 'border-box', + }) + } + } + get #zoom() { + // Safari does not zoom the client rects, while Chrome, Edge and Firefox does + if (/^((?!chrome|android).)*AppleWebKit/i.test(navigator.userAgent) && !window.chrome) { + return window.getComputedStyle(this.document.body).zoom || 1.0 + } + return 1.0 + } + expand() { + if (!this.document) return + const { documentElement } = this.document + if (this.#column) { + const side = this.#vertical ? 'height' : 'width' + const otherSide = this.#vertical ? 'width' : 'height' + const contentRect = this.#contentRange.getBoundingClientRect() + const rootRect = documentElement.getBoundingClientRect() + // offset caused by column break at the start of the page + // which seem to be supported only by WebKit and only for horizontal writing + const contentStart = this.#vertical ? 0 + : this.#rtl ? rootRect.right - contentRect.right : contentRect.left - rootRect.left + const contentSize = (contentStart + contentRect[side]) * this.#zoom + const pageCount = Math.ceil(contentSize / this.#size) + const expandedSize = pageCount * this.#size + this.#element.style.padding = '0' + this.#iframe.style[side] = `${expandedSize}px` + this.#element.style[side] = `${expandedSize + this.#size * 2}px` + this.#iframe.style[otherSide] = '100%' + this.#element.style[otherSide] = '100%' + documentElement.style[side] = `${this.#size}px` + if (this.#overlayer) { + this.#overlayer.element.style.margin = '0' + this.#overlayer.element.style.left = this.#vertical ? '0' : `${this.#size}px` + this.#overlayer.element.style.top = this.#vertical ? `${this.#size}px` : '0' + this.#overlayer.element.style[side] = `${expandedSize}px` + this.#overlayer.redraw() + } + } else { + const side = this.#vertical ? 'width' : 'height' + const otherSide = this.#vertical ? 'height' : 'width' + const contentSize = documentElement.getBoundingClientRect()[side] + const expandedSize = contentSize + this.#element.style.padding = '0' + this.#iframe.style[side] = `${expandedSize}px` + this.#element.style[side] = `${expandedSize}px` + this.#iframe.style[otherSide] = '100%' + this.#element.style[otherSide] = '100%' + if (this.#overlayer) { + this.#overlayer.element.style.margin = '0' + this.#overlayer.element.style.left = '0' + this.#overlayer.element.style.top = '0' + this.#overlayer.element.style[side] = `${expandedSize}px` + this.#overlayer.redraw() + } + } + this.onExpand() + } + set overlayer(overlayer) { + this.#overlayer = overlayer + this.#element.append(overlayer.element) + } + get overlayer() { + return this.#overlayer + } + #loupeEl = null + #loupeScaler = null + #loupeCursor = null + // Show a magnifier loupe inside the iframe document. + // winX/winY are in main-window (screen) coordinates. + showLoupe(winX, winY, { isVertical, color, radius }) { + const doc = this.document + if (!doc) return + + const frameRect = this.#iframe.getBoundingClientRect() + // Cursor in iframe-viewport coordinates. + const vpX = winX - frameRect.left + const vpY = winY - frameRect.top + + // Cursor in document coordinates (accounts for scroll). + const scrollX = doc.scrollingElement?.scrollLeft ?? 0 + const scrollY = doc.scrollingElement?.scrollTop ?? 0 + const docX = vpX + scrollX + const docY = vpY + scrollY + + const MAGNIFICATION = 1.2 + const diameter = radius * 2 + const MARGIN = 8 + + // Position loupe above the cursor (or to the left for vertical text). + const loupeOffset = radius + 16 + let loupeLeft = isVertical ? vpX - loupeOffset - diameter : vpX - radius + let loupeTop = isVertical ? vpY - radius : vpY - loupeOffset - diameter + loupeLeft = Math.max(MARGIN, Math.min(loupeLeft, frameRect.width - diameter - MARGIN)) + loupeTop = Math.max(MARGIN, Math.min(loupeTop, frameRect.height - diameter - MARGIN)) + + // CSS-transform math: map document point (docX, docY) to loupe centre (radius, radius). + // visual_pos = offset + coord × MAGNIFICATION = radius + // ⟹ offset = radius − coord × MAGNIFICATION + const offsetX = radius - docX * MAGNIFICATION + const offsetY = radius - docY * MAGNIFICATION + + // Build loupe DOM structure once; subsequent calls only update positions. + if (!this.#loupeEl || !this.#loupeEl.isConnected) { + this.#loupeEl = doc.createElement('div') + + // Clone the live body once — inside the iframe the epub's CSS + // variables, @font-face fonts, and styles apply automatically. + const bodyClone = doc.body.cloneNode(true) + + // Wrap the clone in a div that replicates documentElement's inline + // styles (column-width, column-gap, padding, height, etc.) so text + // flows with the same column layout as the original document. + const htmlWrapper = doc.createElement('div') + htmlWrapper.style.cssText = doc.documentElement.style.cssText + // expand() constrains documentElement's page-axis dimension to one + // page size (width for horizontal, height for vertical). Override + // with the full scroll dimension so all columns are rendered. + if (this.#vertical) + htmlWrapper.style.height = `${doc.documentElement.scrollHeight}px` + else + htmlWrapper.style.width = `${doc.documentElement.scrollWidth}px` + htmlWrapper.appendChild(bodyClone) + + this.#loupeScaler = doc.createElement('div') + this.#loupeScaler.appendChild(htmlWrapper) + + const cursorLen = Math.round(diameter * 0.24) + this.#loupeCursor = doc.createElement('div') + this.#loupeCursor.style.cssText = isVertical + ? `position:absolute;left:calc(50% - ${cursorLen / 2}px);top:50%;` + + `margin-top:-1px;width:${cursorLen}px;height:2px;background:${color};pointer-events:none;z-index:1;box-sizing:border-box;` + : `position:absolute;left:50%;top:calc(50% - ${cursorLen / 2}px);` + + `margin-left:-1px;width:2px;height:${cursorLen}px;background:${color};pointer-events:none;z-index:1;box-sizing:border-box;` + + this.#loupeEl.appendChild(this.#loupeScaler) + this.#loupeEl.appendChild(this.#loupeCursor) + doc.documentElement.appendChild(this.#loupeEl) + + // Static loupe shell styles (set once). + this.#loupeEl.style.cssText = ` + position: absolute; + width: ${diameter}px; + height: ${diameter}px; + border-radius: 50%; + overflow: hidden; + border: 2.5px solid ${color}; + box-shadow: 0 6px 24px rgba(0,0,0,0.28); + background-color: var(--theme-bg-color); + z-index: 9999; + pointer-events: none; + user-select: none; + box-sizing: border-box; + ` + } + + // Update only the dynamic position values (fast path on every move). + this.#loupeScaler.style.cssText = ` + position: absolute; + left: ${offsetX}px; + top: ${offsetY}px; + width: ${doc.documentElement.scrollWidth}px; + height: ${doc.documentElement.scrollHeight}px; + transform: scale(${MAGNIFICATION}); + transform-origin: 0 0; + pointer-events: none; + ` + this.#loupeEl.style.left = `${loupeLeft + scrollX}px` + this.#loupeEl.style.top = `${loupeTop + scrollY}px` + + // Cut a circular hole in the overlayer so highlights don't paint + // over the loupe. + if (this.#overlayer) { + const overlayerRect = this.#overlayer.element.getBoundingClientRect() + const dx = frameRect.left - overlayerRect.left + const dy = frameRect.top - overlayerRect.top + + const cx = loupeLeft + radius + dx + const cy = loupeTop + radius + dy + const maskRadius = radius + 3 + + this.#overlayer.setHole(cx, cy, maskRadius) + } + } + hideLoupe() { + if (this.#loupeEl) { + this.#loupeEl.remove() + this.#loupeEl = null + this.#loupeScaler = null + this.#loupeCursor = null + } + if (this.#overlayer) + this.#overlayer.clearHole() + } + destroy() { + if (this.document) this.#observer.unobserve(this.document.body) + } +} + +// NOTE: everything here assumes the so-called "negative scroll type" for RTL +export class Paginator extends HTMLElement { + static observedAttributes = [ + 'flow', 'gap', 'margin-top', 'margin-bottom', 'margin-left', 'margin-right', + 'max-inline-size', 'max-block-size', 'max-column-count', + ] + #root = this.attachShadow({ mode: 'open' }) + #observer = new ResizeObserver(() => this.render()) + #top + #background + #container + #header + #footer + #view + #vertical = false + #rtl = false + #marginTop = 0 + #marginBottom = 0 + #index = -1 + #anchor = 0 // anchor view to a fraction (0-1), Range, or Element + #justAnchored = false + #locked = false // while true, prevent any further navigation + #styles + #styleMap = new WeakMap() + #mediaQuery = matchMedia('(prefers-color-scheme: dark)') + #mediaQueryListener + #scrollBounds + #touchState + #touchScrolled + #lastVisibleRange + #scrollLocked = false + constructor() { + super() + this.#root.innerHTML = ` +
+
+ +
+ +
+ ` + + this.#top = this.#root.getElementById('top') + this.#background = this.#root.getElementById('background') + this.#container = this.#root.getElementById('container') + this.#header = this.#root.getElementById('header') + this.#footer = this.#root.getElementById('footer') + + this.#observer.observe(this.#container) + this.#container.addEventListener('scroll', () => this.dispatchEvent(new Event('scroll'))) + this.#container.addEventListener('scroll', debounce(() => { + if (this.scrolled) { + if (this.#justAnchored) this.#justAnchored = false + else this.#afterScroll('scroll') + } + }, 250)) + + const opts = { passive: false } + this.addEventListener('touchstart', this.#onTouchStart.bind(this), opts) + this.addEventListener('touchmove', this.#onTouchMove.bind(this), opts) + this.addEventListener('touchend', this.#onTouchEnd.bind(this)) + this.addEventListener('load', ({ detail: { doc } }) => { + doc.addEventListener('touchstart', this.#onTouchStart.bind(this), opts) + doc.addEventListener('touchmove', this.#onTouchMove.bind(this), opts) + doc.addEventListener('touchend', this.#onTouchEnd.bind(this)) + }) + + this.addEventListener('relocate', ({ detail }) => { + if (detail.reason === 'selection') setSelectionTo(this.#anchor, 0) + else if (detail.reason === 'navigation') { + if (this.#anchor === 1) setSelectionTo(detail.range, 1) + else if (typeof this.#anchor === 'number') + setSelectionTo(detail.range, -1) + else setSelectionTo(this.#anchor, -1) + } + }) + const checkPointerSelection = debounce((range, sel) => { + if (!sel.rangeCount) return + const selRange = sel.getRangeAt(0) + const backward = selectionIsBackward(sel) + if (backward && selRange.compareBoundaryPoints(Range.START_TO_START, range) < 0) + this.prev() + else if (!backward && selRange.compareBoundaryPoints(Range.END_TO_END, range) > 0) + this.next() + }, 700) + this.addEventListener('load', ({ detail: { doc } }) => { + let isPointerSelecting = false + doc.addEventListener('pointerdown', () => isPointerSelecting = true) + doc.addEventListener('pointerup', () => isPointerSelecting = false) + let isKeyboardSelecting = false + doc.addEventListener('keydown', () => isKeyboardSelecting = true) + doc.addEventListener('keyup', () => isKeyboardSelecting = false) + doc.addEventListener('selectionchange', () => { + if (this.scrolled) return + const range = this.#lastVisibleRange + if (!range) return + const sel = doc.getSelection() + if (!sel.rangeCount) return + // FIXME: this won't work on Android WebView, disable for now + if (!isPointerSelecting && isPointerSelecting && sel.type === 'Range') + checkPointerSelection(range, sel) + else if (isKeyboardSelecting) { + const selRange = sel.getRangeAt(0).cloneRange() + const backward = selectionIsBackward(sel) + if (!backward) selRange.collapse() + this.#scrollToAnchor(selRange) + } + }) + doc.addEventListener('focusin', e => { + if (this.scrolled) return null + if (this.#container && this.#container.contains(e.target)) { + // NOTE: `requestAnimationFrame` is needed in WebKit + requestAnimationFrame(() => this.#scrollToAnchor(e.target)) + } + }) + }) + + this.#mediaQueryListener = () => { + if (!this.#view) return + this.#replaceBackground(this.#view.docBackground, this.columnCount) + } + this.#mediaQuery.addEventListener('change', this.#mediaQueryListener) + } + attributeChangedCallback(name, _, value) { + switch (name) { + case 'flow': + this.render() + break + case 'gap': + case 'margin-top': + case 'margin-bottom': + case 'margin-left': + case 'margin-right': + case 'max-block-size': + case 'max-column-count': + this.#top.style.setProperty('--_' + name, value) + this.render() + break + case 'max-inline-size': + // needs explicit `render()` as it doesn't necessarily resize + this.#top.style.setProperty('--_' + name, value) + this.render() + break + } + } + open(book) { + this.bookDir = book.dir + this.sections = book.sections + book.transformTarget?.addEventListener('data', ({ detail }) => { + if (detail.type !== 'text/css') return + detail.data = Promise.resolve(detail.data).then(data => data + // unprefix as most of the props are (only) supported unprefixed + .replace(/([{\s;])-epub-/gi, '$1') + // `page-break-*` unsupported in columns; replace with `column-break-*` + .replace(/page-break-(after|before|inside)\s*:/gi, (_, x) => + `-webkit-column-break-${x}:`) + .replace(/break-(after|before|inside)\s*:\s*(avoid-)?page/gi, (_, x, y) => + `break-${x}: ${y ?? ''}column`)) + }) + } + #createView() { + if (this.#view) { + this.#view.destroy() + this.#container.removeChild(this.#view.element) + } + this.#view = new View({ + container: this, + onExpand: () => this.#scrollToAnchor(this.#anchor), + }) + this.#container.append(this.#view.element) + return this.#view + } + #replaceBackground(background, columnCount) { + const doc = this.#view?.document + if (!doc) return + const htmlStyle = doc.defaultView.getComputedStyle(doc.documentElement) + const themeBgColor = htmlStyle.getPropertyValue('--theme-bg-color') + const overrideColor = htmlStyle.getPropertyValue('--override-color') === 'true' + const bgTextureId = htmlStyle.getPropertyValue('--bg-texture-id') + const isDarkMode = htmlStyle.getPropertyValue('color-scheme') === 'dark' + if (background && themeBgColor) { + const parsedBackground = background.split(/\s(?=(?:url|rgb|hsl|#[0-9a-fA-F]{3,6}))/) + if ((isDarkMode || overrideColor) && (bgTextureId === 'none' || !bgTextureId)) { + parsedBackground[0] = themeBgColor + } + background = parsedBackground.join(' ') + } + this.#background.innerHTML = '' + this.#background.style.display = 'grid' + this.#background.style.gridTemplateColumns = `repeat(${columnCount}, 1fr)` + for (let i = 0; i < columnCount; i++) { + const column = document.createElement('div') + column.style.background = background + column.style.width = '100%' + column.style.height = '100%' + this.#background.appendChild(column) + } + } + #beforeRender({ vertical, rtl, background }) { + this.#vertical = vertical + this.#rtl = rtl + this.#top.classList.toggle('vertical', vertical) + + const { width, height } = this.#container.getBoundingClientRect() + const size = vertical ? height : width + + const style = getComputedStyle(this.#top) + const maxInlineSize = parseFloat(style.getPropertyValue('--_max-inline-size')) + const maxColumnCount = parseInt(style.getPropertyValue('--_max-column-count-spread')) + const marginTop = parseFloat(style.getPropertyValue('--_margin-top')) + const marginRight = parseFloat(style.getPropertyValue('--_margin-right')) + const marginBottom = parseFloat(style.getPropertyValue('--_margin-bottom')) + const marginLeft = parseFloat(style.getPropertyValue('--_margin-left')) + this.#marginTop = marginTop + this.#marginBottom = marginBottom + + const g = parseFloat(style.getPropertyValue('--_gap')) / 100 + // The gap will be a percentage of the #container, not the whole view. + // This means the outer padding will be bigger than the column gap. Let + // `a` be the gap percentage. The actual percentage for the column gap + // will be (1 - a) * a. Let us call this `b`. + // + // To make them the same, we start by shrinking the outer padding + // setting to `b`, but keep the column gap setting the same at `a`. Then + // the actual size for the column gap will be (1 - b) * a. Repeating the + // process again and again, we get the sequence + // x₁ = (1 - b) * a + // x₂ = (1 - x₁) * a + // ... + // which converges to x = (1 - x) * a. Solving for x, x = a / (1 + a). + // So to make the spacing even, we must shrink the outer padding with + // f(x) = x / (1 + x). + // But we want to keep the outer padding, and make the inner gap bigger. + // So we apply the inverse, f⁻¹ = -x / (x - 1) to the column gap. + const gap = -g / (g - 1) * size + + const flow = this.getAttribute('flow') + if (flow === 'scrolled') { + // FIXME: vertical-rl only, not -lr + this.setAttribute('dir', vertical ? 'rtl' : 'ltr') + this.#top.style.padding = '0' + const columnWidth = maxInlineSize + + this.heads = null + this.feet = null + this.#header.replaceChildren() + this.#footer.replaceChildren() + + this.columnCount = 1 + this.#replaceBackground(background, this.columnCount) + + return { flow, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth } + } + + const divisor = Math.min(maxColumnCount + (vertical ? 1 : 0), Math.ceil(Math.floor(size) / Math.floor(maxInlineSize))) + const columnWidth = vertical + ? (size / divisor - marginTop * 1.5 - marginBottom * 1.5) + : (size / divisor - gap - marginRight / 2 - marginLeft / 2) + this.setAttribute('dir', rtl ? 'rtl' : 'ltr') + + // set background to `doc` background + // this is needed because the iframe does not fill the whole element + this.columnCount = divisor + this.#replaceBackground(background, this.columnCount) + + const marginalDivisor = vertical + ? Math.min(2, Math.ceil(Math.floor(width) / Math.floor(maxInlineSize))) + : divisor + const marginalStyle = { + gridTemplateColumns: `repeat(${marginalDivisor}, 1fr)`, + gap: `${gap}px`, + direction: this.bookDir === 'rtl' ? 'rtl' : 'ltr', + } + Object.assign(this.#header.style, marginalStyle) + Object.assign(this.#footer.style, marginalStyle) + const heads = makeMarginals(marginalDivisor, 'head') + const feet = makeMarginals(marginalDivisor, 'foot') + this.heads = heads.map(el => el.children[0]) + this.feet = feet.map(el => el.children[0]) + this.#header.replaceChildren(...heads) + this.#footer.replaceChildren(...feet) + + return { height, width, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth } + } + render() { + if (!this.#view) return + this.#view.render(this.#beforeRender({ + vertical: this.#vertical, + rtl: this.#rtl, + background: this.#view.docBackground, + })) + this.#scrollToAnchor(this.#anchor) + } + get scrolled() { + return this.getAttribute('flow') === 'scrolled' + } + get scrollProp() { + const { scrolled } = this + return this.#vertical ? (scrolled ? 'scrollLeft' : 'scrollTop') + : scrolled ? 'scrollTop' : 'scrollLeft' + } + get sideProp() { + const { scrolled } = this + return this.#vertical ? (scrolled ? 'width' : 'height') + : scrolled ? 'height' : 'width' + } + get size() { + return this.#container.getBoundingClientRect()[this.sideProp] + } + get viewSize() { + if (!this.#view || !this.#view.element) return 0 + return this.#view.element.getBoundingClientRect()[this.sideProp] + } + get start() { + return Math.abs(this.#container[this.scrollProp]) + } + get end() { + return this.start + this.size + } + get page() { + return Math.floor(((this.start + this.end) / 2) / this.size) + } + get pages() { + return Math.round(this.viewSize / this.size) + } + get containerPosition() { + return this.#container[this.scrollProp] + } + get isOverflowX() { + return false + } + get isOverflowY() { + return false + } + set containerPosition(newVal) { + this.#container[this.scrollProp] = newVal + } + set scrollLocked(value) { + this.#scrollLocked = value + } + + scrollBy(dx, dy) { + const delta = this.#vertical ? dy : dx + const [offset, a, b] = this.#scrollBounds + const rtl = this.#rtl + const min = rtl ? offset - b : offset - a + const max = rtl ? offset + a : offset + b + this.containerPosition = Math.max(min, Math.min(max, + this.containerPosition + delta)) + } + + snap(vx, vy) { + const velocity = this.#vertical ? vy : vx + const horizontal = Math.abs(vx) * 2 > Math.abs(vy) + const orthogonal = this.#vertical ? !horizontal : horizontal + const [offset, a, b] = this.#scrollBounds + const { start, end, pages, size } = this + const min = Math.abs(offset) - a + const max = Math.abs(offset) + b + const d = velocity * (this.#rtl ? -size : size) * (orthogonal ? 1 : 0) + const page = Math.floor( + Math.max(min, Math.min(max, (start + end) / 2 + + (isNaN(d) ? 0 : d * 2))) / size) + + this.#scrollToPage(page, 'snap').then(() => { + const dir = page <= 0 ? -1 : page >= pages - 1 ? 1 : null + if (dir) return this.#goTo({ + index: this.#adjacentIndex(dir), + anchor: dir < 0 ? () => 1 : () => 0, + }) + }) + } + #onTouchStart(e) { + const touch = e.changedTouches[0] + this.#touchState = { + x: touch?.screenX, y: touch?.screenY, + t: e.timeStamp, + vx: 0, xy: 0, + dx: 0, dy: 0, + } + } + #onTouchMove(e) { + const state = this.#touchState + if (state.pinched) return + state.pinched = globalThis.visualViewport.scale > 1 + if (this.scrolled || state.pinched) return + if (e.touches.length > 1) { + if (this.#touchScrolled) e.preventDefault() + return + } + const doc = this.#view?.document + const selection = doc?.getSelection() + if (selection && selection.rangeCount > 0 && !selection.isCollapsed) { + return + } + const touch = e.changedTouches[0] + const isStylus = touch.touchType === 'stylus' + if (!isStylus) e.preventDefault() + if (this.#scrollLocked) return + const x = touch.screenX, y = touch.screenY + const dx = state.x - x, dy = state.y - y + const dt = e.timeStamp - state.t + state.x = x + state.y = y + state.t = e.timeStamp + state.vx = dx / dt + state.vy = dy / dt + state.dx += dx + state.dy += dy + this.#touchScrolled = true + if (!this.hasAttribute('animated') || this.hasAttribute('eink')) return + if (!this.#vertical && Math.abs(state.dx) >= Math.abs(state.dy) && !this.hasAttribute('eink') && (!isStylus || Math.abs(dx) > 1)) { + this.scrollBy(dx, 0) + } else if (this.#vertical && Math.abs(state.dx) < Math.abs(state.dy) && !this.hasAttribute('eink') && (!isStylus || Math.abs(dy) > 1)) { + this.scrollBy(0, dy) + } + } + #onTouchEnd() { + if (!this.#touchScrolled) return + this.#touchScrolled = false + if (this.scrolled) return + + // XXX: Firefox seems to report scale as 1... sometimes...? + // at this point I'm basically throwing `requestAnimationFrame` at + // anything that doesn't work + requestAnimationFrame(() => { + if (globalThis.visualViewport.scale === 1) + this.snap(this.#touchState.vx, this.#touchState.vy) + }) + } + // allows one to process rects as if they were LTR and horizontal + #getRectMapper() { + if (this.scrolled) { + const size = this.viewSize + const marginTop = this.#marginTop + const marginBottom = this.#marginBottom + return this.#vertical + ? ({ left, right }) => + ({ left: size - right - marginTop, right: size - left - marginBottom }) + : ({ top, bottom }) => ({ left: top - marginTop, right: bottom - marginBottom }) + } + const pxSize = this.pages * this.size + return this.#rtl + ? ({ left, right }) => + ({ left: pxSize - right, right: pxSize - left }) + : this.#vertical + ? ({ top, bottom }) => ({ left: top, right: bottom }) + : f => f + } + async #scrollToRect(rect, reason) { + if (this.scrolled) { + const offset = this.#getRectMapper()(rect).left - 4 + return this.#scrollTo(offset, reason) + } + const offset = this.#getRectMapper()(rect).left + return this.#scrollToPage(Math.floor(offset / this.size) + (this.#rtl ? -1 : 1), reason) + } + async #scrollTo(offset, reason, smooth) { + const { size } = this + if (this.containerPosition === offset) { + this.#scrollBounds = [offset, this.atStart ? 0 : size, this.atEnd ? 0 : size] + this.#afterScroll(reason) + return + } + // FIXME: vertical-rl only, not -lr + if (this.scrolled && this.#vertical) offset = -offset + if ((reason === 'snap' || smooth) && this.hasAttribute('animated') && !this.hasAttribute('eink')) return animate( + this.containerPosition, offset, 300, easeOutQuad, + x => this.containerPosition = x, + ).then(() => { + this.#scrollBounds = [offset, this.atStart ? 0 : size, this.atEnd ? 0 : size] + this.#afterScroll(reason) + }) + else { + this.containerPosition = offset + this.#scrollBounds = [offset, this.atStart ? 0 : size, this.atEnd ? 0 : size] + this.#afterScroll(reason) + } + } + async #scrollToPage(page, reason, smooth) { + const offset = this.size * (this.#rtl ? -page : page) + return this.#scrollTo(offset, reason, smooth) + } + async scrollToAnchor(anchor, select) { + return this.#scrollToAnchor(anchor, select ? 'selection' : 'navigation') + } + async #scrollToAnchor(anchor, reason = 'anchor') { + this.#anchor = anchor + const rects = uncollapse(anchor)?.getClientRects?.() + // if anchor is an element or a range + if (rects) { + // when the start of the range is immediately after a hyphen in the + // previous column, there is an extra zero width rect in that column + const rect = Array.from(rects) + .find(r => r.width > 0 && r.height > 0 && r.x >= 0 && r.y >= 0) || rects[0] + if (!rect) return + await this.#scrollToRect(rect, reason) + // focus the element when navigating with keyboard or screen reader + if (reason === 'navigation') { + let node = anchor.focus ? anchor : undefined + if (!node && anchor.startContainer) { + node = anchor.startContainer + if (node.nodeType === Node.TEXT_NODE) { + node = node.parentElement + } + } + if (node && node.focus) { + node.tabIndex = -1 + node.style.outline = 'none' + node.focus({ preventScroll: true }) + } + } + return + } + // if anchor is a fraction + if (this.scrolled) { + await this.#scrollTo(anchor * this.viewSize, reason) + return + } + const { pages } = this + if (!pages) return + const textPages = pages - 2 + const newPage = Math.round(anchor * (textPages - 1)) + await this.#scrollToPage(newPage + 1, reason) + } + #getVisibleRange() { + if (this.scrolled) return getVisibleRange(this.#view.document, + this.start, this.end, this.#getRectMapper()) + const size = this.#rtl ? -this.size : this.size + return getVisibleRange(this.#view.document, + this.start - size, this.end - size, this.#getRectMapper()) + } + #afterScroll(reason) { + const range = this.#getVisibleRange() + this.#lastVisibleRange = range + // don't set new anchor if relocation was to scroll to anchor + if (reason !== 'selection' && reason !== 'navigation' && reason !== 'anchor') + this.#anchor = range + else this.#justAnchored = true + + const index = this.#index + const detail = { reason, range, index } + if (this.scrolled) detail.fraction = this.start / this.viewSize + else if (this.pages > 0) { + const { page, pages } = this + this.#header.style.visibility = page > 1 ? 'visible' : 'hidden' + detail.fraction = (page - 1) / (pages - 2) + detail.size = 1 / (pages - 2) + } + this.dispatchEvent(new CustomEvent('relocate', { detail })) + } + async #display(promise) { + const { index, src, data, anchor, onLoad, select } = await promise + this.#index = index + const hasFocus = this.#view?.document?.hasFocus() + if (src) { + const view = this.#createView() + const afterLoad = doc => { + if (doc.head) { + const $styleBefore = doc.createElement('style') + doc.head.prepend($styleBefore) + const $style = doc.createElement('style') + doc.head.append($style) + this.#styleMap.set(doc, [$styleBefore, $style]) + } + onLoad?.({ doc, index }) + } + const beforeRender = this.#beforeRender.bind(this) + await view.load(src, data, afterLoad, beforeRender) + this.dispatchEvent(new CustomEvent('create-overlayer', { + detail: { + doc: view.document, index, + attach: overlayer => view.overlayer = overlayer, + }, + })) + this.#view = view + } + await this.scrollToAnchor((typeof anchor === 'function' + ? anchor(this.#view.document) : anchor) ?? 0, select) + if (hasFocus) this.focusView() + } + #canGoToIndex(index) { + return index >= 0 && index <= this.sections.length - 1 + } + async #goTo({ index, anchor, select }) { + if (index === this.#index) await this.#display({ index, anchor, select }) + else { + const oldIndex = this.#index + const onLoad = detail => { + this.sections[oldIndex]?.unload?.() + this.setStyles(this.#styles) + this.dispatchEvent(new CustomEvent('load', { detail })) + } + await this.#display(Promise.resolve(this.sections[index].load()) + .then(async src => { + const data = await this.sections[index].loadContent?.() + return { index, src, data, anchor, onLoad, select } + }).catch(e => { + console.warn(e) + console.warn(new Error(`Failed to load section ${index}`)) + return {} + })) + } + } + async goTo(target) { + if (this.#locked) return + const resolved = await target + if (this.#canGoToIndex(resolved.index)) return this.#goTo(resolved) + } + #scrollPrev(distance) { + if (!this.#view) return true + if (this.scrolled) { + if (this.start > 0) return this.#scrollTo( + Math.max(0, this.start - (distance ?? this.size)), null, true) + return !this.atStart + } + if (this.atStart) return + const page = this.page - 1 + return this.#scrollToPage(page, 'page', true).then(() => page <= 0) + } + #scrollNext(distance) { + if (!this.#view) return true + if (this.scrolled) { + if (this.viewSize - this.end > 2) return this.#scrollTo( + Math.min(this.viewSize, distance ? this.start + distance : this.end), null, true) + return !this.atEnd + } + if (this.atEnd) return + const page = this.page + 1 + const pages = this.pages + return this.#scrollToPage(page, 'page', true).then(() => page >= pages - 1) + } + get atStart() { + return this.#adjacentIndex(-1) == null && this.page <= 1 + } + get atEnd() { + return this.#adjacentIndex(1) == null && this.page >= this.pages - 2 + } + #adjacentIndex(dir) { + for (let index = this.#index + dir; this.#canGoToIndex(index); index += dir) + if (this.sections[index]?.linear !== 'no') return index + } + async #turnPage(dir, distance) { + if (this.#locked) return + this.#locked = true + const prev = dir === -1 + const shouldGo = await (prev ? this.#scrollPrev(distance) : this.#scrollNext(distance)) + if (shouldGo) await this.#goTo({ + index: this.#adjacentIndex(dir), + anchor: prev ? () => 1 : () => 0, + }) + if (shouldGo || !this.hasAttribute('animated')) await wait(100) + this.#locked = false + } + async prev(distance) { + return await this.#turnPage(-1, distance) + } + async next(distance) { + return await this.#turnPage(1, distance) + } + async pan(dx, dy) { + if (this.#locked) return + this.#locked = true + this.scrollBy(dx, dy) + this.#locked = false + } + prevSection() { + return this.goTo({ index: this.#adjacentIndex(-1) }) + } + nextSection() { + return this.goTo({ index: this.#adjacentIndex(1) }) + } + firstSection() { + const index = this.sections.findIndex(section => section.linear !== 'no') + return this.goTo({ index }) + } + lastSection() { + const index = this.sections.findLastIndex(section => section.linear !== 'no') + return this.goTo({ index }) + } + getContents() { + if (this.#view) return [{ + index: this.#index, + overlayer: this.#view.overlayer, + doc: this.#view.document, + }] + return [] + } + setStyles(styles) { + this.#styles = styles + const $$styles = this.#styleMap.get(this.#view?.document) + if (!$$styles) return + const [$beforeStyle, $style] = $$styles + if (Array.isArray(styles)) { + const [beforeStyle, style] = styles + $beforeStyle.textContent = beforeStyle + $style.textContent = style + } else $style.textContent = styles + + // NOTE: needs `requestAnimationFrame` in Chromium + requestAnimationFrame(() => { + this.#replaceBackground(this.#view.docBackground, this.columnCount) + }) + + // needed because the resize observer doesn't work in Firefox + this.#view?.document?.fonts?.ready?.then(() => this.#view.expand()) + } + focusView() { + this.#view.document.defaultView.focus() + } + showLoupe(winX, winY, { isVertical, color, radius }) { + this.#view?.showLoupe(winX, winY, { isVertical, color, radius }) + } + hideLoupe() { + this.#view?.hideLoupe() + } + destroy() { + this.#observer.unobserve(this) + this.#view.destroy() + this.#view = null + this.sections[this.#index]?.unload?.() + this.#mediaQuery.removeEventListener('change', this.#mediaQueryListener) + } +} + +customElements.define('foliate-paginator', Paginator) diff --git a/packages/foliate-js/pdf.js b/packages/foliate-js/pdf.js new file mode 100644 index 0000000000000000000000000000000000000000..c747b5384ea5fa9111b061648af464e35018590e --- /dev/null +++ b/packages/foliate-js/pdf.js @@ -0,0 +1,315 @@ +const pdfjsPath = path => `/vendor/pdfjs/${path}` + +import '@pdfjs/pdf.min.mjs' +const pdfjsLib = globalThis.pdfjsLib +pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsPath('pdf.worker.min.mjs') + +const fetchText = async url => await (await fetch(url)).text() + +let textLayerBuilderCSS = null +let annotationLayerBuilderCSS = null + +const render = async (page, doc, zoom) => { + if (!doc) return + const scale = zoom * devicePixelRatio + doc.documentElement.style.transform = `scale(${1 / devicePixelRatio})` + doc.documentElement.style.transformOrigin = 'top left' + doc.documentElement.style.setProperty('--total-scale-factor', scale) + doc.documentElement.style.setProperty('--user-unit', '1') + doc.documentElement.style.setProperty('--scale-round-x', '1px') + doc.documentElement.style.setProperty('--scale-round-y', '1px') + const viewport = page.getViewport({ scale }) + + // the canvas must be in the `PDFDocument`'s `ownerDocument` + // (`globalThis.document` by default); that's where the fonts are loaded + 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 canvasElement = doc.querySelector('#canvas') + if (!canvasElement) return + canvasElement.replaceChildren(doc.adoptNode(canvas)) + + const container = doc.querySelector('.textLayer') + const textLayer = new pdfjsLib.TextLayer({ + textContentSource: await page.streamTextContent(), + container, viewport, + }) + await textLayer.render() + + // hide "offscreen" canvases appended to document 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', + }) + + // fix text selection + // https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.js#L105-L107 + const endOfContent = document.createElement('div') + endOfContent.className = 'endOfContent' + container.append(endOfContent) + + let isPanning = false + let startX = 0 + let startY = 0 + let scrollLeft = 0 + let scrollTop = 0 + let scrollParent = null + + const findScrollableParent = (element) => { + let current = element + while (current) { + if (current !== document.body && current.nodeType === 1) { + const style = window.getComputedStyle(current) + const overflow = style.overflow + style.overflowY + style.overflowX + if (/(auto|scroll)/.test(overflow)) { + if (current.scrollHeight > current.clientHeight || + current.scrollWidth > current.clientWidth) { + return current + } + } + } + if (current.parentElement) { + current = current.parentElement + } else if (current.parentNode && current.parentNode.host) { + current = current.parentNode.host + } else { + break + } + } + return window + } + + container.onpointerdown = (e) => { + const selection = doc.getSelection() + const hasTextSelection = selection && selection.toString().length > 0 + + const elementUnderCursor = doc.elementFromPoint(e.clientX, e.clientY) + const hasTextUnderneath = elementUnderCursor && + (elementUnderCursor.tagName === 'SPAN' || elementUnderCursor.tagName === 'P') && + elementUnderCursor.textContent.trim().length > 0 + + if (!hasTextUnderneath && !hasTextSelection) { + isPanning = true + startX = e.screenX + startY = e.screenY + + const iframe = doc.defaultView.frameElement + if (iframe) { + scrollParent = findScrollableParent(iframe) + if (scrollParent === window) { + scrollLeft = window.scrollX || window.pageXOffset + scrollTop = window.scrollY || window.pageYOffset + } else { + scrollLeft = scrollParent.scrollLeft + scrollTop = scrollParent.scrollTop + } + container.style.cursor = 'grabbing' + } + } else { + container.classList.add('selecting') + } + } + + container.onpointermove = (e) => { + if (isPanning && scrollParent) { + e.preventDefault() + + const dx = e.screenX - startX + const dy = e.screenY - startY + + if (scrollParent === window) { + window.scrollTo(scrollLeft - dx, scrollTop - dy) + } else { + scrollParent.scrollLeft = scrollLeft - dx + scrollParent.scrollTop = scrollTop - dy + } + } + } + + container.onpointerup = () => { + if (isPanning) { + isPanning = false + scrollParent = null + container.style.cursor = 'grab' + } else { + container.classList.remove('selecting') + } + } + + container.onpointerleave = () => { + if (isPanning) { + isPanning = false + scrollParent = null + container.style.cursor = 'grab' + } + } + + doc.addEventListener('selectionchange', () => { + const selection = doc.getSelection() + if (selection && selection.toString().length > 0) { + container.style.cursor = 'text' + } else if (!isPanning) { + container.style.cursor = 'grab' + } + }) + + container.style.cursor = 'grab' + + const div = doc.querySelector('.annotationLayer') + const linkService = { + goToDestination: () => {}, + getDestinationHash: dest => JSON.stringify(dest), + addLinkAttributes: (link, url) => link.href = url, + } + await new pdfjsLib.AnnotationLayer({ page, viewport, div, linkService }).render({ + annotations: await page.getAnnotations(), + }) +} + +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)) + } + // https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.css + if (textLayerBuilderCSS == null) { + textLayerBuilderCSS = await fetchText(pdfjsPath('text_layer_builder.css')) + } + // https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/annotation_layer_builder.css + if (annotationLayerBuilderCSS == null) { + annotationLayerBuilderCSS = await fetchText(pdfjsPath('annotation_layer_builder.css')) + } + const data = ` + + + + + +
+
+
+ ` + const src = URL.createObjectURL(new Blob([data], { type: 'text/html' })) + const onZoom = ({ doc, scale }) => render(page, doc, scale) + return { src, data, onZoom } +} + +const makeTOCItem = async (item, pdf) => { + let pageIndex = undefined + + if (item.dest) { + try { + const dest = typeof item.dest === 'string' + ? await pdf.getDestination(item.dest) + : item.dest + if (dest?.[0]) { + pageIndex = await pdf.getPageIndex(dest[0]) + } + } catch (e) { + console.warn('Failed to get page index for TOC item:', item.title, e) + } + } + + return { + label: item.title, + href: item.dest ? JSON.stringify(item.dest) : '', + index: pageIndex, + subitems: item.items?.length + ? await Promise.all(item.items.map(i => makeTOCItem(i, pdf))) + : null, + } +} + +export const makePDF = async file => { + const transport = new pdfjsLib.PDFDataRangeTransport(file.size, []) + transport.requestDataRange = (begin, end) => { + file.slice(begin, end).arrayBuffer().then(chunk => { + transport.onDataRange(begin, chunk) + }) + } + const pdf = await pdfjsLib.getDocument({ + range: transport, + wasmUrl: pdfjsPath(''), + cMapUrl: pdfjsPath('cmaps/'), + standardFontDataUrl: pdfjsPath('standard_fonts/'), + isEvalSupported: false, + }).promise + + const book = { rendition: { layout: 'pre-paginated' } } + + const { metadata, info } = await pdf.getMetadata() ?? {} + // TODO: for better results, parse `metadata.getRaw()` + book.metadata = { + title: metadata?.get('dc:title') ?? info?.Title, + author: metadata?.get('dc:creator') ?? info?.Author, + contributor: metadata?.get('dc:contributor'), + description: metadata?.get('dc:description') ?? info?.Subject, + language: metadata?.get('dc:language'), + publisher: metadata?.get('dc:publisher'), + subject: metadata?.get('dc:subject'), + identifier: metadata?.get('dc:identifier'), + source: metadata?.get('dc:source'), + rights: metadata?.get('dc:rights'), + } + + const outline = await pdf.getOutline() + book.toc = outline ? await Promise.all(outline.map(item => makeTOCItem(item, pdf))) : null + + const cache = new Map() + book.sections = Array.from({ length: pdf.numPages }).map((_, i) => ({ + id: i, + load: async () => { + const cached = cache.get(i) + if (cached) return cached + const url = await renderPage(await pdf.getPage(i + 1)) + cache.set(i, url) + return url + }, + size: 1000, + })) + book.isExternal = uri => /^\w+:/i.test(uri) + book.resolveHref = async href => { + const parsed = JSON.parse(href) + const dest = typeof parsed === 'string' + ? await pdf.getDestination(parsed) : parsed + const index = await pdf.getPageIndex(dest[0]) + return { index } + } + book.splitTOCHref = async href => { + if (!href) return [null, null] + const parsed = JSON.parse(href) + const dest = typeof parsed === 'string' + ? await pdf.getDestination(parsed) : parsed + try { + const index = await pdf.getPageIndex(dest[0]) + return [index, null] + } catch (e) { + console.warn('Error getting page index for href', href) + return [null, null] + } + } + book.getTOCFragment = doc => doc.documentElement + book.getCover = async () => renderPage(await pdf.getPage(1), true) + book.destroy = () => pdf.destroy() + return book +} diff --git a/packages/foliate-js/progress.js b/packages/foliate-js/progress.js new file mode 100644 index 0000000000000000000000000000000000000000..f01c512c77c6eea45ce9b7745eafd44283b8bb26 --- /dev/null +++ b/packages/foliate-js/progress.js @@ -0,0 +1,113 @@ +// assign a unique ID for each TOC item +const assignIDs = toc => { + let id = 0 + const assignID = item => { + item.id = id++ + if (item.subitems) for (const subitem of item.subitems) assignID(subitem) + } + for (const item of toc) assignID(item) + return toc +} + +const flatten = items => items + .map(item => item.subitems?.length + ? [item, flatten(item.subitems)].flat() + : item) + .flat() + +export class TOCProgress { + async init({ toc, ids, splitHref, getFragment }) { + assignIDs(toc) + const items = flatten(toc) + const grouped = new Map() + for (const [i, item] of items.entries()) { + const [id, fragment] = await splitHref(item?.href) ?? [] + const value = { fragment, item } + if (grouped.has(id)) grouped.get(id).items.push(value) + else grouped.set(id, { prev: items[i - 1], items: [value] }) + } + const map = new Map() + for (const [i, id] of ids.entries()) { + if (grouped.has(id)) map.set(id, grouped.get(id)) + else map.set(id, map.get(ids[i - 1])) + } + this.ids = ids + this.map = map + this.getFragment = getFragment + } + getProgress(index, range) { + if (!this.ids) return + const id = this.ids[index] + const obj = this.map.get(id) + if (!obj) return null + const { prev, items } = obj + if (!items) return prev + if (!range || items.length === 1 && !items[0].fragment) return items[0].item + + const doc = range.startContainer.getRootNode() + for (const [i, { fragment }] of items.entries()) { + const el = this.getFragment(doc, fragment) + if (!el) continue + if (range.comparePoint(el, 0) > 0) + return (items[i - 1]?.item ?? prev) + } + return items[items.length - 1].item + } +} + +export class SectionProgress { + constructor(sections, sizePerLoc, sizePerTimeUnit) { + this.sizes = sections.map(s => s.linear != 'no' && s.size > 0 ? s.size : 0) + this.sizePerLoc = sizePerLoc + this.sizePerTimeUnit = sizePerTimeUnit + this.sizeTotal = this.sizes.reduce((a, b) => a + b, 0) + this.sectionFractions = this.#getSectionFractions() + } + #getSectionFractions() { + const { sizeTotal } = this + const results = [0] + let sum = 0 + for (const size of this.sizes) results.push((sum += size) / sizeTotal) + return results + } + // get progress given index of and fractions within a section + getProgress(index, fractionInSection, pageFraction = 0) { + const { sizes, sizePerLoc, sizePerTimeUnit, sizeTotal } = this + const sizeInSection = sizes[index] ?? 0 + const sizeBefore = sizes.slice(0, index).reduce((a, b) => a + b, 0) + const size = sizeBefore + fractionInSection * sizeInSection + const nextSize = size + pageFraction * sizeInSection + const remainingTotal = sizeTotal - size + const remainingSection = (1 - fractionInSection) * sizeInSection + return { + fraction: nextSize / sizeTotal, + section: { + current: index, + total: sizes.length, + }, + location: { + current: Math.floor(size / sizePerLoc), + next: Math.floor(nextSize / sizePerLoc), + total: Math.ceil(sizeTotal / sizePerLoc), + }, + time: { + section: remainingSection / sizePerTimeUnit, + total: remainingTotal / sizePerTimeUnit, + }, + } + } + // the inverse of `getProgress` + // get index of and fraction in section based on total fraction + getSection(fraction) { + if (fraction <= 0) return [0, 0] + if (fraction >= 1) return [this.sizes.length - 1, 1] + fraction = fraction + Number.EPSILON + const { sizeTotal } = this + let index = this.sectionFractions.findIndex(x => x > fraction) - 1 + if (index < 0) return [0, 0] + while (!this.sizes[index]) index++ + const fractionInSection = (fraction - this.sectionFractions[index]) + / (this.sizes[index] / sizeTotal) + return [index, fractionInSection] + } +} diff --git a/packages/foliate-js/quote-image.js b/packages/foliate-js/quote-image.js new file mode 100644 index 0000000000000000000000000000000000000000..1336c59ec62d9a54fe359e22b840a5f98f0fd041 --- /dev/null +++ b/packages/foliate-js/quote-image.js @@ -0,0 +1,86 @@ +const SVG_NS = 'http://www.w3.org/2000/svg' + +// bisect +const fit = (el, a = 1, b = 50) => { + const c = Math.floor(a + (b - a) / 2) + el.style.fontSize = `${c}px` + if (b - a === 1) return + if (el.scrollHeight > el.clientHeight + || el.scrollWidth > el.clientWidth) fit(el, a, c) + else fit(el, c, b) +} + +const width = 540 +const height = 540 +const pixelRatio = 2 + +const html = ` +
+ +
+
+
+
+
+ +
+
+ +
+
+
+
 
+
` + +// TODO: lang, vertical writing +customElements.define('foliate-quoteimage', class extends HTMLElement { + #root = this.attachShadow({ mode: 'closed' }) + constructor() { + super() + this.#root.innerHTML = html + } + async getBlob({ title, author, text }) { + this.#root.querySelector('#title').textContent = title + this.#root.querySelector('#author').textContent = author + this.#root.querySelector('#text').innerText = text + + fit(this.#root.querySelector('main')) + + const img = document.createElement('img') + return new Promise(resolve => { + img.onload = () => { + const canvas = document.createElement('canvas') + canvas.width = pixelRatio * width + canvas.height = pixelRatio * height + const ctx = canvas.getContext('2d') + ctx.drawImage(img, 0, 0, canvas.width, canvas.height) + canvas.toBlob(resolve) + } + const doc = document.implementation.createDocument(SVG_NS, 'svg') + doc.documentElement.setAttribute('viewBox', `0 0 ${width} ${height}`) + const obj = doc.createElementNS(SVG_NS, 'foreignObject') + obj.setAttribute('width', width) + obj.setAttribute('height', height) + obj.append(doc.importNode(this.#root.querySelector('main'), true)) + doc.documentElement.append(obj) + img.src = 'data:image/svg+xml;charset=utf-8,' + + new XMLSerializer().serializeToString(doc) + }) + } +}) diff --git a/packages/foliate-js/reader.html b/packages/foliate-js/reader.html new file mode 100644 index 0000000000000000000000000000000000000000..18d6b5b904a650cbb17a95fc642e72ec2882be08 --- /dev/null +++ b/packages/foliate-js/reader.html @@ -0,0 +1,304 @@ + + + + + +E-Book Reader + + +
+
+ +

Drop a book here!

+

Or to open it.

+
+
+ + +
+ + +
+ + diff --git a/packages/foliate-js/reader.js b/packages/foliate-js/reader.js new file mode 100644 index 0000000000000000000000000000000000000000..f62102c4cde677cc12582753cd5d11bf6ffe7c7d --- /dev/null +++ b/packages/foliate-js/reader.js @@ -0,0 +1,239 @@ +import './view.js' +import { createTOCView } from './ui/tree.js' +import { createMenu } from './ui/menu.js' +import { Overlayer } from './overlayer.js' + +const getCSS = ({ spacing, justify, hyphenate }) => ` + @namespace epub "http://www.idpf.org/2007/ops"; + html { + color-scheme: light dark; + } + /* https://github.com/whatwg/html/issues/5426 */ + @media (prefers-color-scheme: dark) { + a:link { + color: lightblue; + } + } + p, li, blockquote, dd { + line-height: ${spacing}; + text-align: ${justify ? 'justify' : 'start'}; + -webkit-hyphens: ${hyphenate ? 'auto' : 'manual'}; + hyphens: ${hyphenate ? 'auto' : 'manual'}; + -webkit-hyphenate-limit-before: 3; + -webkit-hyphenate-limit-after: 2; + -webkit-hyphenate-limit-lines: 2; + hanging-punctuation: allow-end last; + widows: 2; + } + /* prevent the above from overriding the align attribute */ + [align="left"] { text-align: left; } + [align="right"] { text-align: right; } + [align="center"] { text-align: center; } + [align="justify"] { text-align: justify; } + + pre { + white-space: pre-wrap !important; + } + aside[epub|type~="endnote"], + aside[epub|type~="footnote"], + aside[epub|type~="note"], + aside[epub|type~="rearnote"] { + display: none; + } +` + +const $ = document.querySelector.bind(document) + +const locales = 'en' +const percentFormat = new Intl.NumberFormat(locales, { style: 'percent' }) +const listFormat = new Intl.ListFormat(locales, { style: 'short', type: 'conjunction' }) + +const formatLanguageMap = x => { + if (!x) return '' + if (typeof x === 'string') return x + const keys = Object.keys(x) + return x[keys[0]] +} + +const formatOneContributor = contributor => typeof contributor === 'string' + ? contributor : formatLanguageMap(contributor?.name) + +const formatContributor = contributor => Array.isArray(contributor) + ? listFormat.format(contributor.map(formatOneContributor)) + : formatOneContributor(contributor) + +class Reader { + #tocView + style = { + spacing: 1.4, + justify: true, + hyphenate: true, + } + annotations = new Map() + annotationsByValue = new Map() + closeSideBar() { + $('#dimming-overlay').classList.remove('show') + $('#side-bar').classList.remove('show') + } + constructor() { + $('#side-bar-button').addEventListener('click', () => { + $('#dimming-overlay').classList.add('show') + $('#side-bar').classList.add('show') + }) + $('#dimming-overlay').addEventListener('click', () => this.closeSideBar()) + + const menu = createMenu([ + { + name: 'layout', + label: 'Layout', + type: 'radio', + items: [ + ['Paginated', 'paginated'], + ['Scrolled', 'scrolled'], + ], + onclick: value => { + this.view?.renderer.setAttribute('flow', value) + }, + }, + ]) + menu.element.classList.add('menu') + + $('#menu-button').append(menu.element) + $('#menu-button > button').addEventListener('click', () => + menu.element.classList.toggle('show')) + menu.groups.layout.select('paginated') + } + async open(file) { + this.view = document.createElement('foliate-view') + document.body.append(this.view) + await this.view.open(file) + this.view.addEventListener('load', this.#onLoad.bind(this)) + this.view.addEventListener('relocate', this.#onRelocate.bind(this)) + + const { book } = this.view + book.transformTarget?.addEventListener('data', ({ detail }) => { + detail.data = Promise.resolve(detail.data).catch(e => { + console.error(new Error(`Failed to load ${detail.name}`, { cause: e })) + return '' + }) + }) + this.view.renderer.setStyles?.(getCSS(this.style)) + this.view.renderer.next() + + $('#header-bar').style.visibility = 'visible' + $('#nav-bar').style.visibility = 'visible' + $('#left-button').addEventListener('click', () => this.view.goLeft()) + $('#right-button').addEventListener('click', () => this.view.goRight()) + + const slider = $('#progress-slider') + slider.dir = book.dir + slider.addEventListener('input', e => + this.view.goToFraction(parseFloat(e.target.value))) + for (const fraction of this.view.getSectionFractions()) { + const option = document.createElement('option') + option.value = fraction + $('#tick-marks').append(option) + } + + document.addEventListener('keydown', this.#handleKeydown.bind(this)) + + const title = formatLanguageMap(book.metadata?.title) || 'Untitled Book' + document.title = title + $('#side-bar-title').innerText = title + $('#side-bar-author').innerText = formatContributor(book.metadata?.author) + Promise.resolve(book.getCover?.())?.then(blob => + blob ? $('#side-bar-cover').src = URL.createObjectURL(blob) : null) + + const toc = book.toc + if (toc) { + this.#tocView = createTOCView(toc, href => { + this.view.goTo(href).catch(e => console.error(e)) + this.closeSideBar() + }) + $('#toc-view').append(this.#tocView.element) + } + + // load and show highlights embedded in the file by Calibre + const bookmarks = await book.getCalibreBookmarks?.() + if (bookmarks) { + const { fromCalibreHighlight } = await import('./epubcfi.js') + for (const obj of bookmarks) { + if (obj.type === 'highlight') { + const value = fromCalibreHighlight(obj) + const color = obj.style.which + const note = obj.notes + const annotation = { value, color, note } + const list = this.annotations.get(obj.spine_index) + if (list) list.push(annotation) + else this.annotations.set(obj.spine_index, [annotation]) + this.annotationsByValue.set(value, annotation) + } + } + this.view.addEventListener('create-overlay', e => { + const { index } = e.detail + const list = this.annotations.get(index) + if (list) for (const annotation of list) + this.view.addAnnotation(annotation) + }) + this.view.addEventListener('draw-annotation', e => { + const { draw, annotation } = e.detail + const { color } = annotation + draw(Overlayer.highlight, { color }) + }) + this.view.addEventListener('show-annotation', e => { + const annotation = this.annotationsByValue.get(e.detail.value) + if (annotation.note) alert(annotation.note) + }) + } + } + #handleKeydown(event) { + const k = event.key + if (k === 'ArrowLeft' || k === 'h') this.view.goLeft() + else if(k === 'ArrowRight' || k === 'l') this.view.goRight() + } + #onLoad({ detail: { doc } }) { + doc.addEventListener('keydown', this.#handleKeydown.bind(this)) + } + #onRelocate({ detail }) { + const { fraction, location, tocItem, pageItem } = detail + const percent = percentFormat.format(fraction) + const loc = pageItem + ? `Page ${pageItem.label}` + : `Loc ${location.current}` + const slider = $('#progress-slider') + slider.style.visibility = 'visible' + slider.value = fraction + slider.title = `${percent} · ${loc}` + if (tocItem?.href) this.#tocView?.setCurrentHref?.(tocItem.href) + } +} + +const open = async file => { + document.body.removeChild($('#drop-target')) + const reader = new Reader() + globalThis.reader = reader + await reader.open(file) +} + +const dragOverHandler = e => e.preventDefault() +const dropHandler = e => { + e.preventDefault() + const item = Array.from(e.dataTransfer.items) + .find(item => item.kind === 'file') + if (item) { + const entry = item.webkitGetAsEntry() + open(entry.isFile ? item.getAsFile() : entry).catch(e => console.error(e)) + } +} +const dropTarget = $('#drop-target') +dropTarget.addEventListener('drop', dropHandler) +dropTarget.addEventListener('dragover', dragOverHandler) + +$('#file-input').addEventListener('change', e => + open(e.target.files[0]).catch(e => console.error(e))) +$('#file-button').addEventListener('click', () => $('#file-input').click()) + +const params = new URLSearchParams(location.search) +const url = params.get('url') +if (url) open(url).catch(e => console.error(e)) +else dropTarget.style.visibility = 'visible' diff --git a/packages/foliate-js/rollup.config.js b/packages/foliate-js/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..9f0b02e46cb7261bb140014c58a863f11fd0b785 --- /dev/null +++ b/packages/foliate-js/rollup.config.js @@ -0,0 +1,32 @@ +import { nodeResolve } from '@rollup/plugin-node-resolve' +import terser from '@rollup/plugin-terser' +import { copy } from 'fs-extra' + +const copyPDFJS = () => ({ + name: 'copy-pdfjs', + async writeBundle() { + await copy('node_modules/pdfjs-dist/build/pdf.mjs', 'vendor/pdfjs/pdf.mjs') + await copy('node_modules/pdfjs-dist/build/pdf.mjs.map', 'vendor/pdfjs/pdf.mjs.map') + await copy('node_modules/pdfjs-dist/build/pdf.worker.mjs', 'vendor/pdfjs/pdf.worker.mjs') + await copy('node_modules/pdfjs-dist/build/pdf.worker.mjs.map', 'vendor/pdfjs/pdf.worker.mjs.map') + await copy('node_modules/pdfjs-dist/cmaps', 'vendor/pdfjs/cmaps') + await copy('node_modules/pdfjs-dist/standard_fonts', 'vendor/pdfjs/standard_fonts') + }, +}) + +export default [{ + input: 'rollup/fflate.js', + output: { + dir: 'vendor/', + format: 'esm', + }, + plugins: [nodeResolve(), terser()], +}, +{ + input: 'rollup/zip.js', + output: { + dir: 'vendor/', + format: 'esm', + }, + plugins: [nodeResolve(), terser(), copyPDFJS()], +}] diff --git a/packages/foliate-js/rollup/fflate.js b/packages/foliate-js/rollup/fflate.js new file mode 100644 index 0000000000000000000000000000000000000000..ab9af273b3b64170766cb10958fc3cbbbc5818e4 --- /dev/null +++ b/packages/foliate-js/rollup/fflate.js @@ -0,0 +1 @@ +export { unzlibSync } from 'fflate' diff --git a/packages/foliate-js/rollup/zip.js b/packages/foliate-js/rollup/zip.js new file mode 100644 index 0000000000000000000000000000000000000000..d27b239db6e3dd68efc349fc0e4b8bae68d0f4ff --- /dev/null +++ b/packages/foliate-js/rollup/zip.js @@ -0,0 +1 @@ +export { configure, ZipReader, BlobReader, TextWriter, BlobWriter } from '../node_modules/@zip.js/zip.js/lib/zip-no-worker-inflate.js' diff --git a/packages/foliate-js/search.js b/packages/foliate-js/search.js new file mode 100644 index 0000000000000000000000000000000000000000..a6f176ff7c2f8fbec7401120ae917d119257995f --- /dev/null +++ b/packages/foliate-js/search.js @@ -0,0 +1,130 @@ +// length for context in excerpts +const CONTEXT_LENGTH = 50 + +const normalizeWhitespace = str => str.replace(/\s+/g, ' ') + +const makeExcerpt = (strs, { startIndex, startOffset, endIndex, endOffset }) => { + const start = strs[startIndex] + const end = strs[endIndex] + const match = start === end + ? start.slice(startOffset, endOffset) + : start.slice(startOffset) + + strs.slice(start + 1, end).join('') + + end.slice(0, endOffset) + const trimmedStart = normalizeWhitespace(start.slice(0, startOffset)).trimStart() + const trimmedEnd = normalizeWhitespace(end.slice(endOffset)).trimEnd() + const ellipsisPre = trimmedStart.length < CONTEXT_LENGTH ? '' : '…' + const ellipsisPost = trimmedEnd.length < CONTEXT_LENGTH ? '' : '…' + const pre = `${ellipsisPre}${trimmedStart.slice(-CONTEXT_LENGTH)}` + const post = `${trimmedEnd.slice(0, CONTEXT_LENGTH)}${ellipsisPost}` + return { pre, match, post } +} + +const simpleSearch = function* (strs, query, options = {}) { + const { locales = 'en', sensitivity } = options + const matchCase = sensitivity === 'variant' + const haystack = strs.join('') + const lowerHaystack = matchCase ? haystack : haystack.toLocaleLowerCase(locales) + const needle = matchCase ? query : query.toLocaleLowerCase(locales) + const needleLength = needle.length + let index = -1 + let strIndex = -1 + let sum = 0 + do { + index = lowerHaystack.indexOf(needle, index + 1) + if (index > -1) { + while (sum <= index) sum += strs[++strIndex].length + const startIndex = strIndex + const startOffset = index - (sum - strs[strIndex].length) + const end = index + needleLength + while (sum <= end) sum += strs[++strIndex].length + const endIndex = strIndex + const endOffset = end - (sum - strs[strIndex].length) + const range = { startIndex, startOffset, endIndex, endOffset } + yield { range, excerpt: makeExcerpt(strs, range) } + } + } while (index > -1) +} + +const segmenterSearch = function* (strs, query, options = {}) { + const { locales = 'en', granularity = 'word', sensitivity = 'base' } = options + let segmenter, collator + try { + segmenter = new Intl.Segmenter(locales, { usage: 'search', granularity }) + collator = new Intl.Collator(locales, { sensitivity }) + } catch (e) { + console.warn(e) + segmenter = new Intl.Segmenter('en', { usage: 'search', granularity }) + collator = new Intl.Collator('en', { sensitivity }) + } + const queryLength = Array.from(segmenter.segment(query)).length + + const substrArr = [] + let strIndex = 0 + let segments = segmenter.segment(strs[strIndex])[Symbol.iterator]() + main: while (strIndex < strs.length) { + while (substrArr.length < queryLength) { + const { done, value } = segments.next() + if (done) { + // the current string is exhausted + // move on to the next string + strIndex++ + if (strIndex < strs.length) { + segments = segmenter.segment(strs[strIndex])[Symbol.iterator]() + continue + } else break main + } + const { index, segment } = value + // ignore formatting characters + if (!/[^\p{Format}]/u.test(segment)) continue + // normalize whitespace + if (/\s/u.test(segment)) { + if (!/\s/u.test(substrArr[substrArr.length - 1]?.segment)) + substrArr.push({ strIndex, index, segment: ' ' }) + continue + } + value.strIndex = strIndex + substrArr.push(value) + } + const substr = substrArr.map(x => x.segment).join('') + if (collator.compare(query, substr) === 0) { + const endIndex = strIndex + const lastSeg = substrArr[substrArr.length - 1] + const endOffset = lastSeg.index + lastSeg.segment.length + const startIndex = substrArr[0].strIndex + const startOffset = substrArr[0].index + const range = { startIndex, startOffset, endIndex, endOffset } + yield { range, excerpt: makeExcerpt(strs, range) } + } + substrArr.shift() + } +} + +export const search = (strs, query, options) => { + const { granularity = 'grapheme', sensitivity = 'base' } = options + if (!Intl?.Segmenter || granularity === 'grapheme' + && (sensitivity === 'variant' || sensitivity === 'accent')) + return simpleSearch(strs, query, options) + return segmenterSearch(strs, query, options) +} + +export const searchMatcher = (textWalker, opts) => { + const { defaultLocale, matchCase, matchDiacritics, matchWholeWords, acceptNode } = opts + return function* (doc, query) { + const iter = textWalker(doc, function* (strs, makeRange) { + for (const result of search(strs, query, { + locales: doc.body.lang || doc.documentElement.lang || defaultLocale || 'en', + granularity: matchWholeWords ? 'word' : 'grapheme', + sensitivity: matchDiacritics && matchCase ? 'variant' + : matchDiacritics && !matchCase ? 'accent' + : !matchDiacritics && matchCase ? 'case' + : 'base', + })) { + const { startIndex, startOffset, endIndex, endOffset } = result.range + result.range = makeRange(startIndex, startOffset, endIndex, endOffset) + yield result + } + }, acceptNode) + for (const result of iter) yield result + } +} diff --git a/packages/foliate-js/tests/epubcfi-tests.js b/packages/foliate-js/tests/epubcfi-tests.js new file mode 100644 index 0000000000000000000000000000000000000000..84d4d200de41fdb1ff4b652ed5cb32e478ac1531 --- /dev/null +++ b/packages/foliate-js/tests/epubcfi-tests.js @@ -0,0 +1,236 @@ +import * as CFI from '../epubcfi.js' + +const parser = new DOMParser() +const XML = str => parser.parseFromString(str, 'application/xml') +const XHTML = str => parser.parseFromString(str, 'application/xhtml+xml') + +{ + // example from EPUB CFI spec + const opf = XML(` + + + + + + + + en + + + + + + + + + + + + + + + + + + + +`) + + const a = opf.getElementById('chap01ref') + const b = CFI.toElement(opf, CFI.parse('/6/4[chap01ref]')[0]) + const c = CFI.toElement(opf, CFI.parse('/6/4')[0]) + console.assert(a === b) + console.assert(a === c) +} + +{ + // example from EPUB CFI spec + const page = XHTML(` + + + + + +

+

+

+

+

xxxyyy0123456789

+

+

+ … +

+

+ +`) + + // the exact same page with some text nodes removed, CDATA & comment added, + // and characters changed to entities + const page2 = XHTML(` + + + + +

+

xxxyyy4589

+

+

+ … +

+

+ +`) + + // the exact same page with nodes are to be ignored + const page3 = XHTML(` + + + + +

This is ignored!

+
+

Also ignored

+

+

xxxyyyNote: we put ignored text in this span but not the other ones because although the CFI library should ignore them, they won't be ignored by DOM Ranges, which will break the tests.0123456789

+

+

+ … +

+

+
+ +`) + + const filter = node => node.nodeType !== 1 ? NodeFilter.FILTER_ACCEPT + : node.matches('.reject') ? NodeFilter.FILTER_REJECT + : node.matches('.skip') ? NodeFilter.FILTER_SKIP + : NodeFilter.FILTER_ACCEPT + + const test = (page, filter) => { + for (const cfi of [ + '/4[body01]/10[para05]/3:10', + '/4[body01]/16[svgimg]', + '/4[body01]/10[para05]/1:0', + '/4[body01]/10[para05]/2/1:0', + '/4[body01]/10[para05]/2/1:3', + ]) { + const range = CFI.toRange(page, CFI.parse(cfi), filter) + const a = CFI.fromRange(range, filter) + const b = `epubcfi(${cfi})` + console.assert(a === b, `expected ${b}, got ${a}`) + } + for (let i = 0; i < 10; i++) { + const cfi = `/4/10,/3:${i},/3:${i+1}` + const range = CFI.toRange(page, CFI.parse(cfi), filter) + const n = `${i}` + console.assert(range.toString() === n, `expected ${n}, got ${range}`) + } + } + test(page) + test(page2) + + test(page, filter) + test(page2, filter) + test(page3, filter) +} + +{ + // special characters in ID assertions + const opf = XML(` + + + + + + + + + + +`) + + const a = opf.getElementById('chap0]!/1ref^') + const b = CFI.toElement(opf, CFI.parse('/6/4[chap0^]!/1ref^^]')[0]) + console.assert(a === b) + + const page = XHTML(` + + + + +

+

+

+

+

xxxyyy0123456789

+

+

+ … +

+

+ +`) + + for (const cfi of [ + '/4[body0^]!/1^^]/10[para^]/0^,/5]/3:10', + '/4[body0^]!/1^^]/16[s^]^[vgimg]', + '/4[body0^]!/1^^]/10[para^]/0^,/5]/1:0', + '/4[body0^]!/1^^]/10[para^]/0^,/5]/2/1:0', + '/4[body0^]!/1^^]/10[para^]/0^,/5]/2/1:3', + ]) { + const range = CFI.toRange(page, CFI.parse(cfi)) + const a = CFI.fromRange(range) + const b = `epubcfi(${cfi})` + console.assert(a === b, `expected ${b}, got ${a}`) + } + for (let i = 0; i < 10; i++) { + const cfi = `/4[body0^]!/1^^]/10[para^]/0^,^/5],/3:${i},/3:${i+1}` + const range = CFI.toRange(page, CFI.parse(cfi)) + const n = `${i}` + console.assert(range.toString() === n, `expected ${n}, got ${range}`) + } +} + +{ + for (const [a, b, c] of [ + ['/6/4!/10', '/6/4!/10', 0], + ['/6/4!/2/3:0', '/6/4!/2', 1], + ['/6/4!/2/4/6/8/10/3:0', '/6/4!/4', -1], + [ + '/6/4[chap0^]!/1ref^^]!/4[body01^^]/10[para^]^,05^^]', + '/6/4!/4/10', + 0, + ], + [ + '/6/4[chap0^]!/1ref^^]!/4[body01^^],/10[para^]^,05^^],/15:10[foo^]]', + '/6/4!/4/12', + -1, + ], + ['/6/4', '/6/4!/2', -1], + ['/6/4!/2', '/6/4!/2!/2', -1], + ]) { + const x = CFI.compare(a, b) + console.assert(x === c, `compare ${a} and ${b}, expected ${c}, got ${x}`) + } +} diff --git a/packages/foliate-js/tests/tests.html b/packages/foliate-js/tests/tests.html new file mode 100644 index 0000000000000000000000000000000000000000..2652dab98f49d47c19460fdb563be27b416d194a --- /dev/null +++ b/packages/foliate-js/tests/tests.html @@ -0,0 +1,5 @@ + + + + + diff --git a/packages/foliate-js/tests/tests.js b/packages/foliate-js/tests/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..c0227f1d27611725b7c539aba5d2107c9c2cd8c3 --- /dev/null +++ b/packages/foliate-js/tests/tests.js @@ -0,0 +1 @@ +import './epubcfi-tests.js' diff --git a/packages/foliate-js/text-walker.js b/packages/foliate-js/text-walker.js new file mode 100644 index 0000000000000000000000000000000000000000..c1249b79c6beca30e8f4d27e96cd05fa869ef67b --- /dev/null +++ b/packages/foliate-js/text-walker.js @@ -0,0 +1,43 @@ +const walkRange = (range, walker) => { + const nodes = [] + for (let node = walker.currentNode; node; node = walker.nextNode()) { + const compare = range.comparePoint(node, 0) + if (compare === 0) nodes.push(node) + else if (compare > 0) break + } + return nodes +} + +const walkDocument = (_, walker) => { + const nodes = [] + for (let node = walker.nextNode(); node; node = walker.nextNode()) + nodes.push(node) + return nodes +} + +const filter = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT + | NodeFilter.SHOW_CDATA_SECTION + +const acceptNode = node => { + if (node.nodeType === 1) { + const name = node.tagName.toLowerCase() + if (name === 'script' || name === 'style') return NodeFilter.FILTER_REJECT + return NodeFilter.FILTER_SKIP + } + return NodeFilter.FILTER_ACCEPT +} + +export const textWalker = function* (x, func, filterFunc) { + const root = x.commonAncestorContainer ?? x.body ?? x + const walker = document.createTreeWalker(root, filter, { acceptNode: filterFunc || acceptNode }) + const walk = x.commonAncestorContainer ? walkRange : walkDocument + const nodes = walk(x, walker) + const strs = nodes.map(node => node.nodeValue ?? '') + const makeRange = (startIndex, startOffset, endIndex, endOffset) => { + const range = document.createRange() + range.setStart(nodes[startIndex], startOffset) + range.setEnd(nodes[endIndex], endOffset) + return range + } + for (const match of func(strs, makeRange)) yield match +} diff --git a/packages/foliate-js/tts.js b/packages/foliate-js/tts.js new file mode 100644 index 0000000000000000000000000000000000000000..ca75cc0505b7d14c551130bad6e8c4b21673cc9d --- /dev/null +++ b/packages/foliate-js/tts.js @@ -0,0 +1,377 @@ +const NS = { + XML: 'http://www.w3.org/XML/1998/namespace', + SSML: 'http://www.w3.org/2001/10/synthesis', +} + +const blockTags = new Set([ + 'article', 'aside', 'audio', 'blockquote', 'caption', + 'details', 'dialog', 'div', 'dl', 'dt', 'dd', + 'figure', 'footer', 'form', 'figcaption', + 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', + 'main', 'math', 'nav', 'ol', 'p', 'pre', 'section', 'tr', +]) + +const getLang = el => { + const x = el.lang || el?.getAttributeNS?.(NS.XML, 'lang') + return x ? x : el.parentElement ? getLang(el.parentElement) : null +} + +const getAlphabet = el => { + const x = el?.getAttributeNS?.(NS.XML, 'lang') + return x ? x : el.parentElement ? getAlphabet(el.parentElement) : null +} + +const getSegmenter = (lang = 'en', granularity = 'word') => { + const segmenter = new Intl.Segmenter(lang, { granularity }) + const granularityIsWord = granularity === 'word' + return function* (strs, makeRange) { + const str = strs.join('').replace(/\r\n/g, ' ').replace(/\r/g, ' ').replace(/\n/g, ' ') + let name = 0 + let strIndex = -1 + let sum = 0 + const rawSegments = Array.from(segmenter.segment(str)) + const mergedSegments = [] + for (let i = 0; i < rawSegments.length; i++) { + const current = rawSegments[i] + const next = rawSegments[i + 1] + const segment = current.segment.trim() + const nextSegment = next?.segment?.trim() + const endsWithAbbr = /(?:^|\s)([A-Z][a-z]{1,5})\.$/.test(segment) + const nextStartsWithCapital = /^[A-Z]/.test(nextSegment || '') + if ((endsWithAbbr && nextStartsWithCapital) || segment.length <= 3) { + const mergedSegment = { + index: current.index, + segment: current.segment + (next?.segment || ''), + isWordLike: true, + } + mergedSegments.push(mergedSegment) + i++ + } else { + mergedSegments.push(current) + } + } + for (const { index, segment, isWordLike } of mergedSegments) { + if (granularityIsWord && !isWordLike) continue + while (sum <= index) sum += strs[++strIndex].length + const startIndex = strIndex + const startOffset = index - (sum - strs[strIndex].length) + const end = index + segment.length - 1 + if (end < str.length) while (sum <= end) sum += strs[++strIndex].length + const endIndex = strIndex + const endOffset = end - (sum - strs[strIndex].length) + 1 + yield [(name++).toString(), + makeRange(startIndex, startOffset, endIndex, endOffset)] + } + } +} + +const fragmentToSSML = (fragment, nodeFilter, inherited) => { + const ssml = document.implementation.createDocument(NS.SSML, 'speak') + const { lang } = inherited + if (lang) ssml.documentElement.setAttributeNS(NS.XML, 'lang', lang) + + const convert = (node, parent, inheritedAlphabet) => { + if (!node) return + if (node.nodeType === 3) return ssml.createTextNode(node.textContent) + if (node.nodeType === 4) return ssml.createCDATASection(node.textContent) + if (node.nodeType !== 1 && node.nodeType !== 11) return + if (nodeFilter && nodeFilter(node) === NodeFilter.FILTER_REJECT) return + + let el + const nodeName = node.nodeName.toLowerCase() + if (nodeName === 'foliate-mark') { + el = ssml.createElementNS(NS.SSML, 'mark') + el.setAttribute('name', node.dataset.name) + } + else if (nodeName === 'br') + el = ssml.createElementNS(NS.SSML, 'break') + else if (nodeName === 'em' || nodeName === 'strong') + el = ssml.createElementNS(NS.SSML, 'emphasis') + + const lang = node.lang || node.getAttributeNS?.(NS.XML, 'lang') + if (lang) { + if (!el) el = ssml.createElementNS(NS.SSML, 'lang') + el.setAttributeNS(NS.XML, 'lang', lang) + } + + const alphabet = node.getAttributeNS?.(NS.SSML, 'alphabet') || inheritedAlphabet + if (!el) { + const ph = node.getAttributeNS?.(NS.SSML, 'ph') + if (ph) { + el = ssml.createElementNS(NS.SSML, 'phoneme') + if (alphabet) el.setAttribute('alphabet', alphabet) + el.setAttribute('ph', ph) + } + } + + if (!el) el = parent + + let child = node.firstChild + while (child) { + const childEl = convert(child, el, alphabet) + if (childEl && el !== childEl) el.append(childEl) + child = child.nextSibling + } + return el + } + convert(fragment, ssml.documentElement, inherited.alphabet) + return ssml +} + +const getFragmentWithMarks = (range, textWalker, nodeFilter, granularity) => { + const lang = getLang(range.commonAncestorContainer) + const alphabet = getAlphabet(range.commonAncestorContainer) + + const segmenter = getSegmenter(lang, granularity) + const fragment = range.cloneContents() + + // we need ranges on both the original document (for highlighting) + // and the document fragment (for inserting marks) + // so unfortunately need to do it twice, as you can't copy the ranges + const entries = [...textWalker(range, segmenter, nodeFilter)] + const fragmentEntries = [...textWalker(fragment, segmenter, nodeFilter)] + + for (const [name, range] of fragmentEntries) { + const mark = document.createElement('foliate-mark') + mark.dataset.name = name + range.insertNode(mark) + } + const ssml = fragmentToSSML(fragment, nodeFilter, { lang, alphabet }) + return { entries, ssml } +} + +const rangeIsEmpty = range => !range.toString().trim() + +function* getBlocks(doc) { + let last + const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT) + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + const name = node.tagName.toLowerCase() + if (blockTags.has(name)) { + if (last) { + last.setEndBefore(node) + if (!rangeIsEmpty(last)) yield last + } + last = doc.createRange() + last.setStart(node, 0) + } + } + if (!last) { + last = doc.createRange() + last.setStart(doc.body.firstChild ?? doc.body, 0) + } + last.setEndAfter(doc.body.lastChild ?? doc.body) + if (!rangeIsEmpty(last)) yield last +} + +class ListIterator { + #arr = [] + #iter + #index = -1 + #f + constructor(iter, f = x => x) { + this.#iter = iter + this.#f = f + } + current() { + if (this.#arr[this.#index]) return this.#f(this.#arr[this.#index]) + } + first() { + const newIndex = 0 + if (this.#arr[newIndex]) { + this.#index = newIndex + return this.#f(this.#arr[newIndex]) + } + } + prev() { + const newIndex = this.#index - 1 + if (this.#arr[newIndex]) { + this.#index = newIndex + return this.#f(this.#arr[newIndex]) + } + } + next() { + const newIndex = this.#index + 1 + if (this.#arr[newIndex]) { + this.#index = newIndex + return this.#f(this.#arr[newIndex]) + } + while (true) { + const { done, value } = this.#iter.next() + if (done) break + this.#arr.push(value) + if (this.#arr[newIndex]) { + this.#index = newIndex + return this.#f(this.#arr[newIndex]) + } + } + } + find(f) { + const index = this.#arr.findIndex(x => f(x)) + if (index > -1) { + this.#index = index + return this.#f(this.#arr[index]) + } + while (true) { + const { done, value } = this.#iter.next() + if (done) break + this.#arr.push(value) + if (f(value)) { + this.#index = this.#arr.length - 1 + return this.#f(value) + } + } + } +} + +export class TTS { + #list + #ranges + #lastMark + #serializer = new XMLSerializer() + constructor(doc, textWalker, nodeFilter, highlight, granularity) { + this.doc = doc + this.highlight = highlight + this.#list = new ListIterator(getBlocks(doc), range => { + const { entries, ssml } = getFragmentWithMarks(range, textWalker, nodeFilter, granularity) + this.#ranges = new Map(entries) + return [ssml, range] + }) + } + #getMarkElement(doc, mark) { + if (!mark) return null + return doc.querySelector(`mark[name="${CSS.escape(mark)}"`) + } + #speak(doc, getNode) { + if (!doc) return + if (!getNode) return this.#serializer.serializeToString(doc) + const ssml = document.implementation.createDocument(NS.SSML, 'speak') + ssml.documentElement.replaceWith(ssml.importNode(doc.documentElement, true)) + let node = getNode(ssml)?.previousSibling + while (node) { + const next = node.previousSibling ?? node.parentNode?.previousSibling + node.parentNode.removeChild(node) + node = next + } + const ssmlStr = this.#serializer.serializeToString(ssml) + return ssmlStr + } + start() { + this.#lastMark = null + const [doc] = this.#list.first() ?? [] + if (!doc) return this.next() + return this.#speak(doc, ssml => this.#getMarkElement(ssml, this.#lastMark)) + } + resume() { + const [doc] = this.#list.current() ?? [] + if (!doc) return this.next() + return this.#speak(doc, ssml => this.#getMarkElement(ssml, this.#lastMark)) + } + prev(paused) { + this.#lastMark = null + const [doc, range] = this.#list.prev() ?? [] + if (paused && range) this.highlight(range.cloneRange()) + return this.#speak(doc) + } + next(paused) { + this.#lastMark = null + const [doc, range] = this.#list.next() ?? [] + if (paused && range) this.highlight(range.cloneRange()) + return this.#speak(doc) + } + prevMark(paused) { + const marks = Array.from(this.#ranges.keys()) + if (marks.length === 0) return + + const currentIndex = this.#lastMark ? marks.indexOf(this.#lastMark) : -1 + if (currentIndex > 0) { + const prevMarkName = marks[currentIndex - 1] + const range = this.#ranges.get(prevMarkName) + if (range) { + this.#lastMark = prevMarkName + if (paused) this.highlight(range.cloneRange()) + + const [doc] = this.#list.current() ?? [] + return this.#speak(doc, ssml => this.#getMarkElement(ssml, prevMarkName)) + } + } else { + const [doc, range] = this.#list.prev() ?? [] + if (doc && range) { + const prevMarks = Array.from(this.#ranges.keys()) + if (prevMarks.length > 0) { + const lastMarkName = prevMarks[prevMarks.length - 1] + const lastMarkRange = this.#ranges.get(lastMarkName) + if (lastMarkRange) { + this.#lastMark = lastMarkName + if (paused) this.highlight(lastMarkRange.cloneRange()) + return this.#speak(doc, ssml => this.#getMarkElement(ssml, lastMarkName)) + } + } else { + this.#lastMark = null + if (paused) this.highlight(range.cloneRange()) + return this.#speak(doc) + } + } + } + } + nextMark(paused) { + const marks = Array.from(this.#ranges.keys()) + if (marks.length === 0) return + + const currentIndex = this.#lastMark ? marks.indexOf(this.#lastMark) : -1 + if (currentIndex >= 0 && currentIndex < marks.length - 1) { + const nextMarkName = marks[currentIndex + 1] + const range = this.#ranges.get(nextMarkName) + if (range) { + this.#lastMark = nextMarkName + if (paused) this.highlight(range.cloneRange()) + const [doc] = this.#list.current() ?? [] + return this.#speak(doc, ssml => this.#getMarkElement(ssml, nextMarkName)) + } + } else { + const [doc, range] = this.#list.next() ?? [] + if (doc && range) { + const nextMarks = Array.from(this.#ranges.keys()) + if (nextMarks.length > 0) { + const firstMarkName = nextMarks[0] + const firstMarkRange = this.#ranges.get(firstMarkName) + if (firstMarkRange) { + this.#lastMark = firstMarkName + if (paused) this.highlight(firstMarkRange.cloneRange()) + return this.#speak(doc, ssml => this.#getMarkElement(ssml, firstMarkName)) + } + } else { + this.#lastMark = null + if (paused) this.highlight(range.cloneRange()) + return this.#speak(doc) + } + } + } + } + from(range) { + this.#lastMark = null + const [doc] = this.#list.find(range_ => + range.compareBoundaryPoints(Range.END_TO_START, range_) <= 0) + let mark + for (const [name, range_] of this.#ranges.entries()) + if (range.compareBoundaryPoints(Range.START_TO_START, range_) <= 0) { + mark = name + break + } + return this.#speak(doc, ssml => this.#getMarkElement(ssml, mark)) + } + getLastRange() { + if (this.#lastMark) { + const range = this.#ranges.get(this.#lastMark) + if (range) return range.cloneRange() + } + } + setMark(mark) { + const range = this.#ranges.get(mark) + if (range) { + this.#lastMark = mark + this.highlight(range.cloneRange()) + return range + } + } +} diff --git a/packages/foliate-js/ui/menu.js b/packages/foliate-js/ui/menu.js new file mode 100644 index 0000000000000000000000000000000000000000..d05f074653979bc09333bd2360c0729c4af46079 --- /dev/null +++ b/packages/foliate-js/ui/menu.js @@ -0,0 +1,42 @@ +const createMenuItemRadioGroup = (label, arr, onclick) => { + const group = document.createElement('ul') + group.setAttribute('role', 'group') + group.setAttribute('aria-label', label) + const map = new Map() + const select = value => { + onclick(value) + const item = map.get(value) + for (const child of group.children) + child.setAttribute('aria-checked', child === item ? 'true' : 'false') + } + for (const [label, value] of arr) { + const item = document.createElement('li') + item.setAttribute('role', 'menuitemradio') + item.innerText = label + item.onclick = () => select(value) + map.set(value, item) + group.append(item) + } + return { element: group, select } +} + +export const createMenu = arr => { + const groups = {} + const element = document.createElement('ul') + element.setAttribute('role', 'menu') + const hide = () => element.classList.remove('show') + const hideAnd = f => (...args) => (hide(), f(...args)) + for (const { name, label, type, items, onclick } of arr) { + const widget = type === 'radio' + ? createMenuItemRadioGroup(label, items, hideAnd(onclick)) + : null + if (name) groups[name] = widget + element.append(widget.element) + } + // TODO: keyboard events + window.addEventListener('blur', () => hide()) + window.addEventListener('click', e => { + if (!element.parentNode.contains(e.target)) hide() + }) + return { element, groups } +} diff --git a/packages/foliate-js/ui/tree.js b/packages/foliate-js/ui/tree.js new file mode 100644 index 0000000000000000000000000000000000000000..7ee85b400226f1698d7186d9908db51c7923ad5f --- /dev/null +++ b/packages/foliate-js/ui/tree.js @@ -0,0 +1,169 @@ +const createSVGElement = tag => + document.createElementNS('http://www.w3.org/2000/svg', tag) + +const createExpanderIcon = () => { + const svg = createSVGElement('svg') + svg.setAttribute('viewBox', '0 0 13 10') + svg.setAttribute('width', '13') + svg.setAttribute('height', '13') + const polygon = createSVGElement('polygon') + polygon.setAttribute('points', '2 1, 12 1, 7 9') + svg.append(polygon) + return svg +} + +const createTOCItemElement = (list, map, onclick) => { + let count = 0 + const makeID = () => `toc-element-${count++}` + const createItem = ({ label, href, subitems }, depth = 0) => { + const a = document.createElement(href ? 'a' : 'span') + a.innerText = label + a.setAttribute('role', 'treeitem') + a.tabIndex = -1 + a.style.paddingInlineStart = `${(depth + 1) * 24}px` + list.push(a) + if (href) { + if (!map.has(href)) map.set(href, a) + a.href = href + a.onclick = event => { + event.preventDefault() + onclick(href) + } + } else a.onclick = event => a.firstElementChild?.onclick(event) + + const li = document.createElement('li') + li.setAttribute('role', 'none') + li.append(a) + if (subitems?.length) { + a.setAttribute('aria-expanded', 'false') + const expander = createExpanderIcon() + expander.onclick = event => { + event.preventDefault() + event.stopPropagation() + const expanded = a.getAttribute('aria-expanded') + a.setAttribute('aria-expanded', expanded === 'true' ? 'false' : 'true') + } + a.prepend(expander) + const ol = document.createElement('ol') + ol.id = makeID() + ol.setAttribute('role', 'group') + a.setAttribute('aria-owns', ol.id) + ol.replaceChildren(...subitems.map(item => createItem(item, depth + 1))) + li.append(ol) + } + return li + } + return createItem +} + +// https://www.w3.org/TR/wai-aria-practices-1.2/examples/treeview/treeview-navigation.html +export const createTOCView = (toc, onclick) => { + const $toc = document.createElement('ol') + $toc.setAttribute('role', 'tree') + const list = [] + const map = new Map() + const createItem = createTOCItemElement(list, map, onclick) + $toc.replaceChildren(...toc.map(item => createItem(item))) + + const isTreeItem = item => item?.getAttribute('role') === 'treeitem' + const getParents = function* (el) { + for (let parent = el.parentNode; parent !== $toc; parent = parent.parentNode) { + const item = parent.previousElementSibling + if (isTreeItem(item)) yield item + } + } + + let currentItem, currentVisibleParent + $toc.addEventListener('focusout', () => { + if (!currentItem) return + // reset parent focus from last time + if (currentVisibleParent) currentVisibleParent.tabIndex = -1 + // if current item is visible, let it have the focus + if (currentItem.offsetParent) { + currentItem.tabIndex = 0 + return + } + // current item is hidden; give focus to the nearest visible parent + for (const item of getParents(currentItem)) { + if (item.offsetParent) { + item.tabIndex = 0 + currentVisibleParent = item + break + } + } + }) + + const setCurrentHref = href => { + if (currentItem) { + currentItem.removeAttribute('aria-current') + currentItem.tabIndex = -1 + } + const el = map.get(href) + if (!el) { + currentItem = list[0] + currentItem.tabIndex = 0 + return + } + for (const item of getParents(el)) + item.setAttribute('aria-expanded', 'true') + el.setAttribute('aria-current', 'page') + el.tabIndex = 0 + el.scrollIntoView({ behavior: 'smooth', block: 'center' }) + currentItem = el + } + + const acceptNode = node => isTreeItem(node) && node.offsetParent + ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP + const iter = document.createTreeWalker($toc, 1, { acceptNode }) + const getIter = current => (iter.currentNode = current, iter) + + for (const el of list) el.addEventListener('keydown', event => { + let stop = false + const { currentTarget, key } = event + switch (key) { + case ' ': + case 'Enter': + currentTarget.click() + stop = true + break + case 'ArrowDown': + getIter(currentTarget).nextNode()?.focus() + stop = true + break + case 'ArrowUp': + getIter(currentTarget).previousNode()?.focus() + stop = true + break + case 'ArrowLeft': + if (currentTarget.getAttribute('aria-expanded') === 'true') + currentTarget.setAttribute('aria-expanded', 'false') + else getParents(currentTarget).next()?.value?.focus() + stop = true + break + case 'ArrowRight': + if (currentTarget.getAttribute('aria-expanded') === 'true') + getIter(currentTarget).nextNode()?.focus() + else if (currentTarget.getAttribute('aria-owns')) + currentTarget.setAttribute('aria-expanded', 'true') + stop = true + break + case 'Home': + list[0].focus() + stop = true + break + case 'End': { + const last = list[list.length - 1] + if (last.offsetParent) last.focus() + else getIter(last).previousNode()?.focus() + stop = true + break + } + } + if (stop) { + event.preventDefault() + event.stopPropagation() + } + }) + + return { element: $toc, setCurrentHref } +} diff --git a/packages/foliate-js/uri-template.js b/packages/foliate-js/uri-template.js new file mode 100644 index 0000000000000000000000000000000000000000..d66bbf7f43ed0102eb45af39f899df34372b1b28 --- /dev/null +++ b/packages/foliate-js/uri-template.js @@ -0,0 +1,52 @@ +// URI Template: https://datatracker.ietf.org/doc/html/rfc6570 + +const regex = /{([+#./;?&])?([^}]+?)}/g +const varspecRegex = /(.+?)(\*|:[1-9]\d{0,3})?$/ + +const table = { + undefined: { first: '', sep: ',' }, + '+': { first: '', sep: ',', allowReserved: true }, + '.': { first: '.', sep: '.' }, + '/': { first: '/', sep: '/' }, + ';': { first: ';', sep: ';', named: true, ifemp: '' }, + '?': { first: '?', sep: '&', named: true, ifemp: '=' }, + '&': { first: '&', sep: '&', named: true, ifemp: '=' }, + '#': { first: '&', sep: '&', allowReserved: true }, +} + +// 2.4.1 Prefix Values, "Note that this numbering is in characters, not octets" +const prefix = (maxLength, str) => { + let result = '' + for (const char of str) { + const newResult = char + if (newResult.length > maxLength) return result + else result = newResult + } + return result +} + +export const replace = (str, map) => str.replace(regex, (_, operator, variableList) => { + const { first, sep, named, ifemp, allowReserved } = table[operator] + // TODO: this isn't spec compliant + const encode = allowReserved ? encodeURI : encodeURIComponent + const values = variableList.split(',').map(varspec => { + const match = varspec.match(varspecRegex) + if (!match) return + const [, name, modifier] = match + let value = map.get(name) + if (modifier?.startsWith(':')) { + const maxLength = parseInt(modifier.slice(1)) + value = prefix(maxLength, value) + } + return [name, value ? encode(value) : null] + }) + if (!values.filter(([, value]) => value).length) return '' + return first + values + .map(([name, value]) => value + ? (named ? name + (value ? '=' + value : ifemp) : value) : '') + .filter(x => x).join(sep) +}) + +export const getVariables = str => new Set(Array.from(str.matchAll(regex), + ([,, variableList]) => variableList.split(',') + .map(varspec => varspec.match(varspecRegex)?.[1])).flat()) diff --git a/packages/foliate-js/vendor/fflate.js b/packages/foliate-js/vendor/fflate.js new file mode 100644 index 0000000000000000000000000000000000000000..f275976aa27f70765eafee67c231d4d1d95c862e --- /dev/null +++ b/packages/foliate-js/vendor/fflate.js @@ -0,0 +1 @@ +var r=Uint8Array,a=Uint16Array,e=Int32Array,n=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),t=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),f=function(r,n){for(var i=new a(31),t=0;t<31;++t)i[t]=n+=1<>1|(21845&d)<<1;w=(61680&(w=(52428&w)>>2|(13107&w)<<2))>>4|(3855&w)<<4,c[d]=((65280&w)>>8|(255&w)<<8)>>1}var b=function(r,e,n){for(var i=r.length,t=0,f=new a(e);t>l]=u}else for(o=new a(i),t=0;t>15-r[t]);return o},s=new r(288);for(d=0;d<144;++d)s[d]=8;for(d=144;d<256;++d)s[d]=9;for(d=256;d<280;++d)s[d]=7;for(d=280;d<288;++d)s[d]=8;var h=new r(32);for(d=0;d<32;++d)h[d]=5;var y=b(s,9,1),g=b(h,5,1),p=function(r){for(var a=r[0],e=1;ea&&(a=r[e]);return a},k=function(r,a,e){var n=a/8|0;return(r[n]|r[n+1]<<8)>>(7&a)&e},m=function(r,a){var e=a/8|0;return(r[e]|r[e+1]<<8|r[e+2]<<16)>>(7&a)},x=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],T=function(r,a,e){var n=new Error(a||x[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,T),!e)throw n;return n},E=function(a,e,f,o){var l=a.length,c=o?o.length:0;if(!l||e.f&&!e.l)return f||new r(0);var d=!f,w=d||2!=e.i,s=e.i;d&&(f=new r(3*l));var h=function(a){var e=f.length;if(a>e){var n=new r(Math.max(2*e,a));n.set(f),f=n}},x=e.f||0,E=e.p||0,z=e.b||0,A=e.l,U=e.d,D=e.m,F=e.n,M=8*l;do{if(!A){x=k(a,E,1);var S=k(a,E+1,3);if(E+=3,!S){var I=a[(N=4+((E+7)/8|0))-4]|a[N-3]<<8,O=N+I;if(O>l){s&&T(0);break}w&&h(z+I),f.set(a.subarray(N,O),z),e.b=z+=I,e.p=E=8*O,e.f=x;continue}if(1==S)A=y,U=g,D=9,F=5;else if(2==S){var j=k(a,E,31)+257,q=k(a,E+10,15)+4,B=j+k(a,E+5,31)+1;E+=14;for(var C=new r(B),G=new r(19),H=0;H>4)<16)C[H++]=N;else{var Q=0,R=0;for(16==N?(R=3+k(a,E,3),E+=2,Q=C[H-1]):17==N?(R=3+k(a,E,7),E+=3):18==N&&(R=11+k(a,E,127),E+=7);R--;)C[H++]=Q}}var V=C.subarray(0,j),W=C.subarray(j);D=p(V),F=p(W),A=b(V,D,1),U=b(W,F,1)}else T(1);if(E>M){s&&T(0);break}}w&&h(z+131072);for(var X=(1<>4;if((E+=15&Q)>M){s&&T(0);break}if(Q||T(2),$<256)f[z++]=$;else{if(256==$){Z=E,A=null;break}var _=$-254;if($>264){var rr=n[H=$-257];_=k(a,E,(1<>4;ar||T(3),E+=15&ar;W=u[er];if(er>3){rr=i[er];W+=m(a,E)&(1<M){s&&T(0);break}w&&h(z+131072);var nr=z+_;if(za.length)&&(n=a.length),new r(a.subarray(e,n))}(f,0,z):f.subarray(0,z)},z=new r(0);function A(r,a){return E(r.subarray((e=r,n=a&&a.dictionary,(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&T(6,"invalid zlib data"),(e[1]>>5&1)==+!n&&T(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)),-4),{i:2},a&&a.out,a&&a.dictionary);var e,n}var U="undefined"!=typeof TextDecoder&&new TextDecoder;try{U.decode(z,{stream:!0})}catch(r){}export{A as unzlibSync}; diff --git a/packages/foliate-js/vendor/pdfjs/annotation_layer_builder.css b/packages/foliate-js/vendor/pdfjs/annotation_layer_builder.css new file mode 100644 index 0000000000000000000000000000000000000000..c1c2a8d54ce72110859df5b9bfb86464dafd06d6 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/annotation_layer_builder.css @@ -0,0 +1,407 @@ +/* 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 { + color-scheme: only light; + + --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(--total-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(--total-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; + } + } + + section { + position: absolute; + text-align: initial; + pointer-events: auto; + box-sizing: border-box; + transform-origin: 0 0; + user-select: none; + + &:has(div.annotationContent) { + canvas.annotationContent { + display: none; + } + } + + .overlaidText { + position: absolute; + top: 0; + left: 0; + width: 0; + height: 0; + display: inline-block; + overflow: hidden; + } + } + + .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); + } + + .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(--total-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(--total-scale-factor)); + pointer-events: none; + width: max-content; + max-width: 45%; + height: auto; + } + + .popup { + background-color: rgb(255 255 153); + color: black; + box-shadow: 0 calc(2px * var(--total-scale-factor)) + calc(5px * var(--total-scale-factor)) rgb(136 136 136); + border-radius: calc(2px * var(--total-scale-factor)); + outline: 1.5px solid rgb(255 255 74); + padding: calc(6px * var(--total-scale-factor)); + cursor: pointer; + font: message-box; + white-space: normal; + word-wrap: break-word; + pointer-events: auto; + user-select: text; + } + + .popupAnnotation.focused .popup { + outline-width: 3px; + } + + .popup * { + font-size: calc(9px * var(--total-scale-factor)); + } + + .popup > .header { + display: inline-block; + } + + .popup > .header > .title { + display: inline; + font-weight: bold; + } + + .popup > .header .popupDate { + display: inline-block; + margin-left: calc(5px * var(--total-scale-factor)); + width: fit-content; + } + + .popupContent { + border-top: 1px solid rgb(51 51 51); + margin-top: calc(2px * var(--total-scale-factor)); + padding-top: calc(2px * var(--total-scale-factor)); + } + + .richText > * { + white-space: pre-wrap; + font-size: calc(9px * var(--total-scale-factor)); + } + + .popupTriggerArea { + cursor: pointer; + + &:hover { + backdrop-filter: var(--hcm-highlight-filter); + } + } + + 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/packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..8b64ae41664d86d305f856e98574cd454b7935a5 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d92a261336dc18b8c03a46eb4d462382d33f4338fa195d303256b2031434c874 +size 2404 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5badac01ac6659e82163d8f2080d567cad15e553 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61670bebc4e4827b67230c054fd0d820d6e30c3584d02e386804e62bbedc032a +size 173 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..cf83f329927568f7b3418362169b51468505adfb --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ece6415b853d61e1b2560165151407d35cf16e6556932b85a13ea75276b77402 +size 2379 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d19ad21ee9229c9939c5bdbbb9812f52b2af4518 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:696b1f973c97623496703809eaaa5f9b40696c77540057413f4b826a08edfa7b +size 2398 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4cddf189a15fce44fb8e83d15561fa816c2e3719 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53cb6d560ab377da48cf65d6dcacb0bdb31f13fab7066c580de38c12a73a7ff9 +size 173 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..aa3c9c5668db94d79a65ec5a0f4fb5c773c07644 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:289000f02fd34872b6975503217f33abae6bee676e7d28f640473a67c8db1712 +size 169 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..40aa6a15e4d0a5b6b7075f7174f99f78e0feea2e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2442595218f5f8bd8e1b42188e368587d876cfe0cc4cd87196f077c878f72e2 +size 2651 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d97d3e8c9c40462781b263b64fdbf2e615fc11d7 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8ddceba96bfd9d3740bd1789ee30d1f47c78371520a8084f71f7df58f19be0b +size 290 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/83pv-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/83pv-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d8ea5c4bfea677526f38645e4d212430c2ce5b44 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/83pv-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44040051ec818fe09b9703472bea72efd2759d5eeb5ff0d77c718d6bb5e6d1df +size 905 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/90ms-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/90ms-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5b490d707091001b8b167cca08a9d21a6e6fb07e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/90ms-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c13e043e85ff715b75bb03801e8fd0fb8f3a75e4a48496faa6baaf92b5b48ba1 +size 721 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/90ms-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/90ms-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a0a4486597f4328aa1a39da66b052a9f253e65cd --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/90ms-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:499bb916ce1adbe4289b6e5811f4dc20eb238cdc2ffad20cf26ae56716885bab +size 290 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/90msp-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/90msp-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..be738591ce853809ed110c73f0f28c6941fdc36b --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/90msp-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b8b3b8bbf821702e9a4df9f3596ce292380c8c1b0925dedadbb4e4b2d80498b +size 715 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/90msp-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/90msp-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..563c837852a0fa572ce79eeb0d93a25f15ee917f --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/90msp-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6296c2b5c07dca8128e96d5296d621a3268803d4fa0e5812a21e52fe2802aacb +size 291 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/90pv-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/90pv-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..0c4469cb2940869166542dfeb41d215e8340e9ef --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/90pv-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb5103f03d3a34547e18d316e52b6d9b26e485c662999222f84d2ba54c2e4fa8 +size 982 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/90pv-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/90pv-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ccc2e47779a0755aab96e0e329be4133e6d6707d --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/90pv-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bcb5ad2ba55b9662ce379e16c2d9cc2b82d621a579807353741172e4af615c2 +size 260 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Add-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Add-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f10320d3579b1b011a398737f23f9ede399d3eac --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Add-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2ffab28b990998181bcca9b0e914bb2207820f100ae31d5c469444892e5ad8e +size 2419 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Add-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Add-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..590f8fe481031ce6caaecc24b84d29d2d2e18c22 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Add-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b29f4b52e2465d0485856d5e69f1ba69927deb2848d8fd328c8035583b35bb7e +size 2413 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Add-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Add-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4422b918547f665491e2d229d01daf2bca3bed21 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Add-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2aa2232c283a3f5d0997c2834a36cead0b79ce2657944cfeed08140c293460ff +size 287 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Add-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Add-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4e045dea106c61e77c34caa2ea51cdf278cc4df5 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Add-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25125d3b1be64e86b2df5b3344170b45a42bcaa0b46e43a34314ef73c166e542 +size 282 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-0.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-0.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..6709c8e837aa296da424f2e181cc479e31596c24 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-0.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c65be9d51a9f269a547dc12460707aaf4031ab67ebe8a2900f4b4cc6b3e450e +size 317 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-1.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-1.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..421e94814b04f7b1d9d53bedebc82a5d67bf81ff --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-1.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73152bc1a59cc594b414ac6068be48e5512b96ae85920c40e32a99269fdb0c04 +size 371 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..bfbcff91f0d64b9279175811a3dacffd8f3f6d68 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1b8d353bdef9584c820464e8f1c9e2013d64ebf433cba0aa831dddf515818c2 +size 376 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-3.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-3.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..2c32993a13819195a1574f67d09814f24ceb3b33 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-3.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ffc0c75c79fafde506163d3c08c390d183251009f3fbf6ae50d1167d14b9570 +size 401 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-4.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-4.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f775f867ec2dfc2a01e9fdfb4cc8207daf0497ad --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-4.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98a1f470c878c6b9691a4d7aef776af8ac9b55f5587c9fafa00547f3bf655716 +size 405 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-5.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-5.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..14c65ca8488dae3c31a4468c3a84f7f3f7024bce --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-5.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddd6e29955eb8cb545f2ebd09c628c3bbda5023256eda1b728f743c75fb77829 +size 406 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-6.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-6.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..346a867f4a4e556a39f58adef0623210efbc4b4c --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-6.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:317bb2db71e0e5b7b0c47b75de1da915c2e22f65f0c0861507f9ca7ba238f8a2 +size 406 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..95114edfb3dc011af7e343465675e847c357523b --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e665837f2197c6bd08cd8955ad4d6932cee2398e2e328b25b00e6bfb3bd72af9 +size 41193 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-0.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-0.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7ac56e5672c90d7becf29fe58a4988ba725f68ed --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-0.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b81cce8a11d510e505704953cfa4e4ab080c1a0cab991145a3512ee433946b9 +size 217 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-1.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-1.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f3a519a2d63dab52d0aa5180d0894c32748a45b2 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-1.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0426983081788ec7202703e71f1efa4b860f75b936994236010b39d89251a81e +size 250 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4cfdff6ee7ef6a221eb946f57cd04ef6c7bf985b --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e67b37a83b160ab3831306a71a605893b24454ee81ac9b6123bf2d3984d268d5 +size 465 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-3.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-3.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a466450ec9ece875cd9064d53ad4d587ada0f3ed --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-3.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa299afc3e12a28726147305f191be28c7498078c8b182ece7886ac79cd99078 +size 470 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-4.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-4.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..314ee8ac7da8ce23a2d25393dcfc076bb6bd217a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-4.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fbd7d74c2ddb1350c1cecce54a73fde3f5453093d4bed445283ec0033d2097f +size 601 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-5.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-5.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d40175d34b32ddff3768b04aa15b997d40b5b1f1 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-5.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c22cb2fcff24112fa31dab2111bdc51957006576d31aad5a25e67793ac01428c +size 625 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-UCS2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-UCS2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..3c1e17ea511a371ccaa40dfd9623ae62ac691fb1 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-GB1-UCS2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20507620260c0c935c35afc1e70e5888aa7125d5ec7ffc03cef1959feb2c1641 +size 33974 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-0.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-0.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..00021003414391fd0d4cbc7bfead073523505e19 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-0.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:464f08905236f5703b1f5cf8358767c8b18e6bcc808840d081f1de2c7ab38134 +size 225 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-1.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-1.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4a56eb113f7af45f4b707dfa536e46536de606f2 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-1.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c823848722187d1ffe75ae3f5f9126ccd2d7895a05fad14c919fb119e037008 +size 226 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..582c7429accd502161383ec36de55aaa9b9c02ca --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7810fb808e367e70429e90a9478fe6a3fdc3e214f25c7582ce9c2da6a242315c +size 233 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-3.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-3.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d4bd512c6c61ea30fb92c0145280e5db72b33403 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-3.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84deb1828711ad3d390c9899c38abce1bf619d65ff7bf1a326ec95acc45f08f8 +size 242 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-4.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-4.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d94bb9609b25870548b6ba13a8c4d786c2c9924e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-4.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f8a4f974919c2b8bae5d10175ffa2673be140481e00840542c85d48ef184067 +size 337 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-5.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-5.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..0b9f5f2a101616e3aea3740171d93e32d6238707 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-5.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d3ce4ff28d977f8cf37a912ae4ec811f4175c3167b1ec0b2567feec3e79e1db +size 430 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-6.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-6.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..18e819f89ac689fe88e819345768eb668555fefb --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-6.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5609797b9401b30be72ef9645da62a87829f058c3be4b5c623383119f584b1d9 +size 485 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7dd8c36bde5e8b781bde8532e46f8129db136fd4 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66c5d0dc4964f4093e77b194023f3a0f689324028ec8330e1e1d0570bcba7c2f +size 40951 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-0.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-0.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..35b514c669f8d49d146d77d8e47518e288c13664 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-0.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfb8c3874f0e5a8c3acf597d2c12d2b63e90bc5e4f0fce990ec4c56077d80b32 +size 241 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-1.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-1.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5e6b505872bfe7239eaf72c45093fc67dc968901 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-1.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62f277b7b1c441c007797ae707d5c37258d029ce4661a2b911e2e1ee35e6adc1 +size 386 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f63e2908e18561d6679540ef1c0ed102321f2580 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d77068af462f96d7ad28ad7e7d43eef6423c685b479d7dc25ff5df38db0380d +size 391 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..62385e96a72db267638252d74567efa7cf399eae --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:857b723088be97255053562bfa41bd1075a7f7910d3bab59a0645c8bbc7060ff +size 23293 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ec9e3738f0fbaef2bddd6669644f9264baaf1568 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:718ad0ffbef4c34f8f3f31292c462e519cd567a5511fc8b346c60010d64f4ef9 +size 1086 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f3f0db788ef70d9fe7f42384dcb954bd93d2ef75 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5c37383517477620ced927b6b4ffd4f4cc6230d8051b5b46a21d6768e07f7d8 +size 142 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/B5pc-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/B5pc-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..b24535710cbde43e7d1932dc11247381f45e8b05 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/B5pc-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bab6028aead1d6149400e904ab10cfd319082d826473ed4c582c8eeed920f17e +size 1099 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/B5pc-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/B5pc-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5785556c6153502a105642586662790aa8e35936 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/B5pc-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41543142b9767f3b76133899fc8453282b01ad3c653acaeea42d78c5a7d08c63 +size 144 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/CNS-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/CNS-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..405ed3a6b504093029a07c09c20553f234116e2a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/CNS-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8f89cd61e6486b948205da46499d659ed0aed949b7095fd3c8e95ffe2b0e7a9 +size 1780 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/CNS-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/CNS-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..0ee47dcada91ebfd6a52ecb2f3063212d3687dc0 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/CNS-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cae422bec2ac6dbe86bf921cec942bacd2d0b733ffcca5f91b3ba14e917025a0 +size 1920 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/CNS1-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/CNS1-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..e3894b0dee8aeb63e61c489c2c8e713d0a241501 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/CNS1-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8487971ab20cd16f3de3e8ac56ec994b72b658ad113f2818239dfd5108f501a +size 706 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/CNS1-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/CNS1-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..96e84556331ef86e0571be7bf2bc2a0ac5b3fa2c --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/CNS1-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42df8076aaa7574505e7304af83a3323ec032c4177d64b1309db8c043d594a8a +size 143 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/CNS2-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/CNS2-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..abafc2209162beade6400fa4da02582298a10db9 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/CNS2-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc6024d274d440f0625c69e25f37036ef6cb6689432ceaa160d3432a2a716ca7 +size 504 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/CNS2-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/CNS2-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..6da2639edab38c516b71796400b225156b23a3af --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/CNS2-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e4f70a8afd23a121030fc2e5b5f3816e903b11e7ba8b8c09654b31c80399c38 +size 93 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/ETHK-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/ETHK-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..e61ae53d652e130d49ed998ce6737557dc20532b --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/ETHK-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2f10fa519336bc4efcc7b6deb9604b75429946b40d82e311cb3a97a1994c89a +size 4426 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/ETHK-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/ETHK-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..8338491760ddf402def15f73122dc2cdada53167 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/ETHK-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fea3fd0d9f0f679f80505800851ef2e4131d81127e18c006938ffa2f4c8b247 +size 158 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/ETen-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/ETen-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..952cda20a1802a3ca9d45f8f8b82e83bea0869fc --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/ETen-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87ee6b3f5bfda5fe26fa35431264c7d73070d10dbbf398a75185d63ae322c18d +size 1125 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/ETen-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/ETen-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5d52152d8e1d38dc033636d817dac239c013464e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/ETen-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47dc0d2c21e3bde317947aec1675ceabc1d5460a60bf9c24334b8c407a17172c +size 158 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..8a81f625eeb1fa5fc694aa8547d197a26857cbc8 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5f5a73da4173b7da9a3a20e16f26f9cd5d12deb1553409919e0cec6fd37fdee +size 101 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/ETenms-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/ETenms-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a884d3c64d001b15b3b66f390a0404f83a4b082a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/ETenms-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18252fca90f472f479af1bddd60d6ab51c8e1b55dcf6845951426504934543e0 +size 172 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5b411311a0b829883cc4d31cc92f101323c073d0 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9939cd57fccdc65c5d9f4c205fd497ebdbd283643308da5663801a8c1d9c595 +size 578 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..73f0dc96355805260234ef5da6a6892e9227da30 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1283a50a706507c4436da83ede9ad7a4440be25378f2e96f6c81a430081426a3 +size 170 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Ext-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..0271fd3fa1cf1cee751b97d910d4aaceb4f56ed0 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4000ed4e61a1c668ef453bbd0603cfa383defa793abd46a57ed870d7f527350b +size 2536 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Ext-RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..fcf70734699de60ab98db965bb0e073a94b522eb --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0d2f0df337660e73813238dd4a725f11f0621b90f3273857db253d0e7694caa +size 2542 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Ext-RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d7b33deb7532e5dddde3834e4048217ab9c4f4bd --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f617a22b6d67febb187990952006c91a9f5a4db21155d268c656252d0c21985d +size 218 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Ext-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..31d5affb85b2f3c8c042f091b669eed9d80e1775 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Ext-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2087fb845a9e3acea0c2922cd40e6af67e11957bec74dcd597f1285edd490ce +size 215 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GB-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GB-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..cc6ad23b2521d65d11b971f0e326c0d544166653 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GB-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:928bad06fd84a48f5ba7150d7716609119fb660f2aaa73eccad81ddab9b9d203 +size 549 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GB-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GB-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..35671fbdb6a319f165f47e3b4cfec4d560cac8f6 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GB-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9ad88ac2479da529b16dc48abc5952332e27bc355335f91df5729a587533324 +size 179 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GB-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GB-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..9e525c9fd4a48219adfad1bab5e51a2827e7d60b --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GB-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1018c777a8910b5bb46d7d54a4aee9d51ca5cff8addb2b41c969d9101cb3fd1c +size 528 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GB-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GB-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..6db62958daf6eeeb59dca09c56887bf171fae518 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GB-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b96789143c0bbf9f1641ae7165b3456dccd14dabffcbb0bd654d5bf6f94f863 +size 175 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBK-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBK-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..c076bf76009386ee8e92584afdf56ea0e6e0e4cf --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBK-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2103fed28650ede096a2281104a1a8a4304dae0db414342c636867522307123b +size 14692 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBK-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBK-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..1d47e780ca31e61e7008c7b3cce8c21fdbe767bd --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBK-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7fd35dd14d9dbdb955f34e6c0630618b6620dfd09d4283b2f65a65ce77fcaea +size 180 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBK2K-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBK2K-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..462b61361eddb6c4debbd2408e353a2feb8b8b4d --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBK2K-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d919ae72af16c5cc6846ec87a4326a9f125e493c59d3628429d35c2c95fe8c4 +size 19662 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBK2K-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBK2K-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..30ebd431ef086574e4dddc1ed94302c5c3eb0be7 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBK2K-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b927fdfd595c07ce9158bf2ec13f4641b2e83b01c70989dadfabd6ed7c6ac2dc +size 219 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBKp-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBKp-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..e1048bc98ec9b5a645216f7014175ed4362021e6 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBKp-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d15ebd8e81fb4fe8a244f1b1e877922e03500ac69eddf5001093e502430451d2 +size 14686 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBKp-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBKp-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f3bffd0a067ac8a4e1eb41ade1b9e79d83a18ace --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBKp-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdc736d46e642625dccc8ad8c59f2c69fc7db7a13f2e799c6c6b779e707bb97a +size 181 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBT-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5204548ee1ddb176c2d896b98c522858a28754e0 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc5f44e48a39f3367ae28665027d8ab1d8cedb5a9dcc5068a900acd6709f60f9 +size 7290 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBT-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4dd164ac2320e1832cd050ce2d87f018d69c000f --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1ad24e63653b8aa388c18fa5e498f007564e43dde699a9f91ccb4645c999be8 +size 180 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBT-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..730dd713968a12880611455eb5c5520c4d31a659 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8afda745a505763f3ff54c8126eeb48ef376ea9ed07d9f42ff9a22c5c547ec57 +size 7269 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBT-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7dd0cc956c1dd64ca0f2022920323220a806ad34 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBT-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cdc2ec5c3c7c7033290c9a8894878202f08674eb9b1ae7d36218430326768771 +size 176 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBTpc-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBTpc-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..b05d26d94b1aed0d3bd41d409b9fc4add1b42ab2 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBTpc-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b23e2f7bfdb6c918f567b7324bf858f398bd8cd5f268d74ece19a3c91bf4f32 +size 7298 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBTpc-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBTpc-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..956d3f82ebb66d2e4e276362f4532862f41b1a61 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBTpc-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7a1b13ead9ab511cf2cd01de6ce8b02aa8e8767e84895337d7a3b67f039f93b +size 182 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBpc-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBpc-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5e9c761baf497fadd431068df3bd9ee942af54af --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBpc-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c4a4eb82f05abe51f6650985c630e180438bfdd491318f5d20d2ec29236e1c3 +size 557 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/GBpc-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/GBpc-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..6bc10bd41bc5aaf20bce73769da7d381fad03a5a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/GBpc-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:215bdfa2842705624b4cf4cd29b8e3c720f1e192365e0305c11030a424c84d7c +size 181 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..26d153cd23fc5c29f7f37ead805fd8dfafd01af5 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0233e21047ec00b852125b243cbcf30abee511155b6d8159c24f944384bc9ee +size 553 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKdla-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKdla-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a54ab0c18ab8e1bdfc9ed1a50795378ba205a4ce --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKdla-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5242bce18fb13ab4cc59b146a03eba36e4ce42667eeff09e10981a9d2aa4996b +size 2654 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKdla-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKdla-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..05f5392e04ae005dc67c10a92fc3a635c1618d23 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKdla-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e0537f786c0791d41a925f72bad2d4e7268aa6cbf15a1400a722672cec38e2c +size 148 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKdlb-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKdlb-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ed0ac46bbc78022f1df3fac9bb621ae746d2223b --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKdlb-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdc8159984bf5dbe475c0d5dfcb621ecee4dea07c38c668bd77f4c679e23b9b3 +size 2414 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKdlb-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKdlb-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..89904c6f671784114802e43e4cc27db27ddae429 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKdlb-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b249eb9dcb915ab45057c5d4d7aa55ef88d0efbb092af6bae0b2d4705d139abf +size 148 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKgccs-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKgccs-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..e1135b2bb9ab3ec34078053635fc6170006aa34a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKgccs-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab64c7fc5e9b2e97750cc4f269b0da14fd8649e49151b7598c8df86599bac591 +size 2292 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKgccs-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKgccs-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ce9d842bf57815c36cfe1788c04be65bd5f3f9f8 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKgccs-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02ebdf7cdffb5395fb21091cd58a013a18ae5388922822f9dc6292ef16b98956 +size 149 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKm314-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKm314-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..0400b3cc371c8aa1bca5490c3735da8af81883af --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKm314-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfd8bbde6b36a9da4c1c902c74121a30d9807a7079a00eeea218be6adc223cef +size 1772 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKm314-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKm314-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..be80c6f4a9e2b17221655cc63b5bb4335835ed7e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKm314-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a64a815cfb6fdd480674a868762e3d161fda17543b20c9209978559f0667164 +size 149 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKm471-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKm471-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..69824f40a9cb3173c54cf7c30498f6c6bc472162 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKm471-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49d7c037758826b5b6c0fa329c35bbf25d3943197754e72ecd30c6fb04d745e6 +size 2171 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKm471-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKm471-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..49bbf2a8b9b5539205679a4e6e542766e2b060cf --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKm471-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be24c109e78aa4fe3c1f27d30aab3ed0741e783fa1b6b6c2719741072b54b132 +size 149 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKscs-B5-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKscs-B5-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a4fa7d655dc326e0b83ec6de50aae40d9d230db4 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKscs-B5-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08599378f41d96b40537adef6e6edcc4a787bc63f5accf47c026df4905a13914 +size 4437 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/HKscs-B5-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/HKscs-B5-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a5104733eea4649356189a22c537424cc23dc4bf --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/HKscs-B5-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d073542b7dad1c4cbf01c1af5f0cd13218d1281a491956e310c55702fc8705c4 +size 159 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Hankaku.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Hankaku.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..cbb2f157d2387760a46404895c0dba7aa273eef5 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Hankaku.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b454701f7aecd7856769016dfd04ca64280a060f2c67a2466d50b4395d24974e +size 132 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Hiragana.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Hiragana.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..438e568819d7e0d74d684164842750ec1cab7169 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Hiragana.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ed669394756dd9458651cd9995ab29ab691ecb7686659003306cdf22767a414 +size 124 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSC-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..2a6409f7dea28baec362c86ef7a9b874fc8842fa --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6784e16dbc5861c036c23d3e55f0d4ba0975a3e464da0ee8e49bcfff0be070c4 +size 1848 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSC-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ecd1a949887839d5dfc10977ce8a574788f6c126 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdb36bad85e9924823d49db374067988e024cf80fc894711f2c9178951cbbe95 +size 164 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..b97ddb47b764dd8d228742bbab2fb47442d7fdbf --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1f6d61f1d3304fd539a65ae72624fa567ecc3853bf52e283958a7a2515b3eee +size 1831 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSC-Johab-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-Johab-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..6fd65d4f0cdc2dfe9ec2e4a762b0576c5251bbb7 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-Johab-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:939993d213f68db763bf156217c217ae23af082b91a0eacecf3d11eb4ff8ef8c +size 16791 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSC-Johab-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-Johab-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..fe75ec9e410e78faea9314c3b2a97a632350ebd4 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-Johab-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d61967aac0e666def721e8b8d0fed8f95a879a14f2e76ce516c3d11c621e519 +size 166 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f6572691ac166d7b68128c28f162da8ce8723839 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7da5afd9f1fe74816d79c9325f0139a4efb6438664ebfdf9a7aa92f3034360f +size 160 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..691df78c04b27d8e9a05074072956ea965e62107 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b70d8f6a4fa9e2283dc649f0ff95d906d56efbee50a20e8d2faec3a8fed078e +size 2787 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-HW-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-HW-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..56e193135f6ab07d8dea8e2841e4087d90fcd340 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-HW-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5e6ba22aceb02fdedee11bfb9ed138463d89e85b87810b9f075b469d936f8ec +size 2789 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-HW-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-HW-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..dfd8ad0a30361c6258aa868d0acc9fff69c52fff --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-HW-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:890332a6a26880d463a12f2a6ff048bf9cf7e45077cfb1ca8815b89baa7bf411 +size 169 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..fb949f03a12ee0481f749aaa783ef09158f6c204 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSCms-UHC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1631b531c9a40c8cbe24c2317dba107362e49fa6e18af620414d627c111d570c +size 166 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSCpc-EUC-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSCpc-EUC-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..3bc904bb5d5a2ac9db310a876e04c8d115ec5268 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSCpc-EUC-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:709480682c55cedbb0124b9960d78e28febeee0df2e34607d61aac6601647ec7 +size 2024 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/KSCpc-EUC-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/KSCpc-EUC-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ee3f2f80c8b3ab6531d3108a57bfb73a5300c2cd --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/KSCpc-EUC-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:031707887d6fc2378a36cdb6775334fd7a236c3f95048d8436abf43fe26fc49d +size 166 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Katakana.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Katakana.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7da6e005eb269cfe54b681023c58976fae5c1b00 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Katakana.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b6ca6642fbf8822da00d5e58a8aa275216d5c32dbf2bd73e934197fc9fc5c53 +size 100 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/LICENSE b/packages/foliate-js/vendor/pdfjs/cmaps/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b1ad168ad0dd09b578cafec31d2666049b4d8718 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/LICENSE @@ -0,0 +1,36 @@ +%%Copyright: ----------------------------------------------------------- +%%Copyright: Copyright 1990-2009 Adobe Systems Incorporated. +%%Copyright: All rights reserved. +%%Copyright: +%%Copyright: Redistribution and use in source and binary forms, with or +%%Copyright: without modification, are permitted provided that the +%%Copyright: following conditions are met: +%%Copyright: +%%Copyright: Redistributions of source code must retain the above +%%Copyright: copyright notice, this list of conditions and the following +%%Copyright: disclaimer. +%%Copyright: +%%Copyright: Redistributions in binary form must reproduce the above +%%Copyright: copyright notice, this list of conditions and the following +%%Copyright: disclaimer in the documentation and/or other materials +%%Copyright: provided with the distribution. +%%Copyright: +%%Copyright: Neither the name of Adobe Systems Incorporated nor the names +%%Copyright: of its contributors may be used to endorse or promote +%%Copyright: products derived from this software without specific prior +%%Copyright: written permission. +%%Copyright: +%%Copyright: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +%%Copyright: CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +%%Copyright: INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +%%Copyright: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +%%Copyright: DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +%%Copyright: CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +%%Copyright: SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +%%Copyright: NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +%%Copyright: LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +%%Copyright: HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +%%Copyright: CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +%%Copyright: OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +%%Copyright: SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +%%Copyright: ----------------------------------------------------------- diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/NWP-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/NWP-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5112720355eb6d2b90126e81bf81248ea1bd1c64 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/NWP-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:286c6c9e335da330928a01edc3c97a3a623f1f7f3c42762b0a7dc2f651b1a78f +size 2765 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/NWP-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/NWP-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..022e79c2a5c840bc8eff1743b872e295aad012b8 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/NWP-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a75fb7b59adfb172710758c425d8ac6c93fd5360a64dd4afd5dd04e60ab4b4d +size 252 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/RKSJ-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/RKSJ-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..af3cb9ebb6f6d5a80009a79f4e9dd95c359a33b5 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/RKSJ-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a70de61a22a898f693f02cc011c3e3cff2e10aaa7cddb4661e456a21ae859f78 +size 534 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/RKSJ-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/RKSJ-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..c875ce55766f6be7882cac8e7be478f3c087545f --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/RKSJ-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68c1a64506471a524ea5cfc3b3a9f8f70031989a6bd95427b1351f33ccf50b06 +size 170 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/Roman.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/Roman.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..dee2dd0200c09ba69cc3b56fb58420f3889a8cd5 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/Roman.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c6b3ef9d9e5cb1aa329142ce9414b90f9b6d7f9182a2a9e927378dab8f0d43f +size 96 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UCS2-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UCS2-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7580f04737985d12bf7920da83a4850cb43b5739 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UCS2-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:779428116752f34e2490a1941d24e4634c71e3c22d053b811d2090ae2fb3c704 +size 48280 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UCS2-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UCS2-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5ea590c8ba6ef43412535b1d351523b001ef0b21 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UCS2-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e5cc184b850ea44abc2df8ae5674279df668e8edf5e2a1a2ea2bd77adbd280f +size 156 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF16-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF16-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d88f447029dc7a2450eb9ad5e974794eb452f48a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF16-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32ff139b3c7b91d6ad25f994701f3ce7b242906022c418fd73e6493fc228bfe5 +size 50419 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF16-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF16-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..97d26c8db28d352d1419e567c3b2924bc789fa6a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF16-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:278eb1e68d1a236c60ef59472cf0176ee0d45f364285e76ca12419a08d46fb9a +size 156 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a0b4dff0a671d2e73d0f0f6de12d69bb3187240c --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf26eb67fe19ee5ba915799e80ca72408400aa8342fdf6a244a4f44de8f97336 +size 52679 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7f2f298513c4182c52e7c0fdce40279723bd2fe0 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7da3caf83ceb1cb37936fa10700d9ba6e9c3f72c5bc9724e3ac79bff0c0179e +size 160 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF8-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF8-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..4b21498ae90a12cc7606506037fdb5273554f26a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF8-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f2a742bcd1a84a148a4a518b9eed51a8f9c6ca5ed3bc5e2e41fff97de5dc2d8 +size 53629 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF8-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF8-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..1496ba030a6726f396a64309c09617ed6606c32d --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniCNS-UTF8-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7c3f10780a8c62dd1c8ff6c30dc1e4e23b6cdc87c3a96fcd514cc98ffd3af9d +size 157 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UCS2-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UCS2-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d718d86b0599c2f36e53205ead7b2a7db3f674f9 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UCS2-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9201569b402e81ad8860650bd86350c4fa28e5dd5971f05fcacaf40f51de18ed +size 43366 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UCS2-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UCS2-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..c14c96a90cf493cac1a4488b4c06e595d4f585d3 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UCS2-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f10282335e4d64203bc2a653a3a47d745ec76c8ae04549f4d50180c1899be216 +size 193 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF16-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF16-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..49760046442039fd2f7b703dcc7b181a725ee587 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF16-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:386fd39581245c034da016a92d23f3df1117d169f996100050b264fc09a84e35 +size 44086 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF16-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF16-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..dbc2b682926702dd785f86f7c536c1826b5d57ba --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF16-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0473cfbba612b92dd9918f0ff8aee9112897c48e0ffdc0eb82da3144ed8ea84a +size 178 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..222198f3f1719c3679900821d143de4b2756de51 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f48a145dc4e3ed1dca1dde7111716a72306a2a4191ab05c6bae3a5c3a961cd2f +size 45738 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..bb80749b44d18a70b6aa5dafd1d93ae5573c17d6 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:106acc49b7118bdef944e32107b4f348238f3929a0a15d3b7aab7b9101535993 +size 182 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF8-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF8-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ece911a055744536ed8069c4f790a6968cc14d10 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF8-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f217b439c80ee5fa1bc2cf6d1defcc319f8d84483d166a00ee199e05a68588df +size 46837 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF8-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF8-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d7965131a22e98255394fd469bbb5495f21d41dc --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniGB-UTF8-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a64df947632878eacc532fa193c735c92a383b7d66e6f8374ac193af7c64fc63 +size 181 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..ae03037f1dd73bf6afe6ed5a65b459c9cdf777ba --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad2352f40870880fbf7f8ee5abadff743fbd025fbf9830b8ada472d1c5e4da0b +size 25439 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..e4031542b5097706e3ada89e423def38cacb3326 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16e87edca954177c0881c874859d6783220925d821b5cdfb8755b61ebd93f9ce +size 119 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..161e9dfa87e026cbeed77b19e8e24e7003491890 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1973457e2c0192819947e56068625b34fb9a72ecc8a476ce6d7eaae5f73e2e5c +size 680 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..dc673f2f62fcd116ba392a8fa162d80110ec610f --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UCS2-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42a133d8e2ce9dd6d2288018e01592d2bf2435b326d39b94ea0b6e6a44ac33d3 +size 664 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF16-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF16-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..50ed849993214d0db9587ea4b899d53f5f0586a9 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF16-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6a89c5688978548c83fcee990e205bc63c74274d5c69b49032a3bd4c49a05ee +size 39443 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF16-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF16-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..db177c0f1f38e89b68468f3088975a59f80a7d4a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF16-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c67126fc7c73850855186bb0d6482ac0a365057e0b58778c4ab9f234683fef53 +size 643 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..962d53efb718917bd24c4afb8a2a995ee4ee37c3 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96195950ce0fe24443d8eb426fa6b88534ec421d7bef9046f0b2362809cfba73 +size 40539 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..d5800ef4f96c25495f70336ab9cce9a3bec50bb1 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed4dafda402bdd19c4d5d8bf2ab41473c0f86f384552b4c7b963d6627daedeb1 +size 677 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF8-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF8-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..eca2fe8e71935dc575b1568fcf661e4dbfe78fcb --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF8-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:798fb0bf06ab0788d1f6a91c2db7de581612eef03c628f10e8f7ecd8f70ab448 +size 41695 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF8-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF8-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..3ba14c9550818c171e1c8ccecde5710cffa2969d --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS-UTF8-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1021611424f913b2df0bfdbe94bd327c04e224ec89d8e821c6501ea3d21f4265 +size 678 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..16396201e547839554cc9a6a3e8d1d783a714dcc --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:710a32d7cb43fd6bd9dbf30da5971f8c941590f74441e208d852c2be0e74cc97 +size 39534 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..11b7c181f842177b150237726a9f538a85ee26a8 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b149aff5c5707b57fb3215d1775852c8b1f413ec0f679ea628f25cf87fe098d +size 647 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..2784ecfff52b2d612916d93c60ce90c27606efff --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d2658e18741af7937d586a57c89729a6fec0d86121197c1f8518aa58b29cdfb +size 40630 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5952fdc9b1bc2f2d10da34a9621d90f277d070ac --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6dd475782f2897648a683c48b2fa015a15b8f06856760bddc8a17a63f418bacb +size 681 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..c297defc2bc3661d4f041c1c70f9dce231fda5b3 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:691c614ce432b3e62486efb54e5c84c6da5afe9b51b21253bde4758feb484183 +size 41779 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..8a1edbaea289636e62b83fc3b7a6e7f4303b7013 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40a8c7ea2d46711c5f78fc9a878a7db68b1543ba5cd60ecf14f519a2deb829b7 +size 682 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..0ef0ace9391c373fc45e0cbfe13967ff5bb87290 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6826f94d789d7bf1960668c1c5819c34c9585c1b23152fbc19ee81c7df08524b +size 705 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UCS2-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UCS2-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..159bf84b3f32c50d2b12d43a42e6ac5b481c7987 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UCS2-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:493de9fd1a08f7946065d8ab58f0c3c9fe489f5a0f109f2d05a3169b4bd5789f +size 689 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UTF8-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UTF8-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..99588fb50b1ed8feeab9b304fe23d3bd7d4987be --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISPro-UTF8-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6181d382cf736c5e09492e8be9f26f31fa25b7462253f23ab16646af432cad81 +size 726 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..c043d43eb7f295f5cb16dcabfc96f4043920e051 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:692044e1fb33445668632bc9fe7386805c624864be1ddeb29d65bb0c99fc630c +size 40517 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..98387f3dd58658c50fe682d8ef08f93b896c8ece --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd54e16ca7bffb3a886242549b2bf7d78a277087f7c60d2636f118c21a5b0646 +size 684 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..2ee68600481f9dd7541dd1922103498c5421037a --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f80ea5a989be30ccda5a8804baef6d3b4b044d2b339bf8b31c671b2466171cf6 +size 40608 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..5a79251ca15896f496503a3dba37df4a48042d88 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94c22bd99e771c5fbe0dd8dc39850570d4db0075074aca13e272813edd7cc57f +size 688 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UCS2-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UCS2-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..b1e72c89520ce1b526314d395e472ea268d3c8ae --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UCS2-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1081396ab4adb6f4a5b6c15f896963c244c1c9bcb65ce5616d06096a1b9811c +size 25783 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UCS2-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UCS2-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..8f419542c1b349b393dc41077b8fcd5fd488287c --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UCS2-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cab547431958fbdc1d401d06ebd4dd61a73f5509a10f974df32bcbca11a2e43 +size 178 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF16-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF16-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..e51da5009b4294351efb32c072e3093317907bff --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF16-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42d35b396286499dfae1737a07adb3a64500df37b426580bfb1d3ea872938519 +size 26327 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF16-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF16-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..f4d1c0da9d2a46f67b1f945a1145a192c20a9ea1 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF16-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bdb7390c80dcc136cb47d41dc7460082560969c17322ee739fe3020fb642410 +size 164 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF32-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF32-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..286bbc8779a8bc965fba4be95a8c7b6bdaa4d088 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF32-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a01ec51ed1b828101351e337ffb8250abe11880032e5210f881170fed2588de +size 26451 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF32-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF32-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..7e8c44cc489a9f70face27ec27ac25c2ca443b25 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF32-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfda895eceaed081af030dbbb962b49629eea817fc3c02bae15db93d0c68acd7 +size 168 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF8-H.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF8-H.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..bba9d92e682491e23f7b2df345e926b09649338e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF8-H.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fac9c65145f72d7d42157a3b9c5ed6904632184e6a0888f2b828699afd2002f +size 27790 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF8-V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF8-V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..fb9949f99ab1d926af0865fdec885df53d842f43 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/UniKS-UTF8-V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ecc6cf30dd354b9778ddba163b6cc7302b087ce9f39d1ba73472d2b75ed13ca +size 169 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/V.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/V.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a0c61bd5e4b7ca664a35dbfafe5b606213d1a02e --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/V.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9ad1c0c09ff14bca52f9a28a9767eb857ad0e8946e64ba14c7387a7eb69866a +size 166 diff --git a/packages/foliate-js/vendor/pdfjs/cmaps/WP-Symbol.bcmap b/packages/foliate-js/vendor/pdfjs/cmaps/WP-Symbol.bcmap new file mode 100644 index 0000000000000000000000000000000000000000..a09181c34917b2cff404edbc7cb9b2835c03bce9 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/cmaps/WP-Symbol.bcmap @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:543923bead225732aba30976690ee89095a19628277b5863efecc2c728d5d7bf +size 179 diff --git a/packages/foliate-js/vendor/pdfjs/pdf.mjs b/packages/foliate-js/vendor/pdfjs/pdf.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9fd81738d6fed03907f3b3ee43e44c1358c62e62 --- /dev/null +++ b/packages/foliate-js/vendor/pdfjs/pdf.mjs @@ -0,0 +1,20389 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * 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. + * 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. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ + +/******/ // 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), + OutputScale: () => (/* reexport */ OutputScale), + 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) +}); + +;// ./src/shared/util.js +const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); +const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; +const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; +const MAX_IMAGE_SIZE_TO_CACHE = 10e6; +const LINE_FACTOR = 1.35; +const LINE_DESCENT_FACTOR = 0.35; +const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR; +const RenderingIntentFlag = { + ANY: 0x01, + DISPLAY: 0x02, + PRINT: 0x04, + SAVE: 0x08, + ANNOTATIONS_FORMS: 0x10, + ANNOTATIONS_STORAGE: 0x20, + ANNOTATIONS_DISABLE: 0x40, + IS_EDITING: 0x80, + OPLIST: 0x100 +}; +const AnnotationMode = { + DISABLE: 0, + ENABLE: 1, + ENABLE_FORMS: 2, + ENABLE_STORAGE: 3 +}; +const AnnotationEditorPrefix = "pdfjs_internal_editor_"; +const AnnotationEditorType = { + DISABLE: -1, + NONE: 0, + FREETEXT: 3, + HIGHLIGHT: 9, + STAMP: 13, + INK: 15 +}; +const AnnotationEditorParamsType = { + RESIZE: 1, + CREATE: 2, + FREETEXT_SIZE: 11, + FREETEXT_COLOR: 12, + FREETEXT_OPACITY: 13, + INK_COLOR: 21, + INK_THICKNESS: 22, + INK_OPACITY: 23, + HIGHLIGHT_COLOR: 31, + HIGHLIGHT_DEFAULT_COLOR: 32, + HIGHLIGHT_THICKNESS: 33, + HIGHLIGHT_FREE: 34, + HIGHLIGHT_SHOW_ALL: 35 +}; +const PermissionFlag = { + PRINT: 0x04, + MODIFY_CONTENTS: 0x08, + COPY: 0x10, + MODIFY_ANNOTATIONS: 0x20, + FILL_INTERACTIVE_FORMS: 0x100, + COPY_FOR_ACCESSIBILITY: 0x200, + ASSEMBLE: 0x400, + PRINT_HIGH_QUALITY: 0x800 +}; +const TextRenderingMode = { + FILL: 0, + STROKE: 1, + FILL_STROKE: 2, + INVISIBLE: 3, + FILL_ADD_TO_PATH: 4, + STROKE_ADD_TO_PATH: 5, + FILL_STROKE_ADD_TO_PATH: 6, + ADD_TO_PATH: 7, + FILL_STROKE_MASK: 3, + ADD_TO_PATH_FLAG: 4 +}; +const util_ImageKind = { + GRAYSCALE_1BPP: 1, + RGB_24BPP: 2, + RGBA_32BPP: 3 +}; +const AnnotationType = { + TEXT: 1, + LINK: 2, + FREETEXT: 3, + LINE: 4, + SQUARE: 5, + CIRCLE: 6, + POLYGON: 7, + POLYLINE: 8, + HIGHLIGHT: 9, + UNDERLINE: 10, + SQUIGGLY: 11, + STRIKEOUT: 12, + STAMP: 13, + CARET: 14, + INK: 15, + POPUP: 16, + FILEATTACHMENT: 17, + SOUND: 18, + MOVIE: 19, + WIDGET: 20, + SCREEN: 21, + PRINTERMARK: 22, + TRAPNET: 23, + WATERMARK: 24, + THREED: 25, + REDACT: 26 +}; +const AnnotationReplyType = { + GROUP: "Group", + REPLY: "R" +}; +const AnnotationFlag = { + INVISIBLE: 0x01, + HIDDEN: 0x02, + PRINT: 0x04, + NOZOOM: 0x08, + NOROTATE: 0x10, + NOVIEW: 0x20, + READONLY: 0x40, + LOCKED: 0x80, + TOGGLENOVIEW: 0x100, + LOCKEDCONTENTS: 0x200 +}; +const AnnotationFieldFlag = { + READONLY: 0x0000001, + REQUIRED: 0x0000002, + NOEXPORT: 0x0000004, + MULTILINE: 0x0001000, + PASSWORD: 0x0002000, + NOTOGGLETOOFF: 0x0004000, + RADIO: 0x0008000, + PUSHBUTTON: 0x0010000, + COMBO: 0x0020000, + EDIT: 0x0040000, + SORT: 0x0080000, + FILESELECT: 0x0100000, + MULTISELECT: 0x0200000, + DONOTSPELLCHECK: 0x0400000, + DONOTSCROLL: 0x0800000, + COMB: 0x1000000, + RICHTEXT: 0x2000000, + RADIOSINUNISON: 0x2000000, + COMMITONSELCHANGE: 0x4000000 +}; +const AnnotationBorderStyleType = { + SOLID: 1, + DASHED: 2, + BEVELED: 3, + INSET: 4, + UNDERLINE: 5 +}; +const AnnotationActionEventType = { + E: "Mouse Enter", + X: "Mouse Exit", + D: "Mouse Down", + U: "Mouse Up", + Fo: "Focus", + Bl: "Blur", + PO: "PageOpen", + PC: "PageClose", + PV: "PageVisible", + PI: "PageInvisible", + K: "Keystroke", + F: "Format", + V: "Validate", + C: "Calculate" +}; +const DocumentActionEventType = { + WC: "WillClose", + WS: "WillSave", + DS: "DidSave", + WP: "WillPrint", + DP: "DidPrint" +}; +const PageActionEventType = { + O: "PageOpen", + C: "PageClose" +}; +const VerbosityLevel = { + ERRORS: 0, + WARNINGS: 1, + INFOS: 5 +}; +const CMapCompressionType = { + NONE: 0, + BINARY: 1 +}; +const OPS = { + dependency: 1, + setLineWidth: 2, + setLineCap: 3, + setLineJoin: 4, + setMiterLimit: 5, + setDash: 6, + setRenderingIntent: 7, + setFlatness: 8, + setGState: 9, + save: 10, + restore: 11, + transform: 12, + moveTo: 13, + lineTo: 14, + curveTo: 15, + curveTo2: 16, + curveTo3: 17, + closePath: 18, + rectangle: 19, + stroke: 20, + closeStroke: 21, + fill: 22, + eoFill: 23, + fillStroke: 24, + eoFillStroke: 25, + closeFillStroke: 26, + closeEOFillStroke: 27, + endPath: 28, + clip: 29, + eoClip: 30, + beginText: 31, + endText: 32, + setCharSpacing: 33, + setWordSpacing: 34, + setHScale: 35, + setLeading: 36, + setFont: 37, + setTextRenderingMode: 38, + setTextRise: 39, + moveText: 40, + setLeadingMoveText: 41, + setTextMatrix: 42, + nextLine: 43, + showText: 44, + showSpacedText: 45, + nextLineShowText: 46, + nextLineSetSpacingShowText: 47, + setCharWidth: 48, + setCharWidthAndBounds: 49, + setStrokeColorSpace: 50, + setFillColorSpace: 51, + setStrokeColor: 52, + setStrokeColorN: 53, + setFillColor: 54, + setFillColorN: 55, + setStrokeGray: 56, + setFillGray: 57, + setStrokeRGBColor: 58, + setFillRGBColor: 59, + setStrokeCMYKColor: 60, + setFillCMYKColor: 61, + shadingFill: 62, + beginInlineImage: 63, + beginImageData: 64, + endInlineImage: 65, + paintXObject: 66, + markPoint: 67, + markPointProps: 68, + beginMarkedContent: 69, + beginMarkedContentProps: 70, + endMarkedContent: 71, + beginCompat: 72, + endCompat: 73, + paintFormXObjectBegin: 74, + paintFormXObjectEnd: 75, + beginGroup: 76, + endGroup: 77, + beginAnnotation: 80, + endAnnotation: 81, + paintImageMaskXObject: 83, + paintImageMaskXObjectGroup: 84, + paintImageXObject: 85, + paintInlineImageXObject: 86, + paintInlineImageXObjectGroup: 87, + paintImageXObjectRepeat: 88, + paintImageMaskXObjectRepeat: 89, + paintSolidColorImageMask: 90, + constructPath: 91, + setStrokeTransparent: 92, + setFillTransparent: 93 +}; +const PasswordResponses = { + NEED_PASSWORD: 1, + INCORRECT_PASSWORD: 2 +}; +let verbosity = VerbosityLevel.WARNINGS; +function setVerbosityLevel(level) { + if (Number.isInteger(level)) { + verbosity = level; + } +} +function getVerbosityLevel() { + return verbosity; +} +function info(msg) { + if (verbosity >= VerbosityLevel.INFOS) { + console.log(`Info: ${msg}`); + } +} +function warn(msg) { + if (verbosity >= VerbosityLevel.WARNINGS) { + console.log(`Warning: ${msg}`); + } +} +function unreachable(msg) { + throw new Error(msg); +} +function assert(cond, msg) { + if (!cond) { + unreachable(msg); + } +} +function _isValidProtocol(url) { + switch (url?.protocol) { + case "http:": + case "https:": + case "ftp:": + case "mailto:": + case "tel:": + return true; + default: + return false; + } +} +function createValidAbsoluteUrl(url, baseUrl = null, options = null) { + if (!url) { + return null; + } + try { + if (options && typeof url === "string") { + if (options.addDefaultProtocol && url.startsWith("www.")) { + const dots = url.match(/\./g); + if (dots?.length >= 2) { + url = `http://${url}`; + } + } + if (options.tryConvertEncoding) { + try { + url = stringToUTF8String(url); + } catch {} + } + } + const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url); + if (_isValidProtocol(absoluteUrl)) { + return absoluteUrl; + } + } catch {} + return null; +} +function shadow(obj, prop, value, nonSerializable = false) { + Object.defineProperty(obj, prop, { + value, + enumerable: !nonSerializable, + configurable: true, + writable: false + }); + return value; +} +const BaseException = function BaseExceptionClosure() { + function BaseException(message, name) { + this.message = message; + this.name = name; + } + BaseException.prototype = new Error(); + BaseException.constructor = BaseException; + return BaseException; +}(); +class PasswordException extends BaseException { + constructor(msg, code) { + super(msg, "PasswordException"); + this.code = code; + } +} +class UnknownErrorException extends BaseException { + constructor(msg, details) { + super(msg, "UnknownErrorException"); + this.details = details; + } +} +class InvalidPDFException extends BaseException { + constructor(msg) { + super(msg, "InvalidPDFException"); + } +} +class MissingPDFException extends BaseException { + constructor(msg) { + super(msg, "MissingPDFException"); + } +} +class UnexpectedResponseException extends BaseException { + constructor(msg, status) { + super(msg, "UnexpectedResponseException"); + this.status = status; + } +} +class FormatError extends BaseException { + constructor(msg) { + super(msg, "FormatError"); + } +} +class AbortException extends BaseException { + constructor(msg) { + super(msg, "AbortException"); + } +} +function bytesToString(bytes) { + if (typeof bytes !== "object" || bytes?.length === undefined) { + unreachable("Invalid argument for bytesToString"); + } + const length = bytes.length; + const MAX_ARGUMENT_COUNT = 8192; + if (length < MAX_ARGUMENT_COUNT) { + return String.fromCharCode.apply(null, bytes); + } + const strBuf = []; + for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) { + const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); + const chunk = bytes.subarray(i, chunkEnd); + strBuf.push(String.fromCharCode.apply(null, chunk)); + } + return strBuf.join(""); +} +function stringToBytes(str) { + if (typeof str !== "string") { + unreachable("Invalid argument for stringToBytes"); + } + const length = str.length; + const bytes = new Uint8Array(length); + for (let i = 0; i < length; ++i) { + bytes[i] = str.charCodeAt(i) & 0xff; + } + return bytes; +} +function string32(value) { + return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff); +} +function objectSize(obj) { + return Object.keys(obj).length; +} +function objectFromMap(map) { + const obj = Object.create(null); + for (const [key, value] of map) { + obj[key] = value; + } + return obj; +} +function isLittleEndian() { + const buffer8 = new Uint8Array(4); + buffer8[0] = 1; + const view32 = new Uint32Array(buffer8.buffer, 0, 1); + return view32[0] === 1; +} +function isEvalSupported() { + try { + new Function(""); + return true; + } catch { + return false; + } +} +class util_FeatureTest { + static get isLittleEndian() { + return shadow(this, "isLittleEndian", isLittleEndian()); + } + static get isEvalSupported() { + return shadow(this, "isEvalSupported", isEvalSupported()); + } + static get isOffscreenCanvasSupported() { + return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined"); + } + static get platform() { + if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") { + return shadow(this, "platform", { + isMac: navigator.platform.includes("Mac"), + isWindows: navigator.platform.includes("Win"), + isFirefox: typeof navigator?.userAgent === "string" && navigator.userAgent.includes("Firefox") + }); + } + return shadow(this, "platform", { + isMac: false, + isWindows: false, + isFirefox: false + }); + } + static get isCSSRoundSupported() { + return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)")); + } +} +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]}`; + } + static scaleMinMax(transform, minMax) { + let temp; + if (transform[0]) { + if (transform[0] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[0]; + minMax[2] *= transform[0]; + if (transform[3] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[3]; + minMax[3] *= transform[3]; + } else { + temp = minMax[0]; + minMax[0] = minMax[1]; + minMax[1] = temp; + temp = minMax[2]; + minMax[2] = minMax[3]; + minMax[3] = temp; + if (transform[1] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[1]; + minMax[3] *= transform[1]; + if (transform[2] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[2]; + minMax[2] *= transform[2]; + } + minMax[0] += transform[4]; + minMax[1] += transform[5]; + minMax[2] += transform[4]; + minMax[3] += transform[5]; + } + static transform(m1, m2) { + return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]]; + } + static applyTransform(p, m) { + const xt = p[0] * m[0] + p[1] * m[2] + m[4]; + const yt = p[0] * m[1] + p[1] * m[3] + m[5]; + return [xt, yt]; + } + static applyInverseTransform(p, m) { + const d = m[0] * m[3] - m[1] * m[2]; + const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; + const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; + return [xt, yt]; + } + static getAxialAlignedBoundingBox(r, m) { + const p1 = this.applyTransform(r, m); + const p2 = this.applyTransform(r.slice(2, 4), m); + const p3 = this.applyTransform([r[0], r[3]], m); + const p4 = this.applyTransform([r[2], r[1]], m); + return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])]; + } + static inverseTransform(m) { + const d = m[0] * m[3] - m[1] * m[2]; + return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; + } + static singularValueDecompose2dScale(m) { + const transpose = [m[0], m[2], m[1], m[3]]; + const a = m[0] * transpose[0] + m[1] * transpose[2]; + const b = m[0] * transpose[1] + m[1] * transpose[3]; + const c = m[2] * transpose[0] + m[3] * transpose[2]; + const d = m[2] * transpose[1] + m[3] * transpose[3]; + const first = (a + d) / 2; + const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2; + const sx = first + second || 1; + const sy = first - second || 1; + return [Math.sqrt(sx), Math.sqrt(sy)]; + } + static normalizeRect(rect) { + const r = rect.slice(0); + if (rect[0] > rect[2]) { + r[0] = rect[2]; + r[2] = rect[0]; + } + if (rect[1] > rect[3]) { + r[1] = rect[3]; + r[3] = rect[1]; + } + return r; + } + static intersect(rect1, rect2) { + const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2])); + const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2])); + if (xLow > xHigh) { + return null; + } + const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3])); + const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3])); + if (yLow > yHigh) { + return null; + } + return [xLow, yLow, xHigh, yHigh]; + } + static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) { + if (t <= 0 || t >= 1) { + return; + } + 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; + } + 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; + } +} +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"; + } + if (encoding) { + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(str); + const decoded = decoder.decode(buffer); + if (!decoded.includes("\x1b")) { + return decoded; + } + return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, ""); + } catch (ex) { + warn(`stringToPDFString: "${ex}".`); + } + } + } + const strBuf = []; + for (let i = 0, ii = str.length; i < ii; 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(""); +} +function stringToUTF8String(str) { + return decodeURIComponent(escape(str)); +} +function utf8StringToString(str) { + return unescape(encodeURIComponent(str)); +} +function isArrayEqual(arr1, arr2) { + if (arr1.length !== arr2.length) { + return false; + } + for (let i = 0, ii = arr1.length; i < ii; i++) { + if (arr1[i] !== arr2[i]) { + return false; + } + } + return true; +} +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(""); +} +let NormalizeRegex = null; +let NormalizationMap = null; +function normalizeUnicode(str) { + if (!NormalizeRegex) { + 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) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2)); +} +function getUuid() { + if (typeof crypto !== "undefined" && typeof crypto?.randomUUID === "function") { + return crypto.randomUUID(); + } + const buf = new Uint8Array(32); + if (typeof crypto !== "undefined" && typeof crypto?.getRandomValues === "function") { + crypto.getRandomValues(buf); + } else { + for (let i = 0; i < 32; i++) { + buf[i] = Math.floor(Math.random() * 255); + } + } + return bytesToString(buf); +} +const AnnotationPrefix = "pdfjs_internal_id_"; +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 +}; + +;// ./src/display/base_factory.js + +class BaseFilterFactory { + addFilter(maps) { + return "none"; + } + 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 + }) + }; + } + 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; + } + 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; + } + _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."); + } +} + +;// ./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 = globalThis.document + }) { + super(); + this.#docId = docId; + this.#document = ownerDocument; + } + 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(","); + }; + this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter); + info.url = this.#createUrl(id); + return info.url; + } + addAlphaFilter(map) { + let value = this.#cache.get(map); + if (value) { + return value; + } + const [tableA] = this.#createTables([map]); + const key = `alpha_${tableA}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; + } + 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; + } + addLuminosityFilter(map) { + let value = this.#cache.get(map || "luminosity"); + if (value) { + return value; + } + let tableA, key; + if (map) { + [tableA] = this.#createTables([map]); + key = `luminosity_${tableA}`; + } else { + key = "luminosity"; + } + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; + } + 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; + } + 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; + } + 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; + } + 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; + } + #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); + } + #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); + } + #addTransferMapAlphaConversion(aTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable); + } + #getRGB(color) { + this.#defs.style.color = color; + return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); + } +} +class DOMCanvasFactory extends BaseCanvasFactory { + constructor({ + ownerDocument = globalThis.document, + enableHWA = false + }) { + super({ + enableHWA + }); + this._document = ownerDocument; + } + _createCanvas(width, height) { + const canvas = this._document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + } +} +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(); + } + 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 + })); + } +} +class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { + _fetchData(url) { + return fetchData(url, "arraybuffer").then(data => new Uint8Array(data)); + } +} +class DOMSVGFactory extends BaseSVGFactory { + _createSVG(type) { + return document.createElementNS(SVG_NS, type); + } +} +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; + 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 PageViewport({ + viewBox: this.viewBox.slice(), + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + convertToViewportPoint(x, y) { + return Util.applyTransform([x, y], this.transform); + } + 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]]; + } + convertToPdfPoint(x, y) { + return Util.applyInverseTransform([x, y], this.transform); + } +} +class RenderingCancelledException extends BaseException { + constructor(msg, extraDelay = 0) { + super(msg, "RenderingCancelledException"); + this.extraDelay = extraDelay; + } +} +function isDataScheme(url) { + const ii = url.length; + let i = 0; + while (i < ii && url[i].trim() === "") { + i++; + } + return url.substring(i, i + 5).toLowerCase() === "data:"; +} +function isPdfFile(filename) { + return typeof filename === "string" && /\.pdf$/i.test(filename); +} +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 {} + } + } + return suggestedFilename || defaultFilename; +} +class StatTimer { + started = Object.create(null); + times = []; + time(name) { + if (name in this.started) { + warn(`Timer is already running for ${name}`); + } + this.started[name] = Date.now(); + } + timeEnd(name) { + if (!(name in this.started)) { + warn(`Timer has not been started for ${name}`); + } + this.times.push({ + name, + start: this.started[name], + end: Date.now() + }); + delete this.started[name]; + } + toString() { + const outBuf = []; + let longest = 0; + for (const { + name + } of this.times) { + longest = Math.max(name.length, longest); + } + for (const { + name, + start, + end + } of this.times) { + outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`); + } + return outBuf.join(""); + } +} +function isValidFetchUrl(url, baseUrl) { + try { + const { + protocol + } = baseUrl ? new URL(url, baseUrl) : new URL(url); + return protocol === "http:" || protocol === "https:"; + } catch { + return false; + } +} +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; + } + 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)); + } +} +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]; + } + 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); + } + 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) { + const { + pageWidth, + pageHeight + } = viewport.rawDims; + 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(down, ${w}, var(--scale-round-x, 1px))` : `calc(${w})`, + heightStr = useRound ? `round(down, ${h}, var(--scale-round-y, 1px))` : `calc(${h})`; + if (!mustFlip || viewport.rotation % 180 === 0) { + style.width = widthStr; + style.height = heightStr; + } else { + style.width = heightStr; + style.height = widthStr; + } + } + if (mustRotate) { + div.setAttribute("data-main-rotation", viewport.rotation); + } +} +class OutputScale { + constructor() { + const pixelRatio = window.devicePixelRatio || 1; + this.sx = pixelRatio; + this.sy = pixelRatio; + } + get scaled() { + return this.sx !== 1 || this.sy !== 1; + } + get symmetric() { + return this.sx === this.sy; + } +} + +;// ./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" + }); + } + render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.classList.add("editToolbar", "hidden"); + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#editor._uiManager._signal; + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal + }); + 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; + } + get div() { + return this.#toolbar; + } + 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.#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; + } + } + return [isLTR ? 1 - lastX : lastX, lastY]; + } + show(parent, boxes, isLTR) { + const [x, y] = this.#getLastPoint(boxes, isLTR); + const { + style + } = this.#toolbar ||= this.#render(); + parent.append(this.#toolbar); + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`; + } + hide() { + this.#toolbar.remove(); + } + #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); + } +} + +;// ./src/display/editor/tools.js + + + +function bindEvents(obj, element, names) { + for (const name of names) { + element.addEventListener(name, obj[name].bind(obj)); + } +} +function opacityToHex(opacity) { + return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0"); +} +class IdManager { + #id = 0; + get id() { + return `${AnnotationEditorPrefix}${this.#id++}`; + } +} +class ImageManager { + #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", { + 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 shadow(this, "_isSVGFittingCanvas", promise); + } + async #get(key, rawData) { + this.#cache ||= new Map(); + let data = this.#cache.get(key); + if (data === null) { + return null; + } + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + try { + data ||= { + bitmap: null, + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 0, + isSvg: false + }; + let image; + if (typeof rawData === "string") { + data.url = rawData; + image = await fetchData(rawData, "blob"); + } else if (rawData instanceof File) { + image = data.file = rawData; + } else if (rawData instanceof Blob) { + image = rawData; + } + if (image.type === "image/svg+xml") { + const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas; + const fileReader = new FileReader(); + const imageElement = new Image(); + const imagePromise = new Promise((resolve, reject) => { + imageElement.onload = () => { + data.bitmap = imageElement; + data.isSvg = true; + resolve(); + }; + fileReader.onload = async () => { + const url = data.svgUrl = fileReader.result; + imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url; + }; + imageElement.onerror = fileReader.onerror = reject; + }); + fileReader.readAsDataURL(image); + await imagePromise; + } else { + data.bitmap = await createImageBitmap(image); + } + data.refCounter = 1; + } catch (e) { + console.error(e); + data = null; + } + this.#cache.set(key, data); + if (data) { + this.#cache.set(data.id, data); + } + return data; + } + async getFromFile(file) { + const { + lastModified, + name, + size, + type + } = file; + return this.#get(`${lastModified}_${name}_${size}_${type}`, file); + } + async getFromUrl(url) { + return this.#get(url, url); + } + async getFromBlob(id, blobPromise) { + const blob = await blobPromise; + return this.#get(id, blob); + } + async getFromId(id) { + this.#cache ||= new Map(); + const data = this.#cache.get(id); + if (!data) { + return null; + } + if (data.bitmap) { + data.refCounter += 1; + return data; + } + if (data.file) { + return this.getFromFile(data.file); + } + if (data.blobPromise) { + const { + blobPromise + } = data; + delete data.blobPromise; + return this.getFromBlob(data.id, blobPromise); + } + return this.getFromUrl(data.url); + } + getFromCanvas(id, canvas) { + this.#cache ||= new Map(); + let data = this.#cache.get(id); + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + const offscreen = new OffscreenCanvas(canvas.width, canvas.height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(canvas, 0, 0); + data = { + bitmap: offscreen.transferToImageBitmap(), + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 1, + isSvg: false + }; + this.#cache.set(id, data); + this.#cache.set(data.id, data); + return data; + } + getSvgUrl(id) { + const data = this.#cache.get(id); + if (!data?.isSvg) { + return null; + } + return data.svgUrl; + } + deleteId(id) { + this.#cache ||= new Map(); + const data = this.#cache.get(id); + if (!data) { + return; + } + data.refCounter -= 1; + if (data.refCounter !== 0) { + return; + } + const { + bitmap + } = data; + if (!data.url && !data.file) { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = canvas.getContext("bitmaprenderer"); + ctx.transferFromImageBitmap(bitmap); + data.blobPromise = canvas.convertToBlob(); + } + bitmap.close?.(); + data.bitmap = null; + } + isValidId(id) { + return id.startsWith(`image_${this.#baseId}_`); + } +} +class CommandManager { + #commands = []; + #locked = false; + #maxSize; + #position = -1; + constructor(maxSize = 128) { + this.#maxSize = maxSize; + } + add({ + cmd, + undo, + post, + mustExec, + type = NaN, + overwriteIfSameType = false, + keepUndo = false + }) { + if (mustExec) { + cmd(); + } + if (this.#locked) { + return; + } + const save = { + cmd, + undo, + post, + type + }; + if (this.#position === -1) { + if (this.#commands.length > 0) { + this.#commands.length = 0; + } + this.#position = 0; + this.#commands.push(save); + return; + } + if (overwriteIfSameType && this.#commands[this.#position].type === type) { + if (keepUndo) { + save.undo = this.#commands[this.#position].undo; + } + this.#commands[this.#position] = save; + return; + } + const next = this.#position + 1; + if (next === this.#maxSize) { + this.#commands.splice(0, 1); + } else { + this.#position = next; + if (next < this.#commands.length) { + this.#commands.splice(next); + } + } + this.#commands.push(save); + } + undo() { + if (this.#position === -1) { + return; + } + this.#locked = true; + const { + undo, + post + } = this.#commands[this.#position]; + undo(); + post?.(); + this.#locked = false; + this.#position -= 1; + } + redo() { + if (this.#position < this.#commands.length - 1) { + this.#position += 1; + this.#locked = true; + const { + cmd, + post + } = this.#commands[this.#position]; + cmd(); + post?.(); + this.#locked = false; + } + } + hasSomethingToUndo() { + return this.#position !== -1; + } + hasSomethingToRedo() { + return this.#position < this.#commands.length - 1; + } + destroy() { + this.#commands = null; + } +} +class KeyboardManager { + constructor(callbacks) { + this.buffer = []; + this.callbacks = new Map(); + this.allKeys = new Set(); + const { + isMac + } = util_FeatureTest.platform; + for (const [keys, callback, options = {}] of callbacks) { + for (const key of keys) { + const isMacKey = key.startsWith("mac+"); + if (isMac && isMacKey) { + this.callbacks.set(key.slice(4), { + callback, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } else if (!isMac && !isMacKey) { + this.callbacks.set(key, { + callback, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } + } + } + } + #serialize(event) { + if (event.altKey) { + this.buffer.push("alt"); + } + if (event.ctrlKey) { + this.buffer.push("ctrl"); + } + if (event.metaKey) { + this.buffer.push("meta"); + } + if (event.shiftKey) { + this.buffer.push("shift"); + } + this.buffer.push(event.key); + const str = this.buffer.join("+"); + this.buffer.length = 0; + return str; + } + exec(self, event) { + if (!this.allKeys.has(event.key)) { + return; + } + const info = this.callbacks.get(this.#serialize(event)); + if (!info) { + return; + } + const { + callback, + options: { + bubbles = false, + args = [], + checker = null + } + } = info; + if (checker && !checker(self, event)) { + return; + } + callback.bind(self, ...args, event)(); + if (!bubbles) { + event.stopPropagation(); + event.preventDefault(); + } + } +} +class ColorManager { + static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]); + get _colors() { + const colors = new Map([["CanvasText", null], ["Canvas", null]]); + getColorValues(colors); + return shadow(this, "_colors", colors); + } + convert(color) { + const rgb = getRGB(color); + if (!window.matchMedia("(forced-colors: active)").matches) { + return rgb; + } + for (const [name, RGB] of this._colors) { + if (RGB.every((x, i) => x === rgb[i])) { + return ColorManager._colorsMapping.get(name); + } + } + return rgb; + } + getHexCode(name) { + const rgb = this._colors.get(name); + if (!rgb) { + return name; + } + return Util.makeHexColor(...rgb); + } +} +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; + #mainHighlightColorPicker = null; + #mlManager = null; + #mode = AnnotationEditorType.NONE; + #selectedEditors = new Set(); + #selectedTextNode = null; + #pageColors = null; + #showAllStates = null; + #previousStates = { + isEditing: false, + isEmpty: true, + hasSomethingToUndo: false, + hasSomethingToRedo: false, + hasSelectedEditor: false, + hasSelectedText: false + }; + #translation = [0, 0]; + #translationTimeoutId = null; + #container = null; + #viewer = null; + #updateModeCapability = null; + static TRANSLATE_SMALL = 1; + static TRANSLATE_BIG = 10; + static get _keyboardManager() { + const proto = AnnotationEditorUIManager.prototype; + 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 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, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, { + args: [0, big], + checker: arrowChecker + }]])); + } + 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; + 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: PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: 0 + }; + this.isShiftKeyDown = false; + } + destroy() { + this.#updateModeCapability?.resolve(); + this.#updateModeCapability = null; + this.#abortController?.abort(); + this.#abortController = null; + this._signal = null; + for (const layer of this.#allLayers.values()) { + layer.destroy(); + } + this.#allLayers.clear(); + this.#allEditors.clear(); + this.#editorsToRescale.clear(); + this.#activeEditor = null; + this.#selectedEditors.clear(); + this.#commandManager.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 shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); + } + get direction() { + return shadow(this, "direction", getComputedStyle(this.#container).direction); + } + 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 + }) { + this.#currentPageIndex = pageNumber - 1; + } + focusMainContainer() { + this.#container.focus(); + } + findParent(x, y) { + for (const layer of this.#allLayers.values()) { + const { + x: layerX, + y: layerY, + width, + height + } = layer.div.getBoundingClientRect(); + if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) { + return layer; + } + } + return null; + } + disableUserSelect(value = false) { + this.#viewer.classList.toggle("noUserSelect", value); + } + addShouldRescale(editor) { + this.#editorsToRescale.add(editor); + } + removeShouldRescale(editor) { + this.#editorsToRescale.delete(editor); + } + onScaleChanging({ + scale + }) { + this.commitOrRemove(); + this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS; + for (const editor of this.#editorsToRescale) { + editor.onScaleChanging(); + } + } + onRotationChanging({ + pagesRotation + }) { + 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() { + 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() { + this.#focusManagerAC?.abort(); + this.#focusManagerAC = null; + } + blur() { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + if (!this.hasSelection) { + return; + } + const { + activeElement + } = document; + for (const editor of this.#selectedEditors) { + if (editor.div.contains(activeElement)) { + this.#lastActiveElement = [editor, activeElement]; + editor._focusEventsAllowed = false; + break; + } + } + } + focus() { + if (!this.#lastActiveElement) { + return; + } + const [lastEditor, lastActiveElement] = this.#lastActiveElement; + this.#lastActiveElement = null; + lastActiveElement.addEventListener("focusin", () => { + lastEditor._focusEventsAllowed = true; + }, { + once: true, + signal: this._signal + }); + lastActiveElement.focus(); + } + #addKeyboardManager() { + 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() { + this.#keyboardManagerAC?.abort(); + this.#keyboardManagerAC = null; + } + #addCopyPasteListeners() { + 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() { + 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(); + this.#addCopyPasteListeners(); + } + removeEditListeners() { + 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(); + if (!this.hasSelection) { + return; + } + const editors = []; + for (const editor of this.#selectedEditors) { + const serialized = editor.serialize(true); + if (serialized) { + editors.push(serialized); + } + } + if (editors.length === 0) { + return; + } + event.clipboardData.setData("application/pdfjs", JSON.stringify(editors)); + } + cut(event) { + this.copy(event); + this.delete(); + } + async paste(event) { + event.preventDefault(); + const { + clipboardData + } = event; + for (const item of clipboardData.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + return; + } + } + } + let data = clipboardData.getData("application/pdfjs"); + if (!data) { + return; + } + try { + data = JSON.parse(data); + } catch (ex) { + warn(`paste: "${ex.message}".`); + return; + } + if (!Array.isArray(data)) { + return; + } + this.unselectAll(); + const layer = this.currentLayer; + try { + const newEditors = []; + for (const editor of data) { + const deserializedEditor = await layer.deserialize(editor); + if (!deserializedEditor) { + return; + } + newEditors.push(deserializedEditor); + } + const cmd = () => { + for (const editor of newEditors) { + this.#addEditorToLayer(editor); + } + this.#selectEditors(newEditors); + }; + const undo = () => { + for (const editor of newEditors) { + editor.remove(); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } catch (ex) { + warn(`paste: "${ex.message}".`); + } + } + keydown(event) { + if (!this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = true; + } + if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) { + AnnotationEditorUIManager._keyboardManager.exec(this, event); + } + } + 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) { + const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value); + if (hasChanged) { + this._eventBus.dispatch("annotationeditorstateschanged", { + source: this, + details: Object.assign(this.#previousStates, details) + }); + if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]); + } + } + } + #dispatchUpdateUI(details) { + this._eventBus.dispatch("annotationeditorparamschanged", { + source: this, + details + }); + } + setEditingState(isEditing) { + if (isEditing) { + this.#addFocusManager(); + this.#addCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: this.#mode !== AnnotationEditorType.NONE, + isEmpty: this.#isEmpty(), + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + hasSelectedEditor: false + }); + } else { + this.#removeFocusManager(); + this.#removeCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: false + }); + this.disableUserSelect(false); + } + } + registerEditorTypes(types) { + if (this.#editorTypes) { + return; + } + this.#editorTypes = types; + for (const editorType of this.#editorTypes) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + } + getId() { + return this.#idManager.id; + } + get currentLayer() { + return this.#allLayers.get(this.#currentPageIndex); + } + getLayer(pageIndex) { + return this.#allLayers.get(pageIndex); + } + get currentPageIndex() { + return this.#currentPageIndex; + } + addLayer(layer) { + this.#allLayers.set(layer.pageIndex, layer); + if (this.#isEnabled) { + layer.enable(); + } else { + layer.disable(); + } + } + removeLayer(layer) { + this.#allLayers.delete(layer.pageIndex); + } + async updateMode(mode, editId = null, isFromKeyboard = false) { + if (this.#mode === mode) { + return; + } + if (this.#updateModeCapability) { + await this.#updateModeCapability.promise; + if (!this.#updateModeCapability) { + return; + } + } + this.#updateModeCapability = Promise.withResolvers(); + this.#mode = mode; + if (mode === AnnotationEditorType.NONE) { + this.setEditingState(false); + this.#disableAll(); + this.#updateModeCapability.resolve(); + return; + } + this.setEditingState(true); + await this.#enableAll(); + this.unselectAll(); + for (const layer of this.#allLayers.values()) { + layer.updateMode(mode); + } + if (!editId) { + if (isFromKeyboard) { + this.addNewEditorFromKeyboard(); + } + this.#updateModeCapability.resolve(); + return; + } + for (const editor of this.#allEditors.values()) { + if (editor.annotationElementId === editId) { + this.setSelected(editor); + editor.enterInEditMode(); + } else { + editor.unselect(); + } + } + this.#updateModeCapability.resolve(); + } + addNewEditorFromKeyboard() { + if (this.currentLayer.canCreateNewEmptyEditor()) { + this.currentLayer.addNewEditor(); + } + } + updateToolbar(mode) { + if (mode === this.#mode) { + return; + } + this._eventBus.dispatch("switchannotationeditormode", { + source: this, + mode + }); + } + updateParams(type, value) { + if (!this.#editorTypes) { + 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); + } + for (const editorType of this.#editorTypes) { + 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; + } + this.#isWaiting = mustWait; + for (const layer of this.#allLayers.values()) { + if (mustWait) { + layer.disableClick(); + } else { + layer.enableClick(); + } + layer.div.classList.toggle("waiting", mustWait); + } + } + async #enableAll() { + if (!this.#isEnabled) { + this.#isEnabled = true; + const promises = []; + for (const layer of this.#allLayers.values()) { + promises.push(layer.enable()); + } + await Promise.all(promises); + for (const editor of this.#allEditors.values()) { + editor.enable(); + } + } + } + #disableAll() { + this.unselectAll(); + if (this.#isEnabled) { + this.#isEnabled = false; + for (const layer of this.#allLayers.values()) { + layer.disable(); + } + for (const editor of this.#allEditors.values()) { + editor.disable(); + } + } + } + getEditors(pageIndex) { + const editors = []; + for (const editor of this.#allEditors.values()) { + if (editor.pageIndex === pageIndex) { + editors.push(editor); + } + } + return editors; + } + getEditor(id) { + return this.#allEditors.get(id); + } + addEditor(editor) { + 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)) { + this.#annotationStorage?.remove(editor.id); + } + } + addDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.add(editor.annotationElementId); + this.addChangedExistingAnnotation(editor); + editor.deleted = true; + } + isDeletedAnnotationElement(annotationElementId) { + return this.#deletedAnnotationsElementIds.has(annotationElementId); + } + removeDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.delete(editor.annotationElementId); + this.removeChangedExistingAnnotation(editor); + editor.deleted = false; + } + #addEditorToLayer(editor) { + const layer = this.#allLayers.get(editor.pageIndex); + if (layer) { + layer.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + } + } + setActiveEditor(editor) { + if (this.#activeEditor === editor) { + return; + } + this.#activeEditor = editor; + if (editor) { + 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); + editor.unselect(); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + return; + } + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + setSelected(editor) { + for (const ed of this.#selectedEditors) { + if (ed !== editor) { + ed.unselect(); + } + } + this.#selectedEditors.clear(); + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + isSelected(editor) { + return this.#selectedEditors.has(editor); + } + get firstSelectedEditor() { + return this.#selectedEditors.values().next().value; + } + unselect(editor) { + editor.unselect(); + this.#selectedEditors.delete(editor); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + get hasSelection() { + return this.#selectedEditors.size !== 0; + } + get isEnterHandled() { + return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled; + } + undo() { + this.#commandManager.undo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: true, + isEmpty: this.#isEmpty() + }); + } + redo() { + this.#commandManager.redo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + isEmpty: this.#isEmpty() + }); + } + addCommands(params) { + this.#commandManager.add(params); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: false, + isEmpty: this.#isEmpty() + }); + } + #isEmpty() { + if (this.#allEditors.size === 0) { + return true; + } + if (this.#allEditors.size === 1) { + for (const editor of this.#allEditors.values()) { + return editor.isEmpty(); + } + } + return false; + } + delete() { + this.commitOrRemove(); + if (!this.hasSelection) { + return; + } + const editors = [...this.#selectedEditors]; + const cmd = () => { + for (const editor of editors) { + editor.remove(); + } + }; + const undo = () => { + for (const editor of editors) { + this.#addEditorToLayer(editor); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } + commitOrRemove() { + this.#activeEditor?.commitOrRemove(); + } + hasSomethingToControl() { + 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()) { + continue; + } + this.#selectedEditors.add(editor); + editor.select(); + } + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + selectAll() { + for (const editor of this.#selectedEditors) { + editor.commit(); + } + this.#selectEditors(this.#allEditors.values()); + } + unselectAll() { + if (this.#activeEditor) { + this.#activeEditor.commitOrRemove(); + if (this.#mode !== AnnotationEditorType.NONE) { + return; + } + } + if (!this.hasSelection) { + return; + } + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + this.#dispatchUpdateStates({ + hasSelectedEditor: false + }); + } + translateSelectedEditors(x, y, noCommit = false) { + if (!noCommit) { + this.commitOrRemove(); + } + if (!this.hasSelection) { + return; + } + this.#translation[0] += x; + this.#translation[1] += y; + const [totalX, totalY] = this.#translation; + const editors = [...this.#selectedEditors]; + const TIME_TO_WAIT = 1000; + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + } + this.#translationTimeoutId = setTimeout(() => { + this.#translationTimeoutId = null; + this.#translation[0] = this.#translation[1] = 0; + this.addCommands({ + cmd: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(totalX, totalY); + } + } + }, + undo: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(-totalX, -totalY); + } + } + }, + mustExec: false + }); + }, TIME_TO_WAIT); + for (const editor of editors) { + editor.translateInPage(x, y); + } + } + setUpDragSession() { + if (!this.hasSelection) { + return; + } + this.disableUserSelect(true); + this.#draggingEditors = new Map(); + for (const editor of this.#selectedEditors) { + this.#draggingEditors.set(editor, { + savedX: editor.x, + savedY: editor.y, + savedPageIndex: editor.pageIndex, + newX: 0, + newY: 0, + newPageIndex: -1 + }); + } + } + endDragSession() { + if (!this.#draggingEditors) { + return false; + } + this.disableUserSelect(false); + const map = this.#draggingEditors; + this.#draggingEditors = null; + let mustBeAddedInUndoStack = false; + for (const [{ + x, + y, + pageIndex + }, value] of map) { + value.newX = x; + value.newY = y; + value.newPageIndex = pageIndex; + mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex; + } + if (!mustBeAddedInUndoStack) { + return false; + } + const move = (editor, x, y, pageIndex) => { + if (this.#allEditors.has(editor.id)) { + const parent = this.#allLayers.get(pageIndex); + if (parent) { + editor._setParentAndPosition(parent, x, y); + } else { + editor.pageIndex = pageIndex; + editor.x = x; + editor.y = y; + } + } + }; + this.addCommands({ + cmd: () => { + for (const [editor, { + newX, + newY, + newPageIndex + }] of map) { + move(editor, newX, newY, newPageIndex); + } + }, + undo: () => { + for (const [editor, { + savedX, + savedY, + savedPageIndex + }] of map) { + move(editor, savedX, savedY, savedPageIndex); + } + }, + mustExec: true + }); + return true; + } + dragSelectedEditors(tx, ty) { + if (!this.#draggingEditors) { + return; + } + for (const editor of this.#draggingEditors.keys()) { + editor.drag(tx, ty); + } + } + rebuild(editor) { + if (editor.parent === null) { + const parent = this.getLayer(editor.pageIndex); + if (parent) { + parent.changeParent(editor); + parent.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + editor.rebuild(); + } + } else { + editor.parent.addOrRebuild(editor); + } + } + get isEditorHandlingKeyboard() { + return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents(); + } + isActive(editor) { + return this.#activeEditor === editor; + } + getActive() { + return this.#activeEditor; + } + getMode() { + return this.#mode; + } + get imageManager() { + return shadow(this, "imageManager", new ImageManager()); + } + getSelectionBoxes(textLayer) { + if (!textLayer) { + return null; + } + const selection = document.getSelection(); + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) { + return null; + } + } + 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 "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": + rotator = (x, y, w, h) => ({ + x: 1 - (y + h - layerY) / parentHeight, + y: (x - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); + break; + default: + rotator = (x, y, w, h) => ({ + x: (x - layerX) / parentWidth, + y: (y - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); + break; + } + 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)); + } + } + 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); + } +} + +;// ./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 #l10nNewButton = null; + static _l10nPromise = null; + constructor(editor) { + this.#editor = editor; + this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow; + AltText.#l10nNewButton ||= Object.freeze({ + added: "pdfjs-editor-new-alt-text-added-button-label", + missing: "pdfjs-editor-new-alt-text-missing-button-label", + review: "pdfjs-editor-new-alt-text-to-review-button-label" + }); + } + 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(AltText.#l10nNewButton.missing); + } else { + msg = await AltText._l10nPromise.get("pdfjs-editor-alt-text-button-label"); + } + 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 #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 + } + }); + } + 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) { + button.classList.toggle("done", !!this.#altText); + AltText._l10nPromise.get(AltText.#l10nNewButton[this.#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"); + tooltip.id = `alt-text-tooltip-${this.#editor.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); + } +} + +;// ./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); + _initialData = 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, + 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); + } + 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" + }); + 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)); + } + } + 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) { + return false; + } + 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); + } + } + 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" + }); + } + get _hasBeenMoved() { + return !!this.#initialPosition && (this.#initialPosition[0] !== this.x || this.#initialPosition[1] !== this.y); + } + getBaseTranslation() { + const [parentWidth, parentHeight] = this.parentDimensions; + 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]; + } + } + 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 + } = 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; + return [pageWidth * parentScale, pageHeight * parentScale]; + } + 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 { + 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(); + } + addContainer(container) { + const editToolbarDiv = this._editToolbar?.div; + if (editToolbarDiv) { + editToolbarDiv.before(container); + } else { + this.div.append(container); + } + } + 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); + } + } + #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 + }); + } + 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"); + } + } + 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 this.#isResizerEnabledForKeyboard; + } + needsToBeRebuilt() { + return this.div && !this.isAttachedToDOM; + } + #addFocusListeners() { + if (this.#focusAC || !this.div) { + return; + } + 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) {} + serializeDeleted() { + return { + id: this.annotationElementId, + deleted: true, + pageIndex: this.pageIndex, + popupRef: this._initialData?.popupRef || "" + }; + } + serialize(isForCopying = false, context = null) { + unreachable("An editor must be serializable"); + } + static async 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 { + action: "added" + }; + } + get telemetryFinalData() { + return null; + } + _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; + } + data.type ||= this.editorType; + this._uiManager._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data + } + }); + } + 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(); + } + } +} +class FakeEditor extends AnnotationEditor { + constructor(params) { + super(params); + this.annotationElementId = params.annotationElementId; + this.deleted = true; + } + serialize() { + return this.serializeDeleted(); + } +} + +;// ./src/shared/murmurhash3.js +const SEED = 0xc3d2e1f0; +const MASK_HIGH = 0xffff0000; +const MASK_LOW = 0xffff; +class MurmurHash3_64 { + constructor(seed) { + this.h1 = seed ? seed & 0xffffffff : SEED; + this.h2 = seed ? seed & 0xffffffff : SEED; + } + update(input) { + let data, length; + if (typeof input === "string") { + data = new Uint8Array(input.length * 2); + length = 0; + for (let i = 0, ii = input.length; i < ii; i++) { + const code = input.charCodeAt(i); + if (code <= 0xff) { + data[length++] = code; + } else { + data[length++] = code >>> 8; + data[length++] = code & 0xff; + } + } + } else if (ArrayBuffer.isView(input)) { + data = input.slice(); + length = data.byteLength; + } else { + throw new Error("Invalid data format, must be a string or TypedArray."); + } + const blockCounts = length >> 2; + const tailLength = length - blockCounts * 4; + const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts); + let k1 = 0, + k2 = 0; + let h1 = this.h1, + h2 = this.h2; + const C1 = 0xcc9e2d51, + C2 = 0x1b873593; + const C1_LOW = C1 & MASK_LOW, + C2_LOW = C2 & MASK_LOW; + for (let i = 0; i < blockCounts; i++) { + if (i & 1) { + k1 = dataUint32[i]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + h1 ^= k1; + h1 = h1 << 13 | h1 >>> 19; + h1 = h1 * 5 + 0xe6546b64; + } else { + k2 = dataUint32[i]; + k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW; + k2 = k2 << 15 | k2 >>> 17; + k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW; + h2 ^= k2; + h2 = h2 << 13 | h2 >>> 19; + h2 = h2 * 5 + 0xe6546b64; + } + } + k1 = 0; + switch (tailLength) { + case 3: + k1 ^= data[blockCounts * 4 + 2] << 16; + case 2: + k1 ^= data[blockCounts * 4 + 1] << 8; + case 1: + k1 ^= data[blockCounts * 4]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + if (blockCounts & 1) { + h1 ^= k1; + } else { + h2 ^= k1; + } + } + this.h1 = h1; + this.h2 = h2; + } + hexdigest() { + let h1 = this.h1, + h2 = this.h2; + h1 ^= h2 >>> 1; + h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW; + h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16; + h1 ^= h2 >>> 1; + h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW; + h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16; + h1 ^= h2 >>> 1; + return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"); + } +} + +;// ./src/display/annotation_storage.js + + + +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: "" + }); + } +} + +;// ./src/display/font_loader.js + +class FontLoader { + #systemFonts = new Set(); + constructor({ + ownerDocument = globalThis.document, + styleElement = null + }) { + this._document = ownerDocument; + this.nativeFontFaces = new Set(); + this.styleElement = null; + this.loadingRequests = []; + this.loadTestFontId = 0; + } + addNativeFontFace(nativeFontFace) { + this.nativeFontFaces.add(nativeFontFace); + this._document.fonts.add(nativeFontFace); + } + removeNativeFontFace(nativeFontFace) { + this.nativeFontFaces.delete(nativeFontFace); + this._document.fonts.delete(nativeFontFace); + } + insertRule(rule) { + if (!this.styleElement) { + this.styleElement = this._document.createElement("style"); + this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement); + } + const styleSheet = this.styleElement.sheet; + styleSheet.insertRule(rule, styleSheet.cssRules.length); + } + clear() { + for (const nativeFontFace of this.nativeFontFaces) { + this._document.fonts.delete(nativeFontFace); + } + this.nativeFontFaces.clear(); + this.#systemFonts.clear(); + if (this.styleElement) { + this.styleElement.remove(); + this.styleElement = null; + } + } + async loadSystemFont({ + systemFontInfo: info, + _inspectFont + }) { + if (!info || this.#systemFonts.has(info.loadedName)) { + return; + } + assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); + if (this.isFontLoadingAPISupported) { + const { + loadedName, + src, + style + } = info; + const fontFace = new FontFace(loadedName, src, style); + this.addNativeFontFace(fontFace); + try { + await fontFace.load(); + this.#systemFonts.add(loadedName); + _inspectFont?.(info); + } catch { + warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`); + this.removeNativeFontFace(fontFace); + } + return; + } + unreachable("Not implemented: loadSystemFont without the Font Loading API."); + } + async bind(font) { + if (font.attached || font.missingFile && !font.systemFontInfo) { + return; + } + font.attached = true; + if (font.systemFontInfo) { + await this.loadSystemFont(font); + return; + } + if (this.isFontLoadingAPISupported) { + const nativeFontFace = font.createNativeFontFace(); + if (nativeFontFace) { + this.addNativeFontFace(nativeFontFace); + try { + await nativeFontFace.loaded; + } catch (ex) { + warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); + font.disableFontFace = true; + throw ex; + } + } + return; + } + const rule = font.createFontFaceRule(); + if (rule) { + this.insertRule(rule); + if (this.isSyncFontLoadingSupported) { + return; + } + await new Promise(resolve => { + const request = this._queueLoadingCallback(resolve); + this._prepareFontLoadEvent(font, request); + }); + } + } + get isFontLoadingAPISupported() { + const hasFonts = !!this._document?.fonts; + return shadow(this, "isFontLoadingAPISupported", hasFonts); + } + get isSyncFontLoadingSupported() { + let supported = false; + if (isNodeJS) { + supported = true; + } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) { + supported = true; + } + return shadow(this, "isSyncFontLoadingSupported", supported); + } + _queueLoadingCallback(callback) { + function completeRequest() { + assert(!request.done, "completeRequest() cannot be called twice."); + request.done = true; + while (loadingRequests.length > 0 && loadingRequests[0].done) { + const otherRequest = loadingRequests.shift(); + setTimeout(otherRequest.callback, 0); + } + } + const { + loadingRequests + } = this; + const request = { + done: false, + complete: completeRequest, + callback + }; + loadingRequests.push(request); + return request; + } + 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 shadow(this, "_loadTestFont", testFont); + } + _prepareFontLoadEvent(font, request) { + function int32(data, offset) { + return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff; + } + function spliceString(s, offset, remove, insert) { + const chunk1 = s.substring(0, offset); + const chunk2 = s.substring(offset + remove); + return chunk1 + insert + chunk2; + } + let i, ii; + const canvas = this._document.createElement("canvas"); + canvas.width = 1; + canvas.height = 1; + const ctx = canvas.getContext("2d"); + let called = 0; + function isFontReady(name, callback) { + if (++called > 30) { + warn("Load test font never loaded."); + callback(); + return; + } + ctx.font = "30px " + name; + ctx.fillText(".", 0, 20); + const imageData = ctx.getImageData(0, 0, 1, 1); + if (imageData.data[3] > 0) { + callback(); + return; + } + setTimeout(isFontReady.bind(null, name, callback)); + } + const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`; + let data = this._loadTestFont; + const COMMENT_OFFSET = 976; + data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); + const CFF_CHECKSUM_OFFSET = 16; + const XXXX_VALUE = 0x58585858; + let checksum = int32(data, CFF_CHECKSUM_OFFSET); + for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0; + } + if (i < loadTestFontId.length) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0; + } + 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); + const div = this._document.createElement("div"); + div.style.visibility = "hidden"; + div.style.width = div.style.height = "10px"; + div.style.position = "absolute"; + div.style.top = div.style.left = "0px"; + for (const name of [font.loadedName, loadTestFontId]) { + const span = this._document.createElement("span"); + span.textContent = "Hi"; + span.style.fontFamily = name; + div.append(span); + } + this._document.body.append(div); + isFontReady(loadTestFontId, () => { + div.remove(); + request.complete(); + }); + } +} +class FontFaceObject { + constructor(translatedData, { + disableFontFace = false, + inspectFont = null + }) { + this.compiledGlyphs = Object.create(null); + for (const i in translatedData) { + this[i] = translatedData[i]; + } + this.disableFontFace = disableFontFace === true; + this._inspectFont = inspectFont; + } + createNativeFontFace() { + if (!this.data || this.disableFontFace) { + return null; + } + let nativeFontFace; + if (!this.cssFontInfo) { + nativeFontFace = new FontFace(this.loadedName, this.data, {}); + } else { + const css = { + weight: this.cssFontInfo.fontWeight + }; + if (this.cssFontInfo.italicAngle) { + css.style = `oblique ${this.cssFontInfo.italicAngle}deg`; + } + nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css); + } + this._inspectFont?.(this); + return nativeFontFace; + } + createFontFaceRule() { + if (!this.data || this.disableFontFace) { + return null; + } + const data = bytesToString(this.data); + const url = `url(data:${this.mimetype};base64,${btoa(data)});`; + let rule; + if (!this.cssFontInfo) { + rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`; + } else { + let css = `font-weight: ${this.cssFontInfo.fontWeight};`; + if (this.cssFontInfo.italicAngle) { + css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`; + } + rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`; + } + this._inspectFont?.(this, url); + return rule; + } + getPathGenerator(objs, character) { + if (this.compiledGlyphs[character] !== undefined) { + return this.compiledGlyphs[character]; + } + let cmds; + try { + cmds = objs.get(this.loadedName + "_path_" + character); + } catch (ex) { + warn(`getPathGenerator - ignoring character: "${ex}".`); + } + if (!Array.isArray(cmds) || cmds.length === 0) { + return this.compiledGlyphs[character] = function (c, size) {}; + } + 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] = 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); + } + }; + } +} + +;// ./src/display/node_utils.js + + +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 + })); + }; + 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); + } +} +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); + } +} +class NodeCMapReaderFactory extends BaseCMapReaderFactory { + _fetchData(url, compressionType) { + return node_utils_fetchData(url).then(data => ({ + cMapData: data, + compressionType + })); + } +} +class NodeStandardFontDataFactory extends BaseStandardFontDataFactory { + _fetchData(url) { + return node_utils_fetchData(url); + } +} + +;// ./src/display/pattern_helper.js + + +const PathType = { + FILL: "Fill", + STROKE: "Stroke", + SHADING: "Shading" +}; +function applyBoundingBox(ctx, bbox) { + if (!bbox) { + return; + } + const width = bbox[2] - bbox[0]; + const height = bbox[3] - bbox[1]; + const region = new Path2D(); + region.rect(bbox[0], bbox[1], width, height); + ctx.clip(region); +} +class BaseShadingPattern { + getPattern() { + unreachable("Abstract method `getPattern` called."); + } +} +class RadialAxialShadingPattern extends BaseShadingPattern { + constructor(IR) { + super(); + this._type = IR[1]; + this._bbox = IR[2]; + this._colorStops = IR[3]; + this._p0 = IR[4]; + this._p1 = IR[5]; + this._r0 = IR[6]; + this._r1 = IR[7]; + this.matrix = null; + } + _createGradient(ctx) { + let grad; + if (this._type === "axial") { + grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]); + } else if (this._type === "radial") { + grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1); + } + for (const colorStop of this._colorStops) { + grad.addColorStop(colorStop[0], colorStop[1]); + } + return grad; + } + getPattern(ctx, owner, inverse, pathType) { + let pattern; + if (pathType === PathType.STROKE || pathType === PathType.FILL) { + 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); + const tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.beginPath(); + tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.translate(-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); + } + applyBoundingBox(tmpCtx, this._bbox); + tmpCtx.fillStyle = this._createGradient(tmpCtx); + tmpCtx.fill(); + pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat"); + const domMatrix = new DOMMatrix(inverse); + pattern.setTransform(domMatrix); + } else { + applyBoundingBox(ctx, this._bbox); + pattern = this._createGradient(ctx); + } + return pattern; + } +} +function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { + const coords = context.coords, + colors = context.colors; + const bytes = data.data, + rowSize = data.width * 4; + let tmp; + if (coords[p1 + 1] > coords[p2 + 1]) { + tmp = p1; + p1 = p2; + p2 = tmp; + tmp = c1; + c1 = c2; + c2 = tmp; + } + if (coords[p2 + 1] > coords[p3 + 1]) { + tmp = p2; + p2 = p3; + p3 = tmp; + tmp = c2; + c2 = c3; + c3 = tmp; + } + if (coords[p1 + 1] > coords[p2 + 1]) { + tmp = p1; + p1 = p2; + p2 = tmp; + tmp = c1; + c1 = c2; + c2 = tmp; + } + const x1 = (coords[p1] + context.offsetX) * context.scaleX; + const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; + const x2 = (coords[p2] + context.offsetX) * context.scaleX; + const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; + const x3 = (coords[p3] + context.offsetX) * context.scaleX; + const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; + if (y1 >= y3) { + return; + } + const c1r = colors[c1], + c1g = colors[c1 + 1], + c1b = colors[c1 + 2]; + const c2r = colors[c2], + c2g = colors[c2 + 1], + c2b = colors[c2 + 2]; + const c3r = colors[c3], + c3g = colors[c3 + 1], + c3b = colors[c3 + 2]; + const minY = Math.round(y1), + maxY = Math.round(y3); + let xa, car, cag, cab; + let xb, cbr, cbg, cbb; + for (let y = minY; y <= maxY; y++) { + if (y < y2) { + const k = y < y1 ? 0 : (y1 - y) / (y1 - y2); + xa = x1 - (x1 - x2) * k; + car = c1r - (c1r - c2r) * k; + cag = c1g - (c1g - c2g) * k; + cab = c1b - (c1b - c2b) * k; + } else { + let k; + if (y > y3) { + k = 1; + } else if (y2 === y3) { + k = 0; + } else { + k = (y2 - y) / (y2 - y3); + } + xa = x2 - (x2 - x3) * k; + car = c2r - (c2r - c3r) * k; + cag = c2g - (c2g - c3g) * k; + cab = c2b - (c2b - c3b) * k; + } + let k; + if (y < y1) { + k = 0; + } else if (y > y3) { + k = 1; + } else { + k = (y1 - y) / (y1 - y3); + } + xb = x1 - (x1 - x3) * k; + cbr = c1r - (c1r - c3r) * k; + cbg = c1g - (c1g - c3g) * k; + cbb = c1b - (c1b - c3b) * k; + const x1_ = Math.round(Math.min(xa, xb)); + const x2_ = Math.round(Math.max(xa, xb)); + let j = rowSize * y + x1_ * 4; + for (let x = x1_; x <= x2_; x++) { + k = (xa - x) / (xa - xb); + if (k < 0) { + k = 0; + } else if (k > 1) { + k = 1; + } + bytes[j++] = car - (car - cbr) * k | 0; + bytes[j++] = cag - (cag - cbg) * k | 0; + bytes[j++] = cab - (cab - cbb) * k | 0; + bytes[j++] = 255; + } + } +} +function drawFigure(data, figure, context) { + const ps = figure.coords; + const cs = figure.colors; + let i, ii; + switch (figure.type) { + case "lattice": + const verticesPerRow = figure.verticesPerRow; + const rows = Math.floor(ps.length / verticesPerRow) - 1; + const cols = verticesPerRow - 1; + for (i = 0; i < rows; i++) { + let q = i * verticesPerRow; + for (let j = 0; j < cols; j++, q++) { + drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); + drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); + } + } + break; + case "triangles": + for (i = 0, ii = ps.length; i < ii; i += 3) { + drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); + } + break; + default: + throw new Error("illegal figure"); + } +} +class MeshShadingPattern extends BaseShadingPattern { + constructor(IR) { + super(); + this._coords = IR[2]; + this._colors = IR[3]; + this._figures = IR[4]; + this._bounds = IR[5]; + this._bbox = IR[7]; + this._background = IR[8]; + this.matrix = null; + } + _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) { + const EXPECTED_SCALE = 1.1; + const MAX_PATTERN_SIZE = 3000; + const BORDER_SIZE = 2; + const offsetX = Math.floor(this._bounds[0]); + const offsetY = Math.floor(this._bounds[1]); + const boundsWidth = Math.ceil(this._bounds[2]) - offsetX; + const boundsHeight = Math.ceil(this._bounds[3]) - offsetY; + const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const scaleX = boundsWidth / width; + const scaleY = boundsHeight / height; + const context = { + coords: this._coords, + colors: this._colors, + offsetX: -offsetX, + offsetY: -offsetY, + scaleX: 1 / scaleX, + scaleY: 1 / scaleY + }; + const paddedWidth = width + BORDER_SIZE * 2; + const paddedHeight = height + BORDER_SIZE * 2; + const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight); + const tmpCtx = tmpCanvas.context; + const data = tmpCtx.createImageData(width, height); + if (backgroundColor) { + const bytes = data.data; + for (let i = 0, ii = bytes.length; i < ii; i += 4) { + bytes[i] = backgroundColor[0]; + bytes[i + 1] = backgroundColor[1]; + bytes[i + 2] = backgroundColor[2]; + bytes[i + 3] = 255; + } + } + for (const figure of this._figures) { + drawFigure(data, figure, context); + } + tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); + const canvas = tmpCanvas.canvas; + return { + canvas, + offsetX: offsetX - BORDER_SIZE * scaleX, + offsetY: offsetY - BORDER_SIZE * scaleY, + scaleX, + scaleY + }; + } + getPattern(ctx, owner, inverse, pathType) { + applyBoundingBox(ctx, this._bbox); + let scale; + if (pathType === PathType.SHADING) { + scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx)); + } else { + scale = Util.singularValueDecompose2dScale(owner.baseTransform); + if (this.matrix) { + const matrixScale = Util.singularValueDecompose2dScale(this.matrix); + scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; + } + } + const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases); + if (pathType !== PathType.SHADING) { + ctx.setTransform(...owner.baseTransform); + if (this.matrix) { + ctx.transform(...this.matrix); + } + } + ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); + return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat"); + } +} +class DummyShadingPattern extends BaseShadingPattern { + getPattern() { + return "hotpink"; + } +} +function getShadingPattern(IR) { + switch (IR[0]) { + case "RadialAxial": + return new RadialAxialShadingPattern(IR); + case "Mesh": + return new MeshShadingPattern(IR); + case "Dummy": + return new DummyShadingPattern(); + } + throw new Error(`Unknown IR type: ${IR[0]}`); +} +const PaintType = { + COLORED: 1, + UNCOLORED: 2 +}; +class TilingPattern { + static MAX_PATTERN_SIZE = 3000; + constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) { + this.operatorList = IR[2]; + this.matrix = IR[3]; + this.bbox = IR[4]; + this.xstep = IR[5]; + this.ystep = IR[6]; + this.paintType = IR[7]; + this.tilingType = IR[8]; + this.color = color; + this.ctx = ctx; + this.canvasGraphicsFactory = canvasGraphicsFactory; + this.baseTransform = baseTransform; + } + createPatternCanvas(owner) { + const { + bbox, + operatorList, + paintType, + tilingType, + color, + canvasGraphicsFactory + } = this; + let { + xstep, + ystep + } = this; + xstep = Math.abs(xstep); + ystep = Math.abs(ystep); + info("TilingType: " + tilingType); + const x0 = bbox[0], + y0 = bbox[1], + x1 = bbox[2], + y1 = bbox[3]; + const width = x1 - x0; + const height = y1 - y0; + const matrixScale = Util.singularValueDecompose2dScale(this.matrix); + const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform); + const combinedScaleX = matrixScale[0] * curMatrixScale[0]; + const combinedScaleY = matrixScale[1] * curMatrixScale[1]; + let canvasWidth = width, + canvasHeight = height, + redrawHorizontally = false, + redrawVertically = false; + const xScaledStep = Math.ceil(xstep * combinedScaleX); + const yScaledStep = Math.ceil(ystep * combinedScaleY); + const xScaledWidth = Math.ceil(width * combinedScaleX); + const yScaledHeight = Math.ceil(height * combinedScaleY); + if (xScaledStep >= xScaledWidth) { + canvasWidth = xstep; + } else { + redrawHorizontally = true; + } + if (yScaledStep >= yScaledHeight) { + canvasHeight = ystep; + } else { + redrawVertically = true; + } + const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size); + const tmpCtx = tmpCanvas.context; + const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); + graphics.groupLevel = owner.groupLevel; + this.setFillAndStrokeStyleToContext(graphics, paintType, color); + tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0); + graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0); + tmpCtx.save(); + this.clipBbox(graphics, x0, y0, x1, y1); + graphics.baseTransform = getCurrentTransform(graphics.ctx); + graphics.executeOperatorList(operatorList); + graphics.endDrawing(); + tmpCtx.restore(); + if (redrawHorizontally || redrawVertically) { + const image = tmpCanvas.canvas; + if (redrawHorizontally) { + canvasWidth = xstep; + } + if (redrawVertically) { + canvasHeight = ystep; + } + const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const xSize = dimx2.size; + const ySize = dimy2.size; + const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize); + const tmpCtx2 = tmpCanvas2.context; + const ii = redrawHorizontally ? Math.floor(width / xstep) : 0; + const jj = redrawVertically ? Math.floor(height / ystep) : 0; + for (let i = 0; i <= ii; i++) { + for (let j = 0; j <= jj; j++) { + tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize); + } + } + return { + canvas: tmpCanvas2.canvas, + scaleX: dimx2.scale, + scaleY: dimy2.scale, + offsetX: x0, + offsetY: y0 + }; + } + return { + canvas: tmpCanvas.canvas, + scaleX: dimx.scale, + scaleY: dimy.scale, + offsetX: x0, + offsetY: y0 + }; + } + getSizeAndScale(step, realOutputSize, scale) { + const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize); + let size = Math.ceil(step * scale); + if (size >= maxSize) { + size = maxSize; + } else { + scale = size / step; + } + return { + scale, + size + }; + } + clipBbox(graphics, x0, y0, x1, y1) { + const bboxWidth = x1 - x0; + const bboxHeight = y1 - y0; + graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); + graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]); + graphics.clip(); + graphics.endPath(); + } + setFillAndStrokeStyleToContext(graphics, paintType, color) { + const context = graphics.ctx, + current = graphics.current; + switch (paintType) { + case PaintType.COLORED: + const ctx = this.ctx; + context.fillStyle = ctx.fillStyle; + context.strokeStyle = ctx.strokeStyle; + current.fillColor = ctx.fillStyle; + current.strokeColor = ctx.strokeStyle; + break; + case PaintType.UNCOLORED: + 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 FormatError(`Unsupported paint type: ${paintType}`); + } + } + getPattern(ctx, owner, inverse, pathType) { + let matrix = inverse; + if (pathType !== PathType.SHADING) { + matrix = Util.transform(matrix, owner.baseTransform); + if (this.matrix) { + matrix = Util.transform(matrix, this.matrix); + } + } + const temporaryPatternCanvas = this.createPatternCanvas(owner); + let domMatrix = new DOMMatrix(matrix); + domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY); + const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat"); + pattern.setTransform(domMatrix); + return pattern; + } +} + +;// ./src/shared/image_utils.js + +function convertToRGBA(params) { + switch (params.kind) { + case ImageKind.GRAYSCALE_1BPP: + return convertBlackAndWhiteToRGBA(params); + case ImageKind.RGB_24BPP: + return convertRGBToRGBA(params); + } + return null; +} +function convertBlackAndWhiteToRGBA({ + src, + srcPos = 0, + dest, + width, + height, + nonBlackColor = 0xffffffff, + inverseDecode = false +}) { + const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor]; + const widthInSource = width >> 3; + const widthRemainder = width & 7; + const srcLength = src.length; + dest = new Uint32Array(dest.buffer); + let destPos = 0; + for (let i = 0; i < height; i++) { + for (const max = srcPos + widthInSource; srcPos < max; srcPos++) { + const elem = srcPos < srcLength ? src[srcPos] : 255; + dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping; + } + if (widthRemainder === 0) { + continue; + } + const elem = srcPos < srcLength ? src[srcPos++] : 255; + for (let j = 0; j < widthRemainder; j++) { + dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping; + } + } + return { + srcPos, + destPos + }; +} +function convertRGBToRGBA({ + src, + srcPos = 0, + dest, + destPos = 0, + width, + height +}) { + let i = 0; + const len32 = src.length >> 2; + const src32 = new Uint32Array(src.buffer, srcPos, len32); + if (FeatureTest.isLittleEndian) { + for (; i < len32 - 2; i += 3, destPos += 4) { + const s1 = src32[i]; + const s2 = src32[i + 1]; + const s3 = src32[i + 2]; + dest[destPos] = s1 | 0xff000000; + dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000; + dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000; + dest[destPos + 3] = s3 >>> 8 | 0xff000000; + } + for (let j = i * 4, jj = src.length; j < jj; j += 3) { + dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000; + } + } else { + for (; i < len32 - 2; i += 3, destPos += 4) { + const s1 = src32[i]; + const s2 = src32[i + 1]; + const s3 = src32[i + 2]; + dest[destPos] = s1 | 0xff; + dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff; + dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff; + dest[destPos + 3] = s3 << 8 | 0xff; + } + for (let j = i * 4, jj = src.length; j < jj; j += 3) { + dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff; + } + } + return { + srcPos, + destPos + }; +} +function grayToRGBA(src, dest) { + if (FeatureTest.isLittleEndian) { + for (let i = 0, ii = src.length; i < ii; i++) { + dest[i] = src[i] * 0x10101 | 0xff000000; + } + } else { + for (let i = 0, ii = src.length; i < ii; i++) { + dest[i] = src[i] * 0x1010100 | 0x000000ff; + } + } +} + +;// ./src/display/canvas.js + + + + +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.endPath(); + this.ctx.rect(rect[0], rect[1], width, height); + this.ctx.clip(); + this.ctx.beginPath(); + } + } + 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]; + } +} + +;// ./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; + } +} + +;// ./src/shared/message_handler.js + +const CallbackKind = { + UNKNOWN: 0, + DATA: 1, + ERROR: 2 +}; +const StreamKind = { + UNKNOWN: 0, + CANCEL: 1, + CANCEL_COMPLETE: 2, + CLOSE: 3, + ENQUEUE: 4, + ERROR: 5, + PULL: 6, + PULL_COMPLETE: 7, + START_COMPLETE: 8 +}; +function wrapReason(reason) { + if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) { + unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); + } + switch (reason.name) { + case "AbortException": + return new AbortException(reason.message); + case "MissingPDFException": + return new MissingPDFException(reason.message); + case "PasswordException": + return new PasswordException(reason.message, reason.code); + case "UnexpectedResponseException": + return new UnexpectedResponseException(reason.message, reason.status); + case "UnknownErrorException": + return new UnknownErrorException(reason.message, reason.details); + default: + return new UnknownErrorException(reason.message, reason.toString()); + } +} +class MessageHandler { + constructor(sourceName, targetName, comObj) { + this.sourceName = sourceName; + this.targetName = targetName; + this.comObj = comObj; + this.callbackId = 1; + this.streamId = 1; + this.streamSinks = Object.create(null); + this.streamControllers = Object.create(null); + this.callbackCapabilities = Object.create(null); + this.actionHandler = Object.create(null); + this._onComObjOnMessage = event => { + const data = event.data; + if (data.targetName !== this.sourceName) { + return; + } + if (data.stream) { + this.#processStreamMessage(data); + return; + } + if (data.callback) { + const callbackId = data.callbackId; + const capability = this.callbackCapabilities[callbackId]; + if (!capability) { + throw new Error(`Cannot resolve callback ${callbackId}`); + } + delete this.callbackCapabilities[callbackId]; + if (data.callback === CallbackKind.DATA) { + capability.resolve(data.data); + } else if (data.callback === CallbackKind.ERROR) { + capability.reject(wrapReason(data.reason)); + } else { + throw new Error("Unexpected callback case"); + } + return; + } + const action = this.actionHandler[data.action]; + if (!action) { + throw new Error(`Unknown action from worker: ${data.action}`); + } + if (data.callbackId) { + const cbSourceName = this.sourceName; + const cbTargetName = data.sourceName; + new Promise(function (resolve) { + resolve(action(data.data)); + }).then(function (result) { + comObj.postMessage({ + sourceName: cbSourceName, + targetName: cbTargetName, + callback: CallbackKind.DATA, + callbackId: data.callbackId, + data: result + }); + }, function (reason) { + comObj.postMessage({ + sourceName: cbSourceName, + targetName: cbTargetName, + callback: CallbackKind.ERROR, + callbackId: data.callbackId, + reason: wrapReason(reason) + }); + }); + return; + } + if (data.streamId) { + this.#createStreamSink(data); + return; + } + action(data.data); + }; + comObj.addEventListener("message", this._onComObjOnMessage); + } + on(actionName, handler) { + const ah = this.actionHandler; + if (ah[actionName]) { + throw new Error(`There is already an actionName called "${actionName}"`); + } + ah[actionName] = handler; + } + send(actionName, data, transfers) { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + data + }, transfers); + } + sendWithPromise(actionName, data, transfers) { + const callbackId = this.callbackId++; + const capability = Promise.withResolvers(); + this.callbackCapabilities[callbackId] = capability; + try { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + callbackId, + data + }, transfers); + } catch (ex) { + capability.reject(ex); + } + return capability.promise; + } + sendWithStream(actionName, data, queueingStrategy, transfers) { + const streamId = this.streamId++, + sourceName = this.sourceName, + targetName = this.targetName, + comObj = this.comObj; + return new ReadableStream({ + start: controller => { + const startCapability = Promise.withResolvers(); + this.streamControllers[streamId] = { + controller, + startCall: startCapability, + pullCall: null, + cancelCall: null, + isClosed: false + }; + comObj.postMessage({ + sourceName, + targetName, + action: actionName, + streamId, + data, + desiredSize: controller.desiredSize + }, transfers); + return startCapability.promise; + }, + pull: controller => { + const pullCapability = Promise.withResolvers(); + this.streamControllers[streamId].pullCall = pullCapability; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL, + streamId, + desiredSize: controller.desiredSize + }); + return pullCapability.promise; + }, + cancel: reason => { + 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({ + sourceName, + targetName, + stream: StreamKind.CANCEL, + streamId, + reason: wrapReason(reason) + }); + return cancelCapability.promise; + } + }, queueingStrategy); + } + #createStreamSink(data) { + const streamId = data.streamId, + sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + const self = this, + action = this.actionHandler[data.action]; + const streamSink = { + enqueue(chunk, size = 1, transfers) { + if (this.isCancelled) { + return; + } + const lastDesiredSize = this.desiredSize; + this.desiredSize -= size; + if (lastDesiredSize > 0 && this.desiredSize <= 0) { + this.sinkCapability = Promise.withResolvers(); + this.ready = this.sinkCapability.promise; + } + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ENQUEUE, + streamId, + chunk + }, transfers); + }, + close() { + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CLOSE, + streamId + }); + delete self.streamSinks[streamId]; + }, + error(reason) { + assert(reason instanceof Error, "error must have a valid reason"); + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ERROR, + streamId, + reason: wrapReason(reason) + }); + }, + sinkCapability: Promise.withResolvers(), + onPull: null, + onCancel: null, + isCancelled: false, + desiredSize: data.desiredSize, + ready: null + }; + streamSink.sinkCapability.resolve(); + streamSink.ready = streamSink.sinkCapability.promise; + this.streamSinks[streamId] = streamSink; + new Promise(function (resolve) { + resolve(action(data.data, streamSink)); + }).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + } + #processStreamMessage(data) { + const streamId = data.streamId, + sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + const streamController = this.streamControllers[streamId], + streamSink = this.streamSinks[streamId]; + switch (data.stream) { + case StreamKind.START_COMPLETE: + if (data.success) { + streamController.startCall.resolve(); + } else { + streamController.startCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL_COMPLETE: + if (data.success) { + streamController.pullCall.resolve(); + } else { + streamController.pullCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL: + if (!streamSink) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + break; + } + if (streamSink.desiredSize <= 0 && data.desiredSize > 0) { + streamSink.sinkCapability.resolve(); + } + streamSink.desiredSize = data.desiredSize; + new Promise(function (resolve) { + resolve(streamSink.onPull?.()); + }).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + break; + case StreamKind.ENQUEUE: + assert(streamController, "enqueue should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.controller.enqueue(data.chunk); + break; + case StreamKind.CLOSE: + assert(streamController, "close should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.isClosed = true; + streamController.controller.close(); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.ERROR: + assert(streamController, "error should have stream controller"); + streamController.controller.error(wrapReason(data.reason)); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL_COMPLETE: + if (data.success) { + streamController.cancelCall.resolve(); + } else { + streamController.cancelCall.reject(wrapReason(data.reason)); + } + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL: + if (!streamSink) { + break; + } + new Promise(function (resolve) { + resolve(streamSink.onCancel?.(wrapReason(data.reason))); + }).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + streamSink.sinkCapability.reject(wrapReason(data.reason)); + streamSink.isCancelled = true; + delete this.streamSinks[streamId]; + break; + default: + throw new Error("Unexpected stream case"); + } + } + async #deleteStreamController(streamController, streamId) { + await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]); + delete this.streamControllers[streamId]; + } + destroy() { + this.comObj.removeEventListener("message", this._onComObjOnMessage); + } +} + +;// ./src/display/metadata.js + +class Metadata { + #metadataMap; + #data; + constructor({ + parsedData, + rawData + }) { + this.#metadataMap = parsedData; + this.#data = rawData; + } + getRaw() { + return this.#data; + } + get(name) { + return this.#metadataMap.get(name) ?? null; + } + getAll() { + return objectFromMap(this.#metadataMap); + } + has(name) { + return this.#metadataMap.has(name); + } +} + +;// ./src/display/optional_content_config.js + + +const INTERNAL = Symbol("INTERNAL"); +class OptionalContentGroup { + #isDisplay = false; + #isPrint = false; + #userSet = false; + #visible = true; + 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() { + 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; + } +} +class OptionalContentConfig { + #cachedGetHash = null; + #groups = new Map(); + #initialHash = null; + #order = null; + constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) { + this.renderingIntent = renderingIntent; + this.name = null; + this.creator = null; + if (data === null) { + return; + } + this.name = data.name; + this.creator = data.creator; + this.#order = data.order; + for (const group of data.groups) { + this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group)); + } + if (data.baseState === "OFF") { + for (const group of this.#groups.values()) { + group._setVisible(INTERNAL, false); + } + } + for (const on of data.on) { + this.#groups.get(on)._setVisible(INTERNAL, true); + } + for (const off of data.off) { + this.#groups.get(off)._setVisible(INTERNAL, false); + } + this.#initialHash = this.getHash(); + } + #evaluateVisibilityExpression(array) { + const length = array.length; + if (length < 2) { + return true; + } + const operator = array[0]; + for (let i = 1; i < length; i++) { + const element = array[i]; + let state; + if (Array.isArray(element)) { + state = this.#evaluateVisibilityExpression(element); + } else if (this.#groups.has(element)) { + state = this.#groups.get(element).visible; + } else { + warn(`Optional content group not found: ${element}`); + return true; + } + switch (operator) { + case "And": + if (!state) { + return false; + } + break; + case "Or": + if (state) { + return true; + } + break; + case "Not": + return !state; + default: + return true; + } + } + return operator === "And"; + } + isVisible(group) { + if (this.#groups.size === 0) { + return true; + } + if (!group) { + info("Optional content group not defined."); + return true; + } + if (group.type === "OCG") { + if (!this.#groups.has(group.id)) { + warn(`Optional content group not found: ${group.id}`); + return true; + } + return this.#groups.get(group.id).visible; + } else if (group.type === "OCMD") { + if (group.expression) { + return this.#evaluateVisibilityExpression(group.expression); + } + if (!group.policy || group.policy === "AnyOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return false; + } + } + return true; + } else if (group.policy === "AnyOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return false; + } + } + return true; + } + warn(`Unknown optional content policy ${group.policy}.`); + return true; + } + warn(`Unknown group type ${group.type}.`); + return true; + } + setVisibility(id, visible = true) { + const group = this.#groups.get(id); + if (!group) { + warn(`Optional content group not found: ${id}`); + return; + } + 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() { + return this.#initialHash === null || this.getHash() === this.#initialHash; + } + getOrder() { + if (!this.#groups.size) { + return null; + } + if (this.#order) { + return this.#order.slice(); + } + return [...this.#groups.keys()]; + } + getGroups() { + return this.#groups.size > 0 ? objectFromMap(this.#groups) : null; + } + getGroup(id) { + return this.#groups.get(id) || null; + } + getHash() { + if (this.#cachedGetHash !== null) { + return this.#cachedGetHash; + } + const hash = new MurmurHash3_64(); + for (const [id, group] of this.#groups) { + hash.update(`${id}:${group.visible}`); + } + return this.#cachedGetHash = hash.hexdigest(); + } +} + +;// ./src/display/transport_stream.js + + +class PDFDataTransportStream { + constructor(pdfDataRangeTransport, { + disableRange = false, + disableStream = false + }) { + assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'); + const { + length, + initialData, + progressiveDone, + contentDispositionFilename + } = pdfDataRangeTransport; + this._queuedChunks = []; + this._progressiveDone = progressiveDone; + this._contentDispositionFilename = contentDispositionFilename; + if (initialData?.length > 0) { + const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer; + this._queuedChunks.push(buffer); + } + this._pdfDataRangeTransport = pdfDataRangeTransport; + this._isStreamingSupported = !disableStream; + this._isRangeSupported = !disableRange; + this._contentLength = length; + this._fullRequestReader = null; + this._rangeReaders = []; + pdfDataRangeTransport.addRangeListener((begin, chunk) => { + this._onReceiveData({ + begin, + chunk + }); + }); + pdfDataRangeTransport.addProgressListener((loaded, total) => { + this._onProgress({ + loaded, + total + }); + }); + pdfDataRangeTransport.addProgressiveReadListener(chunk => { + this._onReceiveData({ + chunk + }); + }); + pdfDataRangeTransport.addProgressiveDoneListener(() => { + this._onProgressiveDone(); + }); + pdfDataRangeTransport.transportReady(); + } + _onReceiveData({ + begin, + chunk + }) { + const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer; + if (begin === undefined) { + if (this._fullRequestReader) { + this._fullRequestReader._enqueue(buffer); + } else { + this._queuedChunks.push(buffer); + } + } else { + const found = this._rangeReaders.some(function (rangeReader) { + if (rangeReader._begin !== begin) { + return false; + } + rangeReader._enqueue(buffer); + return true; + }); + assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); + } + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + _onProgress(evt) { + if (evt.total === undefined) { + this._rangeReaders[0]?.onProgress?.({ + loaded: evt.loaded + }); + } else { + this._fullRequestReader?.onProgress?.({ + loaded: evt.loaded, + total: evt.total + }); + } + } + _onProgressiveDone() { + this._fullRequestReader?.progressiveDone(); + this._progressiveDone = true; + } + _removeRangeReader(reader) { + const i = this._rangeReaders.indexOf(reader); + if (i >= 0) { + this._rangeReaders.splice(i, 1); + } + } + getFullReader() { + 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); + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new PDFDataTransportStreamRangeReader(this, begin, end); + this._pdfDataRangeTransport.requestDataRange(begin, end); + this._rangeReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeReaders.slice(0)) { + reader.cancel(reason); + } + this._pdfDataRangeTransport.abort(); + } +} +class PDFDataTransportStreamReader { + constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) { + this._stream = stream; + this._done = progressiveDone || false; + this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null; + this._queuedChunks = queuedChunks || []; + this._loaded = 0; + for (const chunk of this._queuedChunks) { + this._loaded += chunk.byteLength; + } + this._requests = []; + this._headersReady = Promise.resolve(); + stream._fullRequestReader = this; + this.onProgress = null; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunks.push(chunk); + } + this._loaded += chunk.byteLength; + } + get headersReady() { + return this._headersReady; + } + get filename() { + return this._filename; + } + get isRangeSupported() { + return this._stream._isRangeSupported; + } + get isStreamingSupported() { + return this._stream._isStreamingSupported; + } + get contentLength() { + return this._stream._contentLength; + } + async read() { + if (this._queuedChunks.length > 0) { + const chunk = this._queuedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + } + progressiveDone() { + if (this._done) { + return; + } + this._done = true; + } +} +class PDFDataTransportStreamRangeReader { + constructor(stream, begin, end) { + this._stream = stream; + this._begin = begin; + this._end = end; + this._queuedChunk = null; + this._requests = []; + this._done = false; + this.onProgress = null; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length === 0) { + this._queuedChunk = chunk; + } else { + const requestsCapability = this._requests.shift(); + requestsCapability.resolve({ + value: chunk, + done: false + }); + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + } + this._done = true; + this._stream._removeRangeReader(this); + } + get isStreamingSupported() { + return false; + } + async read() { + if (this._queuedChunk) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + this._stream._removeRangeReader(this); + } +} + +;// ./src/display/content_disposition.js + +function getFilenameFromContentDispositionHeader(contentDisposition) { + let needsEncodingFixup = true; + let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = unescape(filename); + filename = rfc5987decode(filename); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + tmp = rfc2231getparam(contentDisposition); + if (tmp) { + const filename = rfc2047decode(tmp); + return fixupEncoding(filename); + } + tmp = toParamRegExp("filename", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + function toParamRegExp(attributePattern, flags) { + return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags); + } + function textdecode(encoding, value) { + if (encoding) { + if (!/^[\x00-\xFF]+$/.test(value)) { + return value; + } + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(value); + value = decoder.decode(buffer); + needsEncodingFixup = false; + } catch {} + } + return value; + } + function fixupEncoding(value) { + if (needsEncodingFixup && /[\x80-\xff]/.test(value)) { + value = textdecode("utf-8", value); + if (needsEncodingFixup) { + value = textdecode("iso-8859-1", value); + } + } + return value; + } + function rfc2231getparam(contentDispositionStr) { + const matches = []; + let match; + const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig"); + while ((match = iter.exec(contentDispositionStr)) !== null) { + let [, n, quot, part] = match; + n = parseInt(n, 10); + if (n in matches) { + if (n === 0) { + break; + } + continue; + } + matches[n] = [quot, part]; + } + const parts = []; + for (let n = 0; n < matches.length; ++n) { + if (!(n in matches)) { + break; + } + let [quot, part] = matches[n]; + part = rfc2616unquote(part); + if (quot) { + part = unescape(part); + if (n === 0) { + part = rfc5987decode(part); + } + } + parts.push(part); + } + return parts.join(""); + } + function rfc2616unquote(value) { + if (value.startsWith('"')) { + const parts = value.slice(1).split('\\"'); + for (let i = 0; i < parts.length; ++i) { + const quotindex = parts[i].indexOf('"'); + if (quotindex !== -1) { + parts[i] = parts[i].slice(0, quotindex); + parts.length = i + 1; + } + parts[i] = parts[i].replaceAll(/\\(.)/g, "$1"); + } + value = parts.join('"'); + } + return value; + } + function rfc5987decode(extvalue) { + const encodingend = extvalue.indexOf("'"); + if (encodingend === -1) { + return extvalue; + } + const encoding = extvalue.slice(0, encodingend); + const langvalue = extvalue.slice(encodingend + 1); + const value = langvalue.replace(/^[^']*'/, ""); + return textdecode(encoding, value); + } + function rfc2047decode(value) { + if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) { + return value; + } + return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) { + if (encoding === "q" || encoding === "Q") { + text = text.replaceAll("_", " "); + text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) { + return String.fromCharCode(parseInt(hex, 16)); + }); + return textdecode(charset, text); + } + try { + text = atob(text); + } catch {} + return textdecode(charset, text); + }); + } + return ""; +} + +;// ./src/display/network_utils.js + + + +function createHeaders(isHttp, httpHeaders) { + const headers = new Headers(); + if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") { + return headers; + } + for (const key in httpHeaders) { + const val = httpHeaders[key]; + if (val !== undefined) { + headers.append(key, val); + } + } + return headers; +} +function validateRangeRequestCapabilities({ + responseHeaders, + isHttp, + rangeChunkSize, + disableRange +}) { + const returnValues = { + allowRangeRequests: false, + suggestedLength: undefined + }; + const length = parseInt(responseHeaders.get("Content-Length"), 10); + if (!Number.isInteger(length)) { + return returnValues; + } + returnValues.suggestedLength = length; + if (length <= 2 * rangeChunkSize) { + return returnValues; + } + if (disableRange || !isHttp) { + return returnValues; + } + if (responseHeaders.get("Accept-Ranges") !== "bytes") { + return returnValues; + } + const contentEncoding = responseHeaders.get("Content-Encoding") || "identity"; + if (contentEncoding !== "identity") { + return returnValues; + } + returnValues.allowRangeRequests = true; + return returnValues; +} +function extractFilenameFromHeader(responseHeaders) { + const contentDisposition = responseHeaders.get("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; +} + +;// ./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 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.headers = createHeaders(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; + const headers = new Headers(stream.headers); + const url = source.url; + fetch(url, createFetchOptions(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 responseHeaders = response.headers; + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: stream.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + this._isRangeSupported = allowRangeRequests; + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + 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(); + const headers = new Headers(stream.headers); + headers.append("Range", `bytes=${begin}-${end - 1}`); + const url = source.url; + fetch(url, createFetchOptions(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(); + } +} + +;// ./src/display/network.js + + +const OK_RESPONSE = 200; +const PARTIAL_CONTENT_RESPONSE = 206; +function network_getArrayBuffer(xhr) { + const data = xhr.response; + if (typeof data !== "string") { + return data; + } + return stringToBytes(data).buffer; +} +class NetworkManager { + constructor({ + url, + httpHeaders, + withCredentials + }) { + this.url = url; + this.isHttp = /^https?:/i.test(url); + this.headers = createHeaders(this.isHttp, httpHeaders); + this.withCredentials = withCredentials || false; + this.currXhrId = 0; + this.pendingRequests = Object.create(null); + } + requestRange(begin, end, listeners) { + const args = { + begin, + end + }; + for (const prop in listeners) { + args[prop] = listeners[prop]; + } + return this.request(args); + } + requestFull(listeners) { + return this.request(listeners); + } + request(args) { + const xhr = new XMLHttpRequest(); + const xhrId = this.currXhrId++; + const pendingRequest = this.pendingRequests[xhrId] = { + xhr + }; + xhr.open("GET", this.url); + xhr.withCredentials = this.withCredentials; + for (const [key, val] of this.headers) { + xhr.setRequestHeader(key, val); + } + if (this.isHttp && "begin" in args && "end" in args) { + xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`); + pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE; + } else { + pendingRequest.expectedStatus = OK_RESPONSE; + } + xhr.responseType = "arraybuffer"; + if (args.onError) { + xhr.onerror = function (evt) { + args.onError(xhr.status); + }; + } + xhr.onreadystatechange = this.onStateChange.bind(this, xhrId); + xhr.onprogress = this.onProgress.bind(this, xhrId); + pendingRequest.onHeadersReceived = args.onHeadersReceived; + pendingRequest.onDone = args.onDone; + pendingRequest.onError = args.onError; + pendingRequest.onProgress = args.onProgress; + xhr.send(null); + return xhrId; + } + onProgress(xhrId, evt) { + const pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + return; + } + pendingRequest.onProgress?.(evt); + } + onStateChange(xhrId, evt) { + const pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + return; + } + const xhr = pendingRequest.xhr; + if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { + pendingRequest.onHeadersReceived(); + delete pendingRequest.onHeadersReceived; + } + if (xhr.readyState !== 4) { + return; + } + if (!(xhrId in this.pendingRequests)) { + return; + } + delete this.pendingRequests[xhrId]; + if (xhr.status === 0 && this.isHttp) { + pendingRequest.onError?.(xhr.status); + return; + } + const xhrStatus = xhr.status || OK_RESPONSE; + const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE; + if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) { + pendingRequest.onError?.(xhr.status); + return; + } + const chunk = network_getArrayBuffer(xhr); + if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { + const rangeHeader = xhr.getResponseHeader("Content-Range"); + const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader); + pendingRequest.onDone({ + begin: parseInt(matches[1], 10), + chunk + }); + } else if (chunk) { + pendingRequest.onDone({ + begin: 0, + chunk + }); + } else { + pendingRequest.onError?.(xhr.status); + } + } + getRequestXhr(xhrId) { + return this.pendingRequests[xhrId].xhr; + } + isPendingRequest(xhrId) { + return xhrId in this.pendingRequests; + } + abortRequest(xhrId) { + const xhr = this.pendingRequests[xhrId].xhr; + delete this.pendingRequests[xhrId]; + xhr.abort(); + } +} +class PDFNetworkStream { + constructor(source) { + this._source = source; + this._manager = new NetworkManager(source); + this._rangeChunkSize = source.rangeChunkSize; + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + _onRangeRequestReaderClosed(reader) { + const i = this._rangeRequestReaders.indexOf(reader); + if (i >= 0) { + this._rangeRequestReaders.splice(i, 1); + } + } + getFullReader() { + assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source); + return this._fullRequestReader; + } + getRangeReader(begin, end) { + const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end); + reader.onClosed = this._onRangeRequestReaderClosed.bind(this); + this._rangeRequestReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } +} +class PDFNetworkStreamFullRequestReader { + constructor(manager, source) { + this._manager = manager; + const args = { + onHeadersReceived: this._onHeadersReceived.bind(this), + onDone: this._onDone.bind(this), + onError: this._onError.bind(this), + onProgress: this._onProgress.bind(this) + }; + this._url = source.url; + this._fullRequestId = manager.requestFull(args); + this._headersCapability = Promise.withResolvers(); + this._disableRange = source.disableRange || false; + this._contentLength = source.length; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._isStreamingSupported = false; + this._isRangeSupported = false; + this._cachedChunks = []; + this._requests = []; + this._done = false; + this._storedError = undefined; + this._filename = null; + this.onProgress = null; + } + _onHeadersReceived() { + const fullRequestXhrId = this._fullRequestId; + const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); + const responseHeaders = new Headers(fullRequestXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).map(x => { + const [key, ...val] = x.split(": "); + return [key, val.join(": ")]; + })); + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: this._manager.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + if (allowRangeRequests) { + this._isRangeSupported = true; + } + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (this._isRangeSupported) { + this._manager.abortRequest(fullRequestXhrId); + } + this._headersCapability.resolve(); + } + _onDone(data) { + if (data) { + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: data.chunk, + done: false + }); + } else { + this._cachedChunks.push(data.chunk); + } + } + this._done = true; + if (this._cachedChunks.length > 0) { + return; + } + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + } + _onError(status) { + this._storedError = createResponseStatusError(status, this._url); + this._headersCapability.reject(this._storedError); + for (const requestCapability of this._requests) { + requestCapability.reject(this._storedError); + } + this._requests.length = 0; + this._cachedChunks.length = 0; + } + _onProgress(evt) { + this.onProgress?.({ + loaded: evt.loaded, + total: evt.lengthComputable ? evt.total : this._contentLength + }); + } + get filename() { + return this._filename; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + get contentLength() { + return this._contentLength; + } + get headersReady() { + return this._headersCapability.promise; + } + async read() { + if (this._storedError) { + throw this._storedError; + } + if (this._cachedChunks.length > 0) { + const chunk = this._cachedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + this._headersCapability.reject(reason); + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + if (this._manager.isPendingRequest(this._fullRequestId)) { + this._manager.abortRequest(this._fullRequestId); + } + this._fullRequestReader = null; + } +} +class PDFNetworkStreamRangeRequestReader { + constructor(manager, begin, end) { + this._manager = manager; + const args = { + onDone: this._onDone.bind(this), + onError: this._onError.bind(this), + onProgress: this._onProgress.bind(this) + }; + this._url = manager.url; + this._requestId = manager.requestRange(begin, end, args); + this._requests = []; + this._queuedChunk = null; + this._done = false; + this._storedError = undefined; + this.onProgress = null; + this.onClosed = null; + } + _close() { + this.onClosed?.(this); + } + _onDone(data) { + const chunk = data.chunk; + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunk = chunk; + } + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + this._close(); + } + _onError(status) { + this._storedError = createResponseStatusError(status, this._url); + for (const requestCapability of this._requests) { + requestCapability.reject(this._storedError); + } + this._requests.length = 0; + this._queuedChunk = null; + } + _onProgress(evt) { + if (!this.isStreamingSupported) { + this.onProgress?.({ + loaded: evt.loaded + }); + } + } + get isStreamingSupported() { + return false; + } + async read() { + if (this._storedError) { + throw this._storedError; + } + if (this._queuedChunk !== null) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + if (this._manager.isPendingRequest(this._requestId)) { + this._manager.abortRequest(this._requestId); + } + this._close(); + } +} + +;// ./src/display/node_stream.js + + + +const urlRegex = /^[a-z][a-z0-9\-+.]+:/i; +function parseUrlOrPath(sourceUrl) { + if (urlRegex.test(sourceUrl)) { + return new URL(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); + } + const https = NodePackages.get("https"); + return https.request(url, { + headers + }, callback); +} +class PDFNodeStream { + constructor(source) { + this.source = source; + this.url = parseUrlOrPath(source.url); + this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:"; + this.isFsUrl = this.url.protocol === "file:"; + this.headers = createHeaders(this.isHttp, source.httpHeaders); + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once."); + this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this); + return this._fullRequestReader; + } + getRangeReader(start, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end); + this._rangeRequestReaders.push(rangeReader); + return rangeReader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } +} +class BaseFullReader { + constructor(stream) { + this._url = stream.url; + this._done = false; + this._storedError = null; + this.onProgress = null; + const source = stream.source; + this._contentLength = source.length; + this._loaded = 0; + this._filename = null; + this._disableRange = source.disableRange || false; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._isStreamingSupported = !source.disableStream; + this._isRangeSupported = !source.disableRange; + this._readableStream = null; + this._readCapability = Promise.withResolvers(); + this._headersCapability = Promise.withResolvers(); + } + 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._readCapability.promise; + if (this._done) { + return { + value: undefined, + done: true + }; + } + if (this._storedError) { + throw this._storedError; + } + const chunk = this._readableStream.read(); + if (chunk === null) { + this._readCapability = Promise.withResolvers(); + return this.read(); + } + this._loaded += chunk.length; + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + const buffer = new Uint8Array(chunk).buffer; + return { + value: buffer, + done: false + }; + } + cancel(reason) { + if (!this._readableStream) { + this._error(reason); + return; + } + this._readableStream.destroy(reason); + } + _error(reason) { + this._storedError = reason; + this._readCapability.resolve(); + } + _setReadableStream(readableStream) { + this._readableStream = readableStream; + readableStream.on("readable", () => { + this._readCapability.resolve(); + }); + readableStream.on("end", () => { + readableStream.destroy(); + this._done = true; + this._readCapability.resolve(); + }); + readableStream.on("error", reason => { + this._error(reason); + }); + if (!this._isStreamingSupported && this._isRangeSupported) { + this._error(new AbortException("streaming is disabled")); + } + if (this._storedError) { + this._readableStream.destroy(this._storedError); + } + } +} +class BaseRangeReader { + constructor(stream) { + this._url = stream.url; + this._done = false; + this._storedError = null; + this.onProgress = null; + this._loaded = 0; + this._readableStream = null; + this._readCapability = Promise.withResolvers(); + const source = stream.source; + this._isStreamingSupported = !source.disableStream; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + if (this._done) { + return { + value: undefined, + done: true + }; + } + if (this._storedError) { + throw this._storedError; + } + const chunk = this._readableStream.read(); + if (chunk === null) { + this._readCapability = Promise.withResolvers(); + return this.read(); + } + this._loaded += chunk.length; + this.onProgress?.({ + loaded: this._loaded + }); + const buffer = new Uint8Array(chunk).buffer; + return { + value: buffer, + done: false + }; + } + cancel(reason) { + if (!this._readableStream) { + this._error(reason); + return; + } + this._readableStream.destroy(reason); + } + _error(reason) { + this._storedError = reason; + this._readCapability.resolve(); + } + _setReadableStream(readableStream) { + this._readableStream = readableStream; + readableStream.on("readable", () => { + this._readCapability.resolve(); + }); + readableStream.on("end", () => { + readableStream.destroy(); + this._done = true; + this._readCapability.resolve(); + }); + readableStream.on("error", reason => { + this._error(reason); + }); + if (this._storedError) { + this._readableStream.destroy(this._storedError); + } + } +} +class PDFNodeStreamFullReader extends BaseFullReader { + constructor(stream) { + super(stream); + const headers = Object.fromEntries(stream.headers); + const handleResponse = response => { + if (response.statusCode === 404) { + const error = new MissingPDFException(`Missing PDF "${this._url}".`); + this._storedError = error; + this._headersCapability.reject(error); + return; + } + this._headersCapability.resolve(); + this._setReadableStream(response); + const responseHeaders = new Headers(this._readableStream.headers); + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: stream.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + this._isRangeSupported = allowRangeRequests; + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + }; + this._request = createRequest(this._url, headers, handleResponse); + this._request.on("error", reason => { + this._storedError = reason; + this._headersCapability.reject(reason); + }); + this._request.end(); + } +} +class PDFNodeStreamRangeReader extends BaseRangeReader { + constructor(stream, start, end) { + super(stream); + const headers = Object.fromEntries(stream.headers); + headers.Range = `bytes=${start}-${end - 1}`; + const handleResponse = response => { + if (response.statusCode === 404) { + const error = new MissingPDFException(`Missing PDF "${this._url}".`); + this._storedError = error; + return; + } + this._setReadableStream(response); + }; + this._request = createRequest(this._url, headers, handleResponse); + this._request.on("error", reason => { + this._storedError = reason; + }); + this._request.end(); + } +} +class PDFNodeStreamFsFullReader extends BaseFullReader { + constructor(stream) { + super(stream); + const fs = NodePackages.get("fs"); + fs.promises.lstat(this._url).then(stat => { + this._contentLength = stat.size; + 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); + const fs = NodePackages.get("fs"); + this._setReadableStream(fs.createReadStream(this._url, { + start, + end: end - 1 + })); + } +} + +;// ./src/display/text_layer.js + + +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 #canvasCtxFonts = new WeakMap(); + 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(); + } + }); + } else { + throw new Error('No "textContentSource" parameter specified.'); + } + this.#container = this.#rootContainer = container; + this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1); + this.#rotation = viewport.rotation; + this.#layoutTextParams = { + 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.finally(() => { + TextLayer.#pendingTextLayers.delete(this); + this.#layoutTextParams = null; + this.#styleCache = null; + }).catch(() => {}); + } + static get fontFamilyMap() { + const { + isWindows, + isFirefox + } = util_FeatureTest.platform; + return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]])); + } + 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 + }); + } + if (scale !== this.#scale) { + onBefore?.(); + this.#scale = scale; + const params = { + 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); + } + } + } + cancel() { + const abortEx = new AbortException("TextLayer task cancelled."); + this.#reader?.cancel(abortEx).catch(() => {}); + this.#reader = null; + this.#capability.reject(abortEx); + } + get textDivs() { + return this.#textDivs; + } + get textContentItemsStr() { + return this.#textContentItemsStr; + } + #processItems(items) { + if (this.#disableProcessItems) { + return; + } + 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; + } + 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; + } + 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; + } + let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily; + fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || 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; + } + } + if (shouldScaleText) { + textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; + } + this.#textDivProperties.set(textDiv, textDivProperties); + this.#layoutTextParams.div = textDiv; + this.#layoutTextParams.properties = textDivProperties; + this.#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); + } + } + #layout(params) { + const { + div, + properties, + ctx + } = params; + const { + style + } = div; + let transform = ""; + if (TextLayer.#minFontSize > 1) { + transform = `scale(${1 / TextLayer.#minFontSize})`; + } + if (properties.canvasWidth !== 0 && properties.hasText) { + const { + fontFamily + } = style; + const { + canvasWidth, + fontSize + } = properties; + TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily); + const { + width + } = ctx.measureText(div.textContent); + if (width > 0) { + transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`; + } + } + if (properties.angle !== 0) { + transform = `rotate(${properties.angle}deg) ${transform}`; + } + if (transform.length > 0) { + style.transform = transform; + } + } + static cleanup() { + if (this.#pendingTextLayers.size > 0) { + return; + } + this.#ascentCache.clear(); + for (const { + canvas + } of this.#canvasContexts.values()) { + canvas.remove(); + } + this.#canvasContexts.clear(); + } + static #getCtx(lang = null) { + let ctx = this.#canvasContexts.get(lang ||= ""); + if (!ctx) { + const canvas = document.createElement("canvas"); + canvas.className = "hiddenCanvasElement"; + canvas.lang = lang; + document.body.append(canvas); + ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: true + }); + this.#canvasContexts.set(lang, ctx); + this.#canvasCtxFonts.set(ctx, { + size: 0, + family: "" + }); + } + return ctx; + } + static #ensureCtxFont(ctx, size, family) { + const cached = this.#canvasCtxFonts.get(ctx); + if (size === cached.size && family === cached.family) { + return; + } + ctx.font = `${size}px ${family}`; + cached.size = size; + cached.family = family; + } + static #ensureMinFontSizeComputed() { + if (this.#minFontSize !== null) { + return; + } + 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(); + } + static #getAscent(fontFamily, lang) { + const cachedAscent = this.#ascentCache.get(fontFamily); + if (cachedAscent) { + return cachedAscent; + } + const ctx = this.#getCtx(lang); + ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE; + this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, 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; + 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; + const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT; + this.#ascentCache.set(fontFamily, ratio); + return ratio; + } +} + +;// ./src/display/xfa_text.js +class XfaText { + static textContent(xfa) { + const items = []; + const output = { + items, + styles: Object.create(null) + }; + function walk(node) { + if (!node) { + return; + } + let str = null; + const name = node.name; + if (name === "#text") { + str = node.value; + } else if (!XfaText.shouldBuildText(name)) { + return; + } else if (node?.attributes?.textContent) { + str = node.attributes.textContent; + } else if (node.value) { + str = node.value; + } + if (str !== null) { + items.push({ + str + }); + } + if (!node.children) { + return; + } + for (const child of node.children) { + walk(child); + } + } + walk(xfa); + return output; + } + static shouldBuildText(name) { + return !(name === "textarea" || name === "input" || name === "option" || name === "select"); + } +} + +;// ./src/display/api.js + + + + + + + + + + + + + + + + +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 + }; + } 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 CanvasFactory = src.CanvasFactory || DefaultCanvasFactory; + const FilterFactory = src.FilterFactory || DefaultFilterFactory; + 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); + if (src.canvasFactory) { + deprecated("`canvasFactory`-instance option, please use `CanvasFactory` instead."); + } + if (src.filterFactory) { + deprecated("`filterFactory`-instance option, please use `FilterFactory` instead."); + } + const styleElement = null; + setVerbosityLevel(verbosity); + const transportFactory = { + canvasFactory: new CanvasFactory({ + ownerDocument, + enableHWA + }), + filterFactory: new FilterFactory({ + docId, + ownerDocument + }), + cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({ + baseUrl: cMapUrl, + isCompressed: cMapPacked + }), + standardFontDataFactory: useWorkerFetch ? null : 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.7.76", + 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."); + } + let NetworkStream; + if (isNodeJS) { + const isFetchSupported = typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype; + NetworkStream = isFetchSupported && isValidFetchUrl(url) ? PDFFetchStream : PDFNodeStream; + } else { + NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : PDFNetworkStream; + } + networkStream = new NetworkStream({ + 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; + } + 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; + } + this._transport = null; + if (this._worker) { + this._worker.destroy(); + this._worker = null; + } + } +} +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); + } + }); + } + onDataProgressiveRead(chunk) { + this._readyCapability.promise.then(() => { + for (const listener of this._progressiveReadListeners) { + listener(chunk); + } + }); + } + onDataProgressiveDone() { + this._readyCapability.promise.then(() => { + for (const listener of this._progressiveDoneListeners) { + listener(); + } + }); + } + 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 canvasFactory() { + return this._transport.canvasFactory; + } + 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 { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getOptionalContentConfig(renderingIntent); + } + 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(); + } + 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({ + canvasContext, + viewport, + intent = "display", + annotationMode = AnnotationMode.ENABLE, + transform = null, + background = null, + optionalContentConfigPromise = null, + annotationCanvasMap = null, + pageColors = null, + printAnnotationStorage = null, + isEditing = false + }) { + this._stats?.time("Overall"); + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing); + const { + 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); + } + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + 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 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 + }); + (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"); + if (!(optionalContentConfig.renderingIntent & renderingIntent)) { + throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods."); + } + internalRenderTask.initializeGraphics({ + transparency, + optionalContentConfig + }); + internalRenderTask.operatorListChanged(); + }).catch(complete); + return renderTask; + } + getOperatorList({ + intent = "display", + annotationMode = AnnotationMode.ENABLE, + printAnnotationStorage = null, + isEditing = false + } = {}) { + function operatorListChanged() { + if (intentState.operatorList.lastChunk) { + intentState.opListReadCapability.resolve(intentState.operatorList); + intentState.renderTasks.delete(opListTask); + } + } + 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); + } + 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); + } + 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 => 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; + } + 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, + modifiedIds + }) { + const { + 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; + } + 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 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 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; + } +} +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(); + } +} +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.7.76"; +const build = "8b73b828b"; + +;// ./src/shared/scripting_utils.js +function makeColorComp(n) { + return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0"); +} +function scaleAndClamp(x) { + return Math.max(0, Math.min(255, 255 * x)); +} +class ColorConverters { + static CMYK_G([c, y, m, k]) { + return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)]; + } + static G_CMYK([g]) { + return ["CMYK", 0, 0, 0, 1 - g]; + } + static G_RGB([g]) { + return ["RGB", g, g, g]; + } + static G_rgb([g]) { + g = scaleAndClamp(g); + return [g, g, g]; + } + static G_HTML([g]) { + const G = makeColorComp(g); + return `#${G}${G}${G}`; + } + static RGB_G([r, g, b]) { + return ["G", 0.3 * r + 0.59 * g + 0.11 * b]; + } + static RGB_rgb(color) { + return color.map(scaleAndClamp); + } + static RGB_HTML(color) { + return `#${color.map(makeColorComp).join("")}`; + } + static T_HTML() { + return "#00000000"; + } + static T_rgb() { + return [null]; + } + static CMYK_RGB([c, y, m, k]) { + return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)]; + } + static CMYK_rgb([c, y, m, k]) { + return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))]; + } + static CMYK_HTML(components) { + const rgb = this.CMYK_RGB(components).slice(1); + return this.RGB_HTML(rgb); + } + static RGB_CMYK([r, g, b]) { + const c = 1 - r; + const m = 1 - g; + const y = 1 - b; + const k = Math.min(c, m, y); + return ["CMYK", c, m, y, k]; + } +} + +;// ./src/display/xfa_layer.js + +class XfaLayer { + static setupStorage(html, id, element, storage, intent) { + const storedData = storage.getValue(id, { + value: null + }); + switch (element.name) { + case "textarea": + if (storedData.value !== null) { + html.textContent = storedData.value; + } + if (intent === "print") { + break; + } + html.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + }); + break; + case "input": + if (element.attributes.type === "radio" || element.attributes.type === "checkbox") { + if (storedData.value === element.attributes.xfaOn) { + html.setAttribute("checked", true); + } else if (storedData.value === element.attributes.xfaOff) { + html.removeAttribute("checked"); + } + if (intent === "print") { + break; + } + html.addEventListener("change", event => { + storage.setValue(id, { + value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff") + }); + }); + } else { + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + } + if (intent === "print") { + break; + } + html.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + }); + } + break; + case "select": + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + for (const option of element.children) { + if (option.attributes.value === storedData.value) { + option.attributes.selected = true; + } else if (option.attributes.hasOwnProperty("selected")) { + delete option.attributes.selected; + } + } + } + html.addEventListener("input", event => { + const options = event.target.options; + const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; + storage.setValue(id, { + value + }); + }); + break; + } + } + static setAttributes({ + html, + element, + storage = null, + intent, + linkService + }) { + const { + attributes + } = element; + const isHTMLAnchorElement = html instanceof HTMLAnchorElement; + if (attributes.type === "radio") { + attributes.name = `${attributes.name}-${intent}`; + } + for (const [key, value] of Object.entries(attributes)) { + if (value === null || value === undefined) { + continue; + } + switch (key) { + case "class": + if (value.length) { + html.setAttribute(key, value.join(" ")); + } + break; + case "dataId": + break; + case "id": + html.setAttribute("data-element-id", value); + break; + case "style": + Object.assign(html.style, value); + break; + case "textContent": + html.textContent = value; + break; + default: + if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") { + html.setAttribute(key, value); + } + } + } + if (isHTMLAnchorElement) { + linkService.addLinkAttributes(html, attributes.href, attributes.newWindow); + } + if (storage && attributes.dataId) { + this.setupStorage(html, attributes.dataId, element, storage); + } + } + static render(parameters) { + const storage = parameters.annotationStorage; + const linkService = parameters.linkService; + const root = parameters.xfaHtml; + const intent = parameters.intent || "display"; + const rootHtml = document.createElement(root.name); + if (root.attributes) { + this.setAttributes({ + html: rootHtml, + element: root, + intent, + linkService + }); + } + 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 (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) { + stack.pop(); + continue; + } + const child = parent.children[++stack.at(-1)[1]]; + if (child === null) { + continue; + } + const { + name + } = child; + if (name === "#text") { + const node = document.createTextNode(child.value); + textDivs.push(node); + html.append(node); + continue; + } + const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name); + html.append(childHtml); + if (child.attributes) { + this.setAttributes({ + html: childHtml, + element: child, + storage, + intent, + linkService + }); + } + if (child.children?.length > 0) { + stack.push([child, -1, childHtml]); + } else if (child.value) { + const node = document.createTextNode(child.value); + if (isNotForRichText && XfaText.shouldBuildText(name)) { + textDivs.push(node); + } + childHtml.append(node); + } + } + for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { + el.setAttribute("readOnly", true); + } + return { + textDivs + }; + } + static update(parameters) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + parameters.div.style.transform = transform; + parameters.div.hidden = false; + } +} + +;// ./src/display/annotation_layer.js + + + + + +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 = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : 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); + this._editOnDoubleClick(); + 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 + }); + this.annotationEditorType = AnnotationEditorType.HIGHLIGHT; + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("highlightAnnotation"); + this._editOnDoubleClick(); + 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 + }); + this.annotationEditorType = AnnotationEditorType.STAMP; + } + render() { + this.container.classList.add("stampAnnotation"); + this.container.setAttribute("role", "img"); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this._editOnDoubleClick(); + 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(); + #structTreeLayer = null; + constructor({ + div, + accessibilityManager, + annotationCanvasMap, + annotationEditorUIManager, + page, + viewport, + structTreeLayer + }) { + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationCanvasMap = annotationCanvasMap; + this.#structTreeLayer = structTreeLayer || null; + this.page = page; + this.viewport = viewport; + this.zIndex = 0; + this._annotationEditorUIManager = annotationEditorUIManager; + } + hasEditableAnnotations() { + return this.#editableAnnotations.size > 0; + } + async #appendElement(element, id) { + const contentElement = element.firstChild || element; + const annotationId = contentElement.id = `${AnnotationPrefix}${id}`; + const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId); + if (ariaAttributes) { + for (const [key, value] of ariaAttributes) { + contentElement.setAttribute(key, value); + } + } + 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"; + } + await 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); + } +} + +;// ./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; + 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(); + let prevChild = null; + for (const child of this.editorDiv.childNodes) { + if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") { + continue; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + prevChild = 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 async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof FreeTextAnnotationElement) { + const { + data: { + defaultAppearanceData: { + fontSize, + fontColor + }, + rect, + rotation, + id, + popupRef + }, + 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, + popupRef + }; + } + const editor = await 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 this.serializeDeleted(); + } + 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(); + } +} + +;// ./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(); + } +} + +;// ./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 #l10nColor = null; + 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"; + ColorPicker.#l10nColor ||= Object.freeze({ + blue: "pdfjs-editor-colorpicker-blue", + green: "pdfjs-editor-colorpicker-green", + pink: "pdfjs-editor-colorpicker-pink", + red: "pdfjs-editor-colorpicker-red", + yellow: "pdfjs-editor-colorpicker-yellow" + }); + } + 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", ColorPicker.#l10nColor[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; + } +} + +;// ./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 _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 if (this.#boxes) { + 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 setColorAndOpacity = (col, opa) => { + this.color = col; + this.parent?.drawLayer.changeColor(this.#id, col); + this.#colorPicker?.updateColor(col); + this.#opacity = opa; + this.parent?.drawLayer.changeOpacity(this.#id, opa); + }; + const savedColor = this.color; + const savedOpacity = this.#opacity; + this.addCommands({ + cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity), + undo: setColorAndOpacity.bind(this, savedColor, savedOpacity), + 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() { + if (!this.annotationElementId) { + 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 async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof HighlightAnnotationElement) { + const { + data: { + quadPoints, + rect, + rotation, + id, + color, + opacity, + popupRef + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color), + opacity, + quadPoints, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + popupRef + }; + } else if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists, + rect, + rotation, + id, + color, + borderStyle: { + rawWidth: thickness + }, + popupRef + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color), + thickness, + inkLists, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + popupRef + }; + } + const { + color, + quadPoints, + inkLists, + opacity + } = data; + const editor = await super.deserialize(data, parent, uiManager); + editor.color = Util.makeHexColor(...color); + editor.#opacity = opacity || 1; + if (inkLists) { + editor.#thickness = data.thickness; + } + editor.annotationElementId = data.id || null; + editor._initialData = initialData; + const [pageWidth, pageHeight] = editor.pageDimensions; + const [pageX, pageY] = editor.pageTranslation; + if (quadPoints) { + const boxes = editor.#boxes = []; + for (let i = 0; i < quadPoints.length; i += 8) { + boxes.push({ + x: (quadPoints[i] - pageX) / pageWidth, + y: 1 - (quadPoints[i + 1] - pageY) / pageHeight, + width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth, + height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight + }); + } + editor.#createOutlines(); + editor.#addToDrawLayer(); + editor.rotate(editor.rotation); + } else if (inkLists) { + editor.#isFreeHighlight = true; + const points = inkLists[0]; + const point = { + x: points[0] - pageX, + y: pageHeight - (points[1] - pageY) + }; + const outliner = new FreeOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001); + for (let i = 0, ii = points.length; i < ii; i += 2) { + point.x = points[i] - pageX; + point.y = pageHeight - (points[i + 1] - pageY); + outliner.add(point); + } + const { + id, + clipPathId + } = parent.drawLayer.highlight(outliner, editor.color, editor._defaultOpacity, true); + editor.#createFreeOutlines({ + highlightOutlines: outliner.getOutlines(), + highlightId: id, + clipPathId + }); + editor.#addToDrawLayer(); + } + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty() || isForCopying) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const rect = this.getRect(0, 0); + const color = AnnotationEditor._colorManager.convert(this.color); + const serialized = { + 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 + }; + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color + } = this._initialData; + return serialized.color.some((c, i) => c !== color[i]); + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getRect(0, 0) + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } +} + +;// ./src/display/editor/ink.js + + + + + +class InkEditor extends AnnotationEditor { + #baseHeight = 0; + #baseWidth = 0; + #canvasContextMenuTimeoutId = null; + #currentPath2D = new Path2D(); + #disableEditing = false; + #drawingAC = null; + #hasSomethingToDraw = false; + #isCanvasInitialized = false; + #observer = null; + #pointerdownAC = null; + #realWidth = 0; + #realHeight = 0; + #requestFrameCallback = null; + static _defaultColor = null; + static _defaultOpacity = 1; + static _defaultThickness = 1; + static _type = "ink"; + static _editorType = AnnotationEditorType.INK; + constructor(params) { + super({ + ...params, + name: "inkEditor" + }); + this.color = params.color || null; + this.thickness = params.thickness || null; + this.opacity = params.opacity || null; + this.paths = []; + this.bezierPath2D = []; + this.allRawPaths = []; + this.currentPath = []; + this.scaleFactor = 1; + this.translationX = this.translationY = 0; + this.x = 0; + this.y = 0; + this._willKeepAspectRatio = true; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.INK_THICKNESS: + InkEditor._defaultThickness = value; + break; + case AnnotationEditorParamsType.INK_COLOR: + InkEditor._defaultColor = value; + break; + case AnnotationEditorParamsType.INK_OPACITY: + InkEditor._defaultOpacity = value / 100; + break; + } + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.INK_THICKNESS: + this.#updateThickness(value); + break; + case AnnotationEditorParamsType.INK_COLOR: + this.#updateColor(value); + break; + case AnnotationEditorParamsType.INK_OPACITY: + this.#updateOpacity(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || AnnotationEditor._defaultLineColor], [AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]]; + } + get propertiesToUpdate() { + 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: 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 + }); + } + #updateColor(color) { + const setColor = col => { + this.color = col; + this.#redraw(); + }; + 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.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: setOpacity.bind(this, opacity), + undo: setOpacity.bind(this, savedOpacity), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.INK_OPACITY, + overwriteIfSameType: true, + keepUndo: true + }); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (!this.canvas) { + this.#createCanvas(); + this.#createObserver(); + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + this.#setCanvasDims(); + } + this.#fitToContent(); + } + remove() { + if (this.canvas === null) { + return; + } + if (!this.isEmpty()) { + this.commit(); + } + this.canvas.width = this.canvas.height = 0; + this.canvas.remove(); + this.canvas = null; + if (this.#canvasContextMenuTimeoutId) { + clearTimeout(this.#canvasContextMenuTimeoutId); + this.#canvasContextMenuTimeoutId = null; + } + this.#observer?.disconnect(); + this.#observer = null; + super.remove(); + } + setParent(parent) { + if (!this.parent && parent) { + this._uiManager.removeShouldRescale(this); + } else if (this.parent && parent === null) { + this._uiManager.addShouldRescale(this); + } + super.setParent(parent); + } + onScaleChanging() { + const [parentWidth, parentHeight] = this.parentDimensions; + const width = this.width * parentWidth; + const height = this.height * parentHeight; + this.setDimensions(width, height); + } + enableEditMode() { + if (this.#disableEditing || this.canvas === null) { + return; + } + super.enableEditMode(); + this._isDraggable = false; + this.#addPointerdownListener(); + } + disableEditMode() { + if (!this.isInEditMode() || this.canvas === null) { + return; + } + super.disableEditMode(); + this._isDraggable = !this.isEmpty(); + this.div.classList.remove("editing"); + this.#removePointerdownListener(); + } + onceAdded() { + this._isDraggable = !this.isEmpty(); + } + isEmpty() { + return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0; + } + #getInitialBBox() { + const { + parentRotation, + parentDimensions: [width, height] + } = this; + switch (parentRotation) { + case 90: + return [0, height, height, width]; + case 180: + return [width, height, width, height]; + case 270: + return [width, 0, height, width]; + default: + return [0, 0, width, height]; + } + } + #setStroke() { + const { + ctx, + color, + opacity, + thickness, + parentScale, + scaleFactor + } = this; + ctx.lineWidth = thickness * parentScale / scaleFactor; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.miterLimit = 10; + ctx.strokeStyle = `${color}${opacityToHex(opacity)}`; + } + #startDrawing(x, y) { + 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 || AnnotationEditor._defaultLineColor; + this.opacity ??= InkEditor._defaultOpacity; + } + this.currentPath.push([x, y]); + this.#hasSomethingToDraw = false; + this.#setStroke(); + this.#requestFrameCallback = () => { + this.#drawPoints(); + if (this.#requestFrameCallback) { + window.requestAnimationFrame(this.#requestFrameCallback); + } + }; + window.requestAnimationFrame(this.#requestFrameCallback); + } + #draw(x, y) { + const [lastX, lastY] = this.currentPath.at(-1); + if (this.currentPath.length > 1 && x === lastX && y === lastY) { + return; + } + const currentPath = this.currentPath; + let path2D = this.#currentPath2D; + currentPath.push([x, y]); + this.#hasSomethingToDraw = true; + if (currentPath.length <= 2) { + path2D.moveTo(...currentPath[0]); + path2D.lineTo(x, y); + return; + } + if (currentPath.length === 3) { + this.#currentPath2D = path2D = new Path2D(); + path2D.moveTo(...currentPath[0]); + } + this.#makeBezierCurve(path2D, ...currentPath.at(-3), ...currentPath.at(-2), x, y); + } + #endPath() { + if (this.currentPath.length === 0) { + return; + } + const lastPoint = this.currentPath.at(-1); + this.#currentPath2D.lineTo(...lastPoint); + } + #stopDrawing(x, y) { + this.#requestFrameCallback = null; + x = Math.min(Math.max(x, 0), this.canvas.width); + y = Math.min(Math.max(y, 0), this.canvas.height); + this.#draw(x, y); + this.#endPath(); + let bezier; + if (this.currentPath.length !== 1) { + bezier = this.#generateBezierPoints(); + } else { + const xy = [x, y]; + bezier = [[xy, xy.slice(), xy.slice(), xy]]; + } + const path2D = this.#currentPath2D; + const currentPath = this.currentPath; + this.currentPath = []; + this.#currentPath2D = new Path2D(); + const cmd = () => { + this.allRawPaths.push(currentPath); + this.paths.push(bezier); + this.bezierPath2D.push(path2D); + this._uiManager.rebuild(this); + }; + const undo = () => { + this.allRawPaths.pop(); + this.paths.pop(); + this.bezierPath2D.pop(); + if (this.paths.length === 0) { + this.remove(); + } else { + if (!this.canvas) { + this.#createCanvas(); + this.#createObserver(); + } + this.#fitToContent(); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } + #drawPoints() { + if (!this.#hasSomethingToDraw) { + return; + } + this.#hasSomethingToDraw = false; + const thickness = Math.ceil(this.thickness * this.parentScale); + const lastPoints = this.currentPath.slice(-3); + const x = lastPoints.map(xy => xy[0]); + const y = lastPoints.map(xy => xy[1]); + const xMin = Math.min(...x) - thickness; + const xMax = Math.max(...x) + thickness; + const yMin = Math.min(...y) - thickness; + const yMax = Math.max(...y) + thickness; + const { + ctx + } = this; + ctx.save(); + ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + for (const path of this.bezierPath2D) { + ctx.stroke(path); + } + ctx.stroke(this.#currentPath2D); + ctx.restore(); + } + #makeBezierCurve(path2D, x0, y0, x1, y1, x2, y2) { + const prevX = (x0 + x1) / 2; + const prevY = (y0 + y1) / 2; + const x3 = (x1 + x2) / 2; + const y3 = (y1 + y2) / 2; + path2D.bezierCurveTo(prevX + 2 * (x1 - prevX) / 3, prevY + 2 * (y1 - prevY) / 3, x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3, x3, y3); + } + #generateBezierPoints() { + const path = this.currentPath; + if (path.length <= 2) { + return [[path[0], path[0], path.at(-1), path.at(-1)]]; + } + const bezierPoints = []; + let i; + let [x0, y0] = path[0]; + for (i = 1; i < path.length - 2; i++) { + const [x1, y1] = path[i]; + const [x2, y2] = path[i + 1]; + const x3 = (x1 + x2) / 2; + const y3 = (y1 + y2) / 2; + const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3]; + const control2 = [x3 + 2 * (x1 - x3) / 3, y3 + 2 * (y1 - y3) / 3]; + bezierPoints.push([[x0, y0], control1, control2, [x3, y3]]); + [x0, y0] = [x3, y3]; + } + const [x1, y1] = path[i]; + const [x2, y2] = path[i + 1]; + const control1 = [x0 + 2 * (x1 - x0) / 3, y0 + 2 * (y1 - y0) / 3]; + const control2 = [x2 + 2 * (x1 - x2) / 3, y2 + 2 * (y1 - y2) / 3]; + bezierPoints.push([[x0, y0], control1, control2, [x2, y2]]); + return bezierPoints; + } + #redraw() { + if (this.isEmpty()) { + this.#updateTransform(); + return; + } + this.#setStroke(); + const { + canvas, + ctx + } = this; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, canvas.width, canvas.height); + this.#updateTransform(); + for (const path of this.bezierPath2D) { + ctx.stroke(path); + } + } + commit() { + if (this.#disableEditing) { + return; + } + super.commit(); + this.isEditing = false; + this.disableEditMode(); + this.setInForeground(); + this.#disableEditing = true; + this.div.classList.add("disabled"); + this.#fitToContent(true); + this.select(); + this.parent.addInkEditorIfNeeded(true); + this.moveInDOM(); + this.div.focus({ + preventScroll: true + }); + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + 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 (!this.div.contains(document.activeElement)) { + this.div.focus({ + preventScroll: true + }); + } + this.#startDrawing(event.offsetX, event.offsetY); + } + canvasPointermove(event) { + event.preventDefault(); + this.#draw(event.offsetX, event.offsetY); + } + canvasPointerup(event) { + event.preventDefault(); + this.#endDrawing(event); + } + canvasPointerleave(event) { + this.#endDrawing(event); + } + #endDrawing(event) { + 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(); + this.setInBackground(); + } + #createCanvas() { + this.canvas = document.createElement("canvas"); + this.canvas.width = this.canvas.height = 0; + this.canvas.className = "inkEditorCanvas"; + this.canvas.setAttribute("data-l10n-id", "pdfjs-ink-canvas"); + this.div.append(this.canvas); + this.ctx = this.canvas.getContext("2d"); + } + #createObserver() { + this.#observer = new ResizeObserver(entries => { + const rect = entries[0].contentRect; + if (rect.width && rect.height) { + this.setDimensions(rect.width, rect.height); + } + }); + 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; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this.width) { + baseX = this.x; + baseY = this.y; + } + super.render(); + 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); + this.#createCanvas(); + if (this.width) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.setAspectRatio(this.width * parentWidth, this.height * parentHeight); + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + this.#isCanvasInitialized = true; + this.#setCanvasDims(); + this.setDims(this.width * parentWidth, this.height * parentHeight); + this.#redraw(); + this.div.classList.add("disabled"); + } else { + this.div.classList.add("editing"); + this.enableEditMode(); + } + this.#createObserver(); + return this.div; + } + #setCanvasDims() { + if (!this.#isCanvasInitialized) { + return; + } + const [parentWidth, parentHeight] = this.parentDimensions; + this.canvas.width = Math.ceil(this.width * parentWidth); + this.canvas.height = Math.ceil(this.height * parentHeight); + this.#updateTransform(); + } + setDimensions(width, height) { + const roundedWidth = Math.round(width); + const roundedHeight = Math.round(height); + if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) { + return; + } + this.#realWidth = roundedWidth; + this.#realHeight = roundedHeight; + this.canvas.style.visibility = "hidden"; + const [parentWidth, parentHeight] = this.parentDimensions; + this.width = width / parentWidth; + this.height = height / parentHeight; + this.fixAndSetPosition(); + if (this.#disableEditing) { + this.#setScaleFactor(width, height); + } + this.#setCanvasDims(); + this.#redraw(); + this.canvas.style.visibility = "visible"; + this.fixDims(); + } + #setScaleFactor(width, height) { + const padding = this.#getPadding(); + const scaleFactorW = (width - padding) / this.#baseWidth; + const scaleFactorH = (height - padding) / this.#baseHeight; + this.scaleFactor = Math.min(scaleFactorW, scaleFactorH); + } + #updateTransform() { + const padding = this.#getPadding() / 2; + this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding); + } + static #buildPath2D(bezier) { + const path2D = new Path2D(); + for (let i = 0, ii = bezier.length; i < ii; i++) { + const [first, control1, control2, second] = bezier[i]; + if (i === 0) { + path2D.moveTo(...first); + } + path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]); + } + return path2D; + } + static #toPDFCoordinates(points, rect, rotation) { + const [blX, blY, trX, trY] = rect; + switch (rotation) { + case 0: + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] += blX; + points[i + 1] = trY - points[i + 1]; + } + break; + case 90: + for (let i = 0, ii = points.length; i < ii; i += 2) { + const x = points[i]; + points[i] = points[i + 1] + blX; + points[i + 1] = x + blY; + } + break; + case 180: + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] = trX - points[i]; + points[i + 1] += blY; + } + break; + case 270: + for (let i = 0, ii = points.length; i < ii; i += 2) { + const x = points[i]; + points[i] = trX - points[i + 1]; + points[i + 1] = trY - x; + } + break; + default: + throw new Error("Invalid rotation"); + } + return points; + } + static #fromPDFCoordinates(points, rect, rotation) { + const [blX, blY, trX, trY] = rect; + switch (rotation) { + case 0: + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] -= blX; + points[i + 1] = trY - points[i + 1]; + } + break; + case 90: + for (let i = 0, ii = points.length; i < ii; i += 2) { + const x = points[i]; + points[i] = points[i + 1] - blY; + points[i + 1] = x - blX; + } + break; + case 180: + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] = trX - points[i]; + points[i + 1] -= blY; + } + break; + case 270: + for (let i = 0, ii = points.length; i < ii; i += 2) { + const x = points[i]; + points[i] = trY - points[i + 1]; + points[i + 1] = trX - x; + } + break; + default: + throw new Error("Invalid rotation"); + } + return points; + } + #serializePaths(s, tx, ty, rect) { + const paths = []; + const padding = this.thickness / 2; + const shiftX = s * tx + padding; + const shiftY = s * ty + padding; + for (const bezier of this.paths) { + const buffer = []; + 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; + const p21 = s * control1[1] + shiftY; + const p30 = s * control2[0] + shiftX; + const p31 = s * control2[1] + shiftY; + const p40 = s * second[0] + shiftX; + const p41 = s * second[1] + shiftY; + if (j === 0) { + buffer.push(p10, p11); + points.push(p10, p11); + } + buffer.push(p20, p21, p30, p31, p40, p41); + points.push(p20, p21); + if (j === jj - 1) { + points.push(p40, p41); + } + } + paths.push({ + bezier: InkEditor.#toPDFCoordinates(buffer, rect, this.rotation), + points: InkEditor.#toPDFCoordinates(points, rect, this.rotation) + }); + } + return paths; + } + #getBbox() { + let xMin = Infinity; + let xMax = -Infinity; + let yMin = Infinity; + let yMax = -Infinity; + for (const path of this.paths) { + for (const [first, control1, control2, second] of path) { + 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]); + yMax = Math.max(yMax, bbox[3]); + } + } + return [xMin, yMin, xMax, yMax]; + } + #getPadding() { + return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0; + } + #fitToContent(firstTime = false) { + if (this.isEmpty()) { + return; + } + if (!this.#disableEditing) { + this.#redraw(); + return; + } + const bbox = this.#getBbox(); + const padding = this.#getPadding(); + 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; + this.width = width / parentWidth; + this.height = height / parentHeight; + this.setAspectRatio(width, height); + const prevTranslationX = this.translationX; + const prevTranslationY = this.translationY; + this.translationX = -bbox[0]; + this.translationY = -bbox[1]; + this.#setCanvasDims(); + this.#redraw(); + this.#realWidth = width; + this.#realHeight = height; + this.setDims(width, height); + const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0; + this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding); + } + static async deserialize(data, parent, uiManager) { + if (data instanceof InkAnnotationElement) { + return null; + } + const editor = await super.deserialize(data, parent, uiManager); + editor.thickness = data.thickness; + editor.color = Util.makeHexColor(...data.color); + editor.opacity = data.opacity; + const [pageWidth, pageHeight] = editor.pageDimensions; + const width = editor.width * pageWidth; + const height = editor.height * pageHeight; + const scaleFactor = editor.parentScale; + const padding = data.thickness / 2; + editor.#disableEditing = true; + editor.#realWidth = Math.round(width); + editor.#realHeight = Math.round(height); + const { + paths, + rect, + rotation + } = data; + for (let { + bezier + } of paths) { + bezier = InkEditor.#fromPDFCoordinates(bezier, rect, rotation); + const path = []; + editor.paths.push(path); + let p0 = scaleFactor * (bezier[0] - padding); + let p1 = scaleFactor * (bezier[1] - padding); + for (let i = 2, ii = bezier.length; i < ii; i += 6) { + const p10 = scaleFactor * (bezier[i] - padding); + const p11 = scaleFactor * (bezier[i + 1] - padding); + const p20 = scaleFactor * (bezier[i + 2] - padding); + const p21 = scaleFactor * (bezier[i + 3] - padding); + const p30 = scaleFactor * (bezier[i + 4] - padding); + const p31 = scaleFactor * (bezier[i + 5] - padding); + path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]); + p0 = p30; + p1 = p31; + } + const path2D = this.#buildPath2D(path); + editor.bezierPath2D.push(path2D); + } + const bbox = editor.#getBbox(); + 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; + } + serialize() { + if (this.isEmpty()) { + return null; + } + const rect = this.getRect(0, 0); + const color = AnnotationEditor._colorManager.convert(this.ctx.strokeStyle); + return { + annotationType: AnnotationEditorType.INK, + color, + thickness: this.thickness, + opacity: this.opacity, + paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, rect), + pageIndex: this.pageIndex, + rect, + rotation: this.rotation, + structTreeParentId: this._structTreeParentId + }; + } +} + +;// ./src/display/editor/stamp.js + + + + +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, + name: "stampEditor" + }); + this.#bitmapUrl = params.bitmapUrl; + this.#bitmapFile = params.bitmapFile; + } + 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 shadow(this, "supportedTypes", types.map(type => `image/${type}`)); + } + static get supportedTypesStr() { + return shadow(this, "supportedTypesStr", this.supportedTypes.join(",")); + } + static isHandlingMimeForPasting(mime) { + return this.supportedTypes.includes(mime); + } + static paste(item, parent) { + 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(); + return; + } + this.#bitmap = data.bitmap; + if (!fromId) { + 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) { + 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, 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) { + this._uiManager.enableWaiting(true); + this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapUrl) { + const url = this.#bitmapUrl; + this.#bitmapUrl = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapFile) { + const file = this.#bitmapFile; + this.#bitmapFile = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + 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) { + this.remove(); + } 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(); + } + remove() { + if (this.#bitmapId) { + this.#bitmap = null; + this._uiManager.imageManager.deleteId(this.#bitmapId); + this.#canvas?.remove(); + this.#canvas = null; + this.#observer?.disconnect(); + this.#observer = null; + if (this.#resizeTimeoutId) { + clearTimeout(this.#resizeTimeoutId); + this.#resizeTimeoutId = null; + } + } + super.remove(); + } + rebuild() { + if (!this.parent) { + if (this.#bitmapId) { + this.#getBitmap(); + } + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (this.#bitmapId && this.#canvas === null) { + this.#getBitmap(); + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + onceAdded() { + this._isDraggable = true; + this.div.focus(); + } + isEmpty() { + return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId); + } + get isResizable() { + return true; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this.width) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.div.hidden = true; + this.div.setAttribute("role", "figure"); + this.addAltTextButton(); + if (this.#bitmap) { + this.#createCanvas(); + } else { + this.#getBitmap(); + } + if (this.width && !this.annotationElementId) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + } + return this.div; + } + #createCanvas() { + const { + div + } = this; + let { + width, + height + } = this.#bitmap; + const [pageWidth, pageHeight] = this.pageDimensions; + const MAX_RATIO = 0.75; + if (this.width) { + width = this.width * pageWidth; + height = this.height * pageHeight; + } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) { + const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height); + width *= factor; + height *= factor; + } + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight); + this._uiManager.enableWaiting(false); + const canvas = this.#canvas = document.createElement("canvas"); + canvas.setAttribute("role", "img"); + this.addContainer(canvas); + if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) { + div.hidden = false; + } + this.#drawBitmap(width, height); + this.#createObserver(); + if (!this.#hasBeenAddedInUndoStack) { + this.parent.addUndoableEditor(this); + this.#hasBeenAddedInUndoStack = true; + } + this._reportTelemetry({ + action: "inserted_image" + }); + if (this.#bitmapFileName) { + canvas.setAttribute("aria-label", this.#bitmapFileName); + } + } + copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) { + if (!maxDataDimension) { + maxDataDimension = 224; + } + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + const outputScale = new OutputScale(); + let bitmap = this.#bitmap; + let width = bitmapWidth, + height = bitmapHeight; + let canvas = null; + if (maxPreviewDimension) { + if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) { + const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight); + width = Math.floor(bitmapWidth * ratio); + height = Math.floor(bitmapHeight * ratio); + } + canvas = document.createElement("canvas"); + const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx); + const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(scaledWidth, scaledHeight); + } + 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 boxDimWidth = boxDim * outputScale.sx; + const boxDimHeight = boxDim * outputScale.sy; + const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2); + const patternCtx = pattern.getContext("2d"); + patternCtx.fillStyle = white; + patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2); + patternCtx.fillStyle = black; + patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight); + patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight); + ctx.fillStyle = ctx.createPattern(pattern, "repeat"); + ctx.fillRect(0, 0, scaledWidth, scaledHeight); + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + let imageData = null; + if (createImageData) { + let dataWidth, dataHeight; + if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) { + dataWidth = bitmap.width; + dataHeight = bitmap.height; + } else { + bitmap = this.#bitmap; + if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) { + const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight); + dataWidth = Math.floor(bitmapWidth * ratio); + dataHeight = Math.floor(bitmapHeight * ratio); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(dataWidth, dataHeight); + } + } + } + const offscreen = new OffscreenCanvas(dataWidth, dataHeight); + const offscreenCtx = offscreen.getContext("2d", { + willReadFrequently: true + }); + offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight); + imageData = { + width: dataWidth, + height: dataHeight, + data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data + }; + } + return { + canvas, + width, + height, + imageData + }; + } + #setDimensions(width, height) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.width = width / parentWidth; + this.height = height / parentHeight; + if (this._initialOptions?.isCentered) { + this.center(); + } else { + this.fixAndSetPosition(); + } + this._initialOptions = null; + if (this.#resizeTimeoutId !== null) { + clearTimeout(this.#resizeTimeoutId); + } + const TIME_TO_WAIT = 200; + this.#resizeTimeoutId = setTimeout(() => { + this.#resizeTimeoutId = null; + this.#drawBitmap(width, height); + }, TIME_TO_WAIT); + } + #scaleBitmap(width, height) { + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + let newWidth = bitmapWidth; + let newHeight = bitmapHeight; + let bitmap = this.#bitmap; + while (newWidth > 2 * width || newHeight > 2 * height) { + const prevWidth = newWidth; + const prevHeight = newHeight; + if (newWidth > 2 * width) { + newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2); + } + if (newHeight > 2 * height) { + newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2); + } + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); + bitmap = offscreen.transferToImageBitmap(); + } + return bitmap; + } + #drawBitmap(width, height) { + const outputScale = new OutputScale(); + const scaledWidth = Math.ceil(width * outputScale.sx); + const scaledHeight = Math.ceil(height * outputScale.sy); + const canvas = this.#canvas; + if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) { + return; + } + canvas.width = scaledWidth; + canvas.height = scaledHeight; + const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight); + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + getImageForAltText() { + return this.#canvas; + } + #serializeBitmap(toUrl) { + if (toUrl) { + if (this.#isSvg) { + const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId); + if (url) { + return url; + } + } + const canvas = document.createElement("canvas"); + ({ + width: canvas.width, + height: canvas.height + } = this.#bitmap); + const ctx = canvas.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0); + return canvas.toDataURL(); + } + if (this.#isSvg) { + const [pageWidth, pageHeight] = this.pageDimensions; + 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); + return offscreen.transferToImageBitmap(); + } + 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) { + this.#setDimensions(rect.width, rect.height); + } + }); + this.#observer.observe(this.div); + this._uiManager._signal.addEventListener("abort", () => { + this.#observer?.disconnect(); + this.#observer = null; + }, { + once: true + }); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof StampAnnotationElement) { + const { + data: { + rect, + rotation, + id, + structParent, + popupRef + }, + container, + parent: { + page: { + pageNumber + } + } + } = data; + const canvas = container.querySelector("canvas"); + const imageData = uiManager.imageManager.getFromCanvas(container.id, canvas); + canvas.remove(); + const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || ""; + initialData = data = { + annotationType: AnnotationEditorType.STAMP, + bitmapId: imageData.id, + bitmap: imageData.bitmap, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + accessibilityData: { + decorative: false, + altText + }, + isSvg: false, + structParent, + popupRef + }; + } + const editor = await super.deserialize(data, parent, uiManager); + const { + rect, + bitmap, + bitmapUrl, + bitmapId, + isSvg, + accessibilityData + } = data; + if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) { + editor.#bitmapId = bitmapId; + if (bitmap) { + editor.#bitmap = bitmap; + } + } else { + editor.#bitmapUrl = bitmapUrl; + } + editor.#isSvg = isSvg; + const [parentWidth, parentHeight] = editor.pageDimensions; + editor.width = (rect[2] - rect[0]) / parentWidth; + editor.height = (rect[3] - rect[1]) / parentHeight; + editor.annotationElementId = data.id || null; + if (accessibilityData) { + editor.altTextData = accessibilityData; + } + editor._initialData = initialData; + editor.#hasBeenAddedInUndoStack = !!initialData; + return editor; + } + serialize(isForCopying = false, context = null) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const serialized = { + annotationType: AnnotationEditorType.STAMP, + bitmapId: this.#bitmapId, + pageIndex: this.pageIndex, + rect: this.getRect(0, 0), + rotation: this.rotation, + isSvg: this.#isSvg, + structTreeParentId: this._structTreeParentId + }; + if (isForCopying) { + serialized.bitmapUrl = this.#serializeBitmap(true); + serialized.accessibilityData = this.serializeAltText(true); + return serialized; + } + const { + decorative, + altText + } = this.serializeAltText(false); + if (!decorative && altText) { + serialized.accessibilityData = { + type: "Figure", + alt: altText + }; + } + if (this.annotationElementId) { + const changes = this.#hasElementChanged(serialized); + if (changes.isSame) { + return null; + } + if (changes.isSameAltText) { + delete serialized.accessibilityData; + } else { + serialized.accessibilityData.structParent = this._initialData.structParent ?? -1; + } + } + serialized.id = this.annotationElementId; + if (context === null) { + return serialized; + } + context.stamps ||= new Map(); + const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null; + if (!context.stamps.has(this.#bitmapId)) { + context.stamps.set(this.#bitmapId, { + area, + serialized + }); + serialized.bitmap = this.#serializeBitmap(false); + } else if (this.#isSvg) { + const prevData = context.stamps.get(this.#bitmapId); + if (area > prevData.area) { + prevData.area = area; + prevData.serialized.bitmap.close(); + prevData.serialized.bitmap = this.#serializeBitmap(false); + } + } + return serialized; + } + #hasElementChanged(serialized) { + const { + rect, + pageIndex, + accessibilityData: { + altText + } + } = this._initialData; + const isSameRect = serialized.rect.every((x, i) => Math.abs(x - rect[i]) < 1); + const isSamePageIndex = serialized.pageIndex === pageIndex; + const isSameAltText = (serialized.accessibilityData?.alt || "") === altText; + return { + isSame: isSameRect && isSamePageIndex && isSameAltText, + isSameAltText + }; + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getRect(0, 0) + }); + return null; + } +} + +;// ./src/display/editor/annotation_editor_layer.js + + + + + + + +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, + structTreeLayer, + 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._structTree = structTreeLayer; + 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); + } + async 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 = await 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); + if (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.getAttribute("role") === "img" || 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", { + target: this.#textLayer.div, + x: event.x, + y: event.y + }); + 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); + } + } + async deserialize(data) { + return (await 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; + } +} + +;// ./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); + } + getSVGRoot(id) { + return this.#mapping.get(id); + } + 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(); + } +} + +;// ./src/pdf.js + + + + + + + + + + + + +const pdfjsVersion = "4.7.76"; +const pdfjsBuild = "8b73b828b"; + +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__OutputScale = __webpack_exports__.OutputScale; +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__OutputScale as OutputScale, __webpack_exports__PDFDataRangeTransport as PDFDataRangeTransport, __webpack_exports__PDFDateString as PDFDateString, __webpack_exports__PDFWorker as PDFWorker, __webpack_exports__PasswordResponses as PasswordResponses, __webpack_exports__PermissionFlag as PermissionFlag, __webpack_exports__PixelsPerInch as PixelsPerInch, __webpack_exports__RenderingCancelledException as RenderingCancelledException, __webpack_exports__TextLayer as TextLayer, __webpack_exports__UnexpectedResponseException as UnexpectedResponseException, __webpack_exports__Util as Util, __webpack_exports__VerbosityLevel as VerbosityLevel, __webpack_exports__XfaLayer as XfaLayer, __webpack_exports__build as build, __webpack_exports__createValidAbsoluteUrl as createValidAbsoluteUrl, __webpack_exports__fetchData as fetchData, __webpack_exports__getDocument as getDocument, __webpack_exports__getFilenameFromUrl as getFilenameFromUrl, __webpack_exports__getPdfFilenameFromUrl as getPdfFilenameFromUrl, __webpack_exports__getXfaPageViewport as getXfaPageViewport, __webpack_exports__isDataScheme as isDataScheme, __webpack_exports__isPdfFile as isPdfFile, __webpack_exports__noContextMenu as noContextMenu, __webpack_exports__normalizeUnicode as normalizeUnicode, __webpack_exports__setLayerDimensions as setLayerDimensions, __webpack_exports__shadow as shadow, __webpack_exports__version as version }; + +//# sourceMappingURL=pdf.mjs.map \ No newline at end of file diff --git a/packages/foliate-js/vendor/pdfjs/pdf.mjs.map b/packages/foliate-js/vendor/pdfjs/pdf.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..cfbd3a2ebad4a84e4aa1b5556606e4c79b3c0845 --- /dev/null +++ b/packages/foliate-js/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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zC20D,IAAI,CAACpvE,MAAM,CAAC,CAAC;IACf;IACA,IAAI,CAAC,CAACshG,OAAO,CAACz/F,KAAK,CAAC,CAAC;EACvB;AACF;;;AC3M0B;AAOA;AAeU;AACgD;AACd;AACN;AACD;AACX;AACc;AACV;AACJ;AACF;AAGlD,MAAM2gG,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 isWindows: navigator.platform.includes(\"Win\"),\n isFirefox:\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (typeof navigator?.userAgent === \"string\" &&\n navigator.userAgent.includes(\"Firefox\")),\n });\n }\n return shadow(this, \"platform\", {\n isMac: false,\n isWindows: false,\n isFirefox: false,\n });\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\n ? `round(down, ${w}, var(--scale-round-x, 1px))`\n : `calc(${w})`,\n heightStr = useRound\n ? `round(down, ${h}, var(--scale-round-y, 1px))`\n : `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\n/**\n * Scale factors for the canvas, necessary with HiDPI displays.\n */\nclass OutputScale {\n constructor() {\n const pixelRatio = window.devicePixelRatio || 1;\n\n /**\n * @type {number} Horizontal scale.\n */\n this.sx = pixelRatio;\n\n /**\n * @type {number} Vertical scale.\n */\n this.sy = pixelRatio;\n }\n\n /**\n * @type {boolean} Returns `true` when scaling is required, `false` otherwise.\n */\n get scaled() {\n return this.sx !== 1 || this.sy !== 1;\n }\n\n get symmetric() {\n return this.sx === this.sy;\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 OutputScale,\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.classList.add(\"editToolbar\", \"hidden\");\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 get div() {\n return this.#toolbar;\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 if (rawData instanceof File) {\n image = data.file = rawData;\n } else if (rawData instanceof Blob) {\n image = 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 getFromBlob(id, blobPromise) {\n const blob = await blobPromise;\n return this.#get(id, blob);\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 if (data.blobPromise) {\n const { blobPromise } = data;\n delete data.blobPromise;\n return this.getFromBlob(data.id, blobPromise);\n }\n return this.getFromUrl(data.url);\n }\n\n getFromCanvas(id, canvas) {\n this.#cache ||= new Map();\n let data = this.#cache.get(id);\n if (data?.bitmap) {\n data.refCounter += 1;\n return data;\n }\n const offscreen = new OffscreenCanvas(canvas.width, canvas.height);\n const ctx = offscreen.getContext(\"2d\");\n ctx.drawImage(canvas, 0, 0);\n data = {\n bitmap: offscreen.transferToImageBitmap(),\n id: `image_${this.#baseId}_${this.#id++}`,\n refCounter: 1,\n isSvg: false,\n };\n this.#cache.set(id, data);\n this.#cache.set(data.id, data);\n return data;\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 const { bitmap } = data;\n if (!data.url && !data.file) {\n // The image has no way to be restored (ctrl+z) so we must fix that.\n const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);\n const ctx = canvas.getContext(\"bitmaprenderer\");\n ctx.transferFromImageBitmap(bitmap);\n data.blobPromise = canvas.convertToBlob();\n }\n\n bitmap.close?.();\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 #updateModeCapability = 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.#updateModeCapability?.resolve();\n this.#updateModeCapability = null;\n\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 async 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 = await 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 async updateMode(mode, editId = null, isFromKeyboard = false) {\n if (this.#mode === mode) {\n return;\n }\n\n if (this.#updateModeCapability) {\n await this.#updateModeCapability.promise;\n if (!this.#updateModeCapability) {\n // This ui manager has been destroyed.\n return;\n }\n }\n\n this.#updateModeCapability = Promise.withResolvers();\n\n this.#mode = mode;\n if (mode === AnnotationEditorType.NONE) {\n this.setEditingState(false);\n this.#disableAll();\n\n this.#updateModeCapability.resolve();\n return;\n }\n this.setEditingState(true);\n await this.#enableAll();\n this.unselectAll();\n for (const layer of this.#allLayers.values()) {\n layer.updateMode(mode);\n }\n if (!editId) {\n if (isFromKeyboard) {\n this.addNewEditorFromKeyboard();\n }\n\n this.#updateModeCapability.resolve();\n return;\n }\n\n for (const editor of this.#allEditors.values()) {\n if (editor.annotationElementId === editId) {\n this.setSelected(editor);\n editor.enterInEditMode();\n } else {\n editor.unselect();\n }\n }\n\n this.#updateModeCapability.resolve();\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 async #enableAll() {\n if (!this.#isEnabled) {\n this.#isEnabled = true;\n const promises = [];\n for (const layer of this.#allLayers.values()) {\n promises.push(layer.enable());\n }\n await Promise.all(promises);\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 #l10nNewButton = null;\n\n static _l10nPromise = null;\n\n constructor(editor) {\n this.#editor = editor;\n this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;\n\n AltText.#l10nNewButton ||= Object.freeze({\n added: \"pdfjs-editor-new-alt-text-added-button-label\",\n missing: \"pdfjs-editor-new-alt-text-missing-button-label\",\n review: \"pdfjs-editor-new-alt-text-to-review-button-label\",\n });\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(AltText.#l10nNewButton.missing);\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 button.classList.toggle(\"done\", !!this.#altText);\n AltText._l10nPromise\n .get(AltText.#l10nNewButton[this.#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 tooltip.id = `alt-text-tooltip-${this.#editor.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 _initialData = 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 return [pageWidth * parentScale, pageHeight * parentScale];\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 addContainer(container) {\n const editToolbarDiv = this._editToolbar?.div;\n if (editToolbarDiv) {\n editToolbarDiv.before(container);\n } else {\n this.div.append(container);\n }\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 when it has been deleted.\n * @returns {Object}\n */\n serializeDeleted() {\n return {\n id: this.annotationElementId,\n deleted: true,\n pageIndex: this.pageIndex,\n popupRef: this._initialData?.popupRef || \"\",\n };\n }\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 {Promise}\n */\n static async 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\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|null}\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 this.serializeDeleted();\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+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD\" +\n \"6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM\" +\n \"AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D\" +\n \"IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA\" +\n \"AAEAAQAAAAEAA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estFont\", 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 );\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 );\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 {\n bbox,\n operatorList,\n paintType,\n tilingType,\n color,\n canvasGraphicsFactory,\n } = this;\n let { xstep, ystep } = this;\n xstep = Math.abs(xstep);\n ystep = Math.abs(ystep);\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\n const x0 = bbox[0],\n y0 = bbox[1],\n x1 = bbox[2],\n y1 = bbox[3];\n const width = x1 - x0;\n const height = y1 - y0;\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 combinedScaleX = matrixScale[0] * curMatrixScale[0];\n const combinedScaleY = matrixScale[1] * curMatrixScale[1];\n\n let canvasWidth = width,\n canvasHeight = height,\n redrawHorizontally = false,\n redrawVertically = false;\n\n const xScaledStep = Math.ceil(xstep * combinedScaleX);\n const yScaledStep = Math.ceil(ystep * combinedScaleY);\n const xScaledWidth = Math.ceil(width * combinedScaleX);\n const yScaledHeight = Math.ceil(height * combinedScaleY);\n\n if (xScaledStep >= xScaledWidth) {\n canvasWidth = xstep;\n } else {\n redrawHorizontally = true;\n }\n if (yScaledStep >= yScaledHeight) {\n canvasHeight = ystep;\n } else {\n redrawVertically = true;\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 canvasWidth,\n this.ctx.canvas.width,\n combinedScaleX\n );\n const dimy = this.getSizeAndScale(\n canvasHeight,\n this.ctx.canvas.height,\n combinedScaleY\n );\n\n const tmpCanvas = owner.cachedCanvases.getCanvas(\n \"pattern\",\n dimx.size,\n dimy.size\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 tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);\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, x0, y0, x1, y1);\n\n graphics.baseTransform = getCurrentTransform(graphics.ctx);\n\n graphics.executeOperatorList(operatorList);\n\n graphics.endDrawing();\n\n tmpCtx.restore();\n\n if (redrawHorizontally || redrawVertically) {\n // The tile is overlapping itself, so we create a new tile with\n // dimensions xstep * ystep.\n // Then we draw the overlapping parts of the original tile on the new\n // tile.\n // Just as a side note, the code here works correctly even if we don't\n // have to redraw the tile horizontally or vertically. In that case, the\n // original tile is drawn on the new tile only once, but it's useless.\n const image = tmpCanvas.canvas;\n if (redrawHorizontally) {\n canvasWidth = xstep;\n }\n if (redrawVertically) {\n canvasHeight = ystep;\n }\n\n const dimx2 = this.getSizeAndScale(\n canvasWidth,\n this.ctx.canvas.width,\n combinedScaleX\n );\n const dimy2 = this.getSizeAndScale(\n canvasHeight,\n this.ctx.canvas.height,\n combinedScaleY\n );\n\n const xSize = dimx2.size;\n const ySize = dimy2.size;\n const tmpCanvas2 = owner.cachedCanvases.getCanvas(\n \"pattern-workaround\",\n xSize,\n ySize\n );\n const tmpCtx2 = tmpCanvas2.context;\n const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;\n const jj = redrawVertically ? Math.floor(height / ystep) : 0;\n\n // Draw the overlapping parts of the original tile on the new tile.\n for (let i = 0; i <= ii; i++) {\n for (let j = 0; j <= jj; j++) {\n tmpCtx2.drawImage(\n image,\n xSize * i,\n ySize * j,\n xSize,\n ySize,\n 0,\n 0,\n xSize,\n ySize\n );\n }\n }\n return {\n canvas: tmpCanvas2.canvas,\n scaleX: dimx2.scale,\n scaleY: dimy2.scale,\n offsetX: x0,\n offsetY: y0,\n };\n }\n\n return {\n canvas: tmpCanvas.canvas,\n scaleX: dimx.scale,\n scaleY: dimy.scale,\n offsetX: x0,\n offsetY: y0,\n };\n }\n\n getSizeAndScale(step, realOutputSize, scale) {\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 // Consume a potential path before clipping.\n this.endPath();\n\n this.ctx.rect(rect[0], rect[1], width, height);\n this.ctx.clip();\n this.ctx.beginPath();\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 createHeaders(isHttp, httpHeaders) {\n const headers = new Headers();\n\n if (!isHttp || !httpHeaders || typeof httpHeaders !== \"object\") {\n return headers;\n }\n for (const key in httpHeaders) {\n const val = httpHeaders[key];\n if (val !== undefined) {\n headers.append(key, val);\n }\n }\n return headers;\n}\n\nfunction validateRangeRequestCapabilities({\n responseHeaders,\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(responseHeaders.get(\"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 (responseHeaders.get(\"Accept-Ranges\") !== \"bytes\") {\n return returnValues;\n }\n\n const contentEncoding = responseHeaders.get(\"Content-Encoding\") || \"identity\";\n if (contentEncoding !== \"identity\") {\n return returnValues;\n }\n\n returnValues.allowRangeRequests = true;\n return returnValues;\n}\n\nfunction extractFilenameFromHeader(responseHeaders) {\n const contentDisposition = responseHeaders.get(\"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 createHeaders,\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 createHeaders,\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 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.headers = createHeaders(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 // Always create a copy of the headers.\n const headers = new Headers(stream.headers);\n\n const url = source.url;\n fetch(\n url,\n createFetchOptions(headers, this._withCredentials, this._abortController)\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 responseHeaders = response.headers;\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n responseHeaders,\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(responseHeaders);\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 // Always create a copy of the headers.\n const headers = new Headers(stream.headers);\n headers.append(\"Range\", `bytes=${begin}-${end - 1}`);\n\n const url = source.url;\n fetch(\n url,\n createFetchOptions(headers, this._withCredentials, this._abortController)\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 createHeaders,\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, httpHeaders, withCredentials }) {\n this.url = url;\n this.isHttp = /^https?:/i.test(url);\n this.headers = createHeaders(this.isHttp, httpHeaders);\n this.withCredentials = 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 [key, val] of this.headers) {\n xhr.setRequestHeader(key, val);\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);\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._headersCapability = 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 responseHeaders = new Headers(\n fullRequestXhr\n .getAllResponseHeaders()\n .trim()\n .split(/[\\r\\n]+/)\n .map(x => {\n const [key, ...val] = x.split(\": \");\n return [key, val.join(\": \")];\n })\n );\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n responseHeaders,\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(responseHeaders);\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._headersCapability.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._headersCapability.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._headersCapability.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._headersCapability.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 createHeaders,\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.headers = createHeaders(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 // Node.js requires the `headers` to be a regular Object.\n const headers = Object.fromEntries(stream.headers);\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 const responseHeaders = new Headers(this._readableStream.headers);\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n responseHeaders,\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(responseHeaders);\n };\n\n this._request = createRequest(this._url, headers, handleResponse);\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 // Node.js requires the `headers` to be a regular Object.\n const headers = Object.fromEntries(stream.headers);\n headers.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, headers, 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 {\n AbortException,\n FeatureTest,\n shadow,\n Util,\n warn,\n} 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 #canvasCtxFonts = new WeakMap();\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 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 .finally(() => {\n TextLayer.#pendingTextLayers.delete(this);\n this.#layoutTextParams = null;\n this.#styleCache = null;\n })\n .catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\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 static get fontFamilyMap() {\n const { isWindows, isFirefox } = FeatureTest.platform;\n return shadow(\n this,\n \"fontFamilyMap\",\n new Map([\n [\n \"sans-serif\",\n `${isWindows && isFirefox ? \"Calibri, \" : \"\"}sans-serif`,\n ],\n [\n \"monospace\",\n `${isWindows && isFirefox ? \"Lucida Console, \" : \"\"}monospace`,\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 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 let fontFamily =\n (this.#fontInspectorEnabled && style.fontSubstitution) ||\n style.fontFamily;\n\n // Workaround for bug 1922063.\n fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || 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 } = 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 TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);\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 ctx = this.#canvasContexts.get((lang ||= \"\"));\n if (!ctx) {\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 ctx = canvas.getContext(\"2d\", {\n alpha: false,\n willReadFrequently: true,\n });\n this.#canvasContexts.set(lang, ctx);\n\n // Also, initialize state for the `#ensureCtxFont` method.\n this.#canvasCtxFonts.set(ctx, { size: 0, family: \"\" });\n }\n return ctx;\n }\n\n static #ensureCtxFont(ctx, size, family) {\n const cached = this.#canvasCtxFonts.get(ctx);\n if (size === cached.size && family === cached.family) {\n return; // The font is already set.\n }\n ctx.font = `${size}px ${family}`;\n cached.size = size;\n cached.family = family;\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 ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;\n this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, 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 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\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 deprecated,\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 that will be used when\n * creating canvases. The default value is {DOMCanvasFactory}.\n * @property {Object} [FilterFactory] - The factory that will be used to\n * create SVG filters when rendering some images on the main canvas.\n * The default value is {DOMFilterFactory}.\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 CanvasFactory = src.CanvasFactory || DefaultCanvasFactory;\n const FilterFactory = src.FilterFactory || DefaultFilterFactory;\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\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n if (src.canvasFactory) {\n deprecated(\n \"`canvasFactory`-instance option, please use `CanvasFactory` instead.\"\n );\n }\n if (src.filterFactory) {\n deprecated(\n \"`filterFactory`-instance option, please use `FilterFactory` instead.\"\n );\n }\n }\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: new CanvasFactory({ ownerDocument, enableHWA }),\n filterFactory: new FilterFactory({ docId, ownerDocument }),\n cMapReaderFactory:\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n useWorkerFetch\n ? null\n : new CMapReaderFactory({ baseUrl: cMapUrl, isCompressed: cMapPacked }),\n standardFontDataFactory:\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n useWorkerFetch\n ? null\n : new StandardFontDataFactory({ baseUrl: standardFontDataUrl }),\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: NetworkStream\");\n }\n if (!url) {\n throw new Error(\"getDocument - no `url` parameter provided.\");\n }\n let NetworkStream;\n\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS\n ) {\n const isFetchSupported =\n typeof fetch !== \"undefined\" &&\n typeof Response !== \"undefined\" &&\n \"body\" in Response.prototype;\n\n NetworkStream =\n isFetchSupported && isValidFetchUrl(url)\n ? PDFFetchStream\n : PDFNodeStream;\n } else {\n NetworkStream = isValidFetchUrl(url)\n ? PDFFetchStream\n : PDFNetworkStream;\n }\n\n networkStream = new NetworkStream({\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 canvas factory instance.\n */\n get canvasFactory() {\n return this._transport.canvasFactory;\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 ` + + + + +
+
+ {{ content }} +
+ +
+ + + + diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/_sass/main.scss b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/_sass/main.scss new file mode 100644 index 0000000000000000000000000000000000000000..92edc877a592e877d037b769337f82568913a9d7 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/_sass/main.scss @@ -0,0 +1,200 @@ +// Styles for GoogleTest docs website on GitHub Pages. +// Color variables are defined in +// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables + +$sidebar-width: 260px; + +body { + display: flex; + margin: 0; +} + +.sidebar { + background: $black; + color: $text-white; + flex-shrink: 0; + height: 100vh; + overflow: auto; + position: sticky; + top: 0; + width: $sidebar-width; +} + +.sidebar h1 { + font-size: 1.5em; +} + +.sidebar h2 { + color: $gray-light; + font-size: 0.8em; + font-weight: normal; + margin-bottom: 0.8em; + padding-left: 2.5em; + text-transform: uppercase; +} + +.sidebar .header { + background: $black; + padding: 2em; + position: sticky; + top: 0; + width: 100%; +} + +.sidebar .header a { + color: $text-white; + text-decoration: none; +} + +.sidebar .nav-toggle { + display: none; +} + +.sidebar .expander { + cursor: pointer; + display: none; + height: 3em; + position: absolute; + right: 1em; + top: 1.5em; + width: 3em; +} + +.sidebar .expander .arrow { + border: solid $white; + border-width: 0 3px 3px 0; + display: block; + height: 0.7em; + margin: 1em auto; + transform: rotate(45deg); + transition: transform 0.5s; + width: 0.7em; +} + +.sidebar nav { + width: 100%; +} + +.sidebar nav ul { + list-style-type: none; + margin-bottom: 1em; + padding: 0; + + &:last-child { + margin-bottom: 2em; + } + + a { + text-decoration: none; + } + + li { + color: $text-white; + padding-left: 2em; + text-decoration: none; + } + + li.active { + background: $border-gray-darker; + font-weight: bold; + } + + li:hover { + background: $border-gray-darker; + } +} + +.main { + background-color: $bg-gray; + width: calc(100% - #{$sidebar-width}); +} + +.main .main-inner { + background-color: $white; + padding: 2em; +} + +.main .footer { + margin: 0; + padding: 2em; +} + +.main table th { + text-align: left; +} + +.main .callout { + border-left: 0.25em solid $white; + padding: 1em; + + a { + text-decoration: underline; + } + + &.important { + background-color: $bg-yellow-light; + border-color: $bg-yellow; + color: $black; + } + + &.note { + background-color: $bg-blue-light; + border-color: $text-blue; + color: $text-blue; + } + + &.tip { + background-color: $green-000; + border-color: $green-700; + color: $green-700; + } + + &.warning { + background-color: $red-000; + border-color: $text-red; + color: $text-red; + } +} + +.main .good pre { + background-color: $bg-green-light; +} + +.main .bad pre { + background-color: $red-000; +} + +@media all and (max-width: 768px) { + body { + flex-direction: column; + } + + .sidebar { + height: auto; + position: relative; + width: 100%; + } + + .sidebar .expander { + display: block; + } + + .sidebar nav { + height: 0; + overflow: hidden; + } + + .sidebar .nav-toggle:checked { + & ~ nav { + height: auto; + } + + & + .expander .arrow { + transform: rotate(-135deg); + } + } + + .main { + width: 100%; + } +} diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/advanced.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/advanced.md new file mode 100644 index 0000000000000000000000000000000000000000..240588a83b4eb72c0c2187191950cb14631cccb1 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/advanced.md @@ -0,0 +1,2446 @@ +# Advanced GoogleTest Topics + +## Introduction + +Now that you have read the [GoogleTest Primer](primer.md) and learned how to +write tests using GoogleTest, it's time to learn some new tricks. This document +will show you more assertions as well as how to construct complex failure +messages, propagate fatal failures, reuse and speed up your test fixtures, and +use various flags with your tests. + +## More Assertions + +This section covers some less frequently used, but still significant, +assertions. + +### Explicit Success and Failure + +See [Explicit Success and Failure](reference/assertions.md#success-failure) in +the Assertions Reference. + +### Exception Assertions + +See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions +Reference. + +### Predicate Assertions for Better Error Messages + +Even though GoogleTest has a rich set of assertions, they can never be complete, +as it's impossible (nor a good idea) to anticipate all scenarios a user might +run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a +complex expression, for lack of a better macro. This has the problem of not +showing you the values of the parts of the expression, making it hard to +understand what went wrong. As a workaround, some users choose to construct the +failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this +is awkward especially when the expression has side-effects or is expensive to +evaluate. + +GoogleTest gives you three different options to solve this problem: + +#### Using an Existing Boolean Function + +If you already have a function or functor that returns `bool` (or a type that +can be implicitly converted to `bool`), you can use it in a *predicate +assertion* to get the function arguments printed for free. See +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions +Reference for details. + +#### Using a Function That Returns an AssertionResult + +While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not +satisfactory: you have to use different macros for different arities, and it +feels more like Lisp than C++. The `::testing::AssertionResult` class solves +this problem. + +An `AssertionResult` object represents the result of an assertion (whether it's +a success or a failure, and an associated message). You can create an +`AssertionResult` using one of these factory functions: + +```c++ +namespace testing { + +// Returns an AssertionResult object to indicate that an assertion has +// succeeded. +AssertionResult AssertionSuccess(); + +// Returns an AssertionResult object to indicate that an assertion has +// failed. +AssertionResult AssertionFailure(); + +} +``` + +You can then use the `<<` operator to stream messages to the `AssertionResult` +object. + +To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), +write a predicate function that returns `AssertionResult` instead of `bool`. For +example, if you define `IsEven()` as: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess(); + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +instead of: + +```c++ +bool IsEven(int n) { + return (n % 2) == 0; +} +``` + +the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: + +```none +Value of: IsEven(Fib(4)) + Actual: false (3 is odd) +Expected: true +``` + +instead of a more opaque + +```none +Value of: IsEven(Fib(4)) + Actual: false +Expected: true +``` + +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well +(one third of Boolean assertions in the Google code base are negative ones), and +are fine with making the predicate slower in the success case, you can supply a +success message: + +```c++ +testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return testing::AssertionSuccess() << n << " is even"; + else + return testing::AssertionFailure() << n << " is odd"; +} +``` + +Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print + +```none + Value of: IsEven(Fib(6)) + Actual: true (8 is even) + Expected: false +``` + +#### Using a Predicate-Formatter + +If you find the default message generated by +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and +[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some +arguments to your predicate do not support streaming to `ostream`, you can +instead use *predicate-formatter assertions* to *fully* customize how the +message is formatted. See +[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the +Assertions Reference for details. + +### Floating-Point Comparison + +See [Floating-Point Comparison](reference/assertions.md#floating-point) in the +Assertions Reference. + +#### Floating-Point Predicate-Format Functions + +Some floating-point operations are useful, but not that often used. In order to +avoid an explosion of new macros, we provide them as predicate-format functions +that can be used in the predicate assertion macro +[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for +example: + +```c++ +using ::testing::FloatLE; +using ::testing::DoubleLE; +... +EXPECT_PRED_FORMAT2(FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(DoubleLE, val1, val2); +``` + +The above code verifies that `val1` is less than, or approximately equal to, +`val2`. + +### Asserting Using gMock Matchers + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### More String Assertions + +(Please read the [previous](#asserting-using-gmock-matchers) section first if +you haven't.) + +You can use the gMock [string matchers](reference/matchers.md#string-matchers) +with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string +comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For +example, + +```c++ +using ::testing::HasSubstr; +using ::testing::MatchesRegex; +... + ASSERT_THAT(foo_string, HasSubstr("needle")); + EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); +``` + +### Windows HRESULT assertions + +See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the +Assertions Reference. + +### Type Assertions + +You can call the function + +```c++ +::testing::StaticAssertTypeEq(); +``` + +to assert that types `T1` and `T2` are the same. The function does nothing if +the assertion is satisfied. If the types are different, the function call will +fail to compile, the compiler error message will say that `T1 and T2 are not the +same type` and most likely (depending on the compiler) show you the actual +values of `T1` and `T2`. This is mainly useful inside template code. + +**Caveat**: When used inside a member function of a class template or a function +template, `StaticAssertTypeEq()` is effective only if the function is +instantiated. For example, given: + +```c++ +template class Foo { + public: + void Bar() { testing::StaticAssertTypeEq(); } +}; +``` + +the code: + +```c++ +void Test1() { Foo foo; } +``` + +will not generate a compiler error, as `Foo::Bar()` is never actually +instantiated. Instead, you need: + +```c++ +void Test2() { Foo foo; foo.Bar(); } +``` + +to cause a compiler error. + +### Assertion Placement + +You can use assertions in any C++ function. In particular, it doesn't have to be +a method of the test fixture class. The one constraint is that assertions that +generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in +void-returning functions. This is a consequence of Google's not using +exceptions. By placing it in a non-void function you'll get a confusing compile +error like `"error: void value not ignored as it ought to be"` or `"cannot +initialize return object of type 'bool' with an rvalue of type 'void'"` or +`"error: no viable conversion from 'void' to 'string'"`. + +If you need to use fatal assertions in a function that returns non-void, one +option is to make the function return the value in an out parameter instead. For +example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You +need to make sure that `*result` contains some sensible value even when the +function returns prematurely. As the function now returns `void`, you can use +any assertion inside of it. + +If changing the function's type is not an option, you should just use assertions +that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. + +{: .callout .note} +NOTE: Constructors and destructors are not considered void-returning functions, +according to the C++ language specification, and so you may not use fatal +assertions in them; you'll get a compilation error if you try. Instead, either +call `abort` and crash the entire test executable, or put the fatal assertion in +a `SetUp`/`TearDown` function; see +[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) + +{: .callout .warning} +WARNING: A fatal assertion in a helper function (private void-returning method) +called from a constructor or destructor does not terminate the current test, as +your intuition might suggest: it merely returns from the constructor or +destructor early, possibly leaving your object in a partially-constructed or +partially-destructed state! You almost certainly want to `abort` or use +`SetUp`/`TearDown` instead. + +## Skipping test execution + +Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test +execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need +to check for preconditions of the system under test during runtime and skip +tests in a meaningful way. + +`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods +of classes derived from either `::testing::Environment` or `::testing::Test`. +For example: + +```c++ +TEST(SkipTest, DoesSkip) { + GTEST_SKIP() << "Skipping single test"; + EXPECT_EQ(0, 1); // Won't fail; it won't be executed +} + +class SkipFixture : public ::testing::Test { + protected: + void SetUp() override { + GTEST_SKIP() << "Skipping all tests for this fixture"; + } +}; + +// Tests for SkipFixture won't be executed. +TEST_F(SkipFixture, SkipsOneTest) { + EXPECT_EQ(5, 7); // Won't fail +} +``` + +As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. + +## Teaching GoogleTest How to Print Your Values + +When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument +values to help you debug. It does this using a user-extensible value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. + +As mentioned earlier, the printer is *extensible*. That means you can teach it +to do a better job at printing your particular type than to dump the bytes. To +do that, define an `AbslStringify()` overload as a `friend` function template +for your type: + +```cpp +namespace foo { + +class Point { // We want GoogleTest to be able to print instances of this. + ... + // Provide a friend overload. + template + friend void AbslStringify(Sink& sink, const Point& point) { + absl::Format(&sink, "(%d, %d)", point.x, point.y); + } + + int x; + int y; +}; + +// If you can't declare the function in the class it's important that the +// AbslStringify overload is defined in the SAME namespace that defines Point. +// C++'s look-up rules rely on that. +enum class EnumWithStringify { kMany = 0, kChoices = 1 }; + +template +void AbslStringify(Sink& sink, EnumWithStringify e) { + absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices"); +} + +} // namespace foo +``` + +{: .callout .note} +Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its +string. For more information about supported operations on `AbslStringify()`'s +sink, see go/abslstringify. + +`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier +within its own format strings to perform type deduction. `Point` above could be +formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`. + +Sometimes, `AbslStringify()` might not be an option: your team may wish to print +types with extra debugging information for testing purposes only. If so, you can +instead define a `PrintTo()` function like this: + +```c++ +#include + +namespace foo { + +class Point { + ... + friend void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; + } + + int x; + int y; +}; + +// If you can't declare the function in the class it's important that PrintTo() +// is defined in the SAME namespace that defines Point. C++'s look-up rules +// rely on that. +void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; +} + +} // namespace foo +``` + +If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be +used by GoogleTest. This allows you to customize how the value appears in +GoogleTest's output without affecting code that relies on the behavior of +`AbslStringify()`. + +If you have an existing `<<` operator and would like to define an +`AbslStringify()`, the latter will be used for GoogleTest printing. + +If you want to print a value `x` using GoogleTest's value printer yourself, just +call `::testing::PrintToString(x)`, which returns an `std::string`: + +```c++ +vector > point_ints = GetPointIntVector(); + +EXPECT_TRUE(IsCorrectPointIntVector(point_ints)) + << "point_ints = " << testing::PrintToString(point_ints); +``` + +For more details regarding `AbslStringify()` and its integration with other +libraries, see go/abslstringify. + +## Death Tests + +In many applications, there are assertions that can cause application failure if +a condition is not met. These consistency checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test that +such assertion statements work as expected. + +Since these precondition checks cause the processes to die, we call such tests +_death tests_. More generally, any test that checks that a program terminates +(except by throwing an exception) in an expected fashion is also a death test. + +Note that if a piece of code throws an exception, we don't consider it "death" +for the purpose of death tests, as the caller of the code could catch the +exception and avoid the crash. If you want to verify exceptions thrown by your +code, see [Exception Assertions](#ExceptionAssertions). + +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see +["Catching" Failures](#catching-failures). + +### How to Write a Death Test + +GoogleTest provides assertion macros to support death tests. See +[Death Assertions](reference/assertions.md#death) in the Assertions Reference +for details. + +To write a death test, simply use one of the macros inside your test function. +For example, + +```c++ +TEST(MyDeathTest, Foo) { + // This death test uses a compound statement. + ASSERT_DEATH({ + int n = 5; + Foo(&n); + }, "Error on line .* of Foo()"); +} + +TEST(MyDeathTest, NormalExit) { + EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +} + +TEST(MyDeathTest, KillProcess) { + EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), + "Sending myself unblockable signal"); +} +``` + +verifies that: + +* calling `Foo(5)` causes the process to die with the given error message, +* calling `NormalExit()` causes the process to print `"Success"` to stderr and + exit with exit code 0, and +* calling `KillProcess()` kills the process with signal `SIGKILL`. + +The test function body may contain other assertions and statements as well, if +necessary. + +Note that a death test only cares about three things: + +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `matcher`? + +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as GoogleTest assertions don't abort +the process. + +### Death Test Naming + +{: .callout .important} +IMPORTANT: We strongly recommend you to follow the convention of naming your +**test suite** (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The +[Death Tests And Threads](#death-tests-and-threads) section below explains why. + +If a test fixture class is shared by normal tests and death tests, you can use +`using` or `typedef` to introduce an alias for the fixture class and avoid +duplicating its code: + +```c++ +class FooTest : public testing::Test { ... }; + +using FooDeathTest = FooTest; + +TEST_F(FooTest, DoesThis) { + // normal test +} + +TEST_F(FooDeathTest, DoesThat) { + // death test +} +``` + +### Regular Expression Syntax + +When built with Bazel and using Abseil, GoogleTest uses the +[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX +systems (Linux, Cygwin, Mac), GoogleTest uses the +[POSIX extended regular expression](https://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +syntax. To learn about POSIX syntax, you may want to read this +[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). + +On Windows, GoogleTest uses its own simple regular expression implementation. It +lacks many features. For example, we don't support union (`"x|y"`), grouping +(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among +others. Below is what we do support (`A` denotes a literal character, period +(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular +expressions.): + +Expression | Meaning +---------- | -------------------------------------------------------------- +`c` | matches any literal character `c` +`\\d` | matches any decimal digit +`\\D` | matches any character that's not a decimal digit +`\\f` | matches `\f` +`\\n` | matches `\n` +`\\r` | matches `\r` +`\\s` | matches any ASCII whitespace, including `\n` +`\\S` | matches any character that's not a whitespace +`\\t` | matches `\t` +`\\v` | matches `\v` +`\\w` | matches any letter, `_`, or decimal digit +`\\W` | matches any character that `\\w` doesn't match +`\\c` | matches any literal character `c`, which must be a punctuation +`.` | matches any single character except `\n` +`A?` | matches 0 or 1 occurrences of `A` +`A*` | matches 0 or many occurrences of `A` +`A+` | matches 1 or many occurrences of `A` +`^` | matches the beginning of a string (not that of each line) +`$` | matches the end of a string (not that of each line) +`xy` | matches `x` followed by `y` + +To help you determine which capability is available on your system, GoogleTest +defines macros to govern which regular expression it is using. The macros are: +`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death +tests to work in all cases, you can either `#if` on these macros or use the more +limited syntax only. + +### How It Works + +See [Death Assertions](reference/assertions.md#death) in the Assertions +Reference. + +### Death Tests And Threads + +The reason for the two death test styles has to do with thread safety. Due to +well-known problems with forking in the presence of threads, death tests should +be run in a single-threaded context. Sometimes, however, it isn't feasible to +arrange that kind of environment. For example, statically-initialized modules +may start threads before main is ever reached. Once threads have been created, +it may be difficult or impossible to clean them up. + +GoogleTest has three features intended to raise awareness of threading issues. + +1. A warning is emitted if multiple threads are running when a death test is + encountered. +2. Test suites with a name ending in "DeathTest" are run before all other + tests. +3. It uses `clone()` instead of `fork()` to spawn the child process on Linux + (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely + to cause the child to hang when the parent process has multiple threads. + +It's perfectly fine to create threads inside a death test statement; they are +executed in a separate process and cannot affect the parent. + +### Death Test Styles + +The "threadsafe" death test style was introduced in order to help mitigate the +risks of testing in a possibly multithreaded environment. It trades increased +test execution time (potentially dramatically so) for improved thread safety. + +The automated testing framework does not set the style flag. You can choose a +particular style of death tests by setting the flag programmatically: + +```c++ +GTEST_FLAG_SET(death_test_style, "threadsafe"); +``` + +You can do this in `main()` to set the style for all death tests in the binary, +or in individual tests. Recall that flags are saved before running each test and +restored afterwards, so you need not do that yourself. For example: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + GTEST_FLAG_SET(death_test_style, "fast"); + return RUN_ALL_TESTS(); +} + +TEST(MyDeathTest, TestOne) { + GTEST_FLAG_SET(death_test_style, "threadsafe"); + // This test is run in the "threadsafe" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +TEST(MyDeathTest, TestTwo) { + // This test is run in the "fast" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} +``` + +### Caveats + +The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If +it leaves the current function via a `return` statement or by throwing an +exception, the death test is considered to have failed. Some GoogleTest macros +may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid +them in `statement`. + +Since `statement` runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will *not* be observable +in the parent process. In particular, if you release memory in a death test, +your program will fail the heap check as the parent process will never see the +memory reclaimed. To solve this problem, you can + +1. try not to free memory in a death test; +2. free the memory again in the parent process; or +3. do not use the heap checker in your program. + +Due to an implementation detail, you cannot place multiple death test assertions +on the same line; otherwise, compilation will fail with an unobvious error +message. + +Despite the improved thread safety afforded by the "threadsafe" style of death +test, thread problems such as deadlock are still possible in the presence of +handlers registered with `pthread_atfork(3)`. + +## Using Assertions in Sub-routines + +{: .callout .note} +Note: If you want to put a series of test assertions in a subroutine to check +for a complex condition, consider using +[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you +provide a more readable error message in case of failure and avoid all of the +issues described below. + +### Adding Traces to Assertions + +If a test sub-routine is called from several places, when an assertion inside it +fails, it can be hard to tell which invocation of the sub-routine the failure is +from. You can alleviate this problem using extra logging or custom failure +messages, but that usually clutters up your tests. A better solution is to use +the `SCOPED_TRACE` macro or the `ScopedTrace` utility: + +```c++ +SCOPED_TRACE(message); +``` + +```c++ +ScopedTrace trace("file_path", line_number, message); +``` + +where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` +macro will cause the current file name, line number, and the given message to be +added in every failure message. `ScopedTrace` accepts explicit file name and +line number in arguments, which is useful for writing test helpers. The effect +will be undone when the control leaves the current lexical scope. + +For example, + +```c++ +10: void Sub1(int n) { +11: EXPECT_EQ(Bar(n), 1); +12: EXPECT_EQ(Bar(n + 1), 2); +13: } +14: +15: TEST(FooTest, Bar) { +16: { +17: SCOPED_TRACE("A"); // This trace point will be included in +18: // every failure in this scope. +19: Sub1(1); +20: } +21: // Now it won't. +22: Sub1(9); +23: } +``` + +could result in messages like these: + +```none +path/to/foo_test.cc:11: Failure +Value of: Bar(n) +Expected: 1 + Actual: 2 +Google Test trace: +path/to/foo_test.cc:17: A + +path/to/foo_test.cc:12: Failure +Value of: Bar(n + 1) +Expected: 2 + Actual: 3 +``` + +Without the trace, it would've been difficult to know which invocation of +`Sub1()` the two failures come from respectively. (You could add an extra +message to each assertion in `Sub1()` to indicate the value of `n`, but that's +tedious.) + +Some tips on using `SCOPED_TRACE`: + +1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the + beginning of a sub-routine, instead of at each call site. +2. When calling sub-routines inside a loop, make the loop iterator part of the + message in `SCOPED_TRACE` such that you can know which iteration the failure + is from. +3. Sometimes the line number of the trace point is enough for identifying the + particular invocation of a sub-routine. In this case, you don't have to + choose a unique message for `SCOPED_TRACE`. You can simply use `""`. +4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer + scope. In this case, all active trace points will be included in the failure + messages, in reverse order they are encountered. +5. The trace dump is clickable in Emacs - hit `return` on a line number and + you'll be taken to that line in the source file! + +### Propagating Fatal Failures + +A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that +when they fail they only abort the _current function_, not the entire test. For +example, the following test will segfault: + +```c++ +void Subroutine() { + // Generates a fatal failure and aborts the current function. + ASSERT_EQ(1, 2); + + // The following won't be executed. + ... +} + +TEST(FooTest, Bar) { + Subroutine(); // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + + // The actual behavior: the function goes on after Subroutine() returns. + int* p = nullptr; + *p = 3; // Segfault! +} +``` + +To alleviate this, GoogleTest provides three different solutions. You could use +either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the +`HasFatalFailure()` function. They are described in the following two +subsections. + +#### Asserting on Subroutines with an exception + +The following code can turn ASSERT-failure into an exception: + +```c++ +class ThrowListener : public testing::EmptyTestEventListener { + void OnTestPartResult(const testing::TestPartResult& result) override { + if (result.type() == testing::TestPartResult::kFatalFailure) { + throw testing::AssertionException(result); + } + } +}; +int main(int argc, char** argv) { + ... + testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); + return RUN_ALL_TESTS(); +} +``` + +This listener should be added after other listeners if you have any, otherwise +they won't see failed `OnTestPartResult`. + +#### Asserting on Subroutines + +As shown above, if your test calls a subroutine that has an `ASSERT_*` failure +in it, the test will continue after the subroutine returns. This may not be what +you want. + +Often people want fatal failures to propagate like exceptions. For that +GoogleTest offers the following macros: + +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------- | ------------------------------------- | -------- +`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. + +Only failures in the thread that executes the assertion are checked to determine +the result of this type of assertions. If `statement` creates new threads, +failures in these threads are ignored. + +Examples: + +```c++ +ASSERT_NO_FATAL_FAILURE(Foo()); + +int i; +EXPECT_NO_FATAL_FAILURE({ + i = Bar(); +}); +``` + +Assertions from multiple threads are currently not supported on Windows. + +#### Checking for Failures in the Current Test + +`HasFatalFailure()` in the `::testing::Test` class returns `true` if an +assertion in the current test has suffered a fatal failure. This allows +functions to catch fatal failures in a sub-routine and return early. + +```c++ +class Test { + public: + ... + static bool HasFatalFailure(); +}; +``` + +The typical usage, which basically simulates the behavior of a thrown exception, +is: + +```c++ +TEST(FooTest, Bar) { + Subroutine(); + // Aborts if Subroutine() had a fatal failure. + if (HasFatalFailure()) return; + + // The following won't be executed. + ... +} +``` + +If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test +fixture, you must add the `::testing::Test::` prefix, as in: + +```c++ +if (testing::Test::HasFatalFailure()) return; +``` + +Similarly, `HasNonfatalFailure()` returns `true` if the current test has at +least one non-fatal failure, and `HasFailure()` returns `true` if the current +test has at least one failure of either kind. + +## Logging Additional Information + +In your test code, you can call `RecordProperty("key", value)` to log additional +information, where `value` can be either a string or an `int`. The *last* value +recorded for a key will be emitted to the +[XML output](#generating-an-xml-report) if you specify one. For example, the +test + +```c++ +TEST_F(WidgetUsageTest, MinAndMaxWidgets) { + RecordProperty("MaximumWidgets", ComputeMaxUsage()); + RecordProperty("MinimumWidgets", ComputeMinUsage()); +} +``` + +will output XML like this: + +```xml + ... + + ... +``` + +{: .callout .note} +> NOTE: +> +> * `RecordProperty()` is a static member of the `Test` class. Therefore it +> needs to be prefixed with `::testing::Test::` if used outside of the +> `TEST` body and the test fixture class. +> * *`key`* must be a valid XML attribute name, and cannot conflict with the +> ones already used by GoogleTest (`name`, `status`, `time`, `classname`, +> `type_param`, and `value_param`). +> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. +> If it's called outside of a test but between a test suite's +> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be +> attributed to the XML element for the test suite. If it's called outside +> of all test suites (e.g. in a test environment), it will be attributed to +> the top-level XML element. + +## Sharing Resources Between Tests in the Same Test Suite + +GoogleTest creates a new test fixture object for each test in order to make +tests independent and easier to debug. However, sometimes tests use resources +that are expensive to set up, making the one-copy-per-test model prohibitively +expensive. + +If the tests don't change the resource, there's no harm in their sharing a +single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest +also supports per-test-suite set-up/tear-down. To use it: + +1. In your test fixture class (say `FooTest` ), declare as `static` some member + variables to hold the shared resources. +2. Outside your test fixture class (typically just below it), define those + member variables, optionally giving them initial values. +3. In the same test fixture class, define a public member function `static void + SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a + small `u`!) to set up the shared resources and a `static void + TearDownTestSuite()` function to tear them down. + +That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the +*first test* in the `FooTest` test suite (i.e. before creating the first +`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* +in it (i.e. after deleting the last `FooTest` object). In between, the tests can +use the shared resources. + +Remember that the test order is undefined, so your code can't depend on a test +preceding or following another. Also, the tests must either not modify the state +of any shared resource, or, if they do modify the state, they must restore the +state to its original value before passing control to the next test. + +Note that `SetUpTestSuite()` may be called multiple times for a test fixture +class that has derived classes, so you should not expect code in the function +body to be run only once. Also, derived classes still have access to shared +resources defined as static members, so careful consideration is needed when +managing shared resources to avoid memory leaks if shared resources are not +properly cleaned up in `TearDownTestSuite()`. + +Here's an example of per-test-suite set-up and tear-down: + +```c++ +class FooTest : public testing::Test { + protected: + // Per-test-suite set-up. + // Called before the first test in this test suite. + // Can be omitted if not needed. + static void SetUpTestSuite() { + shared_resource_ = new ...; + + // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, + // reallocation should be prevented because `SetUpTestSuite()` may be called + // in subclasses of FooTest and lead to memory leak. + // + // if (shared_resource_ == nullptr) { + // shared_resource_ = new ...; + // } + } + + // Per-test-suite tear-down. + // Called after the last test in this test suite. + // Can be omitted if not needed. + static void TearDownTestSuite() { + delete shared_resource_; + shared_resource_ = nullptr; + } + + // You can define per-test set-up logic as usual. + void SetUp() override { ... } + + // You can define per-test tear-down logic as usual. + void TearDown() override { ... } + + // Some expensive resource shared by all tests. + static T* shared_resource_; +}; + +T* FooTest::shared_resource_ = nullptr; + +TEST_F(FooTest, Test1) { + ... you can refer to shared_resource_ here ... +} + +TEST_F(FooTest, Test2) { + ... you can refer to shared_resource_ here ... +} +``` + +{: .callout .note} +NOTE: Though the above code declares `SetUpTestSuite()` protected, it may +sometimes be necessary to declare it public, such as when using it with +`TEST_P`. + +## Global Set-Up and Tear-Down + +Just as you can do set-up and tear-down at the test level and the test suite +level, you can also do it at the test program level. Here's how. + +First, you subclass the `::testing::Environment` class to define a test +environment, which knows how to set-up and tear-down: + +```c++ +class Environment : public ::testing::Environment { + public: + ~Environment() override {} + + // Override this to define how to set up the environment. + void SetUp() override {} + + // Override this to define how to tear down the environment. + void TearDown() override {} +}; +``` + +Then, you register an instance of your environment class with GoogleTest by +calling the `::testing::AddGlobalTestEnvironment()` function: + +```c++ +Environment* AddGlobalTestEnvironment(Environment* env); +``` + +Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The +tests are then executed, provided that none of the environments have reported +fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is +called. + +Note that `SetUp()` and `TearDown()` are only invoked if there is at least one +test to be performed. Importantly, `TearDown()` is executed even if the test is +not run due to a fatal failure or `GTEST_SKIP()`. + +Calling `SetUp()` and `TearDown()` for each iteration depends on the flag +`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are +called for each environment object when the object is recreated for each +iteration. However, if test environments are not recreated for each iteration, +`SetUp()` is called only on the first iteration, and `TearDown()` is called only +on the last iteration. + +It's OK to register multiple environment objects. In this suite, their `SetUp()` +will be called in the order they are registered, and their `TearDown()` will be +called in the reverse order. + +Note that GoogleTest takes ownership of the registered environment objects. +Therefore **do not delete them** by yourself. + +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, +probably in `main()`. If you use `gtest_main`, you need to call this before +`main()` starts for it to take effect. One way to do this is to define a global +variable like this: + +```c++ +testing::Environment* const foo_env = + testing::AddGlobalTestEnvironment(new FooEnvironment); +``` + +However, we strongly recommend you to write your own `main()` and call +`AddGlobalTestEnvironment()` there, as relying on initialization of global +variables makes the code harder to read and may cause problems when you register +multiple environments from different translation units and the environments have +dependencies among them (remember that the compiler doesn't guarantee the order +in which global variables from different translation units are initialized). + +## Value-Parameterized Tests + +*Value-parameterized tests* allow you to test your code with different +parameters without writing multiple copies of the same test. This is useful in a +number of situations, for example: + +* You have a piece of code whose behavior is affected by one or more + command-line flags. You want to make sure your code performs correctly for + various values of those flags. +* You want to test different implementations of an OO interface. +* You want to test your code over various inputs (a.k.a. data-driven testing). + This feature is easy to abuse, so please exercise your good sense when doing + it! + +### How to Write Value-Parameterized Tests + +To write value-parameterized tests, first you should define a fixture class. It +must be derived from both `testing::Test` and `testing::WithParamInterface` +(the latter is a pure interface), where `T` is the type of your parameter +values. For convenience, you can just derive the fixture class from +`testing::TestWithParam`, which itself is derived from both `testing::Test` +and `testing::WithParamInterface`. `T` can be any copyable type. If it's a +raw pointer, you are responsible for managing the lifespan of the pointed +values. + +{: .callout .note} +NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` +they must be declared **public** rather than **protected** in order to use +`TEST_P`. + +```c++ +class FooTest : + public testing::TestWithParam { + // You can implement all the usual fixture class members here. + // To access the test parameter, call GetParam() from class + // TestWithParam. +}; + +// Or, when you want to add parameters to a pre-existing fixture class: +class BaseTest : public testing::Test { + ... +}; +class BarTest : public BaseTest, + public testing::WithParamInterface { + ... +}; +``` + +Then, use the `TEST_P` macro to define as many test patterns using this fixture +as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. + +```c++ +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} +``` + +Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the +test suite with any set of parameters you want. GoogleTest defines a number of +functions for generating test parameters—see details at +[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in +the Testing Reference. + +For example, the following statement will instantiate tests from the `FooTest` +test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the +[`Values`](reference/testing.md#param-generators) parameter generator: + +```c++ +INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, + FooTest, + testing::Values("meeny", "miny", "moe")); +``` + +{: .callout .note} +NOTE: The code above must be placed at global or namespace scope, not at +function scope. + +The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the +instantiation of the test suite. The next argument is the name of the test +pattern, and the last is the +[parameter generator](reference/testing.md#param-generators). + +The parameter generator expression is not evaluated until GoogleTest is +initialized (via `InitGoogleTest()`). Any prior initialization done in the +`main` function will be accessible from the parameter generator, for example, +the results of flag parsing. + +You can instantiate a test pattern more than once, so to distinguish different +instances of the pattern, the instantiation name is added as a prefix to the +actual test suite name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these names: + +* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` + +You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). + +The following statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"` using the +[`ValuesIn`](reference/testing.md#param-generators) parameter generator: + +```c++ +constexpr absl::string_view kPets[] = {"cat", "dog"}; +INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); +``` + +The tests from the instantiation above will have these names: + +* `Pets/FooTest.DoesBlah/0` for `"cat"` +* `Pets/FooTest.DoesBlah/1` for `"dog"` +* `Pets/FooTest.HasBlahBlah/0` for `"cat"` +* `Pets/FooTest.HasBlahBlah/1` for `"dog"` + +Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the +given test suite, whether their definitions come before or *after* the +`INSTANTIATE_TEST_SUITE_P` statement. + +Additionally, by default, every `TEST_P` without a corresponding +`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite +`GoogleTestVerification`. If you have a test suite where that omission is not an +error, for example it is in a library that may be linked in for other reasons or +where the list of test cases is dynamic and may be empty, then this check can be +suppressed by tagging the test suite: + +```c++ +GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); +``` + +You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. + +[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example" +[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" + +### Creating Value-Parameterized Abstract Tests + +In the above, we define and instantiate `FooTest` in the *same* source file. +Sometimes you may want to define value-parameterized tests in a library and let +other people instantiate them later. This pattern is known as *abstract tests*. +As an example of its application, when you are designing an interface you can +write a standard suite of abstract tests (perhaps using a factory function as +the test parameter) that all implementations of the interface are expected to +pass. When someone implements the interface, they can instantiate your suite to +get all the interface-conformance tests for free. + +To define abstract tests, you should organize your code like this: + +1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) + in a header file, say `foo_param_test.h`. Think of this as *declaring* your + abstract tests. +2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes + `foo_param_test.h`. Think of this as *implementing* your abstract tests. + +Once they are defined, you can instantiate them by including `foo_param_test.h`, +invoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test suite +multiple times, possibly in different source files. + +### Specifying Names for Value-Parameterized Test Parameters + +The optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to +specify a function or functor that generates custom test name suffixes based on +the test parameters. The function should accept one argument of type +`testing::TestParamInfo`, and return `std::string`. + +`testing::PrintToStringParamName` is a builtin test suffix generator that +returns the value of `testing::PrintToString(GetParam())`. It does not work for +`std::string` or C strings. + +{: .callout .note} +NOTE: test names must be non-empty, unique, and may only contain ASCII +alphanumeric characters. In particular, they +[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) + +```c++ +class MyTestSuite : public testing::TestWithParam {}; + +TEST_P(MyTestSuite, MyTest) +{ + std::cout << "Example Test Param: " << GetParam() << std::endl; +} + +INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10), + testing::PrintToStringParamName()); +``` + +Providing a custom functor allows for more control over test parameter name +generation, especially for types where the automatic conversion does not +generate helpful parameter names (e.g. strings as demonstrated above). The +following example illustrates this for multiple parameters, an enumeration type +and a string, and also demonstrates how to combine generators. It uses a lambda +for conciseness: + +```c++ +enum class MyType { MY_FOO = 0, MY_BAR = 1 }; + +class MyTestSuite : public testing::TestWithParam> { +}; + +INSTANTIATE_TEST_SUITE_P( + MyGroup, MyTestSuite, + testing::Combine( + testing::Values(MyType::MY_FOO, MyType::MY_BAR), + testing::Values("A", "B")), + [](const testing::TestParamInfo& info) { + std::string name = absl::StrCat( + std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", + std::get<1>(info.param)); + absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); + return name; + }); +``` + +## Typed Tests + +Suppose you have multiple implementations of the same interface and want to make +sure that all of them satisfy some common requirements. Or, you may have defined +several types that are supposed to conform to the same "concept" and you want to +verify it. In both cases, you want the same test logic repeated for different +types. + +While you can write one `TEST` or `TEST_F` for each type you want to test (and +you may even factor the test logic into a function template that you invoke from +the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` +types, you'll end up writing `m*n` `TEST`s. + +*Typed tests* allow you to repeat the same test logic over a list of types. You +only need to write the test logic once, although you must know the type list +when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized by a type. +Remember to derive it from `::testing::Test`: + +```c++ +template +class FooTest : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +Next, associate a list of types with the test suite, which will be repeated for +each type in the list: + +```c++ +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(FooTest, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. Otherwise the compiler will think that each comma in +the type list introduces a new macro argument. + +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this +test suite. You can repeat this as many times as you want: + +```c++ +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } +``` + +You can see [sample6_unittest.cc] for a complete example. + +[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example" + +## Type-Parameterized Tests + +*Type-parameterized tests* are like typed tests, except that they don't require +you to know the list of types ahead of time. Instead, you can define the test +logic first and instantiate it with different type lists later. You can even +instantiate it more than once in the same program. + +If you are designing an interface or concept, you can define a suite of +type-parameterized tests to verify properties that any valid implementation of +the interface/concept should have. Then, the author of each implementation can +just instantiate the test suite with their type to verify that it conforms to +the requirements, without having to write similar tests repeatedly. Here's an +example: + +First, define a fixture class template, as we did with typed tests: + +```c++ +template +class FooTest : public testing::Test { + void DoSomethingInteresting(); + ... +}; +``` + +Next, declare that you will define a type-parameterized test suite: + +```c++ +TYPED_TEST_SUITE_P(FooTest); +``` + +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat +this as many times as you want: + +```c++ +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + + // You will need to use `this` explicitly to refer to fixture members. + this->DoSomethingInteresting() + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } +``` + +Now the tricky part: you need to register all test patterns using the +`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first +argument of the macro is the test suite name; the rest are the names of the +tests in this test suite: + +```c++ +REGISTER_TYPED_TEST_SUITE_P(FooTest, + DoesBlah, HasPropertyA); +``` + +Finally, you are free to instantiate the pattern with the types you want. If you +put the above code in a header file, you can `#include` it in multiple C++ +source files and instantiate it multiple times. + +```c++ +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); +``` + +To distinguish different instances of the pattern, the first argument to the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the +actual test suite name. Remember to pick unique prefixes for different +instances. + +In the special case where the type list contains only one type, you can write +that type directly without `::testing::Types<...>`, like this: + +```c++ +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); +``` + +You can see [sample6_unittest.cc] for a complete example. + +## Testing Private Code + +If you change your software's internal implementation, your tests should not +break as long as the change is not observable by users. Therefore, **per the +black-box testing principle, most of the time you should test your code through +its public interfaces.** + +**If you still find yourself needing to test internal implementation code, +consider if there's a better design.** The desire to test internal +implementation is often a sign that the class is doing too much. Consider +extracting an implementation class, and testing it. Then use that implementation +class in the original class. + +If you absolutely have to test non-public interface code though, you can. There +are two cases to consider: + +* Static functions ( *not* the same as static member functions!) or unnamed + namespaces, and +* Private or protected class members + +To test them, we use the following special techniques: + +* Both static functions and definitions/declarations in an unnamed namespace + are only visible within the same translation unit. To test them, you can + `#include` the entire `.cc` file being tested in your `*_test.cc` file. + (#including `.cc` files is not a good way to reuse code - you should not do + this in production code!) + + However, a better approach is to move the private code into the + `foo::internal` namespace, where `foo` is the namespace your project + normally uses, and put the private declarations in a `*-internal.h` file. + Your production `.cc` files and your tests are allowed to include this + internal header, but your clients are not. This way, you can fully test your + internal implementation without leaking it to your clients. + +* Private class members are only accessible from within the class or by + friends. To access a class' private members, you can declare your test + fixture as a friend to the class and define accessors in your fixture. Tests + using the fixture can then access the private members of your production + class via the accessors in the fixture. Note that even though your fixture + is a friend to your production class, your tests are not automatically + friends to it, as they are technically defined in sub-classes of the + fixture. + + Another way to test private members is to refactor them into an + implementation class, which is then declared in a `*-internal.h` file. Your + clients aren't allowed to include this header but your tests can. Such is + called the + [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) + (Private Implementation) idiom. + + Or, you can declare an individual test as a friend of your class by adding + this line in the class body: + + ```c++ + FRIEND_TEST(TestSuiteName, TestName); + ``` + + For example, + + ```c++ + // foo.h + class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); + + int Bar(void* x); + }; + + // foo_test.cc + ... + TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). + } + ``` + + Pay special attention when your class is defined in a namespace. If you want + your test fixtures and tests to be friends of your class, then they must be + defined in the exact same namespace (no anonymous or inline namespaces). + + For example, if the code to be tested looks like: + + ```c++ + namespace my_namespace { + + class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... definition of the class Foo ... + }; + + } // namespace my_namespace + ``` + + Your test code should be something like: + + ```c++ + namespace my_namespace { + + class FooTest : public testing::Test { + protected: + ... + }; + + TEST_F(FooTest, Bar) { ... } + TEST_F(FooTest, Baz) { ... } + + } // namespace my_namespace + ``` + +## "Catching" Failures + +If you are building a testing utility on top of GoogleTest, you'll want to test +your utility. What framework would you use to test it? GoogleTest, of course. + +The challenge is to verify that your testing utility reports failures correctly. +In frameworks that report a failure by throwing an exception, you could catch +the exception and assert on it. But GoogleTest doesn't use exceptions, so how do +we test that a piece of code generates an expected failure? + +`"gtest/gtest-spi.h"` contains some constructs to do this. +After #including this header, you can use + +```c++ + EXPECT_FATAL_FAILURE(statement, substring); +``` + +to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the +current thread whose message contains the given `substring`, or use + +```c++ + EXPECT_NONFATAL_FAILURE(statement, substring); +``` + +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. + +Only failures in the current thread are checked to determine the result of this +type of expectations. If `statement` creates new threads, failures in these +threads are also ignored. If you want to catch failures in other threads as +well, use one of the following macros instead: + +```c++ + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); +``` + +{: .callout .note} +NOTE: Assertions from multiple threads are currently not supported on Windows. + +For technical reasons, there are some caveats: + +1. You cannot stream a failure message to either macro. + +2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference + local non-static variables or non-static members of `this` object. + +3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a + value. + +## Registering tests programmatically + +The `TEST` macros handle the vast majority of all use cases, but there are few +where runtime registration logic is required. For those cases, the framework +provides the `::testing::RegisterTest` that allows callers to register arbitrary +tests dynamically. + +This is an advanced API only to be used when the `TEST` macros are insufficient. +The macros should be preferred when possible, as they avoid most of the +complexity of calling this function. + +It provides the following signature: + +```c++ +template +TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory); +``` + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the Test object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` for it. + +Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is +undefined. + +Use case example: + +```c++ +class MyFixture : public testing::Test { + public: + // All of these optional, just like in regular macro usage. + static void SetUpTestSuite() { ... } + static void TearDownTestSuite() { ... } + void SetUp() override { ... } + void TearDown() override { ... } +}; + +class MyTest : public MyFixture { + public: + explicit MyTest(int data) : data_(data) {} + void TestBody() override { ... } + + private: + int data_; +}; + +void RegisterMyTests(const std::vector& values) { + for (int v : values) { + testing::RegisterTest( + "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, + std::to_string(v).c_str(), + __FILE__, __LINE__, + // Important to use the fixture type as the return type here. + [=]() -> MyFixture* { return new MyTest(v); }); + } +} +... +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + std::vector values_to_test = LoadValuesFromConfig(); + RegisterMyTests(values_to_test); + ... + return RUN_ALL_TESTS(); +} +``` + +## Getting the Current Test's Name + +Sometimes a function may need to know the name of the currently running test. +For example, you may be using the `SetUp()` method of your test fixture to set +the golden file name based on which test is running. The +[`TestInfo`](reference/testing.md#TestInfo) class has this information. + +To obtain a `TestInfo` object for the currently running test, call +`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) +singleton object: + +```c++ + // Gets information about the currently running test. + // Do NOT delete the returned object - it's managed by the UnitTest class. + const testing::TestInfo* const test_info = + testing::UnitTest::GetInstance()->current_test_info(); + + printf("We are in test %s of test suite %s.\n", + test_info->name(), + test_info->test_suite_name()); +``` + +`current_test_info()` returns a null pointer if no test is running. In +particular, you cannot find the test suite name in `SetUpTestSuite()`, +`TearDownTestSuite()` (where you know the test suite name implicitly), or +functions called from them. + +## Extending GoogleTest by Handling Test Events + +GoogleTest provides an **event listener API** to let you receive notifications +about the progress of a test program and test failures. The events you can +listen to include the start and end of the test program, a test suite, or a test +method, among others. You may use this API to augment or replace the standard +console output, replace the XML output, or provide a completely different form +of output, such as a GUI or a database. You can also use test events as +checkpoints to implement a resource leak checker, for example. + +### Defining Event Listeners + +To define a event listener, you subclass either +[`testing::TestEventListener`](reference/testing.md#TestEventListener) or +[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) +The former is an (abstract) interface, where *each pure virtual method can be +overridden to handle a test event* (For example, when a test starts, the +`OnTestStart()` method will be called.). The latter provides an empty +implementation of all methods in the interface, such that a subclass only needs +to override the methods it cares about. + +When an event is fired, its context is passed to the handler function as an +argument. The following argument types are used: + +* UnitTest reflects the state of the entire test program, +* TestSuite has information about a test suite, which can contain one or more + tests, +* TestInfo contains the state of a test, and +* TestPartResult represents the result of a test assertion. + +An event handler function can examine the argument it receives to find out +interesting information about the event and the test program's state. + +Here's an example: + +```c++ + class MinimalistPrinter : public testing::EmptyTestEventListener { + // Called before a test starts. + void OnTestStart(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s starting.\n", + test_info.test_suite_name(), test_info.name()); + } + + // Called after a failed assertion or a SUCCESS(). + void OnTestPartResult(const testing::TestPartResult& test_part_result) override { + printf("%s in %s:%d\n%s\n", + test_part_result.failed() ? "*** Failure" : "Success", + test_part_result.file_name(), + test_part_result.line_number(), + test_part_result.summary()); + } + + // Called after a test ends. + void OnTestEnd(const testing::TestInfo& test_info) override { + printf("*** Test %s.%s ending.\n", + test_info.test_suite_name(), test_info.name()); + } + }; +``` + +### Using Event Listeners + +To use the event listener you have defined, add an instance of it to the +GoogleTest event listener list (represented by class +[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" +at the end of the name) in your `main()` function, before calling +`RUN_ALL_TESTS()`: + +```c++ +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + // Gets hold of the event listener list. + testing::TestEventListeners& listeners = + testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. GoogleTest takes the ownership. + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +} +``` + +There's only one problem: the default test result printer is still in effect, so +its output will mingle with the output from your minimalist printer. To suppress +the default printer, just release it from the event listener list and delete it. +You can do so by adding one line: + +```c++ + ... + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +``` + +Now, sit back and enjoy a completely different output from your tests. For more +details, see [sample9_unittest.cc]. + +[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example" + +You may append more than one listener to the list. When an `On*Start()` or +`OnTestPartResult()` event is fired, the listeners will receive it in the order +they appear in the list (since new listeners are added to the end of the list, +the default text printer and the default XML generator will receive the event +first). An `On*End()` event will be received by the listeners in the *reverse* +order. This allows output by listeners added later to be framed by output from +listeners added earlier. + +### Generating Failures in Listeners + +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) +when processing an event. There are some restrictions: + +1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will + cause `OnTestPartResult()` to be called recursively). +2. A listener that handles `OnTestPartResult()` is not allowed to generate any + failure. + +When you add listeners to the listener list, you should put listeners that +handle `OnTestPartResult()` *before* listeners that can generate failures. This +ensures that failures generated by the latter are attributed to the right test +by the former. + +See [sample10_unittest.cc] for an example of a failure-raising listener. + +[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example" + +## Running Test Programs: Advanced Options + +GoogleTest test programs are ordinary executables. Once built, you can run them +directly and affect their behavior via the following environment variables +and/or command line flags. For the flags to work, your programs must call +`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. + +To see a list of supported flags and their usage, please run your test program +with the `--help` flag. + +If an option is specified both by an environment variable and by a flag, the +latter takes precedence. + +### Selecting Tests + +#### Listing Test Names + +Sometimes it is necessary to list the available tests in a program before +running them so that a filter may be applied if needed. Including the flag +`--gtest_list_tests` overrides all other flags and lists tests in the following +format: + +```none +TestSuite1. + TestName1 + TestName2 +TestSuite2. + TestName +``` + +None of the tests listed are actually run if the flag is provided. There is no +corresponding environment variable for this flag. + +#### Running a Subset of the Tests + +By default, a GoogleTest program runs all tests the user has defined. Sometimes, +you want to run only a subset of the tests (e.g. for debugging or quickly +verifying a change). If you set the `GTEST_FILTER` environment variable or the +`--gtest_filter` flag to a filter string, GoogleTest will only run the tests +whose full names (in the form of `TestSuiteName.TestName`) match the filter. + +The format of a filter is a '`:`'-separated list of wildcard patterns (called +the *positive patterns*) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the *negative patterns*). A test matches +the filter if and only if it matches any of the positive patterns but does not +match any of the negative patterns. + +A pattern may contain `'*'` (matches any string) or `'?'` (matches any single +character). For convenience, the filter `'*-NegativePatterns'` can be also +written as `'-NegativePatterns'`. + +For example: + +* `./foo_test` Has no flag, and thus runs all its tests. +* `./foo_test --gtest_filter=*` Also runs everything, due to the single + match-everything `*` value. +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite + `FooTest` . +* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full + name contains either `"Null"` or `"Constructor"` . +* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. +* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test + suite `FooTest` except `FooTest.Bar`. +* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs + everything in test suite `FooTest` except `FooTest.Bar` and everything in + test suite `BarTest` except `BarTest.Foo`. + +#### Stop test execution upon first failure + +By default, a GoogleTest program runs all tests the user has defined. In some +cases (e.g. iterative test development & execution) it may be desirable stop +test execution upon first failure (trading improved latency for completeness). +If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, +the test runner will stop execution as soon as the first test failure is found. + +#### Temporarily Disabling Tests + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +If you need to disable all tests in a test suite, you can either add `DISABLED_` +to the front of the name of each test, or alternatively add it to the front of +the test suite name. + +For example, the following tests won't be run by GoogleTest, even though they +will still be compiled: + +```c++ +// Tests that Foo does Abc. +TEST(FooTest, DISABLED_DoesAbc) { ... } + +class DISABLED_BarTest : public testing::Test { ... }; + +// Tests that Bar does Xyz. +TEST_F(DISABLED_BarTest, DoesXyz) { ... } +``` + +{: .callout .note} +NOTE: This feature should only be used for temporary pain-relief. You still have +to fix the disabled tests at a later date. As a reminder, GoogleTest will print +a banner warning you if a test program contains any disabled tests. + +{: .callout .tip} +TIP: You can easily count the number of disabled tests you have using +`grep`. This number can be used as a metric for +improving your test quality. + +#### Temporarily Enabling Disabled Tests + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. +You can combine this with the `--gtest_filter` flag to further select which +disabled tests to run. + +### Repeating the Tests + +Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it +will fail only 1% of the time, making it rather hard to reproduce the bug under +a debugger. This can be a major source of frustration. + +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in +a program many times. Hopefully, a flaky test will eventually fail and give you +a chance to debug. Here's how to use it: + +```none +$ foo_test --gtest_repeat=1000 +Repeat foo_test 1000 times and don't stop at failures. + +$ foo_test --gtest_repeat=-1 +A negative count means repeating forever. + +$ foo_test --gtest_repeat=1000 --gtest_break_on_failure +Repeat foo_test 1000 times, stopping at the first failure. This +is especially useful when running under a debugger: when the test +fails, it will drop into the debugger and you can then inspect +variables and stacks. + +$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* +Repeat the tests whose name matches the filter 1000 times. +``` + +If your test program contains +[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be +repeated in each iteration as well, as the flakiness may be in it. To avoid +repeating global set-up/tear-down, specify +`--gtest_recreate_environments_when_repeating=false`{.nowrap}. + +You can also specify the repeat count by setting the `GTEST_REPEAT` environment +variable. + +### Shuffling the Tests + +You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` +environment variable to `1`) to run the tests in a program in a random order. +This helps to reveal bad dependencies between tests. + +By default, GoogleTest uses a random seed calculated from the current time. +Therefore you'll get a different order every time. The console output includes +the random seed value, such that you can reproduce an order-related test failure +later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` +flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an +integer in the range [0, 99999]. The seed value 0 is special: it tells +GoogleTest to do the default behavior of calculating the seed from the current +time. + +If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different +random seed and re-shuffle the tests in each iteration. + +### Distributing Test Functions to Multiple Machines + +If you have more than one machine you can use to run a test program, you might +want to run the test functions in parallel and get the result faster. We call +this technique *sharding*, where each machine is called a *shard*. + +GoogleTest is compatible with test sharding. To take advantage of this feature, +your test runner (not part of GoogleTest) needs to do the following: + +1. Allocate a number of machines (shards) to run the tests. +1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total + number of shards. It must be the same for all shards. +1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index + of the shard. Different shards must be assigned different indices, which + must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. +1. Run the same test program on all shards. When GoogleTest sees the above two + environment variables, it will select a subset of the test functions to run. + Across all shards, each test function in the program will be run exactly + once. +1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without GoogleTest and thus don't +understand this protocol. In order for your test runner to figure out which test +supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` +to a non-existent file path. If a test program supports sharding, it will create +this file to acknowledge that fact; otherwise it will not create it. The actual +contents of the file are not important at this time, although we may put some +useful information in it in the future. + +Here's an example to make it clear. Suppose you have a test program `foo_test` +that contains the following 5 test functions: + +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` + +Suppose you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set +`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would +run the same `foo_test` on each machine. + +GoogleTest reserves the right to change how the work is distributed across the +shards, but here's one possible scenario: + +* Machine #0 runs `A.V` and `B.X`. +* Machine #1 runs `A.W` and `B.Y`. +* Machine #2 runs `B.Z`. + +### Controlling Test Output + +#### Colored Terminal Output + +GoogleTest can use colors in its terminal output to make it easier to spot the +important information: + +
...
+[----------] 1 test from FooTest
+[ RUN      ] FooTest.DoesAbc
+[       OK ] FooTest.DoesAbc
+[----------] 2 tests from BarTest
+[ RUN      ] BarTest.HasXyzProperty
+[       OK ] BarTest.HasXyzProperty
+[ RUN      ] BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+...
+[==========] 30 tests from 14 test suites ran.
+[   PASSED ] 28 tests.
+[   FAILED ] 2 tests, listed below:
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+[   FAILED ] AnotherTest.DoesXyz
+
+ 2 FAILED TESTS
+
+ +You can set the `GTEST_COLOR` environment variable or the `--gtest_color` +command line flag to `yes`, `no`, or `auto` (the default) to enable colors, +disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest +will use colors if and only if the output goes to a terminal and (on non-Windows +platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. + +#### Suppressing test passes + +By default, GoogleTest prints 1 line of output for each test, indicating if it +passed or failed. To show only test failures, run the test program with +`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. + +#### Suppressing the Elapsed Time + +By default, GoogleTest prints the time it takes to run each test. To disable +that, run the test program with the `--gtest_print_time=0` command line flag, or +set the GTEST_PRINT_TIME environment variable to `0`. + +#### Suppressing UTF-8 Text Output + +In case of assertion failures, GoogleTest prints expected and actual values of +type `string` both as hex-encoded strings as well as in readable UTF-8 text if +they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 +text because, for example, you don't have an UTF-8 compatible output medium, run +the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` +environment variable to `0`. + +#### Generating an XML Report + +GoogleTest can emit a detailed XML report to a file in addition to its normal +textual output. The report contains the duration of each test, and thus can help +you identify slow tests. + +To generate the XML report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will +create the file at the given location. You can also just use the string `"xml"`, +in which case the output can be found in the `test_detail.xml` file in the +current directory. + +If you specify a directory (for example, `"xml:output/directory/"` on Linux or +`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in +that directory, named after the test executable (e.g. `foo_test.xml` for test +program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left +over from a previous run), GoogleTest will pick a different name (e.g. +`foo_test_1.xml`) to avoid overwriting it. + +The report is based on the `junitreport` Ant task. Since that format was +originally intended for Java, a little interpretation is required to make it +apply to GoogleTest tests, as shown here: + +```xml + + + + + + + + + +``` + +* The root `` element corresponds to the entire test program. +* `` elements correspond to GoogleTest test suites. +* `` elements correspond to GoogleTest test functions. + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```xml + + + + + ... + ... + + + + + + + + + +``` + +Things to note: + +* The `tests` attribute of a `` or `` element tells how + many test functions the GoogleTest program or test suite contains, while the + `failures` attribute tells how many of them failed. + +* The `time` attribute expresses the duration of the test, test suite, or + entire test program in seconds. + +* The `timestamp` attribute records the local date and time of the test + execution. + +* The `file` and `line` attributes record the source file location, where the + test was defined. + +* Each `` element corresponds to a single failed GoogleTest + assertion. + +#### Generating a JSON Report + +GoogleTest can also emit a JSON report as an alternative format to XML. To +generate the JSON report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"json:path_to_output_file"`, which will +create the file at the given location. You can also just use the string +`"json"`, in which case the output can be found in the `test_detail.json` file +in the current directory. + +The report format conforms to the following JSON Schema: + +```json +{ + "$schema": "https://json-schema.org/schema#", + "type": "object", + "definitions": { + "TestCase": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "time": { "type": "string" }, + "testsuite": { + "type": "array", + "items": { + "$ref": "#/definitions/TestInfo" + } + } + } + }, + "TestInfo": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, + "status": { + "type": "string", + "enum": ["RUN", "NOTRUN"] + }, + "time": { "type": "string" }, + "classname": { "type": "string" }, + "failures": { + "type": "array", + "items": { + "$ref": "#/definitions/Failure" + } + } + } + }, + "Failure": { + "type": "object", + "properties": { + "failures": { "type": "string" }, + "type": { "type": "string" } + } + } + }, + "properties": { + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "errors": { "type": "integer" }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "time": { "type": "string" }, + "name": { "type": "string" }, + "testsuites": { + "type": "array", + "items": { + "$ref": "#/definitions/TestCase" + } + } + } +} +``` + +The report uses the format that conforms to the following Proto3 using the +[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): + +```proto +syntax = "proto3"; + +package googletest; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; + +message UnitTest { + int32 tests = 1; + int32 failures = 2; + int32 disabled = 3; + int32 errors = 4; + google.protobuf.Timestamp timestamp = 5; + google.protobuf.Duration time = 6; + string name = 7; + repeated TestCase testsuites = 8; +} + +message TestCase { + string name = 1; + int32 tests = 2; + int32 failures = 3; + int32 disabled = 4; + int32 errors = 5; + google.protobuf.Duration time = 6; + repeated TestInfo testsuite = 7; +} + +message TestInfo { + string name = 1; + string file = 6; + int32 line = 7; + enum Status { + RUN = 0; + NOTRUN = 1; + } + Status status = 2; + google.protobuf.Duration time = 3; + string classname = 4; + message Failure { + string failures = 1; + string type = 2; + } + repeated Failure failures = 5; +} +``` + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```json +{ + "tests": 3, + "failures": 1, + "errors": 0, + "time": "0.035s", + "timestamp": "2011-10-31T18:52:42Z", + "name": "AllTests", + "testsuites": [ + { + "name": "MathTest", + "tests": 2, + "failures": 1, + "errors": 0, + "time": "0.015s", + "testsuite": [ + { + "name": "Addition", + "file": "test.cpp", + "line": 1, + "status": "RUN", + "time": "0.007s", + "classname": "", + "failures": [ + { + "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", + "type": "" + }, + { + "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", + "type": "" + } + ] + }, + { + "name": "Subtraction", + "file": "test.cpp", + "line": 2, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + }, + { + "name": "LogicTest", + "tests": 1, + "failures": 0, + "errors": 0, + "time": "0.005s", + "testsuite": [ + { + "name": "NonContradiction", + "file": "test.cpp", + "line": 3, + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + } + ] +} +``` + +{: .callout .important} +IMPORTANT: The exact format of the JSON document is subject to change. + +### Controlling How Failures Are Reported + +#### Detecting Test Premature Exit + +Google Test implements the _premature-exit-file_ protocol for test runners to +catch any kind of unexpected exits of test programs. Upon start, Google Test +creates the file which will be automatically deleted after all work has been +finished. Then, the test runner can check if this file exists. In case the file +remains undeleted, the inspected test has exited prematurely. + +This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment +variable has been set. + +#### Turning Assertion Failures into Break-Points + +When running test programs under a debugger, it's very convenient if the +debugger can catch an assertion failure and automatically drop into interactive +mode. GoogleTest's *break-on-failure* mode supports this behavior. + +To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value +other than `0`. Alternatively, you can use the `--gtest_break_on_failure` +command line flag. + +#### Disabling Catching Test-Thrown Exceptions + +GoogleTest can be used either with or without exceptions enabled. If a test +throws a C++ exception or (on Windows) a structured exception (SEH), by default +GoogleTest catches it, reports it as a test failure, and continues with the next +test method. This maximizes the coverage of a test run. Also, on Windows an +uncaught exception will cause a pop-up window, so catching the exceptions allows +you to run the tests automatically. + +When debugging the test failures, however, you may instead want the exceptions +to be handled by the debugger, such that you can examine the call stack when an +exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` +environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when +running the tests. + +### Sanitizer Integration + +The +[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), +[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), +and +[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) +all provide weak functions that you can override to trigger explicit failures +when they detect sanitizer errors, such as creating a reference from `nullptr`. +To override these functions, place definitions for them in a source file that +you compile as part of your main binary: + +``` +extern "C" { +void __ubsan_on_report() { + FAIL() << "Encountered an undefined behavior sanitizer error"; +} +void __asan_on_error() { + FAIL() << "Encountered an address sanitizer error"; +} +void __tsan_on_report() { + FAIL() << "Encountered a thread sanitizer error"; +} +} // extern "C" +``` + +After compiling your project with one of the sanitizers enabled, if a particular +test triggers a sanitizer error, GoogleTest will report that it failed. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/assets/css/style.scss b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/assets/css/style.scss new file mode 100644 index 0000000000000000000000000000000000000000..bb30f418da7b92d8eaa1fd63caac99aa0576e91c --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/assets/css/style.scss @@ -0,0 +1,5 @@ +--- +--- + +@import "jekyll-theme-primer"; +@import "main"; diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/community_created_documentation.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/community_created_documentation.md new file mode 100644 index 0000000000000000000000000000000000000000..4569075ff23be385fce1656a8db2f77631d00d42 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/community_created_documentation.md @@ -0,0 +1,7 @@ +# Community-Created Documentation + +The following is a list, in no particular order, of links to documentation +created by the Googletest community. + +* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md), + by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy) diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/faq.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..c7d10b5006ba50c44f74a735fbaaaaf382235a31 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/faq.md @@ -0,0 +1,671 @@ +# GoogleTest FAQ + +## Why should test suite names and test names not contain underscore? + +{: .callout .note} +Note: GoogleTest reserves underscore (`_`) for special-purpose keywords, such as +[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition +to the following rationale. + +Underscore (`_`) is special, as C++ reserves the following to be used by the +compiler and the standard library: + +1. any identifier that starts with an `_` followed by an upper-case letter, and +2. any identifier that contains two consecutive underscores (i.e. `__`) + *anywhere* in its name. + +User code is *prohibited* from using such identifiers. + +Now let's look at what this means for `TEST` and `TEST_F`. + +Currently `TEST(TestSuiteName, TestName)` generates a class named +`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName` +contains `_`? + +1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say, + `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus + invalid. +2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get + `Foo__TestName_Test`, which is invalid. +3. If `TestName` starts with an `_` (say, `_Bar`), we get + `TestSuiteName__Bar_Test`, which is invalid. +4. If `TestName` ends with an `_` (say, `Bar_`), we get + `TestSuiteName_Bar__Test`, which is invalid. + +So clearly `TestSuiteName` and `TestName` cannot start or end with `_` +(Actually, `TestSuiteName` can start with `_`—as long as the `_` isn't followed +by an upper-case letter. But that's getting complicated. So for simplicity we +just say that it cannot start with `_`.). + +It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the +middle. However, consider this: + +```c++ +TEST(Time, Flies_Like_An_Arrow) { ... } +TEST(Time_Flies, Like_An_Arrow) { ... } +``` + +Now, the two `TEST`s will both generate the same class +(`Time_Flies_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and +`TestName`. The rule is more constraining than necessary, but it's simple and +easy to remember. It also gives GoogleTest some wiggle room in case its +implementation needs to change in the future. + +If you violate the rule, there may not be immediate consequences, but your test +may (just may) break with a new compiler (or a new version of the compiler you +are using) or with a new version of GoogleTest. Therefore it's best to follow +the rule. + +## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? + +First of all, you can use `nullptr` with each of these macros, e.g. +`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`, +`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide +because `nullptr` does not have the type problems that `NULL` does. + +Due to some peculiarity of C++, it requires some non-trivial template meta +programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` +and `ASSERT_XX()` macros. Therefore we only do it where it's most needed +(otherwise we make the implementation of GoogleTest harder to maintain and more +error-prone than necessary). + +Historically, the `EXPECT_EQ()` macro took the *expected* value as its first +argument and the *actual* value as the second, though this argument order is now +discouraged. It was reasonable that someone wanted +to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested +several times. Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion +fails, you already know that `ptr` must be `NULL`, so it doesn't add any +information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` +works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to +support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta +programming tricks twice in the implementation, making it even harder to +understand and maintain. We believe the benefit doesn't justify the cost. + +Finally, with the growth of the gMock matcher library, we are encouraging people +to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One +significant advantage of the matcher approach is that matchers can be easily +combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be +easily combined. Therefore we want to invest more in the matchers than in the +`EXPECT_XX()` macros. + +## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests? + +For testing various implementations of the same interface, either typed tests or +value-parameterized tests can get it done. It's really up to you the user to +decide which is more convenient for you, depending on your particular case. Some +rough guidelines: + +* Typed tests can be easier to write if instances of the different + implementations can be created the same way, modulo the type. For example, + if all these implementations have a public default constructor (such that + you can write `new TypeParam`), or if their factory functions have the same + form (e.g. `CreateInstance()`). +* Value-parameterized tests can be easier to write if you need different code + patterns to create different implementations' instances, e.g. `new Foo` vs + `new Bar(5)`. To accommodate for the differences, you can write factory + function wrappers and pass these function pointers to the tests as their + parameters. +* When a typed test fails, the default output includes the name of the type, + which can help you quickly identify which implementation is wrong. + Value-parameterized tests only show the number of the failed iteration by + default. You will need to define a function that returns the iteration name + and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more + useful output. +* When using typed tests, you need to make sure you are testing against the + interface type, not the concrete types (in other words, you want to make + sure `implicit_cast(my_concrete_impl)` works, not just that + `my_concrete_impl` works). It's less likely to make mistakes in this area + when using value-parameterized tests. + +I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give +both approaches a try. Practice is a much better way to grasp the subtle +differences between the two tools. Once you have some concrete experience, you +can much more easily decide which one to use the next time. + +## My death test modifies some state, but the change seems lost after the death test finishes. Why? + +Death tests (`EXPECT_DEATH`, etc.) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their respective +sub-processes, but not in the parent process. You can think of them as running +in a parallel universe, more or less. + +In particular, if you use mocking and the death test statement invokes some mock +methods, the parent process will think the calls have never occurred. Therefore, +you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` +macro. + +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug? + +Actually, the bug is in `htonl()`. + +According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to +use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as +a *macro*, which breaks this usage. + +Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not* +standard C++. That hacky implementation has some ad hoc limitations. In +particular, it prevents you from writing `Foo()`, where `Foo` +is a template that has an integral argument. + +The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a +template argument, and thus doesn't compile in opt mode when `a` contains a call +to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as +the solution must work with different compilers on various platforms. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? + +If your class has a static data member: + +```c++ +// foo.h +class Foo { + ... + static const int kBar = 100; +}; +``` + +you also need to define it *outside* of the class body in `foo.cc`: + +```c++ +const int Foo::kBar; // No initializer here. +``` + +Otherwise your code is **invalid C++**, and may break in unexpected ways. In +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc.) +will generate an "undefined reference" linker error. The fact that "it used to +work" doesn't mean it's valid. It just means that you were lucky. :-) + +If the declaration of the static data member is `constexpr` then it is +implicitly an `inline` definition, and a separate definition in `foo.cc` is not +needed: + +```c++ +// foo.h +class Foo { + ... + static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc. +}; +``` + +## Can I derive a test fixture from another? + +Yes. + +Each test fixture has a corresponding and same named test suite. This means only +one test suite can use a particular fixture. Sometimes, however, multiple test +cases may want to use the same or slightly different fixtures. For example, you +may want to make sure that all of a GUI library's test suites don't leak +important system resources like fonts and brushes. + +In GoogleTest, you share a fixture among test suites by putting the shared logic +in a base test fixture, then deriving from that base a separate fixture for each +test suite that wants to use this common logic. You then use `TEST_F()` to write +tests using each derived fixture. + +Typically, your code looks like this: + +```c++ +// Defines a base test fixture. +class BaseTest : public ::testing::Test { + protected: + ... +}; + +// Derives a fixture FooTest from BaseTest. +class FooTest : public BaseTest { + protected: + void SetUp() override { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + + void TearDown() override { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + + ... functions and variables for FooTest ... +}; + +// Tests that use the fixture FooTest. +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +... additional fixtures derived from BaseTest ... +``` + +If necessary, you can continue to derive test fixtures from a derived fixture. +GoogleTest has no limit on how deep the hierarchy can be. + +For a complete example using derived test fixtures, see +[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc). + +## My compiler complains "void value not ignored as it ought to be." What does this mean? + +You're probably using an `ASSERT_*()` in a function that doesn't return `void`. +`ASSERT_*()` can only be used in `void` functions, due to exceptions being +disabled by our build system. Please see more details +[here](advanced.md#assertion-placement). + +## My death test hangs (or seg-faults). How do I fix it? + +In GoogleTest, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work—see +the details at [Death Assertions](reference/assertions.md#death) in the +Assertions Reference. + +In particular, death tests don't like having multiple threads in the parent +process. So the first thing you can try is to eliminate creating threads outside +of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects +instead of real ones in your tests. + +Sometimes this is impossible as some library you must use may be creating +threads before `main()` is even reached. In this case, you can try to minimize +the chance of conflicts by either moving as many activities as possible inside +`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or +leaving as few things as possible in it. Also, you can try to set the death test +style to `"threadsafe"`, which is safer but slower, and see if it helps. + +If you go with thread-safe death tests, remember that they rerun the test +program from the beginning in the child process. Therefore make sure your +program can run side-by-side with itself and is deterministic. + +In the end, this boils down to good concurrent programming. You have to make +sure that there are no race conditions or deadlocks in your program. No silver +bullet - sorry! + +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} + +The first thing to remember is that GoogleTest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, GoogleTest will create +a **fresh** test fixture object, immediately call `SetUp()`, run the test body, +call `TearDown()`, and then delete the test fixture object. + +When you need to write per-test set-up and tear-down logic, you have the choice +between using the test fixture constructor/destructor or `SetUp()`/`TearDown()`. +The former is usually preferred, as it has the following benefits: + +* By initializing a member variable in the constructor, we have the option to + make it `const`, which helps prevent accidental changes to its value and + makes the tests more obviously correct. +* In case we need to subclass the test fixture class, the subclass' + constructor is guaranteed to call the base class' constructor *first*, and + the subclass' destructor is guaranteed to call the base class' destructor + *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of + forgetting to call the base class' `SetUp()/TearDown()` or call them at the + wrong time. + +You may still want to use `SetUp()/TearDown()` in the following cases: + +* C++ does not allow virtual function calls in constructors and destructors. + You can call a method declared as virtual, but it will not use dynamic + dispatch. It will use the definition from the class the constructor of which + is currently executing. This is because calling a virtual method before the + derived class constructor has a chance to run is very dangerous - the + virtual method might operate on uninitialized data. Therefore, if you need + to call a method that will be overridden in a derived class, you have to use + `SetUp()/TearDown()`. +* In the body of a constructor (or destructor), it's not possible to use the + `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal + test failure that should prevent the test from running, it's necessary to + use `abort` and abort the whole test + executable, or to use `SetUp()` instead of a constructor. +* If the tear-down operation could throw an exception, you must use + `TearDown()` as opposed to the destructor, as throwing in a destructor leads + to undefined behavior and usually will kill your program right away. Note + that many standard libraries (like STL) may throw when exceptions are + enabled in the compiler. Therefore you should prefer `TearDown()` if you + want to write portable tests that work with or without exceptions. +* The GoogleTest team is considering making the assertion macros throw on + platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux + client-side), which will eliminate the need for the user to propagate + failures from a subroutine to its caller. Therefore, you shouldn't use + GoogleTest assertions in a destructor if your code could run on such a + platform. + +## The compiler complains "no matching function to call" when I use `ASSERT_PRED*`. How do I fix it? + +See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the +Assertions Reference. + +## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? + +Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, +instead of + +```c++ + return RUN_ALL_TESTS(); +``` + +they write + +```c++ + RUN_ALL_TESTS(); +``` + +This is **wrong and dangerous**. The testing services needs to see the return +value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your +`main()` function ignores it, your test will be considered successful even if it +has a GoogleTest assertion failure. Very bad. + +We have decided to fix this (thanks to Michael Chastain for the idea). Now, your +code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with +`gcc`. If you do so, you'll get a compiler error. + +If you see the compiler complaining about you ignoring the return value of +`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the +return value of `main()`. + +But how could we introduce a change that breaks existing tests? Well, in this +case, the code was already broken in the first place, so we didn't break it. :-) + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? + +Due to a peculiarity of C++, in order to support the syntax for streaming +messages to an `ASSERT_*`, e.g. + +```c++ + ASSERT_EQ(1, Foo()) << "blah blah" << foo; +``` + +we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and +`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the +content of your constructor/destructor to a private void member function, or +switch to `EXPECT_*()` if that works. This +[section](advanced.md#assertion-placement) in the user's guide explains it. + +## My SetUp() function is not called. Why? + +C++ is case-sensitive. Did you spell it as `Setup()`? + +Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and +wonder why it's never called. + +## I have several test suites which share the same test fixture logic; do I have to define a new test fixture class for each of them? This seems pretty tedious. + +You don't have to. Instead of + +```c++ +class FooTest : public BaseTest {}; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +class BarTest : public BaseTest {}; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +you can simply `typedef` the test fixtures: + +```c++ +typedef BaseTest FooTest; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef BaseTest BarTest; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +## GoogleTest output is buried in a whole bunch of LOG messages. What do I do? + +The GoogleTest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the GoogleTest +output, making it hard to read. However, there is an easy solution to this +problem. + +Since `LOG` messages go to stderr, we decided to let GoogleTest output go to +stdout. This way, you can easily separate the two using redirection. For +example: + +```shell +$ ./my_test > gtest_output.txt +``` + +## Why should I prefer test fixtures over global variables? + +There are several good reasons: + +1. It's likely your test needs to change the states of its global variables. + This makes it difficult to keep side effects from escaping one test and + contaminating others, making debugging difficult. By using fixtures, each + test has a fresh set of variables that's different (but with the same + names). Thus, tests are kept independent of each other. +2. Global variables pollute the global namespace. +3. Test fixtures can be reused via subclassing, which cannot be done easily + with global variables. This is useful if many test suites have something in + common. + +## What can the statement argument in ASSERT_DEATH() be? + +`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used +wherever *`statement`* is valid. So basically *`statement`* can be any C++ +statement that makes sense in the current context. In particular, it can +reference global and/or local variables, and can be: + +* a simple function call (often the case), +* a complex expression, or +* a compound statement. + +Some examples are shown here: + +```c++ +// A death test can be a simple function call. +TEST(MyDeathTest, FunctionCall) { + ASSERT_DEATH(Xyz(5), "Xyz failed"); +} + +// Or a complex expression that references variables and functions. +TEST(MyDeathTest, ComplexExpression) { + const bool c = Condition(); + ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), + "(Func1|Method) failed"); +} + +// Death assertions can be used anywhere in a function. In +// particular, they can be inside a loop. +TEST(MyDeathTest, InsideLoop) { + // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. + for (int i = 0; i < 5; i++) { + EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", + ::testing::Message() << "where i is " << i); + } +} + +// A death assertion can contain a compound statement. +TEST(MyDeathTest, CompoundStatement) { + // Verifies that at lease one of Bar(0), Bar(1), ..., and + // Bar(4) dies. + ASSERT_DEATH({ + for (int i = 0; i < 5; i++) { + Bar(i); + } + }, + "Bar has \\d+ errors"); +} +``` + +## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? + +GoogleTest needs to be able to create objects of your test fixture class, so it +must have a default constructor. Normally the compiler will define one for you. +However, there are cases where you have to define your own: + +* If you explicitly declare a non-default constructor for class `FooTest` + (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a + default constructor, even if it would be empty. +* If `FooTest` has a const non-static data member, then you have to define the + default constructor *and* initialize the const member in the initializer + list of the constructor. (Early versions of `gcc` doesn't force you to + initialize the const member. It's a bug that has been fixed in `gcc 4`.) + +## Why does ASSERT_DEATH complain about previous threads that were already joined? + +With the Linux pthread library, there is no turning back once you cross the line +from a single thread to multiple threads. The first time you create a thread, a +manager thread is created in addition, so you get 3, not 2, threads. Later when +the thread you create joins the main thread, the thread count decrements by 1, +but the manager thread will never be killed, so you still have 2 threads, which +means you cannot safely run a death test. + +The new NPTL thread library doesn't suffer from this problem, as it doesn't +create a manager thread. However, if you don't control which machine your test +runs on, you shouldn't depend on this. + +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named `*DeathTest` when it uses `ASSERT_DEATH`? + +GoogleTest does not interleave tests from different test suites. That is, it +runs all tests in one test suite first, and then runs all tests in the next test +suite, and so on. GoogleTest does this because it needs to set up a test suite +before the first test in it is run, and tear it down afterwards. Splitting up +the test case would require multiple set-up and tear-down processes, which is +inefficient and makes the semantics unclean. + +If we were to determine the order of tests based on test name instead of test +case name, then we would have a problem with the following situation: + +```c++ +TEST_F(FooTest, AbcDeathTest) { ... } +TEST_F(FooTest, Uvw) { ... } + +TEST_F(BarTest, DefDeathTest) { ... } +TEST_F(BarTest, Xyz) { ... } +``` + +Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't +interleave tests from different test suites, we need to run all tests in the +`FooTest` case before running any test in the `BarTest` case. This contradicts +with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. + +## But I don't like calling my entire test suite `*DeathTest` when it contains both death tests and non-death tests. What do I do? + +You don't have to, but if you like, you may split up the test suite into +`FooTest` and `FooDeathTest`, where the names make it clear that they are +related: + +```c++ +class FooTest : public ::testing::Test { ... }; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +using FooDeathTest = FooTest; + +TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } +TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } +``` + +## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? + +Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` +makes it harder to search for real problems in the parent's log. Therefore, +GoogleTest only prints them when the death test has failed. + +If you really need to see such LOG messages, a workaround is to temporarily +break the death test (e.g. by changing the regex pattern it is expected to +match). Admittedly, this is a hack. We'll consider a more permanent solution +after the fork-and-exec-style death tests are implemented. + +## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives? + +If you use a user-defined type `FooType` in an assertion, you must make sure +there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function +defined such that we can print a value of `FooType`. + +In addition, if `FooType` is declared in a name space, the `<<` operator also +needs to be defined in the *same* name space. See +[Tip of the Week #49](https://abseil.io/tips/49) for details. + +## How do I suppress the memory leak messages on Windows? + +Since the statically initialized GoogleTest singleton requires allocations on +the heap, the Visual C++ memory leak detector will report memory leaks at the +end of the program run. The easiest way to avoid this is to use the +`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any +statically initialized heap objects. See MSDN for more details and additional +heap check/debug routines. + +## How can my code detect if it is running in a test? + +If you write code that sniffs whether it's running in a test and does different +things accordingly, you are leaking test-only logic into production code and +there is no easy way to ensure that the test-only code paths aren't run by +mistake in production. Such cleverness also leads to +[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly +advise against the practice, and GoogleTest doesn't provide a way to do it. + +In general, the recommended way to cause the code to behave differently under +test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject +different functionality from the test and from the production code. Since your +production code doesn't link in the for-test logic at all (the +[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure +that), there is no danger in accidentally running it. + +However, if you *really*, *really*, *really* have no choice, and if you follow +the rule of ending your test program names with `_test`, you can use the +*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know +whether the code is under test. + +## How do I temporarily disable a test? + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag. + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? + +Yes. + +The rule is **all test methods in the same test suite must use the same fixture +class**. This means that the following is **allowed** because both tests use the +same fixture class (`::testing::Test`). + +```c++ +namespace foo { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` + +However, the following code is **not allowed** and will produce a runtime error +from GoogleTest because the test methods are using different test fixture +classes with the same test suite name. + +```c++ +namespace foo { +class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_cheat_sheet.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_cheat_sheet.md new file mode 100644 index 0000000000000000000000000000000000000000..ddafaaa2206cd618225109c6e422803a214e6b94 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_cheat_sheet.md @@ -0,0 +1,241 @@ +# gMock Cheat Sheet + +## Defining a Mock Class + +### Mocking a Normal Class {#MockClass} + +Given + +```cpp +class Foo { + public: + virtual ~Foo(); + virtual int GetSize() const = 0; + virtual string Describe(const char* name) = 0; + virtual string Describe(int type) = 0; + virtual bool Process(Bar elem, int count) = 0; +}; +``` + +(note that `~Foo()` **must** be virtual) we can define its mock as + +```cpp +#include + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(string, Describe, (const char* name), (override)); + MOCK_METHOD(string, Describe, (int type), (override)); + MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); +}; +``` + +To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, +which warns on all uninteresting calls, or a "strict" mock, which treats them as +failures: + +```cpp +using ::testing::NiceMock; +using ::testing::NaggyMock; +using ::testing::StrictMock; + +NiceMock nice_foo; // The type is a subclass of MockFoo. +NaggyMock naggy_foo; // The type is a subclass of MockFoo. +StrictMock strict_foo; // The type is a subclass of MockFoo. +``` + +{: .callout .note} +**Note:** A mock object is currently naggy by default. We may make it nice by +default in the future. + +### Mocking a Class Template {#MockTemplate} + +Class templates can be mocked just like any class. + +To mock + +```cpp +template +class StackInterface { + public: + virtual ~StackInterface(); + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; +``` + +(note that all member functions that are mocked, including `~StackInterface()` +**must** be virtual). + +```cpp +template +class MockStack : public StackInterface { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Specifying Calling Conventions for Mock Functions + +If your mock function doesn't use the default calling convention, you can +specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. +For example, + +```cpp + MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); + MOCK_METHOD(int, Bar, (double x, double y), + (const, Calltype(STDMETHODCALLTYPE))); +``` + +where `STDMETHODCALLTYPE` is defined by `` on Windows. + +## Using Mocks in Tests {#UsingMocks} + +The typical work flow is: + +1. Import the gMock names you need to use. All gMock symbols are in the + `testing` namespace unless they are macros or otherwise noted. +2. Create the mock objects. +3. Optionally, set the default actions of the mock objects. +4. Set your expectations on the mock objects (How will they be called? What + will they do?). +5. Exercise code that uses the mock objects; if necessary, check the result + using googletest assertions. +6. When a mock object is destructed, gMock automatically verifies that all + expectations on it have been satisfied. + +Here's an example: + +```cpp +using ::testing::Return; // #1 + +TEST(BarTest, DoesThis) { + MockFoo foo; // #2 + + ON_CALL(foo, GetSize()) // #3 + .WillByDefault(Return(1)); + // ... other default actions ... + + EXPECT_CALL(foo, Describe(5)) // #4 + .Times(3) + .WillRepeatedly(Return("Category 5")); + // ... other expectations ... + + EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 +} // #6 +``` + +## Setting Default Actions {#OnCall} + +gMock has a **built-in default action** for any function that returns `void`, +`bool`, a numeric value, or a pointer. In C++11, it will additionally returns +the default-constructed value, if one exists for the given type. + +To customize the default action for functions with return type `T`, use +[`DefaultValue`](reference/mocking.md#DefaultValue). For example: + +```cpp + // Sets the default action for return type std::unique_ptr to + // creating a new Buzz every time. + DefaultValue>::SetFactory( + [] { return std::make_unique(AccessLevel::kInternal); }); + + // When this fires, the default action of MakeBuzz() will run, which + // will return a new Buzz object. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); + + auto buzz1 = mock_buzzer_.MakeBuzz("hello"); + auto buzz2 = mock_buzzer_.MakeBuzz("hello"); + EXPECT_NE(buzz1, nullptr); + EXPECT_NE(buzz2, nullptr); + EXPECT_NE(buzz1, buzz2); + + // Resets the default action for return type std::unique_ptr, + // to avoid interfere with other tests. + DefaultValue>::Clear(); +``` + +To customize the default action for a particular method of a specific mock +object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar +syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you +do not require that the mock method is called. See +[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed +discussion. + +## Setting Expectations {#ExpectCall} + +See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference. + +## Matchers {#MatcherList} + +See the [Matchers Reference](reference/matchers.md). + +## Actions {#ActionList} + +See the [Actions Reference](reference/actions.md). + +## Cardinalities {#CardinalityList} + +See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of +`EXPECT_CALL` in the Mocking Reference. + +## Expectation Order + +By default, expectations can be matched in *any* order. If some or all +expectations must be matched in a given order, you can use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) or +[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of +`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence). + +## Verifying and Resetting a Mock + +gMock will verify the expectations on a mock object when it is destructed, or +you can do it earlier: + +```cpp +using ::testing::Mock; +... +// Verifies and removes the expectations on mock_obj; +// returns true if and only if successful. +Mock::VerifyAndClearExpectations(&mock_obj); +... +// Verifies and removes the expectations on mock_obj; +// also removes the default actions set by ON_CALL(); +// returns true if and only if successful. +Mock::VerifyAndClear(&mock_obj); +``` + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +You can also tell gMock that a mock object can be leaked and doesn't need to be +verified: + +```cpp +Mock::AllowLeak(&mock_obj); +``` + +## Mock Classes + +gMock defines a convenient mock class template + +```cpp +class MockFunction { + public: + MOCK_METHOD(R, Call, (A1, ..., An)); +}; +``` + +See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of +it. + +## Flags + +| Flag | Description | +| :----------------------------- | :---------------------------------------- | +| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | +| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_cook_book.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_cook_book.md new file mode 100644 index 0000000000000000000000000000000000000000..f1b10b472d27dfa398113dca09ab26415d7dfb2f --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_cook_book.md @@ -0,0 +1,4379 @@ +# gMock Cookbook + +You can find recipes for using gMock here. If you haven't yet, please read +[the dummy guide](gmock_for_dummies.md) first to make sure you understand the +basics. + +{: .callout .note} +**Note:** gMock lives in the `testing` name space. For readability, it is +recommended to write `using ::testing::Foo;` once in your file before using the +name `Foo` defined by gMock. We omit such `using` statements in this section for +brevity, but you should do it in your own code. + +## Creating Mock Classes + +Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to +generate mocked methods. The macro gets 3 or 4 parameters: + +```cpp +class MyMock { + public: + MOCK_METHOD(ReturnType, MethodName, (Args...)); + MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...)); +}; +``` + +The first 3 parameters are simply the method declaration, split into 3 parts. +The 4th parameter accepts a closed list of qualifiers, which affect the +generated method: + +* **`const`** - Makes the mocked method a `const` method. Required if + overriding a `const` method. +* **`override`** - Marks the method with `override`. Recommended if overriding + a `virtual` method. +* **`noexcept`** - Marks the method with `noexcept`. Required if overriding a + `noexcept` method. +* **`Calltype(...)`** - Sets the call type for the method (e.g. to + `STDMETHODCALLTYPE`), useful in Windows. +* **`ref(...)`** - Marks the method with the reference qualification + specified. Required if overriding a method that has reference + qualifications. Eg `ref(&)` or `ref(&&)`. + +### Dealing with unprotected commas + +Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent +`MOCK_METHOD` from parsing its arguments correctly: + +{: .bad} +```cpp +class MockFoo { + public: + MOCK_METHOD(std::pair, GetPair, ()); // Won't compile! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Won't compile! +}; +``` + +Solution 1 - wrap with parentheses: + +{: .good} +```cpp +class MockFoo { + public: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); +}; +``` + +Note that wrapping a return or argument type with parentheses is, in general, +invalid C++. `MOCK_METHOD` removes the parentheses. + +Solution 2 - define an alias: + +{: .good} +```cpp +class MockFoo { + public: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +### Mocking Private or Protected Methods + +You must always put a mock method definition (`MOCK_METHOD`) in a `public:` +section of the mock class, regardless of the method being mocked being `public`, +`protected`, or `private` in the base class. This allows `ON_CALL` and +`EXPECT_CALL` to reference the mock function from outside of the mock class. +(Yes, C++ allows a subclass to change the access level of a virtual function in +the base class.) Example: + +```cpp +class Foo { + public: + ... + virtual bool Transform(Gadget* g) = 0; + + protected: + virtual void Resume(); + + private: + virtual int GetTimeOut(); +}; + +class MockFoo : public Foo { + public: + ... + MOCK_METHOD(bool, Transform, (Gadget* g), (override)); + + // The following must be in the public section, even though the + // methods are protected or private in the base class. + MOCK_METHOD(void, Resume, (), (override)); + MOCK_METHOD(int, GetTimeOut, (), (override)); +}; +``` + +### Mocking Overloaded Methods + +You can mock overloaded functions as usual. No special attention is required: + +```cpp +class Foo { + ... + + // Must be virtual as we'll inherit from Foo. + virtual ~Foo(); + + // Overloaded on the types and/or numbers of arguments. + virtual int Add(Element x); + virtual int Add(int times, Element x); + + // Overloaded on the const-ness of this object. + virtual Bar& GetBar(); + virtual const Bar& GetBar() const; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(int, Add, (Element x), (override)); + MOCK_METHOD(int, Add, (int times, Element x), (override)); + + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; +``` + +{: .callout .note} +**Note:** if you don't mock all versions of the overloaded method, the compiler +will give you a warning about some methods in the base class being hidden. To +fix that, use `using` to bring them in scope: + +```cpp +class MockFoo : public Foo { + ... + using Foo::Add; + MOCK_METHOD(int, Add, (Element x), (override)); + // We don't want to mock int Add(int times, Element x); + ... +}; +``` + +### Mocking Class Templates + +You can mock class templates just like any class. + +```cpp +template +class StackInterface { + ... + // Must be virtual as we'll inherit from StackInterface. + virtual ~StackInterface(); + + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; + +template +class MockStack : public StackInterface { + ... + MOCK_METHOD(int, GetSize, (), (override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Mocking Non-virtual Methods {#MockingNonVirtualMethods} + +gMock can mock non-virtual functions to be used in Hi-perf dependency injection. + +In this case, instead of sharing a common base class with the real class, your +mock class will be *unrelated* to the real class, but contain methods with the +same signatures. The syntax for mocking non-virtual methods is the *same* as +mocking virtual methods (just don't add `override`): + +```cpp +// A simple packet stream class. None of its members is virtual. +class ConcretePacketStream { + public: + void AppendPacket(Packet* new_packet); + const Packet* GetPacket(size_t packet_number) const; + size_t NumberOfPackets() const; + ... +}; + +// A mock packet stream class. It inherits from no other, but defines +// GetPacket() and NumberOfPackets(). +class MockPacketStream { + public: + MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const)); + MOCK_METHOD(size_t, NumberOfPackets, (), (const)); + ... +}; +``` + +Note that the mock class doesn't define `AppendPacket()`, unlike the real class. +That's fine as long as the test doesn't need to call it. + +Next, you need a way to say that you want to use `ConcretePacketStream` in +production code, and use `MockPacketStream` in tests. Since the functions are +not virtual and the two classes are unrelated, you must specify your choice at +*compile time* (as opposed to run time). + +One way to do it is to templatize your code that needs to use a packet stream. +More specifically, you will give your code a template type argument for the type +of the packet stream. In production, you will instantiate your template with +`ConcretePacketStream` as the type argument. In tests, you will instantiate the +same template with `MockPacketStream`. For example, you may write: + +```cpp +template +void CreateConnection(PacketStream* stream) { ... } + +template +class PacketReader { + public: + void ReadPackets(PacketStream* stream, size_t packet_num); +}; +``` + +Then you can use `CreateConnection()` and +`PacketReader` in production code, and use +`CreateConnection()` and `PacketReader` in +tests. + +```cpp + MockPacketStream mock_stream; + EXPECT_CALL(mock_stream, ...)...; + .. set more expectations on mock_stream ... + PacketReader reader(&mock_stream); + ... exercise reader ... +``` + +### Mocking Free Functions + +It is not possible to directly mock a free function (i.e. a C-style function or +a static method). If you need to, you can rewrite your code to use an interface +(abstract class). + +Instead of calling a free function (say, `OpenFile`) directly, introduce an +interface for it and have a concrete subclass that calls the free function: + +```cpp +class FileInterface { + public: + ... + virtual bool Open(const char* path, const char* mode) = 0; +}; + +class File : public FileInterface { + public: + ... + bool Open(const char* path, const char* mode) override { + return OpenFile(path, mode); + } +}; +``` + +Your code should talk to `FileInterface` to open a file. Now it's easy to mock +out the function. + +This may seem like a lot of hassle, but in practice you often have multiple +related functions that you can put in the same interface, so the per-function +syntactic overhead will be much lower. + +If you are concerned about the performance overhead incurred by virtual +functions, and profiling confirms your concern, you can combine this with the +recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). + +Alternatively, instead of introducing a new interface, you can rewrite your code +to accept a std::function instead of the free function, and then use +[MockFunction](#MockFunction) to mock the std::function. + +### Old-Style `MOCK_METHODn` Macros + +Before the generic `MOCK_METHOD` macro +[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2), +mocks where created using a family of macros collectively called `MOCK_METHODn`. +These macros are still supported, though migration to the new `MOCK_METHOD` is +recommended. + +The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: + +* The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`, + instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`. +* The number `n` must equal the number of arguments. +* When mocking a const method, one must use `MOCK_CONST_METHODn`. +* When mocking a class template, the macro name must be suffixed with `_T`. +* In order to specify the call type, the macro name must be suffixed with + `_WITH_CALLTYPE`, and the call type is the first macro argument. + +Old macros and their new equivalents: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Simple
OldMOCK_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method
OldMOCK_CONST_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method in a Class Template
OldMOCK_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method in a Class Template
OldMOCK_CONST_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method with Call Type
OldMOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type
OldMOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
Method with Call Type in a Class Template
OldMOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type in a Class Template
OldMOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
+ +### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} + +If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an +"uninteresting call", and the default action (which can be specified using +`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will +also by default cause gMock to print a warning. + +However, sometimes you may want to ignore these uninteresting calls, and +sometimes you may want to treat them as errors. gMock lets you make the decision +on a per-mock-object basis. + +Suppose your test uses a mock class `MockFoo`: + +```cpp +TEST(...) { + MockFoo mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +If a method of `mock_foo` other than `DoThis()` is called, you will get a +warning. However, if you rewrite your test to use `NiceMock` instead, +you can suppress the warning: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +`NiceMock` is a subclass of `MockFoo`, so it can be used wherever +`MockFoo` is accepted. + +It also works if `MockFoo`'s constructor takes some arguments, as +`NiceMock` "inherits" `MockFoo`'s constructors: + +```cpp +using ::testing::NiceMock; + +TEST(...) { + NiceMock mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... +} +``` + +The usage of `StrictMock` is similar, except that it makes all uninteresting +calls failures: + +```cpp +using ::testing::StrictMock; + +TEST(...) { + StrictMock mock_foo; + EXPECT_CALL(mock_foo, DoThis()); + ... code that uses mock_foo ... + + // The test will fail if a method of mock_foo other than DoThis() + // is called. +} +``` + +{: .callout .note} +NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of +*methods* with no expectations); they do not affect *unexpected* calls (calls of +methods with expectations, but they don't match). See +[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected). + +There are some caveats though (sadly they are side effects of C++'s +limitations): + +1. `NiceMock` and `StrictMock` only work for mock methods + defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class. + If a mock method is defined in a **base class** of `MockFoo`, the "nice" or + "strict" modifier may not affect it, depending on the compiler. In + particular, nesting `NiceMock` and `StrictMock` (e.g. + `NiceMock >`) is **not** supported. +2. `NiceMock` and `StrictMock` may not work correctly if the + destructor of `MockFoo` is not virtual. We would like to fix this, but it + requires cleaning up existing tests. + +Finally, you should be **very cautious** about when to use naggy or strict +mocks, as they tend to make tests more brittle and harder to maintain. When you +refactor your code without changing its externally visible behavior, ideally you +shouldn't need to update any tests. If your code interacts with a naggy mock, +however, you may start to get spammed with warnings as the result of your +change. Worse, if your code interacts with a strict mock, your tests may start +to fail and you'll be forced to fix them. Our general recommendation is to use +nice mocks (not yet the default) most of the time, use naggy mocks (the current +default) when developing or debugging tests, and use strict mocks only as the +last resort. + +### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} + +Sometimes a method has a long list of arguments that is mostly uninteresting. +For example: + +```cpp +class LogSink { + public: + ... + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const struct tm* tm_time, + const char* message, size_t message_len) = 0; +}; +``` + +This method's argument list is lengthy and hard to work with (the `message` +argument is not even 0-terminated). If we mock it as is, using the mock will be +awkward. If, however, we try to simplify this interface, we'll need to fix all +clients depending on it, which is often infeasible. + +The trick is to redispatch the method in the mock class: + +```cpp +class ScopedMockLog : public LogSink { + public: + ... + void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, const tm* tm_time, + const char* message, size_t message_len) override { + // We are only interested in the log severity, full file name, and + // log message. + Log(severity, full_filename, std::string(message, message_len)); + } + + // Implements the mock method: + // + // void Log(LogSeverity severity, + // const string& file_path, + // const string& message); + MOCK_METHOD(void, Log, + (LogSeverity severity, const string& file_path, + const string& message)); +}; +``` + +By defining a new mock method with a trimmed argument list, we make the mock +class more user-friendly. + +This technique may also be applied to make overloaded methods more amenable to +mocking. For example, when overloads have been used to implement default +arguments: + +```cpp +class MockTurtleFactory : public TurtleFactory { + public: + Turtle* MakeTurtle(int length, int weight) override { ... } + Turtle* MakeTurtle(int length, int weight, int speed) override { ... } + + // the above methods delegate to this one: + MOCK_METHOD(Turtle*, DoMakeTurtle, ()); +}; +``` + +This allows tests that don't care which overload was invoked to avoid specifying +argument matchers: + +```cpp +ON_CALL(factory, DoMakeTurtle) + .WillByDefault(Return(MakeMockTurtle())); +``` + +### Alternative to Mocking Concrete Classes + +Often you may find yourself using classes that don't implement interfaces. In +order to test your code that uses such a class (let's call it `Concrete`), you +may be tempted to make the methods of `Concrete` virtual and then mock it. + +Try not to do that. + +Making a non-virtual function virtual is a big decision. It creates an extension +point where subclasses can tweak your class' behavior. This weakens your control +on the class because now it's harder to maintain the class invariants. You +should make a function virtual only when there is a valid reason for a subclass +to override it. + +Mocking concrete classes directly is problematic as it creates a tight coupling +between the class and the tests - any small change in the class may invalidate +your tests and make test maintenance a pain. + +To avoid such problems, many programmers have been practicing "coding to +interfaces": instead of talking to the `Concrete` class, your code would define +an interface and talk to it. Then you implement that interface as an adaptor on +top of `Concrete`. In tests, you can easily mock that interface to observe how +your code is doing. + +This technique incurs some overhead: + +* You pay the cost of virtual function calls (usually not a problem). +* There is more abstraction for the programmers to learn. + +However, it can also bring significant benefits in addition to better +testability: + +* `Concrete`'s API may not fit your problem domain very well, as you may not + be the only client it tries to serve. By designing your own interface, you + have a chance to tailor it to your need - you may add higher-level + functionalities, rename stuff, etc instead of just trimming the class. This + allows you to write your code (user of the interface) in a more natural way, + which means it will be more readable, more maintainable, and you'll be more + productive. +* If `Concrete`'s implementation ever has to change, you don't have to rewrite + everywhere it is used. Instead, you can absorb the change in your + implementation of the interface, and your other code and tests will be + insulated from this change. + +Some people worry that if everyone is practicing this technique, they will end +up writing lots of redundant code. This concern is totally understandable. +However, there are two reasons why it may not be the case: + +* Different projects may need to use `Concrete` in different ways, so the best + interfaces for them will be different. Therefore, each of them will have its + own domain-specific interface on top of `Concrete`, and they will not be the + same code. +* If enough projects want to use the same interface, they can always share it, + just like they have been sharing `Concrete`. You can check in the interface + and the adaptor somewhere near `Concrete` (perhaps in a `contrib` + sub-directory) and let many projects use it. + +You need to weigh the pros and cons carefully for your particular problem, but +I'd like to assure you that the Java community has been practicing this for a +long time and it's a proven effective technique applicable in a wide variety of +situations. :-) + +### Delegating Calls to a Fake {#DelegatingToFake} + +Some times you have a non-trivial fake implementation of an interface. For +example: + +```cpp +class Foo { + public: + virtual ~Foo() {} + virtual char DoThis(int n) = 0; + virtual void DoThat(const char* s, int* p) = 0; +}; + +class FakeFoo : public Foo { + public: + char DoThis(int n) override { + return (n > 0) ? '+' : + (n < 0) ? '-' : '0'; + } + + void DoThat(const char* s, int* p) override { + *p = strlen(s); + } +}; +``` + +Now you want to mock this interface such that you can set expectations on it. +However, you also want to use `FakeFoo` for the default behavior, as duplicating +it in the mock object is, well, a lot of work. + +When you define the mock class using gMock, you can have it delegate its default +action to a fake class you already have, using this pattern: + +```cpp +class MockFoo : public Foo { + public: + // Normal mock method definitions using gMock. + MOCK_METHOD(char, DoThis, (int n), (override)); + MOCK_METHOD(void, DoThat, (const char* s, int* p), (override)); + + // Delegates the default actions of the methods to a FakeFoo object. + // This must be called *before* the custom ON_CALL() statements. + void DelegateToFake() { + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return fake_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + fake_.DoThat(s, p); + }); + } + + private: + FakeFoo fake_; // Keeps an instance of the fake in the mock. +}; +``` + +With that, you can use `MockFoo` in your tests as usual. Just remember that if +you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the +fake will be called upon to do it.: + +```cpp +using ::testing::_; + +TEST(AbcTest, Xyz) { + MockFoo foo; + + foo.DelegateToFake(); // Enables the fake for delegation. + + // Put your ON_CALL(foo, ...)s here, if any. + + // No action specified, meaning to use the default action. + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(foo, DoThat(_, _)); + + int n = 0; + EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked. + foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. + EXPECT_EQ(n, 2); +} +``` + +**Some tips:** + +* If you want, you can still override the default action by providing your own + `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. +* In `DelegateToFake()`, you only need to delegate the methods whose fake + implementation you intend to use. + +* The general technique discussed here works for overloaded methods, but + you'll need to tell the compiler which version you mean. To disambiguate a + mock function (the one you specify inside the parentheses of `ON_CALL()`), + use [this technique](#SelectOverload); to disambiguate a fake function (the + one you place inside `Invoke()`), use a `static_cast` to specify the + function's type. For instance, if class `Foo` has methods `char DoThis(int + n)` and `bool DoThis(double x) const`, and you want to invoke the latter, + you need to write `Invoke(&fake_, static_cast(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` + (The strange-looking thing inside the angled brackets of `static_cast` is + the type of a function pointer to the second `DoThis()` method.). + +* Having to mix a mock and a fake is often a sign of something gone wrong. + Perhaps you haven't got used to the interaction-based way of testing yet. Or + perhaps your interface is taking on too many roles and should be split up. + Therefore, **don't abuse this**. We would only recommend to do it as an + intermediate step when you are refactoring your code. + +Regarding the tip on mixing a mock and a fake, here's an example on why it may +be a bad sign: Suppose you have a class `System` for low-level system +operations. In particular, it does file and I/O operations. And suppose you want +to test how your code uses `System` to do I/O, and you just want the file +operations to work normally. If you mock out the entire `System` class, you'll +have to provide a fake implementation for the file operation part, which +suggests that `System` is taking on too many roles. + +Instead, you can define a `FileOps` interface and an `IOOps` interface and split +`System`'s functionalities into the two. Then you can mock `IOOps` without +mocking `FileOps`. + +### Delegating Calls to a Real Object + +When using testing doubles (mocks, fakes, stubs, and etc), sometimes their +behaviors will differ from those of the real objects. This difference could be +either intentional (as in simulating an error such that you can test the error +handling code) or unintentional. If your mocks have different behaviors than the +real objects by mistake, you could end up with code that passes the tests but +fails in production. + +You can use the *delegating-to-real* technique to ensure that your mock has the +same behavior as the real object while retaining the ability to validate calls. +This technique is very similar to the [delegating-to-fake](#DelegatingToFake) +technique, the difference being that we use a real object instead of a fake. +Here's an example: + +```cpp +using ::testing::AtLeast; + +class MockFoo : public Foo { + public: + MockFoo() { + // By default, all calls are delegated to the real object. + ON_CALL(*this, DoThis).WillByDefault([this](int n) { + return real_.DoThis(n); + }); + ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { + real_.DoThat(s, p); + }); + ... + } + MOCK_METHOD(char, DoThis, ...); + MOCK_METHOD(void, DoThat, ...); + ... + private: + Foo real_; +}; + +... + MockFoo mock; + EXPECT_CALL(mock, DoThis()) + .Times(3); + EXPECT_CALL(mock, DoThat("Hi")) + .Times(AtLeast(1)); + ... use mock in test ... +``` + +With this, gMock will verify that your code made the right calls (with the right +arguments, in the right order, called the right number of times, etc), and a +real object will answer the calls (so the behavior will be the same as in +production). This gives you the best of both worlds. + +### Delegating Calls to a Parent Class + +Ideally, you should code to interfaces, whose methods are all pure virtual. In +reality, sometimes you do need to mock a virtual method that is not pure (i.e, +it already has an implementation). For example: + +```cpp +class Foo { + public: + virtual ~Foo(); + + virtual void Pure(int n) = 0; + virtual int Concrete(const char* str) { ... } +}; + +class MockFoo : public Foo { + public: + // Mocking a pure method. + MOCK_METHOD(void, Pure, (int n), (override)); + // Mocking a concrete method. Foo::Concrete() is shadowed. + MOCK_METHOD(int, Concrete, (const char* str), (override)); +}; +``` + +Sometimes you may want to call `Foo::Concrete()` instead of +`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or +perhaps your test doesn't need to mock `Concrete()` at all (but it would be +oh-so painful to have to define a new mock class whenever you don't need to mock +one of its methods). + +You can call `Foo::Concrete()` inside an action by: + +```cpp +... + EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +or tell the mock object that you don't want to mock `Concrete()`: + +```cpp +... + ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) { + return foo.Foo::Concrete(str); + }); +``` + +(Why don't we just write `{ return foo.Concrete(str); }`? If you do that, +`MockFoo::Concrete()` will be called (and cause an infinite recursion) since +`Foo::Concrete()` is virtual. That's just how C++ works.) + +## Using Matchers + +### Matching Argument Values Exactly + +You can specify exactly which arguments a mock method is expecting: + +```cpp +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(5)) + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", bar)); +``` + +### Using Simple Matchers + +You can use matchers to match arguments that have a certain property: + +```cpp +using ::testing::NotNull; +using ::testing::Return; +... + EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. + .WillOnce(Return('a')); + EXPECT_CALL(foo, DoThat("Hello", NotNull())); + // The second argument must not be NULL. +``` + +A frequently used matcher is `_`, which matches anything: + +```cpp + EXPECT_CALL(foo, DoThat(_, NotNull())); +``` + +### Combining Matchers {#CombiningMatchers} + +You can build complex matchers from existing ones using `AllOf()`, +`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`: + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::HasSubstr; +using ::testing::Ne; +using ::testing::Not; +... + // The argument must be > 5 and != 10. + EXPECT_CALL(foo, DoThis(AllOf(Gt(5), + Ne(10)))); + + // The first argument must not contain sub-string "blah". + EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), + NULL)); +``` + +Matchers are function objects, and parametrized matchers can be composed just +like any other function. However because their types can be long and rarely +provide meaningful information, it can be easier to express them with C++14 +generic lambdas to avoid specifying types. For example, + +```cpp +using ::testing::Contains; +using ::testing::Property; + +inline constexpr auto HasFoo = [](const auto& f) { + return Property("foo", &MyClass::foo, Contains(f)); +}; +... + EXPECT_THAT(x, HasFoo("blah")); +``` + +### Casting Matchers {#SafeMatcherCast} + +gMock matchers are statically typed, meaning that the compiler can catch your +mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` +to match a `string` argument). Good for you! + +Sometimes, however, you know what you're doing and want the compiler to give you +some slack. One example is that you have a matcher for `long` and the argument +you want to match is `int`. While the two types aren't exactly the same, there +is nothing really wrong with using a `Matcher` to match an `int` - after +all, we can first convert the `int` argument to a `long` losslessly before +giving it to the matcher. + +To support this need, gMock gives you the `SafeMatcherCast(m)` function. It +casts a matcher `m` to type `Matcher`. To ensure safety, gMock checks that +(let `U` be the type `m` accepts : + +1. Type `T` can be *implicitly* cast to type `U`; +2. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and + floating-point numbers), the conversion from `T` to `U` is not lossy (in + other words, any value representable by `T` can also be represented by `U`); + and +3. When `U` is a reference, `T` must also be a reference (as the underlying + matcher may be interested in the address of the `U` value). + +The code won't compile if any of these conditions isn't met. + +Here's one example: + +```cpp +using ::testing::SafeMatcherCast; + +// A base class and a child class. +class Base { ... }; +class Derived : public Base { ... }; + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, DoThis, (Derived* derived), (override)); +}; + +... + MockFoo foo; + // m is a Matcher we got from somewhere. + EXPECT_CALL(foo, DoThis(SafeMatcherCast(m))); +``` + +If you find `SafeMatcherCast(m)` too limiting, you can use a similar function +`MatcherCast(m)`. The difference is that `MatcherCast` works as long as you +can `static_cast` type `T` to type `U`. + +`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't +always safe as it could throw away information, for example), so be careful not +to misuse/abuse it. + +### Selecting Between Overloaded Functions {#SelectOverload} + +If you expect an overloaded function to be called, the compiler may need some +help on which overloaded version it is. + +To disambiguate functions overloaded on the const-ness of this object, use the +`Const()` argument wrapper. + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + ... + MOCK_METHOD(Bar&, GetBar, (), (override)); + MOCK_METHOD(const Bar&, GetBar, (), (const, override)); +}; + +... + MockFoo foo; + Bar bar1, bar2; + EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). + .WillOnce(ReturnRef(bar1)); + EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). + .WillOnce(ReturnRef(bar2)); +``` + +(`Const()` is defined by gMock and returns a `const` reference to its argument.) + +To disambiguate overloaded functions with the same number of arguments but +different argument types, you may need to specify the exact type of a matcher, +either by wrapping your matcher in `Matcher()`, or using a matcher whose +type is fixed (`TypedEq`, `An()`, etc): + +```cpp +using ::testing::An; +using ::testing::Matcher; +using ::testing::TypedEq; + +class MockPrinter : public Printer { + public: + MOCK_METHOD(void, Print, (int n), (override)); + MOCK_METHOD(void, Print, (char c), (override)); +}; + +TEST(PrinterTest, Print) { + MockPrinter printer; + + EXPECT_CALL(printer, Print(An())); // void Print(int); + EXPECT_CALL(printer, Print(Matcher(Lt(5)))); // void Print(int); + EXPECT_CALL(printer, Print(TypedEq('a'))); // void Print(char); + + printer.Print(3); + printer.Print(6); + printer.Print('a'); +} +``` + +### Performing Different Actions Based on the Arguments + +When a mock method is called, the *last* matching expectation that's still +active will be selected (think "newer overrides older"). So, you can make a +method do different things depending on its argument values like this: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... + // The default case. + EXPECT_CALL(foo, DoThis(_)) + .WillRepeatedly(Return('b')); + // The more specific case. + EXPECT_CALL(foo, DoThis(Lt(5))) + .WillRepeatedly(Return('a')); +``` + +Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be +returned; otherwise `'b'` will be returned. + +### Matching Multiple Arguments as a Whole + +Sometimes it's not enough to match the arguments individually. For example, we +may want to say that the first argument must be less than the second argument. +The `With()` clause allows us to match all arguments of a mock function as a +whole. For example, + +```cpp +using ::testing::_; +using ::testing::Ne; +using ::testing::Lt; +... + EXPECT_CALL(foo, InRange(Ne(0), _)) + .With(Lt()); +``` + +says that the first argument of `InRange()` must not be 0, and must be less than +the second argument. + +The expression inside `With()` must be a matcher of type `Matcher>`, where `A1`, ..., `An` are the types of the function arguments. + +You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms +are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. + +You can use `Args(m)` to match the `n` selected arguments (as a +tuple) against `m`. For example, + +```cpp +using ::testing::_; +using ::testing::AllOf; +using ::testing::Args; +using ::testing::Lt; +... + EXPECT_CALL(foo, Blah) + .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); +``` + +says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y < +z`. Note that in this example, it wasn't necessary to specify the positional +matchers. + +As a convenience and example, gMock provides some matchers for 2-tuples, +including the `Lt()` matcher above. See +[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the +complete list. + +Note that if you want to pass the arguments to a predicate of your own (e.g. +`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to +take a `std::tuple` as its argument; gMock will pass the `n` selected arguments +as *one* single tuple to the predicate. + +### Using Matchers as Predicates + +Have you noticed that a matcher is just a fancy predicate that also knows how to +describe itself? Many existing algorithms take predicates as arguments (e.g. +those defined in STL's `` header), and it would be a shame if gMock +matchers were not allowed to participate. + +Luckily, you can use a matcher where a unary predicate functor is expected by +wrapping it inside the `Matches()` function. For example, + +```cpp +#include +#include + +using ::testing::Matches; +using ::testing::Ge; + +vector v; +... +// How many elements in v are >= 10? +const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); +``` + +Since you can build complex matchers from simpler ones easily using gMock, this +gives you a way to conveniently construct composite predicates (doing the same +using STL's `` header is just painful). For example, here's a +predicate that's satisfied by any number that is >= 0, <= 100, and != 50: + +```cpp +using ::testing::AllOf; +using ::testing::Ge; +using ::testing::Le; +using ::testing::Matches; +using ::testing::Ne; +... +Matches(AllOf(Ge(0), Le(100), Ne(50))) +``` + +### Using Matchers in googletest Assertions + +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. + +### Using Predicates as Matchers + +gMock provides a set of built-in matchers for matching arguments with expected +values—see the [Matchers Reference](reference/matchers.md) for more information. +In case you find the built-in set lacking, you can use an arbitrary unary +predicate function or functor as a matcher - as long as the predicate accepts a +value of the type you want. You do this by wrapping the predicate inside the +`Truly()` function, for example: + +```cpp +using ::testing::Truly; + +int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } +... + // Bar() must be called with an even number. + EXPECT_CALL(foo, Bar(Truly(IsEven))); +``` + +Note that the predicate function / functor doesn't have to return `bool`. It +works as long as the return value can be used as the condition in the statement +`if (condition) ...`. + +### Matching Arguments that Are Not Copyable + +When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of +`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with +the saved copy of `bar`. This way, you don't need to worry about `bar` being +modified or destroyed after the `EXPECT_CALL()` is executed. The same is true +when you use matchers like `Eq(bar)`, `Le(bar)`, and so on. + +But what if `bar` cannot be copied (i.e. has no copy constructor)? You could +define your own matcher function or callback and use it with `Truly()`, as the +previous couple of recipes have shown. Or, you may be able to get away from it +if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is +executed. Just tell gMock that it should save a reference to `bar`, instead of a +copy of it. Here's how: + +```cpp +using ::testing::Eq; +using ::testing::Lt; +... + // Expects that Foo()'s argument == bar. + EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar)))); + + // Expects that Foo()'s argument < bar. + EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar)))); +``` + +Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the +result is undefined. + +### Validating a Member of an Object + +Often a mock function takes a reference to object as an argument. When matching +the argument, you may not want to compare the entire object against a fixed +object, as that may be over-specification. Instead, you may need to validate a +certain member variable or the result of a certain getter method of the object. +You can do this with `Field()` and `Property()`. More specifically, + +```cpp +Field(&Foo::bar, m) +``` + +is a matcher that matches a `Foo` object whose `bar` member variable satisfies +matcher `m`. + +```cpp +Property(&Foo::baz, m) +``` + +is a matcher that matches a `Foo` object whose `baz()` method returns a value +that satisfies matcher `m`. + +For example: + +| Expression | Description | +| :--------------------------- | :--------------------------------------- | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | + +Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument +and be declared as `const`. Don't use `Property()` against member functions that +you do not own, because taking addresses of functions is fragile and generally +not part of the contract of the function. + +`Field()` and `Property()` can also match plain pointers to objects. For +instance, + +```cpp +using ::testing::Field; +using ::testing::Ge; +... +Field(&Foo::number, Ge(3)) +``` + +matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match +will always fail regardless of the inner matcher. + +What if you want to validate more than one members at the same time? Remember +that there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers). + +Finally `Field()` and `Property()` provide overloads that take the field or +property names as the first argument to include it in the error message. This +can be useful when creating combined matchers. + +```cpp +using ::testing::AllOf; +using ::testing::Field; +using ::testing::Matcher; +using ::testing::SafeMatcherCast; + +Matcher IsFoo(const Foo& foo) { + return AllOf(Field("some_field", &Foo::some_field, foo.some_field), + Field("other_field", &Foo::other_field, foo.other_field), + Field("last_field", &Foo::last_field, foo.last_field)); +} +``` + +### Validating the Value Pointed to by a Pointer Argument + +C++ functions often take pointers as arguments. You can use matchers like +`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but +what if you want to make sure the value *pointed to* by the pointer, instead of +the pointer itself, has a certain property? Well, you can use the `Pointee(m)` +matcher. + +`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer +points to. For example: + +```cpp +using ::testing::Ge; +using ::testing::Pointee; +... + EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); +``` + +expects `foo.Bar()` to be called with a pointer that points to a value greater +than or equal to 3. + +One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match +failure, so you can write `Pointee(m)` instead of + +```cpp +using ::testing::AllOf; +using ::testing::NotNull; +using ::testing::Pointee; +... + AllOf(NotNull(), Pointee(m)) +``` + +without worrying that a `NULL` pointer will crash your test. + +Also, did we tell you that `Pointee()` works with both raw pointers **and** +smart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)? + +What if you have a pointer to pointer? You guessed it - you can use nested +`Pointee()` to probe deeper inside the value. For example, +`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points +to a number less than 3 (what a mouthful...). + +### Defining a Custom Matcher Class {#CustomMatcherClass} + +Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers), +which are terse and flexible, and produce good error messages. However, these +macros are not very explicit about the interfaces they create and are not always +suitable, especially for matchers that will be widely reused. + +For more advanced cases, you may need to define your own matcher class. A custom +matcher allows you to test a specific invariant property of that object. Let's +take a look at how to do so. + +Imagine you have a mock function that takes an object of type `Foo`, which has +an `int bar()` method and an `int baz()` method. You want to constrain that the +argument's `bar()` value plus its `baz()` value is a given number. (This is an +invariant.) Here's how we can write and use a matcher class to do so: + +```cpp +class BarPlusBazEqMatcher { + public: + using is_gtest_matcher = void; + + explicit BarPlusBazEqMatcher(int expected_sum) + : expected_sum_(expected_sum) {} + + bool MatchAndExplain(const Foo& foo, + std::ostream* /* listener */) const { + return (foo.bar() + foo.baz()) == expected_sum_; + } + + void DescribeTo(std::ostream* os) const { + *os << "bar() + baz() equals " << expected_sum_; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "bar() + baz() does not equal " << expected_sum_; + } + private: + const int expected_sum_; +}; + +::testing::Matcher BarPlusBazEq(int expected_sum) { + return BarPlusBazEqMatcher(expected_sum); +} + +... + Foo foo; + EXPECT_THAT(foo, BarPlusBazEq(5))...; +``` + +### Matching Containers + +Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock +function and you may want to validate it. Since most STL containers support the +`==` operator, you can write `Eq(expected_container)` or simply +`expected_container` to match a container exactly. + +Sometimes, though, you may want to be more flexible (for example, the first +element must be an exact match, but the second element can be any positive +number, and so on). Also, containers used in tests often have a small number of +elements, and having to define the expected container out-of-line is a bit of a +hassle. + +You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such +cases: + +```cpp +using ::testing::_; +using ::testing::ElementsAre; +using ::testing::Gt; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); +``` + +The above matcher says that the container must have 4 elements, which must be 1, +greater than 0, anything, and 5 respectively. + +If you instead write: + +```cpp +using ::testing::_; +using ::testing::Gt; +using ::testing::UnorderedElementsAre; +... + MOCK_METHOD(void, Foo, (const vector& numbers), (override)); +... + EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); +``` + +It means that the container must have 4 elements, which (under some permutation) +must be 1, greater than 0, anything, and 5 respectively. + +As an alternative you can place the arguments in a C-style array and use +`ElementsAreArray()` or `UnorderedElementsAreArray()` instead: + +```cpp +using ::testing::ElementsAreArray; +... + // ElementsAreArray accepts an array of element values. + const int expected_vector1[] = {1, 5, 2, 4, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); + + // Or, an array of element matchers. + Matcher expected_vector2[] = {1, Gt(2), _, 3, ...}; + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); +``` + +In case the array needs to be dynamically created (and therefore the array size +cannot be inferred by the compiler), you can give `ElementsAreArray()` an +additional argument to specify the array size: + +```cpp +using ::testing::ElementsAreArray; +... + int* const expected_vector3 = new int[count]; + ... fill expected_vector3 with values ... + EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); +``` + +Use `Pair` when comparing maps or other associative containers. + +{% raw %} + +```cpp +using ::testing::UnorderedElementsAre; +using ::testing::Pair; +... + absl::flat_hash_map m = {{"a", 1}, {"b", 2}, {"c", 3}}; + EXPECT_THAT(m, UnorderedElementsAre( + Pair("a", 1), Pair("b", 2), Pair("c", 3))); +``` + +{% endraw %} + +**Tips:** + +* `ElementsAre*()` can be used to match *any* container that implements the + STL iterator pattern (i.e. it has a `const_iterator` type and supports + `begin()/end()`), not just the ones defined in STL. It will even work with + container types yet to be written - as long as they follows the above + pattern. +* You can use nested `ElementsAre*()` to match nested (multi-dimensional) + containers. +* If the container is passed by pointer instead of by reference, just write + `Pointee(ElementsAre*(...))`. +* The order of elements *matters* for `ElementsAre*()`. If you are using it + with containers whose element order are undefined (such as a + `std::unordered_map`) you should use `UnorderedElementsAre`. + +### Sharing Matchers + +Under the hood, a gMock matcher object consists of a pointer to a ref-counted +implementation object. Copying matchers is allowed and very efficient, as only +the pointer is copied. When the last matcher that references the implementation +object dies, the implementation object will be deleted. + +Therefore, if you have some complex matcher that you want to use again and +again, there is no need to build it every time. Just assign it to a matcher +variable and use that variable repeatedly! For example, + +```cpp +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Le; +using ::testing::Matcher; +... + Matcher in_range = AllOf(Gt(5), Le(10)); + ... use in_range as a matcher in multiple EXPECT_CALLs ... +``` + +### Matchers must have no side-effects {#PureMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be *purely functional*: they cannot have +any side effects, and the match result must not depend on anything other than +the matcher's parameters and the value being matched. + +This requirement must be satisfied no matter how a matcher is defined (e.g., if +it is one of the standard matchers, or a custom matcher). In particular, a +matcher can never call a mock function, as that will affect the state of the +mock object and gMock. + +## Setting Expectations + +### Knowing When to Expect {#UseOnCall} + +**`ON_CALL`** is likely the *single most under-utilized construct* in gMock. + +There are basically two constructs for defining the behavior of a mock object: +`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when +a mock method is called, but doesn't imply any expectation on the method +being called. `EXPECT_CALL` not only defines the behavior, but also sets an +expectation that the method will be called with the given arguments, for the +given number of times (and *in the given order* when you specify the order +too). + +Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every +`EXPECT_CALL` adds a constraint on the behavior of the code under test. Having +more constraints than necessary is *baaad* - even worse than not having enough +constraints. + +This may be counter-intuitive. How could tests that verify more be worse than +tests that verify less? Isn't verification the whole point of tests? + +The answer lies in *what* a test should verify. **A good test verifies the +contract of the code.** If a test over-specifies, it doesn't leave enough +freedom to the implementation. As a result, changing the implementation without +breaking the contract (e.g. refactoring and optimization), which should be +perfectly fine to do, can break such tests. Then you have to spend time fixing +them, only to see them broken again the next time the implementation is changed. + +Keep in mind that one doesn't have to verify more than one property in one test. +In fact, **it's a good style to verify only one thing in one test.** If you do +that, a bug will likely break only one or two tests instead of dozens (which +case would you rather debug?). If you are also in the habit of giving tests +descriptive names that tell what they verify, you can often easily guess what's +wrong just from the test log itself. + +So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend +to verify that the call is made. For example, you may have a bunch of `ON_CALL`s +in your test fixture to set the common mock behavior shared by all tests in the +same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s +to verify different aspects of the code's behavior. Compared with the style +where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more +resilient to implementational changes (and thus less likely to require +maintenance) and makes the intent of the tests more obvious (so they are easier +to maintain when you do need to maintain them). + +If you are bothered by the "Uninteresting mock function call" message printed +when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` +instead to suppress all such messages for the mock object, or suppress the +message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO +NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test +that's a pain to maintain. + +### Ignoring Uninteresting Calls + +If you are not interested in how a mock method is called, just don't say +anything about it. In this case, if the method is ever called, gMock will +perform its default action to allow the test program to continue. If you are not +happy with the default action taken by gMock, you can override it using +`DefaultValue::Set()` (described [here](#DefaultValue)) or `ON_CALL()`. + +Please note that once you expressed interest in a particular mock method (via +`EXPECT_CALL()`), all invocations to it must match some expectation. If this +function is called but the arguments don't match any `EXPECT_CALL()` statement, +it will be an error. + +### Disallowing Unexpected Calls + +If a mock method shouldn't be called at all, explicitly say so: + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +If some calls to the method are allowed, but the rest are not, just list all the +expected calls: + +```cpp +using ::testing::AnyNumber; +using ::testing::Gt; +... + EXPECT_CALL(foo, Bar(5)); + EXPECT_CALL(foo, Bar(Gt(10))) + .Times(AnyNumber()); +``` + +A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements +will be an error. + +### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} + +*Uninteresting* calls and *unexpected* calls are different concepts in gMock. +*Very* different. + +A call `x.Y(...)` is **uninteresting** if there's *not even a single* +`EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the +`x.Y()` method at all, as evident in that the test doesn't care to say anything +about it. + +A call `x.Y(...)` is **unexpected** if there are *some* `EXPECT_CALL(x, +Y(...))`s set, but none of them matches the call. Put another way, the test is +interested in the `x.Y()` method (therefore it explicitly sets some +`EXPECT_CALL` to verify how it's called); however, the verification fails as the +test doesn't expect this particular call to happen. + +**An unexpected call is always an error,** as the code under test doesn't behave +the way the test expects it to behave. + +**By default, an uninteresting call is not an error,** as it violates no +constraint specified by the test. (gMock's philosophy is that saying nothing +means there is no constraint.) However, it leads to a warning, as it *might* +indicate a problem (e.g. the test author might have forgotten to specify a +constraint). + +In gMock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or +"strict". How does this affect uninteresting calls and unexpected calls? + +A **nice mock** suppresses uninteresting call *warnings*. It is less chatty than +the default mock, but otherwise is the same. If a test fails with a default +mock, it will also fail using a nice mock instead. And vice versa. Don't expect +making a mock nice to change the test's result. + +A **strict mock** turns uninteresting call warnings into errors. So making a +mock strict may change the test's result. + +Let's look at an example: + +```cpp +TEST(...) { + NiceMock mock_registry; + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); + + // Use mock_registry in code under test. + ... &mock_registry ... +} +``` + +The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have +`"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it +will be an unexpected call, and thus an error. *Having a nice mock doesn't +change the severity of an unexpected call.* + +So how do we tell gMock that `GetDomainOwner()` can be called with some other +arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: + +```cpp + EXPECT_CALL(mock_registry, GetDomainOwner(_)) + .Times(AnyNumber()); // catches all other calls to this method. + EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) + .WillRepeatedly(Return("Larry Page")); +``` + +Remember that `_` is the wildcard matcher that matches anything. With this, if +`GetDomainOwner("google.com")` is called, it will do what the second +`EXPECT_CALL` says; if it is called with a different argument, it will do what +the first `EXPECT_CALL` says. + +Note that the order of the two `EXPECT_CALL`s is important, as a newer +`EXPECT_CALL` takes precedence over an older one. + +For more on uninteresting calls, nice mocks, and strict mocks, read +["The Nice, the Strict, and the Naggy"](#NiceStrictNaggy). + +### Ignoring Uninteresting Arguments {#ParameterlessExpectations} + +If your test doesn't care about the parameters (it only cares about the number +or order of calls), you can often simply omit the parameter list: + +```cpp + // Expect foo.Bar( ... ) twice with any arguments. + EXPECT_CALL(foo, Bar).Times(2); + + // Delegate to the given method whenever the factory is invoked. + ON_CALL(foo_factory, MakeFoo) + .WillByDefault(&BuildFooForTest); +``` + +This functionality is only available when a method is not overloaded; to prevent +unexpected behavior it is a compilation error to try to set an expectation on a +method where the specific overload is ambiguous. You can work around this by +supplying a [simpler mock interface](#SimplerInterfaces) than the mocked class +provides. + +This pattern is also useful when the arguments are interesting, but match logic +is substantially complex. You can leave the argument list unspecified and use +SaveArg actions to [save the values for later verification](#SaveArgVerify). If +you do that, you can easily differentiate calling the method the wrong number of +times from calling it with the wrong arguments. + +### Expecting Ordered Calls {#OrderedCalls} + +Although an `EXPECT_CALL()` statement defined later takes precedence when gMock +tries to match a function call with an expectation, by default calls don't have +to happen in the order `EXPECT_CALL()` statements are written. For example, if +the arguments match the matchers in the second `EXPECT_CALL()`, but not those in +the first and third, then the second expectation will be used. + +If you would rather have all calls occur in the order of the expectations, put +the `EXPECT_CALL()` statements in a block where you define a variable of type +`InSequence`: + +```cpp +using ::testing::_; +using ::testing::InSequence; + + { + InSequence s; + + EXPECT_CALL(foo, DoThis(5)); + EXPECT_CALL(bar, DoThat(_)) + .Times(2); + EXPECT_CALL(foo, DoThis(6)); + } +``` + +In this example, we expect a call to `foo.DoThis(5)`, followed by two calls to +`bar.DoThat()` where the argument can be anything, which are in turn followed by +a call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an +error. + +### Expecting Partially Ordered Calls {#PartialOrder} + +Sometimes requiring everything to occur in a predetermined order can lead to +brittle tests. For example, we may care about `A` occurring before both `B` and +`C`, but aren't interested in the relative order of `B` and `C`. In this case, +the test should reflect our real intent, instead of being overly constraining. + +gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the +calls. One way to express the DAG is to use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`. + +Another way is via the `InSequence()` clause (not the same as the `InSequence` +class), which we borrowed from jMock 2. It's less flexible than `After()`, but +more convenient when you have long chains of sequential calls, as it doesn't +require you to come up with different names for the expectations in the chains. +Here's how it works: + +If we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from +node A to node B wherever A must occur before B, we can get a DAG. We use the +term "sequence" to mean a directed path in this DAG. Now, if we decompose the +DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` +belongs to in order to be able to reconstruct the original DAG. + +So, to specify the partial order on the expectations we need to do two things: +first to define some `Sequence` objects, and then for each `EXPECT_CALL()` say +which `Sequence` objects it is part of. + +Expectations in the same sequence must occur in the order they are written. For +example, + +```cpp +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(foo, A()) + .InSequence(s1, s2); + EXPECT_CALL(bar, B()) + .InSequence(s1); + EXPECT_CALL(bar, C()) + .InSequence(s2); + EXPECT_CALL(foo, D()) + .InSequence(s2); +``` + +specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): + +```text + +---> B + | + A ---| + | + +---> C ---> D +``` + +This means that A must occur before B and C, and C must occur before D. There's +no restriction about the order other than these. + +### Controlling When an Expectation Retires + +When a mock method is called, gMock only considers expectations that are still +active. An expectation is active when created, and becomes inactive (aka +*retires*) when a call that has to occur later has occurred. For example, in + +```cpp +using ::testing::_; +using ::testing::Sequence; +... + Sequence s1, s2; + + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 + .Times(AnyNumber()) + .InSequence(s1, s2); + EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 + .InSequence(s1); + EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 + .InSequence(s2); +``` + +as soon as either #2 or #3 is matched, #1 will retire. If a warning `"File too +large."` is logged after this, it will be an error. + +Note that an expectation doesn't retire automatically when it's saturated. For +example, + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 +``` + +says that there will be exactly one warning with the message `"File too +large."`. If the second warning contains this message too, #2 will match again +and result in an upper-bound-violated error. + +If this is not what you want, you can ask an expectation to retire as soon as it +becomes saturated: + +```cpp +using ::testing::_; +... + EXPECT_CALL(log, Log(WARNING, _, _)); // #1 + EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 + .RetiresOnSaturation(); +``` + +Here #2 can be used only once, so if you have two warnings with the message +`"File too large."`, the first will match #2 and the second will match #1 - +there will be no error. + +## Using Actions + +### Returning References from Mock Methods + +If a mock function's return type is a reference, you need to use `ReturnRef()` +instead of `Return()` to return a result: + +```cpp +using ::testing::ReturnRef; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar&, GetBar, (), (override)); +}; +... + MockFoo foo; + Bar bar; + EXPECT_CALL(foo, GetBar()) + .WillOnce(ReturnRef(bar)); +... +``` + +### Returning Live Values from Mock Methods + +The `Return(x)` action saves a copy of `x` when the action is created, and +always returns the same value whenever it's executed. Sometimes you may want to +instead return the *live* value of `x` (i.e. its value at the time when the +action is *executed*.). Use either `ReturnRef()` or `ReturnPointee()` for this +purpose. + +If the mock function's return type is a reference, you can do it using +`ReturnRef(x)`, as shown in the previous recipe ("Returning References from Mock +Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function +whose return type is not a reference, as doing that usually indicates a user +error. So, what shall you do? + +Though you may be tempted, DO NOT use `std::ref()`: + +```cpp +using ::testing::Return; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetValue, (), (override)); +}; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(Return(std::ref(x))); // Wrong! + x = 42; + EXPECT_EQ(foo.GetValue(), 42); +``` + +Unfortunately, it doesn't work here. The above code will fail with error: + +```text +Value of: foo.GetValue() + Actual: 0 +Expected: 42 +``` + +The reason is that `Return(*value*)` converts `value` to the actual return type +of the mock function at the time when the action is *created*, not when it is +*executed*. (This behavior was chosen for the action to be safe when `value` is +a proxy object that references some temporary objects.) As a result, +`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when +the expectation is set, and `Return(std::ref(x))` will always return 0. + +`ReturnPointee(pointer)` was provided to solve this problem specifically. It +returns the value pointed to by `pointer` at the time the action is *executed*: + +```cpp +using ::testing::ReturnPointee; +... + int x = 0; + MockFoo foo; + EXPECT_CALL(foo, GetValue()) + .WillRepeatedly(ReturnPointee(&x)); // Note the & here. + x = 42; + EXPECT_EQ(foo.GetValue(), 42); // This will succeed now. +``` + +### Combining Actions + +Want to do more than one thing when a function is called? That's fine. `DoAll()` +allows you to do a sequence of actions every time. Only the return value of the +last action in the sequence will be used. + +```cpp +using ::testing::_; +using ::testing::DoAll; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, Bar, (int n), (override)); +}; +... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(DoAll(action_1, + action_2, + ... + action_n)); +``` + +The return value of the last action **must** match the return type of the mocked +method. In the example above, `action_n` could be `Return(true)`, or a lambda +that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the +signature of `DoAll` would not match the signature expected by `WillOnce`, which +is the signature of the mocked method, and it wouldn't compile. + +### Verifying Complex Arguments {#SaveArgVerify} + +If you want to verify that a method is called with a particular argument but the +match criteria is complex, it can be difficult to distinguish between +cardinality failures (calling the method the wrong number of times) and argument +match failures. Similarly, if you are matching multiple parameters, it may not +be easy to distinguishing which argument failed to match. For example: + +```cpp + // Not ideal: this could fail because of a problem with arg1 or arg2, or maybe + // just the method wasn't called. + EXPECT_CALL(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... ))); +``` + +You can instead save the arguments and test them individually: + +```cpp + EXPECT_CALL(foo, SendValues) + .WillOnce(DoAll(SaveArg<1>(&actual_array), SaveArg<2>(&actual_proto))); + ... run the test + EXPECT_THAT(actual_array, ElementsAre(1, 4, 4, 7)); + EXPECT_THAT(actual_proto, EqualsProto( ... )); +``` + +### Mocking Side Effects {#MockingSideEffects} + +Sometimes a method exhibits its effect not via returning a value but via side +effects. For example, it may change some global state or modify an output +argument. To mock side effects, in general you can define your own action by +implementing `::testing::ActionInterface`. + +If all you need to do is to change an output argument, the built-in +`SetArgPointee()` action is convenient: + +```cpp +using ::testing::_; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + MOCK_METHOD(void, Mutate, (bool mutate, int* value), (override)); + ... +} +... + MockMutator mutator; + EXPECT_CALL(mutator, Mutate(true, _)) + .WillOnce(SetArgPointee<1>(5)); +``` + +In this example, when `mutator.Mutate()` is called, we will assign 5 to the +`int` variable pointed to by argument #1 (0-based). + +`SetArgPointee()` conveniently makes an internal copy of the value you pass to +it, removing the need to keep the value in scope and alive. The implication +however is that the value must have a copy constructor and assignment operator. + +If the mock method also needs to return a value as well, you can chain +`SetArgPointee()` with `Return()` using `DoAll()`, remembering to put the +`Return()` statement last: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; + +class MockMutator : public Mutator { + public: + ... + MOCK_METHOD(bool, MutateInt, (int* value), (override)); +} +... + MockMutator mutator; + EXPECT_CALL(mutator, MutateInt(_)) + .WillOnce(DoAll(SetArgPointee<0>(5), + Return(true))); +``` + +Note, however, that if you use the `ReturnOKWith()` method, it will override the +values provided by `SetArgPointee()` in the response parameters of your function +call. + +If the output argument is an array, use the `SetArrayArgument(first, last)` +action instead. It copies the elements in source range `[first, last)` to the +array pointed to by the `N`-th (0-based) argument: + +```cpp +using ::testing::NotNull; +using ::testing::SetArrayArgument; + +class MockArrayMutator : public ArrayMutator { + public: + MOCK_METHOD(void, Mutate, (int* values, int num_values), (override)); + ... +} +... + MockArrayMutator mutator; + int values[5] = {1, 2, 3, 4, 5}; + EXPECT_CALL(mutator, Mutate(NotNull(), 5)) + .WillOnce(SetArrayArgument<0>(values, values + 5)); +``` + +This also works when the argument is an output iterator: + +```cpp +using ::testing::_; +using ::testing::SetArrayArgument; + +class MockRolodex : public Rolodex { + public: + MOCK_METHOD(void, GetNames, (std::back_insert_iterator>), + (override)); + ... +} +... + MockRolodex rolodex; + vector names = {"George", "John", "Thomas"}; + EXPECT_CALL(rolodex, GetNames(_)) + .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); +``` + +### Changing a Mock Object's Behavior Based on the State + +If you expect a call to change the behavior of a mock object, you can use +`::testing::InSequence` to specify different behaviors before and after the +call: + +```cpp +using ::testing::InSequence; +using ::testing::Return; + +... + { + InSequence seq; + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(true)); + EXPECT_CALL(my_mock, Flush()); + EXPECT_CALL(my_mock, IsDirty()) + .WillRepeatedly(Return(false)); + } + my_mock.FlushIfDirty(); +``` + +This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called +and return `false` afterwards. + +If the behavior change is more complex, you can store the effects in a variable +and make a mock method get its return value from that variable: + +```cpp +using ::testing::_; +using ::testing::SaveArg; +using ::testing::Return; + +ACTION_P(ReturnPointee, p) { return *p; } +... + int previous_value = 0; + EXPECT_CALL(my_mock, GetPrevValue) + .WillRepeatedly(ReturnPointee(&previous_value)); + EXPECT_CALL(my_mock, UpdateValue) + .WillRepeatedly(SaveArg<0>(&previous_value)); + my_mock.DoSomethingToUpdateValue(); +``` + +Here `my_mock.GetPrevValue()` will always return the argument of the last +`UpdateValue()` call. + +### Setting the Default Value for a Return Type {#DefaultValue} + +If a mock method's return type is a built-in C++ type or pointer, by default it +will return 0 when invoked. Also, in C++ 11 and above, a mock method whose +return type has a default constructor will return a default-constructed value by +default. You only need to specify an action if this default value doesn't work +for you. + +Sometimes, you may want to change this default value, or you may want to specify +a default value for types gMock doesn't know about. You can do this using the +`::testing::DefaultValue` class template: + +```cpp +using ::testing::DefaultValue; + +class MockFoo : public Foo { + public: + MOCK_METHOD(Bar, CalculateBar, (), (override)); +}; + + +... + Bar default_bar; + // Sets the default return value for type Bar. + DefaultValue::Set(default_bar); + + MockFoo foo; + + // We don't need to specify an action here, as the default + // return value works for us. + EXPECT_CALL(foo, CalculateBar()); + + foo.CalculateBar(); // This should return default_bar. + + // Unsets the default return value. + DefaultValue::Clear(); +``` + +Please note that changing the default value for a type can make your tests hard +to understand. We recommend you to use this feature judiciously. For example, +you may want to make sure the `Set()` and `Clear()` calls are right next to the +code that uses your mock. + +### Setting the Default Actions for a Mock Method + +You've learned how to change the default value of a given type. However, this +may be too coarse for your purpose: perhaps you have two mock methods with the +same return type and you want them to have different behaviors. The `ON_CALL()` +macro allows you to customize your mock's behavior at the method level: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +using ::testing::Gt; +using ::testing::Return; +... + ON_CALL(foo, Sign(_)) + .WillByDefault(Return(-1)); + ON_CALL(foo, Sign(0)) + .WillByDefault(Return(0)); + ON_CALL(foo, Sign(Gt(0))) + .WillByDefault(Return(1)); + + EXPECT_CALL(foo, Sign(_)) + .Times(AnyNumber()); + + foo.Sign(5); // This should return 1. + foo.Sign(-9); // This should return -1. + foo.Sign(0); // This should return 0. +``` + +As you may have guessed, when there are more than one `ON_CALL()` statements, +the newer ones in the order take precedence over the older ones. In other words, +the **last** one that matches the function arguments will be used. This matching +order allows you to set up the common behavior in a mock object's constructor or +the test fixture's set-up phase and specialize the mock's behavior later. + +Note that both `ON_CALL` and `EXPECT_CALL` have the same "later statements take +precedence" rule, but they don't interact. That is, `EXPECT_CALL`s have their +own precedence order distinct from the `ON_CALL` precedence order. + +### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} + +If the built-in actions don't suit you, you can use an existing callable +(function, `std::function`, method, functor, lambda) as an action. + +```cpp +using ::testing::_; using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, Sum, (int x, int y), (override)); + MOCK_METHOD(bool, ComplexJob, (int x), (override)); +}; + +int CalculateSum(int x, int y) { return x + y; } +int Sum3(int x, int y, int z) { return x + y + z; } + +class Helper { + public: + bool ComplexJob(int x); +}; + +... + MockFoo foo; + Helper helper; + EXPECT_CALL(foo, Sum(_, _)) + .WillOnce(&CalculateSum) + .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce(Invoke(&helper, &Helper::ComplexJob)) + .WillOnce([] { return true; }) + .WillRepeatedly([](int x) { return x > 0; }); + + foo.Sum(5, 6); // Invokes CalculateSum(5, 6). + foo.Sum(2, 3); // Invokes Sum3(1, 2, 3). + foo.ComplexJob(10); // Invokes helper.ComplexJob(10). + foo.ComplexJob(-1); // Invokes the inline lambda. +``` + +The only requirement is that the type of the function, etc must be *compatible* +with the signature of the mock function, meaning that the latter's arguments (if +it takes any) can be implicitly converted to the corresponding arguments of the +former, and the former's return type can be implicitly converted to that of the +latter. So, you can invoke something whose type is *not* exactly the same as the +mock function, as long as it's safe to do so - nice, huh? + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::Invoke; + ... + ResultCallback* is_ok = ...; + ... Invoke(is_ok) ...; // This works. + + BlockingClosure* done = new BlockingClosure; + ... Invoke(implicit_cast(done)) ...; // The cast is necessary. + ``` + +### Using Functions with Extra Info as Actions + +The function or functor you call using `Invoke()` must have the same number of +arguments as the mock function you use it for. Sometimes you may have a function +that takes more arguments, and you are willing to pass in the extra arguments +yourself to fill the gap. You can do this in gMock using callbacks with +pre-bound arguments. Here's an example: + +```cpp +using ::testing::Invoke; + +class MockFoo : public Foo { + public: + MOCK_METHOD(char, DoThis, (int n), (override)); +}; + +char SignOfSum(int x, int y) { + const int sum = x + y; + return (sum > 0) ? '+' : (sum < 0) ? '-' : '0'; +} + +TEST_F(FooTest, Test) { + MockFoo foo; + + EXPECT_CALL(foo, DoThis(2)) + .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); + EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2). +} +``` + +### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments + +`Invoke()` passes the mock function's arguments to the function, etc being +invoked such that the callee has the full context of the call to work with. If +the invoked function is not interested in some or all of the arguments, it can +simply ignore them. + +Yet, a common pattern is that a test author wants to invoke a function without +the arguments of the mock function. She could do that using a wrapper function +that throws away the arguments before invoking an underlining nullary function. +Needless to say, this can be tedious and obscures the intent of the test. + +There are two solutions to this problem. First, you can pass any callable of +zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like +`Invoke()` except that it doesn't pass the mock function's arguments to the +callee. Here's an example of each: + +```cpp +using ::testing::_; +using ::testing::InvokeWithoutArgs; + +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, ComplexJob, (int n), (override)); +}; + +bool Job1() { ... } +bool Job2(int n, char c) { ... } + +... + MockFoo foo; + EXPECT_CALL(foo, ComplexJob(_)) + .WillOnce([] { Job1(); }); + .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); + + foo.ComplexJob(10); // Invokes Job1(). + foo.ComplexJob(20); // Invokes Job2(5, 'a'). +``` + +Note that: + +* The action takes ownership of the callback and will delete it when the + action itself is destructed. +* If the type of a callback is derived from a base callback type `C`, you need + to implicitly cast it to `C` to resolve the overloading, e.g. + + ```cpp + using ::testing::InvokeWithoutArgs; + ... + ResultCallback* is_ok = ...; + ... InvokeWithoutArgs(is_ok) ...; // This works. + + BlockingClosure* done = ...; + ... InvokeWithoutArgs(implicit_cast(done)) ...; + // The cast is necessary. + ``` + +### Invoking an Argument of the Mock Function + +Sometimes a mock function will receive a function pointer, a functor (in other +words, a "callable") as an argument, e.g. + +```cpp +class MockFoo : public Foo { + public: + MOCK_METHOD(bool, DoThis, (int n, (ResultCallback1* callback)), + (override)); +}; +``` + +and you may want to invoke this callable argument: + +```cpp +using ::testing::_; +... + MockFoo foo; + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(...); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +{: .callout .note} +NOTE: The section below is legacy documentation from before C++ had lambdas: + +Arghh, you need to refer to a mock function argument but C++ has no lambda +(yet), so you have to define your own action. :-( Or do you really? + +Well, gMock has an action to solve *exactly* this problem: + +```cpp +InvokeArgument(arg_1, arg_2, ..., arg_m) +``` + +will invoke the `N`-th (0-based) argument the mock function receives, with +`arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function +pointer, a functor, or a callback. gMock handles them all. + +With that, you could write: + +```cpp +using ::testing::_; +using ::testing::InvokeArgument; +... + EXPECT_CALL(foo, DoThis(_, _)) + .WillOnce(InvokeArgument<1>(5)); + // Will execute callback->Run(5), where callback is the + // second argument DoThis() receives. +``` + +What if the callable takes an argument by reference? No problem - just wrap it +inside `std::ref()`: + +```cpp + ... + MOCK_METHOD(bool, Bar, + ((ResultCallback2* callback)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + Helper helper; + ... + EXPECT_CALL(foo, Bar(_)) + .WillOnce(InvokeArgument<0>(5, std::ref(helper))); + // std::ref(helper) guarantees that a reference to helper, not a copy of + // it, will be passed to the callback. +``` + +What if the callable takes an argument by reference and we do **not** wrap the +argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the +argument, and pass a *reference to the copy*, instead of a reference to the +original value, to the callable. This is especially handy when the argument is a +temporary value: + +```cpp + ... + MOCK_METHOD(bool, DoThat, (bool (*f)(const double& x, const string& s)), + (override)); + ... + using ::testing::_; + using ::testing::InvokeArgument; + ... + MockFoo foo; + ... + EXPECT_CALL(foo, DoThat(_)) + .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); + // Will execute (*f)(5.0, string("Hi")), where f is the function pointer + // DoThat() receives. Note that the values 5.0 and string("Hi") are + // temporary and dead once the EXPECT_CALL() statement finishes. Yet + // it's fine to perform this action later, since a copy of the values + // are kept inside the InvokeArgument action. +``` + +### Ignoring an Action's Result + +Sometimes you have an action that returns *something*, but you need an action +that returns `void` (perhaps you want to use it in a mock function that returns +`void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the +list). `IgnoreResult()` lets you do that. For example: + +```cpp +using ::testing::_; +using ::testing::DoAll; +using ::testing::IgnoreResult; +using ::testing::Return; + +int Process(const MyData& data); +string DoSomething(); + +class MockFoo : public Foo { + public: + MOCK_METHOD(void, Abc, (const MyData& data), (override)); + MOCK_METHOD(bool, Xyz, (), (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, Abc(_)) + // .WillOnce(Invoke(Process)); + // The above line won't compile as Process() returns int but Abc() needs + // to return void. + .WillOnce(IgnoreResult(Process)); + EXPECT_CALL(foo, Xyz()) + .WillOnce(DoAll(IgnoreResult(DoSomething), + // Ignores the string DoSomething() returns. + Return(true))); +``` + +Note that you **cannot** use `IgnoreResult()` on an action that already returns +`void`. Doing so will lead to ugly compiler errors. + +### Selecting an Action's Arguments {#SelectingArgs} + +Say you have a mock function `Foo()` that takes seven arguments, and you have a +custom action that you want to invoke when `Foo()` is called. Trouble is, the +custom action only wants three arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... + MOCK_METHOD(bool, Foo, + (bool visible, const string& name, int x, int y, + (const map>), double& weight, double min_weight, + double max_wight)); +... +bool IsVisibleInQuadrant1(bool visible, int x, int y) { + return visible && x >= 0 && y >= 0; +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( +``` + +To please the compiler God, you need to define an "adaptor" that has the same +signature as `Foo()` and calls the custom action with the right arguments: + +```cpp +using ::testing::_; +using ::testing::Invoke; +... +bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, + const map, double>& weight, + double min_weight, double max_wight) { + return IsVisibleInQuadrant1(visible, x, y); +} +... + EXPECT_CALL(mock, Foo) + .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. +``` + +But isn't this awkward? + +gMock provides a generic *action adaptor*, so you can spend your time minding +more important business than writing your own adaptors. Here's the syntax: + +```cpp +WithArgs(action) +``` + +creates an action that passes the arguments of the mock function at the given +indices (0-based) to the inner `action` and performs it. Using `WithArgs`, our +original example can be written as: + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::WithArgs; +... + EXPECT_CALL(mock, Foo) + .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); // No need to define your own adaptor. +``` + +For better readability, gMock also gives you: + +* `WithoutArgs(action)` when the inner `action` takes *no* argument, and +* `WithArg(action)` (no `s` after `Arg`) when the inner `action` takes + *one* argument. + +As you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for +`WithoutArgs(Invoke(...))`. + +Here are more tips: + +* The inner action used in `WithArgs` and friends does not have to be + `Invoke()` -- it can be anything. +* You can repeat an argument in the argument list if necessary, e.g. + `WithArgs<2, 3, 3, 5>(...)`. +* You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. +* The types of the selected arguments do *not* have to match the signature of + the inner action exactly. It works as long as they can be implicitly + converted to the corresponding arguments of the inner action. For example, + if the 4-th argument of the mock function is an `int` and `my_action` takes + a `double`, `WithArg<4>(my_action)` will work. + +### Ignoring Arguments in Action Functions + +The [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way +to make a mock function and an action with incompatible argument lists fit +together. The downside is that wrapping the action in `WithArgs<...>()` can get +tedious for people writing the tests. + +If you are defining a function (or method, functor, lambda, callback) to be used +with `Invoke*()`, and you are not interested in some of its arguments, an +alternative to `WithArgs` is to declare the uninteresting arguments as `Unused`. +This makes the definition less cluttered and less fragile in case the types of +the uninteresting arguments change. It could also increase the chance the action +function can be reused. For example, given + +```cpp + public: + MOCK_METHOD(double, Foo, double(const string& label, double x, double y), + (override)); + MOCK_METHOD(double, Bar, (int index, double x, double y), (override)); +``` + +instead of + +```cpp +using ::testing::_; +using ::testing::Invoke; + +double DistanceToOriginWithLabel(const string& label, double x, double y) { + return sqrt(x*x + y*y); +} +double DistanceToOriginWithIndex(int index, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOriginWithLabel)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOriginWithIndex)); +``` + +you could write + +```cpp +using ::testing::_; +using ::testing::Invoke; +using ::testing::Unused; + +double DistanceToOrigin(Unused, double x, double y) { + return sqrt(x*x + y*y); +} +... + EXPECT_CALL(mock, Foo("abc", _, _)) + .WillOnce(Invoke(DistanceToOrigin)); + EXPECT_CALL(mock, Bar(5, _, _)) + .WillOnce(Invoke(DistanceToOrigin)); +``` + +### Sharing Actions + +Just like matchers, a gMock action object consists of a pointer to a ref-counted +implementation object. Therefore copying actions is also allowed and very +efficient. When the last action that references the implementation object dies, +the implementation object will be deleted. + +If you have some complex action that you want to use again and again, you may +not have to build it from scratch every time. If the action doesn't have an +internal state (i.e. if it always does the same thing no matter how many times +it has been called), you can assign it to an action variable and use that +variable repeatedly. For example: + +```cpp +using ::testing::Action; +using ::testing::DoAll; +using ::testing::Return; +using ::testing::SetArgPointee; +... + Action set_flag = DoAll(SetArgPointee<0>(5), + Return(true)); + ... use set_flag in .WillOnce() and .WillRepeatedly() ... +``` + +However, if the action has its own state, you may be surprised if you share the +action object. Suppose you have an action factory `IncrementCounter(init)` which +creates an action that increments and returns a counter whose initial value is +`init`, using two actions created from the same expression and using a shared +action will exhibit different behaviors. Example: + +```cpp + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(IncrementCounter(0)); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(IncrementCounter(0)); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 1 - DoThat() uses a different + // counter than DoThis()'s. +``` + +versus + +```cpp +using ::testing::Action; +... + Action increment = IncrementCounter(0); + EXPECT_CALL(foo, DoThis()) + .WillRepeatedly(increment); + EXPECT_CALL(foo, DoThat()) + .WillRepeatedly(increment); + foo.DoThis(); // Returns 1. + foo.DoThis(); // Returns 2. + foo.DoThat(); // Returns 3 - the counter is shared. +``` + +### Testing Asynchronous Behavior + +One oft-encountered problem with gMock is that it can be hard to test +asynchronous behavior. Suppose you had a `EventQueue` class that you wanted to +test, and you created a separate `EventDispatcher` interface so that you could +easily mock it out. However, the implementation of the class fired all the +events on a background thread, which made test timings difficult. You could just +insert `sleep()` statements and hope for the best, but that makes your test +behavior nondeterministic. A better way is to use gMock actions and +`Notification` objects to force your asynchronous test to behave synchronously. + +```cpp +class MockEventDispatcher : public EventDispatcher { + MOCK_METHOD(bool, DispatchEvent, (int32), (override)); +}; + +TEST(EventQueueTest, EnqueueEventTest) { + MockEventDispatcher mock_event_dispatcher; + EventQueue event_queue(&mock_event_dispatcher); + + const int32 kEventId = 321; + absl::Notification done; + EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId)) + .WillOnce([&done] { done.Notify(); }); + + event_queue.EnqueueEvent(kEventId); + done.WaitForNotification(); +} +``` + +In the example above, we set our normal gMock expectations, but then add an +additional action to notify the `Notification` object. Now we can just call +`Notification::WaitForNotification()` in the main thread to wait for the +asynchronous call to finish. After that, our test suite is complete and we can +safely exit. + +{: .callout .note} +Note: this example has a downside: namely, if the expectation is not satisfied, +our test will run forever. It will eventually time-out and fail, but it will +take longer and be slightly harder to debug. To alleviate this problem, you can +use `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`. + +## Misc Recipes on Using gMock + +### Mocking Methods That Use Move-Only Types + +C++11 introduced *move-only types*. A move-only-typed value can be moved from +one object to another, but cannot be copied. `std::unique_ptr` is probably +the most commonly used move-only type. + +Mocking a method that takes and/or returns move-only types presents some +challenges, but nothing insurmountable. This recipe shows you how you can do it. +Note that the support for move-only method arguments was only introduced to +gMock in April 2017; in older code, you may find more complex +[workarounds](#LegacyMoveOnly) for lack of this feature. + +Let’s say we are working on a fictional project that lets one post and share +snippets called “buzzes”. Your code uses these types: + +```cpp +enum class AccessLevel { kInternal, kPublic }; + +class Buzz { + public: + explicit Buzz(AccessLevel access) { ... } + ... +}; + +class Buzzer { + public: + virtual ~Buzzer() {} + virtual std::unique_ptr MakeBuzz(StringPiece text) = 0; + virtual bool ShareBuzz(std::unique_ptr buzz, int64_t timestamp) = 0; + ... +}; +``` + +A `Buzz` object represents a snippet being posted. A class that implements the +`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in +`Buzzer` may return a `unique_ptr` or take a `unique_ptr`. Now we +need to mock `Buzzer` in our tests. + +To mock a method that accepts or returns move-only types, you just use the +familiar `MOCK_METHOD` syntax as usual: + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(std::unique_ptr, MakeBuzz, (StringPiece text), (override)); + MOCK_METHOD(bool, ShareBuzz, (std::unique_ptr buzz, int64_t timestamp), + (override)); +}; +``` + +Now that we have the mock class defined, we can use it in tests. In the +following code examples, we assume that we have defined a `MockBuzzer` object +named `mock_buzzer_`: + +```cpp + MockBuzzer mock_buzzer_; +``` + +First let’s see how we can set expectations on the `MakeBuzz()` method, which +returns a `unique_ptr`. + +As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or +`.WillRepeatedly()` clause), when that expectation fires, the default action for +that method will be taken. Since `unique_ptr<>` has a default constructor that +returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an +action: + +```cpp +using ::testing::IsNull; +... + // Use the default action. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); + + // Triggers the previous EXPECT_CALL. + EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull()); +``` + +If you are not happy with the default action, you can tweak it as usual; see +[Setting Default Actions](#OnCall). + +If you just need to return a move-only value, you can use it in combination with +`WillOnce`. For example: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")) + .WillOnce(Return(std::make_unique(AccessLevel::kInternal))); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello")); +``` + +Quiz time! What do you think will happen if a `Return` action is performed more +than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come +think of it, after the first time the action runs, the source value will be +consumed (since it’s a move-only value), so the next time around, there’s no +value to move from -- you’ll get a run-time error that `Return(std::move(...))` +can only be run once. + +If you need your mock method to do more than just moving a pre-defined value, +remember that you can always use a lambda or a callable object, which can do +pretty much anything you want: + +```cpp + EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) + .WillRepeatedly([](StringPiece text) { + return std::make_unique(AccessLevel::kInternal); + }); + + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); + EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); +``` + +Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be created +and returned. You cannot do this with `Return(std::make_unique<...>(...))`. + +That covers returning move-only values; but how do we work with methods +accepting move-only arguments? The answer is that they work normally, although +some actions will not compile when any of method's arguments are move-only. You +can always use `Return`, or a [lambda or functor](#FunctionsAsActions): + +```cpp + using ::testing::Unused; + + EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); + EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal)), + 0); + + EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( + [](std::unique_ptr buzz, Unused) { return buzz != nullptr; }); + EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); +``` + +Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) +could in principle support move-only arguments, but the support for this is not +implemented yet. If this is blocking you, please file a bug. + +A few actions (e.g. `DoAll`) copy their arguments internally, so they can never +work with non-copyable objects; you'll have to use functors instead. + +#### Legacy workarounds for move-only types {#LegacyMoveOnly} + +Support for move-only function arguments was only introduced to gMock in April +of 2017. In older code, you may encounter the following workaround for the lack +of this feature (it is no longer necessary - we're including it just for +reference): + +```cpp +class MockBuzzer : public Buzzer { + public: + MOCK_METHOD(bool, DoShareBuzz, (Buzz* buzz, Time timestamp)); + bool ShareBuzz(std::unique_ptr buzz, Time timestamp) override { + return DoShareBuzz(buzz.get(), timestamp); + } +}; +``` + +The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call +it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of +setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock +method: + +```cpp + MockBuzzer mock_buzzer_; + EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); + + // When one calls ShareBuzz() on the MockBuzzer like this, the call is + // forwarded to DoShareBuzz(), which is mocked. Therefore this statement + // will trigger the above EXPECT_CALL. + mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal), 0); +``` + +### Making the Compilation Faster + +Believe it or not, the *vast majority* of the time spent on compiling a mock +class is in generating its constructor and destructor, as they perform +non-trivial tasks (e.g. verification of the expectations). What's more, mock +methods with different signatures have different types and thus their +constructors/destructors need to be generated by the compiler separately. As a +result, if you mock many different types of methods, compiling your mock class +can get really slow. + +If you are experiencing slow compilation, you can move the definition of your +mock class' constructor and destructor out of the class body and into a `.cc` +file. This way, even if you `#include` your mock class in N files, the compiler +only needs to generate its constructor and destructor once, resulting in a much +faster compilation. + +Let's illustrate the idea using an example. Here's the definition of a mock +class before applying this recipe: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // Since we don't declare the constructor or the destructor, + // the compiler will generate them in every translation unit + // where this mock class is used. + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +After the change, it would look like: + +```cpp +// File mock_foo.h. +... +class MockFoo : public Foo { + public: + // The constructor and destructor are declared, but not defined, here. + MockFoo(); + virtual ~MockFoo(); + + MOCK_METHOD(int, DoThis, (), (override)); + MOCK_METHOD(bool, DoThat, (const char* str), (override)); + ... more mock methods ... +}; +``` + +and + +```cpp +// File mock_foo.cc. +#include "path/to/mock_foo.h" + +// The definitions may appear trivial, but the functions actually do a +// lot of things through the constructors/destructors of the member +// variables used to implement the mock methods. +MockFoo::MockFoo() {} +MockFoo::~MockFoo() {} +``` + +### Forcing a Verification + +When it's being destroyed, your friendly mock object will automatically verify +that all expectations on it have been satisfied, and will generate googletest +failures if not. This is convenient as it leaves you with one less thing to +worry about. That is, unless you are not sure if your mock object will be +destroyed. + +How could it be that your mock object won't eventually be destroyed? Well, it +might be created on the heap and owned by the code you are testing. Suppose +there's a bug in that code and it doesn't delete the mock object properly - you +could end up with a passing test when there's actually a bug. + +Using a heap checker is a good idea and can alleviate the concern, but its +implementation is not 100% reliable. So, sometimes you do want to *force* gMock +to verify a mock object before it is (hopefully) destructed. You can do this +with `Mock::VerifyAndClearExpectations(&mock_object)`: + +```cpp +TEST(MyServerTest, ProcessesRequest) { + using ::testing::Mock; + + MockFoo* const foo = new MockFoo; + EXPECT_CALL(*foo, ...)...; + // ... other expectations ... + + // server now owns foo. + MyServer server(foo); + server.ProcessRequest(...); + + // In case that server's destructor will forget to delete foo, + // this will verify the expectations anyway. + Mock::VerifyAndClearExpectations(foo); +} // server is destroyed when it goes out of scope here. +``` + +{: .callout .tip} +**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to +indicate whether the verification was successful (`true` for yes), so you can +wrap that function call inside a `ASSERT_TRUE()` if there is no point going +further when the verification has failed. + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +### Using Checkpoints {#UsingCheckPoints} + +Sometimes you might want to test a mock object's behavior in phases whose sizes +are each manageable, or you might want to set more detailed expectations about +which API calls invoke which mock functions. + +A technique you can use is to put the expectations in a sequence and insert +calls to a dummy "checkpoint" function at specific places. Then you can verify +that the mock function calls do happen at the right time. For example, if you +are exercising the code: + +```cpp + Foo(1); + Foo(2); + Foo(3); +``` + +and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but +`Foo(2)` doesn't invoke anything, you can write: + +```cpp +using ::testing::MockFunction; + +TEST(FooTest, InvokesBarCorrectly) { + MyMock mock; + // Class MockFunction has exactly one mock method. It is named + // Call() and has type F. + MockFunction check; + { + InSequence s; + + EXPECT_CALL(mock, Bar("a")); + EXPECT_CALL(check, Call("1")); + EXPECT_CALL(check, Call("2")); + EXPECT_CALL(mock, Bar("a")); + } + Foo(1); + check.Call("1"); + Foo(2); + check.Call("2"); + Foo(3); +} +``` + +The expectation spec says that the first `Bar("a")` call must happen before +checkpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and +nothing should happen between the two checkpoints. The explicit checkpoints make +it clear which `Bar("a")` is called by which call to `Foo()`. + +### Mocking Destructors + +Sometimes you want to make sure a mock object is destructed at the right time, +e.g. after `bar->A()` is called but before `bar->B()` is called. We already know +that you can specify constraints on the [order](#OrderedCalls) of mock function +calls, so all we need to do is to mock the destructor of the mock function. + +This sounds simple, except for one problem: a destructor is a special function +with special syntax and special semantics, and the `MOCK_METHOD` macro doesn't +work for it: + +```cpp +MOCK_METHOD(void, ~MockFoo, ()); // Won't compile! +``` + +The good news is that you can use a simple pattern to achieve the same effect. +First, add a mock function `Die()` to your mock class and call it in the +destructor, like this: + +```cpp +class MockFoo : public Foo { + ... + // Add the following two lines to the mock class. + MOCK_METHOD(void, Die, ()); + ~MockFoo() override { Die(); } +}; +``` + +(If the name `Die()` clashes with an existing symbol, choose another name.) Now, +we have translated the problem of testing when a `MockFoo` object dies to +testing when its `Die()` method is called: + +```cpp + MockFoo* foo = new MockFoo; + MockBar* bar = new MockBar; + ... + { + InSequence s; + + // Expects *foo to die after bar->A() and before bar->B(). + EXPECT_CALL(*bar, A()); + EXPECT_CALL(*foo, Die()); + EXPECT_CALL(*bar, B()); + } +``` + +And that's that. + +### Using gMock and Threads {#UsingThreads} + +In a **unit** test, it's best if you could isolate and test a piece of code in a +single-threaded context. That avoids race conditions and dead locks, and makes +debugging your test much easier. + +Yet most programs are multi-threaded, and sometimes to test something we need to +pound on it from more than one thread. gMock works for this purpose too. + +Remember the steps for using a mock: + +1. Create a mock object `foo`. +2. Set its default actions and expectations using `ON_CALL()` and + `EXPECT_CALL()`. +3. The code under test calls methods of `foo`. +4. Optionally, verify and reset the mock. +5. Destroy the mock yourself, or let the code under test destroy it. The + destructor will automatically verify it. + +If you follow the following simple rules, your mocks and threads can live +happily together: + +* Execute your *test code* (as opposed to the code being tested) in *one* + thread. This makes your test easy to follow. +* Obviously, you can do step #1 without locking. +* When doing step #2 and #5, make sure no other thread is accessing `foo`. + Obvious too, huh? +* #3 and #4 can be done either in one thread or in multiple threads - anyway + you want. gMock takes care of the locking, so you don't have to do any - + unless required by your test logic. + +If you violate the rules (for example, if you set expectations on a mock while +another thread is calling its methods), you get undefined behavior. That's not +fun, so don't do it. + +gMock guarantees that the action for a mock function is done in the same thread +that called the mock function. For example, in + +```cpp + EXPECT_CALL(mock, Foo(1)) + .WillOnce(action1); + EXPECT_CALL(mock, Foo(2)) + .WillOnce(action2); +``` + +if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, gMock will +execute `action1` in thread 1 and `action2` in thread 2. + +gMock does *not* impose a sequence on actions performed in different threads +(doing so may create deadlocks as the actions may need to cooperate). This means +that the execution of `action1` and `action2` in the above example *may* +interleave. If this is a problem, you should add proper synchronization logic to +`action1` and `action2` to make the test thread-safe. + +Also, remember that `DefaultValue` is a global resource that potentially +affects *all* living mock objects in your program. Naturally, you won't want to +mess with it from multiple threads or when there still are mocks in action. + +### Controlling How Much Information gMock Prints + +When gMock sees something that has the potential of being an error (e.g. a mock +function with no expectation is called, a.k.a. an uninteresting call, which is +allowed but perhaps you forgot to explicitly ban the call), it prints some +warning messages, including the arguments of the function, the return value, and +the stack trace. Hopefully this will remind you to take a look and see if there +is indeed a problem. + +Sometimes you are confident that your tests are correct and may not appreciate +such friendly messages. Some other times, you are debugging your tests or +learning about the behavior of the code you are testing, and wish you could +observe every mock call that happens (including argument values, the return +value, and the stack trace). Clearly, one size doesn't fit all. + +You can control how much gMock tells you using the `--gmock_verbose=LEVEL` +command-line flag, where `LEVEL` is a string with three possible values: + +* `info`: gMock will print all informational messages, warnings, and errors + (most verbose). At this setting, gMock will also log any calls to the + `ON_CALL/EXPECT_CALL` macros. It will include a stack trace in + "uninteresting call" warnings. +* `warning`: gMock will print both warnings and errors (less verbose); it will + omit the stack traces in "uninteresting call" warnings. This is the default. +* `error`: gMock will print errors only (least verbose). + +Alternatively, you can adjust the value of that flag from within your tests like +so: + +```cpp + ::testing::FLAGS_gmock_verbose = "error"; +``` + +If you find gMock printing too many stack frames with its informational or +warning messages, remember that you can control their amount with the +`--gtest_stack_trace_depth=max_depth` flag. + +Now, judiciously use the right flag to enable gMock serve you better! + +### Gaining Super Vision into Mock Calls + +You have a test using gMock. It fails: gMock tells you some expectations aren't +satisfied. However, you aren't sure why: Is there a typo somewhere in the +matchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under +test doing something wrong? How can you find out the cause? + +Won't it be nice if you have X-ray vision and can actually see the trace of all +`EXPECT_CALL`s and mock method calls as they are made? For each call, would you +like to see its actual argument values and which `EXPECT_CALL` gMock thinks it +matches? If you still need some help to figure out who made these calls, how +about being able to see the complete stack trace at each mock call? + +You can unlock this power by running your test with the `--gmock_verbose=info` +flag. For example, given the test program: + +```cpp +#include + +using ::testing::_; +using ::testing::HasSubstr; +using ::testing::Return; + +class MockFoo { + public: + MOCK_METHOD(void, F, (const string& x, const string& y)); +}; + +TEST(Foo, Bar) { + MockFoo mock; + EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(mock, F("a", "b")); + EXPECT_CALL(mock, F("c", HasSubstr("d"))); + + mock.F("a", "good"); + mock.F("a", "b"); +} +``` + +if you run it with `--gmock_verbose=info`, you will see this output: + +```shell +[ RUN ] Foo.Bar + +foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked +Stack trace: ... + +foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked +Stack trace: ... + +foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked +Stack trace: ... + +foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... + Function call: F(@0x7fff7c8dad40"a",@0x7fff7c8dad10"good") +Stack trace: ... + +foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... + Function call: F(@0x7fff7c8dada0"a",@0x7fff7c8dad70"b") +Stack trace: ... + +foo_test.cc:16: Failure +Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... + Expected: to be called once + Actual: never called - unsatisfied and active +[ FAILED ] Foo.Bar +``` + +Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo and +should actually be `"a"`. With the above message, you should see that the actual +`F("a", "good")` call is matched by the first `EXPECT_CALL`, not the third as +you thought. From that it should be obvious that the third `EXPECT_CALL` is +written wrong. Case solved. + +If you are interested in the mock call trace but not the stack traces, you can +combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test +command line. + +### Running Tests in Emacs + +If you build and run your tests in Emacs using the `M-x google-compile` command +(as many googletest users do), the source file locations of gMock and googletest +errors will be highlighted. Just press `` on one of them and you'll be +taken to the offending line. Or, you can just type `C-x`` to jump to the next +error. + +To make it even easier, you can add the following lines to your `~/.emacs` file: + +```text +(global-set-key "\M-m" 'google-compile) ; m is for make +(global-set-key [M-down] 'next-error) +(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) +``` + +Then you can type `M-m` to start a build (if you want to run the test as well, +just make sure `foo_test.run` or `runtests` is in the build command you supply +after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. + +## Extending gMock + +### Writing New Matchers Quickly {#NewMatchers} + +{: .callout .warning} +WARNING: gMock does not guarantee when or how many times a matcher will be +invoked. Therefore, all matchers must be functionally pure. See +[this section](#PureMatchers) for more details. + +The `MATCHER*` family of macros can be used to define custom matchers easily. +The syntax: + +```cpp +MATCHER(name, description_string_expression) { statements; } +``` + +will define a matcher with the given name that executes the statements, which +must return a `bool` to indicate if the match succeeds. Inside the statements, +you can refer to the value being matched by `arg`, and refer to its type by +`arg_type`. + +The *description string* is a `string`-typed expression that documents what the +matcher does, and is used to generate the failure message when the match fails. +It can (and should) reference the special `bool` variable `negation`, and should +evaluate to the description of the matcher when `negation` is `false`, or that +of the matcher's negation when `negation` is `true`. + +For convenience, we allow the description string to be empty (`""`), in which +case gMock will use the sequence of words in the matcher name as the +description. + +#### Basic Example + +```cpp +MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } +``` + +allows you to write + +```cpp + // Expects mock_foo.Bar(n) to be called where n is divisible by 7. + EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); +``` + +or, + +```cpp + using ::testing::Not; + ... + // Verifies that a value is divisible by 7 and the other is not. + EXPECT_THAT(some_expression, IsDivisibleBy7()); + EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); +``` + +If the above assertions fail, they will print something like: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 + ... + Value of: some_other_expression + Expected: not (is divisible by 7) + Actual: 21 +``` + +where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are +automatically calculated from the matcher name `IsDivisibleBy7`. + +#### Adding Custom Failure Messages + +As you may have noticed, the auto-generated descriptions (especially those for +the negation) may not be so great. You can always override them with a `string` +expression of your own: + +```cpp +MATCHER(IsDivisibleBy7, + absl::StrCat(negation ? "isn't" : "is", " divisible by 7")) { + return (arg % 7) == 0; +} +``` + +Optionally, you can stream additional information to a hidden argument named +`result_listener` to explain the match result. For example, a better definition +of `IsDivisibleBy7` is: + +```cpp +MATCHER(IsDivisibleBy7, "") { + if ((arg % 7) == 0) + return true; + + *result_listener << "the remainder is " << (arg % 7); + return false; +} +``` + +With this definition, the above assertion will give a better message: + +```shell + Value of: some_expression + Expected: is divisible by 7 + Actual: 27 (the remainder is 6) +``` + +#### Using EXPECT_ Statements in Matchers + +You can also use `EXPECT_...` (and `ASSERT_...`) statements inside custom +matcher definitions. In many cases, this allows you to write your matcher more +concisely while still providing an informative error message. For example: + +```cpp +MATCHER(IsDivisibleBy7, "") { + const auto remainder = arg % 7; + EXPECT_EQ(remainder, 0); + return true; +} +``` + +If you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`, +you will get an error something like the following: + +```shell +Expected equality of these values: + remainder + Which is: 6 + 0 +``` + +#### `MatchAndExplain` + +You should let `MatchAndExplain()` print *any additional information* that can +help a user understand the match result. Note that it should explain why the +match succeeds in case of a success (unless it's obvious) - this is useful when +the matcher is used inside `Not()`. There is no need to print the argument value +itself, as gMock already prints it for you. + +#### Argument Types + +The type of the value being matched (`arg_type`) is determined by the +context in which you use the matcher and is supplied to you by the compiler, so +you don't need to worry about declaring it (nor can you). This allows the +matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match +any type where the value of `(arg % 7) == 0` can be implicitly converted to a +`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an +`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will +be `unsigned long`; and so on. + +### Writing New Parameterized Matchers Quickly + +Sometimes you'll want to define a matcher that has parameters. For that you can +use the macro: + +```cpp +MATCHER_P(name, param_name, description_string) { statements; } +``` + +where the description string can be either `""` or a `string` expression that +references `negation` and `param_name`. + +For example: + +```cpp +MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +``` + +will allow you to write: + +```cpp + EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +``` + +which may lead to this message (assuming `n` is 10): + +```shell + Value of: Blah("a") + Expected: has absolute value 10 + Actual: -9 +``` + +Note that both the matcher description and its parameter are printed, making the +message human-friendly. + +In the matcher definition body, you can write `foo_type` to reference the type +of a parameter named `foo`. For example, in the body of +`MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer +to the type of `value`. + +gMock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to +support multi-parameter matchers: + +```cpp +MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } +``` + +Please note that the custom description string is for a particular *instance* of +the matcher, where the parameters have been bound to actual values. Therefore +usually you'll want the parameter values to be part of the description. gMock +lets you do that by referencing the matcher parameters in the description string +expression. + +For example, + +```cpp +using ::testing::PrintToString; +MATCHER_P2(InClosedRange, low, hi, + absl::StrFormat("%s in range [%s, %s]", negation ? "isn't" : "is", + PrintToString(low), PrintToString(hi))) { + return low <= arg && arg <= hi; +} +... +EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the message: + +```shell + Expected: is in range [4, 6] +``` + +If you specify `""` as the description, the failure message will contain the +sequence of words in the matcher name followed by the parameter values printed +as a tuple. For example, + +```cpp + MATCHER_P2(InClosedRange, low, hi, "") { ... } + ... + EXPECT_THAT(3, InClosedRange(4, 6)); +``` + +would generate a failure that contains the text: + +```shell + Expected: in closed range (4, 6) +``` + +For the purpose of typing, you can view + +```cpp +MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +``` + +as shorthand for + +```cpp +template +FooMatcherPk +Foo(p1_type p1, ..., pk_type pk) { ... } +``` + +When you write `Foo(v1, ..., vk)`, the compiler infers the types of the +parameters `v1`, ..., and `vk` for you. If you are not happy with the result of +the type inference, you can specify the types by explicitly instantiating the +template, as in `Foo(5, false)`. As said earlier, you don't get to +(or need to) specify `arg_type` as that's determined by the context in which the +matcher is used. + +You can assign the result of expression `Foo(p1, ..., pk)` to a variable of type +`FooMatcherPk`. This can be useful when composing +matchers. Matchers that don't have a parameter or have only one parameter have +special types: you can assign `Foo()` to a `FooMatcher`-typed variable, and +assign `Foo(p)` to a `FooMatcherP`-typed variable. + +While you can instantiate a matcher template with reference types, passing the +parameters by pointer usually makes your code more readable. If, however, you +still want to pass a parameter by reference, be aware that in the failure +message generated by the matcher you will see the value of the referenced object +but not its address. + +You can overload matchers with different numbers of parameters: + +```cpp +MATCHER_P(Blah, a, description_string_1) { ... } +MATCHER_P2(Blah, a, b, description_string_2) { ... } +``` + +While it's tempting to always use the `MATCHER*` macros when defining a new +matcher, you should also consider implementing the matcher interface directly +instead (see the recipes that follow), especially if you need to use the matcher +a lot. While these approaches require more work, they give you more control on +the types of the value being matched and the matcher parameters, which in +general leads to better compiler error messages that pay off in the long run. +They also allow overloading matchers based on parameter types (as opposed to +just based on the number of parameters). + +### Writing New Monomorphic Matchers + +A matcher of argument type `T` implements the matcher interface for `T` and does +two things: it tests whether a value of type `T` matches the matcher, and can +describe what kind of values it matches. The latter ability is used for +generating readable error messages when expectations are violated. + +A matcher of `T` must declare a typedef like: + +```cpp +using is_gtest_matcher = void; +``` + +and supports the following operations: + +```cpp +// Match a value and optionally explain into an ostream. +bool matched = matcher.MatchAndExplain(value, maybe_os); +// where `value` is of type `T` and +// `maybe_os` is of type `std::ostream*`, where it can be null if the caller +// is not interested in there textual explanation. + +matcher.DescribeTo(os); +matcher.DescribeNegationTo(os); +// where `os` is of type `std::ostream*`. +``` + +If you need a custom matcher but `Truly()` is not a good option (for example, +you may not be happy with the way `Truly(predicate)` describes itself, or you +may want your matcher to be polymorphic as `Eq(value)` is), you can define a +matcher to do whatever you want in two steps: first implement the matcher +interface, and then define a factory function to create a matcher instance. The +second step is not strictly needed but it makes the syntax of using the matcher +nicer. + +For example, you can define a matcher to test whether an `int` is divisible by 7 +and then use it like this: + +```cpp +using ::testing::Matcher; + +class DivisibleBy7Matcher { + public: + using is_gtest_matcher = void; + + bool MatchAndExplain(int n, std::ostream*) const { + return (n % 7) == 0; + } + + void DescribeTo(std::ostream* os) const { + *os << "is divisible by 7"; + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is not divisible by 7"; + } +}; + +Matcher DivisibleBy7() { + return DivisibleBy7Matcher(); +} + +... + EXPECT_CALL(foo, Bar(DivisibleBy7())); +``` + +You may improve the matcher message by streaming additional information to the +`os` argument in `MatchAndExplain()`: + +```cpp +class DivisibleBy7Matcher { + public: + bool MatchAndExplain(int n, std::ostream* os) const { + const int remainder = n % 7; + if (remainder != 0 && os != nullptr) { + *os << "the remainder is " << remainder; + } + return remainder == 0; + } + ... +}; +``` + +Then, `EXPECT_THAT(x, DivisibleBy7());` may generate a message like this: + +```shell +Value of: x +Expected: is divisible by 7 + Actual: 23 (the remainder is 2) +``` + +{: .callout .tip} +Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*` +instead of `std::ostream*`. + +### Writing New Polymorphic Matchers + +Expanding what we learned above to *polymorphic* matchers is now just as simple +as adding templates in the right place. + +```cpp + +class NotNullMatcher { + public: + using is_gtest_matcher = void; + + // To implement a polymorphic matcher, we just need to make MatchAndExplain a + // template on its first argument. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, std::ostream*) const { + return p != nullptr; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +NotNullMatcher NotNull() { + return NotNullMatcher(); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +### Legacy Matcher Implementation + +Defining matchers used to be somewhat more complicated, in which it required +several supporting classes and virtual functions. To implement a matcher for +type `T` using the legacy API you have to derive from `MatcherInterface` and +call `MakeMatcher` to construct the object. + +The interface looks like this: + +```cpp +class MatchResultListener { + public: + ... + // Streams x to the underlying ostream; does nothing if the ostream + // is NULL. + template + MatchResultListener& operator<<(const T& x); + + // Returns the underlying ostream. + std::ostream* stream(); +}; + +template +class MatcherInterface { + public: + virtual ~MatcherInterface(); + + // Returns true if and only if the matcher matches x; also explains the match + // result to 'listener'. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; + + // Describes this matcher to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; + + // Describes the negation of this matcher to an ostream. + virtual void DescribeNegationTo(std::ostream* os) const; +}; +``` + +Fortunately, most of the time you can define a polymorphic matcher easily with +the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as +an example: + +```cpp +using ::testing::MakePolymorphicMatcher; +using ::testing::MatchResultListener; +using ::testing::PolymorphicMatcher; + +class NotNullMatcher { + public: + // To implement a polymorphic matcher, first define a COPYABLE class + // that has three members MatchAndExplain(), DescribeTo(), and + // DescribeNegationTo(), like the following. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, + MatchResultListener* /* listener */) const { + return p != NULL; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +// To construct a polymorphic matcher, pass an instance of the class +// to MakePolymorphicMatcher(). Note the return type. +PolymorphicMatcher NotNull() { + return MakePolymorphicMatcher(NotNullMatcher()); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +{: .callout .note} +**Note:** Your polymorphic matcher class does **not** need to inherit from +`MatcherInterface` or any other class, and its methods do **not** need to be +virtual. + +Like in a monomorphic matcher, you may explain the match result by streaming +additional information to the `listener` argument in `MatchAndExplain()`. + +### Writing New Cardinalities + +A cardinality is used in `Times()` to tell gMock how many times you expect a +call to occur. It doesn't have to be exact. For example, you can say +`AtLeast(5)` or `Between(2, 4)`. + +If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities +doesn't suit you, you are free to define your own by implementing the following +interface (in namespace `testing`): + +```cpp +class CardinalityInterface { + public: + virtual ~CardinalityInterface(); + + // Returns true if and only if call_count calls will satisfy this cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; +}; +``` + +For example, to specify that a call must occur even number of times, you can +write + +```cpp +using ::testing::Cardinality; +using ::testing::CardinalityInterface; +using ::testing::MakeCardinality; + +class EvenNumberCardinality : public CardinalityInterface { + public: + bool IsSatisfiedByCallCount(int call_count) const override { + return (call_count % 2) == 0; + } + + bool IsSaturatedByCallCount(int call_count) const override { + return false; + } + + void DescribeTo(std::ostream* os) const { + *os << "called even number of times"; + } +}; + +Cardinality EvenNumber() { + return MakeCardinality(new EvenNumberCardinality); +} + +... + EXPECT_CALL(foo, Bar(3)) + .Times(EvenNumber()); +``` + +### Writing New Actions {#QuickNewActions} + +If the built-in actions don't work for you, you can easily define your own one. +All you need is a call operator with a signature compatible with the mocked +function. So you can use a lambda: + +```cpp +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); +EXPECT_EQ(mock.AsStdFunction()(2), 14); +``` + +Or a struct with a call operator (even a templated one): + +```cpp +struct MultiplyBy { + template + T operator()(T arg) { return arg * multiplier; } + + int multiplier; +}; + +// Then use: +// EXPECT_CALL(...).WillOnce(MultiplyBy{7}); +``` + +It's also fine for the callable to take no arguments, ignoring the arguments +supplied to the mock function: + +```cpp +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); +EXPECT_EQ(mock.AsStdFunction()(0), 17); +``` + +When used with `WillOnce`, the callable can assume it will be called at most +once and is allowed to be a move-only type: + +```cpp +// An action that contains move-only types and has an &&-qualified operator, +// demanding in the type system that it be called at most once. This can be +// used with WillOnce, but the compiler will reject it if handed to +// WillRepeatedly. +struct MoveOnlyAction { + std::unique_ptr move_only_state; + std::unique_ptr operator()() && { return std::move(move_only_state); } +}; + +MockFunction()> mock; +EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique(17)}); +EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17))); +``` + +More generally, to use with a mock function whose signature is `R(Args...)` the +object can be anything convertible to `OnceAction` or +`Action. The difference between the two is that `OnceAction` has +weaker requirements (`Action` requires a copy-constructible input that can be +called repeatedly whereas `OnceAction` requires only move-constructible and +supports `&&`-qualified call operators), but can be used only with `WillOnce`. +`OnceAction` is typically relevant only when supporting move-only types or +actions that want a type-system guarantee that they will be called at most once. + +Typically the `OnceAction` and `Action` templates need not be referenced +directly in your actions: a struct or class with a call operator is sufficient, +as in the examples above. But fancier polymorphic actions that need to know the +specific return type of the mock function can define templated conversion +operators to make that possible. See `gmock-actions.h` for examples. + +#### Legacy macro-based Actions + +Before C++11, the functor-based actions were not supported; the old way of +writing actions was through a set of `ACTION*` macros. We suggest to avoid them +in new code; they hide a lot of logic behind the macro, potentially leading to +harder-to-understand compiler errors. Nevertheless, we cover them here for +completeness. + +By writing + +```cpp +ACTION(name) { statements; } +``` + +in a namespace scope (i.e. not inside a class or function), you will define an +action with the given name that executes the statements. The value returned by +`statements` will be used as the return value of the action. Inside the +statements, you can refer to the K-th (0-based) argument of the mock function as +`argK`. For example: + +```cpp +ACTION(IncrementArg1) { return ++(*arg1); } +``` + +allows you to write + +```cpp +... WillOnce(IncrementArg1()); +``` + +Note that you don't need to specify the types of the mock function arguments. +Rest assured that your code is type-safe though: you'll get a compiler error if +`*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't +compatible with the mock function's return type. + +Another example: + +```cpp +ACTION(Foo) { + (*arg2)(5); + Blah(); + *arg1 = 0; + return arg0; +} +``` + +defines an action `Foo()` that invokes argument #2 (a function pointer) with 5, +calls function `Blah()`, sets the value pointed to by argument #1 to 0, and +returns argument #0. + +For more convenience and flexibility, you can also use the following pre-defined +symbols in the body of `ACTION`: + +`argK_type` | The type of the K-th (0-based) argument of the mock function +:-------------- | :----------------------------------------------------------- +`args` | All arguments of the mock function as a tuple +`args_type` | The type of all arguments of the mock function as a tuple +`return_type` | The return type of the mock function +`function_type` | The type of the mock function + +For example, when using an `ACTION` as a stub action for mock function: + +```cpp +int DoSomething(bool flag, int* ptr); +``` + +we have: + +Pre-defined Symbol | Is Bound To +------------------ | --------------------------------- +`arg0` | the value of `flag` +`arg0_type` | the type `bool` +`arg1` | the value of `ptr` +`arg1_type` | the type `int*` +`args` | the tuple `(flag, ptr)` +`args_type` | the type `std::tuple` +`return_type` | the type `int` +`function_type` | the type `int(bool, int*)` + +#### Legacy macro-based parameterized Actions + +Sometimes you'll want to parameterize an action you define. For that we have +another macro + +```cpp +ACTION_P(name, param) { statements; } +``` + +For example, + +```cpp +ACTION_P(Add, n) { return arg0 + n; } +``` + +will allow you to write + +```cpp +// Returns argument #0 + 5. +... WillOnce(Add(5)); +``` + +For convenience, we use the term *arguments* for the values used to invoke the +mock function, and the term *parameters* for the values used to instantiate an +action. + +Note that you don't need to provide the type of the parameter either. Suppose +the parameter is named `param`, you can also use the gMock-defined symbol +`param_type` to refer to the type of the parameter as inferred by the compiler. +For example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for +the type of `n`. + +gMock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter +actions. For example, + +```cpp +ACTION_P2(ReturnDistanceTo, x, y) { + double dx = arg0 - x; + double dy = arg1 - y; + return sqrt(dx*dx + dy*dy); +} +``` + +lets you write + +```cpp +... WillOnce(ReturnDistanceTo(5.0, 26.5)); +``` + +You can view `ACTION` as a degenerated parameterized action where the number of +parameters is 0. + +You can also easily define actions overloaded on the number of parameters: + +```cpp +ACTION_P(Plus, a) { ... } +ACTION_P2(Plus, a, b) { ... } +``` + +### Restricting the Type of an Argument or Parameter in an ACTION + +For maximum brevity and reusability, the `ACTION*` macros don't ask you to +provide the types of the mock function arguments and the action parameters. +Instead, we let the compiler infer the types for us. + +Sometimes, however, we may want to be more explicit about the types. There are +several tricks to do that. For example: + +```cpp +ACTION(Foo) { + // Makes sure arg0 can be converted to int. + int n = arg0; + ... use n instead of arg0 here ... +} + +ACTION_P(Bar, param) { + // Makes sure the type of arg1 is const char*. + ::testing::StaticAssertTypeEq(); + + // Makes sure param can be converted to bool. + bool flag = param; +} +``` + +where `StaticAssertTypeEq` is a compile-time assertion in googletest that +verifies two types are the same. + +### Writing New Action Templates Quickly + +Sometimes you want to give an action explicit template parameters that cannot be +inferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be +viewed as an extension to `ACTION()` and `ACTION_P*()`. + +The syntax: + +```cpp +ACTION_TEMPLATE(ActionName, + HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), + AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } +``` + +defines an action template that takes *m* explicit template parameters and *n* +value parameters, where *m* is in [1, 10] and *n* is in [0, 10]. `name_i` is the +name of the *i*-th template parameter, and `kind_i` specifies whether it's a +`typename`, an integral constant, or a template. `p_i` is the name of the *i*-th +value parameter. + +Example: + +```cpp +// DuplicateArg(output) converts the k-th argument of the mock +// function to type T and copies it to *output. +ACTION_TEMPLATE(DuplicateArg, + // Note the comma between int and k: + HAS_2_TEMPLATE_PARAMS(int, k, typename, T), + AND_1_VALUE_PARAMS(output)) { + *output = T(std::get(args)); +} +``` + +To create an instance of an action template, write: + +```cpp +ActionName(v1, ..., v_n) +``` + +where the `t`s are the template arguments and the `v`s are the value arguments. +The value argument types are inferred by the compiler. For example: + +```cpp +using ::testing::_; +... + int n; + EXPECT_CALL(mock, Foo).WillOnce(DuplicateArg<1, unsigned char>(&n)); +``` + +If you want to explicitly specify the value argument types, you can provide +additional template arguments: + +```cpp +ActionName(v1, ..., v_n) +``` + +where `u_i` is the desired type of `v_i`. + +`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of +value parameters, but not on the number of template parameters. Without the +restriction, the meaning of the following is unclear: + +```cpp + OverloadedAction(x); +``` + +Are we using a single-template-parameter action where `bool` refers to the type +of `x`, or a two-template-parameter action where the compiler is asked to infer +the type of `x`? + +### Using the ACTION Object's Type + +If you are writing a function that returns an `ACTION` object, you'll need to +know its type. The type depends on the macro used to define the action and the +parameter types. The rule is relatively simple: + + +| Given Definition | Expression | Has Type | +| ----------------------------- | ------------------- | --------------------- | +| `ACTION(Foo)` | `Foo()` | `FooAction` | +| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | +| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | +| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `BarActionP` | +| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz(bool_value, int_value)` | `BazActionP2` | +| ... | ... | ... | + + +Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, +and etc) for actions with different numbers of value parameters, or the action +definitions cannot be overloaded on the number of them. + +### Writing New Monomorphic Actions {#NewMonoActions} + +While the `ACTION*` macros are very convenient, sometimes they are +inappropriate. For example, despite the tricks shown in the previous recipes, +they don't let you directly specify the types of the mock function arguments and +the action parameters, which in general leads to unoptimized compiler error +messages that can baffle unfamiliar users. They also don't allow overloading +actions based on parameter types without jumping through some hoops. + +An alternative to the `ACTION*` macros is to implement +`::testing::ActionInterface`, where `F` is the type of the mock function in +which the action will be used. For example: + +```cpp +template +class ActionInterface { + public: + virtual ~ActionInterface(); + + // Performs the action. Result is the return type of function type + // F, and ArgumentTuple is the tuple of arguments of F. + // + + // For example, if F is int(bool, const string&), then Result would + // be int, and ArgumentTuple would be std::tuple. + virtual Result Perform(const ArgumentTuple& args) = 0; +}; +``` + +```cpp +using ::testing::_; +using ::testing::Action; +using ::testing::ActionInterface; +using ::testing::MakeAction; + +typedef int IncrementMethod(int*); + +class IncrementArgumentAction : public ActionInterface { + public: + int Perform(const std::tuple& args) override { + int* p = std::get<0>(args); // Grabs the first argument. + return *p++; + } +}; + +Action IncrementArgument() { + return MakeAction(new IncrementArgumentAction); +} + +... + EXPECT_CALL(foo, Baz(_)) + .WillOnce(IncrementArgument()); + + int n = 5; + foo.Baz(&n); // Should return 5 and change n to 6. +``` + +### Writing New Polymorphic Actions {#NewPolyActions} + +The previous recipe showed you how to define your own action. This is all good, +except that you need to know the type of the function in which the action will +be used. Sometimes that can be a problem. For example, if you want to use the +action in functions with *different* types (e.g. like `Return()` and +`SetArgPointee()`). + +If an action can be used in several types of mock functions, we say it's +*polymorphic*. The `MakePolymorphicAction()` function template makes it easy to +define such an action: + +```cpp +namespace testing { +template +PolymorphicAction MakePolymorphicAction(const Impl& impl); +} // namespace testing +``` + +As an example, let's define an action that returns the second argument in the +mock function's argument list. The first step is to define an implementation +class: + +```cpp +class ReturnSecondArgumentAction { + public: + template + Result Perform(const ArgumentTuple& args) const { + // To get the i-th (0-based) argument, use std::get(args). + return std::get<1>(args); + } +}; +``` + +This implementation class does *not* need to inherit from any particular class. +What matters is that it must have a `Perform()` method template. This method +template takes the mock function's arguments as a tuple in a **single** +argument, and returns the result of the action. It can be either `const` or not, +but must be invocable with exactly one template argument, which is the result +type. In other words, you must be able to call `Perform(args)` where `R` is +the mock function's return type and `args` is its arguments in a tuple. + +Next, we use `MakePolymorphicAction()` to turn an instance of the implementation +class into the polymorphic action we need. It will be convenient to have a +wrapper for this: + +```cpp +using ::testing::MakePolymorphicAction; +using ::testing::PolymorphicAction; + +PolymorphicAction ReturnSecondArgument() { + return MakePolymorphicAction(ReturnSecondArgumentAction()); +} +``` + +Now, you can use this polymorphic action the same way you use the built-in ones: + +```cpp +using ::testing::_; + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, DoThis, (bool flag, int n), (override)); + MOCK_METHOD(string, DoThat, (int x, const char* str1, const char* str2), + (override)); +}; + + ... + MockFoo foo; + EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument()); + EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument()); + ... + foo.DoThis(true, 5); // Will return 5. + foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". +``` + +### Teaching gMock How to Print Your Values + +When an uninteresting or unexpected call occurs, gMock prints the argument +values and the stack trace to help you debug. Assertion macros like +`EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the +assertion fails. gMock and googletest do this using googletest's user-extensible +value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. +[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values) +explains how to extend the printer to do a better job at printing your +particular type than to dump the bytes. + +## Useful Mocks Created Using gMock + + + + +### Mock std::function {#MockFunction} + +`std::function` is a general function type introduced in C++11. It is a +preferred way of passing callbacks to new interfaces. Functions are copyable, +and are not usually passed around by pointer, which makes them tricky to mock. +But fear not - `MockFunction` can help you with that. + +`MockFunction` has a mock method `Call()` with the signature: + +```cpp + R Call(T1, ..., Tn); +``` + +It also has a `AsStdFunction()` method, which creates a `std::function` proxy +forwarding to Call: + +```cpp + std::function AsStdFunction(); +``` + +To use `MockFunction`, first create `MockFunction` object and set up +expectations on its `Call` method. Then pass proxy obtained from +`AsStdFunction()` to the code you are testing. For example: + +```cpp +TEST(FooTest, RunsCallbackWithBarArgument) { + // 1. Create a mock object. + MockFunction mock_function; + + // 2. Set expectations on Call() method. + EXPECT_CALL(mock_function, Call("bar")).WillOnce(Return(1)); + + // 3. Exercise code that uses std::function. + Foo(mock_function.AsStdFunction()); + // Foo's signature can be either of: + // void Foo(const std::function& fun); + // void Foo(std::function fun); + + // 4. All expectations will be verified when mock_function + // goes out of scope and is destroyed. +} +``` + +Remember that function objects created with `AsStdFunction()` are just +forwarders. If you create multiple of them, they will share the same set of +expectations. + +Although `std::function` supports unlimited number of arguments, `MockFunction` +implementation is limited to ten. If you ever hit that limit... well, your +callback has bigger problems than being mockable. :-) diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_faq.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_faq.md new file mode 100644 index 0000000000000000000000000000000000000000..8f220bf7a8fec033ed9cb827a794397315962fcc --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_faq.md @@ -0,0 +1,390 @@ +# Legacy gMock FAQ + +### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? + +In order for a method to be mocked, it must be *virtual*, unless you use the +[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods). + +### Can I mock a variadic function? + +You cannot mock a variadic function (i.e. a function taking ellipsis (`...`) +arguments) directly in gMock. + +The problem is that in general, there is *no way* for a mock object to know how +many arguments are passed to the variadic method, and what the arguments' types +are. Only the *author of the base class* knows the protocol, and we cannot look +into his or her head. + +Therefore, to mock such a function, the *user* must teach the mock object how to +figure out the number of arguments and their types. One way to do it is to +provide overloaded versions of the function. + +Ellipsis arguments are inherited from C and not really a C++ feature. They are +unsafe to use and don't work with arguments that have constructors or +destructors. Therefore we recommend to avoid them in C++ as much as possible. + +### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? + +If you compile this using Microsoft Visual C++ 2005 SP1: + +```cpp +class Foo { + ... + virtual void Bar(const int i) = 0; +}; + +class MockFoo : public Foo { + ... + MOCK_METHOD(void, Bar, (const int i), (override)); +}; +``` + +You may get the following warning: + +```shell +warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier +``` + +This is a MSVC bug. The same code compiles fine with gcc, for example. If you +use Visual C++ 2008 SP1, you would get the warning: + +```shell +warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers +``` + +In C++, if you *declare* a function with a `const` parameter, the `const` +modifier is ignored. Therefore, the `Foo` base class above is equivalent to: + +```cpp +class Foo { + ... + virtual void Bar(int i) = 0; // int or const int? Makes no difference. +}; +``` + +In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a +`const int` parameter. The compiler will still match them up. + +Since making a parameter `const` is meaningless in the method declaration, we +recommend to remove it in both `Foo` and `MockFoo`. That should workaround the +VC bug. + +Note that we are talking about the *top-level* `const` modifier here. If the +function parameter is passed by pointer or reference, declaring the pointee or +referee as `const` is still meaningful. For example, the following two +declarations are *not* equivalent: + +```cpp +void Bar(int* p); // Neither p nor *p is const. +void Bar(const int* p); // p is not const, but *p is. +``` + +### I can't figure out why gMock thinks my expectations are not satisfied. What should I do? + +You might want to run your test with `--gmock_verbose=info`. This flag lets +gMock print a trace of every mock function call it receives. By studying the +trace, you'll gain insights on why the expectations you set are not met. + +If you see the message "The mock function has no default action set, and its +return type has no default value set.", then try +[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue, +unexpected calls on mocks without default actions don't print out a detailed +comparison between the actual arguments and the expected arguments. + +### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug? + +gMock and `ScopedMockLog` are likely doing the right thing here. + +When a test crashes, the failure signal handler will try to log a lot of +information (the stack trace, and the address map, for example). The messages +are compounded if you have many threads with depth stacks. When `ScopedMockLog` +intercepts these messages and finds that they don't match any expectations, it +prints an error for each of them. + +You can learn to ignore the errors, or you can rewrite your expectations to make +your test more robust, for example, by adding something like: + +```cpp +using ::testing::AnyNumber; +using ::testing::Not; +... + // Ignores any log not done by us. + EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _)) + .Times(AnyNumber()); +``` + +### How can I assert that a function is NEVER called? + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .Times(0); +``` + +### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? + +When gMock detects a failure, it prints relevant information (the mock function +arguments, the state of relevant expectations, and etc) to help the user debug. +If another failure is detected, gMock will do the same, including printing the +state of relevant expectations. + +Sometimes an expectation's state didn't change between two failures, and you'll +see the same description of the state twice. They are however *not* redundant, +as they refer to *different points in time*. The fact they are the same *is* +interesting information. + +### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong? + +Does the class (hopefully a pure interface) you are mocking have a virtual +destructor? + +Whenever you derive from a base class, make sure its destructor is virtual. +Otherwise Bad Things will happen. Consider the following code: + +```cpp +class Base { + public: + // Not virtual, but should be. + ~Base() { ... } + ... +}; + +class Derived : public Base { + public: + ... + private: + std::string value_; +}; + +... + Base* p = new Derived; + ... + delete p; // Surprise! ~Base() will be called, but ~Derived() will not + // - value_ is leaked. +``` + +By changing `~Base()` to virtual, `~Derived()` will be correctly called when +`delete p` is executed, and the heap checker will be happy. + +### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that? + +When people complain about this, often they are referring to code like: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. However, I have to write the expectations in the + // reverse order. This sucks big time!!! + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); +``` + +The problem, is that they didn't pick the **best** way to express the test's +intent. + +By default, expectations don't have to be matched in *any* particular order. If +you want them to match in a certain order, you need to be explicit. This is +gMock's (and jMock's) fundamental philosophy: it's easy to accidentally +over-specify your tests, and we want to make it harder to do so. + +There are two better ways to write the test spec. You could either put the +expectations in sequence: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. Using a sequence, we can write the expectations + // in their natural order. + { + InSequence s; + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .RetiresOnSaturation(); + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(2)) + .RetiresOnSaturation(); + } +``` + +or you can put the sequence of actions in the same expectation: + +```cpp +using ::testing::Return; +... + // foo.Bar() should be called twice, return 1 the first time, and return + // 2 the second time. + EXPECT_CALL(foo, Bar()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .RetiresOnSaturation(); +``` + +Back to the original questions: why does gMock search the expectations (and +`ON_CALL`s) from back to front? Because this allows a user to set up a mock's +behavior for the common case early (e.g. in the mock's constructor or the test +fixture's set-up phase) and customize it with more specific rules later. If +gMock searches from front to back, this very useful pattern won't be possible. + +### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case? + +When choosing between being neat and being safe, we lean toward the latter. So +the answer is that we think it's better to show the warning. + +Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as +the default behavior rarely changes from test to test. Then in the test body +they set the expectations, which are often different for each test. Having an +`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected. +If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If +we quietly let the call go through without notifying the user, bugs may creep in +unnoticed. + +If, however, you are sure that the calls are OK, you can write + +```cpp +using ::testing::_; +... + EXPECT_CALL(foo, Bar(_)) + .WillRepeatedly(...); +``` + +instead of + +```cpp +using ::testing::_; +... + ON_CALL(foo, Bar(_)) + .WillByDefault(...); +``` + +This tells gMock that you do expect the calls and no warning should be printed. + +Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other +values are `info` and `warning`. If you find the output too noisy when +debugging, just choose a less verbose level. + +### How can I delete the mock function's argument in an action? + +If your mock function takes a pointer argument and you want to delete that +argument, you can use testing::DeleteArg() to delete the N'th (zero-indexed) +argument: + +```cpp +using ::testing::_; + ... + MOCK_METHOD(void, Bar, (X* x, const Y& y)); + ... + EXPECT_CALL(mock_foo_, Bar(_, _)) + .WillOnce(testing::DeleteArg<0>())); +``` + +### How can I perform an arbitrary action on a mock function's argument? + +If you find yourself needing to perform some action that's not supported by +gMock directly, remember that you can define your own actions using +[`MakeAction()`](#NewMonoActions) or +[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function +and invoke it using [`Invoke()`](#FunctionsAsActions). + +```cpp +using ::testing::_; +using ::testing::Invoke; + ... + MOCK_METHOD(void, Bar, (X* p)); + ... + EXPECT_CALL(mock_foo_, Bar(_)) + .WillOnce(Invoke(MyAction(...))); +``` + +### My code calls a static/global function. Can I mock it? + +You can, but you need to make some changes. + +In general, if you find yourself needing to mock a static function, it's a sign +that your modules are too tightly coupled (and less flexible, less reusable, +less testable, etc). You are probably better off defining a small interface and +call the function through that interface, which then can be easily mocked. It's +a bit of work initially, but usually pays for itself quickly. + +This Google Testing Blog +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it +excellently. Check it out. + +### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks! + +I know it's not a question, but you get an answer for free any way. :-) + +With gMock, you can create mocks in C++ easily. And people might be tempted to +use them everywhere. Sometimes they work great, and sometimes you may find them, +well, a pain to use. So, what's wrong in the latter case? + +When you write a test without using mocks, you exercise the code and assert that +it returns the correct value or that the system is in an expected state. This is +sometimes called "state-based testing". + +Mocks are great for what some call "interaction-based" testing: instead of +checking the system state at the very end, mock objects verify that they are +invoked the right way and report an error as soon as it arises, giving you a +handle on the precise context in which the error was triggered. This is often +more effective and economical to do than state-based testing. + +If you are doing state-based testing and using a test double just to simulate +the real object, you are probably better off using a fake. Using a mock in this +case causes pain, as it's not a strong point for mocks to perform complex +actions. If you experience this and think that mocks suck, you are just not +using the right tool for your problem. Or, you might be trying to solve the +wrong problem. :-) + +### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? + +By all means, NO! It's just an FYI. :-) + +What it means is that you have a mock function, you haven't set any expectations +on it (by gMock's rule this means that you are not interested in calls to this +function and therefore it can be called any number of times), and it is called. +That's OK - you didn't say it's not OK to call the function! + +What if you actually meant to disallow this function to be called, but forgot to +write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the +user's fault, gMock tries to be nice and prints you a note. + +So, when you see the message and believe that there shouldn't be any +uninteresting calls, you should investigate what's going on. To make your life +easier, gMock dumps the stack trace when an uninteresting call is encountered. +From that you can figure out which mock function it is, and how it is called. + +### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface? + +Either way is fine - you want to choose the one that's more convenient for your +circumstance. + +Usually, if your action is for a particular function type, defining it using +`Invoke()` should be easier; if your action can be used in functions of +different types (e.g. if you are defining `Return(*value*)`), +`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what +types of functions the action can be used in, and implementing `ActionInterface` +is the way to go here. See the implementation of `Return()` in `gmock-actions.h` +for an example. + +### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? + +You got this error as gMock has no idea what value it should return when the +mock method is called. `SetArgPointee()` says what the side effect is, but +doesn't say what the return value should be. You need `DoAll()` to chain a +`SetArgPointee()` with a `Return()` that provides a value appropriate to the API +being mocked. + +See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and +an example. + +### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? + +We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6 +times as much memory when compiling a mock class. We suggest to avoid `/clr` +when compiling native C++ mocks. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_for_dummies.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_for_dummies.md new file mode 100644 index 0000000000000000000000000000000000000000..ed2297c2f79632d979d0b619c7b8c54c752825df --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/gmock_for_dummies.md @@ -0,0 +1,702 @@ +# gMock for Dummies + +## What Is gMock? + +When you write a prototype or test, often it's not feasible or wise to rely on +real objects entirely. A **mock object** implements the same interface as a real +object (so it can be used as one), but lets you specify at run time how it will +be used and what it should do (which methods will be called? in which order? how +many times? with what arguments? what will they return? etc). + +It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks +actually mean very different things in the Test-Driven Development (TDD) +community: + +* **Fake** objects have working implementations, but usually take some + shortcut (perhaps to make the operations less expensive), which makes them + not suitable for production. An in-memory file system would be an example of + a fake. +* **Mocks** are objects pre-programmed with *expectations*, which form a + specification of the calls they are expected to receive. + +If all this seems too abstract for you, don't worry - the most important thing +to remember is that a mock allows you to check the *interaction* between itself +and code that uses it. The difference between fakes and mocks shall become much +clearer once you start to use mocks. + +**gMock** is a library (sometimes we also call it a "framework" to make it sound +cool) for creating mock classes and using them. It does to C++ what +jMock/EasyMock does to Java (well, more or less). + +When using gMock, + +1. first, you use some simple macros to describe the interface you want to + mock, and they will expand to the implementation of your mock class; +2. next, you create some mock objects and specify its expectations and behavior + using an intuitive syntax; +3. then you exercise code that uses the mock objects. gMock will catch any + violation to the expectations as soon as it arises. + +## Why gMock? + +While mock objects help you remove unnecessary dependencies in tests and make +them fast and reliable, using mocks manually in C++ is *hard*: + +* Someone has to implement the mocks. The job is usually tedious and + error-prone. No wonder people go great distance to avoid it. +* The quality of those manually written mocks is a bit, uh, unpredictable. You + may see some really polished ones, but you may also see some that were + hacked up in a hurry and have all sorts of ad hoc restrictions. +* The knowledge you gained from using one mock doesn't transfer to the next + one. + +In contrast, Java and Python programmers have some fine mock frameworks (jMock, +EasyMock, etc), which automate the creation of mocks. As a result, mocking is a +proven effective technique and widely adopted practice in those communities. +Having the right tool absolutely makes the difference. + +gMock was built to help C++ programmers. It was inspired by jMock and EasyMock, +but designed with C++'s specifics in mind. It is your friend if any of the +following problems is bothering you: + +* You are stuck with a sub-optimal design and wish you had done more + prototyping before it was too late, but prototyping in C++ is by no means + "rapid". +* Your tests are slow as they depend on too many libraries or use expensive + resources (e.g. a database). +* Your tests are brittle as some resources they use are unreliable (e.g. the + network). +* You want to test how your code handles a failure (e.g. a file checksum + error), but it's not easy to cause one. +* You need to make sure that your module interacts with other modules in the + right way, but it's hard to observe the interaction; therefore you resort to + observing the side effects at the end of the action, but it's awkward at + best. +* You want to "mock out" your dependencies, except that they don't have mock + implementations yet; and, frankly, you aren't thrilled by some of those + hand-written mocks. + +We encourage you to use gMock as + +* a *design* tool, for it lets you experiment with your interface design early + and often. More iterations lead to better designs! +* a *testing* tool to cut your tests' outbound dependencies and probe the + interaction between your module and its collaborators. + +## Getting Started + +gMock is bundled with googletest. + +## A Case for Mock Turtles + +Let's look at an example. Suppose you are developing a graphics program that +relies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like +API for drawing. How would you test that it does the right thing? Well, you can +run it and compare the screen with a golden screen snapshot, but let's admit it: +tests like this are expensive to run and fragile (What if you just upgraded to a +shiny new graphics card that has better anti-aliasing? Suddenly you have to +update all your golden images.). It would be too painful if all your tests are +like this. Fortunately, you learned about +[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing +to do: instead of having your application talk to the system API directly, wrap +the API in an interface (say, `Turtle`) and code to that interface: + +```cpp +class Turtle { + ... + virtual ~Turtle() {} + virtual void PenUp() = 0; + virtual void PenDown() = 0; + virtual void Forward(int distance) = 0; + virtual void Turn(int degrees) = 0; + virtual void GoTo(int x, int y) = 0; + virtual int GetX() const = 0; + virtual int GetY() const = 0; +}; +``` + +(Note that the destructor of `Turtle` **must** be virtual, as is the case for +**all** classes you intend to inherit from - otherwise the destructor of the +derived class will not be called when you delete an object through a base +pointer, and you'll get corrupted program states like memory leaks.) + +You can control whether the turtle's movement will leave a trace using `PenUp()` +and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and +`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the +turtle. + +Your program will normally use a real implementation of this interface. In +tests, you can use a mock implementation instead. This allows you to easily +check what drawing primitives your program is calling, with what arguments, and +in which order. Tests written this way are much more robust (they won't break +because your new machine does anti-aliasing differently), easier to read and +maintain (the intent of a test is expressed in the code, not in some binary +images), and run *much, much faster*. + +## Writing the Mock Class + +If you are lucky, the mocks you need to use have already been implemented by +some nice people. If, however, you find yourself in the position to write a mock +class, relax - gMock turns this task into a fun game! (Well, almost.) + +### How to Define It + +Using the `Turtle` interface as example, here are the simple steps you need to +follow: + +* Derive a class `MockTurtle` from `Turtle`. +* Take a *virtual* function of `Turtle` (while it's possible to + [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods), + it's much more involved). +* In the `public:` section of the child class, write `MOCK_METHOD();` +* Now comes the fun part: you take the function signature, cut-and-paste it + into the macro, and add two commas - one between the return type and the + name, another between the name and the argument list. +* If you're mocking a const method, add a 4th parameter containing `(const)` + (the parentheses are required). +* Since you're overriding a virtual method, we suggest adding the `override` + keyword. For const methods the 4th parameter becomes `(const, override)`, + for non-const methods just `(override)`. This isn't mandatory. +* Repeat until all virtual functions you want to mock are done. (It goes + without saying that *all* pure virtual methods in your abstract class must + be either mocked or overridden.) + +After the process, you should have something like: + +```cpp +#include // Brings in gMock. + +class MockTurtle : public Turtle { + public: + ... + MOCK_METHOD(void, PenUp, (), (override)); + MOCK_METHOD(void, PenDown, (), (override)); + MOCK_METHOD(void, Forward, (int distance), (override)); + MOCK_METHOD(void, Turn, (int degrees), (override)); + MOCK_METHOD(void, GoTo, (int x, int y), (override)); + MOCK_METHOD(int, GetX, (), (const, override)); + MOCK_METHOD(int, GetY, (), (const, override)); +}; +``` + +You don't need to define these mock methods somewhere else - the `MOCK_METHOD` +macro will generate the definitions for you. It's that simple! + +### Where to Put It + +When you define a mock class, you need to decide where to put its definition. +Some people put it in a `_test.cc`. This is fine when the interface being mocked +(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of +`Foo` changes it, your test could break. (You can't really expect `Foo`'s +maintainer to fix every test that uses `Foo`, can you?) + +Generally, you should not mock classes you don't own. If you must mock such a +class owned by others, define the mock class in `Foo`'s Bazel package (usually +the same directory or a `testing` sub-directory), and put it in a `.h` and a +`cc_library` with `testonly=True`. Then everyone can reference them from their +tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and +only tests that depend on the changed methods need to be fixed. + +Another way to do it: you can introduce a thin layer `FooAdaptor` on top of +`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb +changes in `Foo` much more easily. While this is more work initially, carefully +choosing the adaptor interface can make your code easier to write and more +readable (a net win in the long run), as you can choose `FooAdaptor` to fit your +specific domain much better than `Foo` does. + +## Using Mocks in Tests + +Once you have a mock class, using it is easy. The typical work flow is: + +1. Import the gMock names from the `testing` namespace such that you can use + them unqualified (You only have to do it once per file). Remember that + namespaces are a good idea. +2. Create some mock objects. +3. Specify your expectations on them (How many times will a method be called? + With what arguments? What should it do? etc.). +4. Exercise some code that uses the mocks; optionally, check the result using + googletest assertions. If a mock method is called more than expected or with + wrong arguments, you'll get an error immediately. +5. When a mock is destructed, gMock will automatically check whether all + expectations on it have been satisfied. + +Here's an example: + +```cpp +#include "path/to/mock-turtle.h" +#include +#include + +using ::testing::AtLeast; // #1 + +TEST(PainterTest, CanDrawSomething) { + MockTurtle turtle; // #2 + EXPECT_CALL(turtle, PenDown()) // #3 + .Times(AtLeast(1)); + + Painter painter(&turtle); // #4 + + EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5 +} +``` + +As you might have guessed, this test checks that `PenDown()` is called at least +once. If the `painter` object didn't call this method, your test will fail with +a message like this: + +```text +path/to/my_test.cc:119: Failure +Actual function call count doesn't match this expectation: +Actually: never called; +Expected: called at least once. +Stack trace: +... +``` + +**Tip 1:** If you run the test from an Emacs buffer, you can hit `` on +the line number to jump right to the failed expectation. + +**Tip 2:** If your mock objects are never deleted, the final verification won't +happen. Therefore it's a good idea to turn on the heap checker in your tests +when you allocate mocks on the heap. You get that automatically if you use the +`gtest_main` library already. + +###### Expectation Ordering + +**Important note:** gMock requires expectations to be set **before** the mock +functions are called, otherwise the behavior is **undefined**. Do not alternate +between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set +any expectations on a mock after passing the mock to an API. + +This means `EXPECT_CALL()` should be read as expecting that a call will occur +*in the future*, not that a call has occurred. Why does gMock work like that? +Well, specifying the expectation beforehand allows gMock to report a violation +as soon as it rises, when the context (stack trace, etc) is still available. +This makes debugging much easier. + +Admittedly, this test is contrived and doesn't do much. You can easily achieve +the same effect without using gMock. However, as we shall reveal soon, gMock +allows you to do *so much more* with the mocks. + +## Setting Expectations + +The key to using a mock object successfully is to set the *right expectations* +on it. If you set the expectations too strict, your test will fail as the result +of unrelated changes. If you set them too loose, bugs can slip through. You want +to do it just right such that your test can catch exactly the kind of bugs you +intend it to catch. gMock provides the necessary means for you to do it "just +right." + +### General Syntax + +In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock +method. The general syntax is: + +```cpp +EXPECT_CALL(mock_object, method(matchers)) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +The macro has two arguments: first the mock object, and then the method and its +arguments. Note that the two are separated by a comma (`,`), not a period (`.`). +(Why using a comma? The answer is that it was necessary for technical reasons.) +If the method is not overloaded, the macro can also be called without matchers: + +```cpp +EXPECT_CALL(mock_object, non-overloaded-method) + .Times(cardinality) + .WillOnce(action) + .WillRepeatedly(action); +``` + +This syntax allows the test writer to specify "called with any arguments" +without explicitly specifying the number or types of arguments. To avoid +unintended ambiguity, this syntax may only be used for methods that are not +overloaded. + +Either form of the macro can be followed by some optional *clauses* that provide +more information about the expectation. We'll discuss how each clause works in +the coming sections. + +This syntax is designed to make an expectation read like English. For example, +you can probably guess that + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .Times(5) + .WillOnce(Return(100)) + .WillOnce(Return(150)) + .WillRepeatedly(Return(200)); +``` + +says that the `turtle` object's `GetX()` method will be called five times, it +will return 100 the first time, 150 the second time, and then 200 every time. +Some people like to call this style of syntax a Domain-Specific Language (DSL). + +{: .callout .note} +**Note:** Why do we use a macro to do this? Well it serves two purposes: first +it makes expectations easily identifiable (either by `grep` or by a human +reader), and second it allows gMock to include the source file location of a +failed expectation in messages, making debugging easier. + +### Matchers: What Arguments Do We Expect? + +When a mock function takes arguments, we may specify what arguments we are +expecting, for example: + +```cpp +// Expects the turtle to move forward by 100 units. +EXPECT_CALL(turtle, Forward(100)); +``` + +Oftentimes you do not want to be too specific. Remember that talk about tests +being too rigid? Over specification leads to brittle tests and obscures the +intent of tests. Therefore we encourage you to specify only what's necessary—no +more, no less. If you aren't interested in the value of an argument, write `_` +as the argument, which means "anything goes": + +```cpp +using ::testing::_; +... +// Expects that the turtle jumps to somewhere on the x=50 line. +EXPECT_CALL(turtle, GoTo(50, _)); +``` + +`_` is an instance of what we call **matchers**. A matcher is like a predicate +and can test whether an argument is what we'd expect. You can use a matcher +inside `EXPECT_CALL()` wherever a function argument is expected. `_` is a +convenient way of saying "any value". + +In the above examples, `100` and `50` are also matchers; implicitly, they are +the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be +equal (using `operator==`) to the matcher argument. There are many +[built-in matchers](reference/matchers.md) for common types (as well as +[custom matchers](gmock_cook_book.md#NewMatchers)); for example: + +```cpp +using ::testing::Ge; +... +// Expects the turtle moves forward by at least 100. +EXPECT_CALL(turtle, Forward(Ge(100))); +``` + +If you don't care about *any* arguments, rather than specify `_` for each of +them you may instead omit the parameter list: + +```cpp +// Expects the turtle to move forward. +EXPECT_CALL(turtle, Forward); +// Expects the turtle to jump somewhere. +EXPECT_CALL(turtle, GoTo); +``` + +This works for all non-overloaded methods; if a method is overloaded, you need +to help gMock resolve which overload is expected by specifying the number of +arguments and possibly also the +[types of the arguments](gmock_cook_book.md#SelectOverload). + +### Cardinalities: How Many Times Will It Be Called? + +The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We +call its argument a **cardinality** as it tells *how many times* the call should +occur. It allows us to repeat an expectation many times without actually writing +it as many times. More importantly, a cardinality can be "fuzzy", just like a +matcher can be. This allows a user to express the intent of a test exactly. + +An interesting special case is when we say `Times(0)`. You may have guessed - it +means that the function shouldn't be called with the given arguments at all, and +gMock will report a googletest failure whenever the function is (wrongfully) +called. + +We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the +list of built-in cardinalities you can use, see +[here](gmock_cheat_sheet.md#CardinalityList). + +The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer +the cardinality for you.** The rules are easy to remember: + +* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the + `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. +* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >= + 1, the cardinality is `Times(n)`. +* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >= + 0, the cardinality is `Times(AtLeast(n))`. + +**Quick quiz:** what do you think will happen if a function is expected to be +called twice but actually called four times? + +### Actions: What Should It Do? + +Remember that a mock object doesn't really have a working implementation? We as +users have to tell it what to do when a method is invoked. This is easy in +gMock. + +First, if the return type of a mock function is a built-in type or a pointer, +the function has a **default action** (a `void` function will just return, a +`bool` function will return `false`, and other functions will return 0). In +addition, in C++ 11 and above, a mock function whose return type is +default-constructible (i.e. has a default constructor) has a default action of +returning a default-constructed value. If you don't say anything, this behavior +will be used. + +Second, if a mock function doesn't have a default action, or the default action +doesn't suit you, you can specify the action to be taken each time the +expectation matches using a series of `WillOnce()` clauses followed by an +optional `WillRepeatedly()`. For example, + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillOnce(Return(300)); +``` + +says that `turtle.GetX()` will be called *exactly three times* (gMock inferred +this from how many `WillOnce()` clauses we've written, since we didn't +explicitly write `Times()`), and will return 100, 200, and 300 respectively. + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .WillOnce(Return(100)) + .WillOnce(Return(200)) + .WillRepeatedly(Return(300)); +``` + +says that `turtle.GetY()` will be called *at least twice* (gMock knows this as +we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no +explicit `Times()`), will return 100 and 200 respectively the first two times, +and 300 from the third time on. + +Of course, if you explicitly write a `Times()`, gMock will not try to infer the +cardinality itself. What if the number you specified is larger than there are +`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do +the *default* action for the function every time (unless, of course, you have a +`WillRepeatedly()`.). + +What can we do inside `WillOnce()` besides `Return()`? You can return a +reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, +among [others](gmock_cook_book.md#using-actions). + +**Important note:** The `EXPECT_CALL()` statement evaluates the action clause +only once, even though the action may be performed many times. Therefore you +must be careful about side effects. The following may not do what you want: + +```cpp +using ::testing::Return; +... +int n = 100; +EXPECT_CALL(turtle, GetX()) + .Times(4) + .WillRepeatedly(Return(n++)); +``` + +Instead of returning 100, 101, 102, ..., consecutively, this mock function will +always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` +will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will +return the same pointer every time. If you want the side effect to happen every +time, you need to define a custom action, which we'll teach in the +[cook book](gmock_cook_book.md). + +Time for another quiz! What do you think the following means? + +```cpp +using ::testing::Return; +... +EXPECT_CALL(turtle, GetY()) + .Times(4) + .WillOnce(Return(100)); +``` + +Obviously `turtle.GetY()` is expected to be called four times. But if you think +it will return 100 every time, think twice! Remember that one `WillOnce()` +clause will be consumed each time the function is invoked and the default action +will be taken afterwards. So the right answer is that `turtle.GetY()` will +return 100 the first time, but **return 0 from the second time on**, as +returning 0 is the default action for `int` functions. + +### Using Multiple Expectations {#MultiExpectations} + +So far we've only shown examples where you have a single expectation. More +realistically, you'll specify expectations on multiple mock methods which may be +from multiple mock objects. + +By default, when a mock method is invoked, gMock will search the expectations in +the **reverse order** they are defined, and stop when an active expectation that +matches the arguments is found (you can think of it as "newer rules override +older ones."). If the matching expectation cannot take any more calls, you will +get an upper-bound-violated failure. Here's an example: + +```cpp +using ::testing::_; +... +EXPECT_CALL(turtle, Forward(_)); // #1 +EXPECT_CALL(turtle, Forward(10)) // #2 + .Times(2); +``` + +If `Forward(10)` is called three times in a row, the third time it will be an +error, as the last matching expectation (#2) has been saturated. If, however, +the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, +as now #1 will be the matching expectation. + +{: .callout .note} +**Note:** Why does gMock search for a match in the *reverse* order of the +expectations? The reason is that this allows a user to set up the default +expectations in a mock object's constructor or the test fixture's set-up phase +and then customize the mock by writing more specific expectations in the test +body. So, if you have two expectations on the same method, you want to put the +one with more specific matchers **after** the other, or the more specific rule +would be shadowed by the more general one that comes after it. + +{: .callout .tip} +**Tip:** It is very common to start with a catch-all expectation for a method +and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if +overloaded). This makes any calls to the method expected. This is not necessary +for methods that are not mentioned at all (these are "uninteresting"), but is +useful for methods that have some expectations, but for which other calls are +ok. See +[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected). + +### Ordered vs Unordered Calls {#OrderedCalls} + +By default, an expectation can match a call even though an earlier expectation +hasn't been satisfied. In other words, the calls don't have to occur in the +order the expectations are specified. + +Sometimes, you may want all the expected calls to occur in a strict order. To +say this in gMock is easy: + +```cpp +using ::testing::InSequence; +... +TEST(FooTest, DrawsLineSegment) { + ... + { + InSequence seq; + + EXPECT_CALL(turtle, PenDown()); + EXPECT_CALL(turtle, Forward(100)); + EXPECT_CALL(turtle, PenUp()); + } + Foo(); +} +``` + +By creating an object of type `InSequence`, all expectations in its scope are +put into a *sequence* and have to occur *sequentially*. Since we are just +relying on the constructor and destructor of this object to do the actual work, +its name is really irrelevant. + +In this example, we test that `Foo()` calls the three expected functions in the +order as written. If a call is made out-of-order, it will be an error. + +(What if you care about the relative order of some of the calls, but not all of +them? Can you specify an arbitrary partial order? The answer is ... yes! The +details can be found [here](gmock_cook_book.md#OrderedCalls).) + +### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} + +Now let's do a quick quiz to see how well you can use this mock stuff already. +How would you test that the turtle is asked to go to the origin *exactly twice* +(you want to ignore any other instructions it receives)? + +After you've come up with your answer, take a look at ours and compare notes +(solve it yourself first - don't cheat!): + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(turtle, GoTo(_, _)) // #1 + .Times(AnyNumber()); +EXPECT_CALL(turtle, GoTo(0, 0)) // #2 + .Times(2); +``` + +Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will +see that the arguments match expectation #2 (remember that we always pick the +last matching expectation). Now, since we said that there should be only two +such calls, gMock will report an error immediately. This is basically what we've +told you in the [Using Multiple Expectations](#MultiExpectations) section above. + +This example shows that **expectations in gMock are "sticky" by default**, in +the sense that they remain active even after we have reached their invocation +upper bounds. This is an important rule to remember, as it affects the meaning +of the spec, and is **different** to how it's done in many other mocking +frameworks (Why'd we do that? Because we think our rule makes the common cases +easier to express and understand.). + +Simple? Let's see if you've really understood it: what does the following code +say? + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)); +} +``` + +If you think it says that `turtle.GetX()` will be called `n` times and will +return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we +said, expectations are sticky. So, the second time `turtle.GetX()` is called, +the last (latest) `EXPECT_CALL()` statement will match, and will immediately +lead to an "upper bound violated" error - this piece of code is not very useful! + +One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is +to explicitly say that the expectations are *not* sticky. In other words, they +should *retire* as soon as they are saturated: + +```cpp +using ::testing::Return; +... +for (int i = n; i > 0; i--) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); +} +``` + +And, there's a better way to do it: in this case, we expect the calls to occur +in a specific order, and we line up the actions to match the order. Since the +order is important here, we should make it explicit using a sequence: + +```cpp +using ::testing::InSequence; +using ::testing::Return; +... +{ + InSequence s; + + for (int i = 1; i <= n; i++) { + EXPECT_CALL(turtle, GetX()) + .WillOnce(Return(10*i)) + .RetiresOnSaturation(); + } +} +``` + +By the way, the other situation where an expectation may *not* be sticky is when +it's in a sequence - as soon as another expectation that comes after it in the +sequence has been used, it automatically retires (and will never be used to +match any call). + +### Uninteresting Calls + +A mock object may have many methods, and not all of them are that interesting. +For example, in some tests we may not care about how many times `GetX()` and +`GetY()` get called. + +In gMock, if you are not interested in a method, just don't say anything about +it. If a call to this method occurs, you'll see a warning in the test output, +but it won't be a failure. This is called "naggy" behavior; to change, see +[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy). diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/index.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/index.md new file mode 100644 index 0000000000000000000000000000000000000000..b162c740116394bd6871fe9e65f78cd0289b258f --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/index.md @@ -0,0 +1,22 @@ +# GoogleTest User's Guide + +## Welcome to GoogleTest! + +GoogleTest is Google's C++ testing and mocking framework. This user's guide has +the following contents: + +* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using + GoogleTest. Read this first if you are new to GoogleTest. +* [GoogleTest Advanced](advanced.md) - Read this when you've finished the + Primer and want to utilize GoogleTest to its full potential. +* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples. +* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here + first. +* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock + objects and use them in tests. +* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to + common mocking use cases. +* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for + matchers, actions, invariants, and more. +* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific + questions. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/pkgconfig.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/pkgconfig.md new file mode 100644 index 0000000000000000000000000000000000000000..bf05d59316598d8976984c7ff528399bdc55a459 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/pkgconfig.md @@ -0,0 +1,144 @@ +## Using GoogleTest from various build systems + +GoogleTest comes with pkg-config files that can be used to determine all +necessary flags for compiling and linking to GoogleTest (and GoogleMock). +Pkg-config is a standardised plain-text format containing + +* the includedir (-I) path +* necessary macro (-D) definitions +* further required flags (-pthread) +* the library (-L) path +* the library (-l) to link to + +All current build systems support pkg-config in one way or another. For all +examples here we assume you want to compile the sample +`samples/sample3_unittest.cc`. + +### CMake + +Using `pkg-config` in CMake is fairly easy: + +```cmake +find_package(PkgConfig) +pkg_search_module(GTEST REQUIRED gtest_main) + +add_executable(testapp) +target_sources(testapp PRIVATE samples/sample3_unittest.cc) +target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS}) +target_compile_options(testapp PRIVATE ${GTEST_CFLAGS}) + +enable_testing() +add_test(first_and_only_test testapp) +``` + +It is generally recommended that you use `target_compile_options` + `_CFLAGS` +over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not +just -I flags (GoogleTest might require a macro indicating to internal headers +that all libraries have been compiled with threading enabled. In addition, +GoogleTest might also require `-pthread` in the compiling step, and as such +splitting the pkg-config `Cflags` variable into include dirs and macros for +`target_compile_definitions()` might still miss this). The same recommendation +goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens +to discard `-L` flags and `-pthread`. + +### Help! pkg-config can't find GoogleTest! + +Let's say you have a `CMakeLists.txt` along the lines of the one in this +tutorial and you try to run `cmake`. It is very possible that you get a failure +along the lines of: + +``` +-- Checking for one of the modules 'gtest_main' +CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message): + None of the required 'gtest_main' found +``` + +These failures are common if you installed GoogleTest yourself and have not +sourced it from a distro or other package manager. If so, you need to tell +pkg-config where it can find the `.pc` files containing the information. Say you +installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are +installed under `/usr/local/lib64/pkgconfig`. If you set + +``` +export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig +``` + +pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. + +### Using pkg-config in a cross-compilation setting + +Pkg-config can be used in a cross-compilation setting too. To do this, let's +assume the final prefix of the cross-compiled installation will be `/usr`, and +your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using + +``` +mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. +``` + +Install into the sysroot using `DESTDIR`: + +``` +make -j install DESTDIR=/home/MYUSER/sysroot +``` + +Before we continue, it is recommended to **always** define the following two +variables for pkg-config in a cross-compilation setting: + +``` +export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes +export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes +``` + +otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes +such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for +reasons why this stripping needs to occur usually). + +If you look at the generated pkg-config file, it will look something like + +``` +libdir=/usr/lib64 +includedir=/usr/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.11.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread +``` + +Notice that the sysroot is not included in `libdir` and `includedir`! If you try +to run `pkg-config` with the correct +`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc` +file, you will get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include +$ pkg-config --libs gtest +-L/usr/lib64 -lgtest -lpthread +``` + +which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In +order to use this in a cross-compilation setting, we need to tell pkg-config to +inject the actual sysroot into `-I` and `-L` variables. Let us now tell +pkg-config about the actual sysroot + +``` +export PKG_CONFIG_DIR= +export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot +export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig +``` + +and running `pkg-config` again we get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include +$ pkg-config --libs gtest +-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread +``` + +which contains the correct sysroot now. For a more comprehensive guide to also +including `${CHOST}` in build system calls, see the excellent tutorial by Diego +Elio Pettenò: diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/platforms.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/platforms.md new file mode 100644 index 0000000000000000000000000000000000000000..d35a7be054e80740cc3d82fa776d4efe3418d519 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/platforms.md @@ -0,0 +1,8 @@ +# Supported Platforms + +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions compilers, platforms, and build +tools. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/primer.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/primer.md new file mode 100644 index 0000000000000000000000000000000000000000..61806be6ef86f0f0adeb94c6f984effc2bfc3f96 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/primer.md @@ -0,0 +1,482 @@ +# GoogleTest Primer + +## Introduction: Why GoogleTest? + +*GoogleTest* helps you write better C++ tests. + +GoogleTest is a testing framework developed by the Testing Technology team with +Google's specific requirements and constraints in mind. Whether you work on +Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it +supports *any* kind of tests, not just unit tests. + +So what makes a good test, and how does GoogleTest fit in? We believe: + +1. Tests should be *independent* and *repeatable*. It's a pain to debug a test + that succeeds or fails as a result of other tests. GoogleTest isolates the + tests by running each of them on a different object. When a test fails, + GoogleTest allows you to run it in isolation for quick debugging. +2. Tests should be well *organized* and reflect the structure of the tested + code. GoogleTest groups related tests into test suites that can share data + and subroutines. This common pattern is easy to recognize and makes tests + easy to maintain. Such consistency is especially helpful when people switch + projects and start to work on a new code base. +3. Tests should be *portable* and *reusable*. Google has a lot of code that is + platform-neutral; its tests should also be platform-neutral. GoogleTest + works on different OSes, with different compilers, with or without + exceptions, so GoogleTest tests can work with a variety of configurations. +4. When tests fail, they should provide as much *information* about the problem + as possible. GoogleTest doesn't stop at the first test failure. Instead, it + only stops the current test and continues with the next. You can also set up + tests that report non-fatal failures after which the current test continues. + Thus, you can detect and fix multiple bugs in a single run-edit-compile + cycle. +5. The testing framework should liberate test writers from housekeeping chores + and let them focus on the test *content*. GoogleTest automatically keeps + track of all tests defined, and doesn't require the user to enumerate them + in order to run them. +6. Tests should be *fast*. With GoogleTest, you can reuse shared resources + across tests and pay for the set-up/tear-down only once, without making + tests depend on each other. + +Since GoogleTest is based on the popular xUnit architecture, you'll feel right +at home if you've used JUnit or PyUnit before. If not, it will take you about 10 +minutes to learn the basics and get started. So let's go! + +## Beware of the Nomenclature + +{: .callout .note} +*Note:* There might be some confusion arising from different definitions of the +terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these. + +Historically, GoogleTest started to use the term *Test Case* for grouping +related tests, whereas current publications, including International Software +Testing Qualifications Board ([ISTQB](https://www.istqb.org/)) materials and +various textbooks on software quality, use the term +*[Test Suite][istqb test suite]* for this. + +The related term *Test*, as it is used in GoogleTest, corresponds to the term +*[Test Case][istqb test case]* of ISTQB and others. + +The term *Test* is commonly of broad enough sense, including ISTQB's definition +of *Test Case*, so it's not much of a problem here. But the term *Test Case* as +was used in Google Test is of contradictory sense and thus confusing. + +GoogleTest recently started replacing the term *Test Case* with *Test Suite*. +The preferred API is *TestSuite*. The older TestCase API is being slowly +deprecated and refactored away. + +So please be aware of the different definitions of the terms: + + +Meaning | GoogleTest Term | [ISTQB](https://www.istqb.org/) Term +:----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- +Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] + + +[istqb test case]: https://glossary.istqb.org/en_US/term/test-case-2 +[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite-1-3 + +## Basic Concepts + +When using GoogleTest, you start by writing *assertions*, which are statements +that check whether a condition is true. An assertion's result can be *success*, +*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the +current function; otherwise the program continues normally. + +*Tests* use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it *fails*; otherwise it *succeeds*. + +A *test suite* contains one or many tests. You should group your tests into test +suites that reflect the structure of the tested code. When multiple tests in a +test suite need to share common objects and subroutines, you can put them into a +*test fixture* class. + +A *test program* can contain multiple test suites. + +We'll now explain how to write a test program, starting at the individual +assertion level and building up to tests and test suites. + +## Assertions + +GoogleTest assertions are macros that resemble function calls. You test a class +or function by making assertions about its behavior. When an assertion fails, +GoogleTest prints the assertion's source file and line number location, along +with a failure message. You may also supply a custom failure message which will +be appended to GoogleTest's message. + +The assertions come in pairs that test the same thing but have different effects +on the current function. `ASSERT_*` versions generate fatal failures when they +fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal +failures, which don't abort the current function. Usually `EXPECT_*` are +preferred, as they allow more than one failure to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when the +assertion in question fails. + +Since a failed `ASSERT_*` returns from the current function immediately, +possibly skipping clean-up code that comes after it, it may cause a space leak. +Depending on the nature of the leak, it may or may not be worth fixing - so keep +this in mind if you get a heap checker error in addition to assertion errors. + +To provide a custom failure message, simply stream it into the macro using the +`<<` operator or a sequence of such operators. See the following example, using +the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to +verify value equality: + +```c++ +ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; + +for (int i = 0; i < x.size(); ++i) { + EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; +} +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro--in particular, C strings and `string` objects. If a wide string +(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is +streamed to an assertion, it will be translated to UTF-8 when printed. + +GoogleTest provides a collection of assertions for verifying the behavior of +your code in various ways. You can check Boolean conditions, compare values +based on relational operators, verify string values, floating-point values, and +much more. There are even assertions that enable you to verify more complex +states by providing custom predicates. For the complete list of assertions +provided by GoogleTest, see the [Assertions Reference](reference/assertions.md). + +## Simple Tests + +To create a test: + +1. Use the `TEST()` macro to define and name a test function. These are + ordinary C++ functions that don't return a value. +2. In this function, along with any valid C++ statements you want to include, + use the various GoogleTest assertions to check values. +3. The test's result is determined by the assertions; if any assertion in the + test fails (either fatally or non-fatally), or if the test crashes, the + entire test fails. Otherwise, it succeeds. + +```c++ +TEST(TestSuiteName, TestName) { + ... test body ... +} +``` + +`TEST()` arguments go from general to specific. The *first* argument is the name +of the test suite, and the *second* argument is the test's name within the test +suite. Both names must be valid C++ identifiers, and they should not contain any +underscores (`_`). A test's *full name* consists of its containing test suite +and its individual name. Tests from different test suites can have the same +individual name. + +For example, let's take a simple integer function: + +```c++ +int Factorial(int n); // Returns the factorial of n +``` + +A test suite for this function might look like: + +```c++ +// Tests factorial of 0. +TEST(FactorialTest, HandlesZeroInput) { + EXPECT_EQ(Factorial(0), 1); +} + +// Tests factorial of positive numbers. +TEST(FactorialTest, HandlesPositiveInput) { + EXPECT_EQ(Factorial(1), 1); + EXPECT_EQ(Factorial(2), 2); + EXPECT_EQ(Factorial(3), 6); + EXPECT_EQ(Factorial(8), 40320); +} +``` + +GoogleTest groups the test results by test suites, so logically related tests +should be in the same test suite; in other words, the first argument to their +`TEST()` should be the same. In the above example, we have two tests, +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test +suite `FactorialTest`. + +When naming your test suites and tests, you should follow the same convention as +for +[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names). + +**Availability**: Linux, Windows, Mac. + +## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests} + +If you find yourself writing two or more tests that operate on similar data, you +can use a *test fixture*. This allows you to reuse the same configuration of +objects for several different tests. + +To create a fixture: + +1. Derive a class from `testing::Test` . Start its body with `protected:`, as + we'll want to access fixture members from sub-classes. +2. Inside the class, declare any objects you plan to use. +3. If necessary, write a default constructor or `SetUp()` function to prepare + the objects for each test. A common mistake is to spell `SetUp()` as + **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you + spelled it correctly. +4. If necessary, write a destructor or `TearDown()` function to release any + resources you allocated in `SetUp()` . To learn when you should use the + constructor/destructor and when you should use `SetUp()/TearDown()`, read + the [FAQ](faq.md#CtorVsSetUp). +5. If needed, define subroutines for your tests to share. + +When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to +access objects and subroutines in the test fixture: + +```c++ +TEST_F(TestFixtureClassName, TestName) { + ... test body ... +} +``` + +Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test +fixture class. (`_F` stands for "Fixture"). No test suite name is specified for +this macro. + +Unfortunately, the C++ macro system does not allow us to create a single macro +that can handle both types of tests. Using the wrong macro causes a compiler +error. + +Also, you must first define a test fixture class before using it in a +`TEST_F()`, or you'll get the compiler error "`virtual outside class +declaration`". + +For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean +up by calling `TearDown()`, and then delete the test fixture. Note that +different tests in the same test suite have different test fixture objects, and +GoogleTest always deletes a test fixture before it creates the next one. +GoogleTest does **not** reuse the same test fixture for multiple tests. Any +changes one test makes to the fixture do not affect other tests. + +As an example, let's write tests for a FIFO queue class named `Queue`, which has +the following interface: + +```c++ +template // E is the element type. +class Queue { + public: + Queue(); + void Enqueue(const E& element); + E* Dequeue(); // Returns NULL if the queue is empty. + size_t size() const; + ... +}; +``` + +First, define a fixture class. By convention, you should give it the name +`FooTest` where `Foo` is the class being tested. + +```c++ +class QueueTest : public testing::Test { + protected: + QueueTest() { + // q0_ remains empty + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); + } + + // ~QueueTest() override = default; + + Queue q0_; + Queue q1_; + Queue q2_; +}; +``` + +In this case, we don't need to define a destructor or a `TearDown()` method, +because the implicit destructor generated by the compiler will perform all of +the necessary cleanup. + +Now we'll write tests using `TEST_F()` and this fixture. + +```c++ +TEST_F(QueueTest, IsEmptyInitially) { + EXPECT_EQ(q0_.size(), 0); +} + +TEST_F(QueueTest, DequeueWorks) { + int* n = q0_.Dequeue(); + EXPECT_EQ(n, nullptr); + + n = q1_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 1); + EXPECT_EQ(q1_.size(), 0); + delete n; + + n = q2_.Dequeue(); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 2); + EXPECT_EQ(q2_.size(), 1); + delete n; +} +``` + +The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is +to use `EXPECT_*` when you want the test to continue to reveal more errors after +the assertion failure, and use `ASSERT_*` when continuing after failure doesn't +make sense. For example, the second assertion in the `Dequeue` test is +`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which +would lead to a segfault when `n` is `NULL`. + +When these tests run, the following happens: + +1. GoogleTest constructs a `QueueTest` object (let's call it `t1`). +2. The first test (`IsEmptyInitially`) runs on `t1`. +3. `t1` is destructed. +4. The above steps are repeated on another `QueueTest` object, this time + running the `DequeueWorks` test. + +**Availability**: Linux, Windows, Mac. + +## Invoking the Tests + +`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So, +unlike with many other C++ testing frameworks, you don't have to re-list all +your defined tests in order to run them. + +After defining your tests, you can run them with `RUN_ALL_TESTS()`, which +returns `0` if all the tests are successful, or `1` otherwise. Note that +`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different +test suites, or even different source files. + +When invoked, the `RUN_ALL_TESTS()` macro: + +* Saves the state of all GoogleTest flags. + +* Creates a test fixture object for the first test. + +* Initializes it via `SetUp()`. + +* Runs the test on the fixture object. + +* Cleans up the fixture via `TearDown()`. + +* Deletes the fixture. + +* Restores the state of all GoogleTest flags. + +* Repeats the above steps for the next test, until all tests have run. + +If a fatal failure happens the subsequent steps will be skipped. + +{: .callout .important} +> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or +> you will get a compiler error. The rationale for this design is that the +> automated testing service determines whether a test has passed based on its +> exit code, not on its stdout/stderr output; thus your `main()` function must +> return the value of `RUN_ALL_TESTS()`. +> +> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than +> once conflicts with some advanced GoogleTest features (e.g., thread-safe +> [death tests](advanced.md#death-tests)) and thus is not supported. + +**Availability**: Linux, Windows, Mac. + +## Writing the main() Function + +Most users should *not* need to write their own `main` function and instead link +with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry +point. See the end of this section for details. The remainder of this section +should only apply when you need to do something custom before the tests run that +cannot be expressed within the framework of fixtures and test suites. + +If you write your own `main` function, it should return the value of +`RUN_ALL_TESTS()`. + +You can start from this boilerplate: + +```c++ +#include "this/package/foo.h" + +#include + +namespace my { +namespace project { +namespace { + +// The fixture for testing class Foo. +class FooTest : public testing::Test { + protected: + // You can remove any or all of the following functions if their bodies would + // be empty. + + FooTest() { + // You can do set-up work for each test here. + } + + ~FooTest() override { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + void SetUp() override { + // Code here will be called immediately after the constructor (right + // before each test). + } + + void TearDown() override { + // Code here will be called immediately after each test (right + // before the destructor). + } + + // Class members declared here can be used by all tests in the test suite + // for Foo. +}; + +// Tests that the Foo::Bar() method does Abc. +TEST_F(FooTest, MethodBarDoesAbc) { + const std::string input_filepath = "this/package/testdata/myinputfile.dat"; + const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; + Foo f; + EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); +} + +// Tests that Foo does Xyz. +TEST_F(FooTest, DoesXyz) { + // Exercises the Xyz feature of Foo. +} + +} // namespace +} // namespace project +} // namespace my + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +The `testing::InitGoogleTest()` function parses the command line for GoogleTest +flags, and removes all recognized flags. This allows the user to control a test +program's behavior via various flags, which we'll cover in the +[AdvancedGuide](advanced.md). You **must** call this function before calling +`RUN_ALL_TESTS()`, or the flags won't be properly initialized. + +On Windows, `InitGoogleTest()` also works with wide strings, so it can be used +in programs compiled in `UNICODE` mode as well. + +But maybe you think that writing all those `main` functions is too much work? We +agree with you completely, and that's why Google Test provides a basic +implementation of main(). If it fits your needs, then just link your test with +the `gtest_main` library and you are good to go. + +{: .callout .note} +NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + +## Known Limitations + +* Google Test is designed to be thread-safe. The implementation is thread-safe + on systems where the `pthreads` library is available. It is currently + *unsafe* to use Google Test assertions from two threads concurrently on + other systems (e.g. Windows). In most tests this is not an issue as usually + the assertions are done in the main thread. If you want to help, you can + volunteer to implement the necessary synchronization primitives in + `gtest-port.h` for your platform. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/quickstart-bazel.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/quickstart-bazel.md new file mode 100644 index 0000000000000000000000000000000000000000..4f693dbe7fd422e2f92f82ee23e2eb3aa89ac3bb --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/quickstart-bazel.md @@ -0,0 +1,153 @@ +# Quickstart: Building with Bazel + +This tutorial aims to get you up and running with GoogleTest using the Bazel +build system. If you're using GoogleTest for the first time or need a refresher, +we recommend this tutorial as a starting point. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [Bazel](https://bazel.build/), the preferred build system used by the + GoogleTest team. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have Bazel installed, see the +[Bazel installation guide](https://bazel.build/install). + +{: .callout .note} Note: The terminal commands in this tutorial show a Unix +shell prompt, but the commands work on the Windows command line as well. + +## Set up a Bazel workspace + +A +[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace) +is a directory on your filesystem that you use to manage source files for the +software you want to build. Each workspace directory has a text file named +`WORKSPACE` which may be empty, or may contain references to external +dependencies required to build the outputs. + +First, create a directory for your workspace: + +``` +$ mkdir my_workspace && cd my_workspace +``` + +Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and +recommended way to depend on GoogleTest is to use a +[Bazel external dependency](https://docs.bazel.build/versions/main/external.html) +via the +[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive). +To do this, in the root directory of your workspace (`my_workspace/`), create a +file named `WORKSPACE` with the following contents: + +``` +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "com_google_googletest", + urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"], + strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015", +) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +as a ZIP archive from GitHub. In the above example, +`5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the +GoogleTest version to use; we recommend updating the hash often to point to the +latest version. Use a recent hash on the `main` branch. + +Now you're ready to build C++ code that uses GoogleTest. + +## Create and run a binary + +With your Bazel workspace set up, you can now use GoogleTest code within your +own project. + +As an example, create a file named `hello_test.cc` in your `my_workspace` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, create a file named `BUILD` in the same directory with the +following contents: + +``` +cc_test( + name = "hello_test", + size = "small", + srcs = ["hello_test.cc"], + deps = ["@com_google_googletest//:gtest_main"], +) +``` + +This `cc_test` rule declares the C++ test binary you want to build, and links to +GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE` +file (`@com_google_googletest`). For more information about Bazel `BUILD` files, +see the +[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html). + +{: .callout .note} +NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14` +to ensure that GoogleTest is compiled as C++14 instead of the compiler's default +setting (which could be C++11). For MSVC, the equivalent would be +`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details +on supported language versions. + +Now you can build and run your test: + +
+my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test
+INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
+INFO: Found 1 test target...
+INFO: From Testing //:hello_test:
+==================== Test output for //:hello_test:
+Running main() from gmock_main.cc
+[==========] Running 1 test from 1 test suite.
+[----------] Global test environment set-up.
+[----------] 1 test from HelloTest
+[ RUN      ] HelloTest.BasicAssertions
+[       OK ] HelloTest.BasicAssertions (0 ms)
+[----------] 1 test from HelloTest (0 ms total)
+
+[----------] Global test environment tear-down
+[==========] 1 test from 1 test suite ran. (0 ms total)
+[  PASSED  ] 1 test.
+================================================================================
+Target //:hello_test up-to-date:
+  bazel-bin/hello_test
+INFO: Elapsed time: 4.190s, Critical Path: 3.05s
+INFO: 27 processes: 8 internal, 19 linux-sandbox.
+INFO: Build completed successfully, 27 total actions
+//:hello_test                                                     PASSED in 0.1s
+
+INFO: Build completed successfully, 27 total actions
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/quickstart-cmake.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/quickstart-cmake.md new file mode 100644 index 0000000000000000000000000000000000000000..4e422b74f8302614ea66d2906ad0d8d3a1622ab4 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/quickstart-cmake.md @@ -0,0 +1,157 @@ +# Quickstart: Building with CMake + +This tutorial aims to get you up and running with GoogleTest using CMake. If +you're using GoogleTest for the first time or need a refresher, we recommend +this tutorial as a starting point. If your project uses Bazel, see the +[Quickstart for Bazel](quickstart-bazel.md) instead. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [CMake](https://cmake.org/) and a compatible build tool for building the + project. + * Compatible build tools include + [Make](https://www.gnu.org/software/make/), + [Ninja](https://ninja-build.org/), and others - see + [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html) + for more information. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have CMake installed, see the +[CMake installation guide](https://cmake.org/install). + +{: .callout .note} +Note: The terminal commands in this tutorial show a Unix shell prompt, but the +commands work on the Windows command line as well. + +## Set up a project + +CMake uses a file named `CMakeLists.txt` to configure the build system for a +project. You'll use this file to set up your project and declare a dependency on +GoogleTest. + +First, create a directory for your project: + +``` +$ mkdir my_project && cd my_project +``` + +Next, you'll create the `CMakeLists.txt` file and declare a dependency on +GoogleTest. There are many ways to express dependencies in the CMake ecosystem; +in this quickstart, you'll use the +[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html). +To do this, in your project directory (`my_project`), create a file named +`CMakeLists.txt` with the following contents: + +```cmake +cmake_minimum_required(VERSION 3.14) +project(my_project) + +# GoogleTest requires at least C++14 +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is +the Git commit hash of the GoogleTest version to use; we recommend updating the +hash often to point to the latest version. + +For more information about how to create `CMakeLists.txt` files, see the +[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html). + +## Create and run a binary + +With GoogleTest declared as a dependency, you can use GoogleTest code within +your own project. + +As an example, create a file named `hello_test.cc` in your `my_project` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, add the following to the end of your `CMakeLists.txt` file: + +```cmake +enable_testing() + +add_executable( + hello_test + hello_test.cc +) +target_link_libraries( + hello_test + GTest::gtest_main +) + +include(GoogleTest) +gtest_discover_tests(hello_test) +``` + +The above configuration enables testing in CMake, declares the C++ test binary +you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The +last two lines enable CMake's test runner to discover the tests included in the +binary, using the +[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html). + +Now you can build and run your test: + +
+my_project$ cmake -S . -B build
+-- The C compiler identification is GNU 10.2.1
+-- The CXX compiler identification is GNU 10.2.1
+...
+-- Build files have been written to: .../my_project/build
+
+my_project$ cmake --build build
+Scanning dependencies of target gtest
+...
+[100%] Built target gmock_main
+
+my_project$ cd build && ctest
+Test project .../my_project/build
+    Start 1: HelloTest.BasicAssertions
+1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec
+
+100% tests passed, 0 tests failed out of 1
+
+Total Test time (real) =   0.01 sec
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/actions.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/actions.md new file mode 100644 index 0000000000000000000000000000000000000000..ab81a129eff692d513b27c155abed96dd30f8db6 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/actions.md @@ -0,0 +1,115 @@ +# Actions Reference + +[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a +mock function should do when invoked. This page lists the built-in actions +provided by GoogleTest. All actions are defined in the `::testing` namespace. + +## Returning a Value + +| Action | Description | +| :-------------------------------- | :-------------------------------------------- | +| `Return()` | Return from a `void` mock function. | +| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | +| `ReturnArg()` | Return the `N`-th (0-based) argument. | +| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | +| `ReturnNull()` | Return a null pointer. | +| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | +| `ReturnRef(variable)` | Return a reference to `variable`. | +| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | + +## Side Effects + +| Action | Description | +| :--------------------------------- | :-------------------------------------- | +| `Assign(&variable, value)` | Assign `value` to variable. | +| `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | +| `SaveArg(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | +| `SaveArgPointee(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | +| `SetArgReferee(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | +| `SetArgPointee(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | +| `SetArgumentPointee(value)` | Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0. | +| `SetArrayArgument(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | +| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | +| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | + +## Using a Function, Functor, or Lambda as an Action + +In the following, by "callable" we mean a free function, `std::function`, +functor, or lambda. + +| Action | Description | +| :---------------------------------- | :------------------------------------- | +| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. | +| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | +| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | +| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | +| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | +| `InvokeArgument(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | + +The return value of the invoked function is used as the return value of the +action. + +When defining a callable to be used with `Invoke*()`, you can declare any unused +parameters as `Unused`: + +```cpp +using ::testing::Invoke; +double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } +... +EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); +``` + +`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of +`callback`, which must be permanent. The type of `callback` must be a base +callback type instead of a derived one, e.g. + +```cpp + BlockingClosure* done = new BlockingClosure; + ... Invoke(done) ...; // This won't compile! + + Closure* done2 = new BlockingClosure; + ... Invoke(done2) ...; // This works. +``` + +In `InvokeArgument(...)`, if an argument needs to be passed by reference, +wrap it inside `std::ref()`. For example, + +```cpp +using ::testing::InvokeArgument; +... +InvokeArgument<2>(5, string("Hi"), std::ref(foo)) +``` + +calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by +value, and `foo` by reference. + +## Default Action + +| Action | Description | +| :------------ | :----------------------------------------------------- | +| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | + +{: .callout .note} +**Note:** due to technical reasons, `DoDefault()` cannot be used inside a +composite action - trying to do so will result in a run-time error. + +## Composite Actions + +| Action | Description | +| :----------------------------- | :------------------------------------------ | +| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | +| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | +| `WithArg(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | +| `WithArgs(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | +| `WithoutArgs(a)` | Perform action `a` without any arguments. | + +## Defining Actions + +| Macro | Description | +| :--------------------------------- | :-------------------------------------- | +| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | +| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | +| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | + +The `ACTION*` macros cannot be used inside a function or class. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/assertions.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/assertions.md new file mode 100644 index 0000000000000000000000000000000000000000..492ff5ef6937e5ae3ffc3b3a9e6cd48c3ef0227c --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/assertions.md @@ -0,0 +1,633 @@ +# Assertions Reference + +This page lists the assertion macros provided by GoogleTest for verifying code +behavior. To use them, add `#include `. + +The majority of the macros listed below come as a pair with an `EXPECT_` variant +and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal +failures and allow the current function to continue running, while `ASSERT_` +macros generate fatal failures and abort the current function. + +All assertion macros support streaming a custom failure message into them with +the `<<` operator, for example: + +```cpp +EXPECT_TRUE(my_condition) << "My condition is not true"; +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro—in particular, C strings and string objects. If a wide string (`wchar_t*`, +`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an +assertion, it will be translated to UTF-8 when printed. + +## Explicit Success and Failure {#success-failure} + +The assertions in this section generate a success or failure directly instead of +testing a value or expression. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure, as shown by the +following example: + +```c++ +switch(expression) { + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; +} +``` + +### SUCCEED {#SUCCEED} + +`SUCCEED()` + +Generates a success. This *does not* make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +The `SUCCEED` assertion is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED` messages to GoogleTest output +in the future. + +### FAIL {#FAIL} + +`FAIL()` + +Generates a fatal failure, which returns from the current function. + +Can only be used in functions that return `void`. See +[Assertion Placement](../advanced.md#assertion-placement) for more information. + +### ADD_FAILURE {#ADD_FAILURE} + +`ADD_FAILURE()` + +Generates a nonfatal failure, which allows the current function to continue +running. + +### ADD_FAILURE_AT {#ADD_FAILURE_AT} + +`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)` + +Generates a nonfatal failure at the file and line number specified. + +## Generalized Assertion {#generalized} + +The following assertion allows [matchers](matchers.md) to be used to verify +values. + +### EXPECT_THAT {#EXPECT_THAT} + +`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \ +`ASSERT_THAT(`*`value`*`,`*`matcher`*`)` + +Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*. + +For example, the following code verifies that the string `value1` starts with +`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and +10: + +```cpp +#include + +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Lt; +using ::testing::MatchesRegex; +using ::testing::StartsWith; + +... +EXPECT_THAT(value1, StartsWith("Hello")); +EXPECT_THAT(value2, MatchesRegex("Line \\d+")); +ASSERT_THAT(value3, AllOf(Gt(5), Lt(10))); +``` + +Matchers enable assertions of this form to read like English and generate +informative failure messages. For example, if the above assertion on `value1` +fails, the resulting message will be similar to the following: + +``` +Value of: value1 + Actual: "Hi, world!" +Expected: starts with "Hello" +``` + +GoogleTest provides a built-in library of matchers—see the +[Matchers Reference](matchers.md). It is also possible to write your own +matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers). +The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion. + +*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project, +which adds `assertThat()` to JUnit.* + +## Boolean Conditions {#boolean} + +The following assertions test Boolean conditions. + +### EXPECT_TRUE {#EXPECT_TRUE} + +`EXPECT_TRUE(`*`condition`*`)` \ +`ASSERT_TRUE(`*`condition`*`)` + +Verifies that *`condition`* is true. + +### EXPECT_FALSE {#EXPECT_FALSE} + +`EXPECT_FALSE(`*`condition`*`)` \ +`ASSERT_FALSE(`*`condition`*`)` + +Verifies that *`condition`* is false. + +## Binary Comparison {#binary-comparison} + +The following assertions compare two values. The value arguments must be +comparable by the assertion's comparison operator, otherwise a compiler error +will result. + +If an argument supports the `<<` operator, it will be called to print the +argument when the assertion fails. Otherwise, GoogleTest will attempt to print +them in the best way it can—see +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values). + +Arguments are always evaluated exactly once, so it's OK for the arguments to +have side effects. However, the argument evaluation order is undefined and +programs should not depend on any particular argument evaluation order. + +These assertions work with both narrow and wide string objects (`string` and +`wstring`). + +See also the [Floating-Point Comparison](#floating-point) assertions to compare +floating-point numbers and avoid problems caused by rounding. + +### EXPECT_EQ {#EXPECT_EQ} + +`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`==`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in the same memory location, not if they have the same value. Use +[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead +of `EXPECT_EQ(`*`ptr`*`, NULL)`. + +### EXPECT_NE {#EXPECT_NE} + +`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_NE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`!=`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in different memory locations, not if they have different values. Use +[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead +of `EXPECT_NE(`*`ptr`*`, NULL)`. + +### EXPECT_LT {#EXPECT_LT} + +`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<`*`val2`*. + +### EXPECT_LE {#EXPECT_LE} + +`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<=`*`val2`*. + +### EXPECT_GT {#EXPECT_GT} + +`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>`*`val2`*. + +### EXPECT_GE {#EXPECT_GE} + +`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>=`*`val2`*. + +## String Comparison {#c-strings} + +The following assertions compare two **C strings**. To compare two `string` +objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead. + +These assertions also accept wide C strings (`wchar_t*`). If a comparison of two +wide strings fails, their values will be printed as UTF-8 narrow strings. + +To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or +`EXPECT_NE(`*`c_string`*`, nullptr)`. + +### EXPECT_STREQ {#EXPECT_STREQ} + +`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents. + +### EXPECT_STRNE {#EXPECT_STRNE} + +`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents. + +### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ} + +`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents, +ignoring case. + +### EXPECT_STRCASENE {#EXPECT_STRCASENE} + +`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents, +ignoring case. + +## Floating-Point Comparison {#floating-point} + +The following assertions compare two floating-point values. + +Due to rounding errors, it is very unlikely that two floating-point values will +match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point +comparison to make sense, the user needs to carefully choose the error bound. + +GoogleTest also provides assertions that use a default error bound based on +Units in the Last Place (ULPs). To learn more about ULPs, see the article +[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ} + +`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `float` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ} + +`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `double` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_NEAR {#EXPECT_NEAR} + +`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \ +`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` + +Verifies that the difference between *`val1`* and *`val2`* does not exceed the +absolute error bound *`abs_error`*. + +## Exception Assertions {#exceptions} + +The following assertions verify that a piece of code throws, or does not throw, +an exception. Usage requires exceptions to be enabled in the build environment. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_NO_THROW({ + int n = 5; + DoSomething(&n); +}); +``` + +### EXPECT_THROW {#EXPECT_THROW} + +`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \ +`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)` + +Verifies that *`statement`* throws an exception of type *`exception_type`*. + +### EXPECT_ANY_THROW {#EXPECT_ANY_THROW} + +`EXPECT_ANY_THROW(`*`statement`*`)` \ +`ASSERT_ANY_THROW(`*`statement`*`)` + +Verifies that *`statement`* throws an exception of any type. + +### EXPECT_NO_THROW {#EXPECT_NO_THROW} + +`EXPECT_NO_THROW(`*`statement`*`)` \ +`ASSERT_NO_THROW(`*`statement`*`)` + +Verifies that *`statement`* does not throw any exception. + +## Predicate Assertions {#predicates} + +The following assertions enable more complex predicates to be verified while +printing a more clear failure message than if `EXPECT_TRUE` were used alone. + +### EXPECT_PRED* {#EXPECT_PRED} + +`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred`* returns `true` when passed the given values +as arguments. + +The parameter *`pred`* is a function or functor that accepts as many arguments +as the corresponding macro accepts values. If *`pred`* returns `true` for the +given arguments, the assertion succeeds, otherwise the assertion fails. + +When the assertion fails, it prints the value of each argument. Arguments are +always evaluated exactly once. + +As an example, see the following code: + +```cpp +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds +EXPECT_PRED2(MutuallyPrime, b, c); // Fails +``` + +In the above example, the first assertion succeeds, and the second fails with +the following message: + +``` +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` + +Note that if the given predicate is an overloaded function or a function +template, the assertion macro might not be able to determine which version to +use, and it might be necessary to explicitly specify the type of the function. +For example, for a Boolean function `IsPositive()` overloaded to take either a +single `int` or `double` argument, it would be necessary to write one of the +following: + +```cpp +EXPECT_PRED1(static_cast(IsPositive), 5); +EXPECT_PRED1(static_cast(IsPositive), 3.14); +``` + +Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error. +Similarly, to use a template function, specify the template arguments: + +```cpp +template +bool IsNegative(T x) { + return x < 0; +} +... +EXPECT_PRED1(IsNegative, -5); // Must specify type for IsNegative +``` + +If a template has multiple parameters, wrap the predicate in parentheses so the +macro arguments are parsed correctly: + +```cpp +ASSERT_PRED2((MyPredicate), 5, 0); +``` + +### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT} + +`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred_formatter`* succeeds when passed the given +values as arguments. + +The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function +or functor with the signature: + +```cpp +testing::AssertionResult PredicateFormatter(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` + +where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate +arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn` +can be either value types or reference types; if an argument has type `T`, it +can be declared as either `T` or `const T&`, whichever is appropriate. For more +about the return type `testing::AssertionResult`, see +[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult). + +As an example, see the following code: + +```cpp +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); + + return testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); +} + +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails +``` + +In the above example, the final assertion fails and the predicate-formatter +produces the following failure message: + +``` +b and c (4 and 10) are not mutually prime, as they have a common divisor 2 +``` + +## Windows HRESULT Assertions {#HRESULT} + +The following assertions test for `HRESULT` success or failure. For example: + +```cpp +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +The generated output contains the human-readable error message associated with +the returned `HRESULT` code. + +### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED} + +`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \ +`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)` + +Verifies that *`expression`* is a success `HRESULT`. + +### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} + +`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ +`ASSERT_HRESULT_FAILED(`*`expression`*`)` + +Verifies that *`expression`* is a failure `HRESULT`. + +## Death Assertions {#death} + +The following assertions verify that a piece of code causes the process to +terminate. For context, see [Death Tests](../advanced.md#death-tests). + +These assertions spawn a new process and execute the code under test in that +process. How that happens depends on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the +command-line flag `--gtest_death_test_style`. + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `"threadsafe"` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +**`"fast"`**. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_DEATH({ + int n = 5; + DoSomething(&n); +}, "Error on line .* of DoSomething()"); +``` + +### EXPECT_DEATH {#EXPECT_DEATH} + +`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with a nonzero exit +status and produces `stderr` output that matches *`matcher`*. + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `DoSomething(42)` causes +the process to die with an error message that contains the text `My error`: + +```cpp +EXPECT_DEATH(DoSomething(42), "My error"); +``` + +### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED} + +`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` + +If death tests are supported, behaves the same as +[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing. + +### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH} + +`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` + +In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in +debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*. + +### EXPECT_EXIT {#EXPECT_EXIT} + +`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \ +`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with an exit status +that satisfies *`predicate`*, and produces `stderr` output that matches +*`matcher`*. + +The parameter *`predicate`* is a function or functor that accepts an `int` exit +status and returns a `bool`. GoogleTest provides two predicates to handle common +cases: + +```cpp +// Returns true if the program exited normally with the given exit status code. +::testing::ExitedWithCode(exit_code); + +// Returns true if the program was killed by the given signal. +// Not available on Windows. +::testing::KilledBySignal(signal_number); +``` + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `NormalExit()` causes the +process to print a message containing the text `Success` to `stderr` and exit +with exit status code 0: + +```cpp +EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +``` diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/matchers.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/matchers.md new file mode 100644 index 0000000000000000000000000000000000000000..243e3f95164d3bbc6c42fb5d822409b1b91b98f4 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/matchers.md @@ -0,0 +1,302 @@ +# Matchers Reference + +A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or +`EXPECT_CALL()`, or use it to validate a value directly using two macros: + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | +| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | + +{: .callout .warning} +**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` +is supported, however note that implicit conversions can cause surprising +results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and +may pass unintentionally. + +**BEST PRACTICE:** Prefer to make the comparison explicit via +`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, +expected_value)`. + +Built-in matchers (where `argument` is the function argument, e.g. +`actual_value` in the example above, or when used in the context of +`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are +divided into several categories. All matchers are defined in the `::testing` +namespace unless otherwise noted. + +## Wildcard + +Matcher | Description +:-------------------------- | :----------------------------------------------- +`_` | `argument` can be any value of the correct type. +`A()` or `An()` | `argument` can be any value of type `type`. + +## Generic Comparison + +| Matcher | Description | +| :--------------------- | :-------------------------------------------------- | +| `Eq(value)` or `value` | `argument == value` | +| `Ge(value)` | `argument >= value` | +| `Gt(value)` | `argument > value` | +| `Le(value)` | `argument <= value` | +| `Lt(value)` | `argument < value` | +| `Ne(value)` | `argument != value` | +| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | +| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | +| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | +| `NotNull()` | `argument` is a non-null pointer (raw or smart). | +| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| +| `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | +| `Ref(variable)` | `argument` is a reference to `variable`. | +| `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | + +Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or +destructed later. If the compiler complains that `value` doesn't have a public +copy constructor, try wrap it in `std::ref()`, e.g. +`Eq(std::ref(non_copyable_value))`. If you do that, make sure +`non_copyable_value` is not changed afterwards, or the meaning of your matcher +will be changed. + +`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types +that can be explicitly converted to Boolean, but are not implicitly converted to +Boolean. In other cases, you can use the basic +[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions. + +## Floating-Point Matchers {#FpMatchers} + +| Matcher | Description | +| :------------------------------- | :--------------------------------- | +| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | +| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | +| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | +| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | + +The above matchers use ULP-based comparison (the same as used in googletest). +They automatically pick a reasonable error bound based on the absolute value of +the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, +which requires comparing two NaNs for equality to return false. The +`NanSensitive*` version instead treats two NaNs as equal, which is often what a +user wants. + +| Matcher | Description | +| :------------------------------------------------ | :----------------------- | +| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | +| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | + +## String Matchers + +The `argument` can be either a C string or a C++ string object: + +| Matcher | Description | +| :---------------------- | :------------------------------------------------- | +| `ContainsRegex(string)` | `argument` matches the given regular expression. | +| `EndsWith(suffix)` | `argument` ends with string `suffix`. | +| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | +| `IsEmpty()` | `argument` is an empty string. | +| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | +| `StartsWith(prefix)` | `argument` starts with string `prefix`. | +| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | +| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | +| `StrEq(string)` | `argument` is equal to `string`. | +| `StrNe(string)` | `argument` is not equal to `string`. | +| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. | + +`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They +use the regular expression syntax defined +[here](../advanced.md#regular-expression-syntax). All of these matchers, except +`ContainsRegex()` and `MatchesRegex()` work for wide strings as well. + +## Container Matchers + +Most STL-style containers support `==`, so you can use `Eq(expected_container)` +or simply `expected_container` to match a container exactly. If you want to +write the elements in-line, match them more flexibly, or get more informative +messages, you can use: + +| Matcher | Description | +| :---------------------------------------- | :------------------------------- | +| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | +| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | +| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. | +| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | +| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | +| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | +| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | +| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | +| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | +| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | +| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | +| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | +| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | +| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | + +**Notes:** + +* These matchers can also match: + 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), + and + 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, + int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). +* The array being matched may be multi-dimensional (i.e. its elements can be + arrays). +* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a + matcher for `::std::tuple` where `T` and `U` are the element type of + the actual container and the expected container, respectively. For example, + to compare two `Foo` containers where `Foo` doesn't support `operator==`, + one might write: + + ```cpp + MATCHER(FooEq, "") { + return std::get<0>(arg).Equals(std::get<1>(arg)); + } + ... + EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); + ``` + +## Member Matchers + +| Matcher | Description | +| :------------------------------ | :----------------------------------------- | +| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | +| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. | +| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | +| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | +| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size`+`get(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. | +| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. | +| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message. + +**Notes:** + +* You can use `FieldsAre()` to match any type that supports structured + bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate + types. For example: + + ```cpp + std::tuple my_tuple{7, "hello world"}; + EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello"))); + + struct MyStruct { + int value = 42; + std::string greeting = "aloha"; + }; + MyStruct s; + EXPECT_THAT(s, FieldsAre(42, "aloha")); + ``` + +* Don't use `Property()` against member functions that you do not own, because + taking addresses of functions is fragile and generally not part of the + contract of the function. + +## Matching the Result of a Function, Functor, or Callback + +| Matcher | Description | +| :--------------- | :------------------------------------------------ | +| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | +| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message. + +## Pointer Matchers + +| Matcher | Description | +| :------------------------ | :---------------------------------------------- | +| `Address(m)` | the result of `std::addressof(argument)` matches `m`. | +| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | +| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. | +| `WhenDynamicCastTo(m)` | when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | + +## Multi-argument Matchers {#MultiArgMatchers} + +Technically, all matchers match a *single* value. A "multi-argument" matcher is +just one that matches a *tuple*. The following matchers can be used to match a +tuple `(x, y)`: + +Matcher | Description +:------ | :---------- +`Eq()` | `x == y` +`Ge()` | `x >= y` +`Gt()` | `x > y` +`Le()` | `x <= y` +`Lt()` | `x < y` +`Ne()` | `x != y` + +You can use the following selectors to pick a subset of the arguments (or +reorder them) to participate in the matching: + +| Matcher | Description | +| :------------------------- | :---------------------------------------------- | +| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | +| `Args(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | + +## Composite Matchers + +You can make a matcher from one or more other matchers: + +| Matcher | Description | +| :------------------------------- | :-------------------------------------- | +| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | +| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | +| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.| + +## Adapters for Matchers + +| Matcher | Description | +| :---------------------- | :------------------------------------ | +| `MatcherCast(m)` | casts matcher `m` to type `Matcher`. | +| `SafeMatcherCast(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher`. | +| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | + +`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, +which must be a permanent callback. + +## Using Matchers as Predicates {#MatchersAsPredicatesCheat} + +| Matcher | Description | +| :---------------------------- | :------------------------------------------ | +| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | +| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | +| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | + +## Defining Matchers + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | +| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | +| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | + +**Notes:** + +1. The `MATCHER*` macros cannot be used inside a function or class. +2. The matcher body must be *purely functional* (i.e. it cannot have any side + effect, and the result must not depend on anything other than the value + being matched and the matcher parameters). +3. You can use `PrintToString(x)` to convert a value `x` of any type to a + string. +4. You can use `ExplainMatchResult()` in a custom matcher to wrap another + matcher, for example: + + ```cpp + MATCHER_P(NestedPropertyMatches, matcher, "") { + return ExplainMatchResult(matcher, arg.nested().property(), result_listener); + } + ``` + +5. You can use `DescribeMatcher<>` to describe another matcher. For example: + + ```cpp + MATCHER_P(XAndYThat, matcher, + "X that " + DescribeMatcher(matcher, negation) + + (negation ? " or" : " and") + " Y that " + + DescribeMatcher(matcher, negation)) { + return ExplainMatchResult(matcher, arg.x(), result_listener) && + ExplainMatchResult(matcher, arg.y(), result_listener); + } + ``` diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/mocking.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/mocking.md new file mode 100644 index 0000000000000000000000000000000000000000..ab37ebf36231e8fb654653cbe8f975b57f64218c --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/mocking.md @@ -0,0 +1,588 @@ +# Mocking Reference + +This page lists the facilities provided by GoogleTest for creating and working +with mock objects. To use them, add `#include `. + +## Macros {#macros} + +GoogleTest defines the following macros for working with mocks. + +### MOCK_METHOD {#MOCK_METHOD} + +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \ +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`), +(`*`specs...`*`));` + +Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and +return type *`return_type`* within a mock class. + +The parameters of `MOCK_METHOD` mirror the method declaration. The optional +fourth parameter *`specs...`* is a comma-separated list of qualifiers. The +following qualifiers are accepted: + +| Qualifier | Meaning | +| -------------------------- | -------------------------------------------- | +| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. | +| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. | +| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. | +| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. | +| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. | + +Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments +correctly if they are not appropriately surrounded by parentheses. See the +following example: + +```cpp +class MyMock { + public: + // The following 2 lines will not compile due to commas in the arguments: + MOCK_METHOD(std::pair, GetPair, ()); // Error! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Error! + + // One solution - wrap arguments that contain commas in parentheses: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); + + // Another solution - use type aliases: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +`MOCK_METHOD` must be used in the `public:` section of a mock class definition, +regardless of whether the method being mocked is `public`, `protected`, or +`private` in the base class. + +### EXPECT_CALL {#EXPECT_CALL} + +`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the +method *`method_name`* of the object *`mock_object`* is called with arguments +that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any +code that exercises the mock object. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The expectation will +apply only to calls of *`method_name`* whose arguments match all of the +matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to modify the expectation, and they +must be used in the following order: + +```cpp +EXPECT_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .Times(cardinality) // Can be used at most once + .InSequence(sequences...) // Can be used any number of times + .After(expectations...) // Can be used any number of times + .WillOnce(action) // Can be used any number of times + .WillRepeatedly(action) // Can be used at most once + .RetiresOnSaturation(); // Can be used at most once +``` + +See details for each modifier clause below. + +#### With {#EXPECT_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the expectation to apply only to mock function calls whose arguments +as a whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the expectation that +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +... +EXPECT_CALL(my_mock, SetPosition(_, _)) + .With(Lt()); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once on an expectation and must be the +first clause. + +#### Times {#EXPECT_CALL.Times} + +`.Times(`*`cardinality`*`)` + +Specifies how many times the mock function call is expected. + +The parameter *`cardinality`* represents the number of expected calls and can be +one of the following, all defined in the `::testing` namespace: + +| Cardinality | Meaning | +| ------------------- | --------------------------------------------------- | +| `AnyNumber()` | The function can be called any number of times. | +| `AtLeast(n)` | The function call is expected at least *n* times. | +| `AtMost(n)` | The function call is expected at most *n* times. | +| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. | +| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. | + +If the `Times` clause is omitted, GoogleTest infers the cardinality as follows: + +* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor + [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred + cardinality is `Times(1)`. +* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where + *n* >= 1, the inferred cardinality is `Times(n)`. +* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where + *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`. + +The `Times` clause can be used at most once on an expectation. + +#### InSequence {#EXPECT_CALL.InSequence} + +`.InSequence(`*`sequences...`*`)` + +Specifies that the mock function call is expected in a certain sequence. + +The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects. +Expected calls assigned to the same sequence are expected to occur in the order +the expectations are declared. + +For example, the following code sets the expectation that the `Reset()` method +of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()` +and `Describe()` can occur in any order relative to each other: + +```cpp +using ::testing::Sequence; +Sequence s1, s2; +... +EXPECT_CALL(my_mock, Reset()) + .InSequence(s1, s2); +EXPECT_CALL(my_mock, GetSize()) + .InSequence(s1); +EXPECT_CALL(my_mock, Describe()) + .InSequence(s2); +``` + +The `InSequence` clause can be used any number of times on an expectation. + +See also the [`InSequence` class](#InSequence). + +#### After {#EXPECT_CALL.After} + +`.After(`*`expectations...`*`)` + +Specifies that the mock function call is expected to occur after one or more +other calls. + +The parameter *`expectations...`* can be up to five +[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects. +The mock function call is expected to occur after all of the given expectations. + +For example, the following code sets the expectation that the `Describe()` +method of `my_mock` is called only after both `InitX()` and `InitY()` have been +called. + +```cpp +using ::testing::Expectation; +... +Expectation init_x = EXPECT_CALL(my_mock, InitX()); +Expectation init_y = EXPECT_CALL(my_mock, InitY()); +EXPECT_CALL(my_mock, Describe()) + .After(init_x, init_y); +``` + +The `ExpectationSet` object is helpful when the number of prerequisites for an +expectation is large or variable, for example: + +```cpp +using ::testing::ExpectationSet; +... +ExpectationSet all_inits; +// Collect all expectations of InitElement() calls +for (int i = 0; i < element_count; i++) { + all_inits += EXPECT_CALL(my_mock, InitElement(i)); +} +EXPECT_CALL(my_mock, Describe()) + .After(all_inits); // Expect Describe() call after all InitElement() calls +``` + +The `After` clause can be used any number of times on an expectation. + +#### WillOnce {#EXPECT_CALL.WillOnce} + +`.WillOnce(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for a single +matching function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillOnce` implicitly sets a cardinality on the expectation when +`Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +Each matching function call will perform the next action in the order declared. +For example, the following code specifies that `my_mock.GetNumber()` is expected +to be called exactly 3 times and will return `1`, `2`, and `3` respectively on +the first, second, and third calls: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillOnce(Return(3)); +``` + +The `WillOnce` clause can be used any number of times on an expectation. Unlike +`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most +once, so may be a move-only type and/or have an `&&`-qualified call operator. + +#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} + +`.WillRepeatedly(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for all subsequent +matching function calls. Takes effect after the actions specified in the +[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillRepeatedly` implicitly sets a cardinality on the expectation +when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +If any `WillOnce` clauses have been specified, matching function calls will +perform those actions before the action specified by `WillRepeatedly`. See the +following example: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetName()) + .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls + +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(42)) // Return 42 on the first call + .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls +``` + +The `WillRepeatedly` clause can be used at most once on an expectation. + +#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation} + +`.RetiresOnSaturation()` + +Indicates that the expectation will no longer be active after the expected +number of matching function calls has been reached. + +The `RetiresOnSaturation` clause is only meaningful for expectations with an +upper-bounded cardinality. The expectation will *retire* (no longer match any +function calls) after it has been *saturated* (the upper bound has been +reached). See the following example: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1 + .Times(AnyNumber()); +EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2 + .Times(2) + .RetiresOnSaturation(); +``` + +In the above example, the first two calls to `my_mock.SetNumber(7)` match +expectation 2, which then becomes inactive and no longer matches any calls. A +third call to `my_mock.SetNumber(7)` would then match expectation 1. Without +`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)` +would match expectation 2 again, producing a failure since the limit of 2 calls +was exceeded. + +The `RetiresOnSaturation` clause can be used at most once on an expectation and +must be the last clause. + +### ON_CALL {#ON_CALL} + +`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Defines what happens when the method *`method_name`* of the object +*`mock_object`* is called with arguments that match the given matchers +*`matchers...`*. Requires a modifier clause to specify the method's behavior. +*Does not* set any expectations that the method will be called. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The `ON_CALL` +specification will apply only to calls of *`method_name`* whose arguments match +all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to set the method's behavior, and +they must be used in the following order: + +```cpp +ON_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .WillByDefault(action); // Required +``` + +See details for each modifier clause below. + +#### With {#ON_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the specification to only mock function calls whose arguments as a +whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the default behavior when +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... +ON_CALL(my_mock, SetPosition(_, _)) + .With(Lt()) + .WillByDefault(Return(true)); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once with each `ON_CALL` statement. + +#### WillByDefault {#ON_CALL.WillByDefault} + +`.WillByDefault(`*`action`*`)` + +Specifies the default behavior of a matching mock function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +For example, the following code specifies that by default, a call to +`my_mock.Greet()` will return `"hello"`: + +```cpp +using ::testing::Return; +... +ON_CALL(my_mock, Greet()) + .WillByDefault(Return("hello")); +``` + +The action specified by `WillByDefault` is superseded by the actions specified +on a matching `EXPECT_CALL` statement, if any. See the +[`WillOnce`](#EXPECT_CALL.WillOnce) and +[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`. + +The `WillByDefault` clause must be used exactly once with each `ON_CALL` +statement. + +## Classes {#classes} + +GoogleTest defines the following classes for working with mocks. + +### DefaultValue {#DefaultValue} + +`::testing::DefaultValue` + +Allows a user to specify the default value for a type `T` that is both copyable +and publicly destructible (i.e. anything that can be used as a function return +type). For mock functions with a return type of `T`, this default value is +returned from function calls that do not specify an action. + +Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the +default value: + +```cpp +// Sets the default value to be returned. T must be copy constructible. +DefaultValue::Set(value); + +// Sets a factory. Will be invoked on demand. T must be move constructible. +T MakeT(); +DefaultValue::SetFactory(&MakeT); + +// Unsets the default value. +DefaultValue::Clear(); +``` + +### NiceMock {#NiceMock} + +`::testing::NiceMock` + +Represents a mock object that suppresses warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NiceMock` is analogous to usage of `T`. `NiceMock` is a subclass +of `T`, so it can be used wherever an object of type `T` is accepted. In +addition, `NiceMock` can be constructed with any arguments that a constructor +of `T` accepts. + +For example, the following code suppresses warnings on the mock `my_mock` of +type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NiceMock; +... +NiceMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`NiceMock` only works for mock methods defined using the `MOCK_METHOD` macro +directly in the definition of class `T`. If a mock method is defined in a base +class of `T`, a warning might still be generated. + +`NiceMock` might not work correctly if the destructor of `T` is not virtual. + +### NaggyMock {#NaggyMock} + +`::testing::NaggyMock` + +Represents a mock object that generates warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NaggyMock` is analogous to usage of `T`. `NaggyMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `NaggyMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates warnings on the mock `my_mock` of type +`MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NaggyMock; +... +NaggyMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +Mock objects of type `T` by default behave the same way as `NaggyMock`. + +### StrictMock {#StrictMock} + +`::testing::StrictMock` + +Represents a mock object that generates test failures on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `StrictMock` is analogous to usage of `T`. `StrictMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `StrictMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates a test failure on the mock `my_mock` +of type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::StrictMock; +... +StrictMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`StrictMock` only works for mock methods defined using the `MOCK_METHOD` +macro directly in the definition of class `T`. If a mock method is defined in a +base class of `T`, a failure might not be generated. + +`StrictMock` might not work correctly if the destructor of `T` is not +virtual. + +### Sequence {#Sequence} + +`::testing::Sequence` + +Represents a chronological sequence of expectations. See the +[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage. + +### InSequence {#InSequence} + +`::testing::InSequence` + +An object of this type causes all expectations encountered in its scope to be +put in an anonymous sequence. + +This allows more convenient expression of multiple expectations in a single +sequence: + +```cpp +using ::testing::InSequence; +{ + InSequence seq; + + // The following are expected to occur in the order declared. + EXPECT_CALL(...); + EXPECT_CALL(...); + ... + EXPECT_CALL(...); +} +``` + +The name of the `InSequence` object does not matter. + +### Expectation {#Expectation} + +`::testing::Expectation` + +Represents a mock function call expectation as created by +[`EXPECT_CALL`](#EXPECT_CALL): + +```cpp +using ::testing::Expectation; +Expectation my_expectation = EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. + +### ExpectationSet {#ExpectationSet} + +`::testing::ExpectationSet` + +Represents a set of mock function call expectations. + +Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set: + +```cpp +using ::testing::ExpectationSet; +ExpectationSet my_expectations; +my_expectations += EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/testing.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/testing.md new file mode 100644 index 0000000000000000000000000000000000000000..3ed5211117870eb1e4c18919c120b5380c644263 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/reference/testing.md @@ -0,0 +1,1453 @@ +# Testing Reference + + + +This page lists the facilities provided by GoogleTest for writing test programs. +To use them, add `#include `. + +## Macros + +GoogleTest defines the following macros for writing tests. + +### TEST {#TEST} + +
+TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* in the test suite +*`TestSuiteName`*, consisting of the given statements. + +Both arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers +and must not contain underscores (`_`). Tests in different test suites can have +the same individual name. + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_F {#TEST_F} + +
+TEST_F(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* that uses the test fixture class +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a test fixture class—see +[Test Fixtures](../primer.md#same-data-multiple-tests). + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_P {#TEST_P} + +
+TEST_P(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual value-parameterized test named *`TestName`* that uses the +test fixture class *`TestFixtureName`*. The test suite name is +*`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a value-parameterized test fixture class—see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +The statements within the test body can be any code under test. Within the test +body, the test parameter can be accessed with the `GetParam()` function (see +[`WithParamInterface`](#WithParamInterface)). For example: + +```cpp +TEST_P(MyTestSuite, DoesSomething) { + ... + EXPECT_TRUE(DoSomething(GetParam())); + ... +} +``` + +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +See also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). + +### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P} + +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)` +\ +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)` + +Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with +[`TEST_P`](#TEST_P)). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. If *`InstantiationName`* is empty +(`INSTANTIATE_TEST_SUITE_P(, ...)`), no prefix is added. + +The argument *`param_generator`* is one of the following GoogleTest-provided +functions that generate the test parameters, all defined in the `::testing` +namespace: + + + +| Parameter Generator | Behavior | +| ------------------- | ---------------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | +| `ConvertGenerator(g)` | Yields values generated by generator `g`, `static_cast` to `T`. | + +The optional last argument *`name_generator`* is a function or functor that +generates custom test name suffixes based on the test parameters. The function +must accept an argument of type +[`TestParamInfo`](#TestParamInfo) and return a `std::string`. +The test name suffix can only contain alphanumeric characters and underscores. +GoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a +custom function can be used for more control: + +```cpp +INSTANTIATE_TEST_SUITE_P( + MyInstantiation, MyTestSuite, + testing::Values(...), + [](const testing::TestParamInfo& info) { + // Can use info.param here to generate the test suffix + std::string name = ... + return name; + }); +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +See also +[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST). + +### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} + +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`,`*`NameGenerator`*`)` + +Defines a typed test suite based on the test fixture *`TestFixtureName`*. The +test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type, for example: + +```cpp +template +class MyFixture : public testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. + +The optional third argument *`NameGenerator`* allows specifying a class that +exposes a templated static function `GetName(int)`. For example: + +```cpp +class NameGenerator { + public: + template + static std::string GetName(int) { + if constexpr (std::is_same_v) return "char"; + if constexpr (std::is_same_v) return "int"; + if constexpr (std::is_same_v) return "unsignedInt"; + } +}; +TYPED_TEST_SUITE(MyFixture, MyTypes, NameGenerator); +``` + +See also [`TYPED_TEST`](#TYPED_TEST) and +[Typed Tests](../advanced.md#typed-tests) for more information. + +### TYPED_TEST {#TYPED_TEST} + +
+TYPED_TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual typed test named *`TestName`* in the typed test suite +*`TestSuiteName`*. The test suite must be defined with +[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See the following example: + +```cpp +TYPED_TEST(MyFixture, Example) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of MyFixture via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} +``` + +For more information, see [Typed Tests](../advanced.md#typed-tests). + +### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P} + +`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)` + +Defines a type-parameterized test suite based on the test fixture +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example. + +See also [`TYPED_TEST_P`](#TYPED_TEST_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### TYPED_TEST_P {#TYPED_TEST_P} + +
+TYPED_TEST_P(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual type-parameterized test named *`TestName`* in the +type-parameterized test suite *`TestSuiteName`*. The test suite must be defined +with [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST) +for an example. + +See also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P} + +`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)` + +Registers the type-parameterized tests *`TestNames...`* of the test suite +*`TestSuiteName`*. The test suite and tests must be defined with +[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P). + +For example: + +```cpp +// Define the test suite and tests. +TYPED_TEST_SUITE_P(MyFixture); +TYPED_TEST_P(MyFixture, HasPropertyA) { ... } +TYPED_TEST_P(MyFixture, HasPropertyB) { ... } + +// Register the tests in the test suite. +REGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB); +``` + +See also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P} + +`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)` + +Instantiates the type-parameterized test suite *`TestSuiteName`*. The test suite +must be registered with +[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. If *`InstantiationName`* is empty +(`INSTANTIATE_TYPED_TEST_SUITE_P(, ...)`), no prefix is added. + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly. + +For more information, see +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +### FRIEND_TEST {#FRIEND_TEST} + +`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)` + +Within a class body, declares an individual test as a friend of the class, +enabling the test to access private class members. + +If the class is defined in a namespace, then in order to be friends of the +class, test fixtures and tests must be defined in the exact same namespace, +without inline or anonymous namespaces. + +For example, if the class definition looks like the following: + +```cpp +namespace my_namespace { + +class MyClass { + friend class MyClassTest; + FRIEND_TEST(MyClassTest, HasPropertyA); + FRIEND_TEST(MyClassTest, HasPropertyB); + ... definition of class MyClass ... +}; + +} // namespace my_namespace +``` + +Then the test code should look like: + +```cpp +namespace my_namespace { + +class MyClassTest : public testing::Test { + ... +}; + +TEST_F(MyClassTest, HasPropertyA) { ... } +TEST_F(MyClassTest, HasPropertyB) { ... } + +} // namespace my_namespace +``` + +See [Testing Private Code](../advanced.md#testing-private-code) for more +information. + +### SCOPED_TRACE {#SCOPED_TRACE} + +`SCOPED_TRACE(`*`message`*`)` + +Causes the current file name, line number, and the given message *`message`* to +be added to the failure message for each assertion failure that occurs in the +scope. + +For more information, see +[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions). + +See also the [`ScopedTrace` class](#ScopedTrace). + +### GTEST_SKIP {#GTEST_SKIP} + +`GTEST_SKIP()` + +Prevents further test execution at runtime. + +Can be used in individual test cases or in the `SetUp()` methods of test +environments or test fixtures (classes derived from the +[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global +test environment `SetUp()` method, it skips all tests in the test program. If +used in a test fixture `SetUp()` method, it skips all tests in the corresponding +test suite. + +Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it. + +See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more +information. + +### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST} + +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)` + +Allows the value-parameterized test suite *`TestSuiteName`* to be +uninstantiated. + +By default, every [`TEST_P`](#TEST_P) call without a corresponding +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing +test in the test suite `GoogleTestVerification`. +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the +given test suite. + +## Classes and types + +GoogleTest defines the following classes and types to help with writing tests. + +### AssertionResult {#AssertionResult} + +`testing::AssertionResult` + +A class for indicating whether an assertion was successful. + +When the assertion wasn't successful, the `AssertionResult` object stores a +non-empty failure message that can be retrieved with the object's `message()` +method. + +To create an instance of this class, use one of the factory functions +[`AssertionSuccess()`](#AssertionSuccess) or +[`AssertionFailure()`](#AssertionFailure). + +### AssertionException {#AssertionException} + +`testing::AssertionException` + +Exception which can be thrown from +[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). + +### EmptyTestEventListener {#EmptyTestEventListener} + +`testing::EmptyTestEventListener` + +Provides an empty implementation of all methods in the +[`TestEventListener`](#TestEventListener) interface, such that a subclass only +needs to override the methods it cares about. + +### Environment {#Environment} + +`testing::Environment` + +Represents a global test environment. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). + +#### Protected Methods {#Environment-protected} + +##### SetUp {#Environment::SetUp} + +`virtual void Environment::SetUp()` + +Override this to define how to set up the environment. + +##### TearDown {#Environment::TearDown} + +`virtual void Environment::TearDown()` + +Override this to define how to tear down the environment. + +### ScopedTrace {#ScopedTrace} + +`testing::ScopedTrace` + +An instance of this class causes a trace to be included in every test failure +message generated by code in the scope of the lifetime of the `ScopedTrace` +instance. The effect is undone with the destruction of the instance. + +The `ScopedTrace` constructor has the following form: + +```cpp +template +ScopedTrace(const char* file, int line, const T& message) +``` + +Example usage: + +```cpp +testing::ScopedTrace trace("file.cc", 123, "message"); +``` + +The resulting trace includes the given source file path and line number, and the +given message. The `message` argument can be anything streamable to +`std::ostream`. + +See also [`SCOPED_TRACE`](#SCOPED_TRACE). + +### Test {#Test} + +`testing::Test` + +The abstract class that all tests inherit from. `Test` is not copyable. + +#### Public Methods {#Test-public} + +##### SetUpTestSuite {#Test::SetUpTestSuite} + +`static void Test::SetUpTestSuite()` + +Performs shared setup for all tests in the test suite. GoogleTest calls +`SetUpTestSuite()` before running the first test in the test suite. + +##### TearDownTestSuite {#Test::TearDownTestSuite} + +`static void Test::TearDownTestSuite()` + +Performs shared teardown for all tests in the test suite. GoogleTest calls +`TearDownTestSuite()` after running the last test in the test suite. + +##### HasFatalFailure {#Test::HasFatalFailure} + +`static bool Test::HasFatalFailure()` + +Returns true if and only if the current test has a fatal failure. + +##### HasNonfatalFailure {#Test::HasNonfatalFailure} + +`static bool Test::HasNonfatalFailure()` + +Returns true if and only if the current test has a nonfatal failure. + +##### HasFailure {#Test::HasFailure} + +`static bool Test::HasFailure()` + +Returns true if and only if the current test has any failure, either fatal or +nonfatal. + +##### IsSkipped {#Test::IsSkipped} + +`static bool Test::IsSkipped()` + +Returns true if and only if the current test was skipped. + +##### RecordProperty {#Test::RecordProperty} + +`static void Test::RecordProperty(const std::string& key, const std::string& +value)` \ +`static void Test::RecordProperty(const std::string& key, int value)` + +Logs a property for the current test, test suite, or entire invocation of the +test program. Only the last value for a given key is logged. + +The key must be a valid XML attribute name, and cannot conflict with the ones +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). + +`RecordProperty` is `public static` so it can be called from utility functions +that are not members of the test fixture. + +Calls to `RecordProperty` made during the lifespan of the test (from the moment +its constructor starts to the moment its destructor finishes) are output in XML +as attributes of the `` element. Properties recorded from a fixture's +`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the +corresponding `` element. Calls to `RecordProperty` made in the +global context (before or after invocation of `RUN_ALL_TESTS` or from the +`SetUp`/`TearDown` methods of registered `Environment` objects) are output as +attributes of the `` element. + +#### Protected Methods {#Test-protected} + +##### SetUp {#Test::SetUp} + +`virtual void Test::SetUp()` + +Override this to perform test fixture setup. GoogleTest calls `SetUp()` before +running each individual test. + +##### TearDown {#Test::TearDown} + +`virtual void Test::TearDown()` + +Override this to perform test fixture teardown. GoogleTest calls `TearDown()` +after running each individual test. + +### TestWithParam {#TestWithParam} + +`testing::TestWithParam` + +A convenience class which inherits from both [`Test`](#Test) and +[`WithParamInterface`](#WithParamInterface). + +### TestSuite {#TestSuite} + +Represents a test suite. `TestSuite` is not copyable. + +#### Public Methods {#TestSuite-public} + +##### name {#TestSuite::name} + +`const char* TestSuite::name() const` + +Gets the name of the test suite. + +##### type_param {#TestSuite::type_param} + +`const char* TestSuite::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### should_run {#TestSuite::should_run} + +`bool TestSuite::should_run() const` + +Returns true if any test in this test suite should run. + +##### successful_test_count {#TestSuite::successful_test_count} + +`int TestSuite::successful_test_count() const` + +Gets the number of successful tests in this test suite. + +##### skipped_test_count {#TestSuite::skipped_test_count} + +`int TestSuite::skipped_test_count() const` + +Gets the number of skipped tests in this test suite. + +##### failed_test_count {#TestSuite::failed_test_count} + +`int TestSuite::failed_test_count() const` + +Gets the number of failed tests in this test suite. + +##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count} + +`int TestSuite::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#TestSuite::disabled_test_count} + +`int TestSuite::disabled_test_count() const` + +Gets the number of disabled tests in this test suite. + +##### reportable_test_count {#TestSuite::reportable_test_count} + +`int TestSuite::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### test_to_run_count {#TestSuite::test_to_run_count} + +`int TestSuite::test_to_run_count() const` + +Get the number of tests in this test suite that should run. + +##### total_test_count {#TestSuite::total_test_count} + +`int TestSuite::total_test_count() const` + +Gets the number of all tests in this test suite. + +##### Passed {#TestSuite::Passed} + +`bool TestSuite::Passed() const` + +Returns true if and only if the test suite passed. + +##### Failed {#TestSuite::Failed} + +`bool TestSuite::Failed() const` + +Returns true if and only if the test suite failed. + +##### elapsed_time {#TestSuite::elapsed_time} + +`TimeInMillis TestSuite::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestSuite::start_timestamp} + +`TimeInMillis TestSuite::start_timestamp() const` + +Gets the time of the test suite start, in ms from the start of the UNIX epoch. + +##### GetTestInfo {#TestSuite::GetTestInfo} + +`const TestInfo* TestSuite::GetTestInfo(int i) const` + +Returns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i` +can range from 0 to `total_test_count() - 1`. If `i` is not in that range, +returns `NULL`. + +##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result} + +`const TestResult& TestSuite::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) that holds test properties recorded +during execution of `SetUpTestSuite` and `TearDownTestSuite`. + +### TestInfo {#TestInfo} + +`testing::TestInfo` + +Stores information about a test. + +#### Public Methods {#TestInfo-public} + +##### test_suite_name {#TestInfo::test_suite_name} + +`const char* TestInfo::test_suite_name() const` + +Returns the test suite name. + +##### name {#TestInfo::name} + +`const char* TestInfo::name() const` + +Returns the test name. + +##### type_param {#TestInfo::type_param} + +`const char* TestInfo::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### value_param {#TestInfo::value_param} + +`const char* TestInfo::value_param() const` + +Returns the text representation of the value parameter, or `NULL` if this is not +a value-parameterized test. See +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +##### file {#TestInfo::file} + +`const char* TestInfo::file() const` + +Returns the file name where this test is defined. + +##### line {#TestInfo::line} + +`int TestInfo::line() const` + +Returns the line where this test is defined. + +##### is_in_another_shard {#TestInfo::is_in_another_shard} + +`bool TestInfo::is_in_another_shard() const` + +Returns true if this test should not be run because it's in another shard. + +##### should_run {#TestInfo::should_run} + +`bool TestInfo::should_run() const` + +Returns true if this test should run, that is if the test is not disabled (or it +is disabled but the `also_run_disabled_tests` flag has been specified) and its +full name matches the user-specified filter. + +GoogleTest allows the user to filter the tests by their full names. Only the +tests that match the filter will run. See +[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests) +for more information. + +##### is_reportable {#TestInfo::is_reportable} + +`bool TestInfo::is_reportable() const` + +Returns true if and only if this test will appear in the XML report. + +##### result {#TestInfo::result} + +`const TestResult* TestInfo::result() const` + +Returns the result of the test. See [`TestResult`](#TestResult). + +### TestParamInfo {#TestParamInfo} + +`testing::TestParamInfo` + +Describes a parameter to a value-parameterized test. The type `T` is the type of +the parameter. + +Contains the fields `param` and `index` which hold the value of the parameter +and its integer index respectively. + +### UnitTest {#UnitTest} + +`testing::UnitTest` + +This class contains information about the test program. + +`UnitTest` is a singleton class. The only instance is created when +`UnitTest::GetInstance()` is first called. This instance is never deleted. + +`UnitTest` is not copyable. + +#### Public Methods {#UnitTest-public} + +##### GetInstance {#UnitTest::GetInstance} + +`static UnitTest* UnitTest::GetInstance()` + +Gets the singleton `UnitTest` object. The first time this method is called, a +`UnitTest` object is constructed and returned. Consecutive calls will return the +same object. + +##### original_working_dir {#UnitTest::original_working_dir} + +`const char* UnitTest::original_working_dir() const` + +Returns the working directory when the first [`TEST()`](#TEST) or +[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string. + +##### current_test_suite {#UnitTest::current_test_suite} + +`const TestSuite* UnitTest::current_test_suite() const` + +Returns the [`TestSuite`](#TestSuite) object for the test that's currently +running, or `NULL` if no test is running. + +##### current_test_info {#UnitTest::current_test_info} + +`const TestInfo* UnitTest::current_test_info() const` + +Returns the [`TestInfo`](#TestInfo) object for the test that's currently +running, or `NULL` if no test is running. + +##### random_seed {#UnitTest::random_seed} + +`int UnitTest::random_seed() const` + +Returns the random seed used at the start of the current test run. + +##### successful_test_suite_count {#UnitTest::successful_test_suite_count} + +`int UnitTest::successful_test_suite_count() const` + +Gets the number of successful test suites. + +##### failed_test_suite_count {#UnitTest::failed_test_suite_count} + +`int UnitTest::failed_test_suite_count() const` + +Gets the number of failed test suites. + +##### total_test_suite_count {#UnitTest::total_test_suite_count} + +`int UnitTest::total_test_suite_count() const` + +Gets the number of all test suites. + +##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count} + +`int UnitTest::test_suite_to_run_count() const` + +Gets the number of all test suites that contain at least one test that should +run. + +##### successful_test_count {#UnitTest::successful_test_count} + +`int UnitTest::successful_test_count() const` + +Gets the number of successful tests. + +##### skipped_test_count {#UnitTest::skipped_test_count} + +`int UnitTest::skipped_test_count() const` + +Gets the number of skipped tests. + +##### failed_test_count {#UnitTest::failed_test_count} + +`int UnitTest::failed_test_count() const` + +Gets the number of failed tests. + +##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count} + +`int UnitTest::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#UnitTest::disabled_test_count} + +`int UnitTest::disabled_test_count() const` + +Gets the number of disabled tests. + +##### reportable_test_count {#UnitTest::reportable_test_count} + +`int UnitTest::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### total_test_count {#UnitTest::total_test_count} + +`int UnitTest::total_test_count() const` + +Gets the number of all tests. + +##### test_to_run_count {#UnitTest::test_to_run_count} + +`int UnitTest::test_to_run_count() const` + +Gets the number of tests that should run. + +##### start_timestamp {#UnitTest::start_timestamp} + +`TimeInMillis UnitTest::start_timestamp() const` + +Gets the time of the test program start, in ms from the start of the UNIX epoch. + +##### elapsed_time {#UnitTest::elapsed_time} + +`TimeInMillis UnitTest::elapsed_time() const` + +Gets the elapsed time, in milliseconds. + +##### Passed {#UnitTest::Passed} + +`bool UnitTest::Passed() const` + +Returns true if and only if the unit test passed (i.e. all test suites passed). + +##### Failed {#UnitTest::Failed} + +`bool UnitTest::Failed() const` + +Returns true if and only if the unit test failed (i.e. some test suite failed or +something outside of all tests failed). + +##### GetTestSuite {#UnitTest::GetTestSuite} + +`const TestSuite* UnitTest::GetTestSuite(int i) const` + +Gets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all +the test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i` +is not in that range, returns `NULL`. + +##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result} + +`const TestResult& UnitTest::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) containing information on test failures +and properties logged outside of individual test suites. + +##### listeners {#UnitTest::listeners} + +`TestEventListeners& UnitTest::listeners()` + +Returns the list of event listeners that can be used to track events inside +GoogleTest. See [`TestEventListeners`](#TestEventListeners). + +### TestEventListener {#TestEventListener} + +`testing::TestEventListener` + +The interface for tracing execution of tests. The methods below are listed in +the order the corresponding events are fired. + +#### Public Methods {#TestEventListener-public} + +##### OnTestProgramStart {#TestEventListener::OnTestProgramStart} + +`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)` + +Fired before any test activity starts. + +##### OnTestIterationStart {#TestEventListener::OnTestIterationStart} + +`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test, +int iteration)` + +Fired before each iteration of tests starts. There may be more than one +iteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index, +starting from 0. + +##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart} + +`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest& +unit_test)` + +Fired before environment set-up for each iteration of tests starts. + +##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd} + +`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest& +unit_test)` + +Fired after environment set-up for each iteration of tests ends. + +##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart} + +`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)` + +Fired before the test suite starts. + +##### OnTestStart {#TestEventListener::OnTestStart} + +`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)` + +Fired before the test starts. + +##### OnTestPartResult {#TestEventListener::OnTestPartResult} + +`virtual void TestEventListener::OnTestPartResult(const TestPartResult& +test_part_result)` + +Fired after a failed assertion or a `SUCCEED()` invocation. If you want to throw +an exception from this function to skip to the next test, it must be an +[`AssertionException`](#AssertionException) or inherited from it. + +##### OnTestEnd {#TestEventListener::OnTestEnd} + +`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)` + +Fired after the test ends. + +##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd} + +`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)` + +Fired after the test suite ends. + +##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart} + +`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest& +unit_test)` + +Fired before environment tear-down for each iteration of tests starts. + +##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd} + +`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest& +unit_test)` + +Fired after environment tear-down for each iteration of tests ends. + +##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd} + +`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test, +int iteration)` + +Fired after each iteration of tests finishes. + +##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd} + +`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)` + +Fired after all test activities have ended. + +### TestEventListeners {#TestEventListeners} + +`testing::TestEventListeners` + +Lets users add listeners to track events in GoogleTest. + +#### Public Methods {#TestEventListeners-public} + +##### Append {#TestEventListeners::Append} + +`void TestEventListeners::Append(TestEventListener* listener)` + +Appends an event listener to the end of the list. GoogleTest assumes ownership +of the listener (i.e. it will delete the listener when the test program +finishes). + +##### Release {#TestEventListeners::Release} + +`TestEventListener* TestEventListeners::Release(TestEventListener* listener)` + +Removes the given event listener from the list and returns it. It then becomes +the caller's responsibility to delete the listener. Returns `NULL` if the +listener is not found in the list. + +##### default_result_printer {#TestEventListeners::default_result_printer} + +`TestEventListener* TestEventListeners::default_result_printer() const` + +Returns the standard listener responsible for the default console output. Can be +removed from the listeners list to shut down default console output. Note that +removing this object from the listener list with +[`Release()`](#TestEventListeners::Release) transfers its ownership to the +caller and makes this function return `NULL` the next time. + +##### default_xml_generator {#TestEventListeners::default_xml_generator} + +`TestEventListener* TestEventListeners::default_xml_generator() const` + +Returns the standard listener responsible for the default XML output controlled +by the `--gtest_output=xml` flag. Can be removed from the listeners list by +users who want to shut down the default XML output controlled by this flag and +substitute it with custom one. Note that removing this object from the listener +list with [`Release()`](#TestEventListeners::Release) transfers its ownership to +the caller and makes this function return `NULL` the next time. + +### TestPartResult {#TestPartResult} + +`testing::TestPartResult` + +A copyable object representing the result of a test part (i.e. an assertion or +an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). + +#### Public Methods {#TestPartResult-public} + +##### type {#TestPartResult::type} + +`Type TestPartResult::type() const` + +Gets the outcome of the test part. + +The return type `Type` is an enum defined as follows: + +```cpp +enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure, // Failed and the test should be terminated. + kSkip // Skipped. +}; +``` + +##### file_name {#TestPartResult::file_name} + +`const char* TestPartResult::file_name() const` + +Gets the name of the source file where the test part took place, or `NULL` if +it's unknown. + +##### line_number {#TestPartResult::line_number} + +`int TestPartResult::line_number() const` + +Gets the line in the source file where the test part took place, or `-1` if it's +unknown. + +##### summary {#TestPartResult::summary} + +`const char* TestPartResult::summary() const` + +Gets the summary of the failure message. + +##### message {#TestPartResult::message} + +`const char* TestPartResult::message() const` + +Gets the message associated with the test part. + +##### skipped {#TestPartResult::skipped} + +`bool TestPartResult::skipped() const` + +Returns true if and only if the test part was skipped. + +##### passed {#TestPartResult::passed} + +`bool TestPartResult::passed() const` + +Returns true if and only if the test part passed. + +##### nonfatally_failed {#TestPartResult::nonfatally_failed} + +`bool TestPartResult::nonfatally_failed() const` + +Returns true if and only if the test part non-fatally failed. + +##### fatally_failed {#TestPartResult::fatally_failed} + +`bool TestPartResult::fatally_failed() const` + +Returns true if and only if the test part fatally failed. + +##### failed {#TestPartResult::failed} + +`bool TestPartResult::failed() const` + +Returns true if and only if the test part failed. + +### TestProperty {#TestProperty} + +`testing::TestProperty` + +A copyable object representing a user-specified test property which can be +output as a key/value string pair. + +#### Public Methods {#TestProperty-public} + +##### key {#key} + +`const char* key() const` + +Gets the user-supplied key. + +##### value {#value} + +`const char* value() const` + +Gets the user-supplied value. + +##### SetValue {#SetValue} + +`void SetValue(const std::string& new_value)` + +Sets a new value, overriding the previous one. + +### TestResult {#TestResult} + +`testing::TestResult` + +Contains information about the result of a single test. + +`TestResult` is not copyable. + +#### Public Methods {#TestResult-public} + +##### total_part_count {#TestResult::total_part_count} + +`int TestResult::total_part_count() const` + +Gets the number of all test parts. This is the sum of the number of successful +test parts and the number of failed test parts. + +##### test_property_count {#TestResult::test_property_count} + +`int TestResult::test_property_count() const` + +Returns the number of test properties. + +##### Passed {#TestResult::Passed} + +`bool TestResult::Passed() const` + +Returns true if and only if the test passed (i.e. no test part failed). + +##### Skipped {#TestResult::Skipped} + +`bool TestResult::Skipped() const` + +Returns true if and only if the test was skipped. + +##### Failed {#TestResult::Failed} + +`bool TestResult::Failed() const` + +Returns true if and only if the test failed. + +##### HasFatalFailure {#TestResult::HasFatalFailure} + +`bool TestResult::HasFatalFailure() const` + +Returns true if and only if the test fatally failed. + +##### HasNonfatalFailure {#TestResult::HasNonfatalFailure} + +`bool TestResult::HasNonfatalFailure() const` + +Returns true if and only if the test has a non-fatal failure. + +##### elapsed_time {#TestResult::elapsed_time} + +`TimeInMillis TestResult::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestResult::start_timestamp} + +`TimeInMillis TestResult::start_timestamp() const` + +Gets the time of the test case start, in ms from the start of the UNIX epoch. + +##### GetTestPartResult {#TestResult::GetTestPartResult} + +`const TestPartResult& TestResult::GetTestPartResult(int i) const` + +Returns the [`TestPartResult`](#TestPartResult) for the `i`-th test part result +among all the results. `i` can range from 0 to `total_part_count() - 1`. If `i` +is not in that range, aborts the program. + +##### GetTestProperty {#TestResult::GetTestProperty} + +`const TestProperty& TestResult::GetTestProperty(int i) const` + +Returns the [`TestProperty`](#TestProperty) object for the `i`-th test property. +`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that +range, aborts the program. + +### TimeInMillis {#TimeInMillis} + +`testing::TimeInMillis` + +An integer type representing time in milliseconds. + +### Types {#Types} + +`testing::Types` + +Represents a list of types for use in typed tests and type-parameterized tests. + +The template argument `T...` can be any number of types, for example: + +``` +testing::Types +``` + +See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### WithParamInterface {#WithParamInterface} + +`testing::WithParamInterface` + +The pure interface class that all value-parameterized tests inherit from. + +A value-parameterized test fixture class must inherit from both [`Test`](#Test) +and `WithParamInterface`. In most cases that just means inheriting from +[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may +need to inherit from `Test` and `WithParamInterface` at different levels. + +This interface defines the type alias `ParamType` for the parameter type `T` and +has support for accessing the test parameter value via the `GetParam()` method: + +``` +static const ParamType& GetParam() +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +## Functions + +GoogleTest defines the following functions to help with writing and running +tests. + +### InitGoogleTest {#InitGoogleTest} + +`void testing::InitGoogleTest(int* argc, char** argv)` \ +`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \ +`void testing::InitGoogleTest()` + +Initializes GoogleTest. This must be called before calling +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line +for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it +is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv` +must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is +already the case with the default `argv` passed to `main`. + +No value is returned. Instead, the GoogleTest flag variables are updated. + +The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows +programs compiled in `UNICODE` mode. + +The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded +platforms where there is no `argc`/`argv`. + +### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} + +`Environment* testing::AddGlobalTestEnvironment(Environment* env)` + +Adds a test environment to the test program. Must be called before +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for +more information. + +See also [`Environment`](#Environment). + +### RegisterTest {#RegisterTest} + +```cpp +template +TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory) +``` + +Dynamically registers a test with the framework. + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the `Test` object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` methods for it. + +Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise +behavior is undefined. + +See +[Registering tests programmatically](../advanced.md#registering-tests-programmatically) +for more information. + +### RUN_ALL_TESTS {#RUN_ALL_TESTS} + +`int RUN_ALL_TESTS()` + +Use this function in `main()` to run all tests. It returns `0` if all tests are +successful, or `1` otherwise. + +`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by +[`InitGoogleTest()`](#InitGoogleTest). + +This function was formerly a macro; thus, it is in the global namespace and has +an all-caps name. + +### AssertionSuccess {#AssertionSuccess} + +`AssertionResult testing::AssertionSuccess()` + +Creates a successful assertion result. See +[`AssertionResult`](#AssertionResult). + +### AssertionFailure {#AssertionFailure} + +`AssertionResult testing::AssertionFailure()` + +Creates a failed assertion result. Use the `<<` operator to store a failure +message: + +```cpp +testing::AssertionFailure() << "My failure message"; +``` + +See [`AssertionResult`](#AssertionResult). + +### StaticAssertTypeEq {#StaticAssertTypeEq} + +`testing::StaticAssertTypeEq()` + +Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` +are the same type. The value it returns is irrelevant. + +See [Type Assertions](../advanced.md#type-assertions) for more information. + +### PrintToString {#PrintToString} + +`std::string testing::PrintToString(x)` + +Prints any value `x` using GoogleTest's value printer. + +See +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values) +for more information. + +### PrintToStringParamName {#PrintToStringParamName} + +`std::string testing::PrintToStringParamName(TestParamInfo& info)` + +A built-in parameterized test name generator which returns the result of +[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the +test parameter is a `std::string` or C string. See +[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters) +for more information. + +See also [`TestParamInfo`](#TestParamInfo) and +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/samples.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/samples.md new file mode 100644 index 0000000000000000000000000000000000000000..dedc59098df5ae6a318bae5992694dc11b6daf62 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/docs/samples.md @@ -0,0 +1,22 @@ +# Googletest Samples + +If you're like us, you'd like to look at +[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples) +The sample directory has a number of well-commented samples showing how to use a +variety of googletest features. + +* Sample #1 shows the basic steps of using googletest to test C++ functions. +* Sample #2 shows a more complex unit test for a class with multiple member + functions. +* Sample #3 uses a test fixture. +* Sample #4 teaches you how to use googletest and `googletest.h` together to + get the best of both libraries. +* Sample #5 puts shared testing logic in a base test fixture, and reuses it in + derived fixtures. +* Sample #6 demonstrates type-parameterized tests. +* Sample #7 teaches the basics of value-parameterized tests. +* Sample #8 shows using `Combine()` in value-parameterized tests. +* Sample #9 shows use of the listener API to modify Google Test's console + output and the use of its reflection API to inspect test results. +* Sample #10 shows use of the listener API to implement a primitive memory + leak checker. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/fake_fuchsia_sdk.bzl b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/fake_fuchsia_sdk.bzl new file mode 100644 index 0000000000000000000000000000000000000000..2024dc6c4d0358b2e8c086a018b47f03489aa666 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/fake_fuchsia_sdk.bzl @@ -0,0 +1,33 @@ +"""Provides a fake @fuchsia_sdk implementation that's used when the real one isn't available. + +This is needed since bazel queries on targets that depend on //:gtest (eg: +`bazel query "deps(set(//googletest/test:gtest_all_test))"`) will fail if @fuchsia_sdk is not +defined when bazel is evaluating the transitive closure of the query target. + +See https://github.com/google/googletest/issues/4472. +""" + +def _fake_fuchsia_sdk_impl(repo_ctx): + for stub_target in repo_ctx.attr._stub_build_targets: + stub_package = stub_target + stub_target_name = stub_target.split("/")[-1] + repo_ctx.file("%s/BUILD.bazel" % stub_package, """ +filegroup( + name = "%s", +) +""" % stub_target_name) + +fake_fuchsia_sdk = repository_rule( + doc = "Used to create a fake @fuchsia_sdk repository with stub build targets.", + implementation = _fake_fuchsia_sdk_impl, + attrs = { + "_stub_build_targets": attr.string_list( + doc = "The stub build targets to initialize.", + default = [ + "pkg/fdio", + "pkg/syslog", + "pkg/zx", + ], + ), + }, +) diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/CMakeLists.txt b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..99b2411f36d147fd40a8024cf748fd10c776e33f --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/CMakeLists.txt @@ -0,0 +1,210 @@ +######################################################################## +# Note: CMake support is community-based. The maintainers do not use CMake +# internally. +# +# CMake build script for Google Mock. +# +# To run the tests for Google Mock itself on Linux, use 'make test' or +# ctest. You can select which tests to run using 'ctest -R regex'. +# For more options, run 'ctest --help'. + +option(gmock_build_tests "Build all of Google Mock's own tests." OFF) + +# A directory to find Google Test sources. +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt") + set(gtest_dir gtest) +else() + set(gtest_dir ../googletest) +endif() + +# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). +include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) + +if (COMMAND pre_project_set_up_hermetic_build) + # Google Test also calls hermetic setup functions from add_subdirectory, + # although its changes will not affect things at the current scope. + pre_project_set_up_hermetic_build() +endif() + +######################################################################## +# +# Project-wide settings + +# Name of the project. +# +# CMake files in this project can refer to the root source directory +# as ${gmock_SOURCE_DIR} and to the root binary directory as +# ${gmock_BINARY_DIR}. +# Language "C" is required for find_package(Threads). +cmake_minimum_required(VERSION 3.13) +project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) + +if (COMMAND set_up_hermetic_build) + set_up_hermetic_build() +endif() + +# Instructs CMake to process Google Test's CMakeLists.txt and add its +# targets to the current scope. We are placing Google Test's binary +# directory in a subdirectory of our own as VC compilation may break +# if they are the same (the default). +add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") + + +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) +else() + mark_as_advanced(gmock_build_tests) +endif() + +# Although Google Test's CMakeLists.txt calls this function, the +# changes there don't affect the current scope. Therefore we have to +# call it again here. +config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake + +# Adds Google Mock's and Google Test's header directories to the search path. +# Get Google Test's include dirs from the target, gtest_SOURCE_DIR is broken +# when using fetch-content with the name "GTest". +get_target_property(gtest_include_dirs gtest INCLUDE_DIRECTORIES) +set(gmock_build_include_dirs + "${gmock_SOURCE_DIR}/include" + "${gmock_SOURCE_DIR}" + "${gtest_include_dirs}") +include_directories(${gmock_build_include_dirs}) + +######################################################################## +# +# Defines the gmock & gmock_main libraries. User tests should link +# with one of them. + +# Google Mock libraries. We build them using more strict warnings than what +# are used for other targets, to ensure that Google Mock can be compiled by +# a user aggressive about warnings. +if (MSVC) + cxx_library(gmock + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc) + + cxx_library(gmock_main + "${cxx_strict}" + "${gtest_dir}/src/gtest-all.cc" + src/gmock-all.cc + src/gmock_main.cc) +else() + cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) + target_link_libraries(gmock PUBLIC gtest) + set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION}) + cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) + target_link_libraries(gmock_main PUBLIC gmock) + set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) +endif() + +string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") +target_include_directories(gmock SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +target_include_directories(gmock_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") + +######################################################################## +# +# Install rules. +install_project(gmock gmock_main) + +######################################################################## +# +# Google Mock's own tests. +# +# You can skip this section if you aren't interested in testing +# Google Mock itself. +# +# The tests are not built by default. To build them, set the +# gmock_build_tests option to ON. You can do it by running ccmake +# or specifying the -Dgmock_build_tests=ON flag when running cmake. + +if (gmock_build_tests) + # This must be set in the root directory for the tests to be run by + # 'make test' or ctest. + enable_testing() + + if (MINGW OR CYGWIN) + add_compile_options("-Wa,-mbig-obj") + endif() + + ############################################################ + # C++ tests built with standard compiler flags. + + cxx_test(gmock-actions_test gmock_main) + cxx_test(gmock-cardinalities_test gmock_main) + cxx_test(gmock_ex_test gmock_main) + cxx_test(gmock-function-mocker_test gmock_main) + cxx_test(gmock-internal-utils_test gmock_main) + cxx_test(gmock-matchers-arithmetic_test gmock_main) + cxx_test(gmock-matchers-comparisons_test gmock_main) + cxx_test(gmock-matchers-containers_test gmock_main) + cxx_test(gmock-matchers-misc_test gmock_main) + cxx_test(gmock-more-actions_test gmock_main) + cxx_test(gmock-nice-strict_test gmock_main) + cxx_test(gmock-port_test gmock_main) + cxx_test(gmock-spec-builders_test gmock_main) + cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) + cxx_test(gmock_test gmock_main) + + if (DEFINED GTEST_HAS_PTHREAD) + cxx_test(gmock_stress_test gmock) + endif() + + # gmock_all_test is commented to save time building and running tests. + # Uncomment if necessary. + # cxx_test(gmock_all_test gmock_main) + + ############################################################ + # C++ tests built with non-standard compiler flags. + + if (MSVC) + cxx_library(gmock_main_no_exception "${cxx_no_exception}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + else() + cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_exception PUBLIC gmock) + + cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc) + target_link_libraries(gmock_main_no_rtti PUBLIC gmock) + endif() + cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" + gmock_main_no_exception test/gmock-more-actions_test.cc) + + cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}" + gmock_main_no_rtti test/gmock-spec-builders_test.cc) + + cxx_shared_library(shared_gmock_main "${cxx_default}" + "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) + + # Tests that a binary can be built with Google Mock as a shared library. On + # some system configurations, it may not possible to run the binary without + # knowing more details about the system configurations. We do not try to run + # this binary. To get a more robust shared library coverage, configure with + # -DBUILD_SHARED_LIBS=ON. + cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}" + shared_gmock_main test/gmock-spec-builders_test.cc) + set_target_properties(shared_gmock_test_ + PROPERTIES + COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") + + ############################################################ + # Python tests. + + cxx_executable(gmock_leak_test_ test gmock_main) + py_test(gmock_leak_test) + + cxx_executable(gmock_output_test_ test gmock) + py_test(gmock_output_test) +endif() diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/README.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e1103b16bbfcddff9a9a28b8ae2705b950184646 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/README.md @@ -0,0 +1,40 @@ +# Googletest Mocking (gMock) Framework + +### Overview + +Google's framework for writing and using C++ mock classes. It can help you +derive better designs of your system and write better tests. + +It is inspired by: + +* [jMock](http://www.jmock.org/) +* [EasyMock](https://easymock.org/) +* [Hamcrest](https://code.google.com/p/hamcrest/) + +It is designed with C++'s specifics in mind. + +gMock: + +- Provides a declarative syntax for defining mocks. +- Can define partial (hybrid) mocks, which are a cross of real and mock + objects. +- Handles functions of arbitrary types and overloaded functions. +- Comes with a rich set of matchers for validating function arguments. +- Uses an intuitive syntax for controlling the behavior of a mock. +- Does automatic verification of expectations (no record-and-replay needed). +- Allows arbitrary (partial) ordering constraints on function calls to be + expressed. +- Lets a user extend it by defining new matchers and actions. +- Does not use exceptions. +- Is easy to learn and use. + +Details and examples can be found here: + +* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html) +* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html) +* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html) +* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) + +GoogleMock is a part of +[GoogleTest C++ testing framework](https://github.com/google/googletest/) and a +subject to the same requirements. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/cmake/gmock.pc.in b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/cmake/gmock.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..23c67b5c88db4add6d21403b8ecbaf1be5a88813 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/cmake/gmock.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock +Description: GoogleMock (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gtest = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/cmake/gmock_main.pc.in b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/cmake/gmock_main.pc.in new file mode 100644 index 0000000000000000000000000000000000000000..66ffea7f4431f606c5ca5d87bef505157658244d --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/cmake/gmock_main.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gmock = @PROJECT_VERSION@ +Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/docs/README.md b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1bc57b799cce933c034c31859594ca1b87689aef --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/docs/README.md @@ -0,0 +1,4 @@ +# Content Moved + +We are working on updates to the GoogleTest documentation, which has moved to +the top-level [docs](../../docs) directory. diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-actions.h b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-actions.h new file mode 100644 index 0000000000000000000000000000000000000000..cd12996955b6fdcedf40edcf8ee41a77bd16d2b6 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-actions.h @@ -0,0 +1,2321 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The ACTION* family of macros can be used in a namespace scope to +// define custom actions easily. The syntax: +// +// ACTION(name) { statements; } +// +// will define an action with the given name that executes the +// statements. The value returned by the statements will be used as +// the return value of the action. Inside the statements, you can +// refer to the K-th (0-based) argument of the mock function by +// 'argK', and refer to its type by 'argK_type'. For example: +// +// ACTION(IncrementArg1) { +// arg1_type temp = arg1; +// return ++(*temp); +// } +// +// allows you to write +// +// ...WillOnce(IncrementArg1()); +// +// You can also refer to the entire argument tuple and its type by +// 'args' and 'args_type', and refer to the mock function type and its +// return type by 'function_type' and 'return_type'. +// +// Note that you don't need to specify the types of the mock function +// arguments. However rest assured that your code is still type-safe: +// you'll get a compiler error if *arg1 doesn't support the ++ +// operator, or if the type of ++(*arg1) isn't compatible with the +// mock function's return type, for example. +// +// Sometimes you'll want to parameterize the action. For that you can use +// another macro: +// +// ACTION_P(name, param_name) { statements; } +// +// For example: +// +// ACTION_P(Add, n) { return arg0 + n; } +// +// will allow you to write: +// +// ...WillOnce(Add(5)); +// +// Note that you don't need to provide the type of the parameter +// either. If you need to reference the type of a parameter named +// 'foo', you can write 'foo_type'. For example, in the body of +// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type +// of 'n'. +// +// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support +// multi-parameter actions. +// +// For the purpose of typing, you can view +// +// ACTION_Pk(Foo, p1, ..., pk) { ... } +// +// as shorthand for +// +// template +// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } +// +// In particular, you can provide the template type arguments +// explicitly when invoking Foo(), as in Foo(5, false); +// although usually you can rely on the compiler to infer the types +// for you automatically. You can assign the result of expression +// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. +// +// You can also overload actions with different numbers of parameters: +// +// ACTION_P(Plus, a) { ... } +// ACTION_P2(Plus, a, b) { ... } +// +// While it's tempting to always use the ACTION* macros when defining +// a new action, you should also consider implementing ActionInterface +// or using MakePolymorphicAction() instead, especially if you need to +// use the action a lot. While these approaches require more work, +// they give you more control on the types of the mock function +// arguments and the action parameters, which in general leads to +// better compiler error messages that pay off in the long run. They +// also allow overloading actions based on parameter types (as opposed +// to just based on the number of parameters). +// +// CAVEAT: +// +// ACTION*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// Users can, however, define any local functors (e.g. a lambda) that +// can be used as actions. +// +// MORE INFORMATION: +// +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ + +#ifndef _WIN32_WCE +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) + +namespace testing { + +// To implement an action Foo, define: +// 1. a class FooAction that implements the ActionInterface interface, and +// 2. a factory function that creates an Action object from a +// const FooAction*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Action objects can now be copied like plain values. + +namespace internal { + +// BuiltInDefaultValueGetter::Get() returns a +// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. +// +// This primary template is used when kDefaultConstructible is true. +template +struct BuiltInDefaultValueGetter { + static T Get() { return T(); } +}; +template +struct BuiltInDefaultValueGetter { + static T Get() { + Assert(false, __FILE__, __LINE__, + "Default action undefined for the function return type."); +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#else + return Invalid(); + // The above statement will never be reached, but is required in + // order for this function to compile. +#endif + } +}; + +// BuiltInDefaultValue::Get() returns the "built-in" default value +// for type T, which is NULL when T is a raw pointer type, 0 when T is +// a numeric type, false when T is bool, or "" when T is string or +// std::string. In addition, in C++11 and above, it turns a +// default-constructed T value if T is default constructible. For any +// other type T, the built-in default T value is undefined, and the +// function will abort the process. +template +class BuiltInDefaultValue { + public: + // This function returns true if and only if type T has a built-in default + // value. + static bool Exists() { return ::std::is_default_constructible::value; } + + static T Get() { + return BuiltInDefaultValueGetter< + T, ::std::is_default_constructible::value>::Get(); + } +}; + +// This partial specialization says that we use the same built-in +// default value for T and const T. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return BuiltInDefaultValue::Exists(); } + static T Get() { return BuiltInDefaultValue::Get(); } +}; + +// This partial specialization defines the default values for pointer +// types. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return true; } + static T* Get() { return nullptr; } +}; + +// The following specializations define the default values for +// specific types we care about. +#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ + } + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); + +// There's no need for a default action for signed wchar_t, as that +// type is the same as wchar_t for gcc, and invalid for MSVC. +// +// There's also no need for a default action for unsigned wchar_t, as +// that type is the same as unsigned int for gcc, and invalid for +// MSVC. +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT +#endif + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); + +#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ + +// Partial implementations of metaprogramming types from the standard library +// not available in C++11. + +template +struct negation + // NOLINTNEXTLINE + : std::integral_constant {}; + +// Base case: with zero predicates the answer is always true. +template +struct conjunction : std::true_type {}; + +// With a single predicate, the answer is that predicate. +template +struct conjunction : P1 {}; + +// With multiple predicates the answer is the first predicate if that is false, +// and we recurse otherwise. +template +struct conjunction + : std::conditional, P1>::type {}; + +template +struct disjunction : std::false_type {}; + +template +struct disjunction : P1 {}; + +template +struct disjunction + // NOLINTNEXTLINE + : std::conditional, P1>::type {}; + +template +using void_t = void; + +// Detects whether an expression of type `From` can be implicitly converted to +// `To` according to [conv]. In C++17, [conv]/3 defines this as follows: +// +// An expression e can be implicitly converted to a type T if and only if +// the declaration T t=e; is well-formed, for some invented temporary +// variable t ([dcl.init]). +// +// [conv]/2 implies we can use function argument passing to detect whether this +// initialization is valid. +// +// Note that this is distinct from is_convertible, which requires this be valid: +// +// To test() { +// return declval(); +// } +// +// In particular, is_convertible doesn't give the correct answer when `To` and +// `From` are the same non-moveable type since `declval` will be an rvalue +// reference, defeating the guaranteed copy elision that would otherwise make +// this function work. +// +// REQUIRES: `From` is not cv void. +template +struct is_implicitly_convertible { + private: + // A function that accepts a parameter of type T. This can be called with type + // U successfully only if U is implicitly convertible to T. + template + static void Accept(T); + + // A function that creates a value of type T. + template + static T Make(); + + // An overload be selected when implicit conversion from T to To is possible. + template (Make()))> + static std::true_type TestImplicitConversion(int); + + // A fallback overload selected in all other cases. + template + static std::false_type TestImplicitConversion(...); + + public: + using type = decltype(TestImplicitConversion(0)); + static constexpr bool value = type::value; +}; + +// Like std::invoke_result_t from C++17, but works only for objects with call +// operators (not e.g. member function pointers, which we don't need specific +// support for in OnceAction because std::function deals with them). +template +using call_result_t = decltype(std::declval()(std::declval()...)); + +template +struct is_callable_r_impl : std::false_type {}; + +// Specialize the struct for those template arguments where call_result_t is +// well-formed. When it's not, the generic template above is chosen, resulting +// in std::false_type. +template +struct is_callable_r_impl>, R, F, Args...> + : std::conditional< + std::is_void::value, // + std::true_type, // + is_implicitly_convertible, R>>::type {}; + +// Like std::is_invocable_r from C++17, but works only for objects with call +// operators. See the note on call_result_t. +template +using is_callable_r = is_callable_r_impl; + +// Like std::as_const from C++17. +template +typename std::add_const::type& as_const(T& t) { + return t; +} + +} // namespace internal + +// Specialized for function types below. +template +class OnceAction; + +// An action that can only be used once. +// +// This is accepted by WillOnce, which doesn't require the underlying action to +// be copy-constructible (only move-constructible), and promises to invoke it as +// an rvalue reference. This allows the action to work with move-only types like +// std::move_only_function in a type-safe manner. +// +// For example: +// +// // Assume we have some API that needs to accept a unique pointer to some +// // non-copyable object Foo. +// void AcceptUniquePointer(std::unique_ptr foo); +// +// // We can define an action that provides a Foo to that API. Because It +// // has to give away its unique pointer, it must not be called more than +// // once, so its call operator is &&-qualified. +// struct ProvideFoo { +// std::unique_ptr foo; +// +// void operator()() && { +// AcceptUniquePointer(std::move(Foo)); +// } +// }; +// +// // This action can be used with WillOnce. +// EXPECT_CALL(mock, Call) +// .WillOnce(ProvideFoo{std::make_unique(...)}); +// +// // But a call to WillRepeatedly will fail to compile. This is correct, +// // since the action cannot correctly be used repeatedly. +// EXPECT_CALL(mock, Call) +// .WillRepeatedly(ProvideFoo{std::make_unique(...)}); +// +// A less-contrived example would be an action that returns an arbitrary type, +// whose &&-qualified call operator is capable of dealing with move-only types. +template +class OnceAction final { + private: + // True iff we can use the given callable type (or lvalue reference) directly + // via StdFunctionAdaptor. + template + using IsDirectlyCompatible = internal::conjunction< + // It must be possible to capture the callable in StdFunctionAdaptor. + std::is_constructible::type, Callable>, + // The callable must be compatible with our signature. + internal::is_callable_r::type, + Args...>>; + + // True iff we can use the given callable type via StdFunctionAdaptor once we + // ignore incoming arguments. + template + using IsCompatibleAfterIgnoringArguments = internal::conjunction< + // It must be possible to capture the callable in a lambda. + std::is_constructible::type, Callable>, + // The callable must be invocable with zero arguments, returning something + // convertible to Result. + internal::is_callable_r::type>>; + + public: + // Construct from a callable that is directly compatible with our mocked + // signature: it accepts our function type's arguments and returns something + // convertible to our result type. + template ::type>>, + IsDirectlyCompatible> // + ::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + : function_(StdFunctionAdaptor::type>( + {}, std::forward(callable))) {} + + // As above, but for a callable that ignores the mocked function's arguments. + template ::type>>, + // Exclude callables for which the overload above works. + // We'd rather provide the arguments if possible. + internal::negation>, + IsCompatibleAfterIgnoringArguments>::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + // Call the constructor above with a callable + // that ignores the input arguments. + : OnceAction(IgnoreIncomingArguments::type>{ + std::forward(callable)}) {} + + // We are naturally copyable because we store only an std::function, but + // semantically we should not be copyable. + OnceAction(const OnceAction&) = delete; + OnceAction& operator=(const OnceAction&) = delete; + OnceAction(OnceAction&&) = default; + + // Invoke the underlying action callable with which we were constructed, + // handing it the supplied arguments. + Result Call(Args... args) && { + return function_(std::forward(args)...); + } + + private: + // An adaptor that wraps a callable that is compatible with our signature and + // being invoked as an rvalue reference so that it can be used as an + // StdFunctionAdaptor. This throws away type safety, but that's fine because + // this is only used by WillOnce, which we know calls at most once. + // + // Once we have something like std::move_only_function from C++23, we can do + // away with this. + template + class StdFunctionAdaptor final { + public: + // A tag indicating that the (otherwise universal) constructor is accepting + // the callable itself, instead of e.g. stealing calls for the move + // constructor. + struct CallableTag final {}; + + template + explicit StdFunctionAdaptor(CallableTag, F&& callable) + : callable_(std::make_shared(std::forward(callable))) {} + + // Rather than explicitly returning Result, we return whatever the wrapped + // callable returns. This allows for compatibility with existing uses like + // the following, when the mocked function returns void: + // + // EXPECT_CALL(mock_fn_, Call) + // .WillOnce([&] { + // [...] + // return 0; + // }); + // + // Such a callable can be turned into std::function. If we use an + // explicit return type of Result here then it *doesn't* work with + // std::function, because we'll get a "void function should not return a + // value" error. + // + // We need not worry about incompatible result types because the SFINAE on + // OnceAction already checks this for us. std::is_invocable_r_v itself makes + // the same allowance for void result types. + template + internal::call_result_t operator()( + ArgRefs&&... args) const { + return std::move(*callable_)(std::forward(args)...); + } + + private: + // We must put the callable on the heap so that we are copyable, which + // std::function needs. + std::shared_ptr callable_; + }; + + // An adaptor that makes a callable that accepts zero arguments callable with + // our mocked arguments. + template + struct IgnoreIncomingArguments { + internal::call_result_t operator()(Args&&...) { + return std::move(callable)(); + } + + Callable callable; + }; + + std::function function_; +}; + +// When an unexpected function call is encountered, Google Mock will +// let it return a default value if the user has specified one for its +// return type, or if the return type has a built-in default value; +// otherwise Google Mock won't know what value to return and will have +// to abort the process. +// +// The DefaultValue class allows a user to specify the +// default value for a type T that is both copyable and publicly +// destructible (i.e. anything that can be used as a function return +// type). The usage is: +// +// // Sets the default value for type T to be foo. +// DefaultValue::Set(foo); +template +class DefaultValue { + public: + // Sets the default value for type T; requires T to be + // copy-constructable and have a public destructor. + static void Set(T x) { + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); + } + + // Unsets the default value for type T. + static void Clear() { + delete producer_; + producer_ = nullptr; + } + + // Returns true if and only if the user has set the default value for type T. + static bool IsSet() { return producer_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T if the user has set one; + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. + static T Get() { + return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() + : producer_->Produce(); + } + + private: + class ValueProducer { + public: + virtual ~ValueProducer() = default; + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + T Produce() override { return value_; } + + private: + const T value_; + FixedValueProducer(const FixedValueProducer&) = delete; + FixedValueProducer& operator=(const FixedValueProducer&) = delete; + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + T Produce() override { return factory_(); } + + private: + const FactoryFunction factory_; + FactoryValueProducer(const FactoryValueProducer&) = delete; + FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; + }; + + static ValueProducer* producer_; +}; + +// This partial specialization allows a user to set default values for +// reference types. +template +class DefaultValue { + public: + // Sets the default value for type T&. + static void Set(T& x) { // NOLINT + address_ = &x; + } + + // Unsets the default value for type T&. + static void Clear() { address_ = nullptr; } + + // Returns true if and only if the user has set the default value for type T&. + static bool IsSet() { return address_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T& if the user has set one; + // otherwise returns the built-in default value if there is one; + // otherwise aborts the process. + static T& Get() { + return address_ == nullptr ? internal::BuiltInDefaultValue::Get() + : *address_; + } + + private: + static T* address_; +}; + +// This specialization allows DefaultValue::Get() to +// compile. +template <> +class DefaultValue { + public: + static bool Exists() { return true; } + static void Get() {} +}; + +// Points to the user-set default value for type T. +template +typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; + +// Points to the user-set default value for type T&. +template +T* DefaultValue::address_ = nullptr; + +// Implement this interface to define an action for function type F. +template +class ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + ActionInterface() = default; + virtual ~ActionInterface() = default; + + // Performs the action. This method is not const, as in general an + // action can have side effects and be stateful. For example, a + // get-the-next-element-from-the-collection action will need to + // remember the current element. + virtual Result Perform(const ArgumentTuple& args) = 0; + + private: + ActionInterface(const ActionInterface&) = delete; + ActionInterface& operator=(const ActionInterface&) = delete; +}; + +template +class Action; + +// An Action is a copyable and IMMUTABLE (except by assignment) +// object that represents an action to be taken when a mock function of type +// R(Args...) is called. The implementation of Action is just a +// std::shared_ptr to const ActionInterface. Don't inherit from Action! You +// can view an object implementing ActionInterface as a concrete action +// (including its current state), and an Action object as a handle to it. +template +class Action { + private: + using F = R(Args...); + + // Adapter class to allow constructing Action from a legacy ActionInterface. + // New code should create Actions from functors instead. + struct ActionAdapter { + // Adapter must be copyable to satisfy std::function requirements. + ::std::shared_ptr> impl_; + + template + typename internal::Function::Result operator()(InArgs&&... args) { + return impl_->Perform( + ::std::forward_as_tuple(::std::forward(args)...)); + } + }; + + template + using IsCompatibleFunctor = std::is_constructible, G>; + + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + // Constructs a null Action. Needed for storing Action objects in + // STL containers. + Action() = default; + + // Construct an Action from a specified callable. + // This cannot take std::function directly, because then Action would not be + // directly constructible from lambda (it would require two conversions). + template < + typename G, + typename = typename std::enable_if, std::is_constructible, + G>>::value>::type> + Action(G&& fun) { // NOLINT + Init(::std::forward(fun), IsCompatibleFunctor()); + } + + // Constructs an Action from its implementation. + explicit Action(ActionInterface* impl) + : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} + + // This constructor allows us to turn an Action object into an + // Action, as long as F's arguments can be implicitly converted + // to Func's and Func's return type can be implicitly converted to F's. + template + Action(const Action& action) // NOLINT + : fun_(action.fun_) {} + + // Returns true if and only if this is the DoDefault() action. + bool IsDoDefault() const { return fun_ == nullptr; } + + // Performs the action. Note that this method is const even though + // the corresponding method in ActionInterface is not. The reason + // is that a const Action means that it cannot be re-bound to + // another concrete action, not that the concrete action it binds to + // cannot change state. (Think of the difference between a const + // pointer and a pointer to const.) + Result Perform(ArgumentTuple args) const { + if (IsDoDefault()) { + internal::IllegalDoDefault(__FILE__, __LINE__); + } + return internal::Apply(fun_, ::std::move(args)); + } + + // An action can be used as a OnceAction, since it's obviously safe to call it + // once. + operator OnceAction() const { // NOLINT + // Return a OnceAction-compatible callable that calls Perform with the + // arguments it is provided. We could instead just return fun_, but then + // we'd need to handle the IsDoDefault() case separately. + struct OA { + Action action; + + R operator()(Args... args) && { + return action.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{*this}; + } + + private: + template + friend class Action; + + template + void Init(G&& g, ::std::true_type) { + fun_ = ::std::forward(g); + } + + template + void Init(G&& g, ::std::false_type) { + fun_ = IgnoreArgs::type>{::std::forward(g)}; + } + + template + struct IgnoreArgs { + template + Result operator()(const InArgs&...) const { + return function_impl(); + } + + FunctionImpl function_impl; + }; + + // fun_ is an empty function if and only if this is the DoDefault() action. + ::std::function fun_; +}; + +// The PolymorphicAction class template makes it easy to implement a +// polymorphic action (i.e. an action that can be used in mock +// functions of than one type, e.g. Return()). +// +// To define a polymorphic action, a user first provides a COPYABLE +// implementation class that has a Perform() method template: +// +// class FooAction { +// public: +// template +// Result Perform(const ArgumentTuple& args) const { +// // Processes the arguments and returns a result, using +// // std::get(args) to get the N-th (0-based) argument in the tuple. +// } +// ... +// }; +// +// Then the user creates the polymorphic action using +// MakePolymorphicAction(object) where object has type FooAction. See +// the definition of Return(void) and SetArgumentPointee(value) for +// complete examples. +template +class PolymorphicAction { + public: + explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} + + template + operator Action() const { + return Action(new MonomorphicImpl(impl_)); + } + + private: + template + class MonomorphicImpl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + Result Perform(const ArgumentTuple& args) override { + return impl_.template Perform(args); + } + + private: + Impl impl_; + }; + + Impl impl_; +}; + +// Creates an Action from its implementation and returns it. The +// created Action object owns the implementation. +template +Action MakeAction(ActionInterface* impl) { + return Action(impl); +} + +// Creates a polymorphic action from its implementation. This is +// easier to use than the PolymorphicAction constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicAction(foo); +// vs +// PolymorphicAction(foo); +template +inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { + return PolymorphicAction(impl); +} + +namespace internal { + +// Helper struct to specialize ReturnAction to execute a move instead of a copy +// on return. Useful for move-only types, but could be used on any type. +template +struct ByMoveWrapper { + explicit ByMoveWrapper(T value) : payload(std::move(value)) {} + T payload; +}; + +// The general implementation of Return(R). Specializations follow below. +template +class ReturnAction final { + public: + explicit ReturnAction(R value) : value_(std::move(value)) {} + + template >, // + negation>, // + std::is_convertible, // + std::is_move_constructible>::value>::type> + operator OnceAction() && { // NOLINT + return Impl(std::move(value_)); + } + + template >, // + negation>, // + std::is_convertible, // + std::is_copy_constructible>::value>::type> + operator Action() const { // NOLINT + return Impl(value_); + } + + private: + // Implements the Return(x) action for a mock function that returns type U. + template + class Impl final { + public: + // The constructor used when the return value is allowed to move from the + // input value (i.e. we are converting to OnceAction). + explicit Impl(R&& input_value) + : state_(new State(std::move(input_value))) {} + + // The constructor used when the return value is not allowed to move from + // the input value (i.e. we are converting to Action). + explicit Impl(const R& input_value) : state_(new State(input_value)) {} + + U operator()() && { return std::move(state_->value); } + U operator()() const& { return state_->value; } + + private: + // We put our state on the heap so that the compiler-generated copy/move + // constructors work correctly even when U is a reference-like type. This is + // necessary only because we eagerly create State::value (see the note on + // that symbol for details). If we instead had only the input value as a + // member then the default constructors would work fine. + // + // For example, when R is std::string and U is std::string_view, value is a + // reference to the string backed by input_value. The copy constructor would + // copy both, so that we wind up with a new input_value object (with the + // same contents) and a reference to the *old* input_value object rather + // than the new one. + struct State { + explicit State(const R& input_value_in) + : input_value(input_value_in), + // Make an implicit conversion to Result before initializing the U + // object we store, avoiding calling any explicit constructor of U + // from R. + // + // This simulates the language rules: a function with return type U + // that does `return R()` requires R to be implicitly convertible to + // U, and uses that path for the conversion, even U Result has an + // explicit constructor from R. + value(ImplicitCast_(internal::as_const(input_value))) {} + + // As above, but for the case where we're moving from the ReturnAction + // object because it's being used as a OnceAction. + explicit State(R&& input_value_in) + : input_value(std::move(input_value_in)), + // For the same reason as above we make an implicit conversion to U + // before initializing the value. + // + // Unlike above we provide the input value as an rvalue to the + // implicit conversion because this is a OnceAction: it's fine if it + // wants to consume the input value. + value(ImplicitCast_(std::move(input_value))) {} + + // A copy of the value originally provided by the user. We retain this in + // addition to the value of the mock function's result type below in case + // the latter is a reference-like type. See the std::string_view example + // in the documentation on Return. + R input_value; + + // The value we actually return, as the type returned by the mock function + // itself. + // + // We eagerly initialize this here, rather than lazily doing the implicit + // conversion automatically each time Perform is called, for historical + // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126) + // made the Action conversion operator eagerly convert the R value to + // U, but without keeping the R alive. This broke the use case discussed + // in the documentation for Return, making reference-like types such as + // std::string_view not safe to use as U where the input type R is a + // value-like type such as std::string. + // + // The example the commit gave was not very clear, nor was the issue + // thread (https://github.com/google/googlemock/issues/86), but it seems + // the worry was about reference-like input types R that flatten to a + // value-like type U when being implicitly converted. An example of this + // is std::vector::reference, which is often a proxy type with an + // reference to the underlying vector: + // + // // Helper method: have the mock function return bools according + // // to the supplied script. + // void SetActions(MockFunction& mock, + // const std::vector& script) { + // for (size_t i = 0; i < script.size(); ++i) { + // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i])); + // } + // } + // + // TEST(Foo, Bar) { + // // Set actions using a temporary vector, whose operator[] + // // returns proxy objects that references that will be + // // dangling once the call to SetActions finishes and the + // // vector is destroyed. + // MockFunction mock; + // SetActions(mock, {false, true}); + // + // EXPECT_FALSE(mock.AsStdFunction()(0)); + // EXPECT_TRUE(mock.AsStdFunction()(1)); + // } + // + // This eager conversion helps with a simple case like this, but doesn't + // fully make these types work in general. For example the following still + // uses a dangling reference: + // + // TEST(Foo, Baz) { + // MockFunction()> mock; + // + // // Return the same vector twice, and then the empty vector + // // thereafter. + // auto action = Return(std::initializer_list{ + // "taco", "burrito", + // }); + // + // EXPECT_CALL(mock, Call) + // .WillOnce(action) + // .WillOnce(action) + // .WillRepeatedly(Return(std::vector{})); + // + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty()); + // } + // + U value; + }; + + const std::shared_ptr state_; + }; + + R value_; +}; + +// A specialization of ReturnAction when R is ByMoveWrapper for some T. +// +// This version applies the type system-defeating hack of moving from T even in +// the const call operator, checking at runtime that it isn't called more than +// once, since the user has declared their intent to do so by using ByMove. +template +class ReturnAction> final { + public: + explicit ReturnAction(ByMoveWrapper wrapper) + : state_(new State(std::move(wrapper.payload))) {} + + T operator()() const { + GTEST_CHECK_(!state_->called) + << "A ByMove() action must be performed at most once."; + + state_->called = true; + return std::move(state_->value); + } + + private: + // We store our state on the heap so that we are copyable as required by + // Action, despite the fact that we are stateful and T may not be copyable. + struct State { + explicit State(T&& value_in) : value(std::move(value_in)) {} + + T value; + bool called = false; + }; + + const std::shared_ptr state_; +}; + +// Implements the ReturnNull() action. +class ReturnNullAction { + public: + // Allows ReturnNull() to be used in any pointer-returning function. In C++11 + // this is enforced by returning nullptr, and in non-C++11 by asserting a + // pointer type on compile time. + template + static Result Perform(const ArgumentTuple&) { + return nullptr; + } +}; + +// Implements the Return() action. +class ReturnVoidAction { + public: + // Allows Return() to be used in any void-returning function. + template + static void Perform(const ArgumentTuple&) { + static_assert(std::is_void::value, "Result should be void."); + } +}; + +// Implements the polymorphic ReturnRef(x) action, which can be used +// in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefAction { + public: + // Constructs a ReturnRefAction object from the reference to be returned. + explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT + + // This template type conversion operator allows ReturnRef(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRef(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRef to return a value"); + return Action(new Impl(ref_)); + } + + private: + // Implements the ReturnRef(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(T& ref) : ref_(ref) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return ref_; } + + private: + T& ref_; + }; + + T& ref_; +}; + +// Implements the polymorphic ReturnRefOfCopy(x) action, which can be +// used in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefOfCopyAction { + public: + // Constructs a ReturnRefOfCopyAction object from the reference to + // be returned. + explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT + + // This template type conversion operator allows ReturnRefOfCopy(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRefOfCopy(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRefOfCopy to return a value"); + return Action(new Impl(value_)); + } + + private: + // Implements the ReturnRefOfCopy(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const T& value) : value_(value) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return value_; } + + private: + T value_; + }; + + const T value_; +}; + +// Implements the polymorphic ReturnRoundRobin(v) action, which can be +// used in any function that returns the element_type of v. +template +class ReturnRoundRobinAction { + public: + explicit ReturnRoundRobinAction(std::vector values) { + GTEST_CHECK_(!values.empty()) + << "ReturnRoundRobin requires at least one element."; + state_->values = std::move(values); + } + + template + T operator()(Args&&...) const { + return state_->Next(); + } + + private: + struct State { + T Next() { + T ret_val = values[i++]; + if (i == values.size()) i = 0; + return ret_val; + } + + std::vector values; + size_t i = 0; + }; + std::shared_ptr state_ = std::make_shared(); +}; + +// Implements the polymorphic DoDefault() action. +class DoDefaultAction { + public: + // This template type conversion operator allows DoDefault() to be + // used in any function. + template + operator Action() const { + return Action(); + } // NOLINT +}; + +// Implements the Assign action to set a given pointer referent to a +// particular value. +template +class AssignAction { + public: + AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} + + template + void Perform(const ArgumentTuple& /* args */) const { + *ptr_ = value_; + } + + private: + T1* const ptr_; + const T2 value_; +}; + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Implements the SetErrnoAndReturn action to simulate return from +// various system calls and libc functions. +template +class SetErrnoAndReturnAction { + public: + SetErrnoAndReturnAction(int errno_value, T result) + : errno_(errno_value), result_(result) {} + template + Result Perform(const ArgumentTuple& /* args */) const { + errno = errno_; + return result_; + } + + private: + const int errno_; + const T result_; +}; + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetArgumentPointee(x) action for any function +// whose N-th argument (0-based) is a pointer to x's type. +template +struct SetArgumentPointeeAction { + A value; + + template + void operator()(const Args&... args) const { + *::std::get(std::tie(args...)) = value; + } +}; + +// Implements the Invoke(object_ptr, &Class::Method) action. +template +struct InvokeMethodAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + template + auto operator()(Args&&... args) const + -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { + return (obj_ptr->*method_ptr)(std::forward(args)...); + } +}; + +// Implements the InvokeWithoutArgs(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. InvokeWithoutArgs(f) can be used as an +// Action as long as f's type is compatible with F. +template +struct InvokeWithoutArgsAction { + FunctionImpl function_impl; + + // Allows InvokeWithoutArgs(f) to be used as any action whose type is + // compatible with f. + template + auto operator()(const Args&...) -> decltype(function_impl()) { + return function_impl(); + } +}; + +// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. +template +struct InvokeMethodWithoutArgsAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + using ReturnType = + decltype((std::declval()->*std::declval())()); + + template + ReturnType operator()(const Args&...) const { + return (obj_ptr->*method_ptr)(); + } +}; + +// Implements the IgnoreResult(action) action. +template +class IgnoreResultAction { + public: + explicit IgnoreResultAction(const A& action) : action_(action) {} + + template + operator Action() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename internal::Function::Result Result; + + // Asserts at compile time that F returns void. + static_assert(std::is_void::value, "Result type should be void."); + + return Action(new Impl(action_)); + } + + private: + template + class Impl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const A& action) : action_(action) {} + + void Perform(const ArgumentTuple& args) override { + // Performs the action and ignores its result. + action_.Perform(args); + } + + private: + // Type OriginalFunction is the same as F except that its return + // type is IgnoredValue. + typedef + typename internal::Function::MakeResultIgnoredValue OriginalFunction; + + const Action action_; + }; + + const A action_; +}; + +template +struct WithArgsAction { + InnerAction inner_action; + + // The signature of the function as seen by the inner action, given an out + // action with the given result and argument types. + template + using InnerSignature = + R(typename std::tuple_element>::type...); + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{std::move(inner_action)}; + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator Action() const { // NOLINT + Action> converted(inner_action); + + return [converted](Args&&... args) -> R { + return converted.Perform(std::forward_as_tuple( + std::get(std::forward_as_tuple(std::forward(args)...))...)); + }; + } +}; + +template +class DoAllAction; + +// Base case: only a single action. +template +class DoAllAction { + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& action) + : final_action_(std::forward(action)) {} + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template >::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return std::move(final_action_); + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>::value, + int>::type = 0> + operator Action() const { // NOLINT + return final_action_; + } + + private: + FinalAction final_action_; +}; + +// Recursive case: support N actions by calling the initial action and then +// calling through to the base class containing N-1 actions. +template +class DoAllAction + : private DoAllAction { + private: + using Base = DoAllAction; + + // The type of reference that should be provided to an initial action for a + // mocked function parameter of type T. + // + // There are two quirks here: + // + // * Unlike most forwarding functions, we pass scalars through by value. + // This isn't strictly necessary because an lvalue reference would work + // fine too and be consistent with other non-reference types, but it's + // perhaps less surprising. + // + // For example if the mocked function has signature void(int), then it + // might seem surprising for the user's initial action to need to be + // convertible to Action. This is perhaps less + // surprising for a non-scalar type where there may be a performance + // impact, or it might even be impossible, to pass by value. + // + // * More surprisingly, `const T&` is often not a const reference type. + // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to + // U& or U&& for some non-scalar type U, then InitialActionArgType is + // U&. In other words, we may hand over a non-const reference. + // + // So for example, given some non-scalar type Obj we have the following + // mappings: + // + // T InitialActionArgType + // ------- ----------------------- + // Obj const Obj& + // Obj& Obj& + // Obj&& Obj& + // const Obj const Obj& + // const Obj& const Obj& + // const Obj&& const Obj& + // + // In other words, the initial actions get a mutable view of an non-scalar + // argument if and only if the mock function itself accepts a non-const + // reference type. They are never given an rvalue reference to an + // non-scalar type. + // + // This situation makes sense if you imagine use with a matcher that is + // designed to write through a reference. For example, if the caller wants + // to fill in a reference argument and then return a canned value: + // + // EXPECT_CALL(mock, Call) + // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19))); + // + template + using InitialActionArgType = + typename std::conditional::value, T, const T&>::type; + + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& initial_action, + U&&... other_actions) + : Base({}, std::forward(other_actions)...), + initial_action_(std::forward(initial_action)) {} + + template ...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + OnceAction...)> initial_action; + OnceAction remaining_actions; + + R operator()(Args... args) && { + std::move(initial_action) + .Call(static_cast>(args)...); + + return std::move(remaining_actions).Call(std::forward(args)...); + } + }; + + return OA{ + std::move(initial_action_), + std::move(static_cast(*this)), + }; + } + + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + // Both the initial action and the rest must support conversion to + // Action. + std::is_convertible...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator Action() const { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + Action...)> initial_action; + Action remaining_actions; + + R operator()(Args... args) const { + initial_action.Perform(std::forward_as_tuple( + static_cast>(args)...)); + + return remaining_actions.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{ + initial_action_, + static_cast(*this), + }; + } + + private: + InitialAction initial_action_; +}; + +template +struct ReturnNewAction { + T* operator()() const { + return internal::Apply( + [](const Params&... unpacked_params) { + return new T(unpacked_params...); + }, + params); + } + std::tuple params; +}; + +template +struct ReturnArgAction { + template ::type> + auto operator()(Args&&... args) const -> decltype(std::get( + std::forward_as_tuple(std::forward(args)...))) { + return std::get(std::forward_as_tuple(std::forward(args)...)); + } +}; + +template +struct SaveArgAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = std::get(std::tie(args...)); + } +}; + +template +struct SaveArgPointeeAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = *std::get(std::tie(args...)); + } +}; + +template +struct SetArgRefereeAction { + T value; + + template + void operator()(Args&&... args) const { + using argk_type = + typename ::std::tuple_element>::type; + static_assert(std::is_lvalue_reference::value, + "Argument must be a reference type."); + std::get(std::tie(args...)) = value; + } +}; + +template +struct SetArrayArgumentAction { + I1 first; + I2 last; + + template + void operator()(const Args&... args) const { + auto value = std::get(std::tie(args...)); + for (auto it = first; it != last; ++it, (void)++value) { + *value = *it; + } + } +}; + +template +struct DeleteArgAction { + template + void operator()(const Args&... args) const { + delete std::get(std::tie(args...)); + } +}; + +template +struct ReturnPointeeAction { + Ptr pointer; + template + auto operator()(const Args&...) const -> decltype(*pointer) { + return *pointer; + } +}; + +#if GTEST_HAS_EXCEPTIONS +template +struct ThrowAction { + T exception; + // We use a conversion operator to adapt to any return type. + template + operator Action() const { // NOLINT + T copy = exception; + return [copy](Args...) -> R { throw copy; }; + } +}; +struct RethrowAction { + std::exception_ptr exception; + template + operator Action() const { // NOLINT + return [ex = exception](Args...) -> R { std::rethrow_exception(ex); }; + } +}; +#endif // GTEST_HAS_EXCEPTIONS + +} // namespace internal + +// An Unused object can be implicitly constructed from ANY value. +// This is handy when defining actions that ignore some or all of the +// mock function arguments. For example, given +// +// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); +// MOCK_METHOD3(Bar, double(int index, double x, double y)); +// +// instead of +// +// double DistanceToOriginWithLabel(const string& label, double x, double y) { +// return sqrt(x*x + y*y); +// } +// double DistanceToOriginWithIndex(int index, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)) +// .WillOnce(Invoke(DistanceToOriginWithLabel)); +// EXPECT_CALL(mock, Bar(5, _, _)) +// .WillOnce(Invoke(DistanceToOriginWithIndex)); +// +// you could write +// +// // We can declare any uninteresting argument as Unused. +// double DistanceToOrigin(Unused, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +typedef internal::IgnoredValue Unused; + +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. All but the last action will have a readonly view of the +// arguments. +template +internal::DoAllAction::type...> DoAll( + Action&&... action) { + return internal::DoAllAction::type...>( + {}, std::forward(action)...); +} + +// WithArg(an_action) creates an action that passes the k-th +// (0-based) argument of the mock function to an_action and performs +// it. It adapts an action accepting one argument to one that accepts +// multiple arguments. For convenience, we also provide +// WithArgs(an_action) (defined below) as a synonym. +template +internal::WithArgsAction::type, k> WithArg( + InnerAction&& action) { + return {std::forward(action)}; +} + +// WithArgs(an_action) creates an action that passes +// the selected arguments of the mock function to an_action and +// performs it. It serves as an adaptor between actions with +// different argument lists. +template +internal::WithArgsAction::type, k, ks...> +WithArgs(InnerAction&& action) { + return {std::forward(action)}; +} + +// WithoutArgs(inner_action) can be used in a mock function with a +// non-empty argument list to perform inner_action, which takes no +// argument. In other words, it adapts an action accepting no +// argument to one that accepts (and ignores) arguments. +template +internal::WithArgsAction::type> WithoutArgs( + InnerAction&& action) { + return {std::forward(action)}; +} + +// Creates an action that returns a value. +// +// The returned type can be used with a mock function returning a non-void, +// non-reference type U as follows: +// +// * If R is convertible to U and U is move-constructible, then the action can +// be used with WillOnce. +// +// * If const R& is convertible to U and U is copy-constructible, then the +// action can be used with both WillOnce and WillRepeatedly. +// +// The mock expectation contains the R value from which the U return value is +// constructed (a move/copy of the argument to Return). This means that the R +// value will survive at least until the mock object's expectations are cleared +// or the mock object is destroyed, meaning that U can safely be a +// reference-like type such as std::string_view: +// +// // The mock function returns a view of a copy of the string fed to +// // Return. The view is valid even after the action is performed. +// MockFunction mock; +// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); +// const std::string_view result = mock.AsStdFunction()(); +// EXPECT_EQ("taco", result); +// +template +internal::ReturnAction Return(R value) { + return internal::ReturnAction(std::move(value)); +} + +// Creates an action that returns NULL. +inline PolymorphicAction ReturnNull() { + return MakePolymorphicAction(internal::ReturnNullAction()); +} + +// Creates an action that returns from a void function. +inline PolymorphicAction Return() { + return MakePolymorphicAction(internal::ReturnVoidAction()); +} + +// Creates an action that returns the reference to a variable. +template +inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT + return internal::ReturnRefAction(x); +} + +// Prevent using ReturnRef on reference to temporary. +template +internal::ReturnRefAction ReturnRef(R&&) = delete; + +// Creates an action that returns the reference to a copy of the +// argument. The copy is created when the action is constructed and +// lives as long as the action. +template +inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { + return internal::ReturnRefOfCopyAction(x); +} + +// DEPRECATED: use Return(x) directly with WillOnce. +// +// Modifies the parent action (a Return() action) to perform a move of the +// argument instead of a copy. +// Return(ByMove()) actions can only be executed once and will assert this +// invariant. +template +internal::ByMoveWrapper ByMove(R x) { + return internal::ByMoveWrapper(std::move(x)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { + return internal::ReturnRoundRobinAction(std::move(vals)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin( + std::initializer_list vals) { + return internal::ReturnRoundRobinAction(std::vector(vals)); +} + +// Creates an action that does the default action for the give mock function. +inline internal::DoDefaultAction DoDefault() { + return internal::DoDefaultAction(); +} + +// Creates an action that sets the variable pointed by the N-th +// (0-based) function argument to 'value'. +template +internal::SetArgumentPointeeAction SetArgPointee(T value) { + return {std::move(value)}; +} + +// The following version is DEPRECATED. +template +internal::SetArgumentPointeeAction SetArgumentPointee(T value) { + return {std::move(value)}; +} + +// Creates an action that sets a pointer referent to a given value. +template +PolymorphicAction> Assign(T1* ptr, T2 val) { + return MakePolymorphicAction(internal::AssignAction(ptr, val)); +} + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Creates an action that sets errno and returns the appropriate error. +template +PolymorphicAction> SetErrnoAndReturn( + int errval, T result) { + return MakePolymorphicAction( + internal::SetErrnoAndReturnAction(errval, result)); +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Various overloads for Invoke(). + +// Legacy function. +// Actions can now be implicitly constructed from callables. No need to create +// wrapper objects. +// This function exists for backwards compatibility. +template +typename std::decay::type Invoke(FunctionImpl&& function_impl) { + return std::forward(function_impl); +} + +// Creates an action that invokes the given method on the given object +// with the mock function's arguments. +template +internal::InvokeMethodAction Invoke(Class* obj_ptr, + MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that invokes 'function_impl' with no argument. +template +internal::InvokeWithoutArgsAction::type> +InvokeWithoutArgs(FunctionImpl function_impl) { + return {std::move(function_impl)}; +} + +// Creates an action that invokes the given method on the given object +// with no argument. +template +internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( + Class* obj_ptr, MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that performs an_action and throws away its +// result. In other words, it changes the return type of an_action to +// void. an_action MUST NOT return void, or the code won't compile. +template +inline internal::IgnoreResultAction IgnoreResult(const A& an_action) { + return internal::IgnoreResultAction(an_action); +} + +// Creates a reference wrapper for the given L-value. If necessary, +// you can explicitly specify the type of the reference. For example, +// suppose 'derived' is an object of type Derived, ByRef(derived) +// would wrap a Derived&. If you want to wrap a const Base& instead, +// where Base is a base class of Derived, just write: +// +// ByRef(derived) +// +// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. +// However, it may still be used for consistency with ByMove(). +template +inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT + return ::std::reference_wrapper(l_value); +} + +// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new +// instance of type T, constructed on the heap with constructor arguments +// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. +template +internal::ReturnNewAction::type...> ReturnNew( + Params&&... params) { + return {std::forward_as_tuple(std::forward(params)...)}; +} + +// Action ReturnArg() returns the k-th argument of the mock function. +template +internal::ReturnArgAction ReturnArg() { + return {}; +} + +// Action SaveArg(pointer) saves the k-th (0-based) argument of the +// mock function to *pointer. +template +internal::SaveArgAction SaveArg(Ptr pointer) { + return {pointer}; +} + +// Action SaveArgPointee(pointer) saves the value pointed to +// by the k-th (0-based) argument of the mock function to *pointer. +template +internal::SaveArgPointeeAction SaveArgPointee(Ptr pointer) { + return {pointer}; +} + +// Action SetArgReferee(value) assigns 'value' to the variable +// referenced by the k-th (0-based) argument of the mock function. +template +internal::SetArgRefereeAction::type> SetArgReferee( + T&& value) { + return {std::forward(value)}; +} + +// Action SetArrayArgument(first, last) copies the elements in +// source range [first, last) to the array pointed to by the k-th +// (0-based) argument, which can be either a pointer or an +// iterator. The action does not take ownership of the elements in the +// source range. +template +internal::SetArrayArgumentAction SetArrayArgument(I1 first, + I2 last) { + return {first, last}; +} + +// Action DeleteArg() deletes the k-th (0-based) argument of the mock +// function. +template +internal::DeleteArgAction DeleteArg() { + return {}; +} + +// This action returns the value pointed to by 'pointer'. +template +internal::ReturnPointeeAction ReturnPointee(Ptr pointer) { + return {pointer}; +} + +#if GTEST_HAS_EXCEPTIONS +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown, +// except for std::exception_ptr, which is likely a mistake if +// thrown directly. +template +typename std::enable_if< + !std::is_base_of::type>::value, + internal::ThrowAction::type>>::type +Throw(T&& exception) { + return {std::forward(exception)}; +} +// Action Rethrow(exception_ptr) can be used in a mock function of any type +// to rethrow any exception_ptr. Note that the same object is thrown each time. +inline internal::RethrowAction Rethrow(std::exception_ptr exception) { + return {std::move(exception)}; +} +#endif // GTEST_HAS_EXCEPTIONS + +namespace internal { + +// A macro from the ACTION* family (defined later in gmock-generated-actions.h) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// Builds an implementation of an Action<> for some particular signature, using +// a class defined by an ACTION* macro. +template +struct ActionImpl; + +template +struct ImplBase { + struct Holder { + // Allows each copy of the Action<> to get to the Impl. + explicit operator const Impl&() const { return *ptr; } + std::shared_ptr ptr; + }; + using type = typename std::conditional::value, + Impl, Holder>::type; +}; + +template +struct ActionImpl : ImplBase::type { + using Base = typename ImplBase::type; + using function_type = R(Args...); + using args_type = std::tuple; + + ActionImpl() = default; // Only defined if appropriate for Base. + explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} {} + + R operator()(Args&&... arg) const { + static constexpr size_t kMaxArgs = + sizeof...(Args) <= 10 ? sizeof...(Args) : 10; + return Apply(std::make_index_sequence{}, + std::make_index_sequence<10 - kMaxArgs>{}, + args_type{std::forward(arg)...}); + } + + template + R Apply(std::index_sequence, std::index_sequence, + const args_type& args) const { + // Impl need not be specific to the signature of action being implemented; + // only the implementing function body needs to have all of the specific + // types instantiated. Up to 10 of the args that are provided by the + // args_type get passed, followed by a dummy of unspecified type for the + // remainder up to 10 explicit args. + static constexpr ExcessiveArg kExcessArg{}; + return static_cast(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element::type...>( + /*args=*/args, std::get(args)..., + ((void)excess_id, kExcessArg)...); + } +}; + +// Stores a default-constructed Impl as part of the Action<>'s +// std::function<>. The Impl should be trivial to copy. +template +::testing::Action MakeAction() { + return ::testing::Action(ActionImpl()); +} + +// Stores just the one given instance of Impl. +template +::testing::Action MakeAction(std::shared_ptr impl) { + return ::testing::Action(ActionImpl(std::move(impl))); +} + +#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ + , GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const args_type& args GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_ARG_UNUSED, , 10) + +#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ + const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) + +#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type +#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ + GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) + +#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type +#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type +#define GMOCK_ACTION_TYPE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ + , param##_type gmock_p##i +#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ + , std::forward(gmock_p##i) +#define GMOCK_ACTION_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ + , param(::std::forward(gmock_p##i)) +#define GMOCK_ACTION_INIT_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) + +#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; +#define GMOCK_ACTION_FIELD_PARAMS_(params) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) + +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr impl_; \ + }; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template \ + template \ + return_type \ + full_name::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +} // namespace internal + +// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. +#define ACTION(name) \ + class name##Action { \ + public: \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + }; \ + }; \ + inline name##Action name() GTEST_MUST_USE_RESULT_; \ + inline name##Action name() { return name##Action(); } \ + template \ + return_type name##Action::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) + +#define ACTION_P2(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) + +#define ACTION_P3(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) + +#define ACTION_P4(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) + +#define ACTION_P5(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) + +#define ACTION_P6(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) + +#define ACTION_P7(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) + +#define ACTION_P8(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) + +#define ACTION_P9(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) + +#define ACTION_P10(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-cardinalities.h b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-cardinalities.h new file mode 100644 index 0000000000000000000000000000000000000000..533e604f326c052da2765ce282222b06fa832861 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-cardinalities.h @@ -0,0 +1,159 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements some commonly used cardinalities. More +// cardinalities can be defined by the user implementing the +// CardinalityInterface interface if necessary. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ + +#include + +#include +#include // NOLINT + +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + +namespace testing { + +// To implement a cardinality Foo, define: +// 1. a class FooCardinality that implements the +// CardinalityInterface interface, and +// 2. a factory function that creates a Cardinality object from a +// const FooCardinality*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Cardinality objects can now be copied like plain values. + +// The implementation of a cardinality. +class CardinalityInterface { + public: + virtual ~CardinalityInterface() = default; + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + virtual int ConservativeLowerBound() const { return 0; } + virtual int ConservativeUpperBound() const { return INT_MAX; } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + virtual bool IsSatisfiedByCallCount(int call_count) const = 0; + + // Returns true if and only if call_count calls will saturate this + // cardinality. + virtual bool IsSaturatedByCallCount(int call_count) const = 0; + + // Describes self to an ostream. + virtual void DescribeTo(::std::ostream* os) const = 0; +}; + +// A Cardinality is a copyable and IMMUTABLE (except by assignment) +// object that specifies how many times a mock function is expected to +// be called. The implementation of Cardinality is just a std::shared_ptr +// to const CardinalityInterface. Don't inherit from Cardinality! +class GTEST_API_ Cardinality { + public: + // Constructs a null cardinality. Needed for storing Cardinality + // objects in STL containers. + Cardinality() = default; + + // Constructs a Cardinality from its implementation. + explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} + + // Conservative estimate on the lower/upper bound of the number of + // calls allowed. + int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } + int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } + + // Returns true if and only if call_count calls will satisfy this + // cardinality. + bool IsSatisfiedByCallCount(int call_count) const { + return impl_->IsSatisfiedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will saturate this + // cardinality. + bool IsSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count); + } + + // Returns true if and only if call_count calls will over-saturate this + // cardinality, i.e. exceed the maximum number of allowed calls. + bool IsOverSaturatedByCallCount(int call_count) const { + return impl_->IsSaturatedByCallCount(call_count) && + !impl_->IsSatisfiedByCallCount(call_count); + } + + // Describes self to an ostream + void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + // Describes the given actual call count to an ostream. + static void DescribeActualCallCountTo(int actual_call_count, + ::std::ostream* os); + + private: + std::shared_ptr impl_; +}; + +// Creates a cardinality that allows at least n calls. +GTEST_API_ Cardinality AtLeast(int n); + +// Creates a cardinality that allows at most n calls. +GTEST_API_ Cardinality AtMost(int n); + +// Creates a cardinality that allows any number of calls. +GTEST_API_ Cardinality AnyNumber(); + +// Creates a cardinality that allows between min and max calls. +GTEST_API_ Cardinality Between(int min, int max); + +// Creates a cardinality that allows exactly n calls. +GTEST_API_ Cardinality Exactly(int n); + +// Creates a cardinality from its implementation. +inline Cardinality MakeCardinality(const CardinalityInterface* c) { + return Cardinality(c); +} + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-function-mocker.h b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-function-mocker.h new file mode 100644 index 0000000000000000000000000000000000000000..d2cb13cd834735ec13e3526db5b2f21bc9587c3c --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-function-mocker.h @@ -0,0 +1,519 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements MOCK_METHOD. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ + +#include +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-pp.h" + +namespace testing { +namespace internal { +template +using identity_t = T; + +template +struct ThisRefAdjuster { + template + using AdjustT = typename std::conditional< + std::is_const::type>::value, + typename std::conditional::value, + const T&, const T&&>::type, + typename std::conditional::value, T&, + T&&>::type>::type; + + template + static AdjustT Adjust(const MockType& mock) { + return static_cast>(const_cast(mock)); + } +}; + +constexpr bool PrefixOf(const char* a, const char* b) { + return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); +} + +template +constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(prefix, str); +} + +template +constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(suffix, str + M - N); +} + +template +constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { + return N == M && internal::PrefixOf(a, b); +} + +template +constexpr bool ValidateSpec(const char (&spec)[N]) { + return internal::Equals("const", spec) || + internal::Equals("override", spec) || + internal::Equals("final", spec) || + internal::Equals("noexcept", spec) || + (internal::StartsWith("noexcept(", spec) && + internal::EndsWith(")", spec)) || + internal::Equals("ref(&)", spec) || + internal::Equals("ref(&&)", spec) || + (internal::StartsWith("Calltype(", spec) && + internal::EndsWith(")", spec)); +} + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the FunctionMocker class template +// is meant to be defined in the ::testing namespace. The following +// line is just a trick for working around a bug in MSVC 8.0, which +// cannot handle it if we define FunctionMocker in ::testing. +using internal::FunctionMocker; +} // namespace testing + +#define MOCK_METHOD(...) \ + GMOCK_INTERNAL_WARNING_PUSH() \ + GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ + GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \ + GMOCK_INTERNAL_WARNING_POP() + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ + GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ + GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ + GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ + (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_WRONG_ARITY(...) \ + static_assert( \ + false, \ + "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ + "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ + "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ + "it must also be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ + static_assert( \ + GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ + GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ + static_assert( \ + std::is_function<__VA_ARGS__>::value, \ + "Signature must be a function type, maybe return type contains " \ + "unprotected comma."); \ + static_assert( \ + ::testing::tuple_size::ArgumentTuple>::value == _N, \ + "This method does not take " GMOCK_PP_STRINGIZE( \ + _N) " arguments. Parenthesize all types with unprotected commas.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) + +#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ + _Override, _Final, _NoexceptSpec, \ + _CallType, _RefSpec, _Signature) \ + typename ::testing::internal::Function::Result \ + GMOCK_INTERNAL_EXPAND(_CallType) \ + _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) \ + _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \ + GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .SetOwnerAndName(this, #_MethodName); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + const ::testing::internal::WithoutMatchers&, \ + GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ + GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ + return ::testing::internal::ThisRefAdjuster::Adjust(*this) \ + .gmock_##_MethodName(GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ + } \ + mutable ::testing::FunctionMocker \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) + +#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ + +// Valid modifiers. +#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ + GMOCK_PP_HAS_COMMA( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) + +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ + _elem, ) + +#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) + +#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) + +#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ + GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ + "Token \'" GMOCK_PP_STRINGIZE( \ + _elem) "\' cannot be recognized as a valid specification " \ + "modifier. Is a ',' missing?"); +#else +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ + GMOCK_PP_STRINGIZE( \ + _elem) " cannot be recognized as a valid specification modifier."); +#endif // GMOCK_INTERNAL_STRICT_SPEC_ASSERT + +// Modifiers implementation. +#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CONST_I_const , + +#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , + +#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_FINAL_I_final , + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , + +#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_REF_I_ref , + +#define GMOCK_INTERNAL_UNPACK_ref(x) x + +#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , + +#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ + +// Note: The use of `identity_t` here allows _Ret to represent return types that +// would normally need to be specified in a different way. For example, a method +// returning a function pointer must be written as +// +// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) +// +// But we only support placing the return type at the beginning. To handle this, +// we wrap all calls in identity_t, so that a declaration will be expanded to +// +// identity_t method(method_args_t...) +// +// This allows us to work around the syntactic oddities of function/method +// types. +#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ + ::testing::internal::identity_t( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) + +#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ + GMOCK_PP_IDENTITY) \ + (_elem) + +#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::std::forward(gmock_a##_i) + +#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ + GMOCK_PP_COMMA_IF(_i) \ + gmock_a##_i + +#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::testing::A() + +#define GMOCK_INTERNAL_ARG_O(_i, ...) \ + typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type + +#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ + const ::testing::Matcher::template Arg<_i>::type>& + +#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) +#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) +#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) +#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) +#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) +#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) +#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) +#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) +#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) +#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) +#define MOCK_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) +#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) +#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) +#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) +#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) +#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) +#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) +#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) +#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) +#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) +#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ + (::testing::internal::identity_t<__VA_ARGS__>)) + +#define GMOCK_MOCKER_(arity, constness, Method) \ + GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ diff --git a/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-matchers.h b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-matchers.h new file mode 100644 index 0000000000000000000000000000000000000000..063ee6ca25e73665a5df31a75b722c52caf648d0 --- /dev/null +++ b/packages/simplecc-wasm/OpenCC/deps/googletest-1.15.0/googlemock/include/gmock/gmock-matchers.h @@ -0,0 +1,5624 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The MATCHER* family of macros can be used in a namespace scope to +// define custom matchers easily. +// +// Basic Usage +// =========== +// +// The syntax +// +// MATCHER(name, description_string) { statements; } +// +// defines a matcher with the given name that executes the statements, +// which must return a bool to indicate if the match succeeds. Inside +// the statements, you can refer to the value being matched by 'arg', +// and refer to its type by 'arg_type'. +// +// The description string documents what the matcher does, and is used +// to generate the failure message when the match fails. Since a +// MATCHER() is usually defined in a header file shared by multiple +// C++ source files, we require the description to be a C-string +// literal to avoid possible side effects. It can be empty, in which +// case we'll use the sequence of words in the matcher name as the +// description. +// +// For example: +// +// MATCHER(IsEven, "") { return (arg % 2) == 0; } +// +// allows you to write +// +// // Expects mock_foo.Bar(n) to be called where n is even. +// EXPECT_CALL(mock_foo, Bar(IsEven())); +// +// or, +// +// // Verifies that the value of some_expression is even. +// EXPECT_THAT(some_expression, IsEven()); +// +// If the above assertion fails, it will print something like: +// +// Value of: some_expression +// Expected: is even +// Actual: 7 +// +// where the description "is even" is automatically calculated from the +// matcher name IsEven. +// +// Argument Type +// ============= +// +// Note that the type of the value being matched (arg_type) is +// determined by the context in which you use the matcher and is +// supplied to you by the compiler, so you don't need to worry about +// declaring it (nor can you). This allows the matcher to be +// polymorphic. For example, IsEven() can be used to match any type +// where the value of "(arg % 2) == 0" can be implicitly converted to +// a bool. In the "Bar(IsEven())" example above, if method Bar() +// takes an int, 'arg_type' will be int; if it takes an unsigned long, +// 'arg_type' will be unsigned long; and so on. +// +// Parameterizing Matchers +// ======================= +// +// Sometimes you'll want to parameterize the matcher. For that you +// can use another macro: +// +// MATCHER_P(name, param_name, description_string) { statements; } +// +// For example: +// +// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +// +// will allow you to write: +// +// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +// +// which may lead to this message (assuming n is 10): +// +// Value of: Blah("a") +// Expected: has absolute value 10 +// Actual: -9 +// +// Note that both the matcher description and its parameter are +// printed, making the message human-friendly. +// +// In the matcher definition body, you can write 'foo_type' to +// reference the type of a parameter named 'foo'. For example, in the +// body of MATCHER_P(HasAbsoluteValue, value) above, you can write +// 'value_type' to refer to the type of 'value'. +// +// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to +// support multi-parameter matchers. +// +// Describing Parameterized Matchers +// ================================= +// +// The last argument to MATCHER*() is a string-typed expression. The +// expression can reference all of the matcher's parameters and a +// special bool-typed variable named 'negation'. When 'negation' is +// false, the expression should evaluate to the matcher's description; +// otherwise it should evaluate to the description of the negation of +// the matcher. For example, +// +// using testing::PrintToString; +// +// MATCHER_P2(InClosedRange, low, hi, +// std::string(negation ? "is not" : "is") + " in range [" + +// PrintToString(low) + ", " + PrintToString(hi) + "]") { +// return low <= arg && arg <= hi; +// } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: is in range [4, 6] +// ... +// Expected: is not in range [2, 4] +// +// If you specify "" as the description, the failure message will +// contain the sequence of words in the matcher name followed by the +// parameter values printed as a tuple. For example, +// +// MATCHER_P2(InClosedRange, low, hi, "") { ... } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: in closed range (4, 6) +// ... +// Expected: not (in closed range (2, 4)) +// +// Types of Matcher Parameters +// =========================== +// +// For the purpose of typing, you can view +// +// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +// +// as shorthand for +// +// template +// FooMatcherPk +// Foo(p1_type p1, ..., pk_type pk) { ... } +// +// When you write Foo(v1, ..., vk), the compiler infers the types of +// the parameters v1, ..., and vk for you. If you are not happy with +// the result of the type inference, you can specify the types by +// explicitly instantiating the template, as in Foo(5, +// false). As said earlier, you don't get to (or need to) specify +// 'arg_type' as that's determined by the context in which the matcher +// is used. You can assign the result of expression Foo(p1, ..., pk) +// to a variable of type FooMatcherPk. This +// can be useful when composing matchers. +// +// While you can instantiate a matcher template with reference types, +// passing the parameters by pointer usually makes your code more +// readable. If, however, you still want to pass a parameter by +// reference, be aware that in the failure message generated by the +// matcher you will see the value of the referenced object but not its +// address. +// +// Explaining Match Results +// ======================== +// +// Sometimes the matcher description alone isn't enough to explain why +// the match has failed or succeeded. For example, when expecting a +// long string, it can be very helpful to also print the diff between +// the expected string and the actual one. To achieve that, you can +// optionally stream additional information to a special variable +// named result_listener, whose type is a pointer to class +// MatchResultListener: +// +// MATCHER_P(EqualsLongString, str, "") { +// if (arg == str) return true; +// +// *result_listener << "the difference: " +/// << DiffStrings(str, arg); +// return false; +// } +// +// Overloading Matchers +// ==================== +// +// You can overload matchers with different numbers of parameters: +// +// MATCHER_P(Blah, a, description_string1) { ... } +// MATCHER_P2(Blah, a, b, description_string2) { ... } +// +// Caveats +// ======= +// +// When defining a new matcher, you should also consider implementing +// MatcherInterface or using MakePolymorphicMatcher(). These +// approaches require more work than the MATCHER* macros, but also +// give you more control on the types of the value being matched and +// the matcher parameters, which may leads to better compiler error +// messages when the matcher is used wrong. They also allow +// overloading matchers based on parameter types (as opposed to just +// based on the number of parameters). +// +// MATCHER*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// +// More Information +// ================ +// +// To learn more about using these macros, please search for 'MATCHER' +// on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md +// +// This file also implements some commonly used argument matchers. More +// matchers can be defined by the user implementing the +// MatcherInterface interface if necessary. +// +// See googletest/include/gtest/gtest-matchers.h for the definition of class +// Matcher, class MatcherInterface, and others. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // NOLINT +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" +#include "gtest/gtest.h" + +// MSVC warning C5046 is new as of VS2017 version 15.8. +#if defined(_MSC_VER) && _MSC_VER >= 1915 +#define GMOCK_MAYBE_5046_ 5046 +#else +#define GMOCK_MAYBE_5046_ +#endif + +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by + clients of class B */ + /* Symbol involving type with internal linkage not defined */) + +namespace testing { + +// To implement a matcher Foo for type T, define: +// 1. a class FooMatcherImpl that implements the +// MatcherInterface interface, and +// 2. a factory function that creates a Matcher object from a +// FooMatcherImpl*. +// +// The two-level delegation design makes it possible to allow a user +// to write "v" instead of "Eq(v)" where a Matcher is expected, which +// is impossible if we pass matchers by pointers. It also eases +// ownership management as Matcher objects can now be copied like +// plain values. + +// A match result listener that stores the explanation in a string. +class StringMatchResultListener : public MatchResultListener { + public: + StringMatchResultListener() : MatchResultListener(&ss_) {} + + // Returns the explanation accumulated so far. + std::string str() const { return ss_.str(); } + + // Clears the explanation accumulated so far. + void Clear() { ss_.str(""); } + + private: + ::std::stringstream ss_; + + StringMatchResultListener(const StringMatchResultListener&) = delete; + StringMatchResultListener& operator=(const StringMatchResultListener&) = + delete; +}; + +// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION +// and MUST NOT BE USED IN USER CODE!!! +namespace internal { + +// The MatcherCastImpl class template is a helper for implementing +// MatcherCast(). We need this helper in order to partially +// specialize the implementation of MatcherCast() (C++ allows +// class/struct templates to be partially specialized, but not +// function templates.). + +// This general version is used when MatcherCast()'s argument is a +// polymorphic matcher (i.e. something that can be converted to a +// Matcher but is not one yet; for example, Eq(value)) or a value (for +// example, "hello"). +template +class MatcherCastImpl { + public: + static Matcher Cast(const M& polymorphic_matcher_or_value) { + // M can be a polymorphic matcher, in which case we want to use + // its conversion operator to create Matcher. Or it can be a value + // that should be passed to the Matcher's constructor. + // + // We can't call Matcher(polymorphic_matcher_or_value) when M is a + // polymorphic matcher because it'll be ambiguous if T has an implicit + // constructor from M (this usually happens when T has an implicit + // constructor from any type). + // + // It won't work to unconditionally implicit_cast + // polymorphic_matcher_or_value to Matcher because it won't trigger + // a user-defined conversion from M to T if one exists (assuming M is + // a value). + return CastImpl(polymorphic_matcher_or_value, + std::is_convertible>{}, + std::is_convertible{}); + } + + private: + template + static Matcher CastImpl(const M& polymorphic_matcher_or_value, + std::true_type /* convertible_to_matcher */, + std::integral_constant) { + // M is implicitly convertible to Matcher, which means that either + // M is a polymorphic matcher or Matcher has an implicit constructor + // from M. In both cases using the implicit conversion will produce a + // matcher. + // + // Even if T has an implicit constructor from M, it won't be called because + // creating Matcher would require a chain of two user-defined conversions + // (first to create T from M and then to create Matcher from T). + return polymorphic_matcher_or_value; + } + + // M can't be implicitly converted to Matcher, so M isn't a polymorphic + // matcher. It's a value of a type implicitly convertible to T. Use direct + // initialization to create a matcher. + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::true_type /* convertible_to_T */) { + return Matcher(ImplicitCast_(value)); + } + + // M can't be implicitly converted to either Matcher or T. Attempt to use + // polymorphic matcher Eq(value) in this case. + // + // Note that we first attempt to perform an implicit cast on the value and + // only fall back to the polymorphic Eq() matcher afterwards because the + // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end + // which might be undefined even when Rhs is implicitly convertible to Lhs + // (e.g. std::pair vs. std::pair). + // + // We don't define this method inline as we need the declaration of Eq(). + static Matcher CastImpl(const M& value, + std::false_type /* convertible_to_matcher */, + std::false_type /* convertible_to_T */); +}; + +// This more specialized version is used when MatcherCast()'s argument +// is already a Matcher. This only compiles when type T can be +// statically converted to type U. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& source_matcher) { + return Matcher(new Impl(source_matcher)); + } + + private: + class Impl : public MatcherInterface { + public: + explicit Impl(const Matcher& source_matcher) + : source_matcher_(source_matcher) {} + + // We delegate the matching logic to the source matcher. + bool MatchAndExplain(T x, MatchResultListener* listener) const override { + using FromType = typename std::remove_cv::type>::type>::type; + using ToType = typename std::remove_cv::type>::type>::type; + // Do not allow implicitly converting base*/& to derived*/&. + static_assert( + // Do not trigger if only one of them is a pointer. That implies a + // regular conversion and not a down_cast. + (std::is_pointer::type>::value != + std::is_pointer::type>::value) || + std::is_same::value || + !std::is_base_of::value, + "Can't implicitly convert from to "); + + // Do the cast to `U` explicitly if necessary. + // Otherwise, let implicit conversions do the trick. + using CastType = + typename std::conditional::value, + T&, U>::type; + + return source_matcher_.MatchAndExplain(static_cast(x), + listener); + } + + void DescribeTo(::std::ostream* os) const override { + source_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + source_matcher_.DescribeNegationTo(os); + } + + private: + const Matcher source_matcher_; + }; +}; + +// This even more specialized version is used for efficiently casting +// a matcher to its own type. +template +class MatcherCastImpl> { + public: + static Matcher Cast(const Matcher& matcher) { return matcher; } +}; + +// Template specialization for parameterless Matcher. +template +class MatcherBaseImpl { + public: + MatcherBaseImpl() = default; + + template + operator ::testing::Matcher() const { // NOLINT(runtime/explicit) + return ::testing::Matcher(new + typename Derived::template gmock_Impl()); + } +}; + +// Template specialization for Matcher with parameters. +template