feat(launcher): inspect game installation and destination folders
The install wizard needs to tell whether the chosen folder is a War Thunder installation, which version it is, whether it is a Steam library, and whether the folder for the copy can take it. The patcher reads the game version from win64/aces.exe (the VS_FIXEDFILEINFO block of its version resource) and works out the versions every exe and GUI patch was verified on, from their verified_on lists, so the version check follows the patch definitions instead of a constant. The launcher gets four IPC calls, each validated against the contract: - dialog:pickFolder, a folder picker titled by the window; - install:inspectGameFolder: missing game files, version, verified versions, Steam library; - install:inspectTargetFolder: new or empty, not overlapping the stock installation, Steam library, free space on its drive, and whether it is on the stock installation's drive (the space saving copy needs that); - install:measureFolder: bytes and files of the stock installation, regular files only, links not followed. A folder that does not exist or cannot be read is the folder_unreadable error code, translated in both languages. In development the patch folders and the hook library come from this repository; the packaged layout comes with the installer build. Checked with both typechecks, the launcher build, and the calls made from a running launcher window: the stock folder (2.61.0.37, verified), a non-game folder, a missing path, a Steam library path, four target folders (new, inside the stock folder, not empty, other drive) and the size of the offline copy (96.9 GB in 10,972 files).
This commit is contained in:
1 parent
38e9549e15
commit
ab0d3b1f30
13 files changed
+310
-1
No files matched your search
@@ -1,5 +1,9 @@
|
||||
import { app } from 'electron';
|
||||
import { app, BrowserWindow, dialog } from 'electron';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
|
||||
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 { broadcast, handle } from './register.ts';
|
||||
|
||||
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
|
||||
@@ -11,6 +15,25 @@ export function registerIpcHandlers(): void {
|
||||
userDataPath: app.getPath('userData'),
|
||||
}));
|
||||
|
||||
handle('dialog:pickFolder', async ({ title }, sender) => {
|
||||
const window = BrowserWindow.fromWebContents(sender);
|
||||
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) };
|
||||
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
|
||||
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
|
||||
});
|
||||
|
||||
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
|
||||
handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath));
|
||||
handle('install:measureFolder', async ({ path }) => {
|
||||
await requireFolder(path);
|
||||
try {
|
||||
return await measureFolder(path);
|
||||
} catch (error) {
|
||||
console.warn('[install] measuring the folder failed:', error);
|
||||
throw new AppError('folder_unreadable', { path });
|
||||
}
|
||||
});
|
||||
|
||||
handle('settings:get', () => getSettings());
|
||||
handle('settings:update', async (patch) => {
|
||||
const settings = await updateSettings(patch);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { lstat, readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { FolderSize } from '@shared/schemas/install.ts';
|
||||
|
||||
/**
|
||||
* The size of a folder tree, counted the way the copy will copy it: regular files only. Links
|
||||
* and junctions are not followed. Asynchronous, so the window stays responsive on a large
|
||||
* installation.
|
||||
*/
|
||||
export async function measureFolder(root: string): Promise<FolderSize> {
|
||||
let bytes = 0;
|
||||
let files = 0;
|
||||
const pending = [root];
|
||||
while (pending.length) {
|
||||
const folder = pending.pop()!;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const path = join(folder, entry.name);
|
||||
if (entry.isDirectory()) pending.push(path);
|
||||
else if (entry.isFile()) {
|
||||
bytes += (await lstat(path)).size;
|
||||
files += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { bytes, files };
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { access, readFile, stat } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { executableVersion, GAME_FILES, isInSteamLibrary, verifiedGameVersions } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { GameFolderInspection } from '@shared/schemas/install.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
|
||||
/**
|
||||
* Look at a folder the player chose as their War Thunder installation: is it one, which version,
|
||||
* and is it a Steam library. Only reads.
|
||||
*/
|
||||
export async function inspectGameFolder(path: string): Promise<GameFolderInspection> {
|
||||
await requireFolder(path);
|
||||
const required = Object.values(GAME_FILES);
|
||||
const missingFiles: string[] = [];
|
||||
for (const file of required) {
|
||||
if (!(await exists(join(path, file)))) missingFiles.push(file);
|
||||
}
|
||||
const resources = resourcePaths();
|
||||
return {
|
||||
path,
|
||||
missingFiles,
|
||||
version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(path, GAME_FILES.executable)),
|
||||
verifiedVersions: verifiedGameVersions(resources.exePatches, resources.guiPatches),
|
||||
inSteamLibrary: isInSteamLibrary(path),
|
||||
};
|
||||
}
|
||||
|
||||
async function readVersion(executablePath: string): Promise<string | null> {
|
||||
try {
|
||||
return executableVersion(await readFile(executablePath));
|
||||
} catch (error) {
|
||||
// Not a PE file, or unreadable: the folder is then not a usable installation, which the
|
||||
// missing version already says.
|
||||
console.warn('[game-folder] reading the executable version failed:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Throws folder_unreadable unless `path` is a folder that can be read. */
|
||||
export async function requireFolder(path: string): Promise<void> {
|
||||
let isFolder = false;
|
||||
try {
|
||||
isFolder = (await stat(path)).isDirectory();
|
||||
} catch (error) {
|
||||
console.warn('[game-folder] cannot read', path, error);
|
||||
}
|
||||
if (!isFolder) throw new AppError('folder_unreadable', { path });
|
||||
}
|
||||
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { readdir, realpath, stat, statfs } from 'node:fs/promises';
|
||||
import { dirname, parse, relative, resolve, isAbsolute } from 'node:path';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import type { TargetFolderInspection } from '@shared/schemas/install.ts';
|
||||
|
||||
/**
|
||||
* Look at the folder the player chose for the game copy (install by copying): it must be new or
|
||||
* empty, must not overlap the stock installation, and the drive must have room. Only reads.
|
||||
*/
|
||||
export async function inspectTargetFolder(path: string, stockPath: string): Promise<TargetFolderInspection> {
|
||||
const target = await canonical(path);
|
||||
const stock = await canonical(stockPath);
|
||||
return {
|
||||
path,
|
||||
problem: await targetProblem(target, stock),
|
||||
inSteamLibrary: isInSteamLibrary(target),
|
||||
freeBytes: await freeBytes(target),
|
||||
sameDriveAsStock: parse(target).root.toLowerCase() === parse(stock).root.toLowerCase(),
|
||||
};
|
||||
}
|
||||
|
||||
async function targetProblem(target: string, stock: string): Promise<TargetFolderInspection['problem']> {
|
||||
if (contains(stock, target) || contains(target, stock)) return 'overlaps_stock';
|
||||
let entries: string[];
|
||||
try {
|
||||
const info = await stat(target);
|
||||
if (!info.isDirectory()) return 'not_a_folder';
|
||||
entries = await readdir(target);
|
||||
} catch {
|
||||
return null; // does not exist yet: the copy creates it
|
||||
}
|
||||
return entries.length ? 'not_empty' : null;
|
||||
}
|
||||
|
||||
/** Whether `inner` is `outer` or lies inside it. */
|
||||
function contains(outer: string, inner: string): boolean {
|
||||
const path = relative(outer.toLowerCase(), inner.toLowerCase());
|
||||
return path === '' || (!path.startsWith('..') && !isAbsolute(path));
|
||||
}
|
||||
|
||||
/** Free bytes on the drive of the nearest existing folder at or above `path`. */
|
||||
async function freeBytes(path: string): Promise<number | null> {
|
||||
for (let folder = path; ; folder = dirname(folder)) {
|
||||
try {
|
||||
const info = await statfs(folder);
|
||||
return info.bavail * info.bsize;
|
||||
} catch {
|
||||
if (dirname(folder) === folder) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The real path of the nearest existing part, with the rest appended as given. */
|
||||
async function canonical(path: string): Promise<string> {
|
||||
const absolute = resolve(path);
|
||||
try {
|
||||
return await realpath(absolute);
|
||||
} catch {
|
||||
const parent = dirname(absolute);
|
||||
if (parent === absolute) return absolute;
|
||||
return resolve(await canonical(parent), relative(parent, absolute));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { join, resolve } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
|
||||
/**
|
||||
* Where the launcher finds what it ships besides its own code: the patch definitions and the
|
||||
* network hook library. In development they are this repository's folders.
|
||||
*/
|
||||
export interface ResourcePaths {
|
||||
readonly exePatches: string;
|
||||
readonly guiPatches: string;
|
||||
/** wto_ws.dll, built by native/wto-net/build.ps1. */
|
||||
readonly networkHookLibrary: string;
|
||||
}
|
||||
|
||||
export function resourcePaths(): ResourcePaths {
|
||||
if (app.isPackaged) {
|
||||
// The packaged layout is decided with the installer build; nothing ships it yet.
|
||||
throw new Error('resource paths of a packaged launcher are not defined yet');
|
||||
}
|
||||
// The app path is apps/launcher; the repository is two levels up.
|
||||
const repository = resolve(app.getAppPath(), '..', '..');
|
||||
return {
|
||||
exePatches: join(repository, 'patches', 'exe'),
|
||||
guiPatches: join(repository, 'patches', 'gui'),
|
||||
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
"errors": {
|
||||
"internal_error": "Something went wrong inside the launcher.",
|
||||
"settings_write_failed": "Could not save the settings.",
|
||||
"folder_unreadable": "Cannot read the folder: {{path}}",
|
||||
"unknown": "Something went wrong."
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
"errors": {
|
||||
"internal_error": "启动器内部出错了。",
|
||||
"settings_write_failed": "设置保存失败。",
|
||||
"folder_unreadable": "无法读取文件夹:{{path}}",
|
||||
"unknown": "出错了。"
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ export const APP_ERROR_CODES = [
|
||||
'internal_error',
|
||||
/** The launcher's own settings file could not be written. */
|
||||
'settings_write_failed',
|
||||
/** A folder the player chose does not exist or cannot be read (params: path). */
|
||||
'folder_unreadable',
|
||||
] as const;
|
||||
|
||||
export type AppErrorCode = (typeof APP_ERROR_CODES)[number];
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
export const IPC_CHANNEL_PREFIXES = [
|
||||
/** The launcher itself: version, folders. */
|
||||
'app:',
|
||||
/** System dialogs (folder pickers). */
|
||||
'dialog:',
|
||||
/** Installing the offline version: looking at the chosen folders, copying, patching. */
|
||||
'install:',
|
||||
/** The launcher's own settings. */
|
||||
'settings:',
|
||||
] as const;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import { FolderSizeSchema, GameFolderInspectionSchema, TargetFolderInspectionSchema } from '../schemas/install.ts';
|
||||
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
|
||||
|
||||
/**
|
||||
@@ -19,6 +20,24 @@ export const ipcContract = {
|
||||
userDataPath: z.string(),
|
||||
}),
|
||||
},
|
||||
'dialog:pickFolder': {
|
||||
/** The dialog title, already translated by the window. */
|
||||
input: z.object({ title: z.string().optional() }),
|
||||
/** The chosen folder, or null when the player cancelled. */
|
||||
output: z.object({ path: z.string().nullable() }),
|
||||
},
|
||||
'install:inspectGameFolder': {
|
||||
input: z.object({ path: z.string().min(1) }),
|
||||
output: GameFolderInspectionSchema,
|
||||
},
|
||||
'install:inspectTargetFolder': {
|
||||
input: z.object({ path: z.string().min(1), stockPath: z.string().min(1) }),
|
||||
output: TargetFolderInspectionSchema,
|
||||
},
|
||||
'install:measureFolder': {
|
||||
input: z.object({ path: z.string().min(1) }),
|
||||
output: FolderSizeSchema,
|
||||
},
|
||||
'settings:get': {
|
||||
input: z.void(),
|
||||
output: SettingsSchema,
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/** What the launcher found in a folder the player chose as their War Thunder installation. */
|
||||
export const GameFolderInspectionSchema = z.object({
|
||||
path: z.string(),
|
||||
/** Files a game folder must have that this one lacks; empty for a game folder. */
|
||||
missingFiles: z.array(z.string()),
|
||||
/** The file version of win64/aces.exe, or null when it has none or is missing. */
|
||||
version: z.string().nullable(),
|
||||
/** The versions every patch was verified on; a different version is pointed out, not refused. */
|
||||
verifiedVersions: z.array(z.string()),
|
||||
/** The folder lies in a Steam library: installing into it needs the player's confirmation. */
|
||||
inSteamLibrary: z.boolean(),
|
||||
});
|
||||
export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>;
|
||||
|
||||
/** Why a folder cannot hold the game copy. */
|
||||
export const TARGET_PROBLEMS = [
|
||||
/** The folder holds files already (a copy needs an empty or a new folder). */
|
||||
'not_empty',
|
||||
/** The folder is the stock installation, lies inside it, or contains it. */
|
||||
'overlaps_stock',
|
||||
/** The path names a file, not a folder. */
|
||||
'not_a_folder',
|
||||
] as const;
|
||||
|
||||
export const TargetFolderInspectionSchema = z.object({
|
||||
path: z.string(),
|
||||
problem: z.enum(TARGET_PROBLEMS).nullable(),
|
||||
inSteamLibrary: z.boolean(),
|
||||
/** Bytes free on the drive the folder is on; null when the drive cannot be read. */
|
||||
freeBytes: z.number().nullable(),
|
||||
/** Whether the folder is on the same drive as the stock installation. */
|
||||
sameDriveAsStock: z.boolean(),
|
||||
});
|
||||
export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchema>;
|
||||
|
||||
export const FolderSizeSchema = z.object({
|
||||
bytes: z.number(),
|
||||
files: z.number(),
|
||||
});
|
||||
export type FolderSize = z.output<typeof FolderSizeSchema>;
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* The game version of a stock folder, and the versions the patches were verified on
|
||||
* (implementation notes: a version that differs is only pointed out, never refused).
|
||||
*
|
||||
* The version is the file version of win64/aces.exe: the VS_FIXEDFILEINFO block in its version
|
||||
* resource, which Windows shows as "File version" (2.61.0.37 for the target build).
|
||||
*/
|
||||
import { loadPatches, PeImage } from '@wto/exepatch';
|
||||
import { loadGuiPatches } from './gui-patch-definition.ts';
|
||||
|
||||
/** VS_FIXEDFILEINFO.dwSignature, little-endian. */
|
||||
const FIXED_FILE_INFO_SIGNATURE = 0xfeef04bd;
|
||||
const RESOURCE_SECTION = '.rsrc';
|
||||
|
||||
/** "major.minor.build.revision" from the executable's version resource, or null when it has none. */
|
||||
export function executableVersion(executable: Uint8Array): string | null {
|
||||
const image = new PeImage(executable);
|
||||
if (!image.sections.some((section) => section.name === RESOURCE_SECTION)) return null;
|
||||
const resources = image.sectionBytes(RESOURCE_SECTION);
|
||||
const view = new DataView(resources.buffer, resources.byteOffset, resources.byteLength);
|
||||
// The fixed file info is 4-byte aligned inside the VS_VERSIONINFO resource; its signature
|
||||
// does not occur elsewhere in practice, and the struct version after it must be 1.0.
|
||||
for (let offset = 0; offset + 16 <= resources.byteLength; offset += 4) {
|
||||
if (view.getUint32(offset, true) !== FIXED_FILE_INFO_SIGNATURE) continue;
|
||||
if (view.getUint32(offset + 4, true) !== 0x00010000) continue;
|
||||
const high = view.getUint32(offset + 8, true);
|
||||
const low = view.getUint32(offset + 12, true);
|
||||
return [high >>> 16, high & 0xffff, low >>> 16, low & 0xffff].join('.');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The game versions every exe patch and every GUI patch names in `verified_on`. */
|
||||
export function verifiedGameVersions(exePatches: string, guiPatches: string): string[] {
|
||||
const lists = [
|
||||
...loadPatches(exePatches).map((patch) => patch.verifiedOn),
|
||||
...loadGuiPatches(guiPatches).map((patch) => patch.verifiedOn),
|
||||
];
|
||||
const [first, ...rest] = lists;
|
||||
if (!first) return [];
|
||||
return first.filter((version) => rest.every((list) => list.includes(version))).sort();
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export { copyPlayerDecalCache, playerDecalCacheProblem } from './decals/player-d
|
||||
export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
|
||||
export { patchExecutable, type ExecutableResult } from './executable.ts';
|
||||
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
|
||||
export { executableVersion, verifiedGameVersions } from './game-version.ts';
|
||||
export { rebuildGuiPack, type GuiPackResult } from './gui-pack.ts';
|
||||
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch } from './gui-patch-definition.ts';
|
||||
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
|
||||
|
||||
Reference in new issue
Block a user