diff --git a/apps/launcher/electron.vite.config.ts b/apps/launcher/electron.vite.config.ts index b8b5a34..329d1c6 100644 --- a/apps/launcher/electron.vite.config.ts +++ b/apps/launcher/electron.vite.config.ts @@ -3,12 +3,21 @@ import { defineConfig, externalizeDepsPlugin } from 'electron-vite'; import react from '@vitejs/plugin-react'; // The workspace packages (@wto/patcher, @wto/server) stay external: they ship as -// TypeScript sources and run in utility processes on Electron's own Node, which strips -// the types itself. Bundling them would break the files they find next to their sources. +// TypeScript sources and run on Electron's own Node, which strips the types itself. +// Bundling them would break the files they find next to their sources. export default defineConfig({ main: { plugins: [externalizeDepsPlugin()], resolve: { alias: { '@shared': resolve('src/shared') } }, + build: { + rollupOptions: { + // Utility process entries sit next to index.js, where the main process forks them. + input: { + index: resolve('src/main/index.ts'), + 'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'), + }, + }, + }, }, preload: { plugins: [externalizeDepsPlugin()], diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 7555fb2..39c9bbd 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -4,6 +4,8 @@ import { getSettings, updateSettings } from '../services/config/settings-store.t import { measureFolder } from '../services/game-folder/folder-size.ts'; import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts'; 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 { broadcast, handle } from './register.ts'; /** Registers the handler of every contract channel. One line per channel; the work is in services/. */ @@ -34,6 +36,11 @@ export function registerIpcHandlers(): void { } }); + handle('install:checkPatches', ({ gamePath, dataPath }) => checkGameFolder(gamePath, dataPath)); + handle('install:start', (request) => installGame(request, (progress) => broadcast('event:install-progress', progress))); + handle('install:cancel', () => ({ cancelled: cancelInstall() })); + handle('install:getRecord', async () => ({ record: await readInstallRecord(), defaultDataPath: defaultDataPath() })); + handle('settings:get', () => getSettings()); handle('settings:update', async (patch) => { const settings = await updateSettings(patch); diff --git a/apps/launcher/src/main/services/install/copy-game.ts b/apps/launcher/src/main/services/install/copy-game.ts new file mode 100644 index 0000000..e159aea --- /dev/null +++ b/apps/launcher/src/main/services/install/copy-game.ts @@ -0,0 +1,126 @@ +import { createReadStream, createWriteStream } from 'node:fs'; +import { lstat, mkdir, readdir, rm } from 'node:fs/promises'; +import { join, relative } from 'node:path'; +import { Transform } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; + +/** + * Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock + * folder is only read. Nothing in the target is overwritten (the target was checked to be empty). + */ + +/** + * Top-level folders of an installation that hold what the game produced while the player played + * online, not the game itself: logs, the web content cache, replays, screenshots and the player's + * own missions. The offline copy does not take the online game's data (working rules 18); the + * game creates these folders again when it needs them. + */ +const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']); + +interface CopyEntry { + readonly relativePath: string; + readonly bytes: number; +} + +export interface CopyPlan { + readonly files: readonly CopyEntry[]; + readonly folders: readonly string[]; + readonly totalBytes: number; +} + +export interface CopyProgress { + readonly doneBytes: number; + readonly doneFiles: number; +} + +/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */ +export async function planCopy(source: string): Promise { + const files: CopyEntry[] = []; + const folders: string[] = []; + let totalBytes = 0; + const pending = [source]; + while (pending.length) { + const folder = pending.pop()!; + for (const entry of await readdir(folder, { withFileTypes: true })) { + const path = join(folder, entry.name); + if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue; + if (entry.isDirectory()) { + folders.push(relative(source, path)); + pending.push(path); + } else if (entry.isFile()) { + const bytes = (await lstat(path)).size; + files.push({ relativePath: relative(source, path), bytes }); + totalBytes += bytes; + } + } + } + return { files, folders, totalBytes }; +} + +/** How many files are copied at the same time; enough to keep a disk busy without thrashing it. */ +const PARALLEL_COPIES = 4; + +/** + * Copies the planned files in chunks, so progress moves with every chunk and an abort of + * `signal` stops even a multi-gigabyte data pack at once (then the abort reason is thrown). + * Never overwrites a file in `target`. + */ +export async function copyPlannedFiles( + source: string, + target: string, + plan: CopyPlan, + signal: AbortSignal, + onProgress: (progress: CopyProgress) => void, +): Promise { + await mkdir(target, { recursive: true }); + for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true }); + let next = 0; + let doneBytes = 0; + let doneFiles = 0; + const countBytes = (): Transform => new Transform({ + transform(chunk: Buffer, _encoding, callback) { + doneBytes += chunk.length; + onProgress({ doneBytes, doneFiles }); + callback(null, chunk); + }, + }); + // One failing copy stops the others, and this returns only once all of them have stopped, so a + // caller cleaning up after an error never races a copy still writing. + const stop = new AbortController(); + const stopSignal = AbortSignal.any([signal, stop.signal]); + const copyNext = async (): Promise => { + try { + while (next < plan.files.length) { + stopSignal.throwIfAborted(); + const file = plan.files[next++]!; + await pipeline( + createReadStream(join(source, file.relativePath)), + countBytes(), + // 'wx': fail instead of overwriting a file that is already there. + createWriteStream(join(target, file.relativePath), { flags: 'wx' }), + { signal: stopSignal }, + ); + doneFiles += 1; + onProgress({ doneBytes, doneFiles }); + } + } catch (error) { + stop.abort(error); + throw error; + } + }; + const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext)); + const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected'); + if (failed) throw failed.reason; +} + +/** + * Removes what an interrupted copy left in `target`. Only for a target that was new or empty + * when the copy started, so everything in it came from the copy. + */ +export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise { + if (!targetExisted) { + await rm(target, { recursive: true, force: true }); + return; + } + for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true }); +} diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts new file mode 100644 index 0000000..4f51d09 --- /dev/null +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -0,0 +1,160 @@ +import { access, mkdir } from 'node:fs/promises'; +import { AppError } from '@shared/errors.ts'; +import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; +import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; +import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts'; +import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts'; +import { writeInstallRecord } from './install-record.ts'; +import { checkPatches } from './patch-check.ts'; +import { backUpStockFiles, stockBackupPath } from './stock-backup.ts'; + +/** + * Install the offline version: check the patches against the player's game, + * copy it (method "copy"), keep its stock files in the copy's backup folder and record the + * installation. The patched files are written by the build at every launch, with that launch's + * port; installing writes no patched file. + * + * The patches are checked first, on the stock files the copy would get, so a game whose + * essential patches do not fit is refused before 90 GB are copied. + */ + +/** Room kept free on the target drive beyond the copy itself, for the game's caches and logs. */ +const SPARE_BYTES = 1024 ** 3; +/** At most this often a progress event goes to the window. */ +const PROGRESS_INTERVAL_MS = 250; + +let running: AbortController | null = null; + +export async function installGame(request: InstallRequest, onProgress: (progress: InstallProgress) => void): Promise { + if (running) throw new AppError('install_busy'); + const controller = new AbortController(); + running = controller; + try { + return await install(request, controller.signal, throttled(onProgress)); + } finally { + running = null; + } +} + +/** Stops a running copy at the next file; returns whether an installation was running. */ +export function cancelInstall(): boolean { + if (!running) return false; + running.abort(); + return true; +} + +/** + * The stock files a check of `gameFolder` starts from: its backup folder when it already has one + * (a folder installed before, whose own files may be patched), otherwise its own files. + */ +export async function stockFolderOf(gameFolder: string): Promise { + const backup = stockBackupPath(gameFolder); + try { + await access(backup); + return backup; + } catch { + return gameFolder; + } +} + +/** Which patches fit the game in `gameFolder`, for the window to show before installing. */ +export async function checkGameFolder(gameFolder: string, dataPath: string): Promise { + await requireGameFolder(gameFolder); + return checkPatches(await stockFolderOf(gameFolder), dataPath); +} + +async function install(request: InstallRequest, signal: AbortSignal, report: (progress: InstallProgress) => void): Promise { + const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath; + const game = await requireGameFolder(gameFolder); + const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath; + + const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null; + if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem }); + const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary; + if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed'); + + report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); + await mkdir(request.dataPath, { recursive: true }); + const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath); + const essential = check.unavailable.filter((patch) => patch.essential); + if (essential.length) throw new AppError('essential_patches_unavailable', { patches: essential.map((patch) => patch.patchId).join(', ') }); + if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted'); + signal.throwIfAborted(); + + if (request.method === 'copy') await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report); + + report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); + const stockBackup = await backUpStockFiles(copyPath); + + report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); + const record: InstallRecord = { + method: request.method, + copyPath, + dataPath: request.dataPath, + stockBackupPath: stockBackup, + gameVersion: game.version, + unavailablePatches: check.unavailable, + installedAt: new Date().toISOString(), + }; + await writeInstallRecord(record); + return record; +} + +async function copyGame( + source: string, + target: string, + freeBytes: number | null, + signal: AbortSignal, + report: (progress: InstallProgress) => void, +): Promise { + report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); + const plan = await planCopy(source); + if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) { + throw new AppError('not_enough_space', { neededGb: gigabytes(plan.totalBytes + SPARE_BYTES), freeGb: gigabytes(freeBytes) }); + } + const targetExisted = await exists(target); + const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length }; + report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals }); + try { + await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals })); + } catch (error) { + await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup)); + if (signal.aborted) throw new AppError('install_cancelled'); + console.error('[install] copying failed:', error); + throw new AppError('copy_failed'); + } +} + +async function requireGameFolder(path: string) { + const game = await inspectGameFolder(path); + if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path }); + return game; +} + +/** Passes on the first and last report of each phase and at most one per interval in between. */ +function throttled(onProgress: (progress: InstallProgress) => void): (progress: InstallProgress) => void { + let lastSent = 0; + let lastPhase = ''; + return (progress) => { + const now = Date.now(); + const finished = progress.totalFiles > 0 && progress.doneFiles === progress.totalFiles; + if (progress.phase !== lastPhase || finished || now - lastSent >= PROGRESS_INTERVAL_MS) { + lastSent = now; + lastPhase = progress.phase; + onProgress(progress); + } + }; +} + +function gigabytes(bytes: number): string { + return (bytes / 1024 ** 3).toFixed(1); +} + +async function exists(path: string): Promise { + try { + await access(path); + return true; + } catch { + return false; + } +} diff --git a/apps/launcher/src/main/services/install/install-record.ts b/apps/launcher/src/main/services/install/install-record.ts new file mode 100644 index 0000000..18507bd --- /dev/null +++ b/apps/launcher/src/main/services/install/install-record.ts @@ -0,0 +1,36 @@ +import { join } from 'node:path'; +import { app } from 'electron'; +import { InstallRecordSchema, type InstallRecord } from '@shared/schemas/install.ts'; +import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; + +/** The installed game copy, `/install.json`; null before the first installation. */ + +function recordPath(): string { + return join(app.getPath('userData'), 'install.json'); +} + +export async function readInstallRecord(): Promise { + let raw: unknown; + try { + raw = await readJsonOr(recordPath(), null); + } catch (error) { + console.warn('[install] install.json is unreadable:', error); + return null; + } + if (raw === null) return null; + const parsed = InstallRecordSchema.safeParse(raw); + if (!parsed.success) { + console.warn('[install] install.json did not validate:', parsed.error.issues); + return null; + } + return parsed.data; +} + +export async function writeInstallRecord(record: InstallRecord): Promise { + await writeJsonAtomic(recordPath(), InstallRecordSchema.parse(record)); +} + +/** The data folder offered when the player does not choose one. */ +export function defaultDataPath(): string { + return join(app.getPath('userData'), 'data'); +} diff --git a/apps/launcher/src/main/services/install/patch-check.ts b/apps/launcher/src/main/services/install/patch-check.ts new file mode 100644 index 0000000..f0918cd --- /dev/null +++ b/apps/launcher/src/main/services/install/patch-check.ts @@ -0,0 +1,41 @@ +import { join } from 'node:path'; +import { utilityProcess } from 'electron'; +import { AppError } from '@shared/errors.ts'; +import type { PatchCheck } from '@shared/schemas/install.ts'; +import type { PatchCheckReply, PatchCheckRequest } from '../../workers/patch-check-protocol.ts'; +import { resourcePaths } from '../resources/resource-paths.ts'; + +/** + * Which patches fit the stock files in `stockFolder`, worked out in a utility process + * (workers/patch-check-worker.ts). Nothing is written. + */ +export function checkPatches(stockFolder: string, dataFolder: string): Promise { + const resources = resourcePaths(); + const request: PatchCheckRequest = { + stockFolder, + dataFolder, + exePatches: resources.exePatches, + guiPatches: resources.guiPatches, + networkHookLibrary: resources.networkHookLibrary, + }; + return new Promise((resolve, reject) => { + const worker = utilityProcess.fork(join(import.meta.dirname, 'patch-check-worker.js'), [], { serviceName: 'WTOffline patch check' }); + let answered = false; + worker.once('message', (reply: PatchCheckReply) => { + answered = true; + worker.kill(); + if (reply.ok) { + resolve(reply.check); + } else { + console.error('[install] the patch check failed:', reply.error); + reject(new AppError('patch_check_failed')); + } + }); + worker.once('exit', (code) => { + if (answered) return; + console.error('[install] the patch check process ended without an answer, exit code', code); + reject(new AppError('patch_check_failed')); + }); + worker.postMessage(request); + }); +} diff --git a/apps/launcher/src/main/services/install/stock-backup.ts b/apps/launcher/src/main/services/install/stock-backup.ts new file mode 100644 index 0000000..d0aaf5d --- /dev/null +++ b/apps/launcher/src/main/services/install/stock-backup.ts @@ -0,0 +1,40 @@ +import { constants } from 'node:fs'; +import { access, copyFile, mkdir } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { GAME_FILES } from '@wto/patcher'; + +/** + * The stock files every build starts from, kept inside the game copy: the three data packs and + * the executable the build replaces. After installation the launcher never reads the player's + * online installation again, so a Steam update of it cannot change the offline copy unnoticed; + * for an in-place installation these are also the files to put back to undo it. + */ +export const STOCK_BACKUP_FOLDER = join('wtoffline', 'stock'); + +export function stockBackupPath(copyFolder: string): string { + return join(copyFolder, STOCK_BACKUP_FOLDER); +} + +/** + * Copies each stock file from the copy into the backup folder, unless the backup already has it: + * a backed-up file is never replaced, because the copy's own file may be a patched one by then. + */ +export async function backUpStockFiles(copyFolder: string): Promise { + const backup = stockBackupPath(copyFolder); + for (const file of Object.values(GAME_FILES)) { + const kept = join(backup, file); + if (await exists(kept)) continue; + await mkdir(dirname(kept), { recursive: true }); + await copyFile(join(copyFolder, file), kept, constants.COPYFILE_EXCL); + } + return backup; +} + +async function exists(path: string): Promise { + try { + await access(path); + return true; + } catch { + return false; + } +} diff --git a/apps/launcher/src/main/workers/patch-check-protocol.ts b/apps/launcher/src/main/workers/patch-check-protocol.ts new file mode 100644 index 0000000..8a5f6d9 --- /dev/null +++ b/apps/launcher/src/main/workers/patch-check-protocol.ts @@ -0,0 +1,16 @@ +import type { PatchCheck } from '@shared/schemas/install.ts'; + +/** What the main process sends the patch check worker: everything the build needs. */ +export interface PatchCheckRequest { + /** Folder holding the four stock files (the copy's backup folder). */ + readonly stockFolder: string; + /** The local server's data folder: its store tuning names the packs that get bundle GUIDs. */ + readonly dataFolder: string; + readonly exePatches: string; + readonly guiPatches: string; + readonly networkHookLibrary: string; +} + +export type PatchCheckReply = + | { readonly ok: true; readonly check: PatchCheck } + | { readonly ok: false; readonly error: string }; diff --git a/apps/launcher/src/main/workers/patch-check-worker.ts b/apps/launcher/src/main/workers/patch-check-worker.ts new file mode 100644 index 0000000..55c63b9 --- /dev/null +++ b/apps/launcher/src/main/workers/patch-check-worker.ts @@ -0,0 +1,47 @@ +/** + * Utility process: build the game copy in memory and report which patches fit, writing nothing. + * The build parses a 130 MB executable and three data packs, which would stall the window if it + * ran in the main process. One request per process; the main process ends it after the reply. + */ +import { readFileSync } from 'node:fs'; +import type { MessageEvent } from 'electron'; +import { buildGameCopy, ESSENTIAL_FEATURES, readStockGameFiles } from '@wto/patcher'; +import { multiVehiclePackIds } from '@wto/server'; +import type { PatchCheck } from '@shared/schemas/install.ts'; +import type { PatchCheckReply, PatchCheckRequest } from './patch-check-protocol.ts'; + +/** Any valid port: the port does not decide which patches fit. */ +const CHECK_PORT = 47000; + +process.parentPort.once('message', (event: MessageEvent) => { + let reply: PatchCheckReply; + try { + reply = { ok: true, check: checkPatches(event.data as PatchCheckRequest) }; + } catch (error) { + reply = { ok: false, error: error instanceof Error ? (error.stack ?? error.message) : String(error) }; + } + process.parentPort.postMessage(reply); +}); + +function checkPatches(request: PatchCheckRequest): PatchCheck { + const build = buildGameCopy({ + stock: readStockGameFiles(request.stockFolder), + port: CHECK_PORT, + exePatches: request.exePatches, + guiPatches: request.guiPatches, + networkHookLibrary: readFileSync(request.networkHookLibrary), + multiVehiclePackIds: multiVehiclePackIds(request.dataFolder, () => undefined), + placeholderDecals: true, + }); + const failures = [...build.exePatches.failures, ...build.guiPatches.failures]; + return { + exePatchesReady: build.exePatches.applied.length, + guiPatchesReady: build.guiPatches.applied.length, + unavailable: failures.map((failure) => ({ + patchId: failure.patchId, + features: [...failure.features], + reason: failure.reason, + essential: failure.features.some((feature) => ESSENTIAL_FEATURES.has(feature)), + })), + }; +} diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 4ac93b7..ab7d35b 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -16,6 +16,16 @@ "internal_error": "Something went wrong inside the launcher.", "settings_write_failed": "Could not save the settings.", "folder_unreadable": "Cannot read the folder: {{path}}", + "not_a_game_folder": "This is not a War Thunder game folder: {{path}}", + "target_not_usable": "This folder cannot be used for the installation.", + "steam_library_not_confirmed": "The folder is in a Steam library. Confirm the warning first.", + "not_enough_space": "Not enough disk space: {{neededGb}} GB needed, {{freeGb}} GB free.", + "essential_patches_unavailable": "Your game version lacks changes the offline version cannot run without: {{patches}}", + "missing_features_not_accepted": "Some changes do not fit. Confirm whether to go on without those features first.", + "patch_check_failed": "Checking the game files failed.", + "copy_failed": "Copying the game failed. What was copied has been removed.", + "install_cancelled": "Installation cancelled. What was copied has been removed.", + "install_busy": "An installation is already running.", "unknown": "Something went wrong." } } 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 f4da6c4..4f72f53 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -16,6 +16,16 @@ "internal_error": "启动器内部出错了。", "settings_write_failed": "设置保存失败。", "folder_unreadable": "无法读取文件夹:{{path}}", + "not_a_game_folder": "这不是战争雷霆的游戏文件夹:{{path}}", + "target_not_usable": "这个文件夹不能用来安装。", + "steam_library_not_confirmed": "安装位置在 Steam 游戏库里,需要先确认风险提示。", + "not_enough_space": "磁盘空间不够:需要 {{neededGb}} GB,只剩 {{freeGb}} GB。", + "essential_patches_unavailable": "你的游戏版本缺少离线版必需的改动,无法安装:{{patches}}", + "missing_features_not_accepted": "有些改动用不上,需要先确认是否在缺少这些功能的情况下继续。", + "patch_check_failed": "检查游戏文件时出错了。", + "copy_failed": "复制游戏失败,已复制的部分已删除。", + "install_cancelled": "安装已取消,已复制的部分已删除。", + "install_busy": "已经有一个安装在进行。", "unknown": "出错了。" } } diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index b5e6704..bce029b 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -16,6 +16,26 @@ export const APP_ERROR_CODES = [ 'settings_write_failed', /** A folder the player chose does not exist or cannot be read (params: path). */ 'folder_unreadable', + /** The chosen folder lacks the files of a War Thunder installation (params: path). */ + 'not_a_game_folder', + /** The folder chosen for the copy cannot take it (params: problem, one of TARGET_PROBLEMS). */ + 'target_not_usable', + /** The game copy would go into a Steam library and the player has not confirmed the warning. */ + 'steam_library_not_confirmed', + /** The target drive has too little room (params: neededGb, freeGb). */ + 'not_enough_space', + /** Patches the copy cannot run safely without do not fit this game build (params: patches). */ + 'essential_patches_unavailable', + /** Some patches do not fit and the player has not chosen to go on without their features. */ + 'missing_features_not_accepted', + /** Working out which patches fit failed; the details are in the log. */ + 'patch_check_failed', + /** Copying the game failed; what was copied has been removed. */ + 'copy_failed', + /** The player stopped the installation; what was copied has been removed. */ + 'install_cancelled', + /** An installation is already running. */ + 'install_busy', ] as const; export type AppErrorCode = (typeof APP_ERROR_CODES)[number]; diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index a55d3fc..6a5fd2d 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -1,5 +1,13 @@ import { z } from 'zod'; -import { FolderSizeSchema, GameFolderInspectionSchema, TargetFolderInspectionSchema } from '../schemas/install.ts'; +import { + FolderSizeSchema, + GameFolderInspectionSchema, + InstallProgressSchema, + InstallRecordSchema, + InstallRequestSchema, + PatchCheckSchema, + TargetFolderInspectionSchema, +} from '../schemas/install.ts'; import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts'; /** @@ -38,6 +46,25 @@ export const ipcContract = { input: z.object({ path: z.string().min(1) }), output: FolderSizeSchema, }, + 'install:checkPatches': { + /** The game folder to install from, and the data folder whose store tuning the build uses. */ + input: z.object({ gamePath: z.string().min(1), dataPath: z.string().min(1) }), + output: PatchCheckSchema, + }, + 'install:start': { + /** Runs until the installation is done; progress arrives as event:install-progress. */ + input: InstallRequestSchema, + output: InstallRecordSchema, + }, + 'install:cancel': { + input: z.void(), + /** Whether an installation was running. */ + output: z.object({ cancelled: z.boolean() }), + }, + 'install:getRecord': { + input: z.void(), + output: z.object({ record: InstallRecordSchema.nullable(), defaultDataPath: z.string() }), + }, 'settings:get': { input: z.void(), output: SettingsSchema, @@ -50,6 +77,7 @@ export const ipcContract = { export const ipcEvents = { 'event:settings-changed': SettingsSchema, + 'event:install-progress': InstallProgressSchema, } as const; export type IpcChannel = keyof typeof ipcContract; diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts index ec4701c..67c693d 100644 --- a/apps/launcher/src/shared/schemas/install.ts +++ b/apps/launcher/src/shared/schemas/install.ts @@ -40,3 +40,79 @@ export const FolderSizeSchema = z.object({ files: z.number(), }); export type FolderSize = z.output; + +/** A patch that does not fit the game build, with the feature inventory rows it covers. */ +export const UnavailablePatchSchema = z.object({ + patchId: z.string(), + features: z.array(z.string()), + reason: z.string(), + /** Without it the copy must not be installed (it would not start, or not stay apart from the online game). */ + essential: z.boolean(), +}); +export type UnavailablePatch = z.output; + +/** Which patches fit the game build; nothing is written by the check. */ +export const PatchCheckSchema = z.object({ + exePatchesReady: z.number(), + guiPatchesReady: z.number(), + unavailable: z.array(UnavailablePatchSchema), +}); +export type PatchCheck = z.output; + +/** + * copy: the stock installation is copied to a new folder and only read. + * in-place: the player's own prepared folder is used as the copy; its stock files are kept in + * the backup folder inside it. + */ +export const INSTALL_METHODS = ['copy', 'in-place'] as const; +export type InstallMethod = (typeof INSTALL_METHODS)[number]; + +const InstallChoicesSchema = z.object({ + /** Where the local server keeps saves, caches and logs. */ + dataPath: z.string().min(1), + /** The player confirmed installing into a Steam library after the warning. */ + steamLibraryConfirmed: z.boolean(), + /** The player chose to go on without the features of the unavailable patches. */ + missingFeaturesAccepted: z.boolean(), +}); + +export const InstallRequestSchema = z.discriminatedUnion('method', [ + InstallChoicesSchema.extend({ + method: z.literal('copy'), + /** The War Thunder installation to copy; only read. */ + sourcePath: z.string().min(1), + /** A new or empty folder for the game copy. */ + copyPath: z.string().min(1), + }), + InstallChoicesSchema.extend({ + method: z.literal('in-place'), + /** The player's prepared game folder, used as the game copy. */ + gamePath: z.string().min(1), + }), +]); +export type InstallRequest = z.output; + +export const INSTALL_PHASES = ['checking', 'measuring', 'copying', 'backing-up', 'recording'] as const; + +export const InstallProgressSchema = z.object({ + phase: z.enum(INSTALL_PHASES), + doneBytes: z.number(), + totalBytes: z.number(), + doneFiles: z.number(), + totalFiles: z.number(), +}); +export type InstallProgress = z.output; + +/** What the launcher knows about the installed game copy. */ +export const InstallRecordSchema = z.object({ + method: z.enum(INSTALL_METHODS), + copyPath: z.string(), + dataPath: z.string(), + /** The stock files every build starts from, inside the copy. */ + stockBackupPath: z.string(), + gameVersion: z.string().nullable(), + /** Patches that did not fit when the copy was installed; their features are missing. */ + unavailablePatches: z.array(UnavailablePatchSchema), + installedAt: z.string(), +}); +export type InstallRecord = z.output;