1
0
Fork 0
mirror of https://github.com/mozilla/pdf.js.git synced 2025-04-22 16:18:08 +02:00

[api-minor] Replace the PromiseCapability with Promise.withResolvers()

This replaces our custom `PromiseCapability`-class with the new native `Promise.withResolvers()` functionality, which does *almost* the same thing[1]; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers

The only difference is that `PromiseCapability` also had a `settled`-getter, which was however not widely used and the call-sites can either be removed or re-factored to avoid it. In particular:
 - In `src/display/api.js` we can tweak the `PDFObjects`-class to use a "special" initial data-value and just compare against that, in order to replace the `settled`-state.
 - In `web/app.js` we change the only case to manually track the `settled`-state, which should hopefully be OK given how this is being used.
 - In `web/pdf_outline_viewer.js` we can remove the `settled`-checks, since the code should work just fine without it. The only thing that could potentially happen is that we try to `resolve` a Promise multiple times, which is however *not* a problem since the value of a Promise cannot be changed once fulfilled or rejected.
 - In `web/pdf_viewer.js` we can remove the `settled`-checks, since the code should work fine without them:
     - For the `_onePageRenderedCapability` case the `settled`-check is used in a `EventBus`-listener which is *removed* on its first (valid) invocation.
     - For the `_pagesCapability` case the `settled`-check is used in a print-related helper that works just fine with "only" the other checks.
 - In `test/unit/api_spec.js` we can change the few relevant cases to manually track the `settled`-state, since this is both simple and *test-only* code.

---
[1] In browsers/environments that lack native support, note [the compatibility data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers#browser_compatibility), it'll be polyfilled via the `core-js` library (but only in `legacy` builds).
This commit is contained in:
Jonas Jenwald 2024-03-28 16:42:37 +01:00
parent 55db43966e
commit e4d0e84802
28 changed files with 159 additions and 252 deletions

View file

@ -14,7 +14,7 @@
*/
import { arrayBuffersToBytes, MissingDataException } from "./core_utils.js";
import { assert, PromiseCapability } from "../shared/util.js";
import { assert } from "../shared/util.js";
import { Stream } from "./stream.js";
class ChunkedStream extends Stream {
@ -273,7 +273,7 @@ class ChunkedStreamManager {
this.progressiveDataLength = 0;
this.aborted = false;
this._loadedStreamCapability = new PromiseCapability();
this._loadedStreamCapability = Promise.withResolvers();
}
sendRequest(begin, end) {
@ -347,7 +347,7 @@ class ChunkedStreamManager {
return Promise.resolve();
}
const capability = new PromiseCapability();
const capability = Promise.withResolvers();
this._promisesByRequest.set(requestId, capability);
const chunksToRequest = [];

View file

@ -25,7 +25,6 @@ import {
isArrayEqual,
normalizeUnicode,
OPS,
PromiseCapability,
shadow,
stringToPDFString,
TextRenderingMode,
@ -1270,7 +1269,7 @@ class PartialEvaluator {
return this.fontCache.get(font.cacheKey);
}
const fontCapability = new PromiseCapability();
const { promise, resolve } = Promise.withResolvers();
let preEvaluatedFont;
try {
@ -1328,10 +1327,10 @@ class PartialEvaluator {
// keys. Also, since `fontRef` is used when getting cached fonts,
// we'll not accidentally match fonts cached with the `fontID`.
if (fontRefIsRef) {
this.fontCache.put(fontRef, fontCapability.promise);
this.fontCache.put(fontRef, promise);
} else {
font.cacheKey = `cacheKey_${fontID}`;
this.fontCache.put(font.cacheKey, fontCapability.promise);
this.fontCache.put(font.cacheKey, promise);
}
// Keep track of each font we translated so the caller can
@ -1340,7 +1339,7 @@ class PartialEvaluator {
this.translateFont(preEvaluatedFont)
.then(translatedFont => {
fontCapability.resolve(
resolve(
new TranslatedFont({
loadedName: font.loadedName,
font: translatedFont,
@ -1350,10 +1349,10 @@ class PartialEvaluator {
);
})
.catch(reason => {
// TODO fontCapability.reject?
// TODO reject?
warn(`loadFont - translateFont failed: "${reason}".`);
fontCapability.resolve(
resolve(
new TranslatedFont({
loadedName: font.loadedName,
font: new ErrorFont(
@ -1364,7 +1363,7 @@ class PartialEvaluator {
})
);
});
return fontCapability.promise;
return promise;
}
buildPath(operatorList, fn, args, parsingText = false) {

View file

@ -22,7 +22,6 @@ import {
isNodeJS,
MissingPDFException,
PasswordException,
PromiseCapability,
setVerbosityLevel,
stringToPDFString,
UnexpectedResponseException,
@ -48,7 +47,7 @@ class WorkerTask {
constructor(name) {
this.name = name;
this.terminated = false;
this._capability = new PromiseCapability();
this._capability = Promise.withResolvers();
}
get finished() {
@ -212,7 +211,7 @@ class WorkerMessageHandler {
password,
rangeChunkSize,
};
const pdfManagerCapability = new PromiseCapability();
const pdfManagerCapability = Promise.withResolvers();
let newPdfManager;
if (data) {

View file

@ -28,7 +28,6 @@ import {
MAX_IMAGE_SIZE_TO_CACHE,
MissingPDFException,
PasswordException,
PromiseCapability,
RenderingIntentFlag,
setVerbosityLevel,
shadow,
@ -577,7 +576,7 @@ class PDFDocumentLoadingTask {
static #docId = 0;
constructor() {
this._capability = new PromiseCapability();
this._capability = Promise.withResolvers();
this._transport = null;
this._worker = null;
@ -674,7 +673,7 @@ class PDFDataRangeTransport {
this._progressListeners = [];
this._progressiveReadListeners = [];
this._progressiveDoneListeners = [];
this._readyCapability = new PromiseCapability();
this._readyCapability = Promise.withResolvers();
}
/**
@ -1461,7 +1460,7 @@ class PDFPageProxy {
// If there's no displayReadyCapability yet, then the operatorList
// was never requested before. Make the request and create the promise.
if (!intentState.displayReadyCapability) {
intentState.displayReadyCapability = new PromiseCapability();
intentState.displayReadyCapability = Promise.withResolvers();
intentState.operatorList = {
fnArray: [],
argsArray: [],
@ -1588,7 +1587,7 @@ class PDFPageProxy {
if (!intentState.opListReadCapability) {
opListTask = Object.create(null);
opListTask.operatorListChanged = operatorListChanged;
intentState.opListReadCapability = new PromiseCapability();
intentState.opListReadCapability = Promise.withResolvers();
(intentState.renderTasks ||= new Set()).add(opListTask);
intentState.operatorList = {
fnArray: [],
@ -2049,7 +2048,7 @@ class PDFWorker {
this.destroyed = false;
this.verbosity = verbosity;
this._readyCapability = new PromiseCapability();
this._readyCapability = Promise.withResolvers();
this._port = null;
this._webWorker = null;
this._messageHandler = null;
@ -2365,7 +2364,7 @@ class WorkerTransport {
this._networkStream = networkStream;
this._fullReader = null;
this._lastProgress = null;
this.downloadInfoCapability = new PromiseCapability();
this.downloadInfoCapability = Promise.withResolvers();
this.setupMessageHandler();
@ -2471,7 +2470,7 @@ class WorkerTransport {
}
this.destroyed = true;
this.destroyCapability = new PromiseCapability();
this.destroyCapability = Promise.withResolvers();
this.#passwordCapability?.reject(
new Error("Worker was destroyed during onPassword callback")
@ -2562,7 +2561,7 @@ class WorkerTransport {
});
messageHandler.on("ReaderHeadersReady", data => {
const headersCapability = new PromiseCapability();
const headersCapability = Promise.withResolvers();
const fullReader = this._fullReader;
fullReader.headersReady.then(() => {
// If stream or range are disabled, it's our only way to report
@ -2677,7 +2676,7 @@ class WorkerTransport {
});
messageHandler.on("PasswordRequest", exception => {
this.#passwordCapability = new PromiseCapability();
this.#passwordCapability = Promise.withResolvers();
if (loadingTask.onPassword) {
const updatePassword = password => {
@ -3089,6 +3088,8 @@ class WorkerTransport {
}
}
const INITIAL_DATA = Symbol("INITIAL_DATA");
/**
* A PDF document and page is built of many objects. E.g. there are objects for
* fonts, images, rendering code, etc. These objects may get processed inside of
@ -3105,8 +3106,8 @@ class PDFObjects {
*/
#ensureObj(objId) {
return (this.#objs[objId] ||= {
capability: new PromiseCapability(),
data: null,
...Promise.withResolvers(),
data: INITIAL_DATA,
});
}
@ -3127,7 +3128,7 @@ class PDFObjects {
// not required to be resolved right now.
if (callback) {
const obj = this.#ensureObj(objId);
obj.capability.promise.then(() => callback(obj.data));
obj.promise.then(() => callback(obj.data));
return null;
}
// If there isn't a callback, the user expects to get the resolved data
@ -3135,7 +3136,7 @@ class PDFObjects {
const obj = this.#objs[objId];
// If there isn't an object yet or the object isn't resolved, then the
// data isn't ready yet!
if (!obj?.capability.settled) {
if (!obj || obj.data === INITIAL_DATA) {
throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
}
return obj.data;
@ -3147,7 +3148,7 @@ class PDFObjects {
*/
has(objId) {
const obj = this.#objs[objId];
return obj?.capability.settled ?? false;
return !!obj && obj.data !== INITIAL_DATA;
}
/**
@ -3159,7 +3160,7 @@ class PDFObjects {
resolve(objId, data = null) {
const obj = this.#ensureObj(objId);
obj.data = data;
obj.capability.resolve();
obj.resolve();
}
clear() {
@ -3172,9 +3173,9 @@ class PDFObjects {
*[Symbol.iterator]() {
for (const objId in this.#objs) {
const { capability, data } = this.#objs[objId];
const { data } = this.#objs[objId];
if (!capability.settled) {
if (data === INITIAL_DATA) {
continue;
}
yield [objId, data];
@ -3283,7 +3284,7 @@ class InternalRenderTask {
this._useRequestAnimationFrame =
useRequestAnimationFrame === true && typeof window !== "undefined";
this.cancelled = false;
this.capability = new PromiseCapability();
this.capability = Promise.withResolvers();
this.task = new RenderTask(this);
// caching this-bound methods
this._cancelBound = this.cancel.bind(this);

View file

@ -13,12 +13,7 @@
* limitations under the License.
*/
import {
AbortException,
assert,
PromiseCapability,
warn,
} from "../shared/util.js";
import { AbortException, assert, warn } from "../shared/util.js";
import {
createResponseStatusError,
extractFilenameFromHeader,
@ -118,7 +113,7 @@ class PDFFetchStreamReader {
const source = stream.source;
this._withCredentials = source.withCredentials || false;
this._contentLength = source.length;
this._headersCapability = new PromiseCapability();
this._headersCapability = Promise.withResolvers();
this._disableRange = source.disableRange || false;
this._rangeChunkSize = source.rangeChunkSize;
if (!this._rangeChunkSize && !this._disableRange) {
@ -223,7 +218,7 @@ class PDFFetchStreamRangeReader {
this._loaded = 0;
const source = stream.source;
this._withCredentials = source.withCredentials || false;
this._readCapability = new PromiseCapability();
this._readCapability = Promise.withResolvers();
this._isStreamingSupported = !source.disableStream;
this._abortController = new AbortController();

View file

@ -13,7 +13,7 @@
* limitations under the License.
*/
import { assert, PromiseCapability, stringToBytes } from "../shared/util.js";
import { assert, stringToBytes } from "../shared/util.js";
import {
createResponseStatusError,
extractFilenameFromHeader,
@ -255,7 +255,7 @@ class PDFNetworkStreamFullRequestReader {
};
this._url = source.url;
this._fullRequestId = manager.requestFull(args);
this._headersReceivedCapability = new PromiseCapability();
this._headersReceivedCapability = Promise.withResolvers();
this._disableRange = source.disableRange || false;
this._contentLength = source.length; // Optional
this._rangeChunkSize = source.rangeChunkSize;
@ -375,7 +375,7 @@ class PDFNetworkStreamFullRequestReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = new PromiseCapability();
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}
@ -466,7 +466,7 @@ class PDFNetworkStreamRangeRequestReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = new PromiseCapability();
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}

View file

@ -18,7 +18,6 @@ import {
assert,
isNodeJS,
MissingPDFException,
PromiseCapability,
} from "../shared/util.js";
import {
extractFilenameFromHeader,
@ -128,8 +127,8 @@ class BaseFullReader {
this._isRangeSupported = !source.disableRange;
this._readableStream = null;
this._readCapability = new PromiseCapability();
this._headersCapability = new PromiseCapability();
this._readCapability = Promise.withResolvers();
this._headersCapability = Promise.withResolvers();
}
get headersReady() {
@ -163,7 +162,7 @@ class BaseFullReader {
const chunk = this._readableStream.read();
if (chunk === null) {
this._readCapability = new PromiseCapability();
this._readCapability = Promise.withResolvers();
return this.read();
}
this._loaded += chunk.length;
@ -230,7 +229,7 @@ class BaseRangeReader {
this.onProgress = null;
this._loaded = 0;
this._readableStream = null;
this._readCapability = new PromiseCapability();
this._readCapability = Promise.withResolvers();
const source = stream.source;
this._isStreamingSupported = !source.disableStream;
}
@ -250,7 +249,7 @@ class BaseRangeReader {
const chunk = this._readableStream.read();
if (chunk === null) {
this._readCapability = new PromiseCapability();
this._readCapability = Promise.withResolvers();
return this.read();
}
this._loaded += chunk.length;

View file

@ -16,7 +16,7 @@
/** @typedef {import("./display_utils").PageViewport} PageViewport */
/** @typedef {import("./api").TextContent} TextContent */
import { AbortException, PromiseCapability, Util } from "../shared/util.js";
import { AbortException, Util } from "../shared/util.js";
import { setLayerDimensions } from "./display_utils.js";
/**
@ -326,7 +326,7 @@ class TextLayerRenderTask {
this._reader = null;
this._textDivProperties = textDivProperties || new WeakMap();
this._canceled = false;
this._capability = new PromiseCapability();
this._capability = Promise.withResolvers();
this._layoutTextParams = {
prevFontSize: null,
prevFontFamily: null,
@ -426,21 +426,21 @@ class TextLayerRenderTask {
* @private
*/
_render() {
const capability = new PromiseCapability();
const { promise, resolve, reject } = Promise.withResolvers();
let styleCache = Object.create(null);
if (this._isReadableStream) {
const pump = () => {
this._reader.read().then(({ value, done }) => {
if (done) {
capability.resolve();
resolve();
return;
}
Object.assign(styleCache, value.styles);
this._processItems(value.items, styleCache);
pump();
}, capability.reject);
}, reject);
};
this._reader = this._textContentSource.getReader();
@ -448,12 +448,12 @@ class TextLayerRenderTask {
} else if (this._textContentSource) {
const { items, styles } = this._textContentSource;
this._processItems(items, styles);
capability.resolve();
resolve();
} else {
throw new Error('No "textContentSource" parameter specified.');
}
capability.promise.then(() => {
promise.then(() => {
styleCache = null;
render(this);
}, this._capability.reject);

View file

@ -18,7 +18,7 @@
// eslint-disable-next-line max-len
/** @typedef {import("../interfaces").IPDFStreamRangeReader} IPDFStreamRangeReader */
import { assert, PromiseCapability } from "../shared/util.js";
import { assert } from "../shared/util.js";
import { isPdfFile } from "./display_utils.js";
/** @implements {IPDFStream} */
@ -235,7 +235,7 @@ class PDFDataTransportStreamReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = new PromiseCapability();
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}
@ -300,7 +300,7 @@ class PDFDataTransportStreamRangeReader {
if (this._done) {
return { value: undefined, done: true };
}
const requestCapability = new PromiseCapability();
const requestCapability = Promise.withResolvers();
this._requests.push(requestCapability);
return requestCapability.promise;
}

View file

@ -39,7 +39,6 @@ import {
OPS,
PasswordResponses,
PermissionFlag,
PromiseCapability,
shadow,
UnexpectedResponseException,
Util,
@ -119,7 +118,6 @@ export {
PDFWorker,
PermissionFlag,
PixelsPerInch,
PromiseCapability,
RenderingCancelledException,
renderTextLayer,
setLayerDimensions,

View file

@ -18,7 +18,6 @@ import {
assert,
MissingPDFException,
PasswordException,
PromiseCapability,
UnexpectedResponseException,
UnknownErrorException,
unreachable,
@ -190,7 +189,7 @@ class MessageHandler {
*/
sendWithPromise(actionName, data, transfers) {
const callbackId = this.callbackId++;
const capability = new PromiseCapability();
const capability = Promise.withResolvers();
this.callbackCapabilities[callbackId] = capability;
try {
this.comObj.postMessage(
@ -228,7 +227,7 @@ class MessageHandler {
return new ReadableStream(
{
start: controller => {
const startCapability = new PromiseCapability();
const startCapability = Promise.withResolvers();
this.streamControllers[streamId] = {
controller,
startCall: startCapability,
@ -252,7 +251,7 @@ class MessageHandler {
},
pull: controller => {
const pullCapability = new PromiseCapability();
const pullCapability = Promise.withResolvers();
this.streamControllers[streamId].pullCall = pullCapability;
comObj.postMessage({
sourceName,
@ -268,7 +267,7 @@ class MessageHandler {
cancel: reason => {
assert(reason instanceof Error, "cancel must have a valid reason");
const cancelCapability = new PromiseCapability();
const cancelCapability = Promise.withResolvers();
this.streamControllers[streamId].cancelCall = cancelCapability;
this.streamControllers[streamId].isClosed = true;
comObj.postMessage({
@ -305,7 +304,7 @@ class MessageHandler {
// so when it changes from positive to negative,
// set ready as unresolved promise.
if (lastDesiredSize > 0 && this.desiredSize <= 0) {
this.sinkCapability = new PromiseCapability();
this.sinkCapability = Promise.withResolvers();
this.ready = this.sinkCapability.promise;
}
comObj.postMessage(
@ -349,7 +348,7 @@ class MessageHandler {
});
},
sinkCapability: new PromiseCapability(),
sinkCapability: Promise.withResolvers(),
onPull: null,
onCancel: null,
isCancelled: false,

View file

@ -1031,43 +1031,6 @@ function getModificationDate(date = new Date()) {
return buffer.join("");
}
class PromiseCapability {
#settled = false;
constructor() {
/**
* @type {Promise<any>} The Promise object.
*/
this.promise = new Promise((resolve, reject) => {
/**
* @type {function} Fulfills the Promise.
*/
this.resolve = data => {
this.#settled = true;
resolve(data);
};
/**
* @type {function} Rejects the Promise.
*/
this.reject = reason => {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
assert(reason instanceof Error, 'Expected valid "reason" argument.');
}
this.#settled = true;
reject(reason);
};
});
}
/**
* @type {boolean} If the Promise has been fulfilled/rejected.
*/
get settled() {
return this.#settled;
}
}
let NormalizeRegex = null;
let NormalizationMap = null;
function normalizeUnicode(str) {
@ -1154,7 +1117,6 @@ export {
PasswordException,
PasswordResponses,
PermissionFlag,
PromiseCapability,
RenderingIntentFlag,
setVerbosityLevel,
shadow,