aboutsummaryrefslogtreecommitdiff
path: root/ext/bg/js/settings-dictionaries.js
blob: 72a27475e44209d6e520738bb77ee2d6a0a1ab80 (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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
 * Copyright (C) 2019  Alex Yatskov <alex@foosoft.net>
 * Author: Alex Yatskov <alex@foosoft.net>
 *
 * 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 <http://www.gnu.org/licenses/>.
 */


let dictionaryUI = null;


class SettingsDictionaryListUI {
    constructor(container, template, extraContainer, extraTemplate, optionsDictionaries) {
        this.container = container;
        this.template = template;
        this.extraContainer = extraContainer;
        this.extraTemplate = extraTemplate;
        this.optionsDictionaries = optionsDictionaries;

        this.dictionaryEntries = [];
        this.extra = null;
    }

    setDictionaries(dictionaries) {
        for (const dictionaryEntry of this.dictionaryEntries) {
            dictionaryEntry.cleanup();
        }

        this.dictionaryEntries = [];

        let changed = false;
        for (const dictionaryInfo of toIterable(dictionaries)) {
            if (this.createEntry(dictionaryInfo)) {
                changed = true;
            }
        }

        const titles = this.dictionaryEntries.map(e => e.dictionaryInfo.title);
        const removeKeys = Object.keys(this.optionsDictionaries).filter(key => titles.indexOf(key) < 0);
        if (removeKeys.length >= 0) {
            for (const key of removeKeys) {
                delete this.optionsDictionaries[key];
            }
            changed = true;
        }

        if (changed) {
            this.save();
        }
    }

    createEntry(dictionaryInfo) {
        const title = dictionaryInfo.title;
        let changed = false;
        let optionsDictionary;
        const optionsDictionaries = this.optionsDictionaries;
        if (optionsDictionaries.hasOwnProperty(title)) {
            optionsDictionary = optionsDictionaries[title];
        } else {
            optionsDictionary = SettingsDictionaryListUI.createDictionaryOptions();
            optionsDictionaries[title] = optionsDictionary;
            changed = true;
        }

        const content = document.importNode(this.template.content, true).firstChild;
        this.container.appendChild(content);

        this.dictionaryEntries.push(new SettingsDictionaryEntryUI(this, dictionaryInfo, content, optionsDictionary));

        return changed;
    }

    static createDictionaryOptions() {
        return utilBackgroundIsolate({
            priority: 0,
            enabled: false,
            allowSecondarySearches: false
        });
    }

    createExtra(totalCounts, remainders, totalRemainder) {
        const content = document.importNode(this.extraTemplate.content, true).firstChild;
        this.extraContainer.appendChild(content);
        return new SettingsDictionaryExtraUI(this, totalCounts, remainders, totalRemainder, content);
    }

    setCounts(dictionaryCounts, totalCounts) {
        const remainders = Object.assign({}, totalCounts);
        const keys = Object.keys(remainders);

        for (let i = 0, ii = Math.min(this.dictionaryEntries.length, dictionaryCounts.length); i < ii; ++i) {
            const counts = dictionaryCounts[i];
            this.dictionaryEntries[i].setCounts(counts);

            for (const key of keys) {
                remainders[key] -= counts[key];
            }
        }

        let totalRemainder = 0;
        for (const key of keys) {
            totalRemainder += remainders[key];
        }

        if (this.extra !== null) {
            this.extra.cleanup();
            this.extra = null;
        }

        if (totalRemainder > 0) {
            this.extra = this.createExtra(totalCounts, remainders, totalRemainder);
        }
    }

    save() {
        // Overwrite
    }
}

class SettingsDictionaryEntryUI {
    constructor(parent, dictionaryInfo, content, optionsDictionary) {
        this.parent = parent;
        this.dictionaryInfo = dictionaryInfo;
        this.optionsDictionary = optionsDictionary;
        this.counts = null;
        this.eventListeners = [];

        this.content = content;
        this.enabledCheckbox = this.content.querySelector('.dict-enabled');
        this.allowSecondarySearchesCheckbox = this.content.querySelector('.dict-allow-secondary-searches');
        this.priorityInput = this.content.querySelector('.dict-priority');

        this.content.querySelector('.dict-title').textContent = this.dictionaryInfo.title;
        this.content.querySelector('.dict-revision').textContent = `rev.${this.dictionaryInfo.revision}`;

        this.applyValues();

        this.addEventListener(this.enabledCheckbox, 'change', (e) => this.onEnabledChanged(e), false);
        this.addEventListener(this.allowSecondarySearchesCheckbox, 'change', (e) => this.onAllowSecondarySearchesChanged(e), false);
        this.addEventListener(this.priorityInput, 'change', (e) => this.onPriorityChanged(e), false);
    }

    cleanup() {
        if (this.content !== null) {
            if (this.content.parentNode !== null) {
                this.content.parentNode.removeChild(this.content);
            }
            this.content = null;
        }
        this.dictionaryInfo = null;
        this.clearEventListeners();
    }

    setCounts(counts) {
        this.counts = counts;
        const node = this.content.querySelector('.dict-counts');
        node.textContent = JSON.stringify({
            info: this.dictionaryInfo,
            counts
        }, null, 4);
        node.removeAttribute('hidden');
    }

    save() {
        this.parent.save();
    }

    addEventListener(node, type, listener, options) {
        node.addEventListener(type, listener, options);
        this.eventListeners.push([node, type, listener, options]);
    }

    clearEventListeners() {
        for (const [node, type, listener, options] of this.eventListeners) {
            node.removeEventListener(type, listener, options);
        }
        this.eventListeners = [];
    }

    applyValues() {
        this.enabledCheckbox.checked = this.optionsDictionary.enabled;
        this.allowSecondarySearchesCheckbox.checked = this.optionsDictionary.allowSecondarySearches;
        this.priorityInput.value = `${this.optionsDictionary.priority}`;
    }

    onEnabledChanged(e) {
        this.optionsDictionary.enabled = !!e.target.checked;
        this.save();
    }

    onAllowSecondarySearchesChanged(e) {
        this.optionsDictionary.allowSecondarySearches = !!e.target.checked;
        this.save();
    }

    onPriorityChanged(e) {
        let value = Number.parseFloat(e.target.value);
        if (Number.isNaN(value)) {
            value = this.optionsDictionary.priority;
        } else {
            this.optionsDictionary.priority = value;
            this.save();
        }

        e.target.value = `${value}`;
    }
}

class SettingsDictionaryExtraUI {
    constructor(parent, totalCounts, remainders, totalRemainder, content) {
        this.parent = parent;
        this.content = content;

        this.content.querySelector('.dict-total-count').textContent = `${totalRemainder} item${totalRemainder !== 1 ? 's' : ''}`;

        const node = this.content.querySelector('.dict-counts');
        node.textContent = JSON.stringify({
            counts: totalCounts,
            remainders: remainders
        }, null, 4);
        node.removeAttribute('hidden');
    }

    cleanup() {
        if (this.content !== null) {
            if (this.content.parentNode !== null) {
                this.content.parentNode.removeChild(this.content);
            }
            this.content = null;
        }
    }
}


async function dictSettingsInitialize() {
    const optionsContext = getOptionsContext();
    const options = await apiOptionsGet(optionsContext);

    dictionaryUI = new SettingsDictionaryListUI(
        document.querySelector('#dict-groups'),
        document.querySelector('#dict-template'),
        document.querySelector('#dict-groups-extra'),
        document.querySelector('#dict-extra-template'),
        options.dictionaries
    );
    dictionaryUI.save = () => apiOptionsSave();

    document.querySelector('#dict-purge-button').addEventListener('click', (e) => onDictionaryPurgeButtonClick(e), false);
    document.querySelector('#dict-purge-confirm').addEventListener('click', (e) => onDictionaryPurge(e), false);
    document.querySelector('#dict-file-button').addEventListener('click', (e) => onDictionaryImportButtonClick(e), false);
    document.querySelector('#dict-file').addEventListener('change', (e) => onDictionaryImport(e), false);
    document.querySelector('#dict-main').addEventListener('change', (e) => onDictionaryMainChanged(e), false);

    onDatabaseUpdated(options);
}

async function onDatabaseUpdated(options) {
    try {
        const dictionaries = await utilDatabaseGetDictionaryInfo();
        dictionaryUI.setDictionaries(dictionaries);

        updateMainDictionarySelect(options, dictionaries);

        const {counts, total} = await utilDatabaseGetDictionaryCounts(dictionaries.map(v => v.title), true);
        dictionaryUI.setCounts(counts, total);
    } catch (e) {
        dictionaryErrorsShow([e]);
    }
}

async function updateMainDictionarySelect(options, dictionaries) {
    const select = document.querySelector('#dict-main');
    select.textContent = ''; // Empty

    let option = document.createElement('option');
    option.className = 'text-muted';
    option.value = '';
    option.textContent = 'Not selected';
    select.appendChild(option);

    let value = '';
    const currentValue = options.general.mainDictionary;
    for (const {title, sequenced} of toIterable(dictionaries)) {
        if (!sequenced) { continue; }

        option = document.createElement('option');
        option.value = title;
        option.textContent = title;
        select.appendChild(option);

        if (title === currentValue) {
            value = title;
        }
    }

    select.value = value;

    if (options.general.mainDictionary !== value) {
        options.general.mainDictionary = value;
        apiOptionsSave();
    }
}

async function onDictionaryMainChanged(e) {
    const value = e.target.value;
    const optionsContext = getOptionsContext();
    const options = await apiOptionsGet(optionsContext);
    options.general.mainDictionary = value;
    apiOptionsSave();
}


function dictionaryErrorToString(error) {
    if (error.toString) {
        error = error.toString();
    } else {
        error = `${error}`;
    }

    for (const [match, subst] of dictionaryErrorToString.overrides) {
        if (error.includes(match)) {
            error = subst;
            break;
        }
    }

    return error;
}
dictionaryErrorToString.overrides = [
    [
        'A mutation operation was attempted on a database that did not allow mutations.',
        'Access to IndexedDB appears to be restricted. Firefox seems to require that the history preference is set to "Remember history" before IndexedDB use of any kind is allowed.'
    ],
    [
        'The operation failed for reasons unrelated to the database itself and not covered by any other error code.',
        'Unable to access IndexedDB due to a possibly corrupt user profile. Try using the "Refresh Firefox" feature to reset your user profile.'
    ],
    [
        'BulkError',
        'Unable to finish importing dictionary data into IndexedDB. This may indicate that you do not have sufficient disk space available to complete this operation.'
    ]
];

function dictionaryErrorsShow(errors) {
    const dialog = $('#dict-error');
    dialog.show().text('');

    if (errors !== null && errors.length > 0) {
        const uniqueErrors = {};
        for (let e of errors) {
            console.error(e);
            e = dictionaryErrorToString(e);
            uniqueErrors[e] = uniqueErrors.hasOwnProperty(e) ? uniqueErrors[e] + 1 : 1;
        }

        for (const e in uniqueErrors) {
            const count = uniqueErrors[e];
            const div = document.createElement('p');
            if (count > 1) {
                div.textContent = `${e} `;
                const em = document.createElement('em');
                em.textContent = `(${count})`;
                div.appendChild(em);
            } else {
                div.textContent = `${e}`;
            }
            dialog.append($(div));
        }

        dialog.show();
    } else {
        dialog.hide();
    }
}


function dictionarySpinnerShow(show) {
    const spinner = $('#dict-spinner');
    if (show) {
        spinner.show();
    } else {
        spinner.hide();
    }
}

function onDictionaryImportButtonClick() {
    const dictFile = document.querySelector('#dict-file');
    dictFile.click();
}

function onDictionaryPurgeButtonClick(e) {
    e.preventDefault();
    $('#dict-purge-modal').modal('show');
}

async function onDictionaryPurge(e) {
    e.preventDefault();

    $('#dict-purge-modal').modal('hide');

    const dictControls = $('#dict-importer, #dict-groups, #dict-groups-extra, #dict-main-group').hide();
    const dictProgress = $('#dict-purge').show();

    try {
        dictionaryErrorsShow(null);
        dictionarySpinnerShow(true);

        await utilDatabasePurge();
        for (const options of toIterable(await getOptionsArray())) {
            options.dictionaries = utilBackgroundIsolate({});
            options.general.mainDictionary = '';
        }
        await settingsSaveOptions();

        const optionsContext = getOptionsContext();
        const options = await apiOptionsGet(optionsContext);
        onDatabaseUpdated(options);
    } catch (err) {
        dictionaryErrorsShow([err]);
    } finally {
        dictionarySpinnerShow(false);

        dictControls.show();
        dictProgress.hide();

        if (storageEstimate.mostRecent !== null) {
            storageUpdateStats();
        }
    }
}

async function onDictionaryImport(e) {
    const dictFile = $('#dict-file');
    const dictControls = $('#dict-importer').hide();
    const dictProgress = $('#dict-import-progress').show();

    try {
        dictionaryErrorsShow(null);
        dictionarySpinnerShow(true);

        const setProgress = percent => dictProgress.find('.progress-bar').css('width', `${percent}%`);
        const updateProgress = (total, current) => {
            setProgress(current / total * 100.0);
            if (storageEstimate.mostRecent !== null && !storageUpdateStats.isUpdating) {
                storageUpdateStats();
            }
        };
        setProgress(0.0);

        const exceptions = [];
        const summary = await utilDatabaseImport(e.target.files[0], updateProgress, exceptions);
        for (const options of toIterable(await getOptionsArray())) {
            const dictionaryOptions = SettingsDictionaryListUI.createDictionaryOptions();
            dictionaryOptions.enabled = true;
            options.dictionaries[summary.title] = dictionaryOptions;
            if (summary.sequenced && options.general.mainDictionary === '') {
                options.general.mainDictionary = summary.title;
            }
        }
        await settingsSaveOptions();

        if (exceptions.length > 0) {
            exceptions.push(`Dictionary may not have been imported properly: ${exceptions.length} error${exceptions.length === 1 ? '' : 's'} reported.`);
            dictionaryErrorsShow(exceptions);
        }

        const optionsContext = getOptionsContext();
        const options = await apiOptionsGet(optionsContext);
        onDatabaseUpdated(options);
    } catch (err) {
        dictionaryErrorsShow([err]);
    } finally {
        dictionarySpinnerShow(false);

        dictFile.val('');
        dictControls.show();
        dictProgress.hide();
    }
}