Files
WT-Offline/apps/launcher/src/main/services/main-window.ts
T

93 lines
3.0 KiB
TypeScript

import { join } from 'node:path';
import { app, BrowserWindow, Menu, shell, Tray } from 'electron';
import { getSettings } from './config/settings-store.ts';
/**
* The launcher's single window: a fixed size without the system frame, like the game's own
* launcher. The window draws its title bar and asks for minimize and close over IPC.
*/
/** The layout is drawn for exactly this content size. */
const CONTENT_WIDTH = 1120;
const CONTENT_HEIGHT = 720;
/** The window background before the page paints (--bg in the window's styles). */
const BACKGROUND = '#13191b';
let mainWindow: BrowserWindow | null = null;
let tray: Tray | null = null;
let quitting = false;
export function beginWindowQuit(): void {
quitting = true;
tray?.destroy();
tray = null;
}
async function hideToTray(window: BrowserWindow): Promise<void> {
if (!tray) {
tray = new Tray(await app.getFileIcon(process.execPath, { size: 'small' }));
tray.setToolTip(app.getName());
tray.setContextMenu(Menu.buildFromTemplate([{ role: 'quit' }]));
tray.on('click', () => showMainWindow());
}
if (!window.isDestroyed()) window.hide();
}
export function createMainWindow(): BrowserWindow {
const window = new BrowserWindow({
width: CONTENT_WIDTH,
height: CONTENT_HEIGHT,
useContentSize: true,
resizable: false,
maximizable: false,
fullscreenable: false,
frame: false,
backgroundColor: BACKGROUND,
show: false,
webPreferences: {
preload: join(import.meta.dirname, '../preload/index.cjs'),
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
},
});
window.once('ready-to-show', () => window.show());
// Links leave the launcher for the player's browser; the window itself never navigates away.
window.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
return { action: 'deny' };
});
window.webContents.on('will-navigate', (event) => event.preventDefault());
let handlingClose = false;
window.on('close', (event) => {
if (quitting) return;
event.preventDefault();
if (handlingClose) return;
handlingClose = true;
void getSettings().then(async (settings) => {
if (settings.windowClose === 'tray') await hideToTray(window);
else app.quit();
}).catch((error: unknown) => {
console.warn('[window] the close action failed:', error);
app.quit();
}).finally(() => { handlingClose = false; });
});
window.on('closed', () => {
if (mainWindow === window) mainWindow = null;
});
const devServer = process.env['ELECTRON_RENDERER_URL'];
if (devServer) void window.loadURL(devServer);
else void window.loadFile(join(import.meta.dirname, '../renderer/index.html'));
mainWindow = window;
return window;
}
/** Brings the window forward, building it again if it was closed. */
export function showMainWindow(): void {
const window = mainWindow ?? createMainWindow();
if (window.isMinimized()) window.restore();
if (!window.isVisible()) window.show();
window.focus();
}