Skip to content

Commit

Permalink
WebExtension class (#551)
Browse files Browse the repository at this point in the history
* Add WebExtension class

* Use WebExtension class

* Use WebExtension instance for all runtime message sending

* Use getUrl

* Add a sendMessage variant which ignores the response and error
  • Loading branch information
toasted-nutbread authored Jan 21, 2024
1 parent ebdde1e commit 6ba1ffe
Show file tree
Hide file tree
Showing 13 changed files with 179 additions and 124 deletions.
8 changes: 4 additions & 4 deletions ext/js/app/frontend.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ export class Frontend {
try {
await this._updateOptionsInternal();
} catch (e) {
if (!yomitan.isExtensionUnloaded) {
if (!yomitan.webExtension.unloaded) {
throw e;
}
}
Expand Down Expand Up @@ -368,7 +368,7 @@ export class Frontend {
const scanningOptions = /** @type {import('settings').ProfileOptions} */ (this._options).scanning;

if (error !== null) {
if (yomitan.isExtensionUnloaded) {
if (yomitan.webExtension.unloaded) {
if (textSource !== null && !passive) {
this._showExtensionUnloaded(textSource);
}
Expand Down Expand Up @@ -655,7 +655,7 @@ export class Frontend {
try {
return this._popup !== null && await this._popup.containsPoint(x, y);
} catch (e) {
if (!yomitan.isExtensionUnloaded) {
if (!yomitan.webExtension.unloaded) {
throw e;
}
return false;
Expand Down Expand Up @@ -742,7 +742,7 @@ export class Frontend {
Promise.resolve()
);
this._lastShowPromise.catch((error) => {
if (yomitan.isExtensionUnloaded) { return; }
if (yomitan.webExtension.unloaded) { return; }
log.error(error);
});
return this._lastShowPromise;
Expand Down
2 changes: 1 addition & 1 deletion ext/js/app/popup-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ export class PopupProxy extends EventDispatcher {
try {
return await this._invoke(action, params);
} catch (e) {
if (!yomitan.isExtensionUnloaded) { throw e; }
if (!yomitan.webExtension.unloaded) { throw e; }
return defaultReturnValue;
}
}
Expand Down
4 changes: 2 additions & 2 deletions ext/js/app/popup-window.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ export class PopupWindow extends EventDispatcher {
* @returns {Promise<import('display').DirectApiReturn<TName>|undefined>}
*/
async _invoke(open, action, params) {
if (yomitan.isExtensionUnloaded) {
if (yomitan.webExtension.unloaded) {
return void 0;
}

Expand All @@ -290,7 +290,7 @@ export class PopupWindow extends EventDispatcher {
message
));
} catch (e) {
if (yomitan.isExtensionUnloaded) {
if (yomitan.webExtension.unloaded) {
open = false;
}
}
Expand Down
2 changes: 1 addition & 1 deletion ext/js/app/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,7 @@ export class Popup extends EventDispatcher {
try {
return await this._invoke(action, params);
} catch (e) {
if (!yomitan.isExtensionUnloaded) { throw e; }
if (!yomitan.webExtension.unloaded) { throw e; }
return void 0;
}
}
Expand Down
11 changes: 6 additions & 5 deletions ext/js/background/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,11 @@ import {injectStylesheet} from './script-manager.js';
*/
export class Backend {
/**
* Creates a new instance.
* @param {import('../extension/web-extension.js').WebExtension} webExtension
*/
constructor() {
constructor(webExtension) {
/** @type {import('../extension/web-extension.js').WebExtension} */
this._webExtension = webExtension;
/** @type {JapaneseUtil} */
this._japaneseUtil = new JapaneseUtil(wanakana);
/** @type {Environment} */
Expand Down Expand Up @@ -80,7 +82,7 @@ export class Backend {
});
} else {
/** @type {?OffscreenProxy} */
this._offscreen = new OffscreenProxy();
this._offscreen = new OffscreenProxy(webExtension);
/** @type {DictionaryDatabase|DictionaryDatabaseProxy} */
this._dictionaryDatabase = new DictionaryDatabaseProxy(this._offscreen);
/** @type {Translator|TranslatorProxy} */
Expand Down Expand Up @@ -1902,8 +1904,7 @@ export class Backend {
* @param {import('application').ApiMessage<TName>} message
*/
_sendMessageIgnoreResponse(message) {
const callback = () => this._checkLastError(chrome.runtime.lastError);
chrome.runtime.sendMessage(message, callback);
this._webExtension.sendMessageIgnoreResponse(message);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion ext/js/background/background-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {Backend} from './backend.js';
async function main() {
yomitan.prepare(true);

const backend = new Backend();
const backend = new Backend(yomitan.webExtension);
await backend.prepare();
}

Expand Down
22 changes: 10 additions & 12 deletions ext/js/background/offscreen-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import {isObject} from '../core/utilities.js';
import {ExtensionError} from '../core/extension-error.js';
import {isObject} from '../core/utilities.js';
import {ArrayBufferUtil} from '../data/sandbox/array-buffer-util.js';

export class OffscreenProxy {
constructor() {
/**
* @param {import('../extension/web-extension.js').WebExtension} webExtension
*/
constructor(webExtension) {
/** @type {import('../extension/web-extension.js').WebExtension} */
this._webExtension = webExtension;
/** @type {?Promise<void>} */
this._creatingOffscreen = null;
}
Expand Down Expand Up @@ -76,16 +81,9 @@ export class OffscreenProxy {
* @param {import('offscreen').ApiMessage<TMessageType>} message
* @returns {Promise<import('offscreen').ApiReturn<TMessageType>>}
*/
sendMessagePromise(message) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response) => {
try {
resolve(this._getMessageResponseResult(response));
} catch (error) {
reject(error);
}
});
});
async sendMessagePromise(message) {
const response = await this._webExtension.sendMessagePromise(message);
return this._getMessageResponseResult(/** @type {import('core').Response<import('offscreen').ApiReturn<TMessageType>>} */ (response));
}

/**
Expand Down
27 changes: 11 additions & 16 deletions ext/js/comm/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ import {ExtensionError} from '../core/extension-error.js';

export class API {
/**
* @param {import('../yomitan.js').Yomitan} yomitan
* @param {import('../extension/web-extension.js').WebExtension} webExtension
*/
constructor(yomitan) {
/** @type {import('../yomitan.js').Yomitan} */
this._yomitan = yomitan;
constructor(webExtension) {
/** @type {import('../extension/web-extension.js').WebExtension} */
this._webExtension = webExtension;
}

/**
Expand Down Expand Up @@ -375,13 +375,15 @@ export class API {
const data = {action, params};
return new Promise((resolve, reject) => {
try {
this._yomitan.sendMessage(data, (response) => {
this._checkLastError(chrome.runtime.lastError);
this._webExtension.sendMessage(data, (response) => {
this._webExtension.getLastError();
if (response !== null && typeof response === 'object') {
if (typeof response.error !== 'undefined') {
reject(ExtensionError.deserialize(response.error));
const {error} = /** @type {import('core').UnknownObject} */ (response);
if (typeof error !== 'undefined') {
reject(ExtensionError.deserialize(/** @type {import('core').SerializedError} */ (error)));
} else {
resolve(response.result);
const {result} = /** @type {import('core').UnknownObject} */ (response);
resolve(/** @type {import('api').ApiReturn<TAction>} */ (result));
}
} else {
const message = response === null ? 'Unexpected null response' : `Unexpected response of type ${typeof response}`;
Expand All @@ -393,11 +395,4 @@ export class API {
}
});
}

/**
* @param {chrome.runtime.LastError|undefined} _ignore
*/
_checkLastError(_ignore) {
// NOP
}
}
7 changes: 3 additions & 4 deletions ext/js/display/display.js
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ export class Display extends EventDispatcher {
* @param {Error} error
*/
onError(error) {
if (yomitan.isExtensionUnloaded) { return; }
if (yomitan.webExtension.unloaded) { return; }
log.error(error);
}

Expand Down Expand Up @@ -727,8 +727,7 @@ export class Display extends EventDispatcher {

/** @type {import('display').WindowApiHandler<'displayExtensionUnloaded'>} */
_onMessageExtensionUnloaded() {
if (yomitan.isExtensionUnloaded) { return; }
yomitan.triggerExtensionUnloaded();
yomitan.webExtension.triggerUnloaded();
}

// Private
Expand Down Expand Up @@ -1894,7 +1893,7 @@ export class Display extends EventDispatcher {
* @param {import('text-scanner').SearchedEventDetails} details
*/
_onContentTextScannerSearched({type, dictionaryEntries, sentence, textSource, optionsContext, error}) {
if (error !== null && !yomitan.isExtensionUnloaded) {
if (error !== null && !yomitan.webExtension.unloaded) {
log.error(error);
}

Expand Down
107 changes: 107 additions & 0 deletions ext/js/extension/web-extension.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2024 Yomitan Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import {EventDispatcher} from '../core/event-dispatcher.js';
import {toError} from '../core/to-error.js';

/**
* @augments EventDispatcher<import('web-extension').Events>
*/
export class WebExtension extends EventDispatcher {
constructor() {
super();
/** @type {boolean} */
this._unloaded = false;
}

/** @type {boolean} */
get unloaded() {
return this._unloaded;
}

/**
* @param {string} path
* @returns {string}
*/
getUrl(path) {
return chrome.runtime.getURL(path);
}

/**
* @param {unknown} message
* @param {(response: unknown) => void} responseCallback
* @throws {Error}
*/
sendMessage(message, responseCallback) {
try {
chrome.runtime.sendMessage(message, responseCallback);
} catch (error) {
this.triggerUnloaded();
throw toError(error);
}
}

/**
* @param {unknown} message
* @returns {Promise<unknown>}
*/
sendMessagePromise(message) {
return new Promise((resolve, reject) => {
try {
this.sendMessage(message, (response) => {
const error = this.getLastError();
if (error !== null) {
reject(error);
} else {
resolve(response);
}
});
} catch (error) {
reject(error);
}
});
}

/**
* @param {unknown} message
*/
sendMessageIgnoreResponse(message) {
this.sendMessage(message, () => {
// Clear the last error
this.getLastError();
});
}

/**
* @returns {?Error}
*/
getLastError() {
const {lastError} = chrome.runtime;
if (typeof lastError !== 'undefined') {
const {message} = lastError;
return new Error(typeof message === 'string' ? message : 'An unknown web extension error occured');
}
return null;
}

/** */
triggerUnloaded() {
if (this._unloaded) { return; }
this._unloaded = true;
this.trigger('unloaded', {});
}
}
Loading

0 comments on commit 6ba1ffe

Please sign in to comment.