aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/infrastructure/electron/impl/ElectronMainWindow.ts
blob: f1e3c7e53dc2b8b08eeae86fa0417c9fa61c64fb (plain) (blame)
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
/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import {
  Action,
  MainToRendererIpcMessage,
  RendererToMainIpcMessage,
  Translation,
} from '@sophie/shared';
import { BrowserWindow, ipcMain, IpcMainEvent } from 'electron';
import { reaction } from 'mobx';
import type { IJsonPatch } from 'mobx-state-tree';

import type MainStore from '../../../stores/MainStore.js';
import Disposer from '../../../utils/Disposer.js';
import getLogger from '../../../utils/getLogger.js';
import RendererBridge from '../RendererBridge.js';
import type { MainWindow, ServiceView } from '../types.js';

import ElectronServiceView from './ElectronServiceView.js';
import type ElectronViewFactory from './ElectronViewFactory.js';
import { openDevToolsWhenReady } from './devTools.js';
import lockWebContentsToFile from './lockWebContentsToFile.js';

const log = getLogger('ElectronMainWindow');

function getBackroundColor(useDarkTheme: boolean): string {
  return useDarkTheme ? '#121212' : '#FFF';
}

export default class ElectronMainWindow implements MainWindow {
  private readonly browserWindow: BrowserWindow;

  private readonly bridge: RendererBridge;

  private readonly dispatchActionHandler = (
    event: IpcMainEvent,
    rawAction: unknown,
  ): void => {
    const { id } = event.sender;
    if (id !== this.browserWindow.webContents.id) {
      log.warn(
        'Unexpected',
        RendererToMainIpcMessage.DispatchAction,
        'from webContents',
        id,
      );
      return;
    }
    try {
      const action = Action.parse(rawAction);
      this.store.dispatch(action);
    } catch (error) {
      log.error('Error while dispatching renderer action', rawAction, error);
    }
  };

  private readonly disposeBackgroundColorReaction: Disposer;

  constructor(
    private readonly store: MainStore,
    private readonly parent: ElectronViewFactory,
  ) {
    this.browserWindow = new BrowserWindow({
      show: false,
      autoHideMenuBar: true,
      darkTheme: store.shared.shouldUseDarkColors,
      backgroundColor: getBackroundColor(store.shared.shouldUseDarkColors),
      webPreferences: {
        sandbox: true,
        devTools: parent.devMode,
        preload: parent.resources.getPath('preload', 'index.cjs'),
      },
    });

    const { webContents } = this.browserWindow;

    ipcMain.handle(RendererToMainIpcMessage.GetSharedStoreSnapshot, (event) => {
      const { id } = event.sender;
      if (id !== webContents.id) {
        log.warn(
          'Unexpected',
          RendererToMainIpcMessage.GetSharedStoreSnapshot,
          'from webContents',
          id,
        );
        throw new Error('Invalid IPC call');
      }
      return this.bridge.snapshot;
    });

    ipcMain.handle(
      RendererToMainIpcMessage.GetTranslation,
      (event, translation) => {
        const { id } = event.sender;
        if (id !== webContents.id) {
          log.warn(
            'Unexpected',
            RendererToMainIpcMessage.GetTranslation,
            'from webContents',
            id,
          );
          throw new Error('Invalid IPC call');
        }
        const { language, namespace } = Translation.parse(translation);
        return store.getTranslation(language, namespace);
      },
    );

    this.bridge = new RendererBridge(store, (patch) => {
      webContents.send(MainToRendererIpcMessage.SharedStorePatch, patch);
    });

    ipcMain.on(
      RendererToMainIpcMessage.DispatchAction,
      this.dispatchActionHandler,
    );

    webContents.userAgent = parent.userAgents.mainWindowUserAgent;

    this.disposeBackgroundColorReaction = reaction(
      () => store.shared.shouldUseDarkColors,
      (useDarkTheme) => {
        this.browserWindow.setBackgroundColor(getBackroundColor(useDarkTheme));
      },
    );

    this.browserWindow.on('ready-to-show', () => this.browserWindow.show());

    this.browserWindow.on('close', () => this.dispose());

    if (parent.devMode) {
      openDevToolsWhenReady(this.browserWindow);
    }
  }

  bringToForeground(): void {
    if (!this.browserWindow.isVisible()) {
      this.browserWindow.show();
    }
    if (this.browserWindow.isMinimized()) {
      this.browserWindow.restore();
    }
    this.browserWindow.focus();
  }

  setServiceView(serviceView: ServiceView | undefined) {
    if (serviceView === undefined) {
      // eslint-disable-next-line unicorn/no-null -- Electron API requires passing `null`.
      this.browserWindow.setBrowserView(null);
      return;
    }
    if (serviceView instanceof ElectronServiceView) {
      this.browserWindow.setBrowserView(serviceView.browserView);
      // If this `BrowserView` hasn't been attached previously,
      // we must update its bounds _after_ attaching for the resizing to take effect.
      serviceView.updateBounds();
      return;
    }
    throw new TypeError(
      'Unexpected ServiceView with no underlying BrowserView',
    );
  }

  reloadTranslations(): void {
    this.browserWindow.webContents.send(
      MainToRendererIpcMessage.ReloadTranslations,
    );
  }

  dispose() {
    this.bridge.dispose();
    this.disposeBackgroundColorReaction();
    this.browserWindow.destroy();
    ipcMain.removeHandler(RendererToMainIpcMessage.GetSharedStoreSnapshot);
    ipcMain.removeListener(
      RendererToMainIpcMessage.DispatchAction,
      this.dispatchActionHandler,
    );
  }

  loadInterface(): Promise<void> {
    return lockWebContentsToFile(
      this.parent.resources,
      'index.html',
      this.browserWindow.webContents,
    );
  }

  sendSharedStorePatch(patch: IJsonPatch[]): void {
    this.browserWindow.webContents.send(
      MainToRendererIpcMessage.SharedStorePatch,
      patch,
    );
  }
}