summaryrefslogtreecommitdiff
path: root/ext/js/language/dictionary-worker.js
blob: 3119dd7b22c7d3a38a5aceea8e3280c5021762f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/*
 * Copyright (C) 2023  Yomitan Authors
 * Copyright (C) 2021-2022  Yomichan 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 {ExtensionError} from '../core/extension-error.js';
import {DictionaryImporterMediaLoader} from './dictionary-importer-media-loader.js';

export class DictionaryWorker {
    constructor() {
        /** @type {DictionaryImporterMediaLoader} */
        this._dictionaryImporterMediaLoader = new DictionaryImporterMediaLoader();
    }

    /**
     * @param {ArrayBuffer} archiveContent
     * @param {import('dictionary-importer').ImportDetails} details
     * @param {?import('dictionary-worker').ImportProgressCallback} onProgress
     * @returns {Promise<import('dictionary-importer').ImportResult>}
     */
    importDictionary(archiveContent, details, onProgress) {
        return this._invoke(
            'importDictionary',
            {details, archiveContent},
            [archiveContent],
            onProgress,
            this._formatImportDictionaryResult.bind(this)
        );
    }

    /**
     * @param {string} dictionaryTitle
     * @param {?import('dictionary-worker').DeleteProgressCallback} onProgress
     * @returns {Promise<void>}
     */
    deleteDictionary(dictionaryTitle, onProgress) {
        return this._invoke('deleteDictionary', {dictionaryTitle}, [], onProgress, null);
    }

    /**
     * @param {string[]} dictionaryNames
     * @param {boolean} getTotal
     * @returns {Promise<import('dictionary-database').DictionaryCounts>}
     */
    getDictionaryCounts(dictionaryNames, getTotal) {
        return this._invoke('getDictionaryCounts', {dictionaryNames, getTotal}, [], null, null);
    }

    // Private

    /**
     * @template [TParams=import('core').SerializableObject]
     * @template [TResponseRaw=unknown]
     * @template [TResponse=unknown]
     * @param {string} action
     * @param {TParams} params
     * @param {Transferable[]} transfer
     * @param {?(arg: import('core').SafeAny) => void} onProgress
     * @param {?(result: TResponseRaw) => TResponse} formatResult
     */
    _invoke(action, params, transfer, onProgress, formatResult) {
        return new Promise((resolve, reject) => {
            const worker = new Worker('/js/language/dictionary-worker-main.js', {type: 'module'});
            /** @type {import('dictionary-worker').InvokeDetails<TResponseRaw, TResponse>} */
            const details = {
                complete: false,
                worker,
                resolve,
                reject,
                onMessage: null,
                onProgress,
                formatResult
            };
            // Ugly typecast below due to not being able to explicitly state the template types
            /** @type {(event: MessageEvent<import('dictionary-worker').MessageData<TResponseRaw>>) => void} */
            const onMessage = /** @type {(details: import('dictionary-worker').InvokeDetails<TResponseRaw, TResponse>, event: MessageEvent<import('dictionary-worker').MessageData<TResponseRaw>>) => void} */ (this._onMessage).bind(this, details);
            details.onMessage = onMessage;
            worker.addEventListener('message', onMessage);
            worker.postMessage({action, params}, transfer);
        });
    }

    /**
     * @template [TResponseRaw=unknown]
     * @template [TResponse=unknown]
     * @param {import('dictionary-worker').InvokeDetails<TResponseRaw, TResponse>} details
     * @param {MessageEvent<import('dictionary-worker').MessageData<TResponseRaw>>} event
     */
    _onMessage(details, event) {
        if (details.complete) { return; }
        const {action, params} = event.data;
        switch (action) {
            case 'complete':
                {
                    const {worker, resolve, reject, onMessage, formatResult} = details;
                    if (worker === null || onMessage === null || resolve === null || reject === null) { return; }
                    details.complete = true;
                    details.worker = null;
                    details.resolve = null;
                    details.reject = null;
                    details.onMessage = null;
                    details.onProgress = null;
                    details.formatResult = null;
                    worker.removeEventListener('message', onMessage);
                    worker.terminate();
                    this._onMessageComplete(params, resolve, reject, formatResult);
                }
                break;
            case 'progress':
                this._onMessageProgress(params, details.onProgress);
                break;
            case 'getImageDetails':
                {
                    const {worker} = details;
                    if (worker === null) { return; }
                    this._onMessageGetImageDetails(params, worker);
                }
                break;
        }
    }

    /**
     * @template [TResponseRaw=unknown]
     * @template [TResponse=unknown]
     * @param {import('dictionary-worker').MessageCompleteParams<TResponseRaw>} params
     * @param {(result: TResponse) => void} resolve
     * @param {(reason?: import('core').RejectionReason) => void} reject
     * @param {?(result: TResponseRaw) => TResponse} formatResult
     */
    _onMessageComplete(params, resolve, reject, formatResult) {
        const {error} = params;
        if (typeof error !== 'undefined') {
            reject(ExtensionError.deserialize(error));
        } else {
            const {result} = params;
            if (typeof formatResult === 'function') {
                let result2;
                try {
                    result2 = formatResult(result);
                } catch (e) {
                    reject(e);
                    return;
                }
                resolve(result2);
            } else {
                // If formatResult is not provided, the response is assumed to be the same type
                // For some reason, eslint thinks the TResponse type is undefined
                // eslint-disable-next-line jsdoc/no-undefined-types
                resolve(/** @type {TResponse} */ (/** @type {unknown} */ (result)));
            }
        }
    }

    /**
     * @param {import('dictionary-worker').MessageProgressParams} params
     * @param {?(...args: unknown[]) => void} onProgress
     */
    _onMessageProgress(params, onProgress) {
        if (typeof onProgress !== 'function') { return; }
        const {args} = params;
        onProgress(...args);
    }

    /**
     * @param {import('dictionary-worker').MessageGetImageDetailsParams} params
     * @param {Worker} worker
     */
    async _onMessageGetImageDetails(params, worker) {
        const {id, content, mediaType} = params;
        /** @type {Transferable[]} */
        const transfer = [];
        let response;
        try {
            const result = await this._dictionaryImporterMediaLoader.getImageDetails(content, mediaType, transfer);
            response = {id, result};
        } catch (e) {
            response = {id, error: ExtensionError.serialize(e)};
        }
        worker.postMessage({action: 'getImageDetails.response', params: response}, transfer);
    }

    /**
     * @param {import('dictionary-worker').MessageCompleteResultSerialized} response
     * @returns {import('dictionary-worker').MessageCompleteResult}
     */
    _formatImportDictionaryResult(response) {
        const {result, errors} = response;
        return {
            result,
            errors: errors.map((error) => ExtensionError.deserialize(error))
        };
    }
}