feat(copies): add verified space-saving copies
Offer same-volume hard links for sampled 2.61.0.43 resources after checking their content and keeping mutable files independent. Support converting existing copies and detach registered links during version updates.
This commit is contained in:
1 parent
0881d62766
commit
2a97b0d46c
22 files changed
+3118
-111
No files matched your search
@@ -61,10 +61,10 @@ export function registerIpcHandlers(): void {
|
||||
handle('install:prepareCopy', () => createCopyDraft());
|
||||
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
|
||||
handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath));
|
||||
handle('install:measureFolder', async ({ path }) => {
|
||||
handle('install:measureFolder', async ({ path, version }) => {
|
||||
await requireFolder(path);
|
||||
try {
|
||||
return await measureFolder(path);
|
||||
return await measureFolder(path, version);
|
||||
} catch (error) {
|
||||
console.warn('[install] measuring the folder failed:', error);
|
||||
throw new AppError('folder_unreadable', { path });
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { copyFile, mkdir, readdir, rm } from 'node:fs/promises';
|
||||
import type { BigIntStats } from 'node:fs';
|
||||
import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
@@ -8,7 +7,9 @@ import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
|
||||
import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts';
|
||||
import { installationInProgress } from '../install/install-game.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { checkPatches } from '../install/patch-check.ts';
|
||||
@@ -30,7 +31,11 @@ export function cancelMaintenance(): void {
|
||||
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
|
||||
const record = await requireCopy(id);
|
||||
const source = await readSource(record);
|
||||
return { sourceVersion: source?.version ?? null, updateAvailable: isNewer(source, record.gameVersion) };
|
||||
return {
|
||||
sourceVersion: source?.version ?? null,
|
||||
updateAvailable: isNewer(source, record.gameVersion),
|
||||
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
|
||||
};
|
||||
}
|
||||
|
||||
export async function maintainCopy(
|
||||
@@ -38,7 +43,10 @@ export async function maintainCopy(
|
||||
publish: (progress: MaintenanceProgress) => void,
|
||||
): Promise<Copies> {
|
||||
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
|
||||
const job = { stop: new AbortController(), interruptible: request.operation === 'update' };
|
||||
const job = {
|
||||
stop: new AbortController(),
|
||||
interruptible: request.operation === 'update' || request.operation === 'compact',
|
||||
};
|
||||
current = job;
|
||||
const signal = job.stop.signal;
|
||||
const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => {
|
||||
@@ -60,6 +68,8 @@ export async function maintainCopy(
|
||||
return await repair(record, root, () => report('applying'));
|
||||
case 'update':
|
||||
return await updateFromSource(record, root, signal, report);
|
||||
case 'compact':
|
||||
return await compactCopy(record, root, signal, report);
|
||||
case 'delete':
|
||||
report('applying');
|
||||
return await remove(record, root, request.deleteData);
|
||||
@@ -154,13 +164,15 @@ async function updateFromSource(record: InstallRecord, root: string, signal: Abo
|
||||
const plan = await planCopy(game.path);
|
||||
const inventory = plan.files.map((entry) => entry.relativePath);
|
||||
const found = new Set(inventory.map(key));
|
||||
const remove = (record.sourceFiles ?? []).filter((name) => !found.has(key(name)));
|
||||
const linked = record.hardlinkedFiles ?? [];
|
||||
const linkedPaths = new Set(linked.map(key));
|
||||
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
|
||||
const changed: CopyPlan['files'][number][] = [];
|
||||
for (const file of plan.files) {
|
||||
signal.throwIfAborted();
|
||||
const target = await scopedInstallFile(dataPath, root, file.relativePath);
|
||||
const old = await fileInfo(target);
|
||||
if (!old?.isFile() || old.size !== file.bytes) {
|
||||
if (linkedPaths.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
|
||||
changed.push(file);
|
||||
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
|
||||
const [targetHash, sourceHash] = await Promise.all([
|
||||
@@ -206,6 +218,7 @@ async function updateFromSource(record: InstallRecord, root: string, signal: Abo
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({
|
||||
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
|
||||
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
|
||||
...(linked.length ? { hardlinkedFiles: [] } : {}),
|
||||
})));
|
||||
}
|
||||
|
||||
@@ -223,10 +236,68 @@ async function scopedInstallFile(dataPath: string, root: string, name: string):
|
||||
return target;
|
||||
}
|
||||
|
||||
async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
||||
const hash = createHash('sha256');
|
||||
for await (const bytes of createReadStream(path, { signal })) hash.update(bytes as Buffer);
|
||||
return hash.digest('hex');
|
||||
async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
|
||||
return record.method === 'copy' && source.version === record.gameVersion &&
|
||||
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
|
||||
}
|
||||
|
||||
async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
|
||||
const source = await readSource(record);
|
||||
if (!source || !await convertibleCopy(record, source, root) ||
|
||||
(await inspectGameFolder(root)).version !== source.version) {
|
||||
throw new AppError('hardlink_unavailable');
|
||||
}
|
||||
|
||||
const plan = await planCopy(source.path);
|
||||
const candidates = plan.files.flatMap(({ relativePath, bytes }) => {
|
||||
const evidence = hardlinkResource(source.version, relativePath, bytes);
|
||||
return evidence ? [{ relativePath, evidence }] : [];
|
||||
});
|
||||
const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0);
|
||||
const dataPath = await canonicalCopyPath(record.dataPath);
|
||||
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
|
||||
return changeCopyFiles(root, async (incoming) => {
|
||||
const replacements: string[] = [];
|
||||
const unchanged = new Map<string, BigIntStats>();
|
||||
let checked = 0;
|
||||
let matches = 0;
|
||||
let lastReport = 0;
|
||||
report('checking', 0, total);
|
||||
for (const { relativePath, evidence } of candidates) {
|
||||
const target = await scopedInstallFile(dataPath, root, relativePath);
|
||||
const original = join(source.path, relativePath);
|
||||
const copyStamp = await verifyHardlinkResource(target, evidence, signal);
|
||||
const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null;
|
||||
if (copyStamp && sourceStamp) {
|
||||
if (!sameResource(copyStamp, sourceStamp)) {
|
||||
const staged = join(incoming, relativePath);
|
||||
await mkdir(dirname(staged), { recursive: true });
|
||||
const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp);
|
||||
unchanged.set(target, copyStamp);
|
||||
unchanged.set(staged, stagedStamp);
|
||||
replacements.push(relativePath);
|
||||
}
|
||||
linked.set(key(relativePath), relativePath);
|
||||
matches += 1;
|
||||
}
|
||||
checked += evidence.bytes;
|
||||
if (checked === total || Date.now() - lastReport >= 250) {
|
||||
lastReport = Date.now();
|
||||
report('checking', checked, total);
|
||||
}
|
||||
}
|
||||
if (!matches) throw new AppError('hardlink_no_match');
|
||||
|
||||
signal.throwIfAborted();
|
||||
if ((await readSource(record))?.version !== source.version) throw new AppError('hardlink_file_changed');
|
||||
for (const [path, stamp] of unchanged) {
|
||||
signal.throwIfAborted();
|
||||
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
report('applying', total, total);
|
||||
return { replace: replacements, remove: [] };
|
||||
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
|
||||
}
|
||||
|
||||
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
|
||||
|
||||
@@ -1,26 +1,11 @@
|
||||
import { lstat, readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { FolderSize } from '@shared/schemas/install.ts';
|
||||
import { planCopy } from '../install/copy-game.ts';
|
||||
import { hardlinkResource } from '../install/hardlink-files.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 };
|
||||
/** Estimate the installation size and the bytes eligible for content verification. */
|
||||
export async function measureFolder(root: string, version?: string | null): Promise<FolderSize> {
|
||||
const plan = await planCopy(root);
|
||||
const linkableBytes = plan.files.reduce((total, file) =>
|
||||
total + (hardlinkResource(version, file.relativePath, file.bytes)?.bytes ?? 0), 0);
|
||||
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { readdir, realpath, stat, statfs } from 'node:fs/promises';
|
||||
import { dirname, parse, relative, resolve, isAbsolute } from 'node:path';
|
||||
import { dirname, relative, resolve, isAbsolute } from 'node:path';
|
||||
import { isInSteamLibrary } from '@wto/patcher';
|
||||
import type { TargetFolderInspection } from '@shared/schemas/install.ts';
|
||||
|
||||
@@ -15,10 +15,26 @@ export async function inspectTargetFolder(path: string, stockPath: string): Prom
|
||||
problem: await targetProblem(target, stock),
|
||||
inSteamLibrary: isInSteamLibrary(target),
|
||||
freeBytes: await freeBytes(target),
|
||||
sameDriveAsStock: parse(target).root.toLowerCase() === parse(stock).root.toLowerCase(),
|
||||
sameDriveAsStock: await sameVolume(target, stock),
|
||||
};
|
||||
}
|
||||
|
||||
/** Compare actual volumes, including directories reached through junctions. */
|
||||
export async function sameVolume(left: string, right: string): Promise<boolean> {
|
||||
const [first, second] = await Promise.all([volumeDevice(left), volumeDevice(right)]);
|
||||
return first !== null && first === second;
|
||||
}
|
||||
|
||||
async function volumeDevice(path: string): Promise<bigint | null> {
|
||||
for (let folder = resolve(path); ; folder = dirname(folder)) {
|
||||
try {
|
||||
return (await stat(folder, { bigint: true })).dev || null;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(folder) === folder) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function targetProblem(target: string, stock: string): Promise<TargetFolderInspection['problem']> {
|
||||
if (contains(stock, target) || contains(target, stock)) return 'overlaps_stock';
|
||||
let entries: string[];
|
||||
@@ -39,7 +55,7 @@ function contains(outer: string, inner: string): boolean {
|
||||
}
|
||||
|
||||
/** Free bytes on the drive of the nearest existing folder at or above `path`. */
|
||||
async function freeBytes(path: string): Promise<number | null> {
|
||||
export async function freeBytes(path: string): Promise<number | null> {
|
||||
for (let folder = path; ; folder = dirname(folder)) {
|
||||
try {
|
||||
const info = await statfs(folder);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs';
|
||||
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
|
||||
import { join, relative } from 'node:path';
|
||||
import { Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
|
||||
|
||||
/**
|
||||
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
|
||||
@@ -72,9 +74,11 @@ export async function copyPlannedFiles(
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
onProgress: (progress: CopyProgress) => void,
|
||||
hardlinks?: ReadonlyMap<string, BigIntStats>,
|
||||
): Promise<void> {
|
||||
await mkdir(target, { recursive: true });
|
||||
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
|
||||
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
|
||||
let next = 0;
|
||||
let doneBytes = 0;
|
||||
let doneFiles = 0;
|
||||
@@ -94,15 +98,24 @@ export async function copyPlannedFiles(
|
||||
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 },
|
||||
);
|
||||
const modified = new Date(file.modifiedAt);
|
||||
await utimes(join(target, file.relativePath), modified, modified);
|
||||
const from = join(source, file.relativePath);
|
||||
const to = join(target, file.relativePath);
|
||||
const verified = hardlinks?.get(file.relativePath);
|
||||
if (verified) {
|
||||
const linked = await linkVerifiedResource(from, to, verified);
|
||||
linkedTargets?.set(to, linked);
|
||||
doneBytes += file.bytes;
|
||||
} else {
|
||||
await pipeline(
|
||||
createReadStream(from),
|
||||
countBytes(),
|
||||
// 'wx': fail instead of overwriting a file that is already there.
|
||||
createWriteStream(to, { flags: 'wx' }),
|
||||
{ signal: stopSignal },
|
||||
);
|
||||
const modified = new Date(file.modifiedAt);
|
||||
await utimes(to, modified, modified);
|
||||
}
|
||||
doneFiles += 1;
|
||||
onProgress({ doneBytes, doneFiles });
|
||||
}
|
||||
@@ -114,6 +127,12 @@ export async function copyPlannedFiles(
|
||||
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;
|
||||
if (linkedTargets) {
|
||||
for (const [path, stamp] of linkedTargets) {
|
||||
signal.throwIfAborted();
|
||||
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, type BigIntStats } from 'node:fs';
|
||||
import { link, lstat } from 'node:fs/promises';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import evidence from './hardlink-resources-2.61.0.43.json' with { type: 'json' };
|
||||
|
||||
interface ResourceEvidence {
|
||||
readonly bytes: number;
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
const resources: Readonly<Record<string, ResourceEvidence>> = evidence.files;
|
||||
|
||||
export function hasHardlinkEvidence(version: string | null | undefined): boolean {
|
||||
return version === evidence.gameVersion;
|
||||
}
|
||||
|
||||
/** Only an exact path and size from the sampled build can be offered as a candidate. */
|
||||
export function hardlinkResource(
|
||||
version: string | null | undefined,
|
||||
relativePath: string,
|
||||
bytes: number,
|
||||
): ResourceEvidence | undefined {
|
||||
if (!hasHardlinkEvidence(version)) return undefined;
|
||||
const path = relativePath.replaceAll('\\', '/').toLowerCase();
|
||||
const resource = Object.hasOwn(resources, path) ? resources[path] : undefined;
|
||||
return resource?.bytes === bytes ? resource : undefined;
|
||||
}
|
||||
|
||||
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
|
||||
const hash = createHash('sha256');
|
||||
for await (const chunk of createReadStream(path, { signal })) hash.update(chunk as Buffer);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
/** Read the measured bytes and retain the observed file identity until the link is created. */
|
||||
export async function verifyHardlinkResource(
|
||||
path: string,
|
||||
resource: ResourceEvidence,
|
||||
signal: AbortSignal,
|
||||
): Promise<BigIntStats | null> {
|
||||
signal.throwIfAborted();
|
||||
const before = await lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return null;
|
||||
throw error;
|
||||
});
|
||||
if (!before?.isFile() || before.size !== BigInt(resource.bytes)) return null;
|
||||
const checksum = await fileHash(path, signal);
|
||||
const after = await lstat(path, { bigint: true });
|
||||
if (!sameResource(before, after)) throw new AppError('hardlink_file_changed');
|
||||
return checksum === resource.sha256 ? after : null;
|
||||
}
|
||||
|
||||
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
|
||||
return sameIdentityAndContents(left, right) && left.ctimeNs === right.ctimeNs;
|
||||
}
|
||||
|
||||
export async function linkVerifiedResource(source: string, target: string, verified: BigIntStats): Promise<BigIntStats> {
|
||||
if (!sameResource(verified, await lstat(source, { bigint: true }))) throw new AppError('hardlink_file_changed');
|
||||
await link(source, target);
|
||||
// Linking may change ctime. The inode, contents and modification time must stay the same.
|
||||
const linked = await lstat(target, { bigint: true });
|
||||
if (!sameIdentityAndContents(verified, linked)) throw new AppError('hardlink_file_changed');
|
||||
return linked;
|
||||
}
|
||||
|
||||
function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean {
|
||||
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
|
||||
left.size === right.size && left.mtimeNs === right.mtimeNs;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,13 @@
|
||||
import type { BigIntStats } from 'node:fs';
|
||||
import { access, mkdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
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 { requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
|
||||
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
|
||||
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
|
||||
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { checkPatches } from './patch-check.ts';
|
||||
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
|
||||
|
||||
@@ -35,6 +38,9 @@ export async function installGame(request: InstallRequest, onProgress: (progress
|
||||
running = controller;
|
||||
try {
|
||||
return await install(request, controller.signal, throttled(onProgress));
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw new AppError('install_cancelled');
|
||||
throw error;
|
||||
} finally {
|
||||
running = null;
|
||||
}
|
||||
@@ -75,6 +81,13 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
|
||||
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
|
||||
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
|
||||
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
|
||||
if (useHardLinks) {
|
||||
if (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version)) throw new AppError('hardlink_unavailable');
|
||||
if (copyPathContains(await canonicalCopyPath(gameFolder), await canonicalCopyPath(request.dataPath))) {
|
||||
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
|
||||
}
|
||||
}
|
||||
const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary;
|
||||
if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed');
|
||||
|
||||
@@ -86,8 +99,8 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted');
|
||||
signal.throwIfAborted();
|
||||
|
||||
const sourceFiles = request.method === 'copy'
|
||||
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report)
|
||||
const copied = request.method === 'copy'
|
||||
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, useHardLinks ? game.version : null, signal, report)
|
||||
: undefined;
|
||||
|
||||
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
@@ -106,7 +119,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
unavailablePatches: check.unavailable,
|
||||
installedAt: new Date().toISOString(),
|
||||
lastCheckedAt: new Date().toISOString(),
|
||||
...(sourceFiles ? { sourceFiles } : {}),
|
||||
...copied,
|
||||
};
|
||||
await writeInstallRecord(record);
|
||||
return record;
|
||||
@@ -115,29 +128,70 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
async function copyGame(
|
||||
source: string,
|
||||
target: string,
|
||||
freeBytes: number | null,
|
||||
initialFreeBytes: number | null,
|
||||
hardlinkVersion: string | null,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<string[]> {
|
||||
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
|
||||
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 hardlinks = hardlinkVersion ? await confirmHardlinks(source, hardlinkVersion, plan, signal, report) : undefined;
|
||||
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
|
||||
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
|
||||
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== hardlinkVersion)) {
|
||||
throw new AppError('hardlink_file_changed');
|
||||
}
|
||||
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
|
||||
if (available !== null && available < neededBytes) {
|
||||
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
|
||||
}
|
||||
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 }));
|
||||
return plan.files.map((file) => file.relativePath);
|
||||
await copyPlannedFiles(source, target, plan, signal,
|
||||
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
|
||||
if (hardlinks && (await inspectGameFolder(source)).version !== hardlinkVersion) throw new AppError('hardlink_file_changed');
|
||||
return {
|
||||
sourceFiles: plan.files.map((file) => file.relativePath),
|
||||
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
|
||||
};
|
||||
} 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');
|
||||
if (error instanceof AppError) throw error;
|
||||
console.error('[install] copying failed:', error);
|
||||
throw new AppError('copy_failed');
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmHardlinks(
|
||||
source: string,
|
||||
version: string,
|
||||
plan: CopyPlan,
|
||||
signal: AbortSignal,
|
||||
report: (progress: InstallProgress) => void,
|
||||
): Promise<ReadonlyMap<string, BigIntStats>> {
|
||||
const candidates = plan.files.flatMap((file) => {
|
||||
const evidence = hardlinkResource(version, file.relativePath, file.bytes);
|
||||
return evidence ? [{ path: file.relativePath, evidence }] : [];
|
||||
});
|
||||
const totalBytes = candidates.reduce((total, file) => total + file.evidence.bytes, 0);
|
||||
const links = new Map<string, BigIntStats>();
|
||||
let doneBytes = 0;
|
||||
let doneFiles = 0;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
for (const { path, evidence } of candidates) {
|
||||
const verified = await verifyHardlinkResource(join(source, path), evidence, signal);
|
||||
if (verified) links.set(path, verified);
|
||||
doneBytes += evidence.bytes;
|
||||
doneFiles += 1;
|
||||
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
|
||||
}
|
||||
if (!links.size) throw new AppError('hardlink_no_match');
|
||||
return links;
|
||||
}
|
||||
|
||||
async function requireGameFolder(path: string) {
|
||||
const game = await inspectGameFolder(path);
|
||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
|
||||
|
||||
@@ -123,6 +123,11 @@
|
||||
"method": {
|
||||
"copy": "Copy installation (recommended)",
|
||||
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
||||
"spaceSaving": "Space-saving copy",
|
||||
"spaceSavingBody": "Shares verified large resources on the same volume. Estimated space required is {{size}}. A Steam update in place can change shared files in the copy.",
|
||||
"spaceSavingPending": "Calculating how much space can be saved.",
|
||||
"spaceSavingUnavailable": "This installation has no large resources eligible for space-saving copying.",
|
||||
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
|
||||
"targetTitle": "Select a folder for the copy",
|
||||
"inPlace": "In-place installation",
|
||||
"inPlaceBody": "Uses the selected game folder as the copy. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.",
|
||||
@@ -156,11 +161,14 @@
|
||||
"phase": {
|
||||
"checking": "Checking game files",
|
||||
"measuring": "Counting files",
|
||||
"verifying": "Verifying resources to share",
|
||||
"copying": "Copying game files",
|
||||
"backing-up": "Backing up original files",
|
||||
"recording": "Finishing installation"
|
||||
},
|
||||
"copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
|
||||
"cancelHint": "Can be cancelled at any time; copied files will be deleted",
|
||||
"cancel": "Cancel installation",
|
||||
"cancelling": "Cancelling…"
|
||||
@@ -179,8 +187,13 @@
|
||||
"update": "Update from official installation",
|
||||
"updateAction": "Update copy",
|
||||
"newVersion": "Version {{version}} is available from the installation source.",
|
||||
"updateDetaches": "Version {{version}} is available. Updating copies shared resources into independent files and requires additional space.",
|
||||
"currentVersion": "Installation source version {{version}}",
|
||||
"noSource": "Installation source unavailable",
|
||||
"spaceSaving": "Save space",
|
||||
"spaceSavingHint": "Share identical verified resources with the source. A Steam update in place can change the shared files.",
|
||||
"spaceSavingUnavailable": "Requires a copy and source installation of the same checked version on the same volume.",
|
||||
"compactAction": "Convert",
|
||||
"check": "Recheck patches",
|
||||
"checkHint": "Check the original file backup.",
|
||||
"lastCheck": "Last checked {{date}}",
|
||||
@@ -202,8 +215,9 @@
|
||||
"check": "Patch check complete.",
|
||||
"repair": "Original files restored.",
|
||||
"update": "Copy updated.",
|
||||
"compact": "Space-saving conversion complete.",
|
||||
"delete": "Copy deleted.",
|
||||
"cancelled": "Update cancelled."
|
||||
"cancelled": "Maintenance cancelled."
|
||||
}
|
||||
},
|
||||
"summary": {
|
||||
@@ -217,6 +231,7 @@
|
||||
"method": "Installation type",
|
||||
"methods": {
|
||||
"copy": "Copy installation",
|
||||
"hardlink": "Space-saving copy",
|
||||
"in-place": "In-place installation"
|
||||
},
|
||||
"stock": "Original file backup",
|
||||
@@ -602,6 +617,9 @@
|
||||
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
|
||||
"patch_check_failed": "An error occurred while checking patches.",
|
||||
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
|
||||
"hardlink_unavailable": "Space-saving copying requires a verified game version and a destination on the same volume.",
|
||||
"hardlink_no_match": "The files do not match the verified resources for space-saving copying.",
|
||||
"hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
|
||||
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
|
||||
"install_busy": "An installation is already in progress.",
|
||||
"unknown": "An unknown error occurred."
|
||||
|
||||
@@ -123,6 +123,11 @@
|
||||
"method": {
|
||||
"copy": "复制安装(推荐)",
|
||||
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
||||
"spaceSaving": "节省空间的复制",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用已核对的大资源,预计需要 {{size}}。Steam 就地更新可能改变副本中的共享文件。",
|
||||
"spaceSavingPending": "正在估算可节省的空间。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的大型资源。",
|
||||
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
||||
"targetTitle": "选择存放副本的文件夹",
|
||||
"inPlace": "原位安装",
|
||||
"inPlaceBody": "使用所选游戏文件夹作为副本。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。",
|
||||
@@ -156,11 +161,14 @@
|
||||
"phase": {
|
||||
"checking": "检查游戏文件",
|
||||
"measuring": "统计文件",
|
||||
"verifying": "核对可共用的资源",
|
||||
"copying": "复制游戏文件",
|
||||
"backing-up": "备份原版文件",
|
||||
"recording": "完成安装"
|
||||
},
|
||||
"copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
|
||||
"cancelHint": "可随时取消,已复制的文件将被删除",
|
||||
"cancel": "取消安装",
|
||||
"cancelling": "正在取消…"
|
||||
@@ -179,8 +187,13 @@
|
||||
"update": "从正版更新",
|
||||
"updateAction": "更新副本",
|
||||
"newVersion": "安装来源已更新至 {{version}}。",
|
||||
"updateDetaches": "安装来源中有新版本 {{version}}。更新会把共享资源复制为独立文件,需要额外空间。",
|
||||
"currentVersion": "安装来源版本 {{version}}",
|
||||
"noSource": "安装来源不可用",
|
||||
"spaceSaving": "节省空间",
|
||||
"spaceSavingHint": "将内容一致且已核对的资源与原版共用。Steam 就地更新可能改变这些文件。",
|
||||
"spaceSavingUnavailable": "副本和安装来源须位于同一磁盘卷,并且使用相同的已核对版本。",
|
||||
"compactAction": "转换",
|
||||
"check": "重新检查补丁",
|
||||
"checkHint": "核对原版文件备份。",
|
||||
"lastCheck": "上次检查 {{date}}",
|
||||
@@ -202,8 +215,9 @@
|
||||
"check": "补丁检查已完成。",
|
||||
"repair": "原版文件已还原。",
|
||||
"update": "副本已更新。",
|
||||
"compact": "省空间转换已完成。",
|
||||
"delete": "副本已删除。",
|
||||
"cancelled": "更新已取消。"
|
||||
"cancelled": "维护已取消。"
|
||||
}
|
||||
},
|
||||
"summary": {
|
||||
@@ -217,6 +231,7 @@
|
||||
"method": "安装方式",
|
||||
"methods": {
|
||||
"copy": "复制安装",
|
||||
"hardlink": "节省空间的复制",
|
||||
"in-place": "原位安装"
|
||||
},
|
||||
"stock": "原版文件备份",
|
||||
@@ -602,6 +617,9 @@
|
||||
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
|
||||
"patch_check_failed": "检查补丁时出错。",
|
||||
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
|
||||
"hardlink_unavailable": "省空间复制需要已核对的游戏版本,并且目标与原版位于同一磁盘卷。",
|
||||
"hardlink_no_match": "文件内容与可共用的实测资源不一致。",
|
||||
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
|
||||
"install_cancelled": "安装已取消,已复制的文件已删除。",
|
||||
"install_busy": "已有安装正在进行。",
|
||||
"unknown": "发生未知错误。"
|
||||
|
||||
@@ -55,13 +55,20 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
||||
return (
|
||||
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
|
||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
||||
? t(info.updateAvailable ? 'copies.maintenance.newVersion' : 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||
? t(info.updateAvailable
|
||||
? (record.hardlinkedFiles?.length ? 'copies.maintenance.updateDetaches' : 'copies.maintenance.newVersion')
|
||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||
: t('copies.maintenance.noSource')}>
|
||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||
disabled={working !== null || !info?.updateAvailable} onClick={() => run('update')}>
|
||||
{t('copies.maintenance.updateAction')}
|
||||
</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.spaceSaving')} hint={info?.spaceSavingAvailable
|
||||
? t('copies.maintenance.spaceSavingHint') : t('copies.maintenance.spaceSavingUnavailable')}>
|
||||
<button type="button" className="button" disabled={working !== null || !info?.spaceSavingAvailable}
|
||||
onClick={() => run('compact')}>{t('copies.maintenance.compactAction')}</button>
|
||||
</Row>
|
||||
<Row label={t('copies.maintenance.check')} hint={record.lastCheckedAt
|
||||
? t('copies.maintenance.lastCheck', { date: new Date(record.lastCheckedAt).toLocaleString(i18n.language) })
|
||||
: t('copies.maintenance.checkHint')}>
|
||||
@@ -100,7 +107,7 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
|
||||
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
|
||||
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
|
||||
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
|
||||
{working === 'update' && progress?.phase !== 'applying' && (
|
||||
{(working === 'update' || working === 'compact') && progress?.phase !== 'applying' && (
|
||||
<button type="button" className="button" onClick={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}>
|
||||
{t('wizard.cancel')}
|
||||
</button>
|
||||
|
||||
@@ -40,7 +40,7 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onError
|
||||
<span className={verified ? 'ok' : 'warn'}>{verified ? t('adaptation.verified') : t('adaptation.unverified')}</span>
|
||||
</Row>
|
||||
<Row label={t('copies.summary.location')}>{folder(record.copyPath)}</Row>
|
||||
<Row label={t('copies.summary.method')}>{t(`copies.summary.methods.${record.method}`)}</Row>
|
||||
<Row label={t('copies.summary.method')}>{t(`copies.summary.methods.${record.hardlinkedFiles?.length ? 'hardlink' : record.method}`)}</Row>
|
||||
{record.sourcePath && <Row label={t('copies.summary.source')}>{folder(record.sourcePath)}</Row>}
|
||||
<Row label={t('copies.summary.stock')} hint={t('copies.summary.stockHint')}>{folder(record.stockBackupPath)}</Row>
|
||||
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { FolderSize, GameFolderInspection, InstallMethod, TargetFolderInspection } from '@shared/schemas/install.ts';
|
||||
import { FolderField } from '../../components/FolderField.tsx';
|
||||
@@ -9,34 +9,42 @@ import { ipcInvoke } from '../../ipc.ts';
|
||||
/** Room the copy needs beyond the game itself; the main process checks the same margin. */
|
||||
const SPARE_BYTES = 1024 ** 3;
|
||||
|
||||
type Method = InstallMethod | 'hardlink';
|
||||
|
||||
export interface MethodChoice {
|
||||
readonly method: InstallMethod;
|
||||
readonly method: Method;
|
||||
readonly target: TargetFolderInspection | null;
|
||||
readonly steamConfirmed: boolean;
|
||||
}
|
||||
|
||||
interface MethodStepProps {
|
||||
readonly source: GameFolderInspection;
|
||||
/** Size of the installation; null while it is being measured. */
|
||||
readonly sourceSize: FolderSize | null;
|
||||
readonly choice: MethodChoice;
|
||||
readonly onChoice: (choice: MethodChoice) => void;
|
||||
readonly onChoice: Dispatch<SetStateAction<MethodChoice>>;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** Step 2: copy the game into a new folder, or install into the chosen folder itself. */
|
||||
export function MethodStep({ source, sourceSize, choice, onChoice, onError }: MethodStepProps) {
|
||||
const { t } = useTranslation();
|
||||
const choose = (method: InstallMethod): void => onChoice({ method, target: choice.target, steamConfirmed: false });
|
||||
const choose = (method: Method): void => onChoice({ method, target: choice.target, steamConfirmed: false });
|
||||
const inspectTarget = (path: string): void => {
|
||||
onChoice({ ...choice, target: null, steamConfirmed: false });
|
||||
onChoice((current) => ({ ...current, target: null, steamConfirmed: false }));
|
||||
ipcInvoke('install:inspectTargetFolder', { path, stockPath: source.path })
|
||||
.then((target) => onChoice({ method: 'copy', target, steamConfirmed: false }))
|
||||
.then((target) => onChoice((current) => ({ ...current, target, steamConfirmed: false })))
|
||||
.catch(onError);
|
||||
};
|
||||
const steamWarning = steamLibraryInvolved(source, choice)
|
||||
? <SteamWarning method={choice.method} confirmed={choice.steamConfirmed} onConfirmed={(steamConfirmed) => onChoice({ ...choice, steamConfirmed })} />
|
||||
: null;
|
||||
const targetPicker = (
|
||||
<>
|
||||
<FolderField path={choice.target?.path ?? null} dialogTitle={t('method.targetTitle')} onChosen={inspectTarget} onError={onError} />
|
||||
{choice.target && <TargetVerdict target={choice.target} sourceSize={sourceSize} method={choice.method} />}
|
||||
{steamWarning}
|
||||
</>
|
||||
);
|
||||
const savingAvailable = (sourceSize?.linkableBytes ?? 0) > 0;
|
||||
return (
|
||||
<>
|
||||
<Choice
|
||||
@@ -45,9 +53,20 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
|
||||
body={sourceSize ? t('method.copyBody', { size: formatBytes(sourceSize.bytes) }) : t('method.copyBodyPending')}
|
||||
onSelect={() => choose('copy')}
|
||||
>
|
||||
<FolderField path={choice.target?.path ?? null} dialogTitle={t('method.targetTitle')} onChosen={inspectTarget} onError={onError} />
|
||||
{choice.target && <TargetVerdict target={choice.target} sourceSize={sourceSize} />}
|
||||
{steamWarning}
|
||||
{targetPicker}
|
||||
</Choice>
|
||||
<Choice
|
||||
selected={choice.method === 'hardlink'}
|
||||
disabled={!savingAvailable}
|
||||
title={t('method.spaceSaving')}
|
||||
body={sourceSize
|
||||
? savingAvailable
|
||||
? t('method.spaceSavingBody', { size: formatBytes(bytesToCopy(sourceSize, 'hardlink')) })
|
||||
: t('method.spaceSavingUnavailable')
|
||||
: t('method.spaceSavingPending')}
|
||||
onSelect={() => choose('hardlink')}
|
||||
>
|
||||
{targetPicker}
|
||||
</Choice>
|
||||
<Choice
|
||||
selected={choice.method === 'in-place'}
|
||||
@@ -63,17 +82,18 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
|
||||
|
||||
interface ChoiceProps {
|
||||
readonly selected: boolean;
|
||||
readonly disabled?: boolean;
|
||||
readonly title: string;
|
||||
readonly body: string;
|
||||
readonly onSelect: () => void;
|
||||
/** Shown under the description while the choice is selected. */
|
||||
readonly children: ReactNode;
|
||||
}
|
||||
|
||||
function Choice({ selected, title, body, onSelect, children }: ChoiceProps) {
|
||||
function Choice({ selected, disabled, title, body, onSelect, children }: ChoiceProps) {
|
||||
return (
|
||||
<div className={selected ? 'choice choice-selected' : 'choice'} onClick={selected ? undefined : onSelect}>
|
||||
<input type="radio" name="method" checked={selected} onChange={onSelect} aria-label={title} />
|
||||
<div className={selected ? 'choice choice-selected' : 'choice'} aria-disabled={disabled}
|
||||
onClick={selected || disabled ? undefined : onSelect}>
|
||||
<input type="radio" name="method" checked={selected} disabled={disabled} onChange={onSelect} aria-label={title} />
|
||||
<span className="choice-title">{title}</span>
|
||||
<div className="choice-body">{body}</div>
|
||||
{selected && <div className="choice-detail">{children}</div>}
|
||||
@@ -81,16 +101,26 @@ function Choice({ selected, title, body, onSelect, children }: ChoiceProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function TargetVerdict({ target, sourceSize }: { readonly target: TargetFolderInspection; readonly sourceSize: FolderSize | null }) {
|
||||
const { t } = useTranslation();
|
||||
if (target.problem) return <Notice tone="error">{t(`method.problem.${target.problem}`)}</Notice>;
|
||||
if (target.freeBytes !== null && sourceSize && target.freeBytes < sourceSize.bytes + SPARE_BYTES) {
|
||||
return <Notice tone="error">{t('method.noRoom', { needed: formatBytes(sourceSize.bytes + SPARE_BYTES), free: formatBytes(target.freeBytes) })}</Notice>;
|
||||
}
|
||||
return target.freeBytes === null ? null : <Notice tone="info">{t('method.room', { free: formatBytes(target.freeBytes) })}</Notice>;
|
||||
function bytesToCopy(size: FolderSize, method: Method): number {
|
||||
return size.bytes - (method === 'hardlink' ? (size.linkableBytes ?? 0) : 0);
|
||||
}
|
||||
|
||||
function SteamWarning({ method, confirmed, onConfirmed }: { readonly method: InstallMethod; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) {
|
||||
function TargetVerdict({ target, sourceSize, method }: {
|
||||
readonly target: TargetFolderInspection;
|
||||
readonly sourceSize: FolderSize | null;
|
||||
readonly method: Method;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (target.problem) return <Notice tone="error">{t(`method.problem.${target.problem}`)}</Notice>;
|
||||
if (method === 'hardlink' && !target.sameDriveAsStock) return <Notice tone="error">{t('method.sameVolumeRequired')}</Notice>;
|
||||
if (target.freeBytes === null || !sourceSize) return null;
|
||||
const needed = bytesToCopy(sourceSize, method) + SPARE_BYTES;
|
||||
return target.freeBytes < needed
|
||||
? <Notice tone="error">{t('method.noRoom', { needed: formatBytes(needed), free: formatBytes(target.freeBytes) })}</Notice>
|
||||
: <Notice tone="info">{t('method.room', { free: formatBytes(target.freeBytes) })}</Notice>;
|
||||
}
|
||||
|
||||
function SteamWarning({ method, confirmed, onConfirmed }: { readonly method: Method; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Notice tone="warning">
|
||||
@@ -113,5 +143,6 @@ export function methodUsable(source: GameFolderInspection, sourceSize: FolderSiz
|
||||
if (choice.method === 'in-place') return true;
|
||||
const target = choice.target;
|
||||
if (!target || target.problem || !sourceSize) return false;
|
||||
return target.freeBytes === null || target.freeBytes >= sourceSize.bytes + SPARE_BYTES;
|
||||
if (choice.method === 'hardlink' && (!target.sameDriveAsStock || !sourceSize.linkableBytes)) return false;
|
||||
return target.freeBytes === null || target.freeBytes >= bytesToCopy(sourceSize, choice.method) + SPARE_BYTES;
|
||||
}
|
||||
@@ -4,17 +4,22 @@ import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
|
||||
/**
|
||||
* Step 5: the installation running, phase by phase. Cancelling is in the bottom bar; only the
|
||||
* copy can be stopped, the other phases take seconds.
|
||||
* Step 5: the installation running, phase by phase. Resource verification and copying can be
|
||||
* cancelled from the bottom bar.
|
||||
*/
|
||||
export function ProgressStep({ progress }: { readonly progress: InstallProgress | null }) {
|
||||
export function ProgressStep({ progress, useHardLinks }: {
|
||||
readonly progress: InstallProgress | null;
|
||||
readonly useHardLinks: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const phase = progress?.phase ?? 'checking';
|
||||
const current = INSTALL_PHASES.indexOf(phase);
|
||||
const copying = phase === 'copying' && progress !== null;
|
||||
const phases: readonly InstallProgress['phase'][] = useHardLinks ? INSTALL_PHASES : INSTALL_PHASES.filter((name) => name !== 'verifying');
|
||||
const current = phases.indexOf(phase);
|
||||
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
||||
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
|
||||
return (
|
||||
<>
|
||||
{INSTALL_PHASES.map((name, position) => {
|
||||
{phases.map((name, position) => {
|
||||
const state = position < current ? 'done' : position === current ? 'current' : 'pending';
|
||||
return (
|
||||
<div key={name} className={`phase phase-${state}`}>
|
||||
@@ -23,10 +28,10 @@ export function ProgressStep({ progress }: { readonly progress: InstallProgress
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<ProgressBar value={copying ? progress.doneBytes : 0} max={copying ? progress.totalBytes : null} large />
|
||||
{copying && (
|
||||
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
|
||||
{tracking && (
|
||||
<div className="progress-caption">
|
||||
{t('progress.copied', {
|
||||
{t(caption, {
|
||||
done: formatBytes(progress.doneBytes),
|
||||
total: formatBytes(progress.totalBytes),
|
||||
doneFiles: progress.doneFiles.toLocaleString(),
|
||||
|
||||
@@ -27,7 +27,7 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
|
||||
)}
|
||||
{step === 'data' && <DataStep dataPath={wizard.dataPath} onDataPath={wizard.setDataPath} onError={wizard.report} />}
|
||||
{step === 'check' && <CheckStep check={wizard.check} missingAccepted={wizard.missingAccepted} onMissingAccepted={wizard.setMissingAccepted} />}
|
||||
{step === 'installing' && <ProgressStep progress={wizard.progress} />}
|
||||
{step === 'installing' && <ProgressStep progress={wizard.progress} useHardLinks={wizard.choice.method === 'hardlink'} />}
|
||||
{wizard.message && <p className="error-text" role="alert">{wizard.message}</p>}
|
||||
</Sheet>
|
||||
);
|
||||
|
||||
@@ -40,7 +40,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
setSourceSize(null);
|
||||
if (!sourceUsable(source)) return;
|
||||
let current = true;
|
||||
ipcInvoke('install:measureFolder', { path: source.path })
|
||||
ipcInvoke('install:measureFolder', { path: source.path, version: source.version })
|
||||
.then((size) => current && setSourceSize(size))
|
||||
.catch((error: unknown) => current && report(error));
|
||||
return () => {
|
||||
@@ -92,9 +92,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
|
||||
const install = (): void => {
|
||||
if (!sourceUsable(source) || !draftId) return;
|
||||
const choices = { id: draftId, name, dataPath, steamLibraryConfirmed: choice.steamConfirmed, missingFeaturesAccepted: missingAccepted };
|
||||
const request: InstallRequest = choice.method === 'copy'
|
||||
? { method: 'copy', sourcePath: source.path, copyPath: choice.target!.path, ...choices }
|
||||
: { method: 'in-place', gamePath: source.path, ...choices };
|
||||
const request: InstallRequest = choice.method === 'in-place'
|
||||
? { method: 'in-place', gamePath: source.path, ...choices }
|
||||
: { method: 'copy', useHardLinks: choice.method === 'hardlink', sourcePath: source.path, copyPath: choice.target!.path, ...choices };
|
||||
clear();
|
||||
setProgress(null);
|
||||
setCancelling(false);
|
||||
|
||||
@@ -10,12 +10,12 @@ export function wizardBar(wizard: InstallWizard, t: TFunction): BarModel {
|
||||
|
||||
if (step === 'installing') {
|
||||
const phase = progress?.phase ?? 'checking';
|
||||
const copying = phase === 'copying' && progress !== null;
|
||||
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
|
||||
return {
|
||||
tone: 'busy',
|
||||
title: t(`progress.phase.${phase}`),
|
||||
detail: copying ? t('progress.cancelHint') : stepOf,
|
||||
progress: copying
|
||||
detail: tracking ? t('progress.cancelHint') : stepOf,
|
||||
progress: tracking
|
||||
? {
|
||||
value: progress.doneBytes,
|
||||
max: progress.totalBytes,
|
||||
@@ -24,7 +24,7 @@ export function wizardBar(wizard: InstallWizard, t: TFunction): BarModel {
|
||||
}
|
||||
: { value: 0, max: null },
|
||||
primary: { label: t('wizard.installing'), disabled: true },
|
||||
...(copying ? { secondary: { label: cancelling ? t('progress.cancelling') : t('progress.cancel'), disabled: cancelling, onClick: wizard.cancel } } : {}),
|
||||
...(tracking ? { secondary: { label: cancelling ? t('progress.cancelling') : t('progress.cancel'), disabled: cancelling, onClick: wizard.cancel } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -353,6 +353,11 @@
|
||||
border-color: var(--line-strong);
|
||||
}
|
||||
|
||||
.choice[aria-disabled='true'] {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.choice-selected {
|
||||
border-color: var(--red);
|
||||
background: rgba(229, 57, 53, 0.08);
|
||||
|
||||
@@ -68,6 +68,9 @@ export const APP_ERROR_CODES = [
|
||||
'patch_check_failed',
|
||||
/** Copying the game failed; what was copied has been removed. */
|
||||
'copy_failed',
|
||||
'hardlink_unavailable',
|
||||
'hardlink_no_match',
|
||||
'hardlink_file_changed',
|
||||
/** The player stopped the installation; what was copied has been removed. */
|
||||
'install_cancelled',
|
||||
/** An installation is already running. */
|
||||
|
||||
@@ -79,7 +79,7 @@ export const ipcContract = {
|
||||
output: TargetFolderInspectionSchema,
|
||||
},
|
||||
'install:measureFolder': {
|
||||
input: z.object({ path: z.string().min(1) }),
|
||||
input: z.object({ path: z.string().min(1), version: z.string().nullable().optional() }),
|
||||
output: FolderSizeSchema,
|
||||
},
|
||||
'install:checkPatches': {
|
||||
|
||||
@@ -38,6 +38,7 @@ export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchem
|
||||
export const FolderSizeSchema = z.object({
|
||||
bytes: z.number(),
|
||||
files: z.number(),
|
||||
linkableBytes: z.number().nonnegative().optional(),
|
||||
});
|
||||
export type FolderSize = z.output<typeof FolderSizeSchema>;
|
||||
|
||||
@@ -94,6 +95,7 @@ const InstallChoicesSchema = z.object({
|
||||
export const InstallRequestSchema = z.discriminatedUnion('method', [
|
||||
InstallChoicesSchema.extend({
|
||||
method: z.literal('copy'),
|
||||
useHardLinks: z.boolean().optional(),
|
||||
/** The War Thunder installation to copy; only read. */
|
||||
sourcePath: z.string().min(1),
|
||||
/** A new or empty folder for the game copy. */
|
||||
@@ -107,7 +109,7 @@ export const InstallRequestSchema = z.discriminatedUnion('method', [
|
||||
]);
|
||||
export type InstallRequest = z.output<typeof InstallRequestSchema>;
|
||||
|
||||
export const INSTALL_PHASES = ['checking', 'measuring', 'copying', 'backing-up', 'recording'] as const;
|
||||
export const INSTALL_PHASES = ['checking', 'measuring', 'verifying', 'copying', 'backing-up', 'recording'] as const;
|
||||
|
||||
export const InstallProgressSchema = z.object({
|
||||
phase: z.enum(INSTALL_PHASES),
|
||||
@@ -137,6 +139,8 @@ export const InstallRecordSchema = z.object({
|
||||
currentSaveId: z.string().regex(/^\d+$/).optional(),
|
||||
/** Relative paths read from the installation source during the last copy or update. */
|
||||
sourceFiles: z.array(z.string().min(1)).optional(),
|
||||
/** Relative resource paths linked to the source and detached on a version update. */
|
||||
hardlinkedFiles: z.array(z.string().min(1)).optional(),
|
||||
});
|
||||
export type InstallRecord = z.output<typeof InstallRecordSchema>;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
import { CopyIdSchema } from './install.ts';
|
||||
|
||||
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'delete']);
|
||||
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete']);
|
||||
export const MaintenanceRequestSchema = z.object({
|
||||
id: CopyIdSchema,
|
||||
operation: MaintenanceOperationSchema,
|
||||
@@ -10,6 +10,7 @@ export const MaintenanceRequestSchema = z.object({
|
||||
export const MaintenanceInfoSchema = z.object({
|
||||
sourceVersion: z.string().nullable(),
|
||||
updateAvailable: z.boolean(),
|
||||
spaceSavingAvailable: z.boolean(),
|
||||
});
|
||||
export const MaintenanceProgressSchema = z.object({
|
||||
id: CopyIdSchema,
|
||||
|
||||
Reference in new issue
Block a user