diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 59c2236..7555fb2 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -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); diff --git a/apps/launcher/src/main/services/game-folder/folder-size.ts b/apps/launcher/src/main/services/game-folder/folder-size.ts new file mode 100644 index 0000000..7c4a2e4 --- /dev/null +++ b/apps/launcher/src/main/services/game-folder/folder-size.ts @@ -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 { + 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 }; +} diff --git a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts new file mode 100644 index 0000000..65ef5fa --- /dev/null +++ b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts @@ -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 { + 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 { + 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 { + 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 { + try { + await access(path); + return true; + } catch { + return false; + } +} diff --git a/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts new file mode 100644 index 0000000..a065f43 --- /dev/null +++ b/apps/launcher/src/main/services/game-folder/inspect-target-folder.ts @@ -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 { + 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 { + 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 { + 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 { + 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)); + } +} diff --git a/apps/launcher/src/main/services/resources/resource-paths.ts b/apps/launcher/src/main/services/resources/resource-paths.ts new file mode 100644 index 0000000..ba6279c --- /dev/null +++ b/apps/launcher/src/main/services/resources/resource-paths.ts @@ -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'), + }; +} diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 19d0d6d..4ac93b7 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -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." } } 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 1061092..f4da6c4 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -15,6 +15,7 @@ "errors": { "internal_error": "启动器内部出错了。", "settings_write_failed": "设置保存失败。", + "folder_unreadable": "无法读取文件夹:{{path}}", "unknown": "出错了。" } } diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index e9689d9..b5e6704 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -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]; diff --git a/apps/launcher/src/shared/ipc/channels.ts b/apps/launcher/src/shared/ipc/channels.ts index 39fda57..f6705ed 100644 --- a/apps/launcher/src/shared/ipc/channels.ts +++ b/apps/launcher/src/shared/ipc/channels.ts @@ -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; diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 0c0dbeb..a55d3fc 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -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, diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts new file mode 100644 index 0000000..ec4701c --- /dev/null +++ b/apps/launcher/src/shared/schemas/install.ts @@ -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; + +/** 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; + +export const FolderSizeSchema = z.object({ + bytes: z.number(), + files: z.number(), +}); +export type FolderSize = z.output; diff --git a/packages/patcher/src/game-version.ts b/packages/patcher/src/game-version.ts new file mode 100644 index 0000000..09ae227 --- /dev/null +++ b/packages/patcher/src/game-version.ts @@ -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(); +} diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index 1adad48..af8039b 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -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';