diff options
Diffstat (limited to 'third-party/pdfjs/web/viewer.js')
-rw-r--r-- | third-party/pdfjs/web/viewer.js | 6368 |
1 files changed, 3937 insertions, 2431 deletions
diff --git a/third-party/pdfjs/web/viewer.js b/third-party/pdfjs/web/viewer.js index 1d54e92c7..d0064cf18 100644 --- a/third-party/pdfjs/web/viewer.js +++ b/third-party/pdfjs/web/viewer.js @@ -2,7 +2,7 @@ * @licstart The following is the entire license notice for the * Javascript code in this page * - * Copyright 2020 Mozilla Foundation + * Copyright 2021 Mozilla Foundation * Modifications made for Epiphany by Jan-Michael Brummer <jan.brummer@tabos.org> * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,279 +21,331 @@ * Javascript code in this page */ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ([ +/* 0 */, +/* 1 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -; -let pdfjsWebApp, pdfjsWebAppOptions; -{ - pdfjsWebApp = __webpack_require__(1); - pdfjsWebAppOptions = __webpack_require__(3); -} -; -{ - __webpack_require__(35); -} -; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.OptionKind = exports.AppOptions = void 0; + +var _viewer_compatibility = __webpack_require__(2); + +const OptionKind = { + VIEWER: 0x02, + API: 0x04, + WORKER: 0x08, + PREFERENCE: 0x80 +}; +exports.OptionKind = OptionKind; +const defaultOptions = { + cursorToolOnLoad: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + defaultUrl: { + value: "compressed.tracemonkey-pldi-09.pdf", + kind: OptionKind.VIEWER + }, + defaultZoomValue: { + value: "", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + disableHistory: { + value: false, + kind: OptionKind.VIEWER + }, + disablePageLabels: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enablePermissions: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enablePrintAutoRotate: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableScripting: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + externalLinkRel: { + value: "noopener noreferrer nofollow", + kind: OptionKind.VIEWER + }, + externalLinkTarget: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + historyUpdateUrl: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + ignoreDestinationZoom: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + imageResourcesPath: { + value: "./images/", + kind: OptionKind.VIEWER + }, + maxCanvasPixels: { + value: 16777216, + compatibility: _viewer_compatibility.viewerCompatibilityParams.maxCanvasPixels, + kind: OptionKind.VIEWER + }, + pdfBugEnabled: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + printResolution: { + value: 150, + kind: OptionKind.VIEWER + }, + renderer: { + value: "canvas", + kind: OptionKind.VIEWER + }, + renderInteractiveForms: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + sidebarViewOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + scrollModeOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + spreadModeOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + textLayerMode: { + value: 1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + useOnlyCssZoom: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + viewerCssTheme: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + viewOnLoad: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + cMapPacked: { + value: true, + kind: OptionKind.API + }, + cMapUrl: { + value: "../web/cmaps/", + kind: OptionKind.API + }, + disableAutoFetch: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableFontFace: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableRange: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableStream: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + docBaseUrl: { + value: "", + kind: OptionKind.API + }, + enableXfa: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + fontExtraProperties: { + value: false, + kind: OptionKind.API + }, + isEvalSupported: { + value: true, + kind: OptionKind.API + }, + maxImageSize: { + value: -1, + kind: OptionKind.API + }, + pdfBug: { + value: false, + kind: OptionKind.API + }, + standardFontDataUrl: { + value: "../web/standard_fonts/", + kind: OptionKind.API + }, + verbosity: { + value: 1, + kind: OptionKind.API + }, + workerPort: { + value: null, + kind: OptionKind.WORKER + }, + workerSrc: { + value: "../build/pdf.worker.js", + kind: OptionKind.WORKER + } +}; { - __webpack_require__(40); + defaultOptions.disablePreferences = { + value: false, + kind: OptionKind.VIEWER + }; + defaultOptions.locale = { + value: typeof navigator !== "undefined" ? navigator.language : "en-US", + kind: OptionKind.VIEWER + }; + defaultOptions.sandboxBundleSrc = { + value: "../build/pdf.sandbox.js", + kind: OptionKind.VIEWER + }; + defaultOptions.renderer.kind += OptionKind.PREFERENCE; } +const userOptions = Object.create(null); -function getViewerConfiguration() { - return { - appContainer: document.body, - mainContainer: document.getElementById("viewerContainer"), - viewerContainer: document.getElementById("viewer"), - eventBus: null, - toolbar: { - container: document.getElementById("toolbarViewer"), - numPages: document.getElementById("numPages"), - pageNumber: document.getElementById("pageNumber"), - scaleSelectContainer: document.getElementById("scaleSelectContainer"), - scaleSelect: document.getElementById("scaleSelect"), - customScaleOption: document.getElementById("customScaleOption"), - previous: document.getElementById("previous"), - next: document.getElementById("next"), - zoomIn: document.getElementById("zoomIn"), - zoomOut: document.getElementById("zoomOut"), - viewFind: document.getElementById("viewFind"), - openFile: document.getElementById("openFile"), - print: document.getElementById("print"), - presentationModeButton: document.getElementById("presentationMode"), - download: document.getElementById("download"), - viewBookmark: document.getElementById("viewBookmark") - }, - secondaryToolbar: { - toolbar: document.getElementById("secondaryToolbar"), - toggleButton: document.getElementById("secondaryToolbarToggle"), - toolbarButtonContainer: document.getElementById("secondaryToolbarButtonContainer"), - presentationModeButton: document.getElementById("secondaryPresentationMode"), - openFileButton: document.getElementById("secondaryOpenFile"), - printButton: document.getElementById("secondaryPrint"), - downloadButton: document.getElementById("secondaryDownload"), - viewBookmarkButton: document.getElementById("secondaryViewBookmark"), - firstPageButton: document.getElementById("firstPage"), - lastPageButton: document.getElementById("lastPage"), - pageRotateCwButton: document.getElementById("pageRotateCw"), - pageRotateCcwButton: document.getElementById("pageRotateCcw"), - cursorSelectToolButton: document.getElementById("cursorSelectTool"), - cursorHandToolButton: document.getElementById("cursorHandTool"), - scrollVerticalButton: document.getElementById("scrollVertical"), - scrollHorizontalButton: document.getElementById("scrollHorizontal"), - scrollWrappedButton: document.getElementById("scrollWrapped"), - spreadNoneButton: document.getElementById("spreadNone"), - spreadOddButton: document.getElementById("spreadOdd"), - spreadEvenButton: document.getElementById("spreadEven"), - documentPropertiesButton: document.getElementById("documentProperties") - }, - fullscreen: { - contextFirstPage: document.getElementById("contextFirstPage"), - contextLastPage: document.getElementById("contextLastPage"), - contextPageRotateCw: document.getElementById("contextPageRotateCw"), - contextPageRotateCcw: document.getElementById("contextPageRotateCcw") - }, - sidebar: { - outerContainer: document.getElementById("outerContainer"), - viewerContainer: document.getElementById("viewerContainer"), - toggleButton: document.getElementById("sidebarToggle"), - thumbnailButton: document.getElementById("viewThumbnail"), - outlineButton: document.getElementById("viewOutline"), - attachmentsButton: document.getElementById("viewAttachments"), - layersButton: document.getElementById("viewLayers"), - thumbnailView: document.getElementById("thumbnailView"), - outlineView: document.getElementById("outlineView"), - attachmentsView: document.getElementById("attachmentsView"), - layersView: document.getElementById("layersView") - }, - sidebarResizer: { - outerContainer: document.getElementById("outerContainer"), - resizer: document.getElementById("sidebarResizer") - }, - findBar: { - bar: document.getElementById("findbar"), - toggleButton: document.getElementById("viewFind"), - findField: document.getElementById("findInput"), - highlightAllCheckbox: document.getElementById("findHighlightAll"), - caseSensitiveCheckbox: document.getElementById("findMatchCase"), - entireWordCheckbox: document.getElementById("findEntireWord"), - findMsg: document.getElementById("findMsg"), - findResultsCount: document.getElementById("findResultsCount"), - findPreviousButton: document.getElementById("findPrevious"), - findNextButton: document.getElementById("findNext") - }, - passwordOverlay: { - overlayName: "passwordOverlay", - container: document.getElementById("passwordOverlay"), - label: document.getElementById("passwordText"), - input: document.getElementById("password"), - submitButton: document.getElementById("passwordSubmit"), - cancelButton: document.getElementById("passwordCancel") - }, - documentProperties: { - overlayName: "documentPropertiesOverlay", - container: document.getElementById("documentPropertiesOverlay"), - closeButton: document.getElementById("documentPropertiesClose"), - fields: { - fileName: document.getElementById("fileNameField"), - fileSize: document.getElementById("fileSizeField"), - title: document.getElementById("titleField"), - author: document.getElementById("authorField"), - subject: document.getElementById("subjectField"), - keywords: document.getElementById("keywordsField"), - creationDate: document.getElementById("creationDateField"), - modificationDate: document.getElementById("modificationDateField"), - creator: document.getElementById("creatorField"), - producer: document.getElementById("producerField"), - version: document.getElementById("versionField"), - pageCount: document.getElementById("pageCountField"), - pageSize: document.getElementById("pageSizeField"), - linearized: document.getElementById("linearizedField") +class AppOptions { + constructor() { + throw new Error("Cannot initialize AppOptions."); + } + + static get(name) { + const userOption = userOptions[name]; + + if (userOption !== undefined) { + return userOption; + } + + const defaultOption = defaultOptions[name]; + + if (defaultOption !== undefined) { + return defaultOption.compatibility ?? defaultOption.value; + } + + return undefined; + } + + static getAll(kind = null) { + const options = Object.create(null); + + for (const name in defaultOptions) { + const defaultOption = defaultOptions[name]; + + if (kind) { + if ((kind & defaultOption.kind) === 0) { + continue; + } + + if (kind === OptionKind.PREFERENCE) { + const value = defaultOption.value, + valueType = typeof value; + + if (valueType === "boolean" || valueType === "string" || valueType === "number" && Number.isInteger(value)) { + options[name] = value; + continue; + } + + throw new Error(`Invalid type for preference: ${name}`); + } } - }, - errorWrapper: { - container: document.getElementById("errorWrapper"), - errorMessage: document.getElementById("errorMessage"), - closeButton: document.getElementById("errorClose"), - errorMoreInfo: document.getElementById("errorMoreInfo"), - moreInfoButton: document.getElementById("errorShowMore"), - lessInfoButton: document.getElementById("errorShowLess") - }, - printContainer: document.getElementById("printContainer"), - openFileInputName: "fileInput", - debuggerScriptPath: "./debugger.js" - }; -} -function webViewerLoad() { - const config = getViewerConfiguration(); - window.PDFViewerApplication = pdfjsWebApp.PDFViewerApplication; - window.PDFViewerApplicationOptions = pdfjsWebAppOptions.AppOptions; - const event = document.createEvent("CustomEvent"); - event.initCustomEvent("webviewerloaded", true, true, { - source: window - }); + const userOption = userOptions[name]; + options[name] = userOption !== undefined ? userOption : defaultOption.compatibility ?? defaultOption.value; + } - try { - parent.document.dispatchEvent(event); - } catch (ex) { - console.error(`webviewerloaded: ${ex}`); - document.dispatchEvent(event); + return options; + } + + static set(name, value) { + userOptions[name] = value; + } + + static setAll(options) { + for (const name in options) { + userOptions[name] = options[name]; + } + } + + static remove(name) { + delete userOptions[name]; } - pdfjsWebApp.PDFViewerApplication.run(config); } -if (document.readyState === "interactive" || document.readyState === "complete") { - webViewerLoad(); -} else { - document.addEventListener("DOMContentLoaded", webViewerLoad, true); +exports.AppOptions = AppOptions; + +/***/ }), +/* 2 */ +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.viewerCompatibilityParams = void 0; +const compatibilityParams = Object.create(null); +{ + const userAgent = typeof navigator !== "undefined" && navigator.userAgent || ""; + const platform = typeof navigator !== "undefined" && navigator.platform || ""; + const maxTouchPoints = typeof navigator !== "undefined" && navigator.maxTouchPoints || 1; + const isAndroid = /Android/.test(userAgent); + const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; + const isIOSChrome = /CriOS/.test(userAgent); + + (function checkOnBlobSupport() { + if (isIOSChrome) { + compatibilityParams.disableCreateObjectURL = true; + } + })(); + + (function checkCanvasSizeLimitation() { + if (isIOS || isAndroid) { + compatibilityParams.maxCanvasPixels = 5242880; + } + })(); } +const viewerCompatibilityParams = Object.freeze(compatibilityParams); +exports.viewerCompatibilityParams = viewerCompatibilityParams; /***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { +/* 3 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.PDFPrintServiceFactory = exports.DefaultExternalServices = exports.PDFViewerApplication = void 0; +})); +exports.PDFViewerApplication = exports.PDFPrintServiceFactory = exports.DefaultExternalServices = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); -var _app_options = __webpack_require__(3); +var _app_options = __webpack_require__(1); var _pdfjsLib = __webpack_require__(5); @@ -301,43 +353,45 @@ var _pdf_cursor_tools = __webpack_require__(6); var _pdf_rendering_queue = __webpack_require__(8); -var _pdf_sidebar = __webpack_require__(9); +var _overlay_manager = __webpack_require__(9); -var _overlay_manager = __webpack_require__(10); +var _password_prompt = __webpack_require__(10); -var _password_prompt = __webpack_require__(11); +var _pdf_attachment_viewer = __webpack_require__(11); -var _pdf_attachment_viewer = __webpack_require__(12); +var _pdf_document_properties = __webpack_require__(13); -var _pdf_document_properties = __webpack_require__(14); +var _pdf_find_bar = __webpack_require__(14); -var _pdf_find_bar = __webpack_require__(15); +var _pdf_find_controller = __webpack_require__(15); -var _pdf_find_controller = __webpack_require__(16); +var _pdf_history = __webpack_require__(17); -var _pdf_history = __webpack_require__(18); +var _pdf_layer_viewer = __webpack_require__(18); -var _pdf_layer_viewer = __webpack_require__(19); +var _pdf_link_service = __webpack_require__(19); -var _pdf_link_service = __webpack_require__(20); +var _pdf_outline_viewer = __webpack_require__(20); -var _pdf_outline_viewer = __webpack_require__(21); +var _pdf_presentation_mode = __webpack_require__(21); -var _pdf_presentation_mode = __webpack_require__(22); +var _pdf_scripting_manager = __webpack_require__(22); -var _pdf_sidebar_resizer = __webpack_require__(23); +var _pdf_sidebar = __webpack_require__(23); -var _pdf_thumbnail_viewer = __webpack_require__(24); +var _pdf_sidebar_resizer = __webpack_require__(24); -var _pdf_viewer = __webpack_require__(26); +var _pdf_thumbnail_viewer = __webpack_require__(25); -var _secondary_toolbar = __webpack_require__(31); +var _pdf_viewer = __webpack_require__(27); -var _toolbar = __webpack_require__(33); +var _secondary_toolbar = __webpack_require__(35); -var _viewer_compatibility = __webpack_require__(4); +var _toolbar = __webpack_require__(37); -var _view_history = __webpack_require__(34); +var _viewer_compatibility = __webpack_require__(2); + +var _view_history = __webpack_require__(38); const DEFAULT_SCALE_DELTA = 1.1; const DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000; @@ -349,6 +403,11 @@ const ViewOnLoad = { PREVIOUS: 0, INITIAL: 1 }; +const ViewerCssTheme = { + AUTOMATIC: 0, + LIGHT: 1, + DARK: 2 +}; const KNOWN_VERSIONS = ["1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2.0", "2.1", "2.2", "2.3"]; const KNOWN_GENERATORS = ["acrobat distiller", "acrobat pdfwriter", "adobe livecycle", "adobe pdf library", "adobe photoshop", "ghostscript", "tcpdf", "cairo", "dvipdfm", "dvips", "pdftex", "pdfkit", "itext", "prince", "quarkxpress", "mac os x", "microsoft", "openoffice", "oracle", "luradocument", "pdf-xchange", "antenna house", "aspose.cells", "fpdf"]; @@ -363,7 +422,7 @@ class DefaultExternalServices { static initPassiveLoading(callbacks) {} - static fallback(data, callback) {} + static async fallback(data) {} static reportTelemetry(data) {} @@ -379,6 +438,10 @@ class DefaultExternalServices { throw new Error("Not implemented: createL10n"); } + static createScripting(options) { + throw new Error("Not implemented: createScripting"); + } + static get supportsIntegratedFind() { return (0, _pdfjsLib.shadow)(this, "supportsIntegratedFind", false); } @@ -404,7 +467,7 @@ exports.DefaultExternalServices = DefaultExternalServices; const PDFViewerApplication = { initialBookmark: document.location.hash.substring(1), _initializedCapability: (0, _pdfjsLib.createPromiseCapability)(), - fellback: false, + _fellback: false, appConfig: null, pdfDocument: null, pdfLoadingTask: null, @@ -422,6 +485,7 @@ const PDFViewerApplication = { pdfAttachmentViewer: null, pdfLayerViewer: null, pdfCursorTools: null, + pdfScriptingManager: null, store: null, downloadManager: null, overlayManager: null, @@ -436,17 +500,23 @@ const PDFViewerApplication = { url: "", baseUrl: "", externalServices: DefaultExternalServices, - _boundEvents: {}, - contentDispositionFilename: null, - triggerDelayedFallback: null, + _boundEvents: Object.create(null), + documentInfo: null, + metadata: null, + _contentDispositionFilename: null, + _contentLength: null, _saveInProgress: false, _wheelUnusedTicks: 0, + _idleCallbacks: new Set(), async initialize(appConfig) { this.preferences = this.externalServices.createPreferences(); this.appConfig = appConfig; await this._readPreferences(); await this._parseHashParameters(); + + this._forceCssTheme(); + await this._initializeL10n(); if (this.isViewerEmbedded && _app_options.AppOptions.get("externalLinkTarget") === _pdfjsLib.LinkTarget.NONE) { @@ -472,13 +542,9 @@ const PDFViewerApplication = { } try { - const prefs = await this.preferences.getAll(); - - for (const name in prefs) { - _app_options.AppOptions.set(name, prefs[name]); - } + _app_options.AppOptions.setAll(await this.preferences.getAll()); } catch (reason) { - console.error(`_readPreferences: "${reason.message}".`); + console.error(`_readPreferences: "${reason?.message}".`); } }, @@ -520,10 +586,6 @@ const PDFViewerApplication = { _app_options.AppOptions.set("disableHistory", hashParams.disablehistory === "true"); } - if ("webgl" in hashParams) { - _app_options.AppOptions.set("enableWebGL", hashParams.webgl === "true"); - } - if ("verbosity" in hashParams) { _app_options.AppOptions.set("verbosity", hashParams.verbosity | 0); } @@ -557,6 +619,10 @@ const PDFViewerApplication = { _app_options.AppOptions.set("locale", hashParams.locale); } + if (waitOn.length === 0) { + return undefined; + } + return Promise.all(waitOn).catch(reason => { console.error(`_parseHashParameters: "${reason.message}".`); }); @@ -570,6 +636,44 @@ const PDFViewerApplication = { document.getElementsByTagName("html")[0].dir = dir; }, + _forceCssTheme() { + const cssTheme = _app_options.AppOptions.get("viewerCssTheme"); + + if (cssTheme === ViewerCssTheme.AUTOMATIC || !Object.values(ViewerCssTheme).includes(cssTheme)) { + return; + } + + try { + const styleSheet = document.styleSheets[0]; + const cssRules = styleSheet?.cssRules || []; + const mediaMatcher = "prefers-color-scheme"; + const mediaRule = `(${mediaMatcher}: dark)`; + const mediaRegex = new RegExp(`^@media \\(${mediaMatcher}: dark\\) {\\n\\s*([\\w\\s-.,:;/\\\\{}()]+)\\n}$`); + + for (let i = 0, ii = cssRules.length; i < ii; i++) { + const rule = cssRules[i]; + + if (rule instanceof CSSMediaRule && rule.media?.[0] === mediaRule) { + if (cssTheme === ViewerCssTheme.LIGHT) { + styleSheet.deleteRule(i); + return; + } + + const darkRules = mediaRegex.exec(rule.cssText); + + if (darkRules?.[1]) { + styleSheet.deleteRule(i); + styleSheet.insertRule(darkRules[1], i); + } + + return; + } + } + } catch (reason) { + console.error(`_forceCssTheme: "${reason?.message}".`); + } + }, + async _initializeViewerComponents() { const appConfig = this.appConfig; const eventBus = appConfig.eventBus || new _ui_utils.EventBus({ @@ -578,7 +682,7 @@ const PDFViewerApplication = { this.eventBus = eventBus; this.overlayManager = new _overlay_manager.OverlayManager(); const pdfRenderingQueue = new _pdf_rendering_queue.PDFRenderingQueue(); - pdfRenderingQueue.onIdle = this.cleanup.bind(this); + pdfRenderingQueue.onIdle = this._cleanup.bind(this); this.pdfRenderingQueue = pdfRenderingQueue; const pdfLinkService = new _pdf_link_service.PDFLinkService({ eventBus, @@ -594,6 +698,13 @@ const PDFViewerApplication = { eventBus }); this.findController = findController; + const pdfScriptingManager = new _pdf_scripting_manager.PDFScriptingManager({ + eventBus, + sandboxBundleSrc: _app_options.AppOptions.get("sandboxBundleSrc"), + scriptingFactory: this.externalServices, + docPropertiesLookup: this._scriptingDocProperties.bind(this) + }); + this.pdfScriptingManager = pdfScriptingManager; const container = appConfig.mainContainer; const viewer = appConfig.viewerContainer; this.pdfViewer = new _pdf_viewer.PDFViewer({ @@ -604,18 +715,20 @@ const PDFViewerApplication = { linkService: pdfLinkService, downloadManager, findController, + scriptingManager: pdfScriptingManager, renderer: _app_options.AppOptions.get("renderer"), - enableWebGL: _app_options.AppOptions.get("enableWebGL"), l10n: this.l10n, textLayerMode: _app_options.AppOptions.get("textLayerMode"), imageResourcesPath: _app_options.AppOptions.get("imageResourcesPath"), renderInteractiveForms: _app_options.AppOptions.get("renderInteractiveForms"), enablePrintAutoRotate: _app_options.AppOptions.get("enablePrintAutoRotate"), useOnlyCssZoom: _app_options.AppOptions.get("useOnlyCssZoom"), - maxCanvasPixels: _app_options.AppOptions.get("maxCanvasPixels") + maxCanvasPixels: _app_options.AppOptions.get("maxCanvasPixels"), + enableScripting: _app_options.AppOptions.get("enableScripting") }); pdfRenderingQueue.setViewer(this.pdfViewer); pdfLinkService.setViewer(this.pdfViewer); + pdfScriptingManager.setViewer(this.pdfViewer); this.pdfThumbnailViewer = new _pdf_thumbnail_viewer.PDFThumbnailViewer({ container: appConfig.sidebar.thumbnailView, eventBus, @@ -647,12 +760,11 @@ const PDFViewerApplication = { this.pdfPresentationMode = new _pdf_presentation_mode.PDFPresentationMode({ container, pdfViewer: this.pdfViewer, - eventBus, - contextMenuItems: appConfig.fullscreen + eventBus }); } - this.passwordPrompt = new _password_prompt.PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, this.l10n); + this.passwordPrompt = new _password_prompt.PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, this.l10n, this.isViewerEmbedded); this.pdfOutlineViewer = new _pdf_outline_viewer.PDFOutlineViewer({ container: appConfig.sidebar.outlineView, eventBus, @@ -743,20 +855,15 @@ const PDFViewerApplication = { this.pdfViewer.currentPageNumber = val; }, - get printing() { - return !!this.printService; - }, - get supportsPrinting() { return PDFPrintServiceFactory.instance.supportsPrinting; }, get supportsFullscreen() { - let support; const doc = document.documentElement; - support = !!(doc.requestFullscreen || doc.mozRequestFullScreen || doc.webkitRequestFullScreen || doc.msRequestFullscreen); + let support = !!(doc.requestFullscreen || doc.mozRequestFullScreen || doc.webkitRequestFullScreen); - if (document.fullscreenEnabled === false || document.mozFullScreenEnabled === false || document.webkitFullscreenEnabled === false || document.msFullscreenEnabled === false) { + if (document.fullscreenEnabled === false || document.mozFullScreenEnabled === false || document.webkitFullscreenEnabled === false) { support = false; } @@ -787,7 +894,7 @@ const PDFViewerApplication = { setTitleUsingUrl(url = "") { this.url = url; this.baseUrl = url.split("#")[0]; - let title = (0, _ui_utils.getPDFFileNameFromURL)(url, ""); + let title = (0, _pdfjsLib.getPdfFilenameFromUrl)(url, ""); if (!title) { try { @@ -808,15 +915,44 @@ const PDFViewerApplication = { document.title = title; }, + get _docFilename() { + return this._contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(this.url); + }, + + _cancelIdleCallbacks() { + if (!this._idleCallbacks.size) { + return; + } + + for (const callback of this._idleCallbacks) { + window.cancelIdleCallback(callback); + } + + this._idleCallbacks.clear(); + }, + async close() { - const errorWrapper = this.appConfig.errorWrapper.container; - errorWrapper.setAttribute("hidden", "true"); + this._unblockDocumentLoadEvent(); + + const { + container + } = this.appConfig.errorWrapper; + container.hidden = true; if (!this.pdfLoadingTask) { - return undefined; + return; + } + + if (this.pdfDocument?.annotationStorage.size > 0 && this._annotationStorageModified) { + try { + await this.save({ + sourceEventType: "save" + }); + } catch (reason) {} } - const promise = this.pdfLoadingTask.destroy(); + const promises = []; + promises.push(this.pdfLoadingTask.destroy()); this.pdfLoadingTask = null; if (this.pdfDocument) { @@ -828,14 +964,22 @@ const PDFViewerApplication = { } webViewerResetPermissions(); + this.pdfLinkService.externalLinkEnabled = true; + this._fellback = false; this.store = null; this.isInitialViewSet = false; this.downloadComplete = false; this.url = ""; this.baseUrl = ""; - this.contentDispositionFilename = null; - this.triggerDelayedFallback = null; + this.documentInfo = null; + this.metadata = null; + this._contentDispositionFilename = null; + this._contentLength = null; this._saveInProgress = false; + + this._cancelIdleCallbacks(); + + promises.push(this.pdfScriptingManager.destroyPromise); this.pdfSidebar.reset(); this.pdfOutlineViewer.reset(); this.pdfAttachmentViewer.reset(); @@ -856,7 +1000,7 @@ const PDFViewerApplication = { PDFBug.cleanup(); } - return promise; + await Promise.all(promises); }, async open(file, args) { @@ -894,13 +1038,7 @@ const PDFViewerApplication = { if (args) { for (const key in args) { - const value = args[key]; - - if (key === "length") { - this.pdfDocumentProperties.setFileSize(value); - } - - parameters[key] = value; + parameters[key] = args[key]; } } @@ -928,104 +1066,88 @@ const PDFViewerApplication = { return undefined; } - const message = exception && exception.message; - let loadingErrorMessage; + let key = "loading_error"; if (exception instanceof _pdfjsLib.InvalidPDFException) { - loadingErrorMessage = this.l10n.get("invalid_file_error", null, "Invalid or corrupted PDF file."); + key = "invalid_file_error"; } else if (exception instanceof _pdfjsLib.MissingPDFException) { - loadingErrorMessage = this.l10n.get("missing_file_error", null, "Missing PDF file."); + key = "missing_file_error"; } else if (exception instanceof _pdfjsLib.UnexpectedResponseException) { - loadingErrorMessage = this.l10n.get("unexpected_response_error", null, "Unexpected server response."); - } else { - loadingErrorMessage = this.l10n.get("loading_error", null, "An error occurred while loading the PDF."); + key = "unexpected_response_error"; } - return loadingErrorMessage.then(msg => { - this.error(msg, { - message + return this.l10n.get(key).then(msg => { + this._documentError(msg, { + message: exception?.message }); + throw exception; }); }); }, - download({ - sourceEventType = "download" - } = {}) { - function downloadByUrl() { - downloadManager.downloadUrl(url, filename); + _ensureDownloadComplete() { + if (this.pdfDocument && this.downloadComplete) { + return; } - const url = this.baseUrl; - const filename = this.contentDispositionFilename || (0, _ui_utils.getPDFFileNameFromURL)(this.url); - const downloadManager = this.downloadManager; + throw new Error("PDF document not downloaded."); + }, - downloadManager.onerror = err => { - this.error(`PDF failed to download: ${err}`); - }; + async download({ + sourceEventType = "download" + } = {}) { + const url = this.baseUrl, + filename = this._docFilename; - if (!this.pdfDocument || !this.downloadComplete) { - downloadByUrl(); - return; - } + try { + this._ensureDownloadComplete(); - this.pdfDocument.getData().then(function (data) { + const data = await this.pdfDocument.getData(); const blob = new Blob([data], { type: "application/pdf" }); - downloadManager.download(blob, url, filename, sourceEventType); - }).catch(downloadByUrl); + await this.downloadManager.download(blob, url, filename, sourceEventType); + } catch (reason) { + await this.downloadManager.downloadUrl(url, filename); + } }, - save({ + async save({ sourceEventType = "download" } = {}) { if (this._saveInProgress) { return; } - const url = this.baseUrl; - const filename = this.contentDispositionFilename || (0, _ui_utils.getPDFFileNameFromURL)(this.url); - const downloadManager = this.downloadManager; - - downloadManager.onerror = err => { - this.error(`PDF failed to be saved: ${err}`); - }; + this._saveInProgress = true; + await this.pdfScriptingManager.dispatchWillSave(); + const url = this.baseUrl, + filename = this._docFilename; - if (!this.pdfDocument || !this.downloadComplete) { - this.download({ - sourceEventType - }); - return; - } + try { + this._ensureDownloadComplete(); - this._saveInProgress = true; - this.pdfDocument.saveDocument(this.pdfDocument.annotationStorage).then(data => { + const data = await this.pdfDocument.saveDocument(); const blob = new Blob([data], { type: "application/pdf" }); - downloadManager.download(blob, url, filename, sourceEventType); - }).catch(() => { - this.download({ + await this.downloadManager.download(blob, url, filename, sourceEventType); + } catch (reason) { + await this.download({ sourceEventType }); - }).finally(() => { + } finally { + await this.pdfScriptingManager.dispatchDidSave(); this._saveInProgress = false; - }); + } }, - _delayedFallback(featureId) { - this.externalServices.reportTelemetry({ - type: "unsupportedFeature", - featureId - }); - - if (!this.triggerDelayedFallback) { - this.triggerDelayedFallback = () => { - this.fallback(featureId); - this.triggerDelayedFallback = null; - }; + downloadOrSave(options) { + if (this.pdfDocument?.annotationStorage.size > 0) { + this.save(options); + } else { + this.download(options); } }, @@ -1035,64 +1157,70 @@ const PDFViewerApplication = { featureId }); - if (this.fellback) { + if (this._fellback) { return; } - this.fellback = true; + this._fellback = true; this.externalServices.fallback({ featureId, url: this.baseUrl - }, function response(download) { + }).then(download => { if (!download) { return; } - PDFViewerApplication.download({ + this.download({ sourceEventType: "download" }); }); }, - error(message, moreInfo) { + _documentError(message, moreInfo = null) { + this._unblockDocumentLoadEvent(); + + this._otherError(message, moreInfo); + }, + + _otherError(message, moreInfo = null) { const moreInfoText = [this.l10n.get("error_version_info", { version: _pdfjsLib.version || "?", build: _pdfjsLib.build || "?" - }, "PDF.js v{{version}} (build: {{build}})")]; + })]; if (moreInfo) { moreInfoText.push(this.l10n.get("error_message", { message: moreInfo.message - }, "Message: {{message}}")); + })); if (moreInfo.stack) { moreInfoText.push(this.l10n.get("error_stack", { stack: moreInfo.stack - }, "Stack: {{stack}}")); + })); } else { if (moreInfo.filename) { moreInfoText.push(this.l10n.get("error_file", { file: moreInfo.filename - }, "File: {{file}}")); + })); } if (moreInfo.lineNumber) { moreInfoText.push(this.l10n.get("error_line", { line: moreInfo.lineNumber - }, "Line: {{line}}")); + })); } } } const errorWrapperConfig = this.appConfig.errorWrapper; const errorWrapper = errorWrapperConfig.container; - errorWrapper.removeAttribute("hidden"); + errorWrapper.hidden = false; const errorMessage = errorWrapperConfig.errorMessage; errorMessage.textContent = message; const closeButton = errorWrapperConfig.closeButton; closeButton.onclick = function () { - errorWrapper.setAttribute("hidden", "true"); + errorWrapper.hidden = true; }; const errorMoreInfo = errorWrapperConfig.errorMoreInfo; @@ -1100,23 +1228,23 @@ const PDFViewerApplication = { const lessInfoButton = errorWrapperConfig.lessInfoButton; moreInfoButton.onclick = function () { - errorMoreInfo.removeAttribute("hidden"); - moreInfoButton.setAttribute("hidden", "true"); - lessInfoButton.removeAttribute("hidden"); + errorMoreInfo.hidden = false; + moreInfoButton.hidden = true; + lessInfoButton.hidden = false; errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px"; }; lessInfoButton.onclick = function () { - errorMoreInfo.setAttribute("hidden", "true"); - moreInfoButton.removeAttribute("hidden"); - lessInfoButton.setAttribute("hidden", "true"); + errorMoreInfo.hidden = true; + moreInfoButton.hidden = false; + lessInfoButton.hidden = true; }; moreInfoButton.oncontextmenu = _ui_utils.noContextMenuHandler; lessInfoButton.oncontextmenu = _ui_utils.noContextMenuHandler; closeButton.oncontextmenu = _ui_utils.noContextMenuHandler; - moreInfoButton.removeAttribute("hidden"); - lessInfoButton.setAttribute("hidden", "true"); + moreInfoButton.hidden = false; + lessInfoButton.hidden = true; Promise.all(moreInfoText).then(parts => { errorMoreInfo.value = parts.join("\n"); }); @@ -1150,7 +1278,10 @@ const PDFViewerApplication = { load(pdfDocument) { this.pdfDocument = pdfDocument; - pdfDocument.getDownloadInfo().then(() => { + pdfDocument.getDownloadInfo().then(({ + length + }) => { + this._contentLength = length; this.downloadComplete = true; this.loadingBar.hide(); firstPagePromise.then(() => { @@ -1168,16 +1299,6 @@ const PDFViewerApplication = { baseDocumentUrl = null; this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl); this.pdfDocumentProperties.setDocument(pdfDocument, this.url); - const annotationStorage = pdfDocument.annotationStorage; - - annotationStorage.onSetModified = function () { - window.addEventListener("beforeunload", beforeUnload); - }; - - annotationStorage.onResetModified = function () { - window.removeEventListener("beforeunload", beforeUnload); - }; - const pdfViewer = this.pdfViewer; pdfViewer.setDocument(pdfDocument); const { @@ -1187,13 +1308,13 @@ const PDFViewerApplication = { } = pdfViewer; const pdfThumbnailViewer = this.pdfThumbnailViewer; pdfThumbnailViewer.setDocument(pdfDocument); - const storedPromise = (this.store = new _view_history.ViewHistory(pdfDocument.fingerprint)).getMultiple({ + const storedPromise = (this.store = new _view_history.ViewHistory(pdfDocument.fingerprints[0])).getMultiple({ page: null, zoom: _ui_utils.DEFAULT_SCALE_VALUE, scrollLeft: "0", scrollTop: "0", rotation: null, - sidebarView: _pdf_sidebar.SidebarView.UNKNOWN, + sidebarView: _ui_utils.SidebarView.UNKNOWN, scrollMode: _ui_utils.ScrollMode.UNKNOWN, spreadMode: _ui_utils.SpreadMode.UNKNOWN }).catch(() => { @@ -1201,13 +1322,16 @@ const PDFViewerApplication = { }); firstPagePromise.then(pdfPage => { this.loadingBar.setWidth(this.appConfig.viewerContainer); + + this._initializeAnnotationStorageCallbacks(pdfDocument); + Promise.all([_ui_utils.animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise]).then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => { const viewOnLoad = _app_options.AppOptions.get("viewOnLoad"); this._initializePdfHistory({ - fingerprint: pdfDocument.fingerprint, + fingerprint: pdfDocument.fingerprints[0], viewOnLoad, - initialDest: openAction && openAction.dest + initialDest: openAction?.dest }); const initialBookmark = this.initialBookmark; @@ -1227,7 +1351,7 @@ const PDFViewerApplication = { hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`; rotation = parseInt(stored.rotation, 10); - if (sidebarView === _pdf_sidebar.SidebarView.UNKNOWN) { + if (sidebarView === _ui_utils.SidebarView.UNKNOWN) { sidebarView = stored.sidebarView | 0; } @@ -1240,12 +1364,12 @@ const PDFViewerApplication = { } } - if (pageMode && sidebarView === _pdf_sidebar.SidebarView.UNKNOWN) { - sidebarView = apiPageModeToSidebarView(pageMode); + if (pageMode && sidebarView === _ui_utils.SidebarView.UNKNOWN) { + sidebarView = (0, _ui_utils.apiPageModeToSidebarView)(pageMode); } if (pageLayout && spreadMode === _ui_utils.SpreadMode.UNKNOWN) { - spreadMode = apiPageLayoutToSpreadMode(pageLayout); + spreadMode = (0, _ui_utils.apiPageLayoutToSpreadMode)(pageLayout); } this.setInitialView(hash, { @@ -1286,25 +1410,52 @@ const PDFViewerApplication = { }); }); pagesPromise.then(() => { + this._unblockDocumentLoadEvent(); + this._initializeAutoPrint(pdfDocument, openActionPromise); }); onePageRendered.then(() => { pdfDocument.getOutline().then(outline => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.pdfOutlineViewer.render({ - outline + outline, + pdfDocument }); }); pdfDocument.getAttachments().then(attachments => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.pdfAttachmentViewer.render({ attachments }); }); pdfViewer.optionalContentConfigPromise.then(optionalContentConfig => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.pdfLayerViewer.render({ optionalContentConfig, pdfDocument }); }); + + if ("requestIdleCallback" in window) { + const callback = window.requestIdleCallback(() => { + this._collectTelemetry(pdfDocument); + + this._idleCallbacks.delete(callback); + }, { + timeout: 1000 + }); + + this._idleCallbacks.add(callback); + } }); this._initializePageLabels(pdfDocument); @@ -1312,8 +1463,58 @@ const PDFViewerApplication = { this._initializeMetadata(pdfDocument); }, + async _scriptingDocProperties(pdfDocument) { + if (!this.documentInfo) { + await new Promise(resolve => { + this.eventBus._on("metadataloaded", resolve, { + once: true + }); + }); + + if (pdfDocument !== this.pdfDocument) { + return null; + } + } + + if (!this._contentLength) { + await new Promise(resolve => { + this.eventBus._on("documentloaded", resolve, { + once: true + }); + }); + + if (pdfDocument !== this.pdfDocument) { + return null; + } + } + + return { ...this.documentInfo, + baseURL: this.baseUrl, + filesize: this._contentLength, + filename: this._docFilename, + metadata: this.metadata?.getRaw(), + authors: this.metadata?.get("dc:creator"), + numPages: this.pagesCount, + URL: this.url + }; + }, + + async _collectTelemetry(pdfDocument) { + const markInfo = await this.pdfDocument.getMarkInfo(); + + if (pdfDocument !== this.pdfDocument) { + return; + } + + const tagged = markInfo?.Marked || false; + this.externalServices.reportTelemetry({ + type: "tagged", + tagged + }); + }, + async _initializeAutoPrint(pdfDocument, openActionPromise) { - const [openAction, javaScript] = await Promise.all([openActionPromise, pdfDocument.getJavaScript()]); + const [openAction, javaScript] = await Promise.all([openActionPromise, !this.pdfViewer.enableScripting ? pdfDocument.getJavaScript() : null]); if (pdfDocument !== this.pdfDocument) { return; @@ -1321,7 +1522,7 @@ const PDFViewerApplication = { let triggerAutoPrint = false; - if (openAction && openAction.action === "Print") { + if (openAction?.action === "Print") { triggerAutoPrint = true; } @@ -1331,10 +1532,8 @@ const PDFViewerApplication = { return false; } - console.warn("Warning: JavaScript is not supported"); - - this._delayedFallback(_pdfjsLib.UNSUPPORTED_FEATURES.javaScript); - + console.warn("Warning: JavaScript support is not enabled"); + this.fallback(_pdfjsLib.UNSUPPORTED_FEATURES.javaScript); return true; }); @@ -1348,14 +1547,8 @@ const PDFViewerApplication = { } } - if (!this.supportsPrinting) { - return; - } - if (triggerAutoPrint) { - setTimeout(function () { - window.print(); - }); + this.triggerPrinting(); } }, @@ -1363,7 +1556,8 @@ const PDFViewerApplication = { const { info, metadata, - contentDispositionFilename + contentDispositionFilename, + contentLength } = await pdfDocument.getMetadata(); if (pdfDocument !== this.pdfDocument) { @@ -1372,16 +1566,11 @@ const PDFViewerApplication = { this.documentInfo = info; this.metadata = metadata; - this.contentDispositionFilename = contentDispositionFilename; - console.log(`PDF ${pdfDocument.fingerprint} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${_pdfjsLib.version || "-"}` + `${this.pdfViewer.enableWebGL ? " [WebGL]" : ""})`); - let pdfTitle; - const infoTitle = info && info.Title; - - if (infoTitle) { - pdfTitle = infoTitle; - } - - const metadataTitle = metadata && metadata.get("dc:title"); + this._contentDispositionFilename ?? (this._contentDispositionFilename = contentDispositionFilename); + this._contentLength ?? (this._contentLength = contentLength); + console.log(`PDF ${pdfDocument.fingerprints[0]} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${_pdfjsLib.version || "-"})`); + let pdfTitle = info?.Title; + const metadataTitle = metadata?.get("dc:title"); if (metadataTitle) { if (metadataTitle !== "Untitled" && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) { @@ -1395,14 +1584,17 @@ const PDFViewerApplication = { this.setTitle(contentDispositionFilename); } - if (info.IsXFAPresent && !info.IsAcroFormPresent) { - console.warn("Warning: XFA is not supported"); - - this._delayedFallback(_pdfjsLib.UNSUPPORTED_FEATURES.forms); + if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) { + console.warn("Warning: XFA support is not enabled"); + this.fallback(_pdfjsLib.UNSUPPORTED_FEATURES.forms); } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderInteractiveForms) { console.warn("Warning: Interactive form support is not enabled"); + this.fallback(_pdfjsLib.UNSUPPORTED_FEATURES.forms); + } - this._delayedFallback(_pdfjsLib.UNSUPPORTED_FEATURES.forms); + if (info.IsSignaturesPresent) { + console.warn("Warning: Digital signatures validation is not supported"); + this.fallback(_pdfjsLib.UNSUPPORTED_FEATURES.signatures); } let versionId = "other"; @@ -1420,7 +1612,7 @@ const PDFViewerApplication = { return false; } - generatorId = generator.replace(/[ .\-]/g, "_"); + generatorId = generator.replace(/[ .-]/g, "_"); return true; }); } @@ -1439,6 +1631,9 @@ const PDFViewerApplication = { generator: generatorId, formType }); + this.eventBus.dispatch("metadataloaded", { + source: this + }); }, async _initializePageLabels(pdfDocument) { @@ -1525,6 +1720,26 @@ const PDFViewerApplication = { } }, + _initializeAnnotationStorageCallbacks(pdfDocument) { + if (pdfDocument !== this.pdfDocument) { + return; + } + + const { + annotationStorage + } = pdfDocument; + + annotationStorage.onSetModified = () => { + window.addEventListener("beforeunload", beforeUnload); + this._annotationStorageModified = true; + }; + + annotationStorage.onResetModified = () => { + window.removeEventListener("beforeunload", beforeUnload); + delete this._annotationStorageModified; + }; + }, + setInitialView(storedHash, { rotation, sidebarView, @@ -1569,40 +1784,39 @@ const PDFViewerApplication = { } }, - cleanup() { + _cleanup() { if (!this.pdfDocument) { return; } this.pdfViewer.cleanup(); this.pdfThumbnailViewer.cleanup(); - - if (this.pdfViewer.renderer !== _ui_utils.RendererType.SVG) { - this.pdfDocument.cleanup(); - } + this.pdfDocument.cleanup(this.pdfViewer.renderer === _ui_utils.RendererType.SVG); }, forceRendering() { - this.pdfRenderingQueue.printing = this.printing; + this.pdfRenderingQueue.printing = !!this.printService; this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar.isThumbnailViewVisible; this.pdfRenderingQueue.renderHighestPriority(); }, beforePrint() { + this.pdfScriptingManager.dispatchWillPrint(); + if (this.printService) { return; } if (!this.supportsPrinting) { - this.l10n.get("printing_not_supported", null, "Warning: Printing is not fully supported by this browser.").then(printMessage => { - this.error(printMessage); + this.l10n.get("printing_not_supported").then(msg => { + this._otherError(msg); }); return; } if (!this.pdfViewer.pageViewsReady) { - this.l10n.get("printing_not_ready", null, "Warning: The PDF is not fully loaded for printing.").then(notReadyMessage => { - window.alert(notReadyMessage); + this.l10n.get("printing_not_ready").then(msg => { + window.alert(msg); }); return; } @@ -1623,6 +1837,8 @@ const PDFViewerApplication = { }, afterPrint() { + this.pdfScriptingManager.dispatchDidPrint(); + if (this.printService) { this.printService.destroy(); this.printService = null; @@ -1636,12 +1852,7 @@ const PDFViewerApplication = { }, rotatePages(delta) { - if (!this.pdfDocument) { - return; - } - - const newRotation = (this.pdfViewer.pagesRotation + 360 + delta) % 360; - this.pdfViewer.pagesRotation = newRotation; + this.pdfViewer.pagesRotation += delta; }, requestPresentationMode() { @@ -1652,6 +1863,14 @@ const PDFViewerApplication = { this.pdfPresentationMode.request(); }, + triggerPrinting() { + if (!this.supportsPrinting) { + return; + } + + window.print(); + }, + bindEvents() { const { eventBus, @@ -1736,6 +1955,14 @@ const PDFViewerApplication = { eventBus._on("updatefindcontrolstate", webViewerUpdateFindControlState); + if (_app_options.AppOptions.get("pdfBug")) { + _boundEvents.reportPageStatsPDFBug = reportPageStatsPDFBug; + + eventBus._on("pagerendered", _boundEvents.reportPageStatsPDFBug); + + eventBus._on("pagechanging", _boundEvents.reportPageStatsPDFBug); + } + eventBus._on("fileinputchange", webViewerFileInputChange); eventBus._on("openfile", webViewerOpenFile); @@ -1772,6 +1999,13 @@ const PDFViewerApplication = { }); }; + _boundEvents.windowUpdateFromSandbox = event => { + eventBus.dispatch("updatefromsandbox", { + source: window, + detail: event.detail + }); + }; + window.addEventListener("visibilitychange", webViewerVisibilityChange); window.addEventListener("wheel", webViewerWheel, { passive: false @@ -1781,11 +2015,11 @@ const PDFViewerApplication = { }); window.addEventListener("click", webViewerClick); window.addEventListener("keydown", webViewerKeyDown); - window.addEventListener("keyup", webViewerKeyUp); window.addEventListener("resize", _boundEvents.windowResize); window.addEventListener("hashchange", _boundEvents.windowHashChange); window.addEventListener("beforeprint", _boundEvents.windowBeforePrint); window.addEventListener("afterprint", _boundEvents.windowAfterPrint); + window.addEventListener("updatefromsandbox", _boundEvents.windowUpdateFromSandbox); }, unbindEvents() { @@ -1870,6 +2104,14 @@ const PDFViewerApplication = { eventBus._off("updatefindcontrolstate", webViewerUpdateFindControlState); + if (_boundEvents.reportPageStatsPDFBug) { + eventBus._off("pagerendered", _boundEvents.reportPageStatsPDFBug); + + eventBus._off("pagechanging", _boundEvents.reportPageStatsPDFBug); + + _boundEvents.reportPageStatsPDFBug = null; + } + eventBus._off("fileinputchange", webViewerFileInputChange); eventBus._off("openfile", webViewerOpenFile); @@ -1891,15 +2133,16 @@ const PDFViewerApplication = { }); window.removeEventListener("click", webViewerClick); window.removeEventListener("keydown", webViewerKeyDown); - window.removeEventListener("keyup", webViewerKeyUp); window.removeEventListener("resize", _boundEvents.windowResize); window.removeEventListener("hashchange", _boundEvents.windowHashChange); window.removeEventListener("beforeprint", _boundEvents.windowBeforePrint); window.removeEventListener("afterprint", _boundEvents.windowAfterPrint); + window.removeEventListener("updatefromsandbox", _boundEvents.windowUpdateFromSandbox); _boundEvents.windowResize = null; _boundEvents.windowHashChange = null; _boundEvents.windowBeforePrint = null; _boundEvents.windowAfterPrint = null; + _boundEvents.windowUpdateFromSandbox = null; }, accumulateWheelTicks(ticks) { @@ -1911,6 +2154,18 @@ const PDFViewerApplication = { const wholeTicks = Math.sign(this._wheelUnusedTicks) * Math.floor(Math.abs(this._wheelUnusedTicks)); this._wheelUnusedTicks -= wholeTicks; return wholeTicks; + }, + + _unblockDocumentLoadEvent() { + if (document.blockUnblockOnload) { + document.blockUnblockOnload(false); + } + + this._unblockDocumentLoadEvent = () => {}; + }, + + get scriptingReady() { + return this.pdfScriptingManager.ready; } }; @@ -1940,10 +2195,9 @@ let validateFileURL; throw new Error("file origin does not match viewer's"); } } catch (ex) { - const message = ex && ex.message; - PDFViewerApplication.l10n.get("loading_error", null, "An error occurred while loading the PDF.").then(loadingErrorMessage => { - PDFViewerApplication.error(loadingErrorMessage, { - message + PDFViewerApplication.l10n.get("loading_error").then(msg => { + PDFViewerApplication._documentError(msg, { + message: ex?.message }); }); throw ex; @@ -1969,6 +2223,23 @@ function loadAndEnablePDFBug(enabledTabs) { }); } +function reportPageStatsPDFBug({ + pageNumber +}) { + if (typeof Stats === "undefined" || !Stats.enabled) { + return; + } + + const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1); + const pageStats = pageView?.pdfPage?.stats; + + if (!pageStats) { + return; + } + + Stats.add(pageNumber, pageStats); +} + function webViewerInitialized() { const appConfig = PDFViewerApplication.appConfig; let file; @@ -2018,7 +2289,7 @@ function webViewerInitialized() { if (!PDFViewerApplication.supportsDocumentFonts) { _app_options.AppOptions.set("disableFontFace", true); - PDFViewerApplication.l10n.get("web_fonts_disabled", null, "Web fonts are disabled: unable to use embedded PDF fonts.").then(msg => { + PDFViewerApplication.l10n.get("web_fonts_disabled").then(msg => { console.warn(msg); }); } @@ -2058,33 +2329,16 @@ function webViewerInitialized() { PDFViewerApplication.open(array); PDFViewerApplication.setTitleUsingUrl(file_name); } catch (reason) { - PDFViewerApplication.l10n.get("loading_error", null, "An error occurred while loading the PDF.").then(msg => { - PDFViewerApplication.error(msg, reason); + PDFViewerApplication.l10n.get("loading_error").then(msg => { + PDFViewerApplication._documentError(msg, reason); }); } } -let webViewerOpenFileViaURL; -{ - webViewerOpenFileViaURL = function (file) { - if (file && file.lastIndexOf("file:", 0) === 0) { - PDFViewerApplication.setTitleUsingUrl(file); - const xhr = new XMLHttpRequest(); - - xhr.onload = function () { - PDFViewerApplication.open(new Uint8Array(xhr.response)); - }; - - xhr.open("GET", file); - xhr.responseType = "arraybuffer"; - xhr.send(); - return; - } - - if (file) { - PDFViewerApplication.open(file); - } - }; +function webViewerOpenFileViaURL(file) { + if (file) { + PDFViewerApplication.open(file); + } } function webViewerResetPermissions() { @@ -2099,37 +2353,33 @@ function webViewerResetPermissions() { appConfig.viewerContainer.classList.remove(ENABLE_PERMISSIONS_CLASS); } -function webViewerPageRendered(evt) { - const pageNumber = evt.pageNumber; - const pageIndex = pageNumber - 1; - const pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex); - +function webViewerPageRendered({ + pageNumber, + timestamp, + error +}) { if (pageNumber === PDFViewerApplication.page) { PDFViewerApplication.toolbar.updateLoadingIndicatorState(false); } - if (!pageView) { - return; - } - if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) { - const thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(pageIndex); - thumbnailView.setImage(pageView); - } + const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1); + const thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(pageNumber - 1); - if (typeof Stats !== "undefined" && Stats.enabled && pageView.stats) { - Stats.add(pageNumber, pageView.stats); + if (pageView && thumbnailView) { + thumbnailView.setImage(pageView); + } } - if (pageView.error) { - PDFViewerApplication.l10n.get("rendering_error", null, "An error occurred while rendering the page.").then(msg => { - PDFViewerApplication.error(msg, pageView.error); + if (error) { + PDFViewerApplication.l10n.get("rendering_error").then(msg => { + PDFViewerApplication._otherError(msg, error); }); } PDFViewerApplication.externalServices.reportTelemetry({ type: "pageInfo", - timestamp: evt.timestamp + timestamp }); PDFViewerApplication.pdfDocument.getStats().then(function (stats) { PDFViewerApplication.externalServices.reportTelemetry({ @@ -2146,24 +2396,24 @@ function webViewerPageMode({ switch (mode) { case "thumbs": - view = _pdf_sidebar.SidebarView.THUMBS; + view = _ui_utils.SidebarView.THUMBS; break; case "bookmarks": case "outline": - view = _pdf_sidebar.SidebarView.OUTLINE; + view = _ui_utils.SidebarView.OUTLINE; break; case "attachments": - view = _pdf_sidebar.SidebarView.ATTACHMENTS; + view = _ui_utils.SidebarView.ATTACHMENTS; break; case "layers": - view = _pdf_sidebar.SidebarView.LAYERS; + view = _ui_utils.SidebarView.LAYERS; break; case "none": - view = _pdf_sidebar.SidebarView.NONE; + view = _ui_utils.SidebarView.NONE; break; default: @@ -2188,10 +2438,7 @@ function webViewerNamedAction(evt) { break; case "Print": - if (PDFViewerApplication.supportsPrinting) { - webViewerPrint(); - } - + PDFViewerApplication.triggerPrinting(); break; case "SaveAs": @@ -2200,19 +2447,8 @@ function webViewerNamedAction(evt) { } } -function webViewerPresentationModeChanged({ - active, - switchInProgress -}) { - let state = _ui_utils.PresentationModeState.NORMAL; - - if (switchInProgress) { - state = _ui_utils.PresentationModeState.CHANGING; - } else if (active) { - state = _ui_utils.PresentationModeState.FULLSCREEN; - } - - PDFViewerApplication.pdfViewer.presentationModeState = state; +function webViewerPresentationModeChanged(evt) { + PDFViewerApplication.pdfViewer.presentationModeState = evt.state; } function webViewerSidebarViewChanged(evt) { @@ -2242,7 +2478,7 @@ function webViewerUpdateViewarea(evt) { PDFViewerApplication.appConfig.toolbar.viewBookmark.href = href; PDFViewerApplication.appConfig.secondaryToolbar.viewBookmarkButton.href = href; const currentPage = PDFViewerApplication.pdfViewer.getPageView(PDFViewerApplication.page - 1); - const loading = currentPage.renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED; + const loading = currentPage?.renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED; PDFViewerApplication.toolbar.updateLoadingIndicatorState(loading); } @@ -2298,7 +2534,7 @@ function webViewerHashchange(evt) { let webViewerFileInputChange, webViewerOpenFile; { webViewerFileInputChange = function (evt) { - if (PDFViewerApplication.pdfViewer && PDFViewerApplication.pdfViewer.isInPresentationMode) { + if (PDFViewerApplication.pdfViewer?.isInPresentationMode) { return; } @@ -2328,10 +2564,10 @@ let webViewerFileInputChange, webViewerOpenFile; } const appConfig = PDFViewerApplication.appConfig; - appConfig.toolbar.viewBookmark.setAttribute("hidden", "true"); - appConfig.secondaryToolbar.viewBookmarkButton.setAttribute("hidden", "true"); - appConfig.toolbar.download.setAttribute("hidden", "true"); - appConfig.secondaryToolbar.downloadButton.setAttribute("hidden", "true"); + appConfig.toolbar.viewBookmark.hidden = true; + appConfig.secondaryToolbar.viewBookmarkButton.hidden = true; + appConfig.toolbar.download.hidden = true; + appConfig.secondaryToolbar.downloadButton.hidden = true; }; webViewerOpenFile = function (evt) { @@ -2345,27 +2581,19 @@ function webViewerPresentationMode() { } function webViewerPrint() { - window.print(); -} - -function webViewerDownloadOrSave(sourceEventType) { - if (PDFViewerApplication.pdfDocument && PDFViewerApplication.pdfDocument.annotationStorage.size > 0) { - PDFViewerApplication.save({ - sourceEventType - }); - } else { - PDFViewerApplication.download({ - sourceEventType - }); - } + PDFViewerApplication.triggerPrinting(); } function webViewerDownload() { - webViewerDownloadOrSave("download"); + PDFViewerApplication.downloadOrSave({ + sourceEventType: "download" + }); } function webViewerSave() { - webViewerDownloadOrSave("save"); + PDFViewerApplication.downloadOrSave({ + sourceEventType: "save" + }); } function webViewerFirstPage() { @@ -2381,11 +2609,11 @@ function webViewerLastPage() { } function webViewerNextPage() { - PDFViewerApplication.page++; + PDFViewerApplication.pdfViewer.nextPage(); } function webViewerPreviousPage() { - PDFViewerApplication.page--; + PDFViewerApplication.pdfViewer.previousPage(); } function webViewerZoomIn() { @@ -2404,7 +2632,7 @@ function webViewerPageNumberChanged(evt) { const pdfViewer = PDFViewerApplication.pdfViewer; if (evt.value !== "") { - pdfViewer.currentPageLabel = evt.value; + PDFViewerApplication.pdfLinkService.goToPage(evt.value); } if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) { @@ -2501,21 +2729,15 @@ function webViewerRotationChanging(evt) { PDFViewerApplication.pdfViewer.currentPageNumber = evt.pageNumber; } -function webViewerPageChanging(evt) { - const page = evt.pageNumber; - PDFViewerApplication.toolbar.setPageNumber(page, evt.pageLabel || null); - PDFViewerApplication.secondaryToolbar.setPageNumber(page); +function webViewerPageChanging({ + pageNumber, + pageLabel +}) { + PDFViewerApplication.toolbar.setPageNumber(pageNumber, pageLabel); + PDFViewerApplication.secondaryToolbar.setPageNumber(pageNumber); if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) { - PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(page); - } - - if (typeof Stats !== "undefined" && Stats.enabled) { - const pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1); - - if (pageView && pageView.stats) { - Stats.add(page, pageView.stats); - } + PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(pageNumber); } } @@ -2597,10 +2819,6 @@ function webViewerTouchStart(evt) { } function webViewerClick(evt) { - if (PDFViewerApplication.triggerDelayedFallback && PDFViewerApplication.pdfViewer.containsElement(evt.target)) { - PDFViewerApplication.triggerDelayedFallback(); - } - if (!PDFViewerApplication.secondaryToolbar.isOpen) { return; } @@ -2612,14 +2830,6 @@ function webViewerClick(evt) { } } -function webViewerKeyUp(evt) { - if (evt.keyCode === 9) { - if (PDFViewerApplication.triggerDelayedFallback) { - PDFViewerApplication.triggerDelayedFallback(); - } - } -} - function webViewerKeyDown(evt) { if (PDFViewerApplication.overlayManager.active) { return; @@ -2629,12 +2839,12 @@ function webViewerKeyDown(evt) { ensureViewerFocused = false; const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0); const pdfViewer = PDFViewerApplication.pdfViewer; - const isViewerInPresentationMode = pdfViewer && pdfViewer.isInPresentationMode; + const isViewerInPresentationMode = pdfViewer?.isInPresentationMode; if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) { switch (evt.keyCode) { case 70: - if (!PDFViewerApplication.supportsIntegratedFind) { + if (!PDFViewerApplication.supportsIntegratedFind && !evt.shiftKey) { PDFViewerApplication.findBar.open(); handled = true; } @@ -2760,10 +2970,10 @@ function webViewerKeyDown(evt) { return; } - const curElement = document.activeElement || document.querySelector(":focus"); - const curElementTagName = curElement && curElement.tagName.toUpperCase(); + const curElement = (0, _ui_utils.getActiveOrFocusedElement)(); + const curElementTagName = curElement?.tagName.toUpperCase(); - if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElement && curElement.isContentEditable) { + if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElement?.isContentEditable) { if (evt.keyCode !== 27) { return; } @@ -2879,13 +3089,9 @@ function webViewerKeyDown(evt) { if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) { if (turnPage > 0) { - if (PDFViewerApplication.page < PDFViewerApplication.pagesCount) { - PDFViewerApplication.page++; - } + pdfViewer.nextPage(); } else { - if (PDFViewerApplication.page > 1) { - PDFViewerApplication.page--; - } + pdfViewer.previousPage(); } handled = true; @@ -2934,45 +3140,6 @@ function beforeUnload(evt) { return false; } -function apiPageLayoutToSpreadMode(layout) { - switch (layout) { - case "SinglePage": - case "OneColumn": - return _ui_utils.SpreadMode.NONE; - - case "TwoColumnLeft": - case "TwoPageLeft": - return _ui_utils.SpreadMode.ODD; - - case "TwoColumnRight": - case "TwoPageRight": - return _ui_utils.SpreadMode.EVEN; - } - - return _ui_utils.SpreadMode.NONE; -} - -function apiPageModeToSidebarView(mode) { - switch (mode) { - case "UseNone": - return _pdf_sidebar.SidebarView.NONE; - - case "UseThumbs": - return _pdf_sidebar.SidebarView.THUMBS; - - case "UseOutlines": - return _pdf_sidebar.SidebarView.OUTLINE; - - case "UseAttachments": - return _pdf_sidebar.SidebarView.ATTACHMENTS; - - case "UseOC": - return _pdf_sidebar.SidebarView.LAYERS; - } - - return _pdf_sidebar.SidebarView.NONE; -} - const PDFPrintServiceFactory = { instance: { supportsPrinting: false, @@ -2986,37 +3153,37 @@ const PDFPrintServiceFactory = { exports.PDFPrintServiceFactory = PDFPrintServiceFactory; /***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { +/* 4 */ +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); +exports.apiPageLayoutToSpreadMode = apiPageLayoutToSpreadMode; +exports.apiPageModeToSidebarView = apiPageModeToSidebarView; +exports.approximateFraction = approximateFraction; +exports.backtrackBeforeAllVisibleElements = backtrackBeforeAllVisibleElements; +exports.binarySearchFirstItem = binarySearchFirstItem; +exports.getActiveOrFocusedElement = getActiveOrFocusedElement; +exports.getOutputScale = getOutputScale; +exports.getPageSizeInches = getPageSizeInches; +exports.getVisibleElements = getVisibleElements; +exports.isPortraitOrientation = isPortraitOrientation; exports.isValidRotation = isValidRotation; exports.isValidScrollMode = isValidScrollMode; exports.isValidSpreadMode = isValidSpreadMode; -exports.isPortraitOrientation = isPortraitOrientation; -exports.clamp = clamp; -exports.getPDFFileNameFromURL = getPDFFileNameFromURL; +exports.moveToEndOfArray = moveToEndOfArray; exports.noContextMenuHandler = noContextMenuHandler; +exports.normalizeWheelEventDelta = normalizeWheelEventDelta; +exports.normalizeWheelEventDirection = normalizeWheelEventDirection; exports.parseQueryString = parseQueryString; -exports.backtrackBeforeAllVisibleElements = backtrackBeforeAllVisibleElements; -exports.getVisibleElements = getVisibleElements; exports.roundToDivide = roundToDivide; -exports.getPageSizeInches = getPageSizeInches; -exports.approximateFraction = approximateFraction; -exports.getOutputScale = getOutputScale; exports.scrollIntoView = scrollIntoView; -exports.watchScroll = watchScroll; -exports.binarySearchFirstItem = binarySearchFirstItem; -exports.normalizeWheelEventDirection = normalizeWheelEventDirection; -exports.normalizeWheelEventDelta = normalizeWheelEventDelta; exports.waitOnEventOrTimeout = waitOnEventOrTimeout; -exports.moveToEndOfArray = moveToEndOfArray; -exports.WaitOnType = exports.animationStarted = exports.ProgressBar = exports.EventBus = exports.NullL10n = exports.SpreadMode = exports.ScrollMode = exports.TextLayerMode = exports.RendererType = exports.PresentationModeState = exports.VERTICAL_PADDING = exports.SCROLLBAR_PADDING = exports.MAX_AUTO_SCALE = exports.UNKNOWN_SCALE = exports.MAX_SCALE = exports.MIN_SCALE = exports.DEFAULT_SCALE = exports.DEFAULT_SCALE_VALUE = exports.CSS_UNITS = exports.AutoPrintRegExp = void 0; +exports.watchScroll = watchScroll; +exports.WaitOnType = exports.VERTICAL_PADDING = exports.UNKNOWN_SCALE = exports.TextLayerMode = exports.SpreadMode = exports.SidebarView = exports.ScrollMode = exports.SCROLLBAR_PADDING = exports.RendererType = exports.ProgressBar = exports.PresentationModeState = exports.MIN_SCALE = exports.MAX_SCALE = exports.MAX_AUTO_SCALE = exports.EventBus = exports.DEFAULT_SCALE_VALUE = exports.DEFAULT_SCALE = exports.CSS_UNITS = exports.AutoPrintRegExp = exports.animationStarted = void 0; const CSS_UNITS = 96.0 / 72.0; exports.CSS_UNITS = CSS_UNITS; const DEFAULT_SCALE_VALUE = "auto"; @@ -3035,6 +3202,7 @@ const SCROLLBAR_PADDING = 40; exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING; const VERTICAL_PADDING = 5; exports.VERTICAL_PADDING = VERTICAL_PADDING; +const LOADINGBAR_END_OFFSET_VAR = "--loadingBar-end-offset"; const PresentationModeState = { UNKNOWN: 0, NORMAL: 1, @@ -3042,6 +3210,15 @@ const PresentationModeState = { FULLSCREEN: 3 }; exports.PresentationModeState = PresentationModeState; +const SidebarView = { + UNKNOWN: -1, + NONE: 0, + THUMBS: 1, + OUTLINE: 2, + ATTACHMENTS: 3, + LAYERS: 4 +}; +exports.SidebarView = SidebarView; const RendererType = { CANVAS: "canvas", SVG: "svg" @@ -3070,37 +3247,9 @@ exports.SpreadMode = SpreadMode; const AutoPrintRegExp = /\bprint\s*\(/; exports.AutoPrintRegExp = AutoPrintRegExp; -function formatL10nValue(text, args) { - if (!args) { - return text; - } - - return text.replace(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => { - return name in args ? args[name] : "{{" + name + "}}"; - }); -} - -const NullL10n = { - async getLanguage() { - return "en-us"; - }, - - async getDirection() { - return "ltr"; - }, - - async get(property, args, fallback) { - return formatL10nValue(fallback, args); - }, - - async translate(element) {} - -}; -exports.NullL10n = NullL10n; - function getOutputScale(ctx) { const devicePixelRatio = window.devicePixelRatio || 1; - const backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; + const backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; const pixelRatio = devicePixelRatio / backingStoreRatio; return { sx: pixelRatio, @@ -3109,7 +3258,7 @@ function getOutputScale(ctx) { }; } -function scrollIntoView(element, spot, skipOverflowHiddenElements = false) { +function scrollIntoView(element, spot, scrollMatches = false) { let parent = element.offsetParent; if (!parent) { @@ -3120,12 +3269,7 @@ function scrollIntoView(element, spot, skipOverflowHiddenElements = false) { let offsetY = element.offsetTop + element.clientTop; let offsetX = element.offsetLeft + element.clientLeft; - while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || skipOverflowHiddenElements && getComputedStyle(parent).overflow === "hidden") { - if (parent.dataset._scaleY) { - offsetY /= parent.dataset._scaleY; - offsetX /= parent.dataset._scaleX; - } - + while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { offsetY += parent.offsetTop; offsetX += parent.offsetLeft; parent = parent.offsetParent; @@ -3323,7 +3467,13 @@ function backtrackBeforeAllVisibleElements(index, views, top) { return index; } -function getVisibleElements(scrollEl, views, sortByVisibility = false, horizontal = false) { +function getVisibleElements({ + scrollEl, + views, + sortByVisibility = false, + horizontal = false, + rtl = false +}) { const top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight; const left = scrollEl.scrollLeft, @@ -3335,15 +3485,16 @@ function getVisibleElements(scrollEl, views, sortByVisibility = false, horizonta return elementBottom > top; } - function isElementRightAfterViewLeft(view) { + function isElementNextAfterViewHorizontally(view) { const element = view.div; - const elementRight = element.offsetLeft + element.clientLeft + element.clientWidth; - return elementRight > left; + const elementLeft = element.offsetLeft + element.clientLeft; + const elementRight = elementLeft + element.clientWidth; + return rtl ? elementLeft < right : elementRight > left; } const visible = [], numViews = views.length; - let firstVisibleElementInd = numViews === 0 ? 0 : binarySearchFirstItem(views, horizontal ? isElementRightAfterViewLeft : isElementBottomAfterViewTop); + let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); @@ -3375,13 +3526,16 @@ function getVisibleElements(scrollEl, views, sortByVisibility = false, horizonta const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); - const percent = (viewHeight - hiddenHeight) * (viewWidth - hiddenWidth) * 100 / viewHeight / viewWidth | 0; + const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, + fractionWidth = (viewWidth - hiddenWidth) / viewWidth; + const percent = fractionHeight * fractionWidth * 100 | 0; visible.push({ id: view.id, x: currentWidth, y: currentHeight, view, - percent + percent, + widthPercent: fractionWidth * 100 | 0 }); } @@ -3411,47 +3565,8 @@ function noContextMenuHandler(evt) { evt.preventDefault(); } -function isDataSchema(url) { - let i = 0; - const ii = url.length; - - while (i < ii && url[i].trim() === "") { - i++; - } - - return url.substring(i, i + 5).toLowerCase() === "data:"; -} - -function getPDFFileNameFromURL(url, defaultFilename = "document.pdf") { - if (typeof url !== "string") { - return defaultFilename; - } - - if (isDataSchema(url)) { - console.warn("getPDFFileNameFromURL: " + 'ignoring "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 (ex) {} - } - } - - return suggestedFilename || defaultFilename; -} - function normalizeWheelEventDirection(evt) { - let delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY); + let delta = Math.hypot(evt.deltaX, evt.deltaY); const angle = Math.atan2(evt.deltaY, evt.deltaX); if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { @@ -3550,15 +3665,17 @@ class EventBus { this._listeners = Object.create(null); } - on(eventName, listener) { + on(eventName, listener, options = null) { this._on(eventName, listener, { - external: true + external: true, + once: options?.once }); } - off(eventName, listener) { + off(eventName, listener, options = null) { this._off(eventName, listener, { - external: true + external: true, + once: options?.once }); } @@ -3571,40 +3688,41 @@ class EventBus { const args = Array.prototype.slice.call(arguments, 1); let externalListeners; - eventListeners.slice(0).forEach(function ({ + + for (const { listener, - external - }) { - if (external) { - if (!externalListeners) { - externalListeners = []; - } + external, + once + } of eventListeners.slice(0)) { + if (once) { + this._off(eventName, listener); + } - externalListeners.push(listener); - return; + if (external) { + (externalListeners || (externalListeners = [])).push(listener); + continue; } listener.apply(null, args); - }); + } if (externalListeners) { - externalListeners.forEach(function (listener) { + for (const listener of externalListeners) { listener.apply(null, args); - }); + } + externalListeners = null; } } _on(eventName, listener, options = null) { - let eventListeners = this._listeners[eventName]; - - if (!eventListeners) { - this._listeners[eventName] = eventListeners = []; - } + var _this$_listeners; + const eventListeners = (_this$_listeners = this._listeners)[eventName] || (_this$_listeners[eventName] = []); eventListeners.push({ listener, - external: (options && options.external) === true + external: options?.external === true, + once: options?.once === true }); } @@ -3679,7 +3797,8 @@ class ProgressBar { const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; if (scrollbarWidth > 0) { - this.bar.style.width = `calc(100% - ${scrollbarWidth}px)`; + const doc = document.documentElement; + doc.style.setProperty(LOADINGBAR_END_OFFSET_VAR, `${scrollbarWidth}px`); } } @@ -3690,7 +3809,6 @@ class ProgressBar { this.visible = false; this.bar.classList.add("hidden"); - document.body.classList.remove("loadingInProgress"); } show() { @@ -3699,7 +3817,6 @@ class ProgressBar { } this.visible = true; - document.body.classList.add("loadingInProgress"); this.bar.classList.remove("hidden"); } @@ -3726,299 +3843,61 @@ function moveToEndOfArray(arr, condition) { } } -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.OptionKind = exports.AppOptions = void 0; - -var _viewer_compatibility = __webpack_require__(4); +function getActiveOrFocusedElement() { + let curRoot = document; + let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); -const OptionKind = { - VIEWER: 0x02, - API: 0x04, - WORKER: 0x08, - PREFERENCE: 0x80 -}; -exports.OptionKind = OptionKind; -const defaultOptions = { - cursorToolOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - defaultUrl: { - value: "compressed.tracemonkey-pldi-09.pdf", - kind: OptionKind.VIEWER - }, - defaultZoomValue: { - value: "", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - disableHistory: { - value: false, - kind: OptionKind.VIEWER - }, - disablePageLabels: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePermissions: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enablePrintAutoRotate: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - enableWebGL: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - externalLinkRel: { - value: "noopener noreferrer nofollow", - kind: OptionKind.VIEWER - }, - externalLinkTarget: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - historyUpdateUrl: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - ignoreDestinationZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - imageResourcesPath: { - value: "./images/", - kind: OptionKind.VIEWER - }, - maxCanvasPixels: { - value: 16777216, - compatibility: _viewer_compatibility.viewerCompatibilityParams.maxCanvasPixels, - kind: OptionKind.VIEWER - }, - pdfBugEnabled: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - printResolution: { - value: 150, - kind: OptionKind.VIEWER - }, - renderer: { - value: "canvas", - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - renderInteractiveForms: { - value: true, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - sidebarViewOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - scrollModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - spreadModeOnLoad: { - value: -1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - textLayerMode: { - value: 1, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - useOnlyCssZoom: { - value: false, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - viewOnLoad: { - value: 0, - kind: OptionKind.VIEWER + OptionKind.PREFERENCE - }, - cMapPacked: { - value: true, - kind: OptionKind.API - }, - cMapUrl: { - value: "../web/cmaps/", - kind: OptionKind.API - }, - disableAutoFetch: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableFontFace: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableRange: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - disableStream: { - value: false, - kind: OptionKind.API + OptionKind.PREFERENCE - }, - docBaseUrl: { - value: "", - kind: OptionKind.API - }, - fontExtraProperties: { - value: false, - kind: OptionKind.API - }, - isEvalSupported: { - value: true, - kind: OptionKind.API - }, - maxImageSize: { - value: -1, - kind: OptionKind.API - }, - pdfBug: { - value: false, - kind: OptionKind.API - }, - verbosity: { - value: 1, - kind: OptionKind.API - }, - workerPort: { - value: null, - kind: OptionKind.WORKER - }, - workerSrc: { - value: "../build/pdf.worker.js", - kind: OptionKind.WORKER + while (curActiveOrFocused?.shadowRoot) { + curRoot = curActiveOrFocused.shadowRoot; + curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); } -}; -{ - defaultOptions.disablePreferences = { - value: false, - kind: OptionKind.VIEWER - }; - defaultOptions.locale = { - value: typeof navigator !== "undefined" ? navigator.language : "en-US", - kind: OptionKind.VIEWER - }; -} -const userOptions = Object.create(null); - -class AppOptions { - constructor() { - throw new Error("Cannot initialize AppOptions."); - } - - static get(name) { - const userOption = userOptions[name]; - - if (userOption !== undefined) { - return userOption; - } - - const defaultOption = defaultOptions[name]; - - if (defaultOption !== undefined) { - return defaultOption.compatibility || defaultOption.value; - } - - return undefined; - } - - static getAll(kind = null) { - const options = Object.create(null); - - for (const name in defaultOptions) { - const defaultOption = defaultOptions[name]; - - if (kind) { - if ((kind & defaultOption.kind) === 0) { - continue; - } - - if (kind === OptionKind.PREFERENCE) { - const value = defaultOption.value, - valueType = typeof value; - if (valueType === "boolean" || valueType === "string" || valueType === "number" && Number.isInteger(value)) { - options[name] = value; - continue; - } - - throw new Error(`Invalid type for preference: ${name}`); - } - } - - const userOption = userOptions[name]; - options[name] = userOption !== undefined ? userOption : defaultOption.compatibility || defaultOption.value; - } + return curActiveOrFocused; +} - return options; - } +function apiPageLayoutToSpreadMode(layout) { + switch (layout) { + case "SinglePage": + case "OneColumn": + return SpreadMode.NONE; - static set(name, value) { - userOptions[name] = value; - } + case "TwoColumnLeft": + case "TwoPageLeft": + return SpreadMode.ODD; - static remove(name) { - delete userOptions[name]; + case "TwoColumnRight": + case "TwoPageRight": + return SpreadMode.EVEN; } + return SpreadMode.NONE; } -exports.AppOptions = AppOptions; - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { +function apiPageModeToSidebarView(mode) { + switch (mode) { + case "UseNone": + return SidebarView.NONE; -"use strict"; + case "UseThumbs": + return SidebarView.THUMBS; + case "UseOutlines": + return SidebarView.OUTLINE; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.viewerCompatibilityParams = void 0; -const compatibilityParams = Object.create(null); -{ - const userAgent = typeof navigator !== "undefined" && navigator.userAgent || ""; - const platform = typeof navigator !== "undefined" && navigator.platform || ""; - const maxTouchPoints = typeof navigator !== "undefined" && navigator.maxTouchPoints || 1; - const isAndroid = /Android/.test(userAgent); - const isIE = /Trident/.test(userAgent); - const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; - const isIOSChrome = /CriOS/.test(userAgent); + case "UseAttachments": + return SidebarView.ATTACHMENTS; - (function checkOnBlobSupport() { - if (isIE || isIOSChrome) { - compatibilityParams.disableCreateObjectURL = true; - } - })(); + case "UseOC": + return SidebarView.LAYERS; + } - (function checkCanvasSizeLimitation() { - if (isIOS || isAndroid) { - compatibilityParams.maxCanvasPixels = 5242880; - } - })(); + return SidebarView.NONE; } -const viewerCompatibilityParams = Object.freeze(compatibilityParams); -exports.viewerCompatibilityParams = viewerCompatibilityParams; /***/ }), /* 5 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((module) => { -"use strict"; let pdfjsLib; @@ -4033,18 +3912,19 @@ module.exports = pdfjsLib; /***/ }), /* 6 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFCursorTools = exports.CursorTool = void 0; var _grab_to_pan = __webpack_require__(7); +var _ui_utils = __webpack_require__(4); + const CursorTool = { SELECT: 0, HAND: 1, @@ -4133,20 +4013,22 @@ class PDFCursorTools { }); this.eventBus._on("presentationmodechanged", evt => { - if (evt.switchInProgress) { - return; - } - - let previouslyActive; + switch (evt.state) { + case _ui_utils.PresentationModeState.FULLSCREEN: + { + const previouslyActive = this.active; + this.switchTool(CursorTool.SELECT); + this.activeBeforePresentationMode = previouslyActive; + break; + } - if (evt.active) { - previouslyActive = this.active; - this.switchTool(CursorTool.SELECT); - this.activeBeforePresentationMode = previouslyActive; - } else { - previouslyActive = this.activeBeforePresentationMode; - this.activeBeforePresentationMode = null; - this.switchTool(previouslyActive); + case _ui_utils.PresentationModeState.NORMAL: + { + const previouslyActive = this.activeBeforePresentationMode; + this.activeBeforePresentationMode = null; + this.switchTool(previouslyActive); + break; + } } }); } @@ -4157,14 +4039,13 @@ exports.PDFCursorTools = PDFCursorTools; /***/ }), /* 7 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.GrabToPan = GrabToPan; function GrabToPan(options) { @@ -4221,7 +4102,7 @@ GrabToPan.prototype = { } }, ignoreTarget: function GrabToPan_ignoreTarget(node) { - return node[matchesSelector]("a[href], a[href] *, input, textarea, button, button *, select, option"); + return node.matches("a[href], a[href] *, input, textarea, button, button *, select, option"); }, _onmousedown: function GrabToPan__onmousedown(event) { if (event.button !== 0 || this.ignoreTarget(event.target)) { @@ -4287,32 +4168,16 @@ GrabToPan.prototype = { this.overlay.remove(); } }; -let matchesSelector; -["webkitM", "mozM", "msM", "oM", "m"].some(function (prefix) { - let name = prefix + "atches"; - - if (name in document.documentElement) { - matchesSelector = name; - } - - name += "Selector"; - - if (name in document.documentElement) { - matchesSelector = name; - } - - return matchesSelector; -}); -const isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9; -const chrome = window.chrome; -const isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app); -const isSafari6plus = /Apple/.test(navigator.vendor) && /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent); function isLeftMouseReleased(event) { - if ("buttons" in event && isNotIEorIsIE10plus) { + if ("buttons" in event) { return !(event.buttons & 1); } + const chrome = window.chrome; + const isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app); + const isSafari6plus = /Apple/.test(navigator.vendor) && /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent); + if (isChrome15OrOpera15plus || isSafari6plus) { return event.which === 0; } @@ -4322,15 +4187,17 @@ function isLeftMouseReleased(event) { /***/ }), /* 8 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.PDFRenderingQueue = exports.RenderingStates = void 0; +})); +exports.RenderingStates = exports.PDFRenderingQueue = void 0; + +var _pdfjsLib = __webpack_require__(5); + const CLEANUP_TIMEOUT = 30000; const RenderingStates = { INITIAL: 0, @@ -4444,6 +4311,10 @@ class PDFRenderingQueue { view.draw().finally(() => { this.renderHighestPriority(); }).catch(reason => { + if (reason instanceof _pdfjsLib.RenderingCancelledException) { + return; + } + console.error(`renderView: "${reason}"`); }); break; @@ -4458,417 +4329,13 @@ exports.PDFRenderingQueue = PDFRenderingQueue; /***/ }), /* 9 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.PDFSidebar = exports.SidebarView = void 0; - -var _ui_utils = __webpack_require__(2); - -var _pdf_rendering_queue = __webpack_require__(8); - -const UI_NOTIFICATION_CLASS = "pdfSidebarNotification"; -const SidebarView = { - UNKNOWN: -1, - NONE: 0, - THUMBS: 1, - OUTLINE: 2, - ATTACHMENTS: 3, - LAYERS: 4 -}; -exports.SidebarView = SidebarView; - -class PDFSidebar { - constructor({ - elements, - pdfViewer, - pdfThumbnailViewer, - eventBus, - l10n = _ui_utils.NullL10n, - disableNotification = false - }) { - this.isOpen = false; - this.active = SidebarView.THUMBS; - this.isInitialViewSet = false; - this.onToggled = null; - this.pdfViewer = pdfViewer; - this.pdfThumbnailViewer = pdfThumbnailViewer; - this.outerContainer = elements.outerContainer; - this.viewerContainer = elements.viewerContainer; - this.toggleButton = elements.toggleButton; - this.thumbnailButton = elements.thumbnailButton; - this.outlineButton = elements.outlineButton; - this.attachmentsButton = elements.attachmentsButton; - this.layersButton = elements.layersButton; - this.thumbnailView = elements.thumbnailView; - this.outlineView = elements.outlineView; - this.attachmentsView = elements.attachmentsView; - this.layersView = elements.layersView; - this.eventBus = eventBus; - this.l10n = l10n; - this._disableNotification = disableNotification; - - this._addEventListeners(); - } - - reset() { - this.isInitialViewSet = false; - - this._hideUINotification(null); - - this.switchView(SidebarView.THUMBS); - this.outlineButton.disabled = false; - this.attachmentsButton.disabled = false; - this.layersButton.disabled = false; - } - - get visibleView() { - return this.isOpen ? this.active : SidebarView.NONE; - } - - get isThumbnailViewVisible() { - return this.isOpen && this.active === SidebarView.THUMBS; - } - - get isOutlineViewVisible() { - return this.isOpen && this.active === SidebarView.OUTLINE; - } - - get isAttachmentsViewVisible() { - return this.isOpen && this.active === SidebarView.ATTACHMENTS; - } - - get isLayersViewVisible() { - return this.isOpen && this.active === SidebarView.LAYERS; - } - - setInitialView(view = SidebarView.NONE) { - if (this.isInitialViewSet) { - return; - } - - this.isInitialViewSet = true; - - if (view === SidebarView.NONE || view === SidebarView.UNKNOWN) { - this._dispatchEvent(); - - return; - } - - if (!this._switchView(view, true)) { - this._dispatchEvent(); - } - } - - switchView(view, forceOpen = false) { - this._switchView(view, forceOpen); - } - - _switchView(view, forceOpen = false) { - const isViewChanged = view !== this.active; - let shouldForceRendering = false; - - switch (view) { - case SidebarView.NONE: - if (this.isOpen) { - this.close(); - return true; - } - - return false; - - case SidebarView.THUMBS: - if (this.isOpen && isViewChanged) { - shouldForceRendering = true; - } - - break; - - case SidebarView.OUTLINE: - if (this.outlineButton.disabled) { - return false; - } - - break; - - case SidebarView.ATTACHMENTS: - if (this.attachmentsButton.disabled) { - return false; - } - - break; - - case SidebarView.LAYERS: - if (this.layersButton.disabled) { - return false; - } - - break; - - default: - console.error(`PDFSidebar._switchView: "${view}" is not a valid view.`); - return false; - } - - this.active = view; - this.thumbnailButton.classList.toggle("toggled", view === SidebarView.THUMBS); - this.outlineButton.classList.toggle("toggled", view === SidebarView.OUTLINE); - this.attachmentsButton.classList.toggle("toggled", view === SidebarView.ATTACHMENTS); - this.layersButton.classList.toggle("toggled", view === SidebarView.LAYERS); - this.thumbnailView.classList.toggle("hidden", view !== SidebarView.THUMBS); - this.outlineView.classList.toggle("hidden", view !== SidebarView.OUTLINE); - this.attachmentsView.classList.toggle("hidden", view !== SidebarView.ATTACHMENTS); - this.layersView.classList.toggle("hidden", view !== SidebarView.LAYERS); - - if (forceOpen && !this.isOpen) { - this.open(); - return true; - } - - if (shouldForceRendering) { - this._updateThumbnailViewer(); - - this._forceRendering(); - } - - if (isViewChanged) { - this._dispatchEvent(); - } - - this._hideUINotification(this.active); - - return isViewChanged; - } - - open() { - if (this.isOpen) { - return; - } - - this.isOpen = true; - this.toggleButton.classList.add("toggled"); - this.outerContainer.classList.add("sidebarMoving", "sidebarOpen"); - - if (this.active === SidebarView.THUMBS) { - this._updateThumbnailViewer(); - } - - this._forceRendering(); - - this._dispatchEvent(); - - this._hideUINotification(this.active); - } - - close() { - if (!this.isOpen) { - return; - } - - this.isOpen = false; - this.toggleButton.classList.remove("toggled"); - this.outerContainer.classList.add("sidebarMoving"); - this.outerContainer.classList.remove("sidebarOpen"); - - this._forceRendering(); - - this._dispatchEvent(); - } - - toggle() { - if (this.isOpen) { - this.close(); - } else { - this.open(); - } - } - - _dispatchEvent() { - this.eventBus.dispatch("sidebarviewchanged", { - source: this, - view: this.visibleView - }); - } - - _forceRendering() { - if (this.onToggled) { - this.onToggled(); - } else { - this.pdfViewer.forceRendering(); - this.pdfThumbnailViewer.forceRendering(); - } - } - - _updateThumbnailViewer() { - const { - pdfViewer, - pdfThumbnailViewer - } = this; - const pagesCount = pdfViewer.pagesCount; - - for (let pageIndex = 0; pageIndex < pagesCount; pageIndex++) { - const pageView = pdfViewer.getPageView(pageIndex); - - if (pageView && pageView.renderingState === _pdf_rendering_queue.RenderingStates.FINISHED) { - const thumbnailView = pdfThumbnailViewer.getThumbnail(pageIndex); - thumbnailView.setImage(pageView); - } - } - - pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber); - } - - _showUINotification(view) { - if (this._disableNotification) { - return; - } - - this.l10n.get("toggle_sidebar_notification2.title", null, "Toggle Sidebar (document contains outline/attachments/layers)").then(msg => { - this.toggleButton.title = msg; - }); - - if (!this.isOpen) { - this.toggleButton.classList.add(UI_NOTIFICATION_CLASS); - } else if (view === this.active) { - return; - } - - switch (view) { - case SidebarView.OUTLINE: - this.outlineButton.classList.add(UI_NOTIFICATION_CLASS); - break; - - case SidebarView.ATTACHMENTS: - this.attachmentsButton.classList.add(UI_NOTIFICATION_CLASS); - break; - - case SidebarView.LAYERS: - this.layersButton.classList.add(UI_NOTIFICATION_CLASS); - break; - } - } - - _hideUINotification(view) { - if (this._disableNotification) { - return; - } - - const removeNotification = sidebarView => { - switch (sidebarView) { - case SidebarView.OUTLINE: - this.outlineButton.classList.remove(UI_NOTIFICATION_CLASS); - break; - - case SidebarView.ATTACHMENTS: - this.attachmentsButton.classList.remove(UI_NOTIFICATION_CLASS); - break; - - case SidebarView.LAYERS: - this.layersButton.classList.remove(UI_NOTIFICATION_CLASS); - break; - } - }; - - if (!this.isOpen && view !== null) { - return; - } - - this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS); - - if (view !== null) { - removeNotification(view); - return; - } - - for (view in SidebarView) { - removeNotification(SidebarView[view]); - } - - this.l10n.get("toggle_sidebar.title", null, "Toggle Sidebar").then(msg => { - this.toggleButton.title = msg; - }); - } - - _addEventListeners() { - this.viewerContainer.addEventListener("transitionend", evt => { - if (evt.target === this.viewerContainer) { - this.outerContainer.classList.remove("sidebarMoving"); - } - }); - this.toggleButton.addEventListener("click", () => { - this.toggle(); - }); - this.thumbnailButton.addEventListener("click", () => { - this.switchView(SidebarView.THUMBS); - }); - this.outlineButton.addEventListener("click", () => { - this.switchView(SidebarView.OUTLINE); - }); - this.outlineButton.addEventListener("dblclick", () => { - this.eventBus.dispatch("toggleoutlinetree", { - source: this - }); - }); - this.attachmentsButton.addEventListener("click", () => { - this.switchView(SidebarView.ATTACHMENTS); - }); - this.layersButton.addEventListener("click", () => { - this.switchView(SidebarView.LAYERS); - }); - this.layersButton.addEventListener("dblclick", () => { - this.eventBus.dispatch("resetlayers", { - source: this - }); - }); - - const onTreeLoaded = (count, button, view) => { - button.disabled = !count; - - if (count) { - this._showUINotification(view); - } else if (this.active === view) { - this.switchView(SidebarView.THUMBS); - } - }; - - this.eventBus._on("outlineloaded", evt => { - onTreeLoaded(evt.outlineCount, this.outlineButton, SidebarView.OUTLINE); - }); - - this.eventBus._on("attachmentsloaded", evt => { - onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, SidebarView.ATTACHMENTS); - }); - - this.eventBus._on("layersloaded", evt => { - onTreeLoaded(evt.layersCount, this.layersButton, SidebarView.LAYERS); - }); - - this.eventBus._on("presentationmodechanged", evt => { - if (!evt.active && !evt.switchInProgress && this.isThumbnailViewVisible) { - this._updateThumbnailViewer(); - } - }); - } - -} - -exports.PDFSidebar = PDFSidebar; - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); +})); exports.OverlayManager = void 0; class OverlayManager { @@ -4971,23 +4438,20 @@ class OverlayManager { exports.OverlayManager = OverlayManager; /***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { +/* 10 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PasswordPrompt = void 0; -var _ui_utils = __webpack_require__(2); - var _pdfjsLib = __webpack_require__(5); class PasswordPrompt { - constructor(options, overlayManager, l10n = _ui_utils.NullL10n) { + constructor(options, overlayManager, l10n, isViewerEmbedded = false) { this.overlayName = options.overlayName; this.container = options.container; this.label = options.label; @@ -4996,6 +4460,7 @@ class PasswordPrompt { this.cancelButton = options.cancelButton; this.overlayManager = overlayManager; this.l10n = l10n; + this._isViewerEmbedded = isViewerEmbedded; this.updateCallback = null; this.reason = null; this.submitButton.addEventListener("click", this.verify.bind(this)); @@ -5008,21 +4473,15 @@ class PasswordPrompt { this.overlayManager.register(this.overlayName, this.container, this.close.bind(this), true); } - open() { - this.overlayManager.open(this.overlayName).then(() => { - this.input.focus(); - let promptString; + async open() { + await this.overlayManager.open(this.overlayName); + const passwordIncorrect = this.reason === _pdfjsLib.PasswordResponses.INCORRECT_PASSWORD; - if (this.reason === _pdfjsLib.PasswordResponses.INCORRECT_PASSWORD) { - promptString = this.l10n.get("password_invalid", null, "Invalid password. Please try again."); - } else { - promptString = this.l10n.get("password_label", null, "Enter the password to open this PDF file."); - } + if (!this._isViewerEmbedded || passwordIncorrect) { + this.input.focus(); + } - promptString.then(msg => { - this.label.textContent = msg; - }); - }); + this.label.textContent = await this.l10n.get(`password_${passwordIncorrect ? "invalid" : "label"}`); } close() { @@ -5034,7 +4493,7 @@ class PasswordPrompt { verify() { const password = this.input.value; - if (password && password.length > 0) { + if (password?.length > 0) { this.close(); this.updateCallback(password); } @@ -5050,24 +4509,19 @@ class PasswordPrompt { exports.PasswordPrompt = PasswordPrompt; /***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { +/* 11 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFAttachmentViewer = void 0; var _pdfjsLib = __webpack_require__(5); -var _base_tree_viewer = __webpack_require__(13); - -var _viewer_compatibility = __webpack_require__(4); - -const PdfFileRegExp = /\.pdf$/i; +var _base_tree_viewer = __webpack_require__(12); class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer { constructor(options) { @@ -5117,42 +4571,12 @@ class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer { }); } - _bindPdfLink(element, { - content, - filename - }) { - let blobUrl; - - element.onclick = () => { - if (!blobUrl) { - blobUrl = URL.createObjectURL(new Blob([content], { - type: "application/pdf" - })); - } - - let viewerUrl; - viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename); - - try { - window.open(viewerUrl); - } catch (ex) { - console.error(`_bindPdfLink: ${ex}`); - URL.revokeObjectURL(blobUrl); - blobUrl = null; - this.downloadManager.downloadData(content, filename, "application/pdf"); - } - - return false; - }; - } - _bindLink(element, { content, filename }) { element.onclick = () => { - const contentType = PdfFileRegExp.test(filename) ? "application/pdf" : ""; - this.downloadManager.downloadData(content, filename, contentType); + this.downloadManager.openOrDownloadData(element, content, filename); return false; }; } @@ -5181,22 +4605,16 @@ class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer { for (const name of names) { const item = attachments[name]; - const filename = (0, _pdfjsLib.getFilenameFromUrl)(item.filename); + const content = item.content, + filename = (0, _pdfjsLib.getFilenameFromUrl)(item.filename); const div = document.createElement("div"); div.className = "treeItem"; const element = document.createElement("a"); - if (PdfFileRegExp.test(filename) && !_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) { - this._bindPdfLink(element, { - content: item.content, - filename - }); - } else { - this._bindLink(element, { - content: item.content, - filename - }); - } + this._bindLink(element, { + content, + filename + }); element.textContent = this._normalizeTextContent(filename); div.appendChild(element); @@ -5204,9 +4622,7 @@ class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer { attachmentsCount++; } - this.container.appendChild(fragment); - - this._dispatchEvent(attachmentsCount); + this._finishRendering(fragment, attachmentsCount); } _appendAttachment({ @@ -5248,19 +4664,21 @@ class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer { exports.PDFAttachmentViewer = PDFAttachmentViewer; /***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { +/* 12 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.BaseTreeViewer = void 0; var _pdfjsLib = __webpack_require__(5); +const TREEITEM_OFFSET_TOP = -100; +const TREEITEM_SELECTED_CLASS = "selected"; + class BaseTreeViewer { constructor(options) { if (this.constructor === BaseTreeViewer) { @@ -5273,7 +4691,9 @@ class BaseTreeViewer { } reset() { + this._pdfDocument = null; this._lastToggleIsShow = true; + this._currentTreeItem = null; this.container.textContent = ""; this.container.classList.remove("treeWithDeepNesting"); } @@ -5324,29 +4744,73 @@ class BaseTreeViewer { this._toggleTreeItem(this.container, !this._lastToggleIsShow); } + _finishRendering(fragment, count, hasAnyNesting = false) { + if (hasAnyNesting) { + this.container.classList.add("treeWithDeepNesting"); + this._lastToggleIsShow = !fragment.querySelector(".treeItemsHidden"); + } + + this.container.appendChild(fragment); + + this._dispatchEvent(count); + } + render(params) { throw new Error("Not implemented: render"); } + _updateCurrentTreeItem(treeItem = null) { + if (this._currentTreeItem) { + this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS); + + this._currentTreeItem = null; + } + + if (treeItem) { + treeItem.classList.add(TREEITEM_SELECTED_CLASS); + this._currentTreeItem = treeItem; + } + } + + _scrollToCurrentTreeItem(treeItem) { + if (!treeItem) { + return; + } + + let currentNode = treeItem.parentNode; + + while (currentNode && currentNode !== this.container) { + if (currentNode.classList.contains("treeItem")) { + const toggler = currentNode.firstElementChild; + toggler?.classList.remove("treeItemsHidden"); + } + + currentNode = currentNode.parentNode; + } + + this._updateCurrentTreeItem(treeItem); + + this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP); + } + } exports.BaseTreeViewer = BaseTreeViewer; /***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { +/* 13 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFDocumentProperties = void 0; var _pdfjsLib = __webpack_require__(5); -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); const DEFAULT_FIELD_CONTENT = "-"; const NON_METRIC_LOCALES = ["en-us", "en-lr", "my"]; @@ -5371,7 +4835,7 @@ class PDFDocumentProperties { fields, container, closeButton - }, overlayManager, eventBus, l10n = _ui_utils.NullL10n) { + }, overlayManager, eventBus, l10n) { this.overlayName = overlayName; this.fields = fields; this.container = container; @@ -5397,7 +4861,7 @@ class PDFDocumentProperties { }); } - open() { + async open() { const freezeFieldData = data => { Object.defineProperty(this, "fieldData", { value: Object.freeze(data), @@ -5407,64 +4871,58 @@ class PDFDocumentProperties { }); }; - Promise.all([this.overlayManager.open(this.overlayName), this._dataAvailableCapability.promise]).then(() => { - const currentPageNumber = this._currentPageNumber; - const pagesRotation = this._pagesRotation; + await Promise.all([this.overlayManager.open(this.overlayName), this._dataAvailableCapability.promise]); + const currentPageNumber = this._currentPageNumber; + const pagesRotation = this._pagesRotation; - if (this.fieldData && currentPageNumber === this.fieldData._currentPageNumber && pagesRotation === this.fieldData._pagesRotation) { - this._updateUI(); + if (this.fieldData && currentPageNumber === this.fieldData._currentPageNumber && pagesRotation === this.fieldData._pagesRotation) { + this._updateUI(); - return; - } + return; + } - this.pdfDocument.getMetadata().then(({ - info, - metadata, - contentDispositionFilename - }) => { - return Promise.all([info, metadata, contentDispositionFilename || (0, _ui_utils.getPDFFileNameFromURL)(this.url), this._parseFileSize(this.maybeFileSize), this._parseDate(info.CreationDate), this._parseDate(info.ModDate), this.pdfDocument.getPage(currentPageNumber).then(pdfPage => { - return this._parsePageSize((0, _ui_utils.getPageSizeInches)(pdfPage), pagesRotation); - }), this._parseLinearization(info.IsLinearized)]); - }).then(([info, metadata, fileName, fileSize, creationDate, modDate, pageSize, isLinearized]) => { - freezeFieldData({ - fileName, - fileSize, - title: info.Title, - author: info.Author, - subject: info.Subject, - keywords: info.Keywords, - creationDate, - modificationDate: modDate, - creator: info.Creator, - producer: info.Producer, - version: info.PDFFormatVersion, - pageCount: this.pdfDocument.numPages, - pageSize, - linearized: isLinearized, - _currentPageNumber: currentPageNumber, - _pagesRotation: pagesRotation - }); + const { + info, + contentDispositionFilename, + contentLength + } = await this.pdfDocument.getMetadata(); + const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(this.url), this._parseFileSize(contentLength), this._parseDate(info.CreationDate), this._parseDate(info.ModDate), this.pdfDocument.getPage(currentPageNumber).then(pdfPage => { + return this._parsePageSize((0, _ui_utils.getPageSizeInches)(pdfPage), pagesRotation); + }), this._parseLinearization(info.IsLinearized)]); + freezeFieldData({ + fileName, + fileSize, + title: info.Title, + author: info.Author, + subject: info.Subject, + keywords: info.Keywords, + creationDate, + modificationDate, + creator: info.Creator, + producer: info.Producer, + version: info.PDFFormatVersion, + pageCount: this.pdfDocument.numPages, + pageSize, + linearized: isLinearized, + _currentPageNumber: currentPageNumber, + _pagesRotation: pagesRotation + }); + + this._updateUI(); - this._updateUI(); + const { + length + } = await this.pdfDocument.getDownloadInfo(); - return this.pdfDocument.getDownloadInfo(); - }).then(({ - length - }) => { - this.maybeFileSize = length; - return this._parseFileSize(length); - }).then(fileSize => { - if (fileSize === this.fieldData.fileSize) { - return; - } + if (contentLength === length) { + return; + } - const data = Object.assign(Object.create(null), this.fieldData); - data.fileSize = fileSize; - freezeFieldData(data); + const data = Object.assign(Object.create(null), this.fieldData); + data.fileSize = await this._parseFileSize(length); + freezeFieldData(data); - this._updateUI(); - }); - }); + this._updateUI(); } close() { @@ -5488,16 +4946,9 @@ class PDFDocumentProperties { this._dataAvailableCapability.resolve(); } - setFileSize(fileSize) { - if (Number.isInteger(fileSize) && fileSize > 0) { - this.maybeFileSize = fileSize; - } - } - _reset() { this.pdfDocument = null; this.url = null; - this.maybeFileSize = 0; delete this.fieldData; this._dataAvailableCapability = (0, _pdfjsLib.createPromiseCapability)(); this._currentPageNumber = 1; @@ -5524,21 +4975,18 @@ class PDFDocumentProperties { } async _parseFileSize(fileSize = 0) { - const kb = fileSize / 1024; + const kb = fileSize / 1024, + mb = kb / 1024; if (!kb) { return undefined; - } else if (kb < 1024) { - return this.l10n.get("document_properties_kb", { - size_kb: (+kb.toPrecision(3)).toLocaleString(), - size_b: fileSize.toLocaleString() - }, "{{size_kb}} KB ({{size_b}} bytes)"); } - return this.l10n.get("document_properties_mb", { - size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(), + return this.l10n.get(`document_properties_${mb >= 1 ? "mb" : "kb"}`, { + size_mb: mb >= 1 && (+mb.toPrecision(3)).toLocaleString(), + size_kb: mb < 1 && (+kb.toPrecision(3)).toLocaleString(), size_b: fileSize.toLocaleString() - }, "{{size_mb}} MB ({{size_b}} bytes)"); + }); } async _parsePageSize(pageSizeInches, pagesRotation) { @@ -5562,7 +5010,6 @@ class PDFDocumentProperties { width: Math.round(pageSizeInches.width * 25.4 * 10) / 10, height: Math.round(pageSizeInches.height * 25.4 * 10) / 10 }; - let pageName = null; let rawName = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES); if (!rawName && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) { @@ -5588,21 +5035,16 @@ class PDFDocumentProperties { } } - if (rawName) { - pageName = this.l10n.get("document_properties_page_size_name_" + rawName.toLowerCase(), null, rawName); - } - - return Promise.all([this._isNonMetricLocale ? sizeInches : sizeMillimeters, this.l10n.get("document_properties_page_size_unit_" + (this._isNonMetricLocale ? "inches" : "millimeters"), null, this._isNonMetricLocale ? "in" : "mm"), pageName, this.l10n.get("document_properties_page_size_orientation_" + (isPortrait ? "portrait" : "landscape"), null, isPortrait ? "portrait" : "landscape")]).then(([{ + const [{ width, height - }, unit, name, orientation]) => { - return this.l10n.get("document_properties_page_size_dimension_" + (name ? "name_" : "") + "string", { - width: width.toLocaleString(), - height: height.toLocaleString(), - unit, - name, - orientation - }, "{{width}} × {{height}} {{unit}} (" + (name ? "{{name}}, " : "") + "{{orientation}})"); + }, unit, name, orientation] = await Promise.all([this._isNonMetricLocale ? sizeInches : sizeMillimeters, this.l10n.get(`document_properties_page_size_unit_${this._isNonMetricLocale ? "inches" : "millimeters"}`), rawName && this.l10n.get(`document_properties_page_size_name_${rawName.toLowerCase()}`), this.l10n.get(`document_properties_page_size_orientation_${isPortrait ? "portrait" : "landscape"}`)]); + return this.l10n.get(`document_properties_page_size_dimension_${name ? "name_" : ""}string`, { + width: width.toLocaleString(), + height: height.toLocaleString(), + unit, + name, + orientation }); } @@ -5616,11 +5058,11 @@ class PDFDocumentProperties { return this.l10n.get("document_properties_date_string", { date: dateObject.toLocaleDateString(), time: dateObject.toLocaleTimeString() - }, "{{date}}, {{time}}"); + }); } _parseLinearization(isLinearized) { - return this.l10n.get("document_properties_linearized_" + (isLinearized ? "yes" : "no"), null, isLinearized ? "Yes" : "No"); + return this.l10n.get(`document_properties_linearized_${isLinearized ? "yes" : "no"}`); } } @@ -5628,36 +5070,33 @@ class PDFDocumentProperties { exports.PDFDocumentProperties = PDFDocumentProperties; /***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { +/* 14 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFFindBar = void 0; -var _pdf_find_controller = __webpack_require__(16); - -var _ui_utils = __webpack_require__(2); +var _pdf_find_controller = __webpack_require__(15); const MATCHES_COUNT_LIMIT = 1000; class PDFFindBar { - constructor(options, eventBus, l10n = _ui_utils.NullL10n) { + constructor(options, eventBus, l10n) { this.opened = false; - this.bar = options.bar || null; - this.toggleButton = options.toggleButton || null; - this.findField = options.findField || null; - this.highlightAll = options.highlightAllCheckbox || null; - this.caseSensitive = options.caseSensitiveCheckbox || null; - this.entireWord = options.entireWordCheckbox || null; - this.findMsg = options.findMsg || null; - this.findResultsCount = options.findResultsCount || null; - this.findPreviousButton = options.findPreviousButton || null; - this.findNextButton = options.findNextButton || null; + this.bar = options.bar; + this.toggleButton = options.toggleButton; + this.findField = options.findField; + this.highlightAll = options.highlightAllCheckbox; + this.caseSensitive = options.caseSensitiveCheckbox; + this.entireWord = options.entireWordCheckbox; + this.findMsg = options.findMsg; + this.findResultsCount = options.findResultsCount; + this.findPreviousButton = options.findPreviousButton; + this.findNextButton = options.findNextButton; this.eventBus = eventBus; this.l10n = l10n; this.toggleButton.addEventListener("click", () => { @@ -5717,8 +5156,7 @@ class PDFFindBar { } updateUIState(state, previous, matchesCount) { - let notFound = false; - let findMsg = ""; + let findMsg = Promise.resolve(""); let status = ""; switch (state) { @@ -5730,23 +5168,17 @@ class PDFFindBar { break; case _pdf_find_controller.FindState.NOT_FOUND: - findMsg = this.l10n.get("find_not_found", null, "Phrase not found"); - notFound = true; + findMsg = this.l10n.get("find_not_found"); + status = "notFound"; break; case _pdf_find_controller.FindState.WRAPPED: - if (previous) { - findMsg = this.l10n.get("find_reached_top", null, "Reached top of document, continued from bottom"); - } else { - findMsg = this.l10n.get("find_reached_bottom", null, "Reached end of document, continued from top"); - } - + findMsg = this.l10n.get(`find_reached_${previous ? "top" : "bottom"}`); break; } - this.findField.classList.toggle("notFound", notFound); this.findField.setAttribute("data-status", status); - Promise.resolve(findMsg).then(msg => { + findMsg.then(msg => { this.findMsg.textContent = msg; this._adjustWidth(); @@ -5758,27 +5190,25 @@ class PDFFindBar { current = 0, total = 0 } = {}) { - if (!this.findResultsCount) { - return; - } - const limit = MATCHES_COUNT_LIMIT; - let matchesCountMsg = ""; + let matchCountMsg = Promise.resolve(""); if (total > 0) { if (total > limit) { - matchesCountMsg = this.l10n.get("find_match_count_limit", { + let key = "find_match_count_limit"; + matchCountMsg = this.l10n.get(key, { limit - }, "More than {{limit}} match" + (limit !== 1 ? "es" : "")); + }); } else { - matchesCountMsg = this.l10n.get("find_match_count", { + let key = "find_match_count"; + matchCountMsg = this.l10n.get(key, { current, total - }, "{{current}} of {{total}} match" + (total !== 1 ? "es" : "")); + }); } } - Promise.resolve(matchesCountMsg).then(msg => { + matchCountMsg.then(msg => { this.findResultsCount.textContent = msg; this.findResultsCount.classList.toggle("hidden", !total); @@ -5790,6 +5220,7 @@ class PDFFindBar { if (!this.opened) { this.opened = true; this.toggleButton.classList.add("toggled"); + this.toggleButton.setAttribute("aria-expanded", "true"); this.bar.classList.remove("hidden"); } @@ -5806,6 +5237,7 @@ class PDFFindBar { this.opened = false; this.toggleButton.classList.remove("toggled"); + this.toggleButton.setAttribute("aria-expanded", "false"); this.bar.classList.add("hidden"); this.eventBus.dispatch("findbarclose", { source: this @@ -5839,22 +5271,21 @@ class PDFFindBar { exports.PDFFindBar = PDFFindBar; /***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { +/* 15 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFFindController = exports.FindState = void 0; var _pdfjsLib = __webpack_require__(5); -var _pdf_find_utils = __webpack_require__(17); +var _pdf_find_utils = __webpack_require__(16); -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); const FindState = { FOUND: 0, @@ -5867,6 +5298,7 @@ const FIND_TIMEOUT = 250; const MATCH_SCROLL_OFFSET_TOP = -50; const MATCH_SCROLL_OFFSET_LEFT = -400; const CHARACTERS_TO_NORMALIZE = { + "\u2010": "-", "\u2018": "'", "\u2019": "'", "\u201A": "'", @@ -5887,9 +5319,43 @@ function normalize(text) { normalizationRegex = new RegExp(`[${replace}]`, "g"); } - return text.replace(normalizationRegex, function (ch) { - return CHARACTERS_TO_NORMALIZE[ch]; + let diffs = null; + const normalizedText = text.replace(normalizationRegex, function (ch, index) { + const normalizedCh = CHARACTERS_TO_NORMALIZE[ch], + diff = normalizedCh.length - ch.length; + + if (diff !== 0) { + (diffs || (diffs = [])).push([index, diff]); + } + + return normalizedCh; }); + return [normalizedText, diffs]; +} + +function getOriginalIndex(matchIndex, diffs = null) { + if (!diffs) { + return matchIndex; + } + + let totalDiff = 0; + + for (const [index, diff] of diffs) { + const currentIndex = index + totalDiff; + + if (currentIndex >= matchIndex) { + break; + } + + if (currentIndex + diff > matchIndex) { + totalDiff += matchIndex - currentIndex; + break; + } + + totalDiff += diff; + } + + return matchIndex - totalDiff; } class PDFFindController { @@ -6001,6 +5467,7 @@ class PDFFindController { scrollMatchIntoView({ element = null, + selectedLeft = 0, pageIndex = -1, matchIndex = -1 }) { @@ -6015,7 +5482,7 @@ class PDFFindController { this._scrollMatches = false; const spot = { top: MATCH_SCROLL_OFFSET_TOP, - left: MATCH_SCROLL_OFFSET_LEFT + left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT }; (0, _ui_utils.scrollIntoView)(element, spot, true); } @@ -6038,9 +5505,10 @@ class PDFFindController { }; this._extractTextPromises = []; this._pageContents = []; + this._pageDiffs = []; this._matchesCountTotal = 0; this._pagesToSearch = null; - this._pendingFindMatches = Object.create(null); + this._pendingFindMatches = new Set(); this._resumePageIdx = null; this._dirtyMatch = false; clearTimeout(this._findTimeout); @@ -6051,7 +5519,7 @@ class PDFFindController { get _query() { if (this._state.query !== this._rawQuery) { this._rawQuery = this._state.query; - this._normalizedQuery = normalize(this._state.query); + [this._normalizedQuery] = normalize(this._state.query); } return this._normalizedQuery; @@ -6148,8 +5616,9 @@ class PDFFindController { return true; } - _calculatePhraseMatch(query, pageIndex, pageContent, entireWord) { - const matches = []; + _calculatePhraseMatch(query, pageIndex, pageContent, pageDiffs, entireWord) { + const matches = [], + matchesLength = []; const queryLen = query.length; let matchIdx = -queryLen; @@ -6164,13 +5633,18 @@ class PDFFindController { continue; } - matches.push(matchIdx); + const originalMatchIdx = getOriginalIndex(matchIdx, pageDiffs), + matchEnd = matchIdx + queryLen - 1, + originalQueryLen = getOriginalIndex(matchEnd, pageDiffs) - originalMatchIdx + 1; + matches.push(originalMatchIdx); + matchesLength.push(originalQueryLen); } this._pageMatches[pageIndex] = matches; + this._pageMatchesLength[pageIndex] = matchesLength; } - _calculateWordMatch(query, pageIndex, pageContent, entireWord) { + _calculateWordMatch(query, pageIndex, pageContent, pageDiffs, entireWord) { const matchesWithLength = []; const queryArray = query.match(/\S+/g); @@ -6190,9 +5664,12 @@ class PDFFindController { continue; } + const originalMatchIdx = getOriginalIndex(matchIdx, pageDiffs), + matchEnd = matchIdx + subqueryLen - 1, + originalQueryLen = getOriginalIndex(matchEnd, pageDiffs) - originalMatchIdx + 1; matchesWithLength.push({ - match: matchIdx, - matchLength: subqueryLen, + match: originalMatchIdx, + matchLength: originalQueryLen, skipped: false }); } @@ -6206,6 +5683,7 @@ class PDFFindController { _calculateMatch(pageIndex) { let pageContent = this._pageContents[pageIndex]; + const pageDiffs = this._pageDiffs[pageIndex]; let query = this._query; const { caseSensitive, @@ -6223,9 +5701,9 @@ class PDFFindController { } if (phraseSearch) { - this._calculatePhraseMatch(query, pageIndex, pageContent, entireWord); + this._calculatePhraseMatch(query, pageIndex, pageContent, pageDiffs, entireWord); } else { - this._calculateWordMatch(query, pageIndex, pageContent, entireWord); + this._calculateWordMatch(query, pageIndex, pageContent, pageDiffs, entireWord); } if (this._state.highlightAll) { @@ -6270,11 +5748,12 @@ class PDFFindController { strBuf.push(textItems[j].str); } - this._pageContents[i] = normalize(strBuf.join("")); + [this._pageContents[i], this._pageDiffs[i]] = normalize(strBuf.join("")); extractTextCapability.resolve(i); }, reason => { console.error(`Unable to get text content for page ${i + 1}`, reason); this._pageContents[i] = ""; + this._pageDiffs[i] = null; extractTextCapability.resolve(i); }); }); @@ -6319,14 +5798,14 @@ class PDFFindController { this._updateAllPages(); for (let i = 0; i < numPages; i++) { - if (this._pendingFindMatches[i] === true) { + if (this._pendingFindMatches.has(i)) { continue; } - this._pendingFindMatches[i] = true; + this._pendingFindMatches.add(i); this._extractTextPromises[i].then(pageIdx => { - delete this._pendingFindMatches[pageIdx]; + this._pendingFindMatches.delete(pageIdx); this._calculateMatch(pageIdx); }); @@ -6483,7 +5962,7 @@ class PDFFindController { if (matchIdx !== -1) { for (let i = 0; i < pageIdx; i++) { - current += this._pageMatches[i] && this._pageMatches[i].length || 0; + current += this._pageMatches[i]?.length || 0; } current += matchIdx + 1; @@ -6512,7 +5991,7 @@ class PDFFindController { state, previous, matchesCount: this._requestMatchesCount(), - rawQuery: this._state ? this._state.query : null + rawQuery: this._state?.query ?? null }); } @@ -6521,15 +6000,14 @@ class PDFFindController { exports.PDFFindController = PDFFindController; /***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { +/* 16 */ +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.getCharacterType = getCharacterType; exports.CharacterType = void 0; const CharacterType = { @@ -6617,20 +6095,19 @@ function getCharacterType(charCode) { } /***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { +/* 17 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.isDestHashesEqual = isDestHashesEqual; +})); exports.isDestArraysEqual = isDestArraysEqual; +exports.isDestHashesEqual = isDestHashesEqual; exports.PDFHistory = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); const HASH_CHANGE_TIMEOUT = 1000; const POSITION_UPDATED_THRESHOLD = 50; @@ -6654,19 +6131,17 @@ class PDFHistory { this._isViewerInPresentationMode = false; this.eventBus._on("presentationmodechanged", evt => { - this._isViewerInPresentationMode = evt.active || evt.switchInProgress; + this._isViewerInPresentationMode = evt.state !== _ui_utils.PresentationModeState.NORMAL; }); this.eventBus._on("pagesinit", () => { this._isPagesLoaded = false; - const onPagesLoaded = evt => { - this.eventBus._off("pagesloaded", onPagesLoaded); - + this.eventBus._on("pagesloaded", evt => { this._isPagesLoaded = !!evt.pagesCount; - }; - - this.eventBus._on("pagesloaded", onPagesLoaded); + }, { + once: true + }); }); } @@ -6726,10 +6201,6 @@ class PDFHistory { this._updateInternalState(destination, state.uid, true); - if (this._uid > this._maxUid) { - this._maxUid = this._uid; - } - if (destination.rotation !== undefined) { this._initialRotation = destination.rotation; } @@ -6777,7 +6248,7 @@ class PDFHistory { } else if (!Array.isArray(explicitDest)) { console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); return; - } else if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.linkService.pagesCount)) { + } else if (!this._isValidPage(pageNumber)) { if (pageNumber !== null || this._destination) { console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); return; @@ -6819,6 +6290,39 @@ class PDFHistory { } } + pushPage(pageNumber) { + if (!this._initialized) { + return; + } + + if (!this._isValidPage(pageNumber)) { + console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); + return; + } + + if (this._destination?.page === pageNumber) { + return; + } + + if (this._popStateInProgress) { + return; + } + + this._pushOrReplaceState({ + dest: null, + hash: `page=${pageNumber}`, + page: pageNumber, + rotation: this.linkService.rotation + }); + + if (!this._popStateInProgress) { + this._popStateInProgress = true; + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); + } + } + pushCurrentPosition() { if (!this._initialized || this._popStateInProgress) { return; @@ -6875,7 +6379,7 @@ class PDFHistory { let newUrl; - if (this._updateUrl && destination && destination.hash) { + if (this._updateUrl && destination?.hash) { const baseUrl = document.location.href.split("#")[0]; if (!baseUrl.startsWith("file://")) { @@ -6888,7 +6392,6 @@ class PDFHistory { if (shouldReplace) { window.history.replaceState(newState, "", newUrl); } else { - this._maxUid = this._uid; window.history.pushState(newState, "", newUrl); } } @@ -6928,7 +6431,7 @@ class PDFHistory { let forceReplace = false; if (this._destination.page >= position.first && this._destination.page <= position.page) { - if (this._destination.dest || !this._destination.first) { + if (this._destination.dest !== undefined || !this._destination.first) { return; } @@ -6938,6 +6441,10 @@ class PDFHistory { this._pushOrReplaceState(position, forceReplace); } + _isValidPage(val) { + return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; + } + _isValidState(state, checkReload = false) { if (!state) { return false; @@ -6951,7 +6458,7 @@ class PDFHistory { const [perfEntry] = performance.getEntriesByType("navigation"); - if (!perfEntry || perfEntry.type !== "reload") { + if (perfEntry?.type !== "reload") { return false; } } else { @@ -6976,12 +6483,13 @@ class PDFHistory { this._updateViewareaTimeout = null; } - if (removeTemporary && destination && destination.temporary) { + if (removeTemporary && destination?.temporary) { delete destination.temporary; } this._destination = destination; this._uid = uid; + this._maxUid = Math.max(this._maxUid, uid); this._numPositionUpdates = 0; } @@ -6991,7 +6499,7 @@ class PDFHistory { const nameddest = params.nameddest || ""; let page = params.page | 0; - if (!(Number.isInteger(page) && page > 0 && page <= this.linkService.pagesCount) || checkNameddest && nameddest.length > 0) { + if (!this._isValidPage(page) || checkNameddest && nameddest.length > 0) { page = null; } @@ -7082,16 +6590,12 @@ class PDFHistory { this._updateInternalState(destination, state.uid, true); - if (this._uid > this._maxUid) { - this._maxUid = this._uid; - } - if ((0, _ui_utils.isValidRotation)(destination.rotation)) { this.linkService.rotation = destination.rotation; } if (destination.dest) { - this.linkService.navigateTo(destination.dest); + this.linkService.goToDestination(destination.dest); } else if (destination.hash) { this.linkService.setHash(destination.hash); } else if (destination.page) { @@ -7207,18 +6711,17 @@ function isDestArraysEqual(firstDest, secondDest) { } /***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { +/* 18 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFLayerViewer = void 0; -var _base_tree_viewer = __webpack_require__(13); +var _base_tree_viewer = __webpack_require__(12); class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { constructor(options) { @@ -7233,7 +6736,6 @@ class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { reset() { super.reset(); this._optionalContentConfig = null; - this._pdfDocument = null; } _dispatchEvent(layersCount) { @@ -7278,7 +6780,7 @@ class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { return; } - element.textContent = await this.l10n.get("additional_layers", null, "Additional Layers"); + element.textContent = await this.l10n.get("additional_layers"); element.style.fontStyle = "italic"; } @@ -7306,7 +6808,7 @@ class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { this._optionalContentConfig = optionalContentConfig || null; this._pdfDocument = pdfDocument || null; - const groups = optionalContentConfig && optionalContentConfig.getOrder(); + const groups = optionalContentConfig?.getOrder(); if (!groups) { this._dispatchEvent(0); @@ -7369,14 +6871,7 @@ class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { } } - if (hasAnyNesting) { - this.container.classList.add("treeWithDeepNesting"); - this._lastToggleIsShow = fragment.querySelectorAll(".treeItemsHidden").length === 0; - } - - this.container.appendChild(fragment); - - this._dispatchEvent(layersCount); + this._finishRendering(fragment, layersCount, hasAnyNesting); } async _resetLayers() { @@ -7400,31 +6895,29 @@ class PDFLayerViewer extends _base_tree_viewer.BaseTreeViewer { exports.PDFLayerViewer = PDFLayerViewer; /***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { +/* 19 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.SimpleLinkService = exports.PDFLinkService = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); class PDFLinkService { constructor({ eventBus, externalLinkTarget = null, externalLinkRel = null, - externalLinkEnabled = true, ignoreDestinationZoom = false } = {}) { this.eventBus = eventBus; this.externalLinkTarget = externalLinkTarget; this.externalLinkRel = externalLinkRel; - this.externalLinkEnabled = externalLinkEnabled; + this.externalLinkEnabled = true; this._ignoreDestinationZoom = ignoreDestinationZoom; this.baseUrl = null; this.pdfDocument = null; @@ -7467,90 +6960,107 @@ class PDFLinkService { this.pdfViewer.pagesRotation = value; } - navigateTo(dest) { - const goToDestination = ({ - namedDest, - explicitDest - }) => { - const destRef = explicitDest[0]; - let pageNumber; - - if (destRef instanceof Object) { - pageNumber = this._cachedPageNumber(destRef); - - if (pageNumber === null) { - this.pdfDocument.getPageIndex(destRef).then(pageIndex => { - this.cachePageRef(pageIndex + 1, destRef); - goToDestination({ - namedDest, - explicitDest - }); - }).catch(() => { - console.error(`PDFLinkService.navigateTo: "${destRef}" is not ` + `a valid page reference, for dest="${dest}".`); - }); - return; - } - } else if (Number.isInteger(destRef)) { - pageNumber = destRef + 1; - } else { - console.error(`PDFLinkService.navigateTo: "${destRef}" is not ` + `a valid destination reference, for dest="${dest}".`); - return; - } + _goToDestinationHelper(rawDest, namedDest = null, explicitDest) { + const destRef = explicitDest[0]; + let pageNumber; - if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`PDFLinkService.navigateTo: "${pageNumber}" is not ` + `a valid page number, for dest="${dest}".`); - return; - } + if (typeof destRef === "object" && destRef !== null) { + pageNumber = this._cachedPageNumber(destRef); - if (this.pdfHistory) { - this.pdfHistory.pushCurrentPosition(); - this.pdfHistory.push({ - namedDest, - explicitDest, - pageNumber - }); - } - - this.pdfViewer.scrollPageIntoView({ - pageNumber, - destArray: explicitDest, - ignoreDestinationZoom: this._ignoreDestinationZoom - }); - }; + if (pageNumber === null) { + this.pdfDocument.getPageIndex(destRef).then(pageIndex => { + this.cachePageRef(pageIndex + 1, destRef); - new Promise((resolve, reject) => { - if (typeof dest === "string") { - this.pdfDocument.getDestination(dest).then(destArray => { - resolve({ - namedDest: dest, - explicitDest: destArray - }); + this._goToDestinationHelper(rawDest, namedDest, explicitDest); + }).catch(() => { + console.error(`PDFLinkService._goToDestinationHelper: "${destRef}" is not ` + `a valid page reference, for dest="${rawDest}".`); }); return; } + } else if (Number.isInteger(destRef)) { + pageNumber = destRef + 1; + } else { + console.error(`PDFLinkService._goToDestinationHelper: "${destRef}" is not ` + `a valid destination reference, for dest="${rawDest}".`); + return; + } + + if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { + console.error(`PDFLinkService._goToDestinationHelper: "${pageNumber}" is not ` + `a valid page number, for dest="${rawDest}".`); + return; + } - resolve({ - namedDest: "", - explicitDest: dest + if (this.pdfHistory) { + this.pdfHistory.pushCurrentPosition(); + this.pdfHistory.push({ + namedDest, + explicitDest, + pageNumber }); - }).then(data => { - if (!Array.isArray(data.explicitDest)) { - console.error(`PDFLinkService.navigateTo: "${data.explicitDest}" is` + ` not a valid destination array, for dest="${dest}".`); - return; - } + } - goToDestination(data); + this.pdfViewer.scrollPageIntoView({ + pageNumber, + destArray: explicitDest, + ignoreDestinationZoom: this._ignoreDestinationZoom }); } - getDestinationHash(dest) { + async goToDestination(dest) { + if (!this.pdfDocument) { + return; + } + + let namedDest, explicitDest; + if (typeof dest === "string") { - return this.getAnchorUrl("#" + escape(dest)); + namedDest = dest; + explicitDest = await this.pdfDocument.getDestination(dest); + } else { + namedDest = null; + explicitDest = await dest; + } + + if (!Array.isArray(explicitDest)) { + console.error(`PDFLinkService.goToDestination: "${explicitDest}" is not ` + `a valid destination array, for dest="${dest}".`); + return; + } + + this._goToDestinationHelper(dest, namedDest, explicitDest); + } + + goToPage(val) { + if (!this.pdfDocument) { + return; + } + + const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; + + if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { + console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); + return; } - if (Array.isArray(dest)) { + if (this.pdfHistory) { + this.pdfHistory.pushCurrentPosition(); + this.pdfHistory.pushPage(pageNumber); + } + + this.pdfViewer.scrollPageIntoView({ + pageNumber + }); + } + + getDestinationHash(dest) { + if (typeof dest === "string") { + if (dest.length > 0) { + return this.getAnchorUrl("#" + escape(dest)); + } + } else if (Array.isArray(dest)) { const str = JSON.stringify(dest); - return this.getAnchorUrl("#" + escape(str)); + + if (str.length > 0) { + return this.getAnchorUrl("#" + escape(str)); + } } return this.getAnchorUrl(""); @@ -7561,6 +7071,10 @@ class PDFLinkService { } setHash(hash) { + if (!this.pdfDocument) { + return; + } + let pageNumber, dest; if (hash.includes("=")) { @@ -7628,7 +7142,7 @@ class PDFLinkService { } if ("nameddest" in params) { - this.navigateTo(params.nameddest); + this.goToDestination(params.nameddest); } } else { dest = unescape(hash); @@ -7642,7 +7156,7 @@ class PDFLinkService { } catch (ex) {} if (typeof dest === "string" || isValidExplicitDestination(dest)) { - this.navigateTo(dest); + this.goToDestination(dest); return; } @@ -7667,17 +7181,11 @@ class PDFLinkService { break; case "NextPage": - if (this.page < this.pagesCount) { - this.page++; - } - + this.pdfViewer.nextPage(); break; case "PrevPage": - if (this.page > 1) { - this.page--; - } - + this.pdfViewer.previousPage(); break; case "LastPage": @@ -7709,13 +7217,17 @@ class PDFLinkService { _cachedPageNumber(pageRef) { const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`; - return this._pagesRefCache && this._pagesRefCache[refStr] || null; + return this._pagesRefCache?.[refStr] || null; } isPageVisible(pageNumber) { return this.pdfViewer.isPageVisible(pageNumber); } + isPageCached(pageNumber) { + return this.pdfViewer.isPageCached(pageNumber); + } + } exports.PDFLinkService = PDFLinkService; @@ -7814,7 +7326,9 @@ class SimpleLinkService { set rotation(value) {} - navigateTo(dest) {} + async goToDestination(dest) {} + + goToPage(val) {} getDestinationHash(dest) { return "#"; @@ -7834,25 +7348,30 @@ class SimpleLinkService { return true; } + isPageCached(pageNumber) { + return true; + } + } exports.SimpleLinkService = SimpleLinkService; /***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { +/* 20 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFOutlineViewer = void 0; var _pdfjsLib = __webpack_require__(5); -var _base_tree_viewer = __webpack_require__(13); +var _base_tree_viewer = __webpack_require__(12); + +var _ui_utils = __webpack_require__(4); class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { constructor(options) { @@ -7860,17 +7379,53 @@ class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { this.linkService = options.linkService; this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this)); + + this.eventBus._on("currentoutlineitem", this._currentOutlineItem.bind(this)); + + this.eventBus._on("pagechanging", evt => { + this._currentPageNumber = evt.pageNumber; + }); + + this.eventBus._on("pagesloaded", evt => { + this._isPagesLoaded = !!evt.pagesCount; + + if (this._currentOutlineItemCapability && !this._currentOutlineItemCapability.settled) { + this._currentOutlineItemCapability.resolve(this._isPagesLoaded); + } + }); + + this.eventBus._on("sidebarviewchanged", evt => { + this._sidebarView = evt.view; + }); } reset() { super.reset(); this._outline = null; + this._pageNumberToDestHashCapability = null; + this._currentPageNumber = 1; + this._isPagesLoaded = false; + + if (this._currentOutlineItemCapability && !this._currentOutlineItemCapability.settled) { + this._currentOutlineItemCapability.resolve(false); + } + + this._currentOutlineItemCapability = null; } _dispatchEvent(outlineCount) { + this._currentOutlineItemCapability = (0, _pdfjsLib.createPromiseCapability)(); + + if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) { + this._currentOutlineItemCapability.resolve(false); + } else if (this._isPagesLoaded) { + this._currentOutlineItemCapability.resolve(true); + } + this.eventBus.dispatch("outlineloaded", { source: this, - outlineCount + outlineCount, + currentOutlineItemPromise: this._currentOutlineItemCapability.promise }); } @@ -7895,9 +7450,11 @@ class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { element.href = linkService.getDestinationHash(dest); - element.onclick = () => { + element.onclick = evt => { + this._updateCurrentTreeItem(evt.target.parentNode); + if (dest) { - linkService.navigateTo(dest); + linkService.goToDestination(dest); } return false; @@ -7921,7 +7478,31 @@ class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { count, items }) { - const hidden = count < 0 && Math.abs(count) === items.length; + let hidden = false; + + if (count < 0) { + let totalCount = items.length; + + if (totalCount > 0) { + const queue = [...items]; + + while (queue.length > 0) { + const { + count: nestedCount, + items: nestedItems + } = queue.shift(); + + if (nestedCount > 0 && nestedItems.length > 0) { + totalCount += nestedItems.length; + queue.push(...nestedItems); + } + } + } + + if (Math.abs(count) === totalCount) { + hidden = true; + } + } super._addToggleButton(div, hidden); } @@ -7935,13 +7516,15 @@ class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { } render({ - outline + outline, + pdfDocument }) { if (this._outline) { this.reset(); } this._outline = outline || null; + this._pdfDocument = pdfDocument || null; if (!outline) { this._dispatchEvent(0); @@ -7991,14 +7574,122 @@ class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { } } - if (hasAnyNesting) { - this.container.classList.add("treeWithDeepNesting"); - this._lastToggleIsShow = fragment.querySelectorAll(".treeItemsHidden").length === 0; + this._finishRendering(fragment, outlineCount, hasAnyNesting); + } + + async _currentOutlineItem() { + if (!this._isPagesLoaded) { + throw new Error("_currentOutlineItem: All pages have not been loaded."); } - this.container.appendChild(fragment); + if (!this._outline || !this._pdfDocument) { + return; + } + + const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument); + + if (!pageNumberToDestHash) { + return; + } + + this._updateCurrentTreeItem(null); + + if (this._sidebarView !== _ui_utils.SidebarView.OUTLINE) { + return; + } + + for (let i = this._currentPageNumber; i > 0; i--) { + const destHash = pageNumberToDestHash.get(i); - this._dispatchEvent(outlineCount); + if (!destHash) { + continue; + } + + const linkElement = this.container.querySelector(`a[href="${destHash}"]`); + + if (!linkElement) { + continue; + } + + this._scrollToCurrentTreeItem(linkElement.parentNode); + + break; + } + } + + async _getPageNumberToDestHash(pdfDocument) { + if (this._pageNumberToDestHashCapability) { + return this._pageNumberToDestHashCapability.promise; + } + + this._pageNumberToDestHashCapability = (0, _pdfjsLib.createPromiseCapability)(); + const pageNumberToDestHash = new Map(), + pageNumberNesting = new Map(); + const queue = [{ + nesting: 0, + items: this._outline + }]; + + while (queue.length > 0) { + const levelData = queue.shift(), + currentNesting = levelData.nesting; + + for (const { + dest, + items + } of levelData.items) { + let explicitDest, pageNumber; + + if (typeof dest === "string") { + explicitDest = await pdfDocument.getDestination(dest); + + if (pdfDocument !== this._pdfDocument) { + return null; + } + } else { + explicitDest = dest; + } + + if (Array.isArray(explicitDest)) { + const [destRef] = explicitDest; + + if (typeof destRef === "object" && destRef !== null) { + pageNumber = this.linkService._cachedPageNumber(destRef); + + if (!pageNumber) { + try { + pageNumber = (await pdfDocument.getPageIndex(destRef)) + 1; + + if (pdfDocument !== this._pdfDocument) { + return null; + } + + this.linkService.cachePageRef(pageNumber, destRef); + } catch (ex) {} + } + } else if (Number.isInteger(destRef)) { + pageNumber = destRef + 1; + } + + if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) { + const destHash = this.linkService.getDestinationHash(dest); + pageNumberToDestHash.set(pageNumber, destHash); + pageNumberNesting.set(pageNumber, currentNesting); + } + } + + if (items.length > 0) { + queue.push({ + nesting: currentNesting + 1, + items + }); + } + } + } + + this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null); + + return this._pageNumberToDestHashCapability.promise; } } @@ -8006,18 +7697,17 @@ class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer { exports.PDFOutlineViewer = PDFOutlineViewer; /***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { +/* 21 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFPresentationMode = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); const DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS = 1500; const DELAY_BEFORE_HIDING_CONTROLS = 3000; @@ -8032,8 +7722,7 @@ class PDFPresentationMode { constructor({ container, pdfViewer, - eventBus, - contextMenuItems = null + eventBus }) { this.container = container; this.pdfViewer = pdfViewer; @@ -8044,33 +7733,6 @@ class PDFPresentationMode { this.mouseScrollTimeStamp = 0; this.mouseScrollDelta = 0; this.touchSwipeState = null; - - if (contextMenuItems) { - contextMenuItems.contextFirstPage.addEventListener("click", () => { - this.contextMenuOpen = false; - this.eventBus.dispatch("firstpage", { - source: this - }); - }); - contextMenuItems.contextLastPage.addEventListener("click", () => { - this.contextMenuOpen = false; - this.eventBus.dispatch("lastpage", { - source: this - }); - }); - contextMenuItems.contextPageRotateCw.addEventListener("click", () => { - this.contextMenuOpen = false; - this.eventBus.dispatch("rotatecw", { - source: this - }); - }); - contextMenuItems.contextPageRotateCcw.addEventListener("click", () => { - this.contextMenuOpen = false; - this.eventBus.dispatch("rotateccw", { - source: this - }); - }); - } } request() { @@ -8090,8 +7752,6 @@ class PDFPresentationMode { this.container.mozRequestFullScreen(); } else if (this.container.webkitRequestFullscreen) { this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); - } else if (this.container.msRequestFullscreen) { - this.container.msRequestFullscreen(); } else { return false; } @@ -8110,7 +7770,7 @@ class PDFPresentationMode { evt.preventDefault(); const delta = (0, _ui_utils.normalizeWheelEventDelta)(evt); - const currentTime = new Date().getTime(); + const currentTime = Date.now(); const storedTime = this.mouseScrollTimeStamp; if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) { @@ -8128,7 +7788,7 @@ class PDFPresentationMode { this._resetMouseScrollState(); - const success = totalDelta > 0 ? this._goToPreviousPage() : this._goToNextPage(); + const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage(); if (success) { this.mouseScrollTimeStamp = currentTime; @@ -8137,36 +7797,21 @@ class PDFPresentationMode { } get isFullscreen() { - return !!(document.fullscreenElement || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement); - } - - _goToPreviousPage() { - const page = this.pdfViewer.currentPageNumber; - - if (page <= 1) { - return false; - } - - this.pdfViewer.currentPageNumber = page - 1; - return true; + return !!(document.fullscreenElement || document.mozFullScreen || document.webkitIsFullScreen); } - _goToNextPage() { - const page = this.pdfViewer.currentPageNumber; + _notifyStateChange() { + let state = _ui_utils.PresentationModeState.NORMAL; - if (page >= this.pdfViewer.pagesCount) { - return false; + if (this.switchInProgress) { + state = _ui_utils.PresentationModeState.CHANGING; + } else if (this.active) { + state = _ui_utils.PresentationModeState.FULLSCREEN; } - this.pdfViewer.currentPageNumber = page + 1; - return true; - } - - _notifyStateChange() { this.eventBus.dispatch("presentationmodechanged", { source: this, - active: this.active, - switchInProgress: !!this.switchInProgress + state }); } @@ -8209,7 +7854,6 @@ class PDFPresentationMode { this._showControls(); this.contextMenuOpen = false; - this.container.setAttribute("contextmenu", "viewerContextMenu"); window.getSelection().removeAllRanges(); } @@ -8234,7 +7878,6 @@ class PDFPresentationMode { this._resetMouseScrollState(); - this.container.removeAttribute("contextmenu"); this.contextMenuOpen = false; } @@ -8252,9 +7895,9 @@ class PDFPresentationMode { evt.preventDefault(); if (evt.shiftKey) { - this._goToPreviousPage(); + this.pdfViewer.previousPage(); } else { - this._goToNextPage(); + this.pdfViewer.nextPage(); } } } @@ -8339,9 +7982,9 @@ class PDFPresentationMode { } if (delta > 0) { - this._goToPreviousPage(); + this.pdfViewer.previousPage(); } else if (delta < 0) { - this._goToNextPage(); + this.pdfViewer.nextPage(); } break; @@ -8399,14 +8042,12 @@ class PDFPresentationMode { window.addEventListener("fullscreenchange", this.fullscreenChangeBind); window.addEventListener("mozfullscreenchange", this.fullscreenChangeBind); window.addEventListener("webkitfullscreenchange", this.fullscreenChangeBind); - window.addEventListener("MSFullscreenChange", this.fullscreenChangeBind); } _removeFullscreenChangeListeners() { window.removeEventListener("fullscreenchange", this.fullscreenChangeBind); window.removeEventListener("mozfullscreenchange", this.fullscreenChangeBind); window.removeEventListener("webkitfullscreenchange", this.fullscreenChangeBind); - window.removeEventListener("MSFullscreenChange", this.fullscreenChangeBind); delete this.fullscreenChangeBind; } @@ -8415,26 +8056,829 @@ class PDFPresentationMode { exports.PDFPresentationMode = PDFPresentationMode; /***/ }), +/* 22 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.PDFScriptingManager = void 0; + +var _pdfjsLib = __webpack_require__(5); + +var _ui_utils = __webpack_require__(4); + +var _pdf_rendering_queue = __webpack_require__(8); + +class PDFScriptingManager { + constructor({ + eventBus, + sandboxBundleSrc = null, + scriptingFactory = null, + docPropertiesLookup = null + }) { + this._pdfDocument = null; + this._pdfViewer = null; + this._closeCapability = null; + this._destroyCapability = null; + this._scripting = null; + this._mouseState = Object.create(null); + this._ready = false; + this._eventBus = eventBus; + this._sandboxBundleSrc = sandboxBundleSrc; + this._scriptingFactory = scriptingFactory; + this._docPropertiesLookup = docPropertiesLookup; + } + + setViewer(pdfViewer) { + this._pdfViewer = pdfViewer; + } + + async setDocument(pdfDocument) { + if (this._pdfDocument) { + await this._destroyScripting(); + } + + this._pdfDocument = pdfDocument; + + if (!pdfDocument) { + return; + } + + const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); + + if (!objects && !docActions) { + await this._destroyScripting(); + return; + } + + if (pdfDocument !== this._pdfDocument) { + return; + } + + try { + this._scripting = this._createScripting(); + } catch (error) { + console.error(`PDFScriptingManager.setDocument: "${error?.message}".`); + await this._destroyScripting(); + return; + } + + this._internalEvents.set("updatefromsandbox", event => { + if (event?.source !== window) { + return; + } + + this._updateFromSandbox(event.detail); + }); + + this._internalEvents.set("dispatcheventinsandbox", event => { + this._scripting?.dispatchEventInSandbox(event.detail); + }); + + this._internalEvents.set("pagechanging", ({ + pageNumber, + previous + }) => { + if (pageNumber === previous) { + return; + } + + this._dispatchPageClose(previous); + + this._dispatchPageOpen(pageNumber); + }); + + this._internalEvents.set("pagerendered", ({ + pageNumber + }) => { + if (!this._pageOpenPending.has(pageNumber)) { + return; + } + + if (pageNumber !== this._pdfViewer.currentPageNumber) { + return; + } + + this._dispatchPageOpen(pageNumber); + }); + + this._internalEvents.set("pagesdestroy", async event => { + await this._dispatchPageClose(this._pdfViewer.currentPageNumber); + await this._scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillClose" + }); + this._closeCapability?.resolve(); + }); + + this._domEvents.set("mousedown", event => { + this._mouseState.isDown = true; + }); + + this._domEvents.set("mouseup", event => { + this._mouseState.isDown = false; + }); + + for (const [name, listener] of this._internalEvents) { + this._eventBus._on(name, listener); + } + + for (const [name, listener] of this._domEvents) { + window.addEventListener(name, listener); + } + + try { + const docProperties = await this._getDocProperties(); + + if (pdfDocument !== this._pdfDocument) { + return; + } + + await this._scripting.createSandbox({ + objects, + calculationOrder, + appInfo: { + platform: navigator.platform, + language: navigator.language + }, + docInfo: { ...docProperties, + actions: docActions + } + }); + + this._eventBus.dispatch("sandboxcreated", { + source: this + }); + } catch (error) { + console.error(`PDFScriptingManager.setDocument: "${error?.message}".`); + await this._destroyScripting(); + return; + } + + await this._scripting?.dispatchEventInSandbox({ + id: "doc", + name: "Open" + }); + await this._dispatchPageOpen(this._pdfViewer.currentPageNumber, true); + Promise.resolve().then(() => { + if (pdfDocument === this._pdfDocument) { + this._ready = true; + } + }); + } + + async dispatchWillSave(detail) { + return this._scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillSave" + }); + } + + async dispatchDidSave(detail) { + return this._scripting?.dispatchEventInSandbox({ + id: "doc", + name: "DidSave" + }); + } + + async dispatchWillPrint(detail) { + return this._scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillPrint" + }); + } + + async dispatchDidPrint(detail) { + return this._scripting?.dispatchEventInSandbox({ + id: "doc", + name: "DidPrint" + }); + } + + get mouseState() { + return this._mouseState; + } + + get destroyPromise() { + return this._destroyCapability?.promise || null; + } + + get ready() { + return this._ready; + } + + get _internalEvents() { + return (0, _pdfjsLib.shadow)(this, "_internalEvents", new Map()); + } + + get _domEvents() { + return (0, _pdfjsLib.shadow)(this, "_domEvents", new Map()); + } + + get _pageOpenPending() { + return (0, _pdfjsLib.shadow)(this, "_pageOpenPending", new Set()); + } + + get _visitedPages() { + return (0, _pdfjsLib.shadow)(this, "_visitedPages", new Map()); + } + + async _updateFromSandbox(detail) { + const isInPresentationMode = this._pdfViewer.isInPresentationMode || this._pdfViewer.isChangingPresentationMode; + const { + id, + siblings, + command, + value + } = detail; + + if (!id) { + switch (command) { + case "clear": + console.clear(); + break; + + case "error": + console.error(value); + break; + + case "layout": + this._pdfViewer.spreadMode = (0, _ui_utils.apiPageLayoutToSpreadMode)(value); + break; + + case "page-num": + this._pdfViewer.currentPageNumber = value + 1; + break; + + case "print": + await this._pdfViewer.pagesPromise; + + this._eventBus.dispatch("print", { + source: this + }); + + break; + + case "println": + console.log(value); + break; + + case "zoom": + if (isInPresentationMode) { + return; + } + + this._pdfViewer.currentScaleValue = value; + break; + } + + return; + } + + if (isInPresentationMode) { + if (detail.focus) { + return; + } + } + + delete detail.id; + delete detail.siblings; + const ids = siblings ? [id, ...siblings] : [id]; + + for (const elementId of ids) { + const element = document.getElementById(elementId); + + if (element) { + element.dispatchEvent(new CustomEvent("updatefromsandbox", { + detail + })); + } else { + this._pdfDocument?.annotationStorage.setValue(elementId, detail); + } + } + } + + async _dispatchPageOpen(pageNumber, initialize = false) { + const pdfDocument = this._pdfDocument, + visitedPages = this._visitedPages; + + if (initialize) { + this._closeCapability = (0, _pdfjsLib.createPromiseCapability)(); + } + + if (!this._closeCapability) { + return; + } + + const pageView = this._pdfViewer.getPageView(pageNumber - 1); + + if (pageView?.renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) { + this._pageOpenPending.add(pageNumber); + + return; + } + + this._pageOpenPending.delete(pageNumber); + + const actionsPromise = (async () => { + const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); + + if (pdfDocument !== this._pdfDocument) { + return; + } + + await this._scripting?.dispatchEventInSandbox({ + id: "page", + name: "PageOpen", + pageNumber, + actions + }); + })(); + + visitedPages.set(pageNumber, actionsPromise); + } + + async _dispatchPageClose(pageNumber) { + const pdfDocument = this._pdfDocument, + visitedPages = this._visitedPages; + + if (!this._closeCapability) { + return; + } + + if (this._pageOpenPending.has(pageNumber)) { + return; + } + + const actionsPromise = visitedPages.get(pageNumber); + + if (!actionsPromise) { + return; + } + + visitedPages.set(pageNumber, null); + await actionsPromise; + + if (pdfDocument !== this._pdfDocument) { + return; + } + + await this._scripting?.dispatchEventInSandbox({ + id: "page", + name: "PageClose", + pageNumber + }); + } + + async _getDocProperties() { + if (this._docPropertiesLookup) { + return this._docPropertiesLookup(this._pdfDocument); + } + + throw new Error("_getDocProperties: Unable to lookup properties."); + } + + _createScripting() { + this._destroyCapability = (0, _pdfjsLib.createPromiseCapability)(); + + if (this._scripting) { + throw new Error("_createScripting: Scripting already exists."); + } + + if (this._scriptingFactory) { + return this._scriptingFactory.createScripting({ + sandboxBundleSrc: this._sandboxBundleSrc + }); + } + + throw new Error("_createScripting: Cannot create scripting."); + } + + async _destroyScripting() { + if (!this._scripting) { + this._pdfDocument = null; + this._destroyCapability?.resolve(); + return; + } + + if (this._closeCapability) { + await Promise.race([this._closeCapability.promise, new Promise(resolve => { + setTimeout(resolve, 1000); + })]).catch(reason => {}); + this._closeCapability = null; + } + + this._pdfDocument = null; + + try { + await this._scripting.destroySandbox(); + } catch (ex) {} + + for (const [name, listener] of this._internalEvents) { + this._eventBus._off(name, listener); + } + + this._internalEvents.clear(); + + for (const [name, listener] of this._domEvents) { + window.removeEventListener(name, listener); + } + + this._domEvents.clear(); + + this._pageOpenPending.clear(); + + this._visitedPages.clear(); + + this._scripting = null; + delete this._mouseState.isDown; + this._ready = false; + this._destroyCapability?.resolve(); + } + +} + +exports.PDFScriptingManager = PDFScriptingManager; + +/***/ }), /* 23 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.PDFSidebarResizer = void 0; +})); +exports.PDFSidebar = void 0; + +var _ui_utils = __webpack_require__(4); + +var _pdf_rendering_queue = __webpack_require__(8); + +const UI_NOTIFICATION_CLASS = "pdfSidebarNotification"; + +class PDFSidebar { + constructor({ + elements, + pdfViewer, + pdfThumbnailViewer, + eventBus, + l10n + }) { + this.isOpen = false; + this.active = _ui_utils.SidebarView.THUMBS; + this.isInitialViewSet = false; + this.onToggled = null; + this.pdfViewer = pdfViewer; + this.pdfThumbnailViewer = pdfThumbnailViewer; + this.outerContainer = elements.outerContainer; + this.viewerContainer = elements.viewerContainer; + this.toggleButton = elements.toggleButton; + this.thumbnailButton = elements.thumbnailButton; + this.outlineButton = elements.outlineButton; + this.attachmentsButton = elements.attachmentsButton; + this.layersButton = elements.layersButton; + this.thumbnailView = elements.thumbnailView; + this.outlineView = elements.outlineView; + this.attachmentsView = elements.attachmentsView; + this.layersView = elements.layersView; + this._outlineOptionsContainer = elements.outlineOptionsContainer; + this._currentOutlineItemButton = elements.currentOutlineItemButton; + this.eventBus = eventBus; + this.l10n = l10n; + + this._addEventListeners(); + } + + reset() { + this.isInitialViewSet = false; + + this._hideUINotification(true); + + this.switchView(_ui_utils.SidebarView.THUMBS); + this.outlineButton.disabled = false; + this.attachmentsButton.disabled = false; + this.layersButton.disabled = false; + this._currentOutlineItemButton.disabled = true; + } + + get visibleView() { + return this.isOpen ? this.active : _ui_utils.SidebarView.NONE; + } + + get isThumbnailViewVisible() { + return this.isOpen && this.active === _ui_utils.SidebarView.THUMBS; + } + + get isOutlineViewVisible() { + return this.isOpen && this.active === _ui_utils.SidebarView.OUTLINE; + } + + get isAttachmentsViewVisible() { + return this.isOpen && this.active === _ui_utils.SidebarView.ATTACHMENTS; + } + + get isLayersViewVisible() { + return this.isOpen && this.active === _ui_utils.SidebarView.LAYERS; + } + + setInitialView(view = _ui_utils.SidebarView.NONE) { + if (this.isInitialViewSet) { + return; + } + + this.isInitialViewSet = true; + + if (view === _ui_utils.SidebarView.NONE || view === _ui_utils.SidebarView.UNKNOWN) { + this._dispatchEvent(); + + return; + } + + if (!this._switchView(view, true)) { + this._dispatchEvent(); + } + } + + switchView(view, forceOpen = false) { + this._switchView(view, forceOpen); + } + + _switchView(view, forceOpen = false) { + const isViewChanged = view !== this.active; + let shouldForceRendering = false; + + switch (view) { + case _ui_utils.SidebarView.NONE: + if (this.isOpen) { + this.close(); + return true; + } + + return false; + + case _ui_utils.SidebarView.THUMBS: + if (this.isOpen && isViewChanged) { + shouldForceRendering = true; + } + + break; + + case _ui_utils.SidebarView.OUTLINE: + if (this.outlineButton.disabled) { + return false; + } + + break; -var _ui_utils = __webpack_require__(2); + case _ui_utils.SidebarView.ATTACHMENTS: + if (this.attachmentsButton.disabled) { + return false; + } + + break; + + case _ui_utils.SidebarView.LAYERS: + if (this.layersButton.disabled) { + return false; + } + + break; + + default: + console.error(`PDFSidebar._switchView: "${view}" is not a valid view.`); + return false; + } + + this.active = view; + this.thumbnailButton.classList.toggle("toggled", view === _ui_utils.SidebarView.THUMBS); + this.outlineButton.classList.toggle("toggled", view === _ui_utils.SidebarView.OUTLINE); + this.attachmentsButton.classList.toggle("toggled", view === _ui_utils.SidebarView.ATTACHMENTS); + this.layersButton.classList.toggle("toggled", view === _ui_utils.SidebarView.LAYERS); + this.thumbnailView.classList.toggle("hidden", view !== _ui_utils.SidebarView.THUMBS); + this.outlineView.classList.toggle("hidden", view !== _ui_utils.SidebarView.OUTLINE); + this.attachmentsView.classList.toggle("hidden", view !== _ui_utils.SidebarView.ATTACHMENTS); + this.layersView.classList.toggle("hidden", view !== _ui_utils.SidebarView.LAYERS); + + this._outlineOptionsContainer.classList.toggle("hidden", view !== _ui_utils.SidebarView.OUTLINE); + + if (forceOpen && !this.isOpen) { + this.open(); + return true; + } + + if (shouldForceRendering) { + this._updateThumbnailViewer(); + + this._forceRendering(); + } + + if (isViewChanged) { + this._dispatchEvent(); + } + + return isViewChanged; + } + + open() { + if (this.isOpen) { + return; + } + + this.isOpen = true; + this.toggleButton.classList.add("toggled"); + this.toggleButton.setAttribute("aria-expanded", "true"); + this.outerContainer.classList.add("sidebarMoving", "sidebarOpen"); + + if (this.active === _ui_utils.SidebarView.THUMBS) { + this._updateThumbnailViewer(); + } + + this._forceRendering(); + + this._dispatchEvent(); + + this._hideUINotification(); + } + + close() { + if (!this.isOpen) { + return; + } + + this.isOpen = false; + this.toggleButton.classList.remove("toggled"); + this.toggleButton.setAttribute("aria-expanded", "false"); + this.outerContainer.classList.add("sidebarMoving"); + this.outerContainer.classList.remove("sidebarOpen"); + + this._forceRendering(); + + this._dispatchEvent(); + } + + toggle() { + if (this.isOpen) { + this.close(); + } else { + this.open(); + } + } + _dispatchEvent() { + this.eventBus.dispatch("sidebarviewchanged", { + source: this, + view: this.visibleView + }); + } + + _forceRendering() { + if (this.onToggled) { + this.onToggled(); + } else { + this.pdfViewer.forceRendering(); + this.pdfThumbnailViewer.forceRendering(); + } + } + + _updateThumbnailViewer() { + const { + pdfViewer, + pdfThumbnailViewer + } = this; + const pagesCount = pdfViewer.pagesCount; + + for (let pageIndex = 0; pageIndex < pagesCount; pageIndex++) { + const pageView = pdfViewer.getPageView(pageIndex); + + if (pageView?.renderingState === _pdf_rendering_queue.RenderingStates.FINISHED) { + const thumbnailView = pdfThumbnailViewer.getThumbnail(pageIndex); + thumbnailView.setImage(pageView); + } + } + + pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber); + } + + _showUINotification() { + this.l10n.get("toggle_sidebar_notification2.title").then(msg => { + this.toggleButton.title = msg; + }); + + if (!this.isOpen) { + this.toggleButton.classList.add(UI_NOTIFICATION_CLASS); + } + } + + _hideUINotification(reset = false) { + if (this.isOpen || reset) { + this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS); + } + + if (reset) { + this.l10n.get("toggle_sidebar.title").then(msg => { + this.toggleButton.title = msg; + }); + } + } + + _addEventListeners() { + this.viewerContainer.addEventListener("transitionend", evt => { + if (evt.target === this.viewerContainer) { + this.outerContainer.classList.remove("sidebarMoving"); + } + }); + this.toggleButton.addEventListener("click", () => { + this.toggle(); + }); + this.thumbnailButton.addEventListener("click", () => { + this.switchView(_ui_utils.SidebarView.THUMBS); + }); + this.outlineButton.addEventListener("click", () => { + this.switchView(_ui_utils.SidebarView.OUTLINE); + }); + this.outlineButton.addEventListener("dblclick", () => { + this.eventBus.dispatch("toggleoutlinetree", { + source: this + }); + }); + this.attachmentsButton.addEventListener("click", () => { + this.switchView(_ui_utils.SidebarView.ATTACHMENTS); + }); + this.layersButton.addEventListener("click", () => { + this.switchView(_ui_utils.SidebarView.LAYERS); + }); + this.layersButton.addEventListener("dblclick", () => { + this.eventBus.dispatch("resetlayers", { + source: this + }); + }); + + this._currentOutlineItemButton.addEventListener("click", () => { + this.eventBus.dispatch("currentoutlineitem", { + source: this + }); + }); + + const onTreeLoaded = (count, button, view) => { + button.disabled = !count; + + if (count) { + this._showUINotification(); + } else if (this.active === view) { + this.switchView(_ui_utils.SidebarView.THUMBS); + } + }; + + this.eventBus._on("outlineloaded", evt => { + onTreeLoaded(evt.outlineCount, this.outlineButton, _ui_utils.SidebarView.OUTLINE); + evt.currentOutlineItemPromise.then(enabled => { + if (!this.isInitialViewSet) { + return; + } + + this._currentOutlineItemButton.disabled = !enabled; + }); + }); + + this.eventBus._on("attachmentsloaded", evt => { + onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, _ui_utils.SidebarView.ATTACHMENTS); + }); + + this.eventBus._on("layersloaded", evt => { + onTreeLoaded(evt.layersCount, this.layersButton, _ui_utils.SidebarView.LAYERS); + }); + + this.eventBus._on("presentationmodechanged", evt => { + if (evt.state === _ui_utils.PresentationModeState.NORMAL && this.isThumbnailViewVisible) { + this._updateThumbnailViewer(); + } + }); + } + +} + +exports.PDFSidebar = PDFSidebar; + +/***/ }), +/* 24 */ +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.PDFSidebarResizer = void 0; const SIDEBAR_WIDTH_VAR = "--sidebar-width"; const SIDEBAR_MIN_WIDTH = 200; const SIDEBAR_RESIZING_CLASS = "sidebarResizing"; class PDFSidebarResizer { - constructor(options, eventBus, l10n = _ui_utils.NullL10n) { - this.enabled = false; + constructor(options, eventBus, l10n) { this.isRTL = false; this.sidebarOpen = false; this.doc = document.documentElement; @@ -8444,16 +8888,7 @@ class PDFSidebarResizer { this.outerContainer = options.outerContainer; this.resizer = options.resizer; this.eventBus = eventBus; - this.l10n = l10n; - - if (typeof CSS === "undefined" || typeof CSS.supports !== "function" || !CSS.supports(SIDEBAR_WIDTH_VAR, `calc(-1 * ${SIDEBAR_MIN_WIDTH}px)`)) { - console.warn("PDFSidebarResizer: " + "The browser does not support resizing of the sidebar."); - return; - } - - this.enabled = true; - this.resizer.classList.remove("hidden"); - this.l10n.getDirection().then(dir => { + l10n.getDirection().then(dir => { this.isRTL = dir === "rtl"; }); @@ -8461,26 +8896,26 @@ class PDFSidebarResizer { } get outerContainerWidth() { - if (!this._outerContainerWidth) { - this._outerContainerWidth = this.outerContainer.clientWidth; - } - - return this._outerContainerWidth; + return this._outerContainerWidth || (this._outerContainerWidth = this.outerContainer.clientWidth); } _updateWidth(width = 0) { - if (!this.enabled) { - return false; + const maxWidth = Math.floor(this.outerContainerWidth / 2); + + if (width > maxWidth) { + width = maxWidth; } - const newWidth = (0, _ui_utils.clamp)(width, SIDEBAR_MIN_WIDTH, Math.floor(this.outerContainerWidth / 2)); + if (width < SIDEBAR_MIN_WIDTH) { + width = SIDEBAR_MIN_WIDTH; + } - if (newWidth === this._width) { + if (width === this._width) { return false; } - this._width = newWidth; - this.doc.style.setProperty(SIDEBAR_WIDTH_VAR, `${newWidth}px`); + this._width = width; + this.doc.style.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`); return true; } @@ -8505,10 +8940,6 @@ class PDFSidebarResizer { } _addEventListeners() { - if (!this.enabled) { - return; - } - const _boundEvents = this._boundEvents; _boundEvents.mouseMove = this._mouseMove.bind(this); _boundEvents.mouseUp = this._mouseUp.bind(this); @@ -8523,11 +8954,11 @@ class PDFSidebarResizer { }); this.eventBus._on("sidebarviewchanged", evt => { - this.sidebarOpen = !!(evt && evt.view); + this.sidebarOpen = !!evt?.view; }); this.eventBus._on("resize", evt => { - if (!evt || evt.source !== window) { + if (evt?.source !== window) { return; } @@ -8564,20 +8995,21 @@ class PDFSidebarResizer { exports.PDFSidebarResizer = PDFSidebarResizer; /***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { +/* 25 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFThumbnailViewer = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); -var _pdf_thumbnail_view = __webpack_require__(25); +var _pdf_thumbnail_view = __webpack_require__(26); + +var _pdf_rendering_queue = __webpack_require__(8); const THUMBNAIL_SCROLL_MARGIN = -19; const THUMBNAIL_SELECTED_CLASS = "selected"; @@ -8588,7 +9020,7 @@ class PDFThumbnailViewer { eventBus, linkService, renderingQueue, - l10n = _ui_utils.NullL10n + l10n }) { this.container = container; this.linkService = linkService; @@ -8612,7 +9044,10 @@ class PDFThumbnailViewer { } _getVisibleThumbs() { - return (0, _ui_utils.getVisibleElements)(this.container, this._thumbnails); + return (0, _ui_utils.getVisibleElements)({ + scrollEl: this.container, + views: this._thumbnails + }); } scrollThumbnailIntoView(pageNumber) { @@ -8690,7 +9125,13 @@ class PDFThumbnailViewer { } cleanup() { - _pdf_thumbnail_view.PDFThumbnailView.cleanup(); + for (let i = 0, ii = this._thumbnails.length; i < ii; i++) { + if (this._thumbnails[i] && this._thumbnails[i].renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) { + this._thumbnails[i].reset(); + } + } + + _pdf_thumbnail_view.TempImageFactory.destroyCanvas(); } _resetView() { @@ -8739,7 +9180,6 @@ class PDFThumbnailViewer { linkService: this.linkService, renderingQueue: this.renderingQueue, checkSetImageDisabled, - disableCanvasToImageConversion: false, l10n: this.l10n }); @@ -8782,9 +9222,7 @@ class PDFThumbnailViewer { } for (let i = 0, ii = this._thumbnails.length; i < ii; i++) { - const label = this._pageLabels && this._pageLabels[i]; - - this._thumbnails[i].setPageLabel(label); + this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null); } } @@ -8837,23 +9275,23 @@ class PDFThumbnailViewer { exports.PDFThumbnailViewer = PDFThumbnailViewer; /***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { +/* 26 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.PDFThumbnailView = void 0; +})); +exports.TempImageFactory = exports.PDFThumbnailView = void 0; -var _pdfjsLib = __webpack_require__(5); +var _ui_utils = __webpack_require__(4); -var _ui_utils = __webpack_require__(2); +var _pdfjsLib = __webpack_require__(5); var _pdf_rendering_queue = __webpack_require__(8); +const DRAW_UPSCALE_FACTOR = 2; const MAX_NUM_SCALING_STEPS = 3; const THUMBNAIL_CANVAS_BORDER_WIDTH = 1; const THUMBNAIL_WIDTH = 98; @@ -8879,7 +9317,7 @@ const TempImageFactory = function TempImageFactoryClosure() { ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillRect(0, 0, width, height); ctx.restore(); - return tempCanvas; + return [tempCanvas, tempCanvas.getContext("2d")]; }, destroyCanvas() { @@ -8896,6 +9334,8 @@ const TempImageFactory = function TempImageFactoryClosure() { }; }(); +exports.TempImageFactory = TempImageFactory; + class PDFThumbnailView { constructor({ container, @@ -8905,8 +9345,7 @@ class PDFThumbnailView { linkService, renderingQueue, checkSetImageDisabled, - disableCanvasToImageConversion = false, - l10n = _ui_utils.NullL10n + l10n }) { this.id = id; this.renderingId = "thumbnail" + id; @@ -8926,13 +9365,12 @@ class PDFThumbnailView { return false; }; - this.disableCanvasToImageConversion = disableCanvasToImageConversion; - this.pageWidth = this.viewport.width; - this.pageHeight = this.viewport.height; - this.pageRatio = this.pageWidth / this.pageHeight; + const pageWidth = this.viewport.width, + pageHeight = this.viewport.height, + pageRatio = pageWidth / pageHeight; this.canvasWidth = THUMBNAIL_WIDTH; - this.canvasHeight = this.canvasWidth / this.pageRatio | 0; - this.scale = this.canvasWidth / this.pageWidth; + this.canvasHeight = this.canvasWidth / pageRatio | 0; + this.scale = this.canvasWidth / pageWidth; this.l10n = l10n; const anchor = document.createElement("a"); anchor.href = linkService.getAnchorUrl("#page=" + id); @@ -8942,7 +9380,7 @@ class PDFThumbnailView { }); anchor.onclick = function () { - linkService.page = id; + linkService.goToPage(id); return false; }; @@ -8976,19 +9414,14 @@ class PDFThumbnailView { reset() { this.cancelRendering(); this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL; - this.pageWidth = this.viewport.width; - this.pageHeight = this.viewport.height; - this.pageRatio = this.pageWidth / this.pageHeight; - this.canvasHeight = this.canvasWidth / this.pageRatio | 0; - this.scale = this.canvasWidth / this.pageWidth; + const pageWidth = this.viewport.width, + pageHeight = this.viewport.height, + pageRatio = pageWidth / pageHeight; + this.canvasHeight = this.canvasWidth / pageRatio | 0; + this.scale = this.canvasWidth / pageWidth; this.div.removeAttribute("data-loaded"); const ring = this.ring; - const childNodes = ring.childNodes; - - for (let i = childNodes.length - 1; i >= 0; i--) { - ring.removeChild(childNodes[i]); - } - + ring.textContent = ""; const borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH; ring.style.width = this.canvasWidth + borderAdjustment + "px"; ring.style.height = this.canvasHeight + borderAdjustment + "px"; @@ -9027,51 +9460,32 @@ class PDFThumbnailView { this.resume = null; } - _getPageDrawContext(noCtxScale = false) { + _getPageDrawContext(upscaleFactor = 1) { const canvas = document.createElement("canvas"); - this.canvas = canvas; canvas.mozOpaque = true; const ctx = canvas.getContext("2d", { alpha: false }); const outputScale = (0, _ui_utils.getOutputScale)(ctx); - canvas.width = this.canvasWidth * outputScale.sx | 0; - canvas.height = this.canvasHeight * outputScale.sy | 0; - canvas.style.width = this.canvasWidth + "px"; - canvas.style.height = this.canvasHeight + "px"; - - if (!noCtxScale && outputScale.scaled) { - ctx.scale(outputScale.sx, outputScale.sy); - } - - return ctx; + canvas.width = upscaleFactor * this.canvasWidth * outputScale.sx | 0; + canvas.height = upscaleFactor * this.canvasHeight * outputScale.sy | 0; + const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; + return { + ctx, + canvas, + transform + }; } - _convertCanvasToImage() { - if (!this.canvas) { - return; - } - + _convertCanvasToImage(canvas) { if (this.renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) { - return; + throw new Error("_convertCanvasToImage: Rendering has not finished."); } - const className = "thumbnailImage"; - - if (this.disableCanvasToImageConversion) { - this.canvas.className = className; - - this._thumbPageCanvas.then(msg => { - this.canvas.setAttribute("aria-label", msg); - }); - - this.div.setAttribute("data-loaded", true); - this.ring.appendChild(this.canvas); - return; - } + const reducedCanvas = this._reduceImage(canvas); const image = document.createElement("img"); - image.className = className; + image.className = "thumbnailImage"; this._thumbPageCanvas.then(msg => { image.setAttribute("aria-label", msg); @@ -9079,13 +9493,12 @@ class PDFThumbnailView { image.style.width = this.canvasWidth + "px"; image.style.height = this.canvasHeight + "px"; - image.src = this.canvas.toDataURL(); + image.src = reducedCanvas.toDataURL(); this.image = image; this.div.setAttribute("data-loaded", true); this.ring.appendChild(image); - this.canvas.width = 0; - this.canvas.height = 0; - delete this.canvas; + reducedCanvas.width = 0; + reducedCanvas.height = 0; } draw() { @@ -9104,33 +9517,33 @@ class PDFThumbnailView { } this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING; - const renderCapability = (0, _pdfjsLib.createPromiseCapability)(); - const finishRenderTask = error => { + const finishRenderTask = async (error = null) => { if (renderTask === this.renderTask) { this.renderTask = null; } if (error instanceof _pdfjsLib.RenderingCancelledException) { - renderCapability.resolve(undefined); return; } this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED; - this._convertCanvasToImage(); + this._convertCanvasToImage(canvas); - if (!error) { - renderCapability.resolve(undefined); - } else { - renderCapability.reject(error); + if (error) { + throw error; } }; - const ctx = this._getPageDrawContext(); + const { + ctx, + canvas, + transform + } = this._getPageDrawContext(DRAW_UPSCALE_FACTOR); const drawViewport = this.viewport.clone({ - scale: this.scale + scale: DRAW_UPSCALE_FACTOR * this.scale }); const renderContinueCallback = cont => { @@ -9150,17 +9563,27 @@ class PDFThumbnailView { const renderContext = { canvasContext: ctx, + transform, viewport: drawViewport, optionalContentConfigPromise: this._optionalContentConfigPromise }; const renderTask = this.renderTask = pdfPage.render(renderContext); renderTask.onContinue = renderContinueCallback; - renderTask.promise.then(function () { - finishRenderTask(null); + const resultPromise = renderTask.promise.then(function () { + return finishRenderTask(null); }, function (error) { - finishRenderTask(error); + return finishRenderTask(error); + }); + resultPromise.finally(() => { + canvas.width = 0; + canvas.height = 0; + const pageCached = this.linkService.isPageCached(this.id); + + if (!pageCached) { + this.pdfPage?.cleanup(); + } }); - return renderCapability.promise; + return resultPromise; } setImage(pageView) { @@ -9172,34 +9595,38 @@ class PDFThumbnailView { return; } - const img = pageView.canvas; + const { + canvas, + pdfPage + } = pageView; - if (!img) { + if (!canvas) { return; } if (!this.pdfPage) { - this.setPdfPage(pageView.pdfPage); + this.setPdfPage(pdfPage); } this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED; - const ctx = this._getPageDrawContext(true); + this._convertCanvasToImage(canvas); + } - const canvas = ctx.canvas; + _reduceImage(img) { + const { + ctx, + canvas + } = this._getPageDrawContext(); if (img.width <= 2 * canvas.width) { ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); - - this._convertCanvasToImage(); - - return; + return canvas; } let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS; let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS; - const reducedImage = TempImageFactory.getCanvas(reducedWidth, reducedHeight); - const reducedImageCtx = reducedImage.getContext("2d"); + const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight); while (reducedWidth > img.width || reducedHeight > img.height) { reducedWidth >>= 1; @@ -9215,24 +9642,19 @@ class PDFThumbnailView { } ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height); - - this._convertCanvasToImage(); + return canvas; } get _thumbPageTitle() { - var _this$pageLabel; - return this.l10n.get("thumb_page_title", { - page: (_this$pageLabel = this.pageLabel) != null ? _this$pageLabel : this.id - }, "Page {{page}}"); + page: this.pageLabel ?? this.id + }); } get _thumbPageCanvas() { - var _this$pageLabel2; - return this.l10n.get("thumb_page_canvas", { - page: (_this$pageLabel2 = this.pageLabel) != null ? _this$pageLabel2 : this.id - }, "Thumbnail of Page {{page}}"); + page: this.pageLabel ?? this.id + }); } setPageLabel(label) { @@ -9247,35 +9669,28 @@ class PDFThumbnailView { } this._thumbPageCanvas.then(msg => { - if (this.image) { - this.image.setAttribute("aria-label", msg); - } else if (this.disableCanvasToImageConversion && this.canvas) { - this.canvas.setAttribute("aria-label", msg); - } + this.image?.setAttribute("aria-label", msg); }); } - static cleanup() { - TempImageFactory.destroyCanvas(); - } - } exports.PDFThumbnailView = PDFThumbnailView; /***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { +/* 27 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFViewer = void 0; -var _base_viewer = __webpack_require__(27); +var _ui_utils = __webpack_require__(4); + +var _base_viewer = __webpack_require__(28); var _pdfjsLib = __webpack_require__(5); @@ -9333,7 +9748,7 @@ class PDFViewer extends _base_viewer.BaseViewer { break; } - if (page.id === currentId) { + if (page.id === currentId && this._scrollMode === _ui_utils.ScrollMode.VERTICAL && this._spreadMode === _ui_utils.SpreadMode.NONE) { stillFullyVisible = true; break; } @@ -9351,30 +9766,35 @@ class PDFViewer extends _base_viewer.BaseViewer { exports.PDFViewer = PDFViewer; /***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { +/* 28 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.BaseViewer = void 0; -var _ui_utils = __webpack_require__(2); +var _pdfjsLib = __webpack_require__(5); + +var _ui_utils = __webpack_require__(4); var _pdf_rendering_queue = __webpack_require__(8); -var _annotation_layer_builder = __webpack_require__(28); +var _annotation_layer_builder = __webpack_require__(29); -var _pdfjsLib = __webpack_require__(5); +var _l10n_utils = __webpack_require__(30); + +var _pdf_page_view = __webpack_require__(31); + +var _pdf_link_service = __webpack_require__(19); -var _pdf_page_view = __webpack_require__(29); +var _struct_tree_layer_builder = __webpack_require__(32); -var _pdf_link_service = __webpack_require__(20); +var _text_layer_builder = __webpack_require__(33); -var _text_layer_builder = __webpack_require__(30); +var _xfa_layer_builder = __webpack_require__(34); const DEFAULT_CACHE_SIZE = 10; @@ -9414,6 +9834,10 @@ function PDFPageViewBuffer(size) { data.shift().destroy(); } }; + + this.has = function (view) { + return data.includes(view); + }; } function isSameScale(oldScale, newScale) { @@ -9434,28 +9858,39 @@ class BaseViewer { throw new Error("Cannot initialize BaseViewer."); } + const viewerVersion = '2.10.377'; + + if (_pdfjsLib.version !== viewerVersion) { + throw new Error(`The API version "${_pdfjsLib.version}" does not match the Viewer version "${viewerVersion}".`); + } + this._name = this.constructor.name; this.container = options.container; this.viewer = options.viewer || options.container.firstElementChild; - if (!(this.container instanceof HTMLDivElement && this.viewer instanceof HTMLDivElement)) { + if (!(this.container?.tagName.toUpperCase() === "DIV" && this.viewer?.tagName.toUpperCase() === "DIV")) { throw new Error("Invalid `container` and/or `viewer` option."); } + if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { + throw new Error("The `container` must be absolutely positioned."); + } + this.eventBus = options.eventBus; this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService(); this.downloadManager = options.downloadManager || null; this.findController = options.findController || null; + this._scriptingManager = options.scriptingManager || null; this.removePageBorders = options.removePageBorders || false; this.textLayerMode = Number.isInteger(options.textLayerMode) ? options.textLayerMode : _ui_utils.TextLayerMode.ENABLE; this.imageResourcesPath = options.imageResourcesPath || ""; - this.renderInteractiveForms = typeof options.renderInteractiveForms === "boolean" ? options.renderInteractiveForms : true; + this.renderInteractiveForms = options.renderInteractiveForms !== false; this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; this.renderer = options.renderer || _ui_utils.RendererType.CANVAS; - this.enableWebGL = options.enableWebGL || false; this.useOnlyCssZoom = options.useOnlyCssZoom || false; this.maxCanvasPixels = options.maxCanvasPixels; - this.l10n = options.l10n || _ui_utils.NullL10n; + this.l10n = options.l10n || _l10n_utils.NullL10n; + this.enableScripting = options.enableScripting === true && !!this._scriptingManager; this.defaultRenderingQueue = !options.renderingQueue; if (this.defaultRenderingQueue) { @@ -9496,7 +9931,7 @@ class BaseViewer { } return this._pages.every(function (pageView) { - return pageView && pageView.pdfPage; + return pageView?.pdfPage; }); } @@ -9531,11 +9966,13 @@ class BaseViewer { return false; } + const previous = this._currentPageNumber; this._currentPageNumber = val; this.eventBus.dispatch("pagechanging", { source: this, pageNumber: val, - pageLabel: this._pageLabels && this._pageLabels[val - 1] + pageLabel: this._pageLabels?.[val - 1] ?? null, + previous }); if (resetCurrentPageView) { @@ -9546,7 +9983,7 @@ class BaseViewer { } get currentPageLabel() { - return this._pageLabels && this._pageLabels[this._currentPageNumber - 1]; + return this._pageLabels?.[this._currentPageNumber - 1] ?? null; } set currentPageLabel(val) { @@ -9610,6 +10047,12 @@ class BaseViewer { return; } + rotation %= 360; + + if (rotation < 0) { + rotation += 360; + } + if (this._pagesRotation === rotation) { return; } @@ -9663,6 +10106,10 @@ class BaseViewer { setDocument(pdfDocument) { if (this.pdfDocument) { + this.eventBus.dispatch("pagesdestroy", { + source: this + }); + this._cancelRendering(); this._resetView(); @@ -9670,6 +10117,10 @@ class BaseViewer { if (this.findController) { this.findController.setDocument(null); } + + if (this._scriptingManager) { + this._scriptingManager.setDocument(null); + } } this.pdfDocument = pdfDocument; @@ -9678,9 +10129,9 @@ class BaseViewer { return; } + const isPureXfa = pdfDocument.isPureXfa; const pagesCount = pdfDocument.numPages; const firstPagePromise = pdfDocument.getPage(1); - const annotationStorage = pdfDocument.annotationStorage; const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig(); this._pagesCapability.promise.then(() => { @@ -9725,6 +10176,7 @@ class BaseViewer { scale: scale * _ui_utils.CSS_UNITS }); const textLayerFactory = this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE ? this : null; + const xfaLayerFactory = isPureXfa ? this : null; for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { const pageView = new _pdf_page_view.PDFPageView({ @@ -9733,16 +10185,16 @@ class BaseViewer { id: pageNum, scale, defaultViewport: viewport.clone(), - annotationStorage, optionalContentConfigPromise, renderingQueue: this.renderingQueue, textLayerFactory, textLayerMode: this.textLayerMode, annotationLayerFactory: this, + xfaLayerFactory, + structTreeLayerFactory: this, imageResourcesPath: this.imageResourcesPath, renderInteractiveForms: this.renderInteractiveForms, renderer: this.renderer, - enableWebGL: this.enableWebGL, useOnlyCssZoom: this.useOnlyCssZoom, maxCanvasPixels: this.maxCanvasPixels, l10n: this.l10n @@ -9767,6 +10219,10 @@ class BaseViewer { this.findController.setDocument(pdfDocument); } + if (this.enableScripting) { + this._scriptingManager.setDocument(pdfDocument); + } + if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > 7500) { this._pagesCapability.resolve(); @@ -9831,9 +10287,7 @@ class BaseViewer { } for (let i = 0, ii = this._pages.length; i < ii; i++) { - const pageView = this._pages[i]; - const label = this._pageLabels && this._pageLabels[i]; - pageView.setPageLabel(label); + this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); } } @@ -9937,6 +10391,14 @@ class BaseViewer { } } + get _pageWidthScaleFactor() { + if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL && !this.isInPresentationMode) { + return 2; + } + + return 1; + } + _setScale(value, noScroll = false) { let scale = parseFloat(value); @@ -9957,7 +10419,7 @@ class BaseViewer { [hPadding, vPadding] = [vPadding, hPadding]; } - const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale; + const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this._pageWidthScaleFactor; const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; switch (value) { @@ -10003,6 +10465,20 @@ class BaseViewer { }); } + pageLabelToPageNumber(label) { + if (!this._pageLabels) { + return null; + } + + const i = this._pageLabels.indexOf(label); + + if (i < 0) { + return null; + } + + return i + 1; + } + scrollPageIntoView({ pageNumber, destArray = null, @@ -10059,6 +10535,8 @@ class BaseViewer { if (y === null && this._location) { x = this._location.left; y = this._location.top; + } else if (typeof y !== "number") { + y = pageHeight; } break; @@ -10189,6 +10667,10 @@ class BaseViewer { return this.isInPresentationMode ? false : this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL; } + get _isContainerRtl() { + return getComputedStyle(this.container).direction === "rtl"; + } + get isInPresentationMode() { return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN; } @@ -10228,7 +10710,13 @@ class BaseViewer { } _getVisiblePages() { - return (0, _ui_utils.getVisibleElements)(this.container, this._pages, true, this._isScrollModeHorizontal); + return (0, _ui_utils.getVisibleElements)({ + scrollEl: this.container, + views: this._pages, + sortByVisibility: true, + horizontal: this._isScrollModeHorizontal, + rtl: this._isScrollModeHorizontal && this._isContainerRtl + }); } isPageVisible(pageNumber) { @@ -10236,8 +10724,8 @@ class BaseViewer { return false; } - if (pageNumber < 1 || pageNumber > this.pagesCount) { - console.error(`${this._name}.isPageVisible: "${pageNumber}" is out of bounds.`); + if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { + console.error(`${this._name}.isPageVisible: "${pageNumber}" is not a valid page.`); return false; } @@ -10246,6 +10734,25 @@ class BaseViewer { }); } + isPageCached(pageNumber) { + if (!this.pdfDocument || !this._buffer) { + return false; + } + + if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { + console.error(`${this._name}.isPageCached: "${pageNumber}" is not a valid page.`); + return false; + } + + const pageView = this._pages[pageNumber - 1]; + + if (!pageView) { + return false; + } + + return this._buffer.has(pageView); + } + cleanup() { for (let i = 0, ii = this._pages.length; i < ii; i++) { if (this._pages[i] && this._pages[i].renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) { @@ -10318,16 +10825,33 @@ class BaseViewer { }); } - createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = false, l10n = _ui_utils.NullL10n) { + createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = false, l10n = _l10n_utils.NullL10n, enableScripting = null, hasJSActionsPromise = null, mouseState = null) { return new _annotation_layer_builder.AnnotationLayerBuilder({ pageDiv, pdfPage, - annotationStorage, + annotationStorage: annotationStorage || this.pdfDocument?.annotationStorage, imageResourcesPath, renderInteractiveForms, linkService: this.linkService, downloadManager: this.downloadManager, - l10n + l10n, + enableScripting: enableScripting ?? this.enableScripting, + hasJSActionsPromise: hasJSActionsPromise || this.pdfDocument?.hasJSActions(), + mouseState: mouseState || this._scriptingManager?.mouseState + }); + } + + createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null) { + return new _xfa_layer_builder.XfaLayerBuilder({ + pageDiv, + pdfPage, + annotationStorage: annotationStorage || this.pdfDocument?.annotationStorage + }); + } + + createStructTreeLayerBuilder(pdfPage) { + return new _struct_tree_layer_builder.StructTreeLayerBuilder({ + pdfPage }); } @@ -10346,30 +10870,23 @@ class BaseViewer { } getPagesOverview() { - const pagesOverview = this._pages.map(function (pageView) { + return this._pages.map(pageView => { const viewport = pageView.pdfPage.getViewport({ scale: 1 }); - return { - width: viewport.width, - height: viewport.height, - rotation: viewport.rotation - }; - }); - if (!this.enablePrintAutoRotate) { - return pagesOverview; - } - - return pagesOverview.map(function (size) { - if ((0, _ui_utils.isPortraitOrientation)(size)) { - return size; + if (!this.enablePrintAutoRotate || (0, _ui_utils.isPortraitOrientation)(viewport)) { + return { + width: viewport.width, + height: viewport.height, + rotation: viewport.rotation + }; } return { - width: size.height, - height: size.width, - rotation: (size.rotation + 90) % 360 + width: viewport.height, + height: viewport.width, + rotation: (viewport.rotation - 90) % 360 }; }); } @@ -10510,32 +11027,192 @@ class BaseViewer { return; } + if (this._currentScaleValue && isNaN(this._currentScaleValue)) { + this._setScale(this._currentScaleValue, true); + } + this._setCurrentPageNumber(pageNumber, true); this.update(); } + _getPageAdvance(currentPageNumber, previous = false) { + if (this.isInPresentationMode) { + return 1; + } + + switch (this._scrollMode) { + case _ui_utils.ScrollMode.WRAPPED: + { + const { + views + } = this._getVisiblePages(), + pageLayout = new Map(); + + for (const { + id, + y, + percent, + widthPercent + } of views) { + if (percent === 0 || widthPercent < 100) { + continue; + } + + let yArray = pageLayout.get(y); + + if (!yArray) { + pageLayout.set(y, yArray || (yArray = [])); + } + + yArray.push(id); + } + + for (const yArray of pageLayout.values()) { + const currentIndex = yArray.indexOf(currentPageNumber); + + if (currentIndex === -1) { + continue; + } + + const numPages = yArray.length; + + if (numPages === 1) { + break; + } + + if (previous) { + for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { + const currentId = yArray[i], + expectedId = yArray[i + 1] - 1; + + if (currentId < expectedId) { + return currentPageNumber - expectedId; + } + } + } else { + for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { + const currentId = yArray[i], + expectedId = yArray[i - 1] + 1; + + if (currentId > expectedId) { + return expectedId - currentPageNumber; + } + } + } + + if (previous) { + const firstId = yArray[0]; + + if (firstId < currentPageNumber) { + return currentPageNumber - firstId + 1; + } + } else { + const lastId = yArray[numPages - 1]; + + if (lastId > currentPageNumber) { + return lastId - currentPageNumber + 1; + } + } + + break; + } + + break; + } + + case _ui_utils.ScrollMode.HORIZONTAL: + { + break; + } + + case _ui_utils.ScrollMode.VERTICAL: + { + if (this._spreadMode === _ui_utils.SpreadMode.NONE) { + break; + } + + const parity = this._spreadMode - 1; + + if (previous && currentPageNumber % 2 !== parity) { + break; + } else if (!previous && currentPageNumber % 2 === parity) { + break; + } + + const { + views + } = this._getVisiblePages(), + expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; + + for (const { + id, + percent, + widthPercent + } of views) { + if (id !== expectedId) { + continue; + } + + if (percent > 0 && widthPercent === 100) { + return 2; + } + + break; + } + + break; + } + } + + return 1; + } + + nextPage() { + const currentPageNumber = this._currentPageNumber, + pagesCount = this.pagesCount; + + if (currentPageNumber >= pagesCount) { + return false; + } + + const advance = this._getPageAdvance(currentPageNumber, false) || 1; + this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); + return true; + } + + previousPage() { + const currentPageNumber = this._currentPageNumber; + + if (currentPageNumber <= 1) { + return false; + } + + const advance = this._getPageAdvance(currentPageNumber, true) || 1; + this.currentPageNumber = Math.max(currentPageNumber - advance, 1); + return true; + } + } exports.BaseViewer = BaseViewer; /***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { +/* 29 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.DefaultAnnotationLayerFactory = exports.AnnotationLayerBuilder = void 0; var _pdfjsLib = __webpack_require__(5); -var _ui_utils = __webpack_require__(2); +var _l10n_utils = __webpack_require__(30); -var _pdf_link_service = __webpack_require__(20); +var _pdf_link_service = __webpack_require__(19); class AnnotationLayerBuilder { constructor({ @@ -10546,7 +11223,10 @@ class AnnotationLayerBuilder { annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = true, - l10n = _ui_utils.NullL10n + l10n = _l10n_utils.NullL10n, + enableScripting = false, + hasJSActionsPromise = null, + mouseState = null }) { this.pageDiv = pageDiv; this.pdfPage = pdfPage; @@ -10556,14 +11236,17 @@ class AnnotationLayerBuilder { this.renderInteractiveForms = renderInteractiveForms; this.l10n = l10n; this.annotationStorage = annotationStorage; + this.enableScripting = enableScripting; + this._hasJSActionsPromise = hasJSActionsPromise; + this._mouseState = mouseState; this.div = null; this._cancelled = false; } render(viewport, intent = "display") { - return this.pdfPage.getAnnotations({ + return Promise.all([this.pdfPage.getAnnotations({ intent - }).then(annotations => { + }), this._hasJSActionsPromise]).then(([annotations, hasJSActions = false]) => { if (this._cancelled) { return; } @@ -10583,7 +11266,10 @@ class AnnotationLayerBuilder { renderInteractiveForms: this.renderInteractiveForms, linkService: this.linkService, downloadManager: this.downloadManager, - annotationStorage: this.annotationStorage + annotationStorage: this.annotationStorage, + enableScripting: this.enableScripting, + hasJSActions, + mouseState: this._mouseState }; if (this.div) { @@ -10610,7 +11296,7 @@ class AnnotationLayerBuilder { return; } - this.div.setAttribute("hidden", "true"); + this.div.hidden = true; } } @@ -10618,7 +11304,7 @@ class AnnotationLayerBuilder { exports.AnnotationLayerBuilder = AnnotationLayerBuilder; class DefaultAnnotationLayerFactory { - createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = true, l10n = _ui_utils.NullL10n) { + createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = true, l10n = _l10n_utils.NullL10n, enableScripting = false, hasJSActionsPromise = null, mouseState = null) { return new AnnotationLayerBuilder({ pageDiv, pdfPage, @@ -10626,7 +11312,10 @@ class DefaultAnnotationLayerFactory { renderInteractiveForms, linkService: new _pdf_link_service.SimpleLinkService(), l10n, - annotationStorage + annotationStorage, + enableScripting, + hasJSActionsPromise, + mouseState }); } @@ -10635,24 +11324,153 @@ class DefaultAnnotationLayerFactory { exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory; /***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { +/* 30 */ +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); +exports.fixupLangCode = fixupLangCode; +exports.getL10nFallback = getL10nFallback; +exports.NullL10n = void 0; +const DEFAULT_L10N_STRINGS = { + of_pages: "of {{pagesCount}}", + page_of_pages: "({{pageNumber}} of {{pagesCount}})", + document_properties_kb: "{{size_kb}} KB ({{size_b}} bytes)", + document_properties_mb: "{{size_mb}} MB ({{size_b}} bytes)", + document_properties_date_string: "{{date}}, {{time}}", + document_properties_page_size_unit_inches: "in", + document_properties_page_size_unit_millimeters: "mm", + document_properties_page_size_orientation_portrait: "portrait", + document_properties_page_size_orientation_landscape: "landscape", + document_properties_page_size_name_a3: "A3", + document_properties_page_size_name_a4: "A4", + document_properties_page_size_name_letter: "Letter", + document_properties_page_size_name_legal: "Legal", + document_properties_page_size_dimension_string: "{{width}} × {{height}} {{unit}} ({{orientation}})", + document_properties_page_size_dimension_name_string: "{{width}} × {{height}} {{unit}} ({{name}}, {{orientation}})", + document_properties_linearized_yes: "Yes", + document_properties_linearized_no: "No", + print_progress_percent: "{{progress}}%", + "toggle_sidebar.title": "Toggle Sidebar", + "toggle_sidebar_notification2.title": "Toggle Sidebar (document contains outline/attachments/layers)", + additional_layers: "Additional Layers", + page_landmark: "Page {{page}}", + thumb_page_title: "Page {{page}}", + thumb_page_canvas: "Thumbnail of Page {{page}}", + find_reached_top: "Reached top of document, continued from bottom", + find_reached_bottom: "Reached end of document, continued from top", + "find_match_count[one]": "{{current}} of {{total}} match", + "find_match_count[other]": "{{current}} of {{total}} matches", + "find_match_count_limit[one]": "More than {{limit}} match", + "find_match_count_limit[other]": "More than {{limit}} matches", + find_not_found: "Phrase not found", + error_version_info: "PDF.js v{{version}} (build: {{build}})", + error_message: "Message: {{message}}", + error_stack: "Stack: {{stack}}", + error_file: "File: {{file}}", + error_line: "Line: {{line}}", + rendering_error: "An error occurred while rendering the page.", + page_scale_width: "Page Width", + page_scale_fit: "Page Fit", + page_scale_auto: "Automatic Zoom", + page_scale_actual: "Actual Size", + page_scale_percent: "{{scale}}%", + loading: "Loading…", + loading_error: "An error occurred while loading the PDF.", + invalid_file_error: "Invalid or corrupted PDF file.", + missing_file_error: "Missing PDF file.", + unexpected_response_error: "Unexpected server response.", + printing_not_supported: "Warning: Printing is not fully supported by this browser.", + printing_not_ready: "Warning: The PDF is not fully loaded for printing.", + web_fonts_disabled: "Web fonts are disabled: unable to use embedded PDF fonts." +}; + +function getL10nFallback(key, args) { + switch (key) { + case "find_match_count": + key = `find_match_count[${args.total === 1 ? "one" : "other"}]`; + break; + + case "find_match_count_limit": + key = `find_match_count_limit[${args.limit === 1 ? "one" : "other"}]`; + break; + } + + return DEFAULT_L10N_STRINGS[key] || ""; +} + +const PARTIAL_LANG_CODES = { + en: "en-US", + es: "es-ES", + fy: "fy-NL", + ga: "ga-IE", + gu: "gu-IN", + hi: "hi-IN", + hy: "hy-AM", + nb: "nb-NO", + ne: "ne-NP", + nn: "nn-NO", + pa: "pa-IN", + pt: "pt-PT", + sv: "sv-SE", + zh: "zh-CN" +}; + +function fixupLangCode(langCode) { + return PARTIAL_LANG_CODES[langCode?.toLowerCase()] || langCode; +} + +function formatL10nValue(text, args) { + if (!args) { + return text; + } + + return text.replace(/\{\{\s*(\w+)\s*\}\}/g, (all, name) => { + return name in args ? args[name] : "{{" + name + "}}"; + }); +} + +const NullL10n = { + async getLanguage() { + return "en-us"; + }, + + async getDirection() { + return "ltr"; + }, + + async get(key, args = null, fallback = getL10nFallback(key, args)) { + return formatL10nValue(fallback, args); + }, + + async translate(element) {} + +}; +exports.NullL10n = NullL10n; + +/***/ }), +/* 31 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); exports.PDFPageView = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); var _pdfjsLib = __webpack_require__(5); +var _l10n_utils = __webpack_require__(30); + var _pdf_rendering_queue = __webpack_require__(8); -var _viewer_compatibility = __webpack_require__(4); +var _viewer_compatibility = __webpack_require__(2); const MAX_CANVAS_PIXELS = _viewer_compatibility.viewerCompatibilityParams.maxCanvasPixels || 16777216; @@ -10668,34 +11486,42 @@ class PDFPageView { this.scale = options.scale || _ui_utils.DEFAULT_SCALE; this.viewport = defaultViewport; this.pdfPageRotate = defaultViewport.rotation; - this._annotationStorage = options.annotationStorage || null; this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; this.hasRestrictedScaling = false; this.textLayerMode = Number.isInteger(options.textLayerMode) ? options.textLayerMode : _ui_utils.TextLayerMode.ENABLE; this.imageResourcesPath = options.imageResourcesPath || ""; - this.renderInteractiveForms = typeof options.renderInteractiveForms === "boolean" ? options.renderInteractiveForms : true; + this.renderInteractiveForms = options.renderInteractiveForms !== false; this.useOnlyCssZoom = options.useOnlyCssZoom || false; this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS; this.eventBus = options.eventBus; this.renderingQueue = options.renderingQueue; this.textLayerFactory = options.textLayerFactory; this.annotationLayerFactory = options.annotationLayerFactory; + this.xfaLayerFactory = options.xfaLayerFactory; + this.structTreeLayerFactory = options.structTreeLayerFactory; this.renderer = options.renderer || _ui_utils.RendererType.CANVAS; - this.enableWebGL = options.enableWebGL || false; - this.l10n = options.l10n || _ui_utils.NullL10n; + this.l10n = options.l10n || _l10n_utils.NullL10n; this.paintTask = null; this.paintedViewportMap = new WeakMap(); this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL; this.resume = null; - this.error = null; + this._renderError = null; this.annotationLayer = null; this.textLayer = null; this.zoomLayer = null; + this.xfaLayer = null; + this.structTreeLayer = null; const div = document.createElement("div"); div.className = "page"; div.style.width = Math.floor(this.viewport.width) + "px"; div.style.height = Math.floor(this.viewport.height) + "px"; div.setAttribute("data-page-number", this.id); + div.setAttribute("role", "region"); + this.l10n.get("page_landmark", { + page: this.id + }).then(msg => { + div.setAttribute("aria-label", msg); + }); this.div = div; container.appendChild(div); } @@ -10708,7 +11534,6 @@ class PDFPageView { scale: this.scale * _ui_utils.CSS_UNITS, rotation: totalRotation }); - this.stats = pdfPage.stats; this.reset(); } @@ -10736,6 +11561,22 @@ class PDFPageView { } } + async _renderXfaLayer() { + let error = null; + + try { + await this.xfaLayer.render(this.viewport, "display"); + } catch (ex) { + error = ex; + } finally { + this.eventBus.dispatch("xfalayerrendered", { + source: this, + pageNumber: this.id, + error + }); + } + } + _resetZoomLayer(removeFromDOM = false) { if (!this.zoomLayer) { return; @@ -10753,21 +11594,32 @@ class PDFPageView { this.zoomLayer = null; } - reset(keepZoomLayer = false, keepAnnotations = false) { - this.cancelRendering(keepAnnotations); + reset({ + keepZoomLayer = false, + keepAnnotationLayer = false, + keepXfaLayer = false + } = {}) { + this.cancelRendering({ + keepAnnotationLayer, + keepXfaLayer + }); this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL; const div = this.div; div.style.width = Math.floor(this.viewport.width) + "px"; div.style.height = Math.floor(this.viewport.height) + "px"; - const childNodes = div.childNodes; - const currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null; - const currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null; + const childNodes = div.childNodes, + zoomLayerNode = keepZoomLayer && this.zoomLayer || null, + annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, + xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null; for (let i = childNodes.length - 1; i >= 0; i--) { const node = childNodes[i]; - if (currentZoomLayerNode === node || currentAnnotationNode === node) { - continue; + switch (node) { + case zoomLayerNode: + case annotationLayerNode: + case xfaLayerNode: + continue; } div.removeChild(node); @@ -10775,14 +11627,15 @@ class PDFPageView { div.removeAttribute("data-loaded"); - if (currentAnnotationNode) { + if (annotationLayerNode) { this.annotationLayer.hide(); - } else if (this.annotationLayer) { - this.annotationLayer.cancel(); - this.annotationLayer = null; } - if (!currentZoomLayerNode) { + if (xfaLayerNode) { + this.xfaLayer.hide(); + } + + if (!zoomLayerNode) { if (this.canvas) { this.paintedViewportMap.delete(this.canvas); this.canvas.width = 0; @@ -10800,6 +11653,10 @@ class PDFPageView { this.loadingIconDiv = document.createElement("div"); this.loadingIconDiv.className = "loadingIcon"; + this.loadingIconDiv.setAttribute("role", "img"); + this.l10n.get("loading").then(msg => { + this.loadingIconDiv?.setAttribute("aria-label", msg); + }); div.appendChild(this.loadingIconDiv); } @@ -10821,12 +11678,17 @@ class PDFPageView { }); if (this.svg) { - this.cssTransform(this.svg, true); + this.cssTransform({ + target: this.svg, + redrawAnnotationLayer: true, + redrawXfaLayer: true + }); this.eventBus.dispatch("pagerendered", { source: this, pageNumber: this.id, cssTransform: true, - timestamp: performance.now() + timestamp: performance.now(), + error: this._renderError }); return; } @@ -10843,30 +11705,44 @@ class PDFPageView { if (this.canvas) { if (this.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) { - this.cssTransform(this.canvas, true); + this.cssTransform({ + target: this.canvas, + redrawAnnotationLayer: true, + redrawXfaLayer: true + }); this.eventBus.dispatch("pagerendered", { source: this, pageNumber: this.id, cssTransform: true, - timestamp: performance.now() + timestamp: performance.now(), + error: this._renderError }); return; } - if (!this.zoomLayer && !this.canvas.hasAttribute("hidden")) { + if (!this.zoomLayer && !this.canvas.hidden) { this.zoomLayer = this.canvas.parentNode; this.zoomLayer.style.position = "absolute"; } } if (this.zoomLayer) { - this.cssTransform(this.zoomLayer.firstChild); + this.cssTransform({ + target: this.zoomLayer.firstChild + }); } - this.reset(true, true); + this.reset({ + keepZoomLayer: true, + keepAnnotationLayer: true, + keepXfaLayer: true + }); } - cancelRendering(keepAnnotations = false) { + cancelRendering({ + keepAnnotationLayer = false, + keepXfaLayer = false + } = {}) { if (this.paintTask) { this.paintTask.cancel(); this.paintTask = null; @@ -10879,13 +11755,28 @@ class PDFPageView { this.textLayer = null; } - if (!keepAnnotations && this.annotationLayer) { + if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { this.annotationLayer.cancel(); this.annotationLayer = null; } + + if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { + this.xfaLayer.cancel(); + this.xfaLayer = null; + } + + if (this._onTextLayerRendered) { + this.eventBus._off("textlayerrendered", this._onTextLayerRendered); + + this._onTextLayerRendered = null; + } } - cssTransform(target, redrawAnnotations = false) { + cssTransform({ + target, + redrawAnnotationLayer = false, + redrawXfaLayer = false + }) { const width = this.viewport.width; const height = this.viewport.height; const div = this.div; @@ -10901,8 +11792,7 @@ class PDFPageView { scaleY = width / height; } - const cssTransform = "rotate(" + relativeRotation + "deg) " + "scale(" + scaleX + "," + scaleY + ")"; - target.style.transform = cssTransform; + target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`; if (this.textLayer) { const textLayerViewport = this.textLayer.viewport; @@ -10942,13 +11832,17 @@ class PDFPageView { break; } - textLayerDiv.style.transform = "rotate(" + textAbsRotation + "deg) " + "scale(" + scale + ", " + scale + ") " + "translate(" + transX + ", " + transY + ")"; + textLayerDiv.style.transform = `rotate(${textAbsRotation}deg) ` + `scale(${scale}) ` + `translate(${transX}, ${transY})`; textLayerDiv.style.transformOrigin = "0% 0%"; } - if (redrawAnnotations && this.annotationLayer) { + if (redrawAnnotationLayer && this.annotationLayer) { this._renderAnnotationLayer(); } + + if (redrawXfaLayer && this.xfaLayer) { + this._renderXfaLayer(); + } } get width() { @@ -10991,7 +11885,7 @@ class PDFPageView { canvasWrapper.style.height = div.style.height; canvasWrapper.classList.add("canvasWrapper"); - if (this.annotationLayer && this.annotationLayer.div) { + if (this.annotationLayer?.div) { div.insertBefore(canvasWrapper, this.annotationLayer.div); } else { div.appendChild(canvasWrapper); @@ -11005,7 +11899,7 @@ class PDFPageView { textLayerDiv.style.width = canvasWrapper.style.width; textLayerDiv.style.height = canvasWrapper.style.height; - if (this.annotationLayer && this.annotationLayer.div) { + if (this.annotationLayer?.div) { div.insertBefore(textLayerDiv, this.annotationLayer.div); } else { div.appendChild(textLayerDiv); @@ -11015,6 +11909,11 @@ class PDFPageView { } this.textLayer = textLayer; + + if (this.xfaLayer?.div) { + div.appendChild(this.xfaLayer.div); + } + let renderContinueCallback = null; if (this.renderingQueue) { @@ -11034,16 +11933,17 @@ class PDFPageView { }; } - const finishPaintTask = async error => { + const finishPaintTask = async (error = null) => { if (paintTask === this.paintTask) { this.paintTask = null; } if (error instanceof _pdfjsLib.RenderingCancelledException) { - this.error = null; + this._renderError = null; return; } + this._renderError = error; this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED; if (this.loadingIconDiv) { @@ -11053,13 +11953,12 @@ class PDFPageView { this._resetZoomLayer(true); - this.error = error; - this.stats = pdfPage.stats; this.eventBus.dispatch("pagerendered", { source: this, pageNumber: this.id, cssTransform: false, - timestamp: performance.now() + timestamp: performance.now(), + error: this._renderError }); if (error) { @@ -11070,11 +11969,12 @@ class PDFPageView { const paintTask = this.renderer === _ui_utils.RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper); paintTask.onRenderContinue = renderContinueCallback; this.paintTask = paintTask; - const resultPromise = paintTask.promise.then(function () { - return finishPaintTask(null).then(function () { + const resultPromise = paintTask.promise.then(() => { + return finishPaintTask(null).then(() => { if (textLayer) { const readableStream = pdfPage.streamTextContent({ - normalizeWhitespace: true + normalizeWhitespace: true, + includeMarkedContent: true }); textLayer.setTextContentStream(readableStream); textLayer.render(); @@ -11086,12 +11986,54 @@ class PDFPageView { if (this.annotationLayerFactory) { if (!this.annotationLayer) { - this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, this._annotationStorage, this.imageResourcesPath, this.renderInteractiveForms, this.l10n); + this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, null, this.imageResourcesPath, this.renderInteractiveForms, this.l10n, null, null, null); } this._renderAnnotationLayer(); } + if (this.xfaLayerFactory) { + if (!this.xfaLayer) { + this.xfaLayer = this.xfaLayerFactory.createXfaLayerBuilder(div, pdfPage, null); + } + + this._renderXfaLayer(); + } + + if (this.structTreeLayerFactory && this.textLayer && this.canvas) { + this._onTextLayerRendered = event => { + if (event.pageNumber !== this.id) { + return; + } + + this.eventBus._off("textlayerrendered", this._onTextLayerRendered); + + this._onTextLayerRendered = null; + + if (!this.canvas) { + return; + } + + this.pdfPage.getStructTree().then(tree => { + if (!tree) { + return; + } + + if (!this.canvas) { + return; + } + + const treeDom = this.structTreeLayer.render(tree); + treeDom.classList.add("structTree"); + this.canvas.appendChild(treeDom); + }); + }; + + this.eventBus._on("textlayerrendered", this._onTextLayerRendered); + + this.structTreeLayer = this.structTreeLayerFactory.createStructTreeLayerBuilder(pdfPage); + } + div.setAttribute("data-loaded", true); this.eventBus.dispatch("pagerender", { source: this, @@ -11116,17 +12058,12 @@ class PDFPageView { }; const viewport = this.viewport; const canvas = document.createElement("canvas"); - this.l10n.get("page_canvas", { - page: this.id - }, "Page {{page}}").then(msg => { - canvas.setAttribute("aria-label", msg); - }); - canvas.setAttribute("hidden", "hidden"); + canvas.hidden = true; let isCanvasHidden = true; const showCanvas = function () { if (isCanvasHidden) { - canvas.removeAttribute("hidden"); + canvas.hidden = false; isCanvasHidden = false; } }; @@ -11175,7 +12112,6 @@ class PDFPageView { canvasContext: ctx, transform, viewport: this.viewport, - enableWebGL: this.enableWebGL, renderInteractiveForms: this.renderInteractiveForms, optionalContentConfigPromise: this._optionalContentConfigPromise }; @@ -11216,7 +12152,7 @@ class PDFPageView { }); const promise = pdfPage.getOperatorList().then(opList => { ensureNotCancelled(); - const svgGfx = new _pdfjsLib.SVGGraphics(pdfPage.commonObjs, pdfPage.objs); + const svgGfx = new _pdfjsLib.SVGGraphics(pdfPage.commonObjs, pdfPage.objs, _viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL); return svgGfx.getSVG(opList, actualSizeViewport).then(svg => { ensureNotCancelled(); this.svg = svg; @@ -11256,16 +12192,141 @@ class PDFPageView { exports.PDFPageView = PDFPageView; /***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { +/* 32 */ +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); -exports.DefaultTextLayerFactory = exports.TextLayerBuilder = void 0; +})); +exports.StructTreeLayerBuilder = exports.DefaultStructTreeLayerFactory = void 0; +const PDF_ROLE_TO_HTML_ROLE = { + Document: null, + DocumentFragment: null, + Part: "group", + Sect: "group", + Div: "group", + Aside: "note", + NonStruct: "none", + P: null, + H: "heading", + Title: null, + FENote: "note", + Sub: "group", + Lbl: null, + Span: null, + Em: null, + Strong: null, + Link: "link", + Annot: "note", + Form: "form", + Ruby: null, + RB: null, + RT: null, + RP: null, + Warichu: null, + WT: null, + WP: null, + L: "list", + LI: "listitem", + LBody: null, + Table: "table", + TR: "row", + TH: "columnheader", + TD: "cell", + THead: "columnheader", + TBody: null, + TFoot: null, + Caption: null, + Figure: "figure", + Formula: null, + Artifact: null +}; +const HEADING_PATTERN = /^H(\d+)$/; + +class StructTreeLayerBuilder { + constructor({ + pdfPage + }) { + this.pdfPage = pdfPage; + } + + render(structTree) { + return this._walk(structTree); + } + + _setAttributes(structElement, htmlElement) { + if (structElement.alt !== undefined) { + htmlElement.setAttribute("aria-label", structElement.alt); + } + + if (structElement.id !== undefined) { + htmlElement.setAttribute("aria-owns", structElement.id); + } + } + + _walk(node) { + if (!node) { + return null; + } + + const element = document.createElement("span"); + + if ("role" in node) { + const { + role + } = node; + const match = role.match(HEADING_PATTERN); + + if (match) { + element.setAttribute("role", "heading"); + element.setAttribute("aria-level", match[1]); + } else if (PDF_ROLE_TO_HTML_ROLE[role]) { + element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); + } + } + + this._setAttributes(node, element); + + if (node.children) { + if (node.children.length === 1 && "id" in node.children[0]) { + this._setAttributes(node.children[0], element); + } else { + for (const kid of node.children) { + element.appendChild(this._walk(kid)); + } + } + } + + return element; + } + +} + +exports.StructTreeLayerBuilder = StructTreeLayerBuilder; + +class DefaultStructTreeLayerFactory { + createStructTreeLayerBuilder(pdfPage) { + return new StructTreeLayerBuilder({ + pdfPage + }); + } + +} + +exports.DefaultStructTreeLayerFactory = DefaultStructTreeLayerFactory; + +/***/ }), +/* 33 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TextLayerBuilder = exports.DefaultTextLayerFactory = void 0; var _pdfjsLib = __webpack_require__(5); @@ -11381,13 +12442,11 @@ class TextLayerBuilder { } const { - findController, textContentItemsStr } = this; let i = 0, iIndex = 0; const end = textContentItemsStr.length - 1; - const queryLen = findController.state.query.length; const result = []; for (let m = 0, mm = matches.length; m < mm; m++) { @@ -11408,12 +12467,7 @@ class TextLayerBuilder { offset: matchIdx - iIndex } }; - - if (matchesLength) { - matchIdx += matchesLength[m]; - } else { - matchIdx += queryLen; - } + matchIdx += matchesLength[m]; while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { iIndex += textContentItemsStr[i].length; @@ -11453,7 +12507,7 @@ class TextLayerBuilder { function beginText(begin, className) { const divIdx = begin.divIdx; textDivs[divIdx].textContent = ""; - appendTextToDiv(divIdx, 0, begin.offset, className); + return appendTextToDiv(divIdx, 0, begin.offset, className); } function appendTextToDiv(divIdx, fromOffset, toOffset, className) { @@ -11463,13 +12517,14 @@ class TextLayerBuilder { if (className) { const span = document.createElement("span"); - span.className = className; + span.className = `${className} appended`; span.appendChild(node); div.appendChild(span); - return; + return className.includes("selected") ? span.offsetLeft : 0; } div.appendChild(node); + return 0; } let i0 = selectedMatchIdx, @@ -11488,14 +12543,7 @@ class TextLayerBuilder { const end = match.end; const isSelected = isSelectedPage && i === selectedMatchIdx; const highlightSuffix = isSelected ? " selected" : ""; - - if (isSelected) { - findController.scrollMatchIntoView({ - element: textDivs[begin.divIdx], - pageIndex: pageIdx, - matchIndex: selectedMatchIdx - }); - } + let selectedLeft = 0; if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { if (prevEnd !== null) { @@ -11508,9 +12556,9 @@ class TextLayerBuilder { } if (begin.divIdx === end.divIdx) { - appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); + selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); } else { - appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); + selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { textDivs[n0].className = "highlight middle" + highlightSuffix; @@ -11520,6 +12568,15 @@ class TextLayerBuilder { } prevEnd = end; + + if (isSelected) { + findController.scrollMatchIntoView({ + element: textDivs[begin.divIdx], + selectedLeft, + pageIndex: pageIdx, + matchIndex: selectedMatchIdx + }); + } } if (prevEnd) { @@ -11554,7 +12611,7 @@ class TextLayerBuilder { clearedUntilDivIdx = match.end.divIdx + 1; } - if (!findController || !findController.highlightMatches) { + if (!findController?.highlightMatches) { return; } @@ -11640,22 +12697,130 @@ class DefaultTextLayerFactory { exports.DefaultTextLayerFactory = DefaultTextLayerFactory; /***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { +/* 34 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); +exports.XfaLayerBuilder = exports.DefaultXfaLayerFactory = void 0; + +var _pdfjsLib = __webpack_require__(5); + +class XfaLayerBuilder { + constructor({ + pageDiv, + pdfPage, + xfaHtml, + annotationStorage + }) { + this.pageDiv = pageDiv; + this.pdfPage = pdfPage; + this.xfaHtml = xfaHtml; + this.annotationStorage = annotationStorage; + this.div = null; + this._cancelled = false; + } + + render(viewport, intent = "display") { + if (intent === "print") { + const parameters = { + viewport: viewport.clone({ + dontFlip: true + }), + div: this.div, + xfa: this.xfaHtml, + page: null, + annotationStorage: this.annotationStorage, + intent + }; + const div = document.createElement("div"); + this.pageDiv.appendChild(div); + parameters.div = div; + + _pdfjsLib.XfaLayer.render(parameters); + + return Promise.resolve(); + } + + return this.pdfPage.getXfa().then(xfa => { + if (this._cancelled) { + return; + } + + const parameters = { + viewport: viewport.clone({ + dontFlip: true + }), + div: this.div, + xfa, + page: this.pdfPage, + annotationStorage: this.annotationStorage, + intent + }; + + if (this.div) { + _pdfjsLib.XfaLayer.update(parameters); + } else { + this.div = document.createElement("div"); + this.pageDiv.appendChild(this.div); + parameters.div = this.div; + + _pdfjsLib.XfaLayer.render(parameters); + } + }).catch(error => { + console.error(error); + }); + } + + cancel() { + this._cancelled = true; + } + + hide() { + if (!this.div) { + return; + } + + this.div.hidden = true; + } + +} + +exports.XfaLayerBuilder = XfaLayerBuilder; + +class DefaultXfaLayerFactory { + createXfaLayerBuilder(pageDiv, pdfPage, annotationStorage = null, xfaHtml = null) { + return new XfaLayerBuilder({ + pageDiv, + pdfPage, + annotationStorage, + xfaHtml + }); + } + +} + +exports.DefaultXfaLayerFactory = DefaultXfaLayerFactory; + +/***/ }), +/* 35 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); exports.SecondaryToolbar = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); var _pdf_cursor_tools = __webpack_require__(6); -var _pdf_single_page_viewer = __webpack_require__(32); +var _pdf_single_page_viewer = __webpack_require__(36); class SecondaryToolbar { constructor(options, mainContainer, eventBus) { @@ -11917,6 +13082,7 @@ class SecondaryToolbar { this._setMaxHeight(); this.toggleButton.classList.add("toggled"); + this.toggleButton.setAttribute("aria-expanded", "true"); this.toolbar.classList.remove("hidden"); } @@ -11928,6 +13094,7 @@ class SecondaryToolbar { this.opened = false; this.toolbar.classList.add("hidden"); this.toggleButton.classList.remove("toggled"); + this.toggleButton.setAttribute("aria-expanded", "false"); } toggle() { @@ -11958,18 +13125,17 @@ class SecondaryToolbar { exports.SecondaryToolbar = SecondaryToolbar; /***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { +/* 36 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.PDFSinglePageViewer = void 0; -var _base_viewer = __webpack_require__(27); +var _base_viewer = __webpack_require__(28); var _pdfjsLib = __webpack_require__(5); @@ -11986,6 +13152,10 @@ class PDFSinglePageViewer extends _base_viewer.BaseViewer { return (0, _pdfjsLib.shadow)(this, "_viewerElement", this._shadowViewer); } + get _pageWidthScaleFactor() { + return 1; + } + _resetView() { super._resetView(); @@ -12075,30 +13245,33 @@ class PDFSinglePageViewer extends _base_viewer.BaseViewer { _updateSpreadMode() {} + _getPageAdvance() { + return 1; + } + } exports.PDFSinglePageViewer = PDFSinglePageViewer; /***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { +/* 37 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.Toolbar = void 0; -var _ui_utils = __webpack_require__(2); +var _ui_utils = __webpack_require__(4); const PAGE_NUMBER_LOADING_INDICATOR = "visiblePageIsLoading"; const SCALE_SELECT_CONTAINER_WIDTH = 140; const SCALE_SELECT_WIDTH = 162; class Toolbar { - constructor(options, eventBus, l10n = _ui_utils.NullL10n) { + constructor(options, eventBus, l10n) { this.toolbar = options.container; this.eventBus = eventBus; this.l10n = l10n; @@ -12220,6 +13393,13 @@ class Toolbar { value: this.value }); }); + scaleSelect.addEventListener("click", function (evt) { + const target = evt.target; + + if (this.value === self.pageScaleValue && target.tagName.toUpperCase() === "OPTION") { + this.blur(); + } + }); scaleSelect.oncontextmenu = _ui_utils.noContextMenuHandler; this.eventBus._on("localized", () => { @@ -12251,7 +13431,7 @@ class Toolbar { items.pageNumber.type = "number"; this.l10n.get("of_pages", { pagesCount - }, "of {{pagesCount}}").then(msg => { + }).then(msg => { items.numPages.textContent = msg; }); } @@ -12264,7 +13444,7 @@ class Toolbar { this.l10n.get("page_of_pages", { pageNumber, pagesCount - }, "({{pageNumber}} of {{pagesCount}})").then(msg => { + }).then(msg => { items.numPages.textContent = msg; }); } else { @@ -12275,10 +13455,9 @@ class Toolbar { items.next.disabled = pageNumber >= pagesCount; items.zoomOut.disabled = pageScale <= _ui_utils.MIN_SCALE; items.zoomIn.disabled = pageScale >= _ui_utils.MAX_SCALE; - const customScale = Math.round(pageScale * 10000) / 100; this.l10n.get("page_scale_percent", { - scale: customScale - }, "{{scale}}%").then(msg => { + scale: Math.round(pageScale * 10000) / 100 + }).then(msg => { let predefinedValueFound = false; for (const option of items.scaleSelect.options) { @@ -12308,7 +13487,7 @@ class Toolbar { items, l10n } = this; - const predefinedValuesPromise = Promise.all([l10n.get("page_scale_auto", null, "Automatic Zoom"), l10n.get("page_scale_actual", null, "Actual Size"), l10n.get("page_scale_fit", null, "Page Fit"), l10n.get("page_scale_width", null, "Page Width")]); + const predefinedValuesPromise = Promise.all([l10n.get("page_scale_auto"), l10n.get("page_scale_actual"), l10n.get("page_scale_fit"), l10n.get("page_scale_width")]); let canvas = document.createElement("canvas"); canvas.mozOpaque = true; let ctx = canvas.getContext("2d", { @@ -12350,15 +13529,14 @@ class Toolbar { exports.Toolbar = Toolbar; /***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { +/* 38 */ +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.ViewHistory = void 0; const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20; @@ -12446,24 +13624,25 @@ class ViewHistory { exports.ViewHistory = ViewHistory; /***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { +/* 39 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.GenericCom = void 0; -var _app = __webpack_require__(1); +var _app = __webpack_require__(3); + +var _preferences = __webpack_require__(40); -var _preferences = __webpack_require__(36); +var _download_manager = __webpack_require__(41); -var _download_manager = __webpack_require__(37); +var _genericl10n = __webpack_require__(42); -var _genericl10n = __webpack_require__(38); +var _generic_scripting = __webpack_require__(44); ; const GenericCom = {}; @@ -12482,7 +13661,7 @@ class GenericPreferences extends _preferences.BasePreferences { class GenericExternalServices extends _app.DefaultExternalServices { static createDownloadManager(options) { - return new _download_manager.DownloadManager(options); + return new _download_manager.DownloadManager(); } static createPreferences() { @@ -12495,56 +13674,28 @@ class GenericExternalServices extends _app.DefaultExternalServices { return new _genericl10n.GenericL10n(locale); } + static createScripting({ + sandboxBundleSrc + }) { + return new _generic_scripting.GenericScripting(sandboxBundleSrc); + } + } _app.PDFViewerApplication.externalServices = GenericExternalServices; /***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { +/* 40 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.BasePreferences = void 0; -var _app_options = __webpack_require__(3); - -let defaultPreferences = null; - -function getDefaultPreferences() { - if (!defaultPreferences) { - defaultPreferences = Promise.resolve({ - "cursorToolOnLoad": 0, - "defaultZoomValue": "", - "disablePageLabels": false, - "enablePermissions": false, - "enablePrintAutoRotate": false, - "enableWebGL": false, - "externalLinkTarget": 0, - "historyUpdateUrl": false, - "ignoreDestinationZoom": false, - "pdfBugEnabled": false, - "renderer": "canvas", - "renderInteractiveForms": true, - "sidebarViewOnLoad": -1, - "scrollModeOnLoad": -1, - "spreadModeOnLoad": -1, - "textLayerMode": 1, - "useOnlyCssZoom": false, - "viewOnLoad": 0, - "disableAutoFetch": false, - "disableFontFace": false, - "disableRange": false, - "disableStream": false - }); - } - - return defaultPreferences; -} +var _app_options = __webpack_require__(1); class BasePreferences { constructor() { @@ -12552,30 +13703,45 @@ class BasePreferences { throw new Error("Cannot initialize BasePreferences."); } - this.prefs = null; - this._initializedPromise = getDefaultPreferences().then(defaults => { - Object.defineProperty(this, "defaults", { - value: Object.freeze(defaults), - writable: false, - enumerable: true, - configurable: false - }); - this.prefs = Object.assign(Object.create(null), defaults); - return this._readFromStorage(defaults); - }).then(prefs => { - if (!prefs) { - return; - } - - for (const name in prefs) { - const defaultValue = this.defaults[name], - prefValue = prefs[name]; + Object.defineProperty(this, "defaults", { + value: Object.freeze({ + "cursorToolOnLoad": 0, + "defaultZoomValue": "", + "disablePageLabels": false, + "enablePermissions": false, + "enablePrintAutoRotate": true, + "enableScripting": true, + "externalLinkTarget": 0, + "historyUpdateUrl": false, + "ignoreDestinationZoom": false, + "pdfBugEnabled": false, + "renderer": "canvas", + "renderInteractiveForms": true, + "sidebarViewOnLoad": -1, + "scrollModeOnLoad": -1, + "spreadModeOnLoad": -1, + "textLayerMode": 1, + "useOnlyCssZoom": false, + "viewerCssTheme": 0, + "viewOnLoad": 0, + "disableAutoFetch": false, + "disableFontFace": false, + "disableRange": false, + "disableStream": false, + "enableXfa": false + }), + writable: false, + enumerable: true, + configurable: false + }); + this.prefs = Object.create(null); + this._initializedPromise = this._readFromStorage(this.defaults).then(prefs => { + for (const name in this.defaults) { + const prefValue = prefs?.[name]; - if (defaultValue === undefined || typeof prefValue !== typeof defaultValue) { - continue; + if (typeof prefValue === typeof this.defaults[name]) { + this.prefs[name] = prefValue; } - - this.prefs[name] = prefValue; } }); } @@ -12590,7 +13756,7 @@ class BasePreferences { async reset() { await this._initializedPromise; - this.prefs = Object.assign(Object.create(null), this.defaults); + this.prefs = Object.create(null); return this._writeToStorage(this.defaults); } @@ -12611,7 +13777,7 @@ class BasePreferences { if (valueType === "number" && defaultType === "string") { value = value.toString(); } else { - throw new Error(`Set preference: "${value}" is a ${valueType}, ` + `expected a ${defaultType}.`); + throw new Error(`Set preference: "${value}" is a ${valueType}, expected a ${defaultType}.`); } } else { if (valueType === "number" && !Number.isInteger(value)) { @@ -12625,24 +13791,26 @@ class BasePreferences { async get(name) { await this._initializedPromise; - const defaultValue = this.defaults[name]; + const defaultValue = this.defaults[name], + prefValue = this.prefs[name]; if (defaultValue === undefined) { throw new Error(`Get preference: "${name}" is undefined.`); - } else { - const prefValue = this.prefs[name]; - - if (prefValue !== undefined) { - return prefValue; - } } - return defaultValue; + return prefValue !== undefined ? prefValue : defaultValue; } async getAll() { await this._initializedPromise; - return Object.assign(Object.create(null), this.defaults, this.prefs); + const obj = Object.create(null); + + for (const name in this.defaults) { + const prefValue = this.prefs[name]; + obj[name] = prefValue !== undefined ? prefValue : this.defaults[name]; + } + + return obj; } } @@ -12650,20 +13818,19 @@ class BasePreferences { exports.BasePreferences = BasePreferences; /***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { +/* 41 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.DownloadManager = void 0; var _pdfjsLib = __webpack_require__(5); -var _viewer_compatibility = __webpack_require__(4); +var _viewer_compatibility = __webpack_require__(2); ; @@ -12687,6 +13854,10 @@ function download(blobUrl, filename) { } class DownloadManager { + constructor() { + this._openBlobUrls = new WeakMap(); + } + downloadUrl(url, filename) { if (!(0, _pdfjsLib.createValidAbsoluteUrl)(url, "http://example.com")) { return; @@ -12696,26 +13867,44 @@ class DownloadManager { } downloadData(data, filename, contentType) { - if (navigator.msSaveBlob) { - navigator.msSaveBlob(new Blob([data], { - type: contentType - }), filename); - return; - } - const blobUrl = (0, _pdfjsLib.createObjectURL)(data, contentType, _viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL); download(blobUrl, filename); } - download(blob, url, filename, sourceEventType = "download") { - if (navigator.msSaveBlob) { - if (!navigator.msSaveBlob(blob, filename)) { - this.downloadUrl(url, filename); + openOrDownloadData(element, data, filename) { + const isPdfData = (0, _pdfjsLib.isPdfFile)(filename); + const contentType = isPdfData ? "application/pdf" : ""; + + if (isPdfData && !_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) { + let blobUrl = this._openBlobUrls.get(element); + + if (!blobUrl) { + blobUrl = URL.createObjectURL(new Blob([data], { + type: contentType + })); + + this._openBlobUrls.set(element, blobUrl); } - return; + let viewerUrl; + viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename); + + try { + window.open(viewerUrl); + return true; + } catch (ex) { + console.error(`openOrDownloadData: ${ex}`); + URL.revokeObjectURL(blobUrl); + + this._openBlobUrls.delete(element); + } } + this.downloadData(data, filename, contentType); + return false; + } + + download(blob, url, filename, sourceEventType = "download") { if (_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) { this.downloadUrl(url, filename); return; @@ -12730,18 +13919,19 @@ class DownloadManager { exports.DownloadManager = DownloadManager; /***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { +/* 42 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); exports.GenericL10n = void 0; -__webpack_require__(39); +__webpack_require__(43); + +var _l10n_utils = __webpack_require__(30); const webL10n = document.webL10n; @@ -12749,7 +13939,7 @@ class GenericL10n { constructor(lang) { this._lang = lang; this._ready = new Promise((resolve, reject) => { - webL10n.setLanguage(lang, () => { + webL10n.setLanguage((0, _l10n_utils.fixupLangCode)(lang), () => { resolve(webL10n); }); }); @@ -12765,9 +13955,9 @@ class GenericL10n { return l10n.getDirection(); } - async get(property, args, fallback) { + async get(key, args = null, fallback = (0, _l10n_utils.getL10nFallback)(key, args)) { const l10n = await this._ready; - return l10n.get(property, args, fallback); + return l10n.get(key, args, fallback); } async translate(element) { @@ -12780,10 +13970,9 @@ class GenericL10n { exports.GenericL10n = GenericL10n; /***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { +/* 43 */ +/***/ (() => { -"use strict"; document.webL10n = function (window, document, undefined) { @@ -13603,22 +14792,89 @@ document.webL10n = function (window, document, undefined) { }(window, document); /***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { +/* 44 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", { +Object.defineProperty(exports, "__esModule", ({ value: true -}); +})); +exports.docPropertiesLookup = docPropertiesLookup; +exports.GenericScripting = void 0; + +var _pdfjsLib = __webpack_require__(5); + +async function docPropertiesLookup(pdfDocument) { + const url = "", + baseUrl = url.split("#")[0]; + let { + info, + metadata, + contentDispositionFilename, + contentLength + } = await pdfDocument.getMetadata(); + + if (!contentLength) { + const { + length + } = await pdfDocument.getDownloadInfo(); + contentLength = length; + } + + return { ...info, + baseURL: baseUrl, + filesize: contentLength, + filename: contentDispositionFilename || (0, _pdfjsLib.getPdfFilenameFromUrl)(url), + metadata: metadata?.getRaw(), + authors: metadata?.get("dc:creator"), + numPages: pdfDocument.numPages, + URL: url + }; +} + +class GenericScripting { + constructor(sandboxBundleSrc) { + this._ready = (0, _pdfjsLib.loadScript)(sandboxBundleSrc, true).then(() => { + return window.pdfjsSandbox.QuickJSSandbox(); + }); + } + + async createSandbox(data) { + const sandbox = await this._ready; + sandbox.create(data); + } + + async dispatchEventInSandbox(event) { + const sandbox = await this._ready; + sandbox.dispatchEvent(event); + } + + async destroySandbox() { + const sandbox = await this._ready; + sandbox.nukeSandbox(); + } + +} + +exports.GenericScripting = GenericScripting; + +/***/ }), +/* 45 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); exports.PDFPrintService = PDFPrintService; -var _ui_utils = __webpack_require__(2); +var _app = __webpack_require__(3); -var _app = __webpack_require__(1); +var _print_utils = __webpack_require__(46); -var _viewer_compatibility = __webpack_require__(4); +var _viewer_compatibility = __webpack_require__(2); let activeService = null; let overlayManager = null; @@ -13628,8 +14884,6 @@ function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printRe const PRINT_UNITS = printResolution / 72.0; scratchCanvas.width = Math.floor(size.width * PRINT_UNITS); scratchCanvas.height = Math.floor(size.height * PRINT_UNITS); - const width = Math.floor(size.width * _ui_utils.CSS_UNITS) + "px"; - const height = Math.floor(size.height * _ui_utils.CSS_UNITS) + "px"; const ctx = scratchCanvas.getContext("2d"); ctx.save(); ctx.fillStyle = "rgb(255, 255, 255)"; @@ -13644,15 +14898,10 @@ function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printRe rotation: size.rotation }), intent: "print", - annotationStorage: pdfDocument.annotationStorage, + includeAnnotationStorage: true, optionalContentConfigPromise }; return pdfPage.render(renderContext).promise; - }).then(function () { - return { - width, - height - }; }); } @@ -13662,7 +14911,7 @@ function PDFPrintService(pdfDocument, pagesOverview, printContainer, printResolu this.printContainer = printContainer; this._printResolution = printResolution || 150; this._optionalContentConfigPromise = optionalContentConfigPromise || pdfDocument.getOptionalContentConfig(); - this.l10n = l10n || _ui_utils.NullL10n; + this.l10n = l10n; this.currentPage = -1; this.scratchCanvas = document.createElement("canvas"); } @@ -13682,7 +14931,7 @@ PDFPrintService.prototype = { this.pageStyleSheet = document.createElement("style"); const pageSize = this.pagesOverview[0]; - this.pageStyleSheet.textContent = "@supports ((size:A4) and (size:1pt 1pt)) {" + "@page { size: " + pageSize.width + "pt " + pageSize.height + "pt;}" + "}"; + this.pageStyleSheet.textContent = "@page { size: " + pageSize.width + "pt " + pageSize.height + "pt;}"; body.appendChild(this.pageStyleSheet); }, @@ -13713,6 +14962,11 @@ PDFPrintService.prototype = { }, renderPages() { + if (this.pdfDocument.isPureXfa) { + (0, _print_utils.getXfaHtmlForPrinting)(this.printContainer, this.pdfDocument); + return Promise.resolve(); + } + const pageCount = this.pagesOverview.length; const renderNextPage = (resolve, reject) => { @@ -13734,11 +14988,9 @@ PDFPrintService.prototype = { return new Promise(renderNextPage); }, - useRenderedPage(printItem) { + useRenderedPage() { this.throwIfInactive(); const img = document.createElement("img"); - img.style.width = printItem.width; - img.style.height = printItem.height; const scratchCanvas = this.scratchCanvas; if ("toBlob" in scratchCanvas && !_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) { @@ -13750,6 +15002,7 @@ PDFPrintService.prototype = { } const wrapper = document.createElement("div"); + wrapper.className = "printedPage"; wrapper.appendChild(img); this.printContainer.appendChild(wrapper); return new Promise(function (resolve, reject) { @@ -13843,7 +15096,7 @@ function renderProgress(index, total, l10n) { progressBar.value = progress; l10n.get("print_progress_percent", { progress - }, progress + "%").then(msg => { + }).then(msg => { progressPerc.textContent = msg; }); } @@ -13903,6 +15156,259 @@ _app.PDFPrintServiceFactory.instance = { }; +/***/ }), +/* 46 */ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getXfaHtmlForPrinting = getXfaHtmlForPrinting; + +var _ui_utils = __webpack_require__(4); + +var _xfa_layer_builder = __webpack_require__(34); + +var _pdfjsLib = __webpack_require__(5); + +function getXfaHtmlForPrinting(printContainer, pdfDocument) { + const xfaHtml = pdfDocument.allXfaHtml; + const factory = new _xfa_layer_builder.DefaultXfaLayerFactory(); + const scale = Math.round(_ui_utils.CSS_UNITS * 100) / 100; + + for (const xfaPage of xfaHtml.children) { + const page = document.createElement("div"); + page.className = "xfaPrintedPage"; + printContainer.appendChild(page); + const builder = factory.createXfaLayerBuilder(page, null, pdfDocument.annotationStorage, xfaPage); + const viewport = (0, _pdfjsLib.getXfaPageViewport)(xfaPage, { + scale + }); + builder.render(viewport, "print"); + } +} + /***/ }) -/******/ ]); +/******/ ]); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. +(() => { +var exports = __webpack_exports__; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "PDFViewerApplicationOptions", ({ + enumerable: true, + get: function () { + return _app_options.AppOptions; + } +})); +Object.defineProperty(exports, "PDFViewerApplication", ({ + enumerable: true, + get: function () { + return _app.PDFViewerApplication; + } +})); + +var _app_options = __webpack_require__(1); + +var _app = __webpack_require__(3); + +const pdfjsVersion = '2.10.377'; +const pdfjsBuild = '156762c48'; +window.PDFViewerApplication = _app.PDFViewerApplication; +window.PDFViewerApplicationOptions = _app_options.AppOptions; +; +; +{ + __webpack_require__(39); +} +; +{ + __webpack_require__(45); +} + +function getViewerConfiguration() { + let errorWrapper = null; + errorWrapper = { + container: document.getElementById("errorWrapper"), + errorMessage: document.getElementById("errorMessage"), + closeButton: document.getElementById("errorClose"), + errorMoreInfo: document.getElementById("errorMoreInfo"), + moreInfoButton: document.getElementById("errorShowMore"), + lessInfoButton: document.getElementById("errorShowLess") + }; + return { + appContainer: document.body, + mainContainer: document.getElementById("viewerContainer"), + viewerContainer: document.getElementById("viewer"), + eventBus: null, + toolbar: { + container: document.getElementById("toolbarViewer"), + numPages: document.getElementById("numPages"), + pageNumber: document.getElementById("pageNumber"), + scaleSelectContainer: document.getElementById("scaleSelectContainer"), + scaleSelect: document.getElementById("scaleSelect"), + customScaleOption: document.getElementById("customScaleOption"), + previous: document.getElementById("previous"), + next: document.getElementById("next"), + zoomIn: document.getElementById("zoomIn"), + zoomOut: document.getElementById("zoomOut"), + viewFind: document.getElementById("viewFind"), + openFile: document.getElementById("openFile"), + print: document.getElementById("print"), + presentationModeButton: document.getElementById("presentationMode"), + download: document.getElementById("download"), + viewBookmark: document.getElementById("viewBookmark") + }, + secondaryToolbar: { + toolbar: document.getElementById("secondaryToolbar"), + toggleButton: document.getElementById("secondaryToolbarToggle"), + toolbarButtonContainer: document.getElementById("secondaryToolbarButtonContainer"), + presentationModeButton: document.getElementById("secondaryPresentationMode"), + openFileButton: document.getElementById("secondaryOpenFile"), + printButton: document.getElementById("secondaryPrint"), + downloadButton: document.getElementById("secondaryDownload"), + viewBookmarkButton: document.getElementById("secondaryViewBookmark"), + firstPageButton: document.getElementById("firstPage"), + lastPageButton: document.getElementById("lastPage"), + pageRotateCwButton: document.getElementById("pageRotateCw"), + pageRotateCcwButton: document.getElementById("pageRotateCcw"), + cursorSelectToolButton: document.getElementById("cursorSelectTool"), + cursorHandToolButton: document.getElementById("cursorHandTool"), + scrollVerticalButton: document.getElementById("scrollVertical"), + scrollHorizontalButton: document.getElementById("scrollHorizontal"), + scrollWrappedButton: document.getElementById("scrollWrapped"), + spreadNoneButton: document.getElementById("spreadNone"), + spreadOddButton: document.getElementById("spreadOdd"), + spreadEvenButton: document.getElementById("spreadEven"), + documentPropertiesButton: document.getElementById("documentProperties") + }, + sidebar: { + outerContainer: document.getElementById("outerContainer"), + viewerContainer: document.getElementById("viewerContainer"), + toggleButton: document.getElementById("sidebarToggle"), + thumbnailButton: document.getElementById("viewThumbnail"), + outlineButton: document.getElementById("viewOutline"), + attachmentsButton: document.getElementById("viewAttachments"), + layersButton: document.getElementById("viewLayers"), + thumbnailView: document.getElementById("thumbnailView"), + outlineView: document.getElementById("outlineView"), + attachmentsView: document.getElementById("attachmentsView"), + layersView: document.getElementById("layersView"), + outlineOptionsContainer: document.getElementById("outlineOptionsContainer"), + currentOutlineItemButton: document.getElementById("currentOutlineItem") + }, + sidebarResizer: { + outerContainer: document.getElementById("outerContainer"), + resizer: document.getElementById("sidebarResizer") + }, + findBar: { + bar: document.getElementById("findbar"), + toggleButton: document.getElementById("viewFind"), + findField: document.getElementById("findInput"), + highlightAllCheckbox: document.getElementById("findHighlightAll"), + caseSensitiveCheckbox: document.getElementById("findMatchCase"), + entireWordCheckbox: document.getElementById("findEntireWord"), + findMsg: document.getElementById("findMsg"), + findResultsCount: document.getElementById("findResultsCount"), + findPreviousButton: document.getElementById("findPrevious"), + findNextButton: document.getElementById("findNext") + }, + passwordOverlay: { + overlayName: "passwordOverlay", + container: document.getElementById("passwordOverlay"), + label: document.getElementById("passwordText"), + input: document.getElementById("password"), + submitButton: document.getElementById("passwordSubmit"), + cancelButton: document.getElementById("passwordCancel") + }, + documentProperties: { + overlayName: "documentPropertiesOverlay", + container: document.getElementById("documentPropertiesOverlay"), + closeButton: document.getElementById("documentPropertiesClose"), + fields: { + fileName: document.getElementById("fileNameField"), + fileSize: document.getElementById("fileSizeField"), + title: document.getElementById("titleField"), + author: document.getElementById("authorField"), + subject: document.getElementById("subjectField"), + keywords: document.getElementById("keywordsField"), + creationDate: document.getElementById("creationDateField"), + modificationDate: document.getElementById("modificationDateField"), + creator: document.getElementById("creatorField"), + producer: document.getElementById("producerField"), + version: document.getElementById("versionField"), + pageCount: document.getElementById("pageCountField"), + pageSize: document.getElementById("pageSizeField"), + linearized: document.getElementById("linearizedField") + } + }, + errorWrapper, + printContainer: document.getElementById("printContainer"), + openFileInputName: "fileInput", + debuggerScriptPath: "./debugger.js" + }; +} + +function webViewerLoad() { + const config = getViewerConfiguration(); + const event = document.createEvent("CustomEvent"); + event.initCustomEvent("webviewerloaded", true, true, { + source: window + }); + + try { + parent.document.dispatchEvent(event); + } catch (ex) { + console.error(`webviewerloaded: ${ex}`); + document.dispatchEvent(event); + } + + _app.PDFViewerApplication.run(config); +} + +if (document.blockUnblockOnload) { + document.blockUnblockOnload(true); +} + +if (document.readyState === "interactive" || document.readyState === "complete") { + webViewerLoad(); +} else { + document.addEventListener("DOMContentLoaded", webViewerLoad, true); +} +})(); + +/******/ })() +; //# sourceMappingURL=viewer.js.map |