summaryrefslogtreecommitdiffhomepage
path: root/gui/src/main/window-controller.ts
blob: c4d6b4723275d25a6ce8046890dc02106873648b (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
import { BrowserWindow, Display, screen, Tray, WebContents } from 'electron';
import { IWindowShapeParameters } from '../shared/ipc-types';
import { Scheduler } from '../shared/scheduler';
import { IpcMainEventChannel } from './ipc-event-channel';
import { isWindows11OrNewer } from './platform-version';

interface IPosition {
  x: number;
  y: number;
}

interface IWindowPositioning {
  getPosition(window: BrowserWindow): IPosition;
  getWindowShapeParameters(window: BrowserWindow): IWindowShapeParameters;
}

// Tray applications are positioned aproximately 10px from the tray in Windows 11.
const MARGIN = isWindows11OrNewer() ? 10 : 0;

class StandaloneWindowPositioning implements IWindowPositioning {
  public getPosition(window: BrowserWindow): IPosition {
    const windowBounds = window.getBounds();

    const primaryDisplay = screen.getPrimaryDisplay();
    const workArea = primaryDisplay.workArea;
    const maxX = workArea.x + workArea.width - windowBounds.width;
    const maxY = workArea.y + workArea.height - windowBounds.height;

    const x = Math.min(Math.max(windowBounds.x, workArea.x), maxX);
    const y = Math.min(Math.max(windowBounds.y, workArea.y), maxY);

    return { x, y };
  }

  public getWindowShapeParameters(_window: BrowserWindow): IWindowShapeParameters {
    return {};
  }
}

class AttachedToTrayWindowPositioning implements IWindowPositioning {
  private tray: Tray;

  constructor(tray: Tray) {
    this.tray = tray;
  }

  public getPosition(window: BrowserWindow): IPosition {
    const windowBounds = window.getBounds();
    const trayBounds = this.tray.getBounds();

    const activeDisplay = screen.getDisplayNearestPoint({
      x: trayBounds.x,
      y: trayBounds.y,
    });
    const workArea = activeDisplay.workArea;
    const placement = this.getTrayPlacement();
    const maxX = workArea.x + workArea.width - windowBounds.width;
    const maxY = workArea.y + workArea.height - windowBounds.height;

    let x = 0;
    let y = 0;

    switch (placement) {
      case 'top':
        x = trayBounds.x + (trayBounds.width - windowBounds.width) * 0.5;
        y = workArea.y + MARGIN;
        break;

      case 'bottom':
        x = trayBounds.x + (trayBounds.width - windowBounds.width) * 0.5;
        y = workArea.y + workArea.height - windowBounds.height - MARGIN;
        break;

      case 'left':
        x = workArea.x + MARGIN;
        y = trayBounds.y + (trayBounds.height - windowBounds.height) * 0.5;
        break;

      case 'right':
        x = workArea.width - windowBounds.width - MARGIN;
        y = trayBounds.y + (trayBounds.height - windowBounds.height) * 0.5;
        break;

      case 'none':
        x = workArea.x + (workArea.width - windowBounds.width) * 0.5;
        y = workArea.y + (workArea.height - windowBounds.height) * 0.5;
        break;
    }

    x = Math.min(Math.max(x, workArea.x), maxX);
    y = Math.min(Math.max(y, workArea.y), maxY);

    return {
      x: Math.round(x),
      y: Math.round(y),
    };
  }

  public getWindowShapeParameters(window: BrowserWindow): IWindowShapeParameters {
    const trayBounds = this.tray.getBounds();
    const windowBounds = window.getBounds();
    const arrowPosition = trayBounds.x - windowBounds.x + trayBounds.width * 0.5;
    return {
      arrowPosition,
    };
  }

  private getTrayPlacement() {
    switch (process.platform) {
      case 'darwin':
        // macOS has menubar always placed at the top
        return 'top';

      case 'win32': {
        // taskbar occupies some part of the screen excluded from work area
        const primaryDisplay = screen.getPrimaryDisplay();
        const displaySize = primaryDisplay.size;
        const workArea = primaryDisplay.workArea;

        if (workArea.width < displaySize.width) {
          return workArea.x > 0 ? 'left' : 'right';
        } else if (workArea.height < displaySize.height) {
          return workArea.y > 0 ? 'top' : 'bottom';
        } else {
          return 'none';
        }
      }

      default:
        return 'none';
    }
  }
}

export default class WindowController {
  private windowValue: BrowserWindow;
  private webContentsValue: WebContents;
  private windowPositioning: IWindowPositioning;

  private windowPositioningScheduler = new Scheduler();

  get window(): BrowserWindow | undefined {
    return this.windowValue.isDestroyed() ? undefined : this.windowValue;
  }

  get webContents(): WebContents | undefined {
    return this.webContentsValue.isDestroyed() ? undefined : this.webContentsValue;
  }

  constructor(windowValue: BrowserWindow, tray: Tray, private unpinnedWindow: boolean) {
    this.windowValue = windowValue;
    this.webContentsValue = windowValue.webContents;
    this.windowPositioning = unpinnedWindow
      ? new StandaloneWindowPositioning()
      : new AttachedToTrayWindowPositioning(tray);

    this.installDisplayMetricsHandler();
    this.installHideHandler();
  }

  public show(whenReady = true) {
    if (whenReady) {
      this.executeWhenWindowIsReady(() => this.showImmediately());
    } else {
      this.showImmediately();
    }
  }

  public hide() {
    this.window?.hide();
  }

  public toggle() {
    if (this.window?.isVisible()) {
      this.hide();
    } else {
      this.show();
    }
  }

  public isVisible(): boolean {
    return this.window?.isVisible() ?? false;
  }

  public updatePosition() {
    if (this.window) {
      const { x, y } = this.windowPositioning.getPosition(this.window);
      this.window.setPosition(x, y, false);
    }

    this.notifyUpdateWindowShape();
  }

  public destroy() {
    if (this.window && !this.window.isDestroyed()) {
      this.window.destroy();
    }
  }

  public static getContentSize(unpinnedWindow: boolean): { width: number; height: number } {
    return {
      width: 320,
      height: WindowController.getContentHeight(unpinnedWindow),
    };
  }

  private installHideHandler() {
    this.window?.addListener('hide', () => this.windowPositioningScheduler.cancel());
    this.window?.addListener('closed', () => this.windowPositioningScheduler.cancel());
  }

  private showImmediately() {
    const window = this.window;

    // When running with unpinned window on Windows there's a bug that causes the app to become
    // wider if opened from minimized if the updated position is set before the window is opened.
    // Unfortunately the order can't always be changed since this would cause the Window to "jump"
    // in other scenarios.
    if (
      process.platform === 'win32' &&
      this.windowPositioning instanceof StandaloneWindowPositioning
    ) {
      window?.show();
      window?.focus();

      this.updatePosition();
    } else {
      this.updatePosition();

      window?.show();
      window?.focus();
    }
  }

  private notifyUpdateWindowShape() {
    if (this.window) {
      const shapeParameters = this.windowPositioning.getWindowShapeParameters(this.window);

      IpcMainEventChannel.window.notifyShape(this.webContentsValue, shapeParameters);
    }
  }

  // Installs display event handlers to update the window position on any changes in the display or
  // workarea dimensions.
  private installDisplayMetricsHandler() {
    if (this.window) {
      screen.addListener('display-metrics-changed', this.onDisplayMetricsChanged);
      this.window.once('closed', () => {
        screen.removeListener('display-metrics-changed', this.onDisplayMetricsChanged);
      });
    }
  }

  private onDisplayMetricsChanged = (
    _event: Electron.Event,
    _display: Display,
    changedMetrics: string[],
  ) => {
    if (changedMetrics.includes('workArea') && this.window?.isVisible()) {
      this.onWorkAreaSizeChange();
      if (process.platform === 'win32') {
        this.windowPositioningScheduler.schedule(() => this.onWorkAreaSizeChange(), 500);
      }
    }

    // On Linux and Windows, the window won't be properly rescaled back to it's original
    // size if the DPI scaling factor is changed.
    // https://github.com/electron/electron/issues/11050
    if (
      changedMetrics.includes('scaleFactor') &&
      (process.platform === 'win32' || process.platform === 'linux')
    ) {
      this.forceResizeWindow();
    }
  };

  private onWorkAreaSizeChange() {
    this.updatePosition();
  }

  private forceResizeWindow() {
    const { width, height } = WindowController.getContentSize(this.unpinnedWindow);
    this.window?.setContentSize(width, height);
  }

  private executeWhenWindowIsReady(closure: () => void) {
    if (this.webContents?.isLoading() === false && this.webContents?.getURL() !== '') {
      closure();
    } else {
      this.webContents?.once('did-stop-loading', () => {
        closure();
      });
    }
  }

  // On both Linux and Windows the app height is applied incorrectly:
  // https://github.com/electron/electron/issues/28777
  private static getContentHeight(unpinnedWindow: boolean): number {
    // The height we want to achieve.
    const contentHeight = 568;

    switch (process.platform) {
      case 'darwin': {
        // The size of transparent area around arrow on macOS.
        const headerBarArrowHeight = 12;

        return unpinnedWindow ? contentHeight : contentHeight + headerBarArrowHeight;
      }
      case 'win32':
        // On Windows the app height ends up slightly lower than we set it to if running in unpinned
        // mode and the app becomes a tiny bit taller when pinned to task bar.
        return unpinnedWindow ? contentHeight + 19 : contentHeight - 1;
      case 'linux':
        // On Linux the app ends up slightly lower than we set it to.
        return contentHeight - 25;
      default:
        return contentHeight;
    }
  }
}