Pop-up dictionary browser extension for language learning. Successor to Yomichan. (PERSONAL FORK)
1/*
2 * Copyright (C) 2023-2025 Yomitan Authors
3 * Copyright (C) 2016-2022 Yomichan Authors
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19import {ExtensionError} from '../core/extension-error.js';
20import {isObjectNotArray} from '../core/object-utilities.js';
21import {base64ToArrayBuffer} from '../data/array-buffer-util.js';
22
23/**
24 * This class is responsible for creating and communicating with an offscreen document.
25 * This offscreen document is used to solve three issues:
26 *
27 * - Provide clipboard access for the `ClipboardReader` class in the context of a MV3 extension.
28 * The background service workers doesn't have access a webpage to read the clipboard from,
29 * so it must be done in the offscreen page.
30 *
31 * - Create a worker for image rendering, which both selects the images from the database,
32 * decodes/rasterizes them, and then sends (= postMessage transfers) them back to a worker
33 * in the popup to be rendered onto OffscreenCanvas.
34 *
35 * - Provide a longer lifetime for the dictionary database. The background service worker can be
36 * terminated by the web browser, which means that when it restarts, it has to go through its
37 * initialization process again. This initialization process can take a non-trivial amount of
38 * time, which is primarily caused by the startup of the IndexedDB database, especially when a
39 * large amount of dictionary data is installed.
40 *
41 * The offscreen document stays alive longer, potentially forever, which may be an artifact of
42 * the clipboard access it requests in the `reasons` parameter. Therefore, this initialization
43 * process should only take place once, or at the very least, less frequently than the service
44 * worker.
45 *
46 * The long lifetime of the offscreen document is not guaranteed by the spec, which could
47 * result in this code functioning poorly in the future if a web browser vendor changes the
48 * APIs or the implementation substantially, and this is even referenced on the Chrome
49 * developer website.
50 * @see https://developer.chrome.com/blog/Offscreen-Documents-in-Manifest-v3
51 * @see https://developer.chrome.com/docs/extensions/reference/api/offscreen
52 */
53export class OffscreenProxy {
54 /**
55 * @param {import('../extension/web-extension.js').WebExtension} webExtension
56 */
57 constructor(webExtension) {
58 /** @type {import('../extension/web-extension.js').WebExtension} */
59 this._webExtension = webExtension;
60 /** @type {?Promise<void>} */
61 this._creatingOffscreen = null;
62
63 /** @type {?MessagePort} */
64 this._currentOffscreenPort = null;
65 }
66
67 /**
68 * @see https://developer.chrome.com/docs/extensions/reference/offscreen/
69 */
70 async prepare() {
71 if (await this._hasOffscreenDocument()) {
72 void this.sendMessagePromise({action: 'createAndRegisterPortOffscreen'});
73 return;
74 }
75 if (this._creatingOffscreen) {
76 await this._creatingOffscreen;
77 return;
78 }
79
80 this._creatingOffscreen = chrome.offscreen.createDocument({
81 url: 'offscreen.html',
82 reasons: [
83 /** @type {chrome.offscreen.Reason} */ ('CLIPBOARD'),
84 ],
85 justification: 'Access to the clipboard',
86 });
87 await this._creatingOffscreen;
88 this._creatingOffscreen = null;
89 }
90
91 /**
92 * @returns {Promise<boolean>}
93 */
94 async _hasOffscreenDocument() {
95 const offscreenUrl = chrome.runtime.getURL('offscreen.html');
96 if (!chrome.runtime.getContexts) { // Chrome version below 116
97 // Clients: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/clients
98 // @ts-expect-error - Types not set up for service workers yet
99 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
100 const matchedClients = await clients.matchAll();
101 // @ts-expect-error - Types not set up for service workers yet
102 return await matchedClients.some((client) => client.url === offscreenUrl);
103 }
104
105 const contexts = await chrome.runtime.getContexts({
106 contextTypes: [
107 /** @type {chrome.runtime.ContextType} */ ('OFFSCREEN_DOCUMENT'),
108 ],
109 documentUrls: [offscreenUrl],
110 });
111 return contexts.length > 0;
112 }
113
114 /**
115 * @template {import('offscreen').ApiNames} TMessageType
116 * @param {import('offscreen').ApiMessage<TMessageType>} message
117 * @returns {Promise<import('offscreen').ApiReturn<TMessageType>>}
118 */
119 async sendMessagePromise(message) {
120 const response = await this._webExtension.sendMessagePromise(message);
121 return this._getMessageResponseResult(/** @type {import('core').Response<import('offscreen').ApiReturn<TMessageType>>} */ (response));
122 }
123
124 /**
125 * @template [TReturn=unknown]
126 * @param {import('core').Response<TReturn>} response
127 * @returns {TReturn}
128 * @throws {Error}
129 */
130 _getMessageResponseResult(response) {
131 const runtimeError = chrome.runtime.lastError;
132 if (typeof runtimeError !== 'undefined') {
133 throw new Error(runtimeError.message);
134 }
135 if (!isObjectNotArray(response)) {
136 throw new Error('Offscreen document did not respond');
137 }
138 const responseError = response.error;
139 if (responseError) {
140 throw ExtensionError.deserialize(responseError);
141 }
142 return response.result;
143 }
144
145 /**
146 * @param {MessagePort} port
147 */
148 async registerOffscreenPort(port) {
149 if (this._currentOffscreenPort) {
150 this._currentOffscreenPort.close();
151 }
152 this._currentOffscreenPort = port;
153 }
154
155 /**
156 * When you need to transfer Transferable objects, you can use this method which uses postMessage over the MessageChannel port established with the offscreen document.
157 * @template {import('offscreen').McApiNames} TMessageType
158 * @param {import('offscreen').McApiMessage<TMessageType>} message
159 * @param {Transferable[]} transfers
160 */
161 sendMessageViaPort(message, transfers) {
162 if (this._currentOffscreenPort !== null) {
163 this._currentOffscreenPort.postMessage(message, transfers);
164 } else {
165 void this.sendMessagePromise({action: 'createAndRegisterPortOffscreen'});
166 }
167 }
168}
169
170export class DictionaryDatabaseProxy {
171 /**
172 * @param {OffscreenProxy} offscreen
173 */
174 constructor(offscreen) {
175 /** @type {OffscreenProxy} */
176 this._offscreen = offscreen;
177 }
178
179 /**
180 * @returns {Promise<void>}
181 */
182 async prepare() {
183 await this._offscreen.sendMessagePromise({action: 'databasePrepareOffscreen'});
184 }
185
186 /**
187 * @returns {Promise<import('dictionary-importer').Summary[]>}
188 */
189 async getDictionaryInfo() {
190 return this._offscreen.sendMessagePromise({action: 'getDictionaryInfoOffscreen'});
191 }
192
193 /**
194 * @returns {Promise<boolean>}
195 */
196 async purge() {
197 return await this._offscreen.sendMessagePromise({action: 'databasePurgeOffscreen'});
198 }
199
200 /**
201 * @param {import('dictionary-database').MediaRequest[]} targets
202 * @returns {Promise<import('dictionary-database').Media[]>}
203 */
204 async getMedia(targets) {
205 const serializedMedia = /** @type {import('dictionary-database').Media<string>[]} */ (await this._offscreen.sendMessagePromise({action: 'databaseGetMediaOffscreen', params: {targets}}));
206 return serializedMedia.map((m) => ({...m, content: base64ToArrayBuffer(m.content)}));
207 }
208
209 /**
210 * @param {MessagePort} port
211 * @returns {Promise<void>}
212 */
213 async connectToDatabaseWorker(port) {
214 this._offscreen.sendMessageViaPort({action: 'connectToDatabaseWorker'}, [port]);
215 }
216}
217
218export class TranslatorProxy {
219 /**
220 * @param {OffscreenProxy} offscreen
221 */
222 constructor(offscreen) {
223 /** @type {OffscreenProxy} */
224 this._offscreen = offscreen;
225 }
226
227 /** */
228 async prepare() {
229 await this._offscreen.sendMessagePromise({action: 'translatorPrepareOffscreen'});
230 }
231
232 /**
233 * @param {string} text
234 * @param {import('translation').FindKanjiOptions} options
235 * @returns {Promise<import('dictionary').KanjiDictionaryEntry[]>}
236 */
237 async findKanji(text, options) {
238 const enabledDictionaryMapList = [...options.enabledDictionaryMap];
239 /** @type {import('offscreen').FindKanjiOptionsOffscreen} */
240 const modifiedOptions = {
241 ...options,
242 enabledDictionaryMap: enabledDictionaryMapList,
243 };
244 return this._offscreen.sendMessagePromise({action: 'findKanjiOffscreen', params: {text, options: modifiedOptions}});
245 }
246
247 /**
248 * @param {import('translator').FindTermsMode} mode
249 * @param {string} text
250 * @param {import('translation').FindTermsOptions} options
251 * @returns {Promise<import('translator').FindTermsResult>}
252 */
253 async findTerms(mode, text, options) {
254 const {enabledDictionaryMap, excludeDictionaryDefinitions, textReplacements} = options;
255 const enabledDictionaryMapList = [...enabledDictionaryMap];
256 const excludeDictionaryDefinitionsList = excludeDictionaryDefinitions ? [...excludeDictionaryDefinitions] : null;
257 const textReplacementsSerialized = textReplacements.map((group) => {
258 return group !== null ? group.map((opt) => ({...opt, pattern: opt.pattern.toString()})) : null;
259 });
260 /** @type {import('offscreen').FindTermsOptionsOffscreen} */
261 const modifiedOptions = {
262 ...options,
263 enabledDictionaryMap: enabledDictionaryMapList,
264 excludeDictionaryDefinitions: excludeDictionaryDefinitionsList,
265 textReplacements: textReplacementsSerialized,
266 };
267 return this._offscreen.sendMessagePromise({action: 'findTermsOffscreen', params: {mode, text, options: modifiedOptions}});
268 }
269
270 /**
271 * @param {import('translator').TermReadingList} termReadingList
272 * @param {string[]} dictionaries
273 * @returns {Promise<import('translator').TermFrequencySimple[]>}
274 */
275 async getTermFrequencies(termReadingList, dictionaries) {
276 return this._offscreen.sendMessagePromise({action: 'getTermFrequenciesOffscreen', params: {termReadingList, dictionaries}});
277 }
278
279 /** */
280 async clearDatabaseCaches() {
281 await this._offscreen.sendMessagePromise({action: 'clearDatabaseCachesOffscreen'});
282 }
283}
284
285export class ClipboardReaderProxy {
286 /**
287 * @param {OffscreenProxy} offscreen
288 */
289 constructor(offscreen) {
290 /** @type {?import('environment').Browser} */
291 this._browser = null;
292 /** @type {OffscreenProxy} */
293 this._offscreen = offscreen;
294 }
295
296 /** @type {?import('environment').Browser} */
297 get browser() { return this._browser; }
298 set browser(value) {
299 if (this._browser === value) { return; }
300 this._browser = value;
301 void this._offscreen.sendMessagePromise({action: 'clipboardSetBrowserOffscreen', params: {value}});
302 }
303
304 /**
305 * @param {boolean} useRichText
306 * @returns {Promise<string>}
307 */
308 async getText(useRichText) {
309 return await this._offscreen.sendMessagePromise({action: 'clipboardGetTextOffscreen', params: {useRichText}});
310 }
311
312 /**
313 * @returns {Promise<?string>}
314 */
315 async getImage() {
316 return await this._offscreen.sendMessagePromise({action: 'clipboardGetImageOffscreen'});
317 }
318}