summaryrefslogtreecommitdiff
path: root/ext/fg/js/float.js
blob: 2debdeffd51e9c14361f982cc51edbff6bcee279 (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
/*
 * Copyright (C) 2016-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
 * Display
 * FrameEndpoint
 * Frontend
 * PopupFactory
 * api
 * dynamicLoader
 */

class DisplayFloat extends Display {
    constructor() {
        super(document.querySelector('#spinner'), document.querySelector('#definitions'));
        this._autoPlayAudioTimer = null;
        this._nestedPopupsPrepared = false;
        this._ownerFrameId = null;
        this._frameEndpoint = new FrameEndpoint();
        this._windowMessageHandlers = new Map([
            ['configure',          {handler: this._onMessageConfigure.bind(this)}],
            ['setOptionsContext',  {handler: this._onMessageSetOptionsContext.bind(this)}],
            ['setContent',         {handler: this._onMessageSetContent.bind(this)}],
            ['clearAutoPlayTimer', {handler: this._onMessageClearAutoPlayTimer.bind(this)}],
            ['setCustomCss',       {handler: this._onMessageSetCustomCss.bind(this)}],
            ['setContentScale',    {handler: this._onMessageSetContentScale.bind(this)}]
        ]);

        this.registerActions([
            ['copy-host-selection', () => this._copySelection()]
        ]);
        this.registerHotkeys([
            {key: 'C', modifiers: ['ctrl'], action: 'copy-host-selection'}
        ]);
    }

    async prepare() {
        await super.prepare();

        window.addEventListener('message', this._onMessage.bind(this), false);

        this._frameEndpoint.signal();
    }

    onEscape() {
        this._invoke('closePopup');
    }

    async setOptionsContext(optionsContext) {
        super.setOptionsContext(optionsContext);
        await this.updateOptions();
    }

    async getDocumentTitle() {
        try {
            const uniqueId = yomichan.generateId(16);

            const promise = yomichan.getTemporaryListenerResult(
                chrome.runtime.onMessage,
                ({action, params}, {resolve}) => {
                    if (
                        action === 'documentInformationBroadcast' &&
                        isObject(params) &&
                        params.uniqueId === uniqueId &&
                        params.frameId === 0
                    ) {
                        resolve(params);
                    }
                },
                2000
            );
            api.broadcastTab('requestDocumentInformationBroadcast', {uniqueId});

            const {title} = await promise;
            return title;
        } catch (e) {
            return '';
        }
    }

    autoPlayAudio() {
        this._clearAutoPlayTimer();
        this._autoPlayAudioTimer = window.setTimeout(() => super.autoPlayAudio(), 400);
    }

    // Message handling

    _onMessage(e) {
        let data = e.data;
        if (!this._frameEndpoint.authenticate(data)) { return; }
        data = data.data;

        if (typeof data !== 'object' || data === null) {
            this._logMessageError(e, 'Invalid data');
            return;
        }

        const action = data.action;
        if (typeof action !== 'string') {
            this._logMessageError(e, 'Invalid data');
            return;
        }

        const handlerInfo = this._windowMessageHandlers.get(action);
        if (typeof handlerInfo === 'undefined') {
            this._logMessageError(e, `Invalid action: ${JSON.stringify(action)}`);
            return;
        }

        const handler = handlerInfo.handler;
        handler(data.params);
    }

    async _onMessageConfigure({messageId, frameId, ownerFrameId, popupId, optionsContext, childrenSupported, scale}) {
        this._ownerFrameId = ownerFrameId;
        this.setOptionsContext(optionsContext);

        await this.updateOptions();

        if (childrenSupported && !this._nestedPopupsPrepared) {
            const {depth, url} = optionsContext;
            this._prepareNestedPopups(popupId, depth, frameId, url);
            this._nestedPopupsPrepared = true;
        }

        this._setContentScale(scale);

        api.sendMessageToFrame(frameId, 'popupConfigured', {messageId});
    }

    _onMessageSetOptionsContext({optionsContext}) {
        this.setOptionsContext(optionsContext);
    }

    _onMessageSetContent({type, details}) {
        this.setContent(type, details);
    }

    _onMessageClearAutoPlayTimer() {
        this._clearAutoPlayTimer.bind(this);
    }

    _onMessageSetCustomCss({css}) {
        this.setCustomCss(css);
    }

    _onMessageSetContentScale({scale}) {
        this._setContentScale(scale);
    }

    // Private

    _copySelection() {
        if (window.getSelection().toString()) { return false; }
        this._invoke('copySelection');
        return true;
    }

    _clearAutoPlayTimer() {
        if (this._autoPlayAudioTimer) {
            window.clearTimeout(this._autoPlayAudioTimer);
            this._autoPlayAudioTimer = null;
        }
    }

    _setContentScale(scale) {
        const body = document.body;
        if (body === null) { return; }
        body.style.fontSize = `${scale}em`;
    }

    _logMessageError(event, type) {
        yomichan.logWarning(new Error(`Popup received invalid message from origin ${JSON.stringify(event.origin)}: ${type}`));
    }

    async _prepareNestedPopups(id, depth, parentFrameId, url) {
        let complete = false;

        const onOptionsUpdated = async () => {
            const optionsContext = this.getOptionsContext();
            const options = await api.optionsGet(optionsContext);
            const maxPopupDepthExceeded = !(typeof depth === 'number' && depth < options.scanning.popupNestingMaxDepth);
            if (maxPopupDepthExceeded || complete) { return; }

            complete = true;
            yomichan.off('optionsUpdated', onOptionsUpdated);

            try {
                await this._setupNestedPopups(id, depth, parentFrameId, url);
            } catch (e) {
                yomichan.logError(e);
            }
        };

        yomichan.on('optionsUpdated', onOptionsUpdated);

        await onOptionsUpdated();
    }

    async _setupNestedPopups(id, depth, parentFrameId, url) {
        await dynamicLoader.loadScripts([
            '/mixed/js/text-scanner.js',
            '/mixed/js/frame-client.js',
            '/fg/js/popup.js',
            '/fg/js/popup-proxy.js',
            '/fg/js/popup-factory.js',
            '/fg/js/frame-offset-forwarder.js',
            '/fg/js/frontend.js'
        ]);

        const {frameId} = await api.frameInformationGet();

        const popupFactory = new PopupFactory(frameId);
        popupFactory.prepare();

        const frontend = new Frontend(
            frameId,
            popupFactory,
            {
                id,
                depth,
                parentFrameId,
                url,
                proxy: true
            }
        );
        await frontend.prepare();
    }

    _invoke(action, params={}) {
        return api.crossFrame.invoke(this._ownerFrameId, action, params);
    }
}