From e41b73aaa31f39bbb3f2a032d11904080af8c0a8 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:02:39 +0800 Subject: [PATCH] feat(launcher): launch the game through the guarded lab --- apps/launcher/electron.vite.config.ts | 1 + apps/launcher/src/main/index.ts | 15 +- apps/launcher/src/main/ipc/handlers.ts | 9 + .../main/services/diagnostics/diagnostics.ts | 6 +- .../src/main/services/launch/build-copy.ts | 62 ++++++ .../src/main/services/launch/lab-handoff.ts | 177 ++++++++++++++++++ .../main/services/launch/launch-controller.ts | 157 ++++++++++++++++ .../main/services/launch/process-output.ts | 16 ++ .../launcher/src/main/services/main-window.ts | 36 +++- .../src/main/workers/build-protocol.ts | 19 ++ .../launcher/src/main/workers/build-worker.ts | 53 ++++++ apps/launcher/src/renderer/src/App.tsx | 41 +++- .../src/renderer/src/i18n/locales/en.json | 61 +++++- .../src/renderer/src/i18n/locales/zh-CN.json | 61 +++++- .../src/renderer/src/pages/home/home-bar.ts | 71 ++++++- .../src/pages/settings/DeveloperSettings.tsx | 35 ++++ .../pages/settings/DiagnosticsSettings.tsx | 8 +- .../src/pages/settings/GeneralSettings.tsx | 12 ++ .../src/pages/settings/LaunchSettings.tsx | 29 +++ .../src/renderer/src/shell/navigation.ts | 2 +- apps/launcher/src/shared/errors.ts | 12 ++ apps/launcher/src/shared/ipc/channels.ts | 2 + apps/launcher/src/shared/ipc/contract.ts | 23 +++ apps/launcher/src/shared/schemas/launch.ts | 22 +++ apps/launcher/src/shared/schemas/settings.ts | 13 ++ 25 files changed, 920 insertions(+), 23 deletions(-) create mode 100644 apps/launcher/src/main/services/launch/build-copy.ts create mode 100644 apps/launcher/src/main/services/launch/lab-handoff.ts create mode 100644 apps/launcher/src/main/services/launch/launch-controller.ts create mode 100644 apps/launcher/src/main/services/launch/process-output.ts create mode 100644 apps/launcher/src/main/workers/build-protocol.ts create mode 100644 apps/launcher/src/main/workers/build-worker.ts create mode 100644 apps/launcher/src/renderer/src/pages/settings/DeveloperSettings.tsx create mode 100644 apps/launcher/src/renderer/src/pages/settings/LaunchSettings.tsx create mode 100644 apps/launcher/src/shared/schemas/launch.ts diff --git a/apps/launcher/electron.vite.config.ts b/apps/launcher/electron.vite.config.ts index 329d1c6..1ea6046 100644 --- a/apps/launcher/electron.vite.config.ts +++ b/apps/launcher/electron.vite.config.ts @@ -14,6 +14,7 @@ export default defineConfig({ // Utility process entries sit next to index.js, where the main process forks them. input: { index: resolve('src/main/index.ts'), + 'build-worker': resolve('src/main/workers/build-worker.ts'), 'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'), }, }, diff --git a/apps/launcher/src/main/index.ts b/apps/launcher/src/main/index.ts index 6e74d51..0dc2e25 100644 --- a/apps/launcher/src/main/index.ts +++ b/apps/launcher/src/main/index.ts @@ -2,7 +2,8 @@ import { app } from 'electron'; import { registerIpcHandlers } from './ipc/handlers.ts'; import { handleArtProtocol, registerArtScheme } from './services/background-art/art-protocol.ts'; import { startLauncherLogging } from './services/diagnostics/launcher-log.ts'; -import { createMainWindow, showMainWindow } from './services/main-window.ts'; +import { stopLaunch } from './services/launch/launch-controller.ts'; +import { beginWindowQuit, createMainWindow, showMainWindow } from './services/main-window.ts'; /** * Main process entry. Order: @@ -26,6 +27,18 @@ if (!app.requestSingleInstanceLock()) { startLauncherLogging(); app.on('second-instance', () => showMainWindow()); app.on('window-all-closed', () => app.quit()); + let quitAfterLaunch = false; + app.on('before-quit', (event) => { + const cleanup = stopLaunch(); + if (!cleanup) { + beginWindowQuit(); + return; + } + event.preventDefault(); + if (quitAfterLaunch) return; + quitAfterLaunch = true; + void cleanup.finally(() => app.quit()); + }); // A top-level await on whenReady deadlocks an ESM main entry on Windows. void app.whenReady().then(() => { registerIpcHandlers(); diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index b9b3dde..2934ea0 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -9,6 +9,8 @@ import { inspectGameFolder, requireFolder } from '../services/game-folder/inspec import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts'; import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts'; import { defaultDataPath, readInstallRecord } from '../services/install/install-record.ts'; +import { readInstalledLab } from '../services/launch/lab-handoff.ts'; +import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts'; import { broadcast, handle } from './register.ts'; @@ -19,6 +21,7 @@ export function registerIpcHandlers(): void { return { version: app.getVersion(), electron: process.versions.electron, + development: !app.isPackaged, systemLocale: app.getLocale(), userDataPath: app.getPath('userData'), supportedGameVersions: recordedGameVersions(resources.patches), @@ -72,6 +75,12 @@ export function registerIpcHandlers(): void { return patchFeatures(resources.patches).map((feature) => ({ ...feature, patchIds: [...feature.patchIds] })); }); + handle('launch:getState', () => getLaunchState()); + handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); + handle('launch:start', () => startLaunch((state) => broadcast('event:launch-state', state))); + handle('launch:stop', async () => { await stopLaunch(); }); + handle('launch:openServerStatus', () => openServerStatus()); + handle('settings:get', () => getSettings()); handle('settings:update', async (patch) => { const settings = await updateSettings(patch); diff --git a/apps/launcher/src/main/services/diagnostics/diagnostics.ts b/apps/launcher/src/main/services/diagnostics/diagnostics.ts index 0d53a82..40d9715 100644 --- a/apps/launcher/src/main/services/diagnostics/diagnostics.ts +++ b/apps/launcher/src/main/services/diagnostics/diagnostics.ts @@ -4,6 +4,7 @@ import { join } from 'node:path'; import { app, dialog, shell, type BrowserWindow } from 'electron'; import { zipSync } from 'fflate'; import { AppError } from '@shared/errors.ts'; +import { getSettings } from '../config/settings-store.ts'; import { readInstallRecord } from '../install/install-record.ts'; import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts'; @@ -41,8 +42,9 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{ await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name)); } } - const record = await readInstallRecord(); - if (record) await addServerLogs(files, record.dataPath); + const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); + const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath; + if (dataPath) await addServerLogs(files, dataPath); const temporary = `${result.filePath}.${randomUUID()}.tmp`; try { diff --git a/apps/launcher/src/main/services/launch/build-copy.ts b/apps/launcher/src/main/services/launch/build-copy.ts new file mode 100644 index 0000000..53ec6b6 --- /dev/null +++ b/apps/launcher/src/main/services/launch/build-copy.ts @@ -0,0 +1,62 @@ +import { join } from 'node:path'; +import { utilityProcess } from 'electron'; +import { AppError } from '@shared/errors.ts'; +import type { BuildReply, BuildRequest } from '../../workers/build-protocol.ts'; +import { forwardProcessOutput } from './process-output.ts'; + +export async function buildCopy( + request: BuildRequest, + signal: AbortSignal, + progress: (written: number, total: number, file?: string) => void, +): Promise { + signal.throwIfAborted(); + const worker = utilityProcess.fork(join(import.meta.dirname, 'build-worker.js'), [], { + serviceName: 'WTOffline game build', + stdio: 'pipe', + }); + forwardProcessOutput(worker.stdout, 'build', 'info'); + forwardProcessOutput(worker.stderr, 'build', 'error'); + let writing = false; + const abort = (): void => { + // Once writes begin, finish the generation before accepting a retry. + if (!writing) worker.kill(); + }; + + try { + await new Promise((resolve, reject) => { + worker.once('exit', (code) => { + console.warn('[build] utility process exited:', code); + reject(signal.aborted ? signal.reason : new AppError('launch_build_failed')); + }); + worker.on('message', (reply: BuildReply) => { + switch (reply.kind) { + case 'prepared': + if (signal.aborted) { + reject(signal.reason); + break; + } + progress(0, reply.total); + writing = true; + worker.postMessage({ kind: 'write' }); + break; + case 'progress': + progress(reply.written, reply.total, reply.file); + break; + case 'written': + resolve(); + break; + case 'failed': + reject(new AppError(reply.error)); + break; + } + }); + signal.addEventListener('abort', abort, { once: true }); + worker.postMessage(request); + }); + signal.throwIfAborted(); + } finally { + signal.removeEventListener('abort', abort); + worker.removeAllListeners('exit'); + worker.kill(); + } +} diff --git a/apps/launcher/src/main/services/launch/lab-handoff.ts b/apps/launcher/src/main/services/launch/lab-handoff.ts new file mode 100644 index 0000000..c693b17 --- /dev/null +++ b/apps/launcher/src/main/services/launch/lab-handoff.ts @@ -0,0 +1,177 @@ +import { spawn } from 'node:child_process'; +import { lstat, readFile, realpath, writeFile } from 'node:fs/promises'; +import { isAbsolute, join, relative, resolve } from 'node:path'; +import { app } from 'electron'; +import { z } from 'zod'; +import { HEALTH_PATH } from '@wto/server'; +import { AppError } from '@shared/errors.ts'; +import { forwardProcessOutput } from './process-output.ts'; + +const Configuration = z.object({ + lab: z.string().min(1), + copy: z.string().min(1), + port: z.number().int().min(1).max(65535), + labUser: z.literal('wto-lab'), +}); +const Status = z.object({ + state: z.string(), + message: z.string(), + guardExitCode: z.number().nullable().optional(), +}); +const Health = z.object({ app: z.literal('wto-server'), pid: z.number() }); + +export interface Lab { + readonly installPath: string; + readonly copyPath: string; + readonly controlPath: string; + readonly port: number; +} + +export async function readInstalledLab(): Promise { + if (app.isPackaged || process.platform !== 'win32') throw new AppError('launch_lab_required'); + const programData = process.env['ProgramData']; + if (!programData) throw new AppError('launch_lab_missing'); + const installPath = join(programData, 'WTOffline-lab'); + try { + const config = Configuration.parse(JSON.parse(await readFile(join(installPath, 'lab.json'), 'utf8'))); + const root = await realpath(config.lab); + const copyPath = await realpath(resolve(root, config.copy)); + const relation = relative(root, copyPath); + if (!isAbsolute(config.lab) || !relation || relation.startsWith('..') || isAbsolute(relation)) { + throw new Error('The game copy is outside the lab.'); + } + const executableFolder = await realpath(join(copyPath, 'win64')); + if (relative(copyPath, executableFolder).toLowerCase() !== 'win64') { + throw new Error('The lab executable folder points outside the copy.'); + } + const controlPath = await realpath(join(root, 'automation')); + if (relative(root, controlPath).toLowerCase() !== 'automation') { + throw new Error('The lab control folder points outside the lab.'); + } + for (const name of ['Run-GuardedGame.ps1', 'WtoNetworkGuard.exe']) { + if (!(await lstat(join(installPath, name))).isFile()) throw new Error(`Missing lab file: ${name}`); + } + return { installPath, copyPath, controlPath, port: config.port }; + } catch (error) { + console.warn('[lab] the installed automation is unavailable:', error); + throw new AppError('launch_lab_missing'); + } +} + +export function labStatusUrl(port: number): string { + return `http://127.0.0.1:${port}${HEALTH_PATH}`; +} + +async function readStatus(lab: Lab): Promise | null> { + try { + return Status.parse(JSON.parse(await readFile(join(lab.controlPath, 'status.json'), 'utf8'))); + } catch { + return null; + } +} + +async function isReady(port: number, pid: number): Promise { + try { + const response = await fetch(labStatusUrl(port), { signal: AbortSignal.timeout(900) }); + return response.ok && Health.parse(await response.json()).pid === pid; + } catch { + return false; + } +} + +async function stopGame(lab: Lab): Promise { + await writeFile(join(lab.controlPath, 'stop-request'), '', { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'EEXIST') throw error; + }); +} + +type LabPhase = 'starting-server' | 'starting-game' | 'running' | 'server-exited'; + +/** The installed guard owns the game process and observes the stop request. */ +export async function runLab( + lab: Lab, + stockPath: string, + dataPath: string, + signal: AbortSignal, + publish: (phase: LabPhase) => void, +): Promise { + signal.throwIfAborted(); + const repository = resolve(app.getAppPath(), '..', '..'); + const child = spawn('powershell.exe', [ + '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', + '-File', join(repository, 'tools', 'lab', 'Start-LabTest.ps1'), + '-SkipBuild', '-Stock', stockPath, '-Data', dataPath, '-Install', lab.installPath, + ], { cwd: repository, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + + let serverPid: number | null = null; + let running = false; + let processClosed = false; + let serverExited = false; + let occupied = false; + let failures = 0; + let checking = false; + let stopSent = false; + + const requestStop = (): void => { + if (!running || stopSent || processClosed) return; + stopSent = true; + void stopGame(lab).catch((error: unknown) => { + stopSent = false; + console.error('[lab] could not request a guarded stop:', error); + }); + }; + const observe = (line: string): void => { + if (/Port \d+ is already in use\./.test(line)) occupied = true; + const ready = /^\[WTO lab test\] Local server pid (\d+) listening/.exec(line); + if (ready) { + serverPid = Number(ready[1]); + publish('starting-game'); + } + if (line.startsWith('[WTO lab test] Game running (pid ')) { + running = true; + publish('running'); + if (signal.aborted) requestStop(); + } + if (line.startsWith('[WTO lab test] Run ')) running = false; + }; + forwardProcessOutput(child.stdout, 'lab', 'info', observe); + forwardProcessOutput(child.stderr, 'lab', 'error', observe); + publish('starting-server'); + signal.addEventListener('abort', requestStop, { once: true }); + const interval = setInterval(() => { + if (!running || !serverPid || processClosed || checking) return; + if (signal.aborted || serverExited) { + requestStop(); + return; + } + checking = true; + void isReady(lab.port, serverPid).then((ready) => { + if (!running || processClosed) return; + failures = ready ? 0 : failures + 1; + if (failures < 3) return; + serverExited = true; + publish('server-exited'); + requestStop(); + }).finally(() => { checking = false; }); + }, 1000); + + try { + const code = await new Promise((done, fail) => { + child.once('error', fail); + child.once('close', done); + }); + processClosed = true; + if (signal.aborted) return; + if (occupied) throw new AppError('launch_port_busy'); + if (serverExited) throw new AppError('launch_server_exited'); + const status = serverPid === null ? null : await readStatus(lab); + if (code !== 0 || status?.state !== 'finished' || (status.guardExitCode ?? 0) !== 0 || + status.message.startsWith('EXTERNAL TCP CONNECTION')) { + throw new AppError('launch_lab_failed'); + } + } finally { + processClosed = true; + clearInterval(interval); + signal.removeEventListener('abort', requestStop); + } +} diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts new file mode 100644 index 0000000..b27951e --- /dev/null +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -0,0 +1,157 @@ +import { execFile } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { isAbsolute, join, relative } from 'node:path'; +import { promisify } from 'node:util'; +import { BrowserWindow, shell } from 'electron'; +import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import type { LaunchState } from '@shared/schemas/launch.ts'; +import { getSettings } from '../config/settings-store.ts'; +import { readInstallRecord } from '../install/install-record.ts'; +import { resourcePaths } from '../resources/resource-paths.ts'; +import { buildCopy } from './build-copy.ts'; +import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts'; + +const execute = promisify(execFile); + +interface LaunchJob { + readonly stop: AbortController; + readonly report: (state: LaunchState) => void; + done: Promise; +} + +let active: LaunchJob | null = null; +let state: LaunchState = { phase: 'ready' }; + +export function getLaunchState(): LaunchState { + return state; +} + +export function startLaunch(report: LaunchJob['report']): LaunchState { + if (active) throw new AppError('launch_busy'); + const job = { stop: new AbortController(), report, done: Promise.resolve() }; + active = job; + update(job, { phase: 'checking' }); + job.done = launch(job).catch((error: unknown) => { + const port = state.port; + const context = port === undefined ? {} : { port }; + if (job.stop.signal.aborted) { + update(job, { phase: 'ready' }); + return; + } + console.error('[launch] launch failed:', error); + const code = error instanceof AppError ? error.code : 'launch_lab_failed'; + switch (code) { + case 'launch_port_busy': + update(job, { phase: 'port-busy', ...context }); + break; + case 'launch_server_exited': + update(job, { phase: 'server-exited', ...context }); + break; + default: + update(job, { phase: 'failed', error: code, ...context }); + break; + } + }).finally(() => { + active = null; + }); + return state; +} + +export function stopLaunch(): Promise | null { + const job = active; + if (!job) return null; + if (!job.stop.signal.aborted) { + update(job, { ...state, phase: 'stopping' }); + job.stop.abort(); + } + return job.done; +} + +export async function openServerStatus(): Promise { + if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited'); + await shell.openExternal(labStatusUrl(state.port)); +} + +function update(job: LaunchJob, next: LaunchState): void { + state = next; + job.report(next); +} + +async function launch(job: LaunchJob): Promise { + const signal = job.stop.signal; + const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); + if (!record) throw new AppError('launch_no_copy'); + if (!settings.developerMode) throw new AppError('launch_lab_required'); + if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam'); + const currentVersion = await readVersion(record.copyPath, signal); + if (!currentVersion || currentVersion !== record.gameVersion) { + update(job, { phase: 'version-changed', actualVersion: currentVersion }); + return; + } + + const lab = await readInstalledLab(); + const stockPath = settings.labStockPath ?? record.stockBackupPath; + const dataPath = settings.labDataPath ?? record.dataPath; + if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) { + throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath }); + } + const relativeData = relative(stockPath, dataPath); + if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) { + throw new AppError('launch_copy_in_steam'); + } + update(job, { phase: 'checking', port: lab.port }); + const [labVersion, stockVersion, games] = await Promise.all([ + readVersion(lab.copyPath, signal), + readVersion(stockPath, signal), + execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }), + ]); + signal.throwIfAborted(); + if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version'); + if (/^"aces\.exe",/im.test(games.stdout)) throw new AppError('launch_game_running'); + await checkPort(lab.port); + signal.throwIfAborted(); + update(job, { phase: 'building', port: lab.port }); + await buildCopy({ + kind: 'build', + stockPath, + copyPath: lab.copyPath, + dataPath, + port: lab.port, + ...resourcePaths(), + acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), + }, signal, (filesWritten, filesTotal, file) => { + if (!signal.aborted) update(job, { + phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), + }); + }); + + await runLab(lab, stockPath, dataPath, signal, (phase) => { + if (!signal.aborted) update(job, { phase, port: lab.port }); + if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') { + for (const window of BrowserWindow.getAllWindows()) window.minimize(); + } + }); + update(job, { phase: 'ready' }); +} + +async function readVersion(folder: string, signal: AbortSignal): Promise { + try { + return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal })); + } catch (error) { + signal.throwIfAborted(); + console.warn('[launch] reading the game version failed:', folder, error); + return null; + } +} + +async function checkPort(port: number): Promise { + await new Promise((resolve, reject) => { + const listener = createServer(); + listener.once('error', (error: NodeJS.ErrnoException) => reject( + error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error, + )); + listener.listen(port, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve())); + }); +} diff --git a/apps/launcher/src/main/services/launch/process-output.ts b/apps/launcher/src/main/services/launch/process-output.ts new file mode 100644 index 0000000..7ffaaa7 --- /dev/null +++ b/apps/launcher/src/main/services/launch/process-output.ts @@ -0,0 +1,16 @@ +import { createInterface } from 'node:readline'; + +/** Preserve complete lines when a process splits or combines them across writes. */ +export function forwardProcessOutput( + stream: NodeJS.ReadableStream | null, + prefix: string, + level: 'info' | 'error', + onLine?: (line: string) => void, +): void { + if (!stream) return; + const reader = createInterface({ input: stream, crlfDelay: Infinity, terminal: false }); + reader.on('line', (line) => { + console[level](`[${prefix}] ${line}`); + onLine?.(line); + }); +} diff --git a/apps/launcher/src/main/services/main-window.ts b/apps/launcher/src/main/services/main-window.ts index efa3588..f08ae2e 100644 --- a/apps/launcher/src/main/services/main-window.ts +++ b/apps/launcher/src/main/services/main-window.ts @@ -1,5 +1,6 @@ import { join } from 'node:path'; -import { BrowserWindow, shell } from 'electron'; +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 @@ -13,6 +14,24 @@ const CONTENT_HEIGHT = 720; 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 { + 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({ @@ -39,6 +58,20 @@ export function createMainWindow(): BrowserWindow { 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; }); @@ -54,5 +87,6 @@ export function createMainWindow(): BrowserWindow { export function showMainWindow(): void { const window = mainWindow ?? createMainWindow(); if (window.isMinimized()) window.restore(); + if (!window.isVisible()) window.show(); window.focus(); } diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts new file mode 100644 index 0000000..4c87af6 --- /dev/null +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -0,0 +1,19 @@ +import type { AppErrorCode } from '@shared/errors.ts'; + +export interface BuildRequest { + readonly kind: 'build'; + readonly stockPath: string; + readonly copyPath: string; + readonly dataPath: string; + readonly port: number; + readonly patches: string; + readonly networkHookLibrary: string; + readonly acceptedUnavailable: readonly string[]; +} + +export type BuildCommand = BuildRequest | { readonly kind: 'write' }; +export type BuildReply = + | { readonly kind: 'prepared'; readonly total: number } + | { readonly kind: 'progress'; readonly written: number; readonly total: number; readonly file: string } + | { readonly kind: 'written' } + | { readonly kind: 'failed'; readonly error: AppErrorCode }; diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts new file mode 100644 index 0000000..f4fa3d1 --- /dev/null +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -0,0 +1,53 @@ +import { readFileSync } from 'node:fs'; +import type { MessageEvent } from 'electron'; +import { assertWritableCopy, buildGameCopy, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; +import { multiVehiclePackIds } from '@wto/server'; +import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; + +let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[] } | null = null; + +function send(reply: BuildReply): void { + process.parentPort.postMessage(reply); +} + +function build(request: BuildRequest): void { + assertWritableCopy(request.stockPath, request.copyPath); + const result = buildGameCopy({ + stock: readStockGameFiles(request.stockPath), + patches: request.patches, + networkHookLibrary: readFileSync(request.networkHookLibrary), + port: request.port, + multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), + placeholderDecals: true, + }); + const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; + const accepted = new Set(request.acceptedUnavailable); + if (result.blocking.length > 0 || unavailable.some((failure) => !accepted.has(failure.patchId))) { + console.error('[build] the copy has unaccepted or essential failures:', unavailable); + send({ kind: 'failed', error: 'launch_build_unavailable' }); + return; + } + prepared = { copyPath: request.copyPath, files: result.files }; + send({ kind: 'prepared', total: prepared.files.length }); +} + +process.parentPort.on('message', (event: MessageEvent) => { + const command = event.data as BuildCommand; + try { + if (command.kind === 'build') { + build(command); + return; + } + if (!prepared) throw new Error('No build is ready to write.'); + const { copyPath, files } = prepared; + prepared = null; + for (const [index, file] of files.entries()) { + writeGameCopy(copyPath, [file]); + send({ kind: 'progress', written: index + 1, total: files.length, file: file.path }); + } + send({ kind: 'written' }); + } catch (error) { + console.error('[build] preparing the game copy failed:', error); + send({ kind: 'failed', error: 'launch_build_failed' }); + } +}); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index a0b5c3b..76ece19 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -2,10 +2,11 @@ import { useEffect, useState, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import type { IpcOutput } from '@shared/ipc/contract.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; +import type { LaunchState } from '@shared/schemas/launch.ts'; import type { Settings } from '@shared/schemas/settings.ts'; import { Sheet } from './components/Sheet.tsx'; import { applyLanguage, resolveLanguage } from './i18n/index.ts'; -import { ipcOn } from './ipc.ts'; +import { ipcInvoke, ipcOn } from './ipc.ts'; import { AboutPage } from './pages/about/AboutPage.tsx'; import { CopySummary } from './pages/copies/CopySummary.tsx'; import { FeatureStatus } from './pages/copies/FeatureStatus.tsx'; @@ -17,8 +18,10 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts'; import { WizardMain } from './pages/install/WizardMain.tsx'; import { WizardSide } from './pages/install/WizardSide.tsx'; import { wizardBar } from './pages/install/wizard-bar.ts'; +import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx'; import { DiagnosticsSettings } from './pages/settings/DiagnosticsSettings.tsx'; import { GeneralSettings } from './pages/settings/GeneralSettings.tsx'; +import { LaunchSettings } from './pages/settings/LaunchSettings.tsx'; import { Background } from './shell/Background.tsx'; import { BottomBar } from './shell/BottomBar.tsx'; import type { BarModel } from './shell/bar-model.ts'; @@ -52,6 +55,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A const { message, report } = useErrorMessage(); const [settings, setSettings] = useState(initialSettings); const [record, setRecord] = useState(initialRecord); + const [launch, setLaunch] = useState({ phase: 'ready' }); const [route, setRoute] = useState(START_ROUTE); const supported = info.supportedGameVersions; @@ -68,8 +72,25 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A useEffect(() => ipcOn('event:settings-changed', setSettings), []); useEffect(() => applyLanguage(resolveLanguage(settings.language, info.systemLocale)), [settings.language, info.systemLocale]); + useEffect(() => { + let mounted = true; + let receivedEvent = false; + const dispose = ipcOn('event:launch-state', (state) => { + receivedEvent = true; + setLaunch(state); + }); + ipcInvoke('launch:getState').then((state) => { + if (mounted && !receivedEvent) setLaunch(state); + }).catch(report); + return () => { mounted = false; dispose(); }; + }, [report]); + const go = (to: Destination): void => setRoute((current) => navigate(current, to)); - const home = homeBar(record, t, wizard.start); + const home = homeBar(record, launch, t, wizard.start, { + start: () => { ipcInvoke('launch:start').catch(report); }, + stop: () => { ipcInvoke('launch:stop').catch(report); }, + checkVersion: () => go({ page: 'copies', section: 'features' }), + }); const view = ((): View => { if (wizard.active) { @@ -90,14 +111,20 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A }; case 'about': return { side: homeSide, main: , bar: home }; - case 'settings': + case 'settings': { + const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev'); + const content = { + general: , + launch: , + diag: , + dev: , + }; return { - side: t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />, - main: route.settings === 'diag' - ? - : , + side: t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />, + main: content[route.settings], bar: home, }; + } case 'copies': { const side = ( <> diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index b8a8378..f24c74e 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -62,9 +62,27 @@ "install": "Install", "ready": "Ready", "readyMissing": "Ready · {{count}} features unavailable", - "readyDetail": "Game {{version}} · Launch unavailable", + "readyDetail": "Game {{version}}", "launch": "Launch" }, + "launch": { + "checking": "Checking the game copy", + "building": "Generating game files", + "starting-server": "Starting local server", + "starting-game": "Starting game", + "starting": "Starting…", + "running": "Game running", + "runningDetail": "Local server · Port {{port}}", + "stopping": "Stopping game", + "cancel": "Cancel", + "stop": "End game", + "retry": "Retry", + "check": "Check", + "version-changed": "The copy version has changed", + "versionDetail": "Game version {{version}}", + "port-busy": "Port {{port}} is already in use", + "server-exited": "The local server exited unexpectedly" + }, "folder": { "none": "Not selected", "choose": "Browse…", @@ -199,8 +217,33 @@ "settings": { "sections": { "general": "General", + "launch": "Launch", + "dev": "Developer", "diag": "Diagnostics" }, + "windowClose": "When closing the window", + "windowQuit": "Quit launcher", + "windowTray": "Minimize to system tray", + "afterGameStarts": "When the game starts", + "windowMinimize": "Minimize launcher", + "windowKeep": "Keep window open", + "launch": { + "port": "Local server port", + "portHint": "Port set by the installed lab automation", + "exit": "When the game exits", + "exitHint": "Isolated launch", + "automatic": "Close local server" + }, + "developer": { + "mode": "Developer mode", + "modeHint": "Launches the lab copy under the wto-lab Windows account", + "enabled": "Enabled", + "stock": "Stock backup", + "stockHint": "Defaults to the selected copy’s stock backup", + "data": "Lab data folder", + "dataHint": "Defaults to the selected copy’s data folder", + "reset": "Restore default" + }, "diagnostics": { "logs": "Logs", "logsHint": "Logs recorded by the launcher", @@ -208,7 +251,9 @@ "export": "Export diagnostics", "exportHint": "Save logs, settings and the installation record to a ZIP file", "save": "Export…", - "saved": "Diagnostics saved to {{path}}." + "saved": "Diagnostics saved to {{path}}.", + "serverStatus": "Local server status", + "openStatus": "Open in browser" }, "language": "Language", "languageHint": "Display language of the launcher" @@ -281,6 +326,18 @@ "internal_error": "An internal launcher error occurred.", "logs_folder_open_failed": "The launcher log folder could not be opened.", "diagnostics_export_failed": "The diagnostics archive could not be saved.", + "launch_no_copy": "A game copy must be installed before launching.", + "launch_busy": "A launch is already in progress.", + "launch_lab_required": "Enable developer mode to launch through the isolated lab.", + "launch_lab_missing": "The isolated lab automation could not be loaded.", + "launch_lab_version": "The lab copy and the stock backup must use the same game version.", + "launch_lab_failed": "The isolated launch failed. See the launcher log.", + "launch_game_running": "Another game process is running.", + "launch_copy_in_steam": "The launch requires a separate copy and data folder outside Steam.", + "launch_build_failed": "The game files could not be generated.", + "launch_build_unavailable": "The build found unavailable patches that require review.", + "launch_port_busy": "The local server port is already in use.", + "launch_server_exited": "The local server is unavailable.", "settings_write_failed": "The settings could not be saved.", "folder_unreadable": "The folder cannot be read: {{path}}", "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 75f00d7..c55b231 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -62,9 +62,27 @@ "install": "安装", "ready": "就绪", "readyMissing": "就绪 · {{count}} 项功能不可用", - "readyDetail": "游戏 {{version}} · 启动暂不可用", + "readyDetail": "游戏 {{version}}", "launch": "启动" }, + "launch": { + "checking": "正在检查副本", + "building": "正在生成游戏文件", + "starting-server": "正在启动本地服务器", + "starting-game": "正在启动游戏", + "starting": "启动中…", + "running": "游戏运行中", + "runningDetail": "本地服务器 · 端口 {{port}}", + "stopping": "正在结束游戏", + "cancel": "取消", + "stop": "结束游戏", + "retry": "重试", + "check": "检查", + "version-changed": "副本版本已变更", + "versionDetail": "游戏版本 {{version}}", + "port-busy": "端口 {{port}} 已被占用", + "server-exited": "本地服务器意外退出" + }, "folder": { "none": "未选择", "choose": "浏览…", @@ -199,8 +217,33 @@ "settings": { "sections": { "general": "常规", + "launch": "启动", + "dev": "开发者", "diag": "诊断" }, + "windowClose": "关闭窗口时", + "windowQuit": "退出启动器", + "windowTray": "最小化到系统托盘", + "afterGameStarts": "游戏启动后", + "windowMinimize": "最小化启动器", + "windowKeep": "保持窗口", + "launch": { + "port": "本地服务器端口", + "portHint": "使用已安装实验自动化的端口设置", + "exit": "游戏退出后", + "exitHint": "隔离启动", + "automatic": "关闭本地服务器" + }, + "developer": { + "mode": "开发模式", + "modeHint": "以 wto-lab 用户身份启动实验副本", + "enabled": "启用", + "stock": "原版文件备份", + "stockHint": "默认使用当前副本的原版文件备份", + "data": "实验数据目录", + "dataHint": "默认使用当前副本的数据目录", + "reset": "恢复默认" + }, "diagnostics": { "logs": "日志", "logsHint": "启动器运行日志", @@ -208,7 +251,9 @@ "export": "导出诊断信息", "exportHint": "导出包含日志、设置和安装记录的 ZIP 文件", "save": "导出…", - "saved": "诊断信息已保存到 {{path}}。" + "saved": "诊断信息已保存到 {{path}}。", + "serverStatus": "本地服务器状态页", + "openStatus": "在浏览器中打开" }, "language": "语言", "languageHint": "启动器界面的显示语言" @@ -281,6 +326,18 @@ "internal_error": "启动器内部错误。", "logs_folder_open_failed": "无法打开启动器日志文件夹。", "diagnostics_export_failed": "无法保存诊断信息。", + "launch_no_copy": "启动前需要安装游戏副本。", + "launch_busy": "启动流程正在运行。", + "launch_lab_required": "请启用开发模式以通过隔离实验副本启动。", + "launch_lab_missing": "无法读取隔离实验自动化配置。", + "launch_lab_version": "实验副本和原版文件备份必须使用同一游戏版本。", + "launch_lab_failed": "隔离启动失败。请查看启动器日志。", + "launch_game_running": "已有游戏进程在运行。", + "launch_copy_in_steam": "启动需使用 Steam 目录外的副本和数据目录。", + "launch_build_failed": "无法生成游戏文件。", + "launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。", + "launch_port_busy": "本地服务器端口已被占用。", + "launch_server_exited": "本地服务器不可用。", "settings_write_failed": "无法保存设置。", "folder_unreadable": "无法读取文件夹:{{path}}", "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", diff --git a/apps/launcher/src/renderer/src/pages/home/home-bar.ts b/apps/launcher/src/renderer/src/pages/home/home-bar.ts index 37ababa..21bab4a 100644 --- a/apps/launcher/src/renderer/src/pages/home/home-bar.ts +++ b/apps/launcher/src/renderer/src/pages/home/home-bar.ts @@ -1,13 +1,72 @@ import type { TFunction } from 'i18next'; import type { InstallRecord } from '@shared/schemas/install.ts'; +import type { LaunchState } from '@shared/schemas/launch.ts'; import type { BarModel } from '../../shell/bar-model.ts'; import { missingFeatures } from '../copies/missing-features.ts'; -/** - * The bottom bar outside the wizard: install before the first installation, launch after it. - * The launch action is disabled until the launcher can start a copy. - */ -export function homeBar(record: InstallRecord | null, t: TFunction, onInstall: () => void): BarModel { +interface LaunchActions { + readonly start: () => void; + readonly stop: () => void; + readonly checkVersion: () => void; +} + +/** The installation and launch actions shown outside the wizard. */ +export function homeBar( + record: InstallRecord | null, + state: LaunchState, + t: TFunction, + onInstall: () => void, + actions: LaunchActions, +): BarModel { + const launch = { label: t('bar.launch'), onClick: actions.start }; + const retry = { label: t('launch.retry'), onClick: actions.start }; + const starting = { label: t('launch.starting'), disabled: true }; + const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null }; + switch (state.phase) { + case 'checking': + case 'building': + return { + tone: 'busy', + title: state.phase === 'checking' ? t('launch.checking') : t('launch.building'), + detail: state.file, + progress, + primary: starting, + secondary: { label: t('launch.cancel'), onClick: actions.stop }, + }; + case 'starting-server': + case 'starting-game': + case 'stopping': + return { + tone: 'busy', + title: t(`launch.${state.phase}`), + progress: { value: 0, max: null }, + primary: starting, + }; + case 'running': + return { + tone: 'ok', + title: t('launch.running'), + detail: t('launch.runningDetail', { port: state.port }), + primary: { label: t('launch.running'), disabled: true }, + secondary: { label: t('launch.stop'), onClick: actions.stop }, + }; + case 'port-busy': + return { tone: 'bad', title: t('launch.port-busy', { port: state.port }), primary: retry }; + case 'server-exited': + return { tone: 'bad', title: t('launch.server-exited'), primary: retry }; + case 'version-changed': + return { + tone: 'warn', + title: t('launch.version-changed'), + detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }), + primary: { label: t('launch.check'), onClick: actions.checkVersion }, + }; + case 'failed': + return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_lab_failed'}`), primary: retry }; + case 'ready': + break; + } + if (!record) { return { tone: 'idle', @@ -21,6 +80,6 @@ export function homeBar(record: InstallRecord | null, t: TFunction, onInstall: ( tone: missing ? 'warn' : 'ok', title: missing ? t('bar.readyMissing', { count: missing }) : t('bar.ready'), detail: t('bar.readyDetail', { version: record.gameVersion ?? t('source.versionUnknown') }), - primary: { label: t('bar.launch'), disabled: true }, + primary: launch, }; } diff --git a/apps/launcher/src/renderer/src/pages/settings/DeveloperSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/DeveloperSettings.tsx new file mode 100644 index 0000000..1c9d29c --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/settings/DeveloperSettings.tsx @@ -0,0 +1,35 @@ +import { useTranslation } from 'react-i18next'; +import type { Settings, SettingsPatch } from '@shared/schemas/settings.ts'; +import { FolderField } from '../../components/FolderField.tsx'; +import { Row } from '../../components/Row.tsx'; +import { Sheet } from '../../components/Sheet.tsx'; +import { ipcInvoke } from '../../ipc.ts'; + +interface DeveloperSettingsProps { + readonly settings: Settings; + readonly onError: (error: unknown) => void; +} + +export function DeveloperSettings({ settings, onError }: DeveloperSettingsProps) { + const { t } = useTranslation(); + const update = (patch: SettingsPatch): void => { ipcInvoke('settings:update', patch).catch(onError); }; + + return ( + + + + + + update({ labStockPath: path })} onError={onError} /> + {settings.labStockPath && } + + + update({ labDataPath: path })} onError={onError} /> + {settings.labDataPath && } + + + ); +} diff --git a/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx index e114f7a..cec0c41 100644 --- a/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx +++ b/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx @@ -5,10 +5,11 @@ import { Sheet } from '../../components/Sheet.tsx'; import { ipcInvoke } from '../../ipc.ts'; interface DiagnosticsSettingsProps { + readonly serverRunning: boolean; readonly onError: (error: unknown) => void; } -export function DiagnosticsSettings({ onError }: DiagnosticsSettingsProps) { +export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) { const { t } = useTranslation(); const [exporting, setExporting] = useState(false); const [savedPath, setSavedPath] = useState(null); @@ -38,6 +39,11 @@ export function DiagnosticsSettings({ onError }: DiagnosticsSettingsProps) { {t('settings.diagnostics.save')} + + + {savedPath &&

{t('settings.diagnostics.saved', { path: savedPath })}

} ); diff --git a/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx index ddd603d..9cde364 100644 --- a/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx +++ b/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx @@ -38,6 +38,18 @@ export function GeneralSettings({ settings, pictures, onError }: GeneralSettings + + + + + +