aboutsummaryrefslogtreecommitdiff
path: root/ext/mixed/js/text-scanner.js
blob: bff9544f231358969c4af0ea3ff0a63d9ede6dcb (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
/*
 * Copyright (C) 2019-2020  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/>.
 */

/* global
 * DOM
 * TextSourceRange
 * docRangeFromPoint
 */

class TextScanner {
    constructor(node, ignoreElements, ignorePoints) {
        this.node = node;
        this.ignoreElements = ignoreElements;
        this.ignorePoints = ignorePoints;

        this.ignoreNodes = null;

        this.scanTimerPromise = null;
        this.causeCurrent = null;
        this.textSourceCurrent = null;
        this.pendingLookup = false;
        this.options = null;

        this.enabled = false;
        this.eventListeners = new EventListenerCollection();

        this.primaryTouchIdentifier = null;
        this.preventNextContextMenu = false;
        this.preventNextMouseDown = false;
        this.preventNextClick = false;
        this.preventScroll = false;
    }

    onMouseOver(e) {
        if (this.ignoreElements().includes(e.target)) {
            this.scanTimerClear();
        }
    }

    onMouseMove(e) {
        this.scanTimerClear();

        if (this.pendingLookup || DOM.isMouseButtonDown(e, 'primary')) {
            return;
        }

        const scanningOptions = this.options.scanning;
        const scanningModifier = scanningOptions.modifier;
        if (!(
            TextScanner.isScanningModifierPressed(scanningModifier, e) ||
            (scanningOptions.middleMouse && DOM.isMouseButtonDown(e, 'auxiliary'))
        )) {
            return;
        }

        const search = async () => {
            if (scanningModifier === 'none') {
                if (!await this.scanTimerWait()) {
                    // Aborted
                    return;
                }
            }

            await this.searchAt(e.clientX, e.clientY, 'mouse');
        };

        search();
    }

    onMouseDown(e) {
        if (this.preventNextMouseDown) {
            this.preventNextMouseDown = false;
            this.preventNextClick = true;
            e.preventDefault();
            e.stopPropagation();
            return false;
        }

        if (DOM.isMouseButtonDown(e, 'primary')) {
            this.scanTimerClear();
            this.onSearchClear(true);
        }
    }

    onMouseOut() {
        this.scanTimerClear();
    }

    onClick(e) {
        if (this.preventNextClick) {
            this.preventNextClick = false;
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    }

    onAuxClick() {
        this.preventNextContextMenu = false;
    }

    onContextMenu(e) {
        if (this.preventNextContextMenu) {
            this.preventNextContextMenu = false;
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    }

    onTouchStart(e) {
        if (this.primaryTouchIdentifier !== null || e.changedTouches.length === 0) {
            return;
        }

        this.preventScroll = false;
        this.preventNextContextMenu = false;
        this.preventNextMouseDown = false;
        this.preventNextClick = false;

        const primaryTouch = e.changedTouches[0];
        if (DOM.isPointInSelection(primaryTouch.clientX, primaryTouch.clientY, this.node.getSelection())) {
            return;
        }

        this.primaryTouchIdentifier = primaryTouch.identifier;

        if (this.pendingLookup) {
            return;
        }

        const textSourceCurrentPrevious = this.textSourceCurrent !== null ? this.textSourceCurrent.clone() : null;

        this.searchAt(primaryTouch.clientX, primaryTouch.clientY, 'touchStart')
            .then(() => {
                if (
                    this.textSourceCurrent === null ||
                    this.textSourceCurrent.equals(textSourceCurrentPrevious)
                ) {
                    return;
                }

                this.preventScroll = true;
                this.preventNextContextMenu = true;
                this.preventNextMouseDown = true;
            });
    }

    onTouchEnd(e) {
        if (
            this.primaryTouchIdentifier === null ||
            TextScanner.getTouch(e.changedTouches, this.primaryTouchIdentifier) === null
        ) {
            return;
        }

        this.primaryTouchIdentifier = null;
        this.preventScroll = false;
        this.preventNextClick = false;
        // Don't revert context menu and mouse down prevention,
        // since these events can occur after the touch has ended.
        // this.preventNextContextMenu = false;
        // this.preventNextMouseDown = false;
    }

    onTouchCancel(e) {
        this.onTouchEnd(e);
    }

    onTouchMove(e) {
        if (!this.preventScroll || !e.cancelable || this.primaryTouchIdentifier === null) {
            return;
        }

        const primaryTouch = TextScanner.getTouch(e.changedTouches, this.primaryTouchIdentifier);
        if (primaryTouch === null) {
            return;
        }

        this.searchAt(primaryTouch.clientX, primaryTouch.clientY, 'touchMove');

        e.preventDefault(); // Disable scroll
    }

    async onSearchSource(_textSource, _cause) {
        throw new Error('Override me');
    }

    onError(error) {
        logError(error, false);
    }

    async scanTimerWait() {
        const delay = this.options.scanning.delay;
        const promise = promiseTimeout(delay, true);
        this.scanTimerPromise = promise;
        try {
            return await promise;
        } finally {
            if (this.scanTimerPromise === promise) {
                this.scanTimerPromise = null;
            }
        }
    }

    scanTimerClear() {
        if (this.scanTimerPromise !== null) {
            this.scanTimerPromise.resolve(false);
            this.scanTimerPromise = null;
        }
    }

    setEnabled(enabled, canEnable) {
        if (enabled && canEnable) {
            if (!this.enabled) {
                this.hookEvents();
                this.enabled = true;
            }
        } else {
            if (this.enabled) {
                this.eventListeners.removeAllEventListeners();
                this.enabled = false;
            }
            this.onSearchClear(false);
        }
    }

    hookEvents() {
        let eventListenerInfos = this.getMouseEventListeners();
        if (this.options.scanning.touchInputEnabled) {
            eventListenerInfos = eventListenerInfos.concat(this.getTouchEventListeners());
        }

        for (const [node, type, listener, options] of eventListenerInfos) {
            this.eventListeners.addEventListener(node, type, listener, options);
        }
    }

    getMouseEventListeners() {
        return [
            [this.node, 'mousedown', this.onMouseDown.bind(this)],
            [this.node, 'mousemove', this.onMouseMove.bind(this)],
            [this.node, 'mouseover', this.onMouseOver.bind(this)],
            [this.node, 'mouseout', this.onMouseOut.bind(this)]
        ];
    }

    getTouchEventListeners() {
        return [
            [this.node, 'click', this.onClick.bind(this)],
            [this.node, 'auxclick', this.onAuxClick.bind(this)],
            [this.node, 'touchstart', this.onTouchStart.bind(this)],
            [this.node, 'touchend', this.onTouchEnd.bind(this)],
            [this.node, 'touchcancel', this.onTouchCancel.bind(this)],
            [this.node, 'touchmove', this.onTouchMove.bind(this), {passive: false}],
            [this.node, 'contextmenu', this.onContextMenu.bind(this)]
        ];
    }

    setOptions(options, canEnable=true) {
        this.options = options;
        this.setEnabled(this.options.general.enable, canEnable);
    }

    async searchAt(x, y, cause) {
        try {
            this.scanTimerClear();

            if (this.pendingLookup) {
                return;
            }

            for (const ignorePointFn of this.ignorePoints) {
                if (await ignorePointFn(x, y)) {
                    return;
                }
            }

            const textSource = docRangeFromPoint(x, y, this.options.scanning.deepDomScan);
            try {
                if (this.textSourceCurrent !== null && this.textSourceCurrent.equals(textSource)) {
                    return;
                }

                this.pendingLookup = true;
                const result = await this.onSearchSource(textSource, cause);
                if (result !== null) {
                    this.causeCurrent = cause;
                    this.textSourceCurrent = textSource;
                    if (this.options.scanning.selectText) {
                        textSource.select();
                    }
                }
                this.pendingLookup = false;
            } finally {
                if (textSource !== null) {
                    textSource.cleanup();
                }
            }
        } catch (e) {
            this.onError(e);
        }
    }

    setTextSourceScanLength(textSource, length) {
        textSource.setEndOffset(length);
        if (this.ignoreNodes === null || !textSource.range) {
            return;
        }

        length = textSource.text().length;
        while (textSource.range && length > 0) {
            const nodes = TextSourceRange.getNodesInRange(textSource.range);
            if (!TextSourceRange.anyNodeMatchesSelector(nodes, this.ignoreNodes)) {
                break;
            }
            --length;
            textSource.setEndOffset(length);
        }
    }

    onSearchClear(_) {
        if (this.textSourceCurrent !== null) {
            if (this.options.scanning.selectText) {
                this.textSourceCurrent.deselect();
            }
            this.textSourceCurrent = null;
        }
    }

    getCurrentTextSource() {
        return this.textSourceCurrent;
    }

    setCurrentTextSource(textSource) {
        return this.textSourceCurrent = textSource;
    }

    static isScanningModifierPressed(scanningModifier, mouseEvent) {
        switch (scanningModifier) {
            case 'alt': return mouseEvent.altKey;
            case 'ctrl': return mouseEvent.ctrlKey;
            case 'shift': return mouseEvent.shiftKey;
            case 'none': return true;
            default: return false;
        }
    }

    static getTouch(touchList, identifier) {
        for (const touch of touchList) {
            if (touch.identifier === identifier) {
                return touch;
            }
        }
        return null;
    }
}