From 1271c9aedbc6ed6d2b38f84b1672bf4600912f73 Mon Sep 17 00:00:00 2001 From: Updatebot Date: Sun, 5 Jun 2022 18:44:01 +0000 Subject: [PATCH] Bug 1772598 - Update PDF.js to 19539676813b5df6ca4726a1bfa6765193b1067c r=pdfjs-reviewers,Snuffleupagus Differential Revision: https://phabricator.services.mozilla.com/D148307 --- toolkit/components/pdfjs/content/build/pdf.js | 124 +++--- .../pdfjs/content/build/pdf.scripting.js | 25 +- .../pdfjs/content/build/pdf.worker.js | 219 +++++++--- .../components/pdfjs/content/web/viewer.css | 24 +- .../components/pdfjs/content/web/viewer.html | 5 - .../components/pdfjs/content/web/viewer.js | 384 +++++++++--------- toolkit/components/pdfjs/moz.yaml | 4 +- 7 files changed, 457 insertions(+), 328 deletions(-) diff --git a/toolkit/components/pdfjs/content/build/pdf.js b/toolkit/components/pdfjs/content/build/pdf.js index 84575a1968044..6666eefecf089 100644 --- a/toolkit/components/pdfjs/content/build/pdf.js +++ b/toolkit/components/pdfjs/content/build/pdf.js @@ -29,7 +29,7 @@ exports["pdfjs-dist/build/pdf"] = factory(); else root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory(); -})(this, () => { +})(globalThis, () => { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ @@ -42,7 +42,7 @@ return /******/ (() => { // webpackBootstrap Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0; +exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0; exports.arrayByteLength = arrayByteLength; exports.arraysToBytes = arraysToBytes; exports.assert = assert; @@ -75,6 +75,8 @@ const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; +const LINE_FACTOR = 1.35; +exports.LINE_FACTOR = LINE_FACTOR; const RenderingIntentFlag = { ANY: 0x01, DISPLAY: 0x02, @@ -1341,7 +1343,7 @@ async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", { docId, - apiVersion: '2.14.290', + apiVersion: '2.15.51', source: { data: source.data, url: source.url, @@ -1362,6 +1364,10 @@ async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null }); + if (source.data) { + source.data = null; + } + if (worker.destroyed) { throw new Error("Worker was destroyed"); } @@ -3365,9 +3371,9 @@ class InternalRenderTask { } -const version = '2.14.290'; +const version = '2.15.51'; exports.version = version; -const build = '38c82357b'; +const build = '195396768'; exports.build = build; /***/ }), @@ -9270,6 +9276,7 @@ var _scripting_utils = __w_pdfjs_require__(20); var _xfa_layer = __w_pdfjs_require__(21); const DEFAULT_TAB_INDEX = 1000; +const DEFAULT_FONT_SIZE = 9; const GetElementsByNameSet = new WeakSet(); function getRectDims(rect) { @@ -9470,10 +9477,10 @@ class AnnotationElement { break; } - const borderColor = data.borderColor || data.color || null; + const borderColor = data.borderColor || null; if (borderColor) { - container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); + container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); } else { container.style.borderWidth = 0; } @@ -9733,12 +9740,12 @@ class AnnotationElement { class LinkAnnotationElement extends AnnotationElement { constructor(parameters, options = null) { - const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.resetForm || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"])); super(parameters, { - isRenderable, + isRenderable: true, ignoreBorder: !!options?.ignoreBorder, createQuadrilaterals: true }); + this.isTooltipOnly = parameters.data.isTooltipOnly; } render() { @@ -9747,26 +9754,34 @@ class LinkAnnotationElement extends AnnotationElement { linkService } = this; const link = document.createElement("a"); + let isBound = false; if (data.url) { linkService.addLinkAttributes(link, data.url, data.newWindow); + isBound = true; } else if (data.action) { this._bindNamedAction(link, data.action); + + isBound = true; } else if (data.dest) { this._bindLink(link, data.dest); - } else { - let hasClickAction = false; + isBound = true; + } else { if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { - hasClickAction = true; - this._bindJSAction(link, data); + + isBound = true; } if (data.resetForm) { this._bindResetFormAction(link, data.resetForm); - } else if (!hasClickAction) { + + isBound = true; + } else if (this.isTooltipOnly && !isBound) { this._bindLink(link, ""); + + isBound = true; } } @@ -9779,7 +9794,11 @@ class LinkAnnotationElement extends AnnotationElement { } this.container.className = "linkAnnotation"; - this.container.appendChild(link); + + if (isBound) { + this.container.appendChild(link); + } + return this.container; } @@ -10054,6 +10073,31 @@ class WidgetAnnotationElement extends AnnotationElement { element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]); } + _setTextStyle(element) { + const TEXT_ALIGNMENT = ["left", "center", "right"]; + const { + fontColor + } = this.data.defaultAppearanceData; + const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE; + const style = element.style; + + if (this.data.multiLine) { + const height = Math.abs(this.data.rect[3] - this.data.rect[1]); + const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1; + const lineHeight = height / numberOfLines; + style.fontSize = `${Math.min(fontSize, Math.round(lineHeight / _util.LINE_FACTOR))}px`; + } else { + const height = Math.abs(this.data.rect[3] - this.data.rect[1]); + style.fontSize = `${Math.min(fontSize, Math.round(height / _util.LINE_FACTOR))}px`; + } + + style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); + + if (this.data.textAlignment !== null) { + style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; + } + } + } class TextWidgetAnnotationElement extends WidgetAnnotationElement { @@ -10098,10 +10142,18 @@ class TextWidgetAnnotationElement extends WidgetAnnotationElement { if (this.data.multiLine) { element = document.createElement("textarea"); element.textContent = textContent; + + if (this.data.doNotScroll) { + element.style.overflowY = "hidden"; + } } else { element = document.createElement("input"); element.type = "text"; element.setAttribute("value", textContent); + + if (this.data.doNotScroll) { + element.style.overflowX = "hidden"; + } } GetElementsByNameSet.add(element); @@ -10340,25 +10392,6 @@ class TextWidgetAnnotationElement extends WidgetAnnotationElement { return this.container; } - _setTextStyle(element) { - const TEXT_ALIGNMENT = ["left", "center", "right"]; - const { - fontSize, - fontColor - } = this.data.defaultAppearanceData; - const style = element.style; - - if (fontSize) { - style.fontSize = `${fontSize}px`; - } - - style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); - - if (this.data.textAlignment !== null) { - style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; - } - } - } class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { @@ -10581,14 +10614,7 @@ class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { const storedData = storage.getValue(id, { value: this.data.fieldValue }); - let { - fontSize - } = this.data.defaultAppearanceData; - - if (!fontSize) { - fontSize = 9; - } - + const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE; const fontSizeStyle = `calc(${fontSize}px * var(--zoom-factor))`; const selectElement = document.createElement("select"); GetElementsByNameSet.add(selectElement); @@ -10596,7 +10622,6 @@ class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { selectElement.name = this.data.fieldName; selectElement.setAttribute("id", id); selectElement.tabIndex = DEFAULT_TAB_INDEX; - selectElement.style.fontSize = `${fontSize}px`; if (!this.data.combo) { selectElement.size = this.data.options.length; @@ -10797,6 +10822,10 @@ class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { }); } + if (this.data.combo) { + this._setTextStyle(selectElement); + } else {} + this._setBackgroundColor(selectElement); this._setDefaultPropertiesFromJS(selectElement); @@ -11534,7 +11563,9 @@ class AnnotationLayer { firstChild } = element; - if (firstChild.nodeName === "CANVAS") { + if (!firstChild) { + element.appendChild(canvas); + } else if (firstChild.nodeName === "CANVAS") { element.replaceChild(canvas, firstChild); } else { element.insertBefore(canvas, firstChild); @@ -12509,7 +12540,6 @@ class TextLayerRenderTask { const canvas = this._document.createElement("canvas"); canvas.height = canvas.width = DEFAULT_FONT_SIZE; - canvas.mozOpaque = true; this._layoutTextCtx = canvas.getContext("2d", { alpha: false }); @@ -12926,8 +12956,8 @@ var _svg = __w_pdfjs_require__(23); var _xfa_layer = __w_pdfjs_require__(21); -const pdfjsVersion = '2.14.290'; -const pdfjsBuild = '38c82357b'; +const pdfjsVersion = '2.15.51'; +const pdfjsBuild = '195396768'; ; })(); diff --git a/toolkit/components/pdfjs/content/build/pdf.scripting.js b/toolkit/components/pdfjs/content/build/pdf.scripting.js index 4e3d79197ef54..1168bac13d83e 100644 --- a/toolkit/components/pdfjs/content/build/pdf.scripting.js +++ b/toolkit/components/pdfjs/content/build/pdf.scripting.js @@ -29,7 +29,7 @@ exports["pdfjs-dist/build/pdf.scripting"] = factory(); else root.pdfjsScripting = factory(); -})(this, () => { +})(globalThis, () => { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ @@ -2638,6 +2638,10 @@ class EventDispatcher { } if (id === "doc") { + if (event.name === "Open") { + this.formatAll(); + } + this._document.obj._dispatchDocEvent(event.name); } else if (id === "page") { this._document.obj._dispatchPageEvent(event.name, baseEvent.actions, baseEvent.pageNumber); @@ -2740,6 +2744,21 @@ class EventDispatcher { } } + formatAll() { + const event = globalThis.event = new Event({}); + + for (const source of Object.values(this._objects)) { + event.value = source.obj.value; + + if (this.runActions(source, source, event, "Format")) { + source.obj._send({ + id: source.obj._id, + formattedValue: event.value?.toString?.() + }); + } + } + } + runValidation(source, event) { const didValidateRun = this.runActions(source, source, event, "Validate"); @@ -5020,8 +5039,8 @@ Object.defineProperty(exports, "initSandbox", ({ var _initialization = __w_pdfjs_require__(1); -const pdfjsVersion = '2.14.290'; -const pdfjsBuild = '38c82357b'; +const pdfjsVersion = '2.15.51'; +const pdfjsBuild = '195396768'; })(); /******/ return __webpack_exports__; diff --git a/toolkit/components/pdfjs/content/build/pdf.worker.js b/toolkit/components/pdfjs/content/build/pdf.worker.js index cec7840a7c1af..c89c560b3d122 100644 --- a/toolkit/components/pdfjs/content/build/pdf.worker.js +++ b/toolkit/components/pdfjs/content/build/pdf.worker.js @@ -29,7 +29,7 @@ exports["pdfjs-dist/build/pdf.worker"] = factory(); else root["pdfjs-dist/build/pdf.worker"] = root.pdfjsWorker = factory(); -})(this, () => { +})(globalThis, () => { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ @@ -117,7 +117,7 @@ class WorkerMessageHandler { const WorkerTasks = []; const verbosity = (0, _util.getVerbosityLevel)(); const apiVersion = docParams.apiVersion; - const workerVersion = '2.14.290'; + const workerVersion = '2.15.51'; if (apiVersion !== workerVersion) { throw new Error(`The API version "${apiVersion}" does not match ` + `the Worker version "${workerVersion}".`); @@ -699,7 +699,7 @@ if (typeof window === "undefined" && !_is_node.isNodeJS && typeof self !== "unde Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0; +exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0; exports.arrayByteLength = arrayByteLength; exports.arraysToBytes = arraysToBytes; exports.assert = assert; @@ -732,6 +732,8 @@ const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; +const LINE_FACTOR = 1.35; +exports.LINE_FACTOR = LINE_FACTOR; const RenderingIntentFlag = { ANY: 0x01, DISPLAY: 0x02, @@ -2923,6 +2925,7 @@ exports.getInheritableProperty = getInheritableProperty; exports.getLookupTableFactory = getLookupTableFactory; exports.isWhiteSpace = isWhiteSpace; exports.log2 = log2; +exports.numberToString = numberToString; exports.parseXFAPath = parseXFAPath; exports.readInt8 = readInt8; exports.readUint16 = readUint16; @@ -3392,6 +3395,24 @@ function recoverJsURL(str) { return null; } +function numberToString(value) { + if (Number.isInteger(value)) { + return value.toString(); + } + + const roundedValue = Math.round(value * 100); + + if (roundedValue % 100 === 0) { + return (roundedValue / 100).toString(); + } + + if (roundedValue % 10 === 0) { + return value.toFixed(1); + } + + return value.toFixed(2); +} + /***/ }), /* 9 */ /***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => { @@ -6304,8 +6325,6 @@ var _writer = __w_pdfjs_require__(73); var _factory = __w_pdfjs_require__(76); -const LINE_FACTOR = 1.35; - class AnnotationFactory { static create(xref, ref, pdfManager, idFactory, collectFields) { return Promise.all([pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("baseUrl"), pdfManager.ensureDoc("xfaDatasets"), collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1]).then(([acroForm, baseUrl, xfaDatasets, pageIndex]) => pdfManager.ensure(this, "_create", [xref, ref, pdfManager, idFactory, acroForm, xfaDatasets, collectFields, pageIndex])); @@ -6696,6 +6715,37 @@ class Annotation { this.color = getRgbColor(color); } + setLineEndings(lineEndings) { + this.lineEndings = ["None", "None"]; + + if (Array.isArray(lineEndings) && lineEndings.length === 2) { + for (let i = 0; i < 2; i++) { + const obj = lineEndings[i]; + + if (obj instanceof _primitives.Name) { + switch (obj.name) { + case "None": + continue; + + case "Square": + case "Circle": + case "Diamond": + case "OpenArrow": + case "ClosedArrow": + case "Butt": + case "ROpenArrow": + case "RClosedArrow": + case "Slash": + this.lineEndings[i] = obj.name; + continue; + } + } + + (0, _util.warn)(`Ignoring invalid lineEnding: ${obj}`); + } + } + } + setBorderAndBackgroundColors(mk) { if (mk instanceof _primitives.Dict) { this.borderColor = getRgbColor(mk.getArray("BC"), null); @@ -6705,6 +6755,28 @@ class Annotation { } } + getBorderAndBackgroundAppearances() { + if (!this.backgroundColor && !this.borderColor) { + return ""; + } + + const width = this.data.rect[2] - this.data.rect[0]; + const height = this.data.rect[3] - this.data.rect[1]; + const rect = `0 0 ${width} ${height} re`; + let str = ""; + + if (this.backgroundColor) { + str = `${(0, _default_appearance.getPdfColor)(this.backgroundColor)} ${rect} f `; + } + + if (this.borderColor) { + const borderWidth = this.borderStyle.width || 1; + str += `${borderWidth} w ${(0, _default_appearance.getPdfColor)(this.borderColor)} ${rect} S `; + } + + return str; + } + setBorderStyle(borderStyle) { this.borderStyle = new AnnotationBorderStyle(); @@ -7416,7 +7488,8 @@ class WidgetAnnotation extends Annotation { descent = 0; } - const vPadding = defaultPadding + Math.abs(descent) * fontSize; + const defaultVPadding = Math.min(Math.floor((totalHeight - fontSize) / 2), defaultPadding); + const vPadding = defaultVPadding + Math.abs(descent) * fontSize; const alignment = this.data.textAlignment; if (this.data.multiLine) { @@ -7429,13 +7502,15 @@ class WidgetAnnotation extends Annotation { return this._getCombAppearance(defaultAppearance, font, encodedString, totalWidth, hPadding, vPadding); } + const colors = this.getBorderAndBackgroundAppearances(); + if (alignment === 0 || alignment > 2) { - return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm (${(0, _util.escapeString)(encodedString)}) Tj` + " ET Q EMC"; + return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm (${(0, _util.escapeString)(encodedString)}) Tj` + " ET Q EMC"; } const renderedText = this._renderText(encodedString, font, fontSize, totalWidth, alignment, hPadding, vPadding); - return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC"; + return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC"; } async _getFontData(evaluator, task) { @@ -7471,7 +7546,7 @@ class WidgetAnnotation extends Annotation { if (lineCount === -1) { const textWidth = this._getTextWidth(text, font); - fontSize = roundWithTwoDigits(Math.min(height / LINE_FACTOR, width / textWidth)); + fontSize = roundWithTwoDigits(Math.min(height / _util.LINE_FACTOR, width / textWidth)); } else { const lines = text.split(/\r\n?|\n/); const cachedLines = []; @@ -7504,13 +7579,13 @@ class WidgetAnnotation extends Annotation { }; fontSize = 12; - let lineHeight = fontSize * LINE_FACTOR; + let lineHeight = fontSize * _util.LINE_FACTOR; let numberOfLines = Math.round(height / lineHeight); numberOfLines = Math.max(numberOfLines, lineCount); while (true) { lineHeight = height / numberOfLines; - fontSize = roundWithTwoDigits(lineHeight / LINE_FACTOR); + fontSize = roundWithTwoDigits(lineHeight / _util.LINE_FACTOR); if (isTooBig(fontSize)) { numberOfLines++; @@ -7548,8 +7623,8 @@ class WidgetAnnotation extends Annotation { shift = hPadding; } - shift = shift.toFixed(2); - vPadding = vPadding.toFixed(2); + shift = (0, _core_utils.numberToString)(shift); + vPadding = (0, _core_utils.numberToString)(vPadding); return `${shift} ${vPadding} Td (${(0, _util.escapeString)(text)}) Tj`; } @@ -7632,10 +7707,11 @@ class TextWidgetAnnotation extends WidgetAnnotation { this.data.maxLen = maximumLength; this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE); this.data.comb = this.hasFieldFlag(_util.AnnotationFieldFlag.COMB) && !this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD) && !this.hasFieldFlag(_util.AnnotationFieldFlag.FILESELECT) && this.data.maxLen !== null; + this.data.doNotScroll = this.hasFieldFlag(_util.AnnotationFieldFlag.DONOTSCROLL); } _getCombAppearance(defaultAppearance, font, text, width, hPadding, vPadding) { - const combWidth = (width / this.data.maxLen).toFixed(2); + const combWidth = (0, _core_utils.numberToString)(width / this.data.maxLen); const buf = []; const positions = font.getCharPositions(text); @@ -7643,8 +7719,9 @@ class TextWidgetAnnotation extends WidgetAnnotation { buf.push(`(${(0, _util.escapeString)(text.substring(start, end))}) Tj`); } + const colors = this.getBorderAndBackgroundAppearances(); const renderedComb = buf.join(` ${combWidth} 0 Td `); - return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm ${renderedComb}` + " ET Q EMC"; + return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm ${renderedComb}` + " ET Q EMC"; } _getMultilineAppearance(defaultAppearance, text, font, fontSize, width, height, alignment, hPadding, vPadding) { @@ -7662,7 +7739,8 @@ class TextWidgetAnnotation extends WidgetAnnotation { } const renderedText = buf.join("\n"); - return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 0 ${height} Tm ${renderedText}` + " ET Q EMC"; + const colors = this.getBorderAndBackgroundAppearances(); + return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 ${height} Tm ${renderedText}` + " ET Q EMC"; } _splitLine(line, font, fontSize, width, cache = {}) { @@ -7976,8 +8054,8 @@ class ButtonWidgetAnnotation extends WidgetAnnotation { (0, _util.unreachable)(`_getDefaultCheckedAppearance - unsupported type: ${type}`); } - const xShift = (width - metrics.width) / 2; - const yShift = (height - metrics.height) / 2; + const xShift = (0, _core_utils.numberToString)((width - metrics.width) / 2); + const yShift = (0, _core_utils.numberToString)((height - metrics.height) / 2); const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`; const appearanceStreamDict = new _primitives.Dict(params.xref); appearanceStreamDict.set("FormType", 1); @@ -8283,7 +8361,7 @@ class ChoiceWidgetAnnotation extends WidgetAnnotation { defaultAppearance = this._defaultAppearance; } - const lineHeight = fontSize * LINE_FACTOR; + const lineHeight = fontSize * _util.LINE_FACTOR; const vPadding = (lineHeight - fontSize) / 2; const numberOfVisibleLines = Math.floor(totalHeight / lineHeight); let firstIndex; @@ -8379,6 +8457,8 @@ class LinkAnnotation extends Annotation { this.data.quadPoints = quadPoints; } + this.data.borderColor = this.data.borderColor || this.data.color; + _catalog.Catalog.parseDestDictionary({ destDict: params.dict, resultObj: this.data, @@ -8462,15 +8542,20 @@ class FreeTextAnnotation extends MarkupAnnotation { class LineAnnotation extends MarkupAnnotation { constructor(parameters) { super(parameters); + const { + dict + } = parameters; this.data.annotationType = _util.AnnotationType.LINE; - const lineCoordinates = parameters.dict.getArray("L"); + const lineCoordinates = dict.getArray("L"); this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates); + this.setLineEndings(dict.getArray("LE")); + this.data.lineEndings = this.lineEndings; if (!this.appearance) { const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0]; - const strokeAlpha = parameters.dict.get("CA"); + const strokeAlpha = dict.get("CA"); let fillColor = null, - interiorColor = parameters.dict.getArray("IC"); + interiorColor = dict.getArray("IC"); if (interiorColor) { interiorColor = getRgbColor(interiorColor, null); @@ -8612,9 +8697,18 @@ class CircleAnnotation extends MarkupAnnotation { class PolylineAnnotation extends MarkupAnnotation { constructor(parameters) { super(parameters); + const { + dict + } = parameters; this.data.annotationType = _util.AnnotationType.POLYLINE; this.data.vertices = []; - const rawVertices = parameters.dict.getArray("Vertices"); + + if (!(this instanceof PolygonAnnotation)) { + this.setLineEndings(dict.getArray("LE")); + this.data.lineEndings = this.lineEndings; + } + + const rawVertices = dict.getArray("Vertices"); if (!Array.isArray(rawVertices)) { return; @@ -8629,7 +8723,7 @@ class PolylineAnnotation extends MarkupAnnotation { if (!this.appearance) { const strokeColor = this.color ? Array.from(this.color).map(c => c / 255) : [0, 0, 0]; - const strokeAlpha = parameters.dict.get("CA"); + const strokeAlpha = dict.get("CA"); const borderWidth = this.borderStyle.width || 1, borderAdjust = 2 * borderWidth; const bbox = [Infinity, Infinity, -Infinity, -Infinity]; @@ -8911,14 +9005,15 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDefaultAppearance = createDefaultAppearance; +exports.getPdfColor = getPdfColor; exports.parseDefaultAppearance = parseDefaultAppearance; +var _core_utils = __w_pdfjs_require__(8); + var _util = __w_pdfjs_require__(2); var _colorspace = __w_pdfjs_require__(24); -var _core_utils = __w_pdfjs_require__(8); - var _evaluator = __w_pdfjs_require__(25); var _primitives = __w_pdfjs_require__(5); @@ -9001,20 +9096,21 @@ function parseDefaultAppearance(str) { return new DefaultAppearanceEvaluator(str).parse(); } +function getPdfColor(color) { + if (color[0] === color[1] && color[1] === color[2]) { + const gray = color[0] / 255; + return `${(0, _core_utils.numberToString)(gray)} g`; + } + + return Array.from(color).map(c => (0, _core_utils.numberToString)(c / 255)).join(" ") + " rg"; +} + function createDefaultAppearance({ fontSize, fontName, fontColor }) { - let colorCmd; - - if (fontColor.every(c => c === 0)) { - colorCmd = "0 g"; - } else { - colorCmd = Array.from(fontColor).map(c => (c / 255).toFixed(2)).join(" ") + " rg"; - } - - return `/${(0, _core_utils.escapePDFName)(fontName)} ${fontSize} Tf ${colorCmd}`; + return `/${(0, _core_utils.escapePDFName)(fontName)} ${fontSize} Tf ${getPdfColor(fontColor)}`; } /***/ }), @@ -13973,24 +14069,32 @@ class TranslatedFont { } _removeType3ColorOperators(operatorList, isEmptyBBox = false) { - if (isEmptyBBox) { + const charBBox = _util.Util.normalizeRect(operatorList.argsArray[0].slice(2)), + width = charBBox[2] - charBBox[0], + height = charBBox[3] - charBBox[1]; + + if (width === 0 || height === 0) { + operatorList.fnArray.splice(0, 1); + operatorList.argsArray.splice(0, 1); + } else if (isEmptyBBox) { if (!this._bbox) { this._bbox = [Infinity, Infinity, -Infinity, -Infinity]; } - const charBBox = _util.Util.normalizeRect(operatorList.argsArray[0].slice(2)); - this._bbox[0] = Math.min(this._bbox[0], charBBox[0]); this._bbox[1] = Math.min(this._bbox[1], charBBox[1]); this._bbox[2] = Math.max(this._bbox[2], charBBox[2]); this._bbox[3] = Math.max(this._bbox[3], charBBox[3]); } - let i = 1, + let i = 0, ii = operatorList.length; while (i < ii) { switch (operatorList.fnArray[i]) { + case _util.OPS.setCharWidthAndBounds: + break; + case _util.OPS.setStrokeColorSpace: case _util.OPS.setFillColorSpace: case _util.OPS.setStrokeColor: @@ -14540,6 +14644,7 @@ class EvaluatorPreprocessor { }); this.stateManager = stateManager; this.nonProcessedArgs = []; + this._isPathOp = false; this._numInvalidPathOPS = 0; } @@ -14566,6 +14671,12 @@ class EvaluatorPreprocessor { const numArgs = opSpec.numArgs; let argsLength = args !== null ? args.length : 0; + if (!this._isPathOp) { + this._numInvalidPathOPS = 0; + } + + this._isPathOp = fn >= _util.OPS.moveTo && fn <= _util.OPS.endPath; + if (!opSpec.variableArgs) { if (argsLength !== numArgs) { const nonProcessedArgs = this.nonProcessedArgs; @@ -14588,7 +14699,7 @@ class EvaluatorPreprocessor { if (argsLength < numArgs) { const partialMsg = `command ${cmd}: expected ${numArgs} args, ` + `but received ${argsLength} args.`; - if (fn >= _util.OPS.moveTo && fn <= _util.OPS.endPath && ++this._numInvalidPathOPS > EvaluatorPreprocessor.MAX_INVALID_PATH_OPS) { + if (this._isPathOp && ++this._numInvalidPathOPS > EvaluatorPreprocessor.MAX_INVALID_PATH_OPS) { throw new _util.FormatError(`Invalid ${partialMsg}`); } @@ -19924,9 +20035,7 @@ class SimpleSegmentVisitor { const buffer = new Uint8ClampedArray(rowSize * info.height); if (info.defaultPixelValue) { - for (let i = 0, ii = buffer.length; i < ii; i++) { - buffer[i] = 0xff; - } + buffer.fill(0xff); } this.buffer = buffer; @@ -44957,24 +45066,6 @@ function writeArray(array, buffer, transform) { buffer.push("]"); } -function numberToString(value) { - if (Number.isInteger(value)) { - return value.toString(); - } - - const roundedValue = Math.round(value * 100); - - if (roundedValue % 100 === 0) { - return (roundedValue / 100).toString(); - } - - if (roundedValue % 10 === 0) { - return value.toFixed(1); - } - - return value.toFixed(2); -} - function writeValue(value, buffer, transform) { if (value instanceof _primitives.Name) { buffer.push(`/${(0, _core_utils.escapePDFName)(value.name)}`); @@ -44989,7 +45080,7 @@ function writeValue(value, buffer, transform) { buffer.push(`(${(0, _util.escapeString)(value)})`); } else if (typeof value === "number") { - buffer.push(numberToString(value)); + buffer.push((0, _core_utils.numberToString)(value)); } else if (typeof value === "boolean") { buffer.push(value.toString()); } else if (value instanceof _primitives.Dict) { @@ -62433,8 +62524,8 @@ Object.defineProperty(exports, "WorkerMessageHandler", ({ var _worker = __w_pdfjs_require__(1); -const pdfjsVersion = '2.14.290'; -const pdfjsBuild = '38c82357b'; +const pdfjsVersion = '2.15.51'; +const pdfjsBuild = '195396768'; })(); /******/ return __webpack_exports__; diff --git a/toolkit/components/pdfjs/content/web/viewer.css b/toolkit/components/pdfjs/content/web/viewer.css index 09a5705989fb7..cb16c95970651 100644 --- a/toolkit/components/pdfjs/content/web/viewer.css +++ b/toolkit/components/pdfjs/content/web/viewer.css @@ -142,10 +142,9 @@ background-image: var(--annotation-unfocused-field-background); border: 1px solid transparent; box-sizing: border-box; - font-size: 9px; + font: 9px sans-serif; height: 100%; margin: 0; - padding: 0 3px; vertical-align: top; width: 100%; } @@ -159,8 +158,6 @@ } .annotationLayer .textWidgetAnnotation textarea { - font: message-box; - font-size: 9px; resize: none; } @@ -250,7 +247,6 @@ .annotationLayer .buttonWidgetAnnotation.checkBox input, .annotationLayer .buttonWidgetAnnotation.radioButton input { appearance: none; - padding: 0; } .annotationLayer .popupWrapper { @@ -783,13 +779,14 @@ --sidebar-transition-timing-function: ease; --scale-select-container-width: 140px; --scale-select-overflow: 22px; - --loadingBar-end-offset: 0; --toolbar-icon-opacity: 0.7; --doorhanger-icon-opacity: 0.9; --main-color: rgba(12, 12, 13, 1); --body-bg-color: rgba(237, 237, 240, 1); + --progressBar-percent: 0%; + --progressBar-end-offset: 0; --progressBar-color: rgba(10, 132, 255, 1); --progressBar-indeterminate-bg-color: rgba(221, 221, 222, 1); --progressBar-indeterminate-blend-color: rgba(116, 177, 239, 1); @@ -1096,7 +1093,7 @@ select { #loadingBar { position: absolute; - inset-inline: 0 var(--loadingBar-end-offset); + inset-inline: 0 var(--progressBar-end-offset); height: 4px; background-color: var(--body-bg-color); border-bottom: 1px solid var(--toolbar-border-color); @@ -1113,23 +1110,26 @@ select { position: absolute; top: 0; left: 0; - width: 0%; + width: 100%; + transform: scaleX(var(--progressBar-percent)); + transform-origin: 0 0; height: 100%; background-color: var(--progressBar-color); overflow: hidden; - transition: width 200ms; + transition: transform 200ms; } @keyframes progressIndeterminate { 0% { - left: -142px; + transform: translateX(-142px); } 100% { - left: 0; + transform: translateX(0); } } #loadingBar .progress.indeterminate { + transform: none; background-color: var(--progressBar-indeterminate-bg-color); transition: none; } @@ -1572,7 +1572,6 @@ select { mask-image: var(--toolbarButton-print-icon); } - #download::before, #secondaryDownload::before { mask-image: var(--toolbarButton-download-icon); @@ -1921,7 +1920,6 @@ a:focus > .thumbnail > .thumbnailSelectionRing, background: rgba(0, 0, 255, 0.3); } - .dialogButton { width: auto; margin: 3px 4px 2px !important; diff --git a/toolkit/components/pdfjs/content/web/viewer.html b/toolkit/components/pdfjs/content/web/viewer.html index 4b1cd13a81b91..b334df283ef0d 100644 --- a/toolkit/components/pdfjs/content/web/viewer.html +++ b/toolkit/components/pdfjs/content/web/viewer.html @@ -30,11 +30,8 @@ - - - @@ -124,7 +121,6 @@ Presentation Mode - @@ -233,7 +229,6 @@ Presentation Mode - diff --git a/toolkit/components/pdfjs/content/web/viewer.js b/toolkit/components/pdfjs/content/web/viewer.js index 6df7f42928480..ce27571c41ad2 100644 --- a/toolkit/components/pdfjs/content/web/viewer.js +++ b/toolkit/components/pdfjs/content/web/viewer.js @@ -670,8 +670,12 @@ const PDFViewerApplication = { docPropertiesLookup: this._scriptingDocProperties.bind(this) }); this.pdfScriptingManager = pdfScriptingManager; - const container = appConfig.mainContainer; - const viewer = appConfig.viewerContainer; + const container = appConfig.mainContainer, + viewer = appConfig.viewerContainer; + const pageColors = { + background: _app_options.AppOptions.get("pageColorsBackground"), + foreground: _app_options.AppOptions.get("pageColorsForeground") + }; this.pdfViewer = new _pdf_viewer.PDFViewer({ container, viewer, @@ -690,10 +694,7 @@ const PDFViewerApplication = { useOnlyCssZoom: _app_options.AppOptions.get("useOnlyCssZoom"), maxCanvasPixels: _app_options.AppOptions.get("maxCanvasPixels"), enablePermissions: _app_options.AppOptions.get("enablePermissions"), - pageColors: { - background: _app_options.AppOptions.get("pageColorsBackground"), - foreground: _app_options.AppOptions.get("pageColorsForeground") - } + pageColors }); pdfRenderingQueue.setViewer(this.pdfViewer); pdfLinkService.setViewer(this.pdfViewer); @@ -703,7 +704,8 @@ const PDFViewerApplication = { eventBus, renderingQueue: pdfRenderingQueue, linkService: pdfLinkService, - l10n: this.l10n + l10n: this.l10n, + pageColors }); pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer); @@ -719,7 +721,9 @@ const PDFViewerApplication = { this.findBar = new _pdf_find_bar.PDFFindBar(appConfig.findBar, eventBus, this.l10n); } - this.pdfDocumentProperties = new _pdf_document_properties.PDFDocumentProperties(appConfig.documentProperties, this.overlayManager, eventBus, this.l10n); + this.pdfDocumentProperties = new _pdf_document_properties.PDFDocumentProperties(appConfig.documentProperties, this.overlayManager, eventBus, this.l10n, () => { + return this._docFilename; + }); this.pdfCursorTools = new _pdf_cursor_tools.PDFCursorTools({ container, eventBus, @@ -1069,9 +1073,7 @@ const PDFViewerApplication = { throw new Error("PDF document not downloaded."); }, - async download({ - sourceEventType = "download" - } = {}) { + async download() { const url = this._downloadUrl, filename = this._docFilename; @@ -1082,15 +1084,13 @@ const PDFViewerApplication = { const blob = new Blob([data], { type: "application/pdf" }); - await this.downloadManager.download(blob, url, filename, sourceEventType); + await this.downloadManager.download(blob, url, filename); } catch (reason) { await this.downloadManager.downloadUrl(url, filename); } }, - async save({ - sourceEventType = "download" - } = {}) { + async save() { if (this._saveInProgress) { return; } @@ -1107,23 +1107,21 @@ const PDFViewerApplication = { const blob = new Blob([data], { type: "application/pdf" }); - await this.downloadManager.download(blob, url, filename, sourceEventType); + await this.downloadManager.download(blob, url, filename); } catch (reason) { console.error(`Error when saving the document: ${reason.message}`); - await this.download({ - sourceEventType - }); + await this.download(); } finally { await this.pdfScriptingManager.dispatchDidSave(); this._saveInProgress = false; } }, - downloadOrSave(options) { + downloadOrSave() { if (this.pdfDocument?.annotationStorage.size > 0) { - this.save(options); + this.save(); } else { - this.download(options); + this.download(); } }, @@ -1230,7 +1228,7 @@ const PDFViewerApplication = { let baseDocumentUrl; baseDocumentUrl = this.baseUrl; this.pdfLinkService.setDocument(pdfDocument, baseDocumentUrl); - this.pdfDocumentProperties.setDocument(pdfDocument, this.url); + this.pdfDocumentProperties.setDocument(pdfDocument); const pdfViewer = this.pdfViewer; pdfViewer.setDocument(pdfDocument); const { @@ -1507,7 +1505,7 @@ const PDFViewerApplication = { this._contentDispositionFilename ??= contentDispositionFilename; 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; + let pdfTitle = info.Title; const metadataTitle = metadata?.get("dc:title"); if (metadataTitle) { @@ -1517,9 +1515,9 @@ const PDFViewerApplication = { } if (pdfTitle) { - this.setTitle(`${pdfTitle} - ${contentDispositionFilename || document.title}`); - } else if (contentDispositionFilename) { - this.setTitle(contentDispositionFilename); + this.setTitle(`${pdfTitle} - ${this._contentDispositionFilename || document.title}`); + } else if (this._contentDispositionFilename) { + this.setTitle(this._contentDispositionFilename); } if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) { @@ -1724,7 +1722,7 @@ const PDFViewerApplication = { forceRendering() { this.pdfRenderingQueue.printing = !!this.printService; - this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar.isThumbnailViewVisible; + this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar.visibleView === _ui_utils.SidebarView.THUMBS; this.pdfRenderingQueue.renderHighestPriority(); }, @@ -1832,8 +1830,6 @@ const PDFViewerApplication = { eventBus._on("download", webViewerDownload); - eventBus._on("save", webViewerSave); - eventBus._on("firstpage", webViewerFirstPage); eventBus._on("lastpage", webViewerLastPage); @@ -2067,7 +2063,7 @@ function webViewerPageRendered({ PDFViewerApplication.toolbar.updateLoadingIndicatorState(false); } - if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) { + if (PDFViewerApplication.pdfSidebar.visibleView === _ui_utils.SidebarView.THUMBS) { const pageView = PDFViewerApplication.pdfViewer.getPageView(pageNumber - 1); const thumbnailView = PDFViewerApplication.pdfThumbnailViewer.getThumbnail(pageNumber - 1); @@ -2138,7 +2134,7 @@ function webViewerNamedAction(evt) { break; case "SaveAs": - webViewerSave(); + PDFViewerApplication.downloadOrSave(); break; } } @@ -2147,17 +2143,19 @@ function webViewerPresentationModeChanged(evt) { PDFViewerApplication.pdfViewer.presentationModeState = evt.state; } -function webViewerSidebarViewChanged(evt) { - PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = PDFViewerApplication.pdfSidebar.isThumbnailViewVisible; +function webViewerSidebarViewChanged({ + view +}) { + PDFViewerApplication.pdfRenderingQueue.isThumbnailViewEnabled = view === _ui_utils.SidebarView.THUMBS; if (PDFViewerApplication.isInitialViewSet) { - PDFViewerApplication.store?.set("sidebarView", evt.view).catch(() => {}); + PDFViewerApplication.store?.set("sidebarView", view).catch(() => {}); } } -function webViewerUpdateViewarea(evt) { - const location = evt.location; - +function webViewerUpdateViewarea({ + location +}) { if (PDFViewerApplication.isInitialViewSet) { PDFViewerApplication.store?.setMultiple({ page: location.pageNumber, @@ -2233,15 +2231,7 @@ function webViewerPrint() { } function webViewerDownload() { - PDFViewerApplication.downloadOrSave({ - sourceEventType: "download" - }); -} - -function webViewerSave() { - PDFViewerApplication.downloadOrSave({ - sourceEventType: "save" - }); + PDFViewerApplication.downloadOrSave(); } function webViewerFirstPage() { @@ -2376,7 +2366,7 @@ function webViewerPageChanging({ PDFViewerApplication.toolbar.setPageNumber(pageNumber, pageLabel); PDFViewerApplication.secondaryToolbar.setPageNumber(pageNumber); - if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) { + if (PDFViewerApplication.pdfSidebar.visibleView === _ui_utils.SidebarView.THUMBS) { PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(pageNumber); } } @@ -2784,6 +2774,7 @@ exports.apiPageModeToSidebarView = apiPageModeToSidebarView; exports.approximateFraction = approximateFraction; exports.backtrackBeforeAllVisibleElements = backtrackBeforeAllVisibleElements; exports.binarySearchFirstItem = binarySearchFirstItem; +exports.docStyle = void 0; exports.getActiveOrFocusedElement = getActiveOrFocusedElement; exports.getPageSizeInches = getPageSizeInches; exports.getVisibleElements = getVisibleElements; @@ -2817,7 +2808,6 @@ 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 RenderingStates = { INITIAL: 0, RUNNING: 1, @@ -3254,37 +3244,29 @@ const animationStarted = new Promise(function (resolve) { window.requestAnimationFrame(resolve); }); exports.animationStarted = animationStarted; +const docStyle = document.documentElement.style; +exports.docStyle = docStyle; function clamp(v, min, max) { return Math.min(Math.max(v, min), max); } class ProgressBar { - constructor(id, { - height, - width, - units - } = {}) { + constructor(id) { this.visible = true; this.div = document.querySelector(id + " .progress"); this.bar = this.div.parentNode; - this.height = height || 100; - this.width = width || 100; - this.units = units || "%"; - this.div.style.height = this.height + this.units; this.percent = 0; } - _updateBar() { + #updateBar() { if (this._indeterminate) { this.div.classList.add("indeterminate"); - this.div.style.width = this.width + this.units; return; } this.div.classList.remove("indeterminate"); - const progressSize = this.width * this._percent / 100; - this.div.style.width = progressSize + this.units; + docStyle.setProperty("--progressBar-percent", `${this._percent}%`); } get percent() { @@ -3294,8 +3276,7 @@ class ProgressBar { set percent(val) { this._indeterminate = isNaN(val); this._percent = clamp(val, 0, 100); - - this._updateBar(); + this.#updateBar(); } setWidth(viewer) { @@ -3307,8 +3288,7 @@ class ProgressBar { const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; if (scrollbarWidth > 0) { - const doc = document.documentElement; - doc.style.setProperty(LOADINGBAR_END_OFFSET_VAR, `${scrollbarWidth}px`); + docStyle.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); } } @@ -4857,11 +4837,12 @@ class PDFDocumentProperties { dialog, fields, closeButton - }, overlayManager, eventBus, l10n) { + }, overlayManager, eventBus, l10n, fileNameLookup) { this.dialog = dialog; this.fields = fields; this.overlayManager = overlayManager; this.l10n = l10n; + this._fileNameLookup = fileNameLookup; this.#reset(); closeButton.addEventListener("click", this.close.bind(this)); this.overlayManager.register(this.dialog); @@ -4892,10 +4873,9 @@ class PDFDocumentProperties { 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 => { + const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([this._fileNameLookup(), 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)]); this.#fieldData = Object.freeze({ @@ -4935,7 +4915,7 @@ class PDFDocumentProperties { this.overlayManager.close(this.dialog); } - setDocument(pdfDocument, url = null) { + setDocument(pdfDocument) { if (this.pdfDocument) { this.#reset(); this.#updateUI(true); @@ -4946,14 +4926,12 @@ class PDFDocumentProperties { } this.pdfDocument = pdfDocument; - this.url = url; this._dataAvailableCapability.resolve(); } #reset() { this.pdfDocument = null; - this.url = null; this.#fieldData = null; this._dataAvailableCapability = (0, _pdfjsLib.createPromiseCapability)(); this._currentPageNumber = 1; @@ -5326,16 +5304,51 @@ const DIACRITICS_REG_EXP = /\p{M}+/gu; const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; -let normalizationRegex = null; +const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; +const SYLLABLES_LENGTHS = new Map(); +const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; +let noSyllablesRegExp = null; +let withSyllablesRegExp = null; function normalize(text) { - if (!normalizationRegex) { + const syllablePositions = []; + let m; + + while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { + let { + index + } = m; + + for (const char of m[0]) { + let len = SYLLABLES_LENGTHS.get(char); + + if (!len) { + len = char.normalize("NFD").length; + SYLLABLES_LENGTHS.set(char, len); + } + + syllablePositions.push([len, index++]); + } + } + + let normalizationRegex; + + if (syllablePositions.length === 0 && noSyllablesRegExp) { + normalizationRegex = noSyllablesRegExp; + } else if (syllablePositions.length > 0 && withSyllablesRegExp) { + normalizationRegex = withSyllablesRegExp; + } else { const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); - normalizationRegex = new RegExp(`([${replace}])|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(\\n)`, "gum"); + const regexp = `([${replace}])|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(\\n)`; + + if (syllablePositions.length === 0) { + normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); + } else { + normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); + } } const rawDiacriticsPositions = []; - let m; while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { rawDiacriticsPositions.push([m[0].length, m.index]); @@ -5343,12 +5356,13 @@ function normalize(text) { let normalized = text.normalize("NFD"); const positions = [[0, 0]]; - let k = 0; + let rawDiacriticsIndex = 0; + let syllableIndex = 0; let shift = 0; let shiftOrigin = 0; let eol = 0; let hasDiacritics = false; - normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, i) => { + normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, i) => { i -= shiftOrigin; if (p1) { @@ -5369,12 +5383,12 @@ function normalize(text) { hasDiacritics = true; let jj = len; - if (i + eol === rawDiacriticsPositions[k]?.[1]) { - jj -= rawDiacriticsPositions[k][0]; - ++k; + if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { + jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; + ++rawDiacriticsIndex; } - for (let j = 1; j < jj + 1; j++) { + for (let j = 1; j <= jj; j++) { positions.push([i - 1 - shift + j, shift - j]); } @@ -5401,11 +5415,27 @@ function normalize(text) { return p3.charAt(0); } - positions.push([i - shift + 1, shift - 1]); - shift -= 1; - shiftOrigin += 1; - eol += 1; - return " "; + if (p4) { + positions.push([i - shift + 1, shift - 1]); + shift -= 1; + shiftOrigin += 1; + eol += 1; + return " "; + } + + if (i + eol === syllablePositions[syllableIndex]?.[1]) { + const newCharLen = syllablePositions[syllableIndex][0] - 1; + ++syllableIndex; + + for (let j = 1; j <= newCharLen; j++) { + positions.push([i - (shift - j), shift - j]); + } + + shift -= newCharLen; + shiftOrigin += newCharLen; + } + + return p5; }); positions.push([normalized.length, shift]); return [normalized, positions, hasDiacritics]; @@ -8038,7 +8068,7 @@ class PDFScriptingManager { break; case "SaveAs": - this._eventBus.dispatch("save", { + this._eventBus.dispatch("download", { source: this }); @@ -8275,6 +8305,7 @@ class PDFSidebar { this.isOpen = false; this.active = _ui_utils.SidebarView.THUMBS; this.isInitialViewSet = false; + this.isInitialEventDispatched = false; this.onToggled = null; this.pdfViewer = pdfViewer; this.pdfThumbnailViewer = pdfThumbnailViewer; @@ -8293,15 +8324,13 @@ class PDFSidebar { this._currentOutlineItemButton = elements.currentOutlineItemButton; this.eventBus = eventBus; this.l10n = l10n; - - this._addEventListeners(); + this.#addEventListeners(); } reset() { this.isInitialViewSet = false; - - this._hideUINotification(true); - + this.isInitialEventDispatched = false; + this.#hideUINotification(true); this.switchView(_ui_utils.SidebarView.THUMBS); this.outlineButton.disabled = false; this.attachmentsButton.disabled = false; @@ -8313,22 +8342,6 @@ class PDFSidebar { 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; @@ -8337,21 +8350,18 @@ class PDFSidebar { this.isInitialViewSet = true; if (view === _ui_utils.SidebarView.NONE || view === _ui_utils.SidebarView.UNKNOWN) { - this._dispatchEvent(); - + this.#dispatchEvent(); return; } - if (!this._switchView(view, true)) { - this._dispatchEvent(); + this.switchView(view, true); + + if (!this.isInitialEventDispatched) { + this.#dispatchEvent(); } } switchView(view, forceOpen = false) { - this._switchView(view, forceOpen); - } - - _switchView(view, forceOpen = false) { const isViewChanged = view !== this.active; let shouldForceRendering = false; @@ -8359,10 +8369,9 @@ class PDFSidebar { case _ui_utils.SidebarView.NONE: if (this.isOpen) { this.close(); - return true; } - return false; + return; case _ui_utils.SidebarView.THUMBS: if (this.isOpen && isViewChanged) { @@ -8373,28 +8382,28 @@ class PDFSidebar { case _ui_utils.SidebarView.OUTLINE: if (this.outlineButton.disabled) { - return false; + return; } break; case _ui_utils.SidebarView.ATTACHMENTS: if (this.attachmentsButton.disabled) { - return false; + return; } break; case _ui_utils.SidebarView.LAYERS: if (this.layersButton.disabled) { - return false; + return; } break; default: - console.error(`PDFSidebar._switchView: "${view}" is not a valid view.`); - return false; + console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`); + return; } this.active = view; @@ -8419,20 +8428,17 @@ class PDFSidebar { if (forceOpen && !this.isOpen) { this.open(); - return true; + return; } if (shouldForceRendering) { - this._updateThumbnailViewer(); - - this._forceRendering(); + this.#updateThumbnailViewer(); + this.#forceRendering(); } if (isViewChanged) { - this._dispatchEvent(); + this.#dispatchEvent(); } - - return isViewChanged; } open() { @@ -8446,14 +8452,12 @@ class PDFSidebar { this.outerContainer.classList.add("sidebarMoving", "sidebarOpen"); if (this.active === _ui_utils.SidebarView.THUMBS) { - this._updateThumbnailViewer(); + this.#updateThumbnailViewer(); } - this._forceRendering(); - - this._dispatchEvent(); - - this._hideUINotification(); + this.#forceRendering(); + this.#dispatchEvent(); + this.#hideUINotification(); } close() { @@ -8466,10 +8470,8 @@ class PDFSidebar { this.toggleButton.setAttribute("aria-expanded", "false"); this.outerContainer.classList.add("sidebarMoving"); this.outerContainer.classList.remove("sidebarOpen"); - - this._forceRendering(); - - this._dispatchEvent(); + this.#forceRendering(); + this.#dispatchEvent(); } toggle() { @@ -8480,14 +8482,18 @@ class PDFSidebar { } } - _dispatchEvent() { + #dispatchEvent() { + if (this.isInitialViewSet && !this.isInitialEventDispatched) { + this.isInitialEventDispatched = true; + } + this.eventBus.dispatch("sidebarviewchanged", { source: this, view: this.visibleView }); } - _forceRendering() { + #forceRendering() { if (this.onToggled) { this.onToggled(); } else { @@ -8496,7 +8502,7 @@ class PDFSidebar { } } - _updateThumbnailViewer() { + #updateThumbnailViewer() { const { pdfViewer, pdfThumbnailViewer @@ -8515,7 +8521,7 @@ class PDFSidebar { pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber); } - _showUINotification() { + #showUINotification() { this.l10n.get("toggle_sidebar_notification2.title").then(msg => { this.toggleButton.title = msg; }); @@ -8525,7 +8531,7 @@ class PDFSidebar { } } - _hideUINotification(reset = false) { + #hideUINotification(reset = false) { if (this.isOpen || reset) { this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS); } @@ -8537,7 +8543,7 @@ class PDFSidebar { } } - _addEventListeners() { + #addEventListeners() { this.sidebarContainer.addEventListener("transitionend", evt => { if (evt.target === this.sidebarContainer) { this.outerContainer.classList.remove("sidebarMoving"); @@ -8579,7 +8585,7 @@ class PDFSidebar { button.disabled = !count; if (count) { - this._showUINotification(); + this.#showUINotification(); } else if (this.active === view) { this.switchView(_ui_utils.SidebarView.THUMBS); } @@ -8605,8 +8611,8 @@ class PDFSidebar { }); this.eventBus._on("presentationmodechanged", evt => { - if (evt.state === _ui_utils.PresentationModeState.NORMAL && this.isThumbnailViewVisible) { - this._updateThumbnailViewer(); + if (evt.state === _ui_utils.PresentationModeState.NORMAL && this.visibleView === _ui_utils.SidebarView.THUMBS) { + this.#updateThumbnailViewer(); } }); } @@ -8617,7 +8623,7 @@ exports.PDFSidebar = PDFSidebar; /***/ }), /* 24 */ -/***/ ((__unused_webpack_module, exports) => { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { @@ -8625,6 +8631,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PDFSidebarResizer = void 0; + +var _ui_utils = __webpack_require__(3); + const SIDEBAR_WIDTH_VAR = "--sidebar-width"; const SIDEBAR_MIN_WIDTH = 200; const SIDEBAR_RESIZING_CLASS = "sidebarResizing"; @@ -8633,7 +8642,6 @@ class PDFSidebarResizer { constructor(options, eventBus, l10n) { this.isRTL = false; this.sidebarOpen = false; - this.doc = document.documentElement; this._width = null; this._outerContainerWidth = null; this._boundEvents = Object.create(null); @@ -8667,7 +8675,9 @@ class PDFSidebarResizer { } this._width = width; - this.doc.style.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`); + + _ui_utils.docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`); + return true; } @@ -8770,12 +8780,14 @@ class PDFThumbnailViewer { eventBus, linkService, renderingQueue, - l10n + l10n, + pageColors }) { this.container = container; this.linkService = linkService; this.renderingQueue = renderingQueue; this.l10n = l10n; + this.pageColors = pageColors || null; this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdated.bind(this)); this._resetView(); @@ -8935,7 +8947,8 @@ class PDFThumbnailViewer { linkService: this.linkService, renderingQueue: this.renderingQueue, checkSetImageDisabled, - l10n: this.l10n + l10n: this.l10n, + pageColors: this.pageColors }); this._thumbnails.push(thumbnail); @@ -9055,7 +9068,6 @@ class TempImageFactory { const tempCanvas = this.#tempCanvas ||= document.createElement("canvas"); tempCanvas.width = width; tempCanvas.height = height; - tempCanvas.mozOpaque = true; const ctx = tempCanvas.getContext("2d", { alpha: false }); @@ -9090,7 +9102,8 @@ class PDFThumbnailView { linkService, renderingQueue, checkSetImageDisabled, - l10n + l10n, + pageColors }) { this.id = id; this.renderingId = "thumbnail" + id; @@ -9100,6 +9113,7 @@ class PDFThumbnailView { this.viewport = defaultViewport; this.pdfPageRotate = defaultViewport.rotation; this._optionalContentConfigPromise = optionalContentConfigPromise || null; + this.pageColors = pageColors || null; this.linkService = linkService; this.renderingQueue = renderingQueue; this.renderTask = null; @@ -9209,7 +9223,6 @@ class PDFThumbnailView { _getPageDrawContext(upscaleFactor = 1) { const canvas = document.createElement("canvas"); - canvas.mozOpaque = true; const ctx = canvas.getContext("2d", { alpha: false }); @@ -9312,7 +9325,8 @@ class PDFThumbnailView { canvasContext: ctx, transform, viewport: drawViewport, - optionalContentConfigPromise: this._optionalContentConfigPromise + optionalContentConfigPromise: this._optionalContentConfigPromise, + pageColors: this.pageColors }; const renderTask = this.renderTask = pdfPage.render(renderContext); renderTask.onContinue = renderContinueCallback; @@ -9584,7 +9598,7 @@ class BaseViewer { throw new Error("Cannot initialize BaseViewer."); } - const viewerVersion = '2.14.290'; + const viewerVersion = '2.15.51'; if (_pdfjsLib.version !== viewerVersion) { throw new Error(`The API version "${_pdfjsLib.version}" does not match the Viewer version "${viewerVersion}".`); @@ -9617,7 +9631,6 @@ class BaseViewer { this.renderingQueue = options.renderingQueue; } - this._doc = document.documentElement; this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this)); this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN; this._onBeforeDraw = this._onAfterDraw = null; @@ -10257,7 +10270,7 @@ class BaseViewer { return; } - this._doc.style.setProperty("--zoom-factor", newScale); + _ui_utils.docStyle.setProperty("--zoom-factor", newScale); const updateArgs = { scale: newScale @@ -11160,7 +11173,7 @@ class BaseViewer { if (height !== this.#previousContainerHeight) { this.#previousContainerHeight = height; - this._doc.style.setProperty("--viewer-container-height", `${height}px`); + _ui_utils.docStyle.setProperty("--viewer-container-height", `${height}px`); } } @@ -11658,10 +11671,7 @@ class PDFPageView { }); if (this._isStandalone) { - const { - style - } = document.documentElement; - style.setProperty("--zoom-factor", this.scale); + _ui_utils.docStyle.setProperty("--zoom-factor", this.scale); } if (this.svg) { @@ -12063,7 +12073,6 @@ class PDFPageView { canvasWrapper.appendChild(canvas); this.canvas = canvas; - canvas.mozOpaque = true; const ctx = canvas.getContext("2d", { alpha: false }); @@ -13249,8 +13258,7 @@ class Toolbar { this.eventBus._on("localized", () => { this._wasLocalized = true; - - this._adjustScaleWidth(); + this.#adjustScaleWidth(); this._updateUIState(true); }); @@ -13327,21 +13335,20 @@ class Toolbar { pageNumberInput.classList.toggle(PAGE_NUMBER_LOADING_INDICATOR, loading); } - async _adjustScaleWidth() { + async #adjustScaleWidth() { const { items, l10n } = this; const predefinedValuesPromise = Promise.all([l10n.get("page_scale_auto"), l10n.get("page_scale_actual"), l10n.get("page_scale_fit"), l10n.get("page_scale_width")]); + await _ui_utils.animationStarted; const style = getComputedStyle(items.scaleSelect), scaleSelectContainerWidth = parseInt(style.getPropertyValue("--scale-select-container-width"), 10), scaleSelectOverflow = parseInt(style.getPropertyValue("--scale-select-overflow"), 10); - let canvas = document.createElement("canvas"); - canvas.mozOpaque = true; - let ctx = canvas.getContext("2d", { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d", { alpha: false }); - await _ui_utils.animationStarted; ctx.font = `${style.fontSize} ${style.fontFamily}`; let maxWidth = 0; @@ -13358,13 +13365,11 @@ class Toolbar { maxWidth += 2 * scaleSelectOverflow; if (maxWidth > scaleSelectContainerWidth) { - const doc = document.documentElement; - doc.style.setProperty("--scale-select-container-width", `${maxWidth}px`); + _ui_utils.docStyle.setProperty("--scale-select-container-width", `${maxWidth}px`); } canvas.width = 0; canvas.height = 0; - canvas = ctx = null; } } @@ -13557,13 +13562,11 @@ class DownloadManager { const blobUrl = URL.createObjectURL(new Blob([data], { type: contentType })); - FirefoxCom.requestAsync("download", { + FirefoxCom.request("download", { blobUrl, originalUrl: blobUrl, filename, isAttachment: true - }).then(error => { - URL.revokeObjectURL(blobUrl); }); } @@ -13599,19 +13602,12 @@ class DownloadManager { return false; } - download(blob, url, filename, sourceEventType = "download") { + download(blob, url, filename) { const blobUrl = URL.createObjectURL(blob); - FirefoxCom.requestAsync("download", { + FirefoxCom.request("download", { blobUrl, originalUrl: url, - filename, - sourceEventType - }).then(error => { - if (error) { - console.error("`ChromeActions.download` failed."); - } - - URL.revokeObjectURL(blobUrl); + filename }); } @@ -13726,7 +13722,7 @@ class MozL10n { return; } - _app.PDFViewerApplication.eventBus.dispatch(type, { + _app.PDFViewerApplication.eventBus.dispatch("download", { source: window }); }; @@ -14373,8 +14369,8 @@ var _app_options = __webpack_require__(1); var _app = __webpack_require__(2); -const pdfjsVersion = '2.14.290'; -const pdfjsBuild = '38c82357b'; +const pdfjsVersion = '2.15.51'; +const pdfjsBuild = '195396768'; window.PDFViewerApplication = _app.PDFViewerApplication; window.PDFViewerApplicationOptions = _app_options.AppOptions; ; diff --git a/toolkit/components/pdfjs/moz.yaml b/toolkit/components/pdfjs/moz.yaml index 9b35ab3f33625..1097988de820b 100644 --- a/toolkit/components/pdfjs/moz.yaml +++ b/toolkit/components/pdfjs/moz.yaml @@ -20,8 +20,8 @@ origin: # Human-readable identifier for this version/release # Generally "version NNN", "tag SSS", "bookmark SSS" - release: commit 38c82357b247199b11fb573d0a3d4201347a47fc - revision: 38c82357b247199b11fb573d0a3d4201347a47fc + release: 19539676813b5df6ca4726a1bfa6765193b1067c (2022-06-02T14:52:48Z). + revision: 19539676813b5df6ca4726a1bfa6765193b1067c # The package's license, where possible using the mnemonic from # https://spdx.org/licenses/