|
3 | 3 | * SPDX-License-Identifier: AGPL-3.0-or-later |
4 | 4 | */ |
5 | 5 |
|
6 | | -import { screen } from 'electron' |
| 6 | +import type { IpcMainEvent } from 'electron' |
| 7 | +import { BrowserWindow, ipcMain, screen } from 'electron' |
7 | 8 | import { getAppConfig } from './AppConfig.ts' |
8 | 9 |
|
9 | 10 | /** |
@@ -47,3 +48,48 @@ export function getScaledWindowMinSize({ minWidth, minHeight }: { minWidth: numb |
47 | 48 | minHeight: height, |
48 | 49 | } |
49 | 50 | } |
| 51 | + |
| 52 | +/** |
| 53 | + * Memoized promises of waitWindowMarkedReady. |
| 54 | + * Using WeakMap so that the promises are garbage collected when the window is destroyed. |
| 55 | + */ |
| 56 | +const windowMarkedReadyPromises = new WeakMap<BrowserWindow, Promise<void>>() |
| 57 | + |
| 58 | +/** |
| 59 | + * Wait for the window to be marked as ready to show by its renderer process |
| 60 | + * @param window - BrowserWindow |
| 61 | + */ |
| 62 | +export function waitWindowMarkedReady(window: BrowserWindow): Promise<void> { |
| 63 | + // As a window is marked ready only once. |
| 64 | + // Awaiting promise is memoized to allow multiple calls and calls on a ready window. |
| 65 | + |
| 66 | + if (windowMarkedReadyPromises.has(window)) { |
| 67 | + return windowMarkedReadyPromises.get(window)! |
| 68 | + } |
| 69 | + |
| 70 | + const promise: Promise<void> = new Promise((resolve) => { |
| 71 | + const handleMarkWindowReady = (event: IpcMainEvent) => { |
| 72 | + if (event.sender === window.webContents) { |
| 73 | + ipcMain.removeListener('app:markWindowReady', handleMarkWindowReady) |
| 74 | + resolve() |
| 75 | + } |
| 76 | + } |
| 77 | + ipcMain.on('app:markWindowReady', handleMarkWindowReady) |
| 78 | + }) |
| 79 | + |
| 80 | + windowMarkedReadyPromises.set(window, promise) |
| 81 | + |
| 82 | + return promise |
| 83 | +} |
| 84 | + |
| 85 | +/** |
| 86 | + * Show the window when it is marked as ready to show its renderer process |
| 87 | + * @param window - The BrowserWindow |
| 88 | + */ |
| 89 | +export async function showWhenWindowMarkedReady(window: BrowserWindow): Promise<void> { |
| 90 | + if (window.isVisible()) { |
| 91 | + return |
| 92 | + } |
| 93 | + await waitWindowMarkedReady(window) |
| 94 | + window.show() |
| 95 | +} |
0 commit comments