merge: bring main into feat/tank-ai-nav

Takes main's mounted gun traverse limits, capture and hit feedback,
LocalMP air AI sync, mod tech tree insertions and launcher changes.

Conflicts resolved:
- wto_ai_runtime.das: fire update runs before navigation, as on main,
  so a hull-aim request is driven in the same frame; navigation keeps
  the navmesh state and slot arguments of this branch.
- wto_ai_nav_common.das: main's wto_try_hull_aim replaces the old
  limited-traverse pivot and uses this branch's drive command helper
  and stuck-watch reset.
- build.ps1 and local_mp_internal.h: keep both sides' sources and
  declarations.
This commit is contained in:
N0VAN0M4LY committed 2026-12-05 22:14:34 +08:00
commit 77e4806ffc
114 files changed
+4330 -623

No files matched your search

+13 -4
View File
@@ -11,7 +11,7 @@ import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagn
import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts';
import { changeDecalSource, decalImportInProgress, detectDecalCacheSource } from '../services/install/decals.ts';
import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
@@ -32,6 +32,7 @@ import {
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -68,11 +69,18 @@ export function registerIpcHandlers(): void {
BrowserWindow.fromWebContents(sender)?.close();
});
handle('dialog:pickFolder', async ({ title }, sender) => {
handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => {
const window = BrowserWindow.fromWebContents(sender);
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) };
const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath);
const options = {
properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>,
...(title ? { title } : {}),
...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('folder', chosen);
return { path: chosen };
});
handle('install:prepareCopy', () => createCopyDraft());
@@ -156,6 +164,7 @@ export function registerIpcHandlers(): void {
return updated;
});
handle('copies:cancelMaintenance', () => cancelMaintenance());
handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) }));
handle('saves:list', ({ copyId }) => getSaveList(copyId));
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
@@ -7,6 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { readClientMarker, writeClientMarker } from '../install/client-marker.ts';
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
import {
fileHash,
@@ -69,7 +70,7 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted();
return changeCopyFiles(root, async (incoming) => {
const updated = await changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes);
let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
@@ -104,6 +105,13 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
})));
if (!preserveHardlinks && linked.length > 0) {
const marker = await readClientMarker(root);
if (marker?.origin === 'hardlink' || (marker === null && record.method === 'copy')) {
await writeClientMarker(root, 'copy');
}
}
return updated;
}
interface UpdateFilePlan {
@@ -188,7 +196,7 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
const total = candidates.reduce((bytes, file) => bytes + file.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 updated = await changeCopyFiles(root, async (incoming) => {
const replacements: string[] = [];
const unchanged = new Map<string, BigIntStats>();
let checked = 0;
@@ -225,6 +233,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
report('applying', total, total);
return { replace: replacements, remove: [] };
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
await writeClientMarker(root, 'hardlink');
return updated;
}
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
@@ -1,21 +1,29 @@
import { readdir, rm } from 'node:fs/promises';
import { isAbsolute, join, parse, relative } from 'node:path';
import { app } from 'electron';
import { isAbsolute, relative } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { installationInProgress } from '../install/install-game.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import {
canDeleteCopyFiles,
canRestoreStock,
checkedRoot,
failLocation,
removeCopy,
resolveClientOrigin,
withCanonicalSources,
} from './copy-removal.ts';
import { readSource, setCopySource } from './copy-source.ts';
export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts';
let current: {
stop: AbortController;
interruptible: boolean;
@@ -35,9 +43,23 @@ export function cancelMaintenance(): void {
}
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
const record = await requireCopy(id);
const source = await readSource(record);
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
const registry = await listCopies();
const record = registry.copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([
readSource(record),
canonicalCopyPath(record.copyPath),
canonicalCopyPath(record.dataPath),
withCanonicalSources(registry.copies),
]);
const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([
readClientMarker(copyPath),
detectHardlinkedResources(copyPath),
canRestoreStock(record, copyPath),
]);
const clientOrigin = resolveClientOrigin(record, diskMarker);
const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) &&
canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies);
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
return {
@@ -47,6 +69,10 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
clientOrigin,
hasHardlinkedResources,
canDeleteFiles,
canRestoreAndRemove,
};
}
@@ -94,6 +120,19 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
const { id, operation, steamLocations } = request;
const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
if (operation === 'delete') {
return removeCopy(
record,
{
deleteFiles: request.deleteFiles === true,
restoreStock: request.restoreStock === true,
deleteData: request.deleteData === true,
},
signal,
report,
labServerUses,
);
}
const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath);
@@ -101,7 +140,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) {
if (operation !== 'confirm-steam' && needsConfirmation) {
throw new AppError('launch_steam_confirmation_required');
}
@@ -123,9 +162,6 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
return updateFromSource(record, root, signal, report);
case 'compact':
return compactCopy(record, root, signal, report);
case 'delete':
report('applying');
return remove(record, root, request.deleteData);
}
}
@@ -135,42 +171,6 @@ async function requireCopy(id: string): Promise<InstallRecord> {
return record;
}
function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath, true);
const backup = await canonicalCopyPath(record.stockBackupPath);
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
if (relative(expectedBackup, backup) !== '') {
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
}
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (copyPathContains(source, root) || copyPathContains(root, source)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
const root = await canonicalCopyPath(path);
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
const appPath = await canonicalCopyPath(app.getAppPath());
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
}
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
failLocation('folder_is_symlink', { path, root });
}
return root;
}
async function labServerUses(root: string): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab || relative(lab.copyPath, root) !== '') return false;
@@ -183,38 +183,3 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
}));
}
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
return removeCopyRecord(record.id);
}
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
}
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await rm(root, { recursive: true, force: true });
}
if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true });
return removeCopyRecord(record.id);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
await removeExcept(path, kept);
} else {
await rm(path, { recursive: true, force: true });
}
}
}
@@ -0,0 +1,272 @@
import { constants } from 'node:fs';
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
import { app } from 'electron';
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { readClientMarker, type ClientMarker } from '../install/client-marker.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts';
import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning } from '../launch/launch-controller.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import type { Report } from './copy-file-maintenance.ts';
const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const;
export interface RemoveCopyOptions {
readonly deleteFiles: boolean;
readonly restoreStock: boolean;
readonly deleteData: boolean;
}
export function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
/**
* Resolve the effective client origin by preferring a valid on-disk marker while
* keeping in-place registrations conservatively locked as `in-place`.
*/
export function resolveClientOrigin(
record: InstallRecord,
diskMarker: ClientMarker | null,
): ClientOrigin | null {
if (record.method === 'in-place') return 'in-place';
if (diskMarker) return diskMarker.origin;
if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy';
return null;
}
/**
* Only launcher-created copies or existing folders carrying a valid copy/hardlink marker
* outside any Steam library and disjoint from every registered copy's sourcePath may be deleted.
*/
export function canDeleteCopyFiles(
record: InstallRecord,
root: string,
effectiveOrigin: ClientOrigin | null,
allCopies: readonly InstallRecord[] = [],
): boolean {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false;
if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false;
const normalizedRoot = resolve(root);
const normalizedCopyPath = resolve(record.copyPath);
const sources = record.sourcePath
? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)]
: allCopies.map((copy) => copy.sourcePath);
for (const candidate of sources) {
if (!candidate) continue;
const source = resolve(candidate);
if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) {
return false;
}
}
return true;
}
/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */
export async function canRestoreStock(record: InstallRecord, root: string): Promise<boolean> {
try {
const safeRoot = await checkedRoot(record);
const canonicalRoot = await canonicalCopyPath(root);
if (relative(safeRoot, canonicalRoot) !== '') return false;
const backup = await requireStockBackupLocation(safeRoot);
const fsPromises = rawFs().promises;
for (const file of Object.values(GAME_FILES)) {
const stockFile = join(backup, file);
const info = await fileInfo(stockFile);
if (!info?.isFile()) return false;
await fsPromises.access(stockFile, constants.R_OK);
}
return true;
} catch {
return false;
}
}
/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */
export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise<InstallRecord[]> {
return Promise.all(copies.map(async (copy) => (
copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy
)));
}
export async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath, true);
const backup = await canonicalCopyPath(record.stockBackupPath);
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
if (relative(expectedBackup, backup) !== '') {
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
}
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (pathsOverlap(source, root)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
export async function safeFolder(path: string, steamAllowed = false): Promise<string> {
const root = await canonicalCopyPath(path);
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
const appPath = await canonicalCopyPath(app.getAppPath());
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
}
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
failLocation('folder_is_symlink', { path, root });
}
return root;
}
export async function removeCopy(
record: InstallRecord,
options: RemoveCopyOptions,
signal: AbortSignal,
report: Report,
labServerUses: (root: string) => Promise<boolean>,
): Promise<Copies> {
const { deleteFiles, restoreStock, deleteData } = options;
if (deleteFiles && restoreStock) {
failLocation('delete_files_and_restore_stock_conflict', { id: record.id });
}
const canonicalRoot = await canonicalCopyPath(record.copyPath);
if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) {
throw new AppError('maintenance_busy');
}
signal.throwIfAborted();
// Pure list removal touches no files on disk and skips copyPath/stockBackup checks
// so missing, moved, or damaged client registrations can always be removed safely.
if (!deleteFiles && !deleteData && !restoreStock) {
report('applying');
return removeCopyRecord(record.id);
}
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
if ((deleteFiles || deleteData) && copyInSteam) {
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
method: record.method,
copyPath: record.copyPath,
root: canonicalRoot,
});
}
let root = canonicalRoot;
if (deleteFiles) {
const allCopies = (await listCopies()).copies;
const canonicalCopies = await withCanonicalSources(allCopies);
const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot));
if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) ||
!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) {
failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot });
}
root = await checkedRoot(record);
const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root));
if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) ||
!canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) {
failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root });
}
} else if (restoreStock) {
root = await checkedRoot(record);
if (!(await canRestoreStock(record, root))) {
failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath });
}
}
const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
const stockBackup = await canonicalCopyPath(record.stockBackupPath);
if (deleteData) {
const rawRoot = resolve(record.copyPath);
const overlapsSource = source !== null && pathsOverlap(data, source);
const containsCopy = deleteFiles
? relative(data, root) !== '' && copyPathContains(data, root)
: copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup);
if (overlapsSource || containsCopy) {
failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock });
}
}
report('applying');
const fsPromises = rawFs().promises;
if (restoreStock) {
await restoreStockAndCleanOfflineFiles(root, data, deleteData);
} else if (deleteFiles) {
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await fsPromises.rm(root, { recursive: true, force: true });
}
}
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
await fsPromises.rm(data, { recursive: true, force: true });
}
return removeCopyRecord(record.id);
}
/**
* Atomically restore the four stock core files from `wtoffline/stock`, then remove
* only launcher-created hook files and the `wtoffline` folder without touching base game files.
*/
async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise<void> {
const fsPromises = rawFs().promises;
const backup = await requireStockBackupLocation(root);
await changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) {
const sourceFile = join(backup, file);
if (!(await fileInfo(sourceFile))?.isFile()) {
failLocation('stock_backup_source_missing', { root, file, sourceFile });
}
const targetFile = join(incoming, file);
await fsPromises.mkdir(dirname(targetFile), { recursive: true });
await fsPromises.copyFile(sourceFile, targetFile);
}
return { replace: files, remove: [] };
}, async () => undefined);
const exeDir = dirname(GAME_FILES.executable);
for (const name of OFFLINE_HOOK_FILES) {
const hookFile = await stagedPath(root, join(exeDir, name));
const info = await fileInfo(hookFile);
if (info && !info.isDirectory()) {
await fsPromises.rm(hookFile, { force: true });
}
}
const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER));
const wtofflineInfo = await fileInfo(wtofflineFolder);
if (wtofflineInfo?.isDirectory()) {
if (!deleteData && copyPathContains(wtofflineFolder, data)) {
await removeExcept(wtofflineFolder, data);
} else {
await fsPromises.rm(wtofflineFolder, { recursive: true, force: true });
}
}
}
function pathsOverlap(left: string, right: string): boolean {
return copyPathContains(left, right) || copyPathContains(right, left);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
const fsPromises = rawFs().promises;
for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
await removeExcept(path, kept);
} else {
await fsPromises.rm(path, { recursive: true, force: true });
}
}
}
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { GameFolderInspection } from '@shared/schemas/install.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
@@ -61,6 +62,10 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
needsStockSource = hasMarkerFile || liveExePatched;
}
}
const [clientMarker, hasHardlinkedResources] = await Promise.all([
readClientMarker(resolved),
detectHardlinkedResources(resolved),
]);
return {
path,
resolvedPath: resolved,
@@ -70,6 +75,8 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
hasOfflineBackup,
needsStockSource,
clientOrigin: clientMarker?.origin ?? null,
hasHardlinkedResources,
};
}
@@ -0,0 +1,114 @@
import { join } from 'node:path';
import { z } from 'zod';
import { hardlinkResourceRules, isHardlinkableResource } from '@wto/patcher';
import { ClientOriginSchema, type ClientOrigin } from '@shared/schemas/install.ts';
import { writeJsonAtomic } from '../../util/atomic-json.ts';
import { rawFs } from '../../util/raw-fs.ts';
/** Relative path of the self-describing client identity marker inside a client folder. */
export const CLIENT_MARKER_FILE = join('wtoffline', 'client.json');
export const ClientMarkerSchema = z.object({
format: z.literal(1),
origin: ClientOriginSchema,
createdBy: z.literal('wtoffline-launcher'),
createdAt: z.string().min(1),
updatedAt: z.string().min(1).optional(),
});
export type ClientMarker = z.output<typeof ClientMarkerSchema>;
/** Cap on qualifying resource files inspected when sampling for hard links. */
const MAX_RESOURCE_SAMPLES = 64;
export function clientMarkerPath(copyFolder: string): string {
return join(copyFolder, CLIENT_MARKER_FILE);
}
/**
* Safely read and validate `<copyFolder>/wtoffline/client.json`.
* Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing.
*/
export async function readClientMarker(copyFolder: string): Promise<ClientMarker | null> {
try {
const text = await rawFs().promises.readFile(clientMarkerPath(copyFolder), 'utf8');
const parsed = ClientMarkerSchema.safeParse(JSON.parse(text) as unknown);
return parsed.success ? parsed.data : null;
} catch {
return null;
}
}
/**
* Atomically write `<copyFolder>/wtoffline/client.json`.
* Preserves `createdAt` and records `updatedAt` when updating an existing valid marker.
*/
export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise<ClientMarker> {
const existing = await readClientMarker(copyFolder);
const now = new Date().toISOString();
const marker: ClientMarker = existing
? {
format: 1,
origin,
createdBy: 'wtoffline-launcher',
createdAt: existing.createdAt,
updatedAt: now,
}
: {
format: 1,
origin,
createdBy: 'wtoffline-launcher',
createdAt: now,
};
await writeJsonAtomic(clientMarkerPath(copyFolder), marker);
return marker;
}
/**
* Lightweight probe for hard-linked read-only resource packs under allowed content directories.
* Returns `true` as soon as a single qualifying resource reports `nlink >= 2`, or `false` on
* missing/unreadable directories or when no sampled resource is hard-linked.
*/
export async function detectHardlinkedResources(copyFolder: string): Promise<boolean> {
const fsPromises = rawFs().promises;
const rules = hardlinkResourceRules();
const queue: Array<{ absDir: string; relDir: string }> = rules.allowedDirectories.map((dir) => {
const clean = dir.replace(/\/+$/, '');
return { absDir: join(copyFolder, clean), relDir: clean };
});
let sampled = 0;
while (queue.length > 0 && sampled < MAX_RESOURCE_SAMPLES) {
const current = queue.shift()!;
let entries;
try {
entries = await fsPromises.readdir(current.absDir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
const absPath = join(current.absDir, entry.name);
const relPath = `${current.relDir}/${entry.name}`;
if (entry.isDirectory()) {
queue.push({ absDir: absPath, relDir: relPath });
continue;
}
if (!entry.isFile()) continue;
const lower = entry.name.toLowerCase();
if (!rules.allowedExtensions.some((ext) => lower.endsWith(ext))) continue;
try {
const stats = await fsPromises.lstat(absPath);
if (!stats.isFile() || !isHardlinkableResource(relPath, stats.size)) continue;
if (stats.nlink >= 2) return true;
sampled += 1;
if (sampled >= MAX_RESOURCE_SAMPLES) return false;
} catch {
continue;
}
}
}
return false;
}
@@ -68,6 +68,12 @@ export interface CopyPlan {
export interface CopyProgress {
readonly doneBytes: number;
readonly doneFiles: number;
/** Bytes actually written to disk so far (excludes hard-linked files). */
readonly copiedBytes: number;
/** Bytes shared via hard links so far (occupies no extra disk space). */
readonly linkedBytes: number;
/** Number of hard-linked files created so far. */
readonly linkedFiles: number;
}
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
@@ -129,12 +135,19 @@ export async function copyPlannedFiles(
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
let next = 0;
let doneBytes = 0;
let copiedBytes = 0;
let linkedBytes = 0;
let linkedFiles = 0;
let doneFiles = 0;
const emitProgress = (): void => {
// Keep doneBytes aligned with actual bytes written to disk so hard-linked files
// do not inflate copy progress.
onProgress({ doneBytes: copiedBytes, doneFiles, copiedBytes, linkedBytes, linkedFiles });
};
const countBytes = (): Transform => new Transform({
transform(chunk: Buffer, _encoding, callback) {
doneBytes += chunk.length;
onProgress({ doneBytes, doneFiles });
copiedBytes += chunk.length;
emitProgress();
callback(null, chunk);
},
});
@@ -155,7 +168,8 @@ export async function copyPlannedFiles(
if (verified) {
const linked = await linkVerifiedResource(from, to, verified);
linkedTargets?.set(to, linked);
doneBytes += file.bytes;
linkedBytes += file.bytes;
linkedFiles += 1;
} else {
await pipeline(
fs.createReadStream(from),
@@ -168,7 +182,7 @@ export async function copyPlannedFiles(
await fsPromises.utimes(to, modified, modified);
}
doneFiles += 1;
onProgress({ doneBytes, doneFiles });
emitProgress();
}
} catch (error) {
if (!hasError && !stop.signal.aborted && !signal.aborted) {
@@ -1,6 +1,31 @@
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { dirname, join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem } from '@shared/schemas/install.ts';
import { copyPathContains } from './install-record.ts';
import { STOCK_BACKUP_FOLDER } from './stock-backup.ts';
/**
* Validate where the offline data folder sits relative to the client and stock folders.
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
* client folder itself or an ancestor of it would mix game files into the data root.
*/
export function dataFolderProblem(
dataPath: string,
copyPath: string | null,
sourcePath: string | null,
externalStockPath: string | null,
): DataFolderProblem | null {
if (copyPath && (copyPathContains(dataPath, copyPath) ||
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
return 'overlaps_client';
}
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
return 'overlaps_stock';
}
return null;
}
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
export async function requireUnredirectedData(root: string): Promise<void> {
@@ -22,6 +22,25 @@ export function decalCachePath(dataPath: string, cacheId: string): string {
return join(dataPath, CACHE_FOLDER, cacheId);
}
/**
* Read-only check whether a player-chosen or registered folder contains a usable decal cache
* (<game>, <game>/cache, or <game>/cache/content). Returns the canonical cache/content path when
* valid, or null when absent, invalid, or unreadable.
*/
export async function detectDecalCacheSource(folderPath: string): Promise<string | null> {
if (!folderPath || !isAbsolute(folderPath)) return null;
try {
const rawSource = await realpath(folderPath).catch(() => null);
if (!rawSource) return null;
const resolved = resolvePlayerDecalCacheFolder(rawSource);
const canonical = await realpath(resolved).catch(() => null);
if (!canonical) return null;
return playerDecalCacheProblem(canonical) === undefined ? canonical : null;
} catch {
return null;
}
}
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
const data = await canonicalCopyPath(dataPath);
@@ -1,7 +1,11 @@
import { createHash } from 'node:crypto';
import { createReadStream, type BigIntStats } from 'node:fs';
import { link, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { isHardlinkableResource } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallProgress } from '@shared/schemas/install.ts';
import type { CopyPlan } from './copy-game.ts';
export type ResourceMatchResult =
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
@@ -83,3 +87,27 @@ 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;
}
/** Collect and stat every eligible read-only resource pack in `plan` before hard-linking. */
export async function prepareHardlinks(
source: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
const totalBytes = candidates.reduce((total, file) => total + file.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 file of candidates) {
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
if (verified) links.set(file.relativePath, verified);
doneBytes += file.bytes;
doneFiles += 1;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
}
if (!links.size) throw new AppError('hardlink_no_match');
return links;
}
@@ -1,19 +1,21 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path';
import { dirname, isAbsolute, relative } from 'node:path';
import { app } from 'electron';
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import type { ClientOrigin, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
import { requireUnredirectedData } from './data-location.ts';
import { readClientMarker, writeClientMarker } from './client-marker.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
import { dataFolderProblem, requireUnredirectedData } from './data-location.ts';
import { discardDecalCache, importDecalCache } from './decals.ts';
import { statHardlinkResource } from './hardlink-files.ts';
import { prepareHardlinks } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts';
export { dataFolderProblem } from './data-location.ts';
/**
* Install the offline version: check the patches against the player's game,
@@ -101,6 +103,16 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
? await refreshStockBackup(copyPath)
: await backUpStockFiles(copyPath);
// Record launcher-created client origin on disk; never overwrite or fabricate a marker for existing folders.
let detectedOrigin: ClientOrigin | undefined;
if (request.method === 'copy') {
await writeClientMarker(copyPath, useHardLinks ? 'hardlink' : 'copy');
} else if (request.method === 'in-place') {
await writeClientMarker(copyPath, 'in-place');
} else {
detectedOrigin = (await readClientMarker(copyPath))?.origin;
}
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = {
id: request.id,
@@ -116,6 +128,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(),
...(decalCacheId ? { decalCacheId } : {}),
...(detectedOrigin ? { detectedOrigin } : {}),
...copied,
};
await writeInstallRecord(record);
@@ -176,28 +189,6 @@ async function inspectInstallation(request: InstallRequest) {
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
}
/**
* Validate where the offline data folder sits relative to the client and stock folders.
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
* client folder itself or an ancestor of it would mix game files into the data root.
*/
export function dataFolderProblem(
dataPath: string,
copyPath: string | null,
sourcePath: string | null,
externalStockPath: string | null,
): DataFolderProblem | null {
if (copyPath && (copyPathContains(dataPath, copyPath) ||
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
return 'overlaps_client';
}
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
return 'overlaps_stock';
}
return null;
}
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
const stockGame = await requireGameFolder(stockSourcePath);
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
@@ -219,8 +210,10 @@ async function copyGame(
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
const hardlinks = useHardLinks ? await prepareHardlinks(source, 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;
const linkTotalBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
const linkTotalFiles = hardlinks ? hardlinks.size : 0;
const copyTotalBytes = Math.max(0, plan.totalBytes - linkTotalBytes);
const neededBytes = copyTotalBytes + SPARE_BYTES;
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
throw new AppError('hardlink_file_changed');
}
@@ -229,11 +222,26 @@ async function copyGame(
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 });
// Track actual disk-copy bytes in doneBytes/totalBytes so hard-linked resource archives
// do not inflate the progress bar or cause sudden jumps when links are created.
const totals = {
totalBytes: copyTotalBytes > 0 ? copyTotalBytes : plan.files.length,
totalFiles: plan.files.length,
copyTotalBytes,
...(hardlinks ? { linkTotalBytes, linkTotalFiles } : {}),
};
const toProgress = (done: { doneFiles: number; copiedBytes: number; linkedBytes: number; linkedFiles: number }): InstallProgress => ({
phase: 'copying',
doneBytes: copyTotalBytes > 0 ? done.copiedBytes : done.doneFiles,
doneFiles: done.doneFiles,
copiedBytes: done.copiedBytes,
...(hardlinks ? { linkedBytes: done.linkedBytes, linkedFiles: done.linkedFiles } : {}),
...totals,
});
report(toProgress({ doneFiles: 0, copiedBytes: 0, linkedBytes: 0, linkedFiles: 0 }));
try {
await copyPlannedFiles(source, target, plan, signal,
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
(done) => report(toProgress(done)), hardlinks);
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
return {
sourceFiles: plan.files.map((file) => file.relativePath),
@@ -248,29 +256,6 @@ async function copyGame(
}
}
async function prepareHardlinks(
source: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
const totalBytes = candidates.reduce((total, file) => total + file.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 file of candidates) {
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
if (verified) links.set(file.relativePath, verified);
doneBytes += file.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 });
@@ -17,6 +17,7 @@ import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
@@ -236,8 +237,10 @@ export async function exportModPreset(
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const defaultDir = await resolveDialogDefaultPath('mod-preset');
const fileName = `${safeName}.wto-mods-preset.json`;
const dialogOptions = {
defaultPath: `${safeName}.wto-mods-preset.json`,
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
@@ -252,6 +255,7 @@ export async function exportModPreset(
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
await rememberDialogPath('mod-preset', choice.filePath);
return { path: choice.filePath };
}
@@ -260,9 +264,11 @@ export async function importModPreset(
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const defaultPath = await resolveDialogDefaultPath('mod-preset');
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
...(defaultPath ? { defaultPath } : {}),
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
@@ -270,6 +276,7 @@ export async function importModPreset(
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
await rememberDialogPath('mod-preset', choice.filePaths[0]);
let parsedRaw: unknown;
try {
@@ -309,6 +316,7 @@ export async function setModsFolder(copyId: string, folderPath: string | null):
}
}
await updateSettings({ modsFolder: folderPath });
if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath);
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
@@ -6,6 +6,7 @@ import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
@@ -95,15 +96,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
}
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const defaultPath = await resolveDialogDefaultPath('save-archive');
const options = {
properties: ['openFile' as const],
filters: [{ name: 'ZIP', extensions: ['zip'] }],
...(defaultPath ? { defaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : result.filePaths[0] ?? null };
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('save-archive', chosen);
return { path: chosen };
}
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const defaultDir = await resolveDialogDefaultPath('save-archive');
const fileName = `WTOffline-save-${userId}.zip`;
const options = {
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'ZIP', extensions: ['zip'] }],
};
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null };
try {
@@ -113,6 +126,7 @@ export async function exportSave(copyId: string, userId: string, window: Browser
console.error('[saves] could not export the save:', error);
throw new AppError('save_operation_failed');
}
await rememberDialogPath('save-archive', result.filePath);
return { path: result.filePath };
}
@@ -275,9 +289,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId:
}
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
const defaultPath = await resolveDialogDefaultPath('official-backups');
const options = {
properties: ['openFile' as const, 'multiSelections' as const],
filters: [{ name: 'BLK', extensions: ['blk'] }],
...(defaultPath ? { defaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return result.canceled ? [] : result.filePaths;
if (result.canceled || result.filePaths.length === 0) return [];
if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]);
return result.filePaths;
}
export async function previewSelectedBackups(
+171
View File
@@ -0,0 +1,171 @@
import { stat } from 'node:fs/promises';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { readJsonOr, writeJsonAtomic } from './atomic-json.ts';
/**
* Remembers the last directory chosen in native open/save dialogs, keyed by dialog category,
* persisted to `<userData>/dialog-paths.json`. Read/write errors are swallowed so dialog
* behavior is never disrupted.
*/
export type DialogPathCategory =
| 'folder'
| 'save-archive'
| 'official-backups'
| 'mods-folder'
| 'mod-preset';
export interface DialogPathStore {
resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined>;
rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void>;
}
const DIALOG_PATHS_FILENAME = 'dialog-paths.json';
const LAST_KEY = 'last';
const MAX_ANCESTOR_STEPS = 128;
/**
* Resolve `candidate` to an existing directory:
* - If it is an existing directory, return its normalized path.
* - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory.
* - Return `undefined` when no existing ancestor directory can be reached.
*/
export async function resolveExistingDirectory(candidate: string | null | undefined): Promise<string | undefined> {
if (!candidate) return undefined;
const trimmed = candidate.trim();
if (!trimmed || !isAbsolute(trimmed)) return undefined;
let current = resolve(trimmed);
for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) {
try {
const info = await stat(current);
if (info.isDirectory()) return current;
} catch {
// Missing or inaccessible path; continue walking toward the filesystem root.
}
const parent = dirname(current);
if (parent === current) return undefined;
current = parent;
}
return undefined;
}
/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */
export function createDialogPathStore(
resolveStorePath: () => Promise<string | null> | string | null,
): DialogPathStore {
let cached: Map<string, string> | null = null;
let loading: Promise<Map<string, string>> | null = null;
let pending: Promise<void> = Promise.resolve();
async function loadMap(): Promise<Map<string, string>> {
if (cached) return cached;
if (loading) return loading;
loading = (async () => {
const map = new Map<string, string>();
const storePath = await resolveStorePath();
if (storePath) {
try {
const raw = await readJsonOr(storePath, null);
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
if (typeof value === 'string' && value.trim().length > 0) {
map.set(key, value);
}
}
}
} catch (error) {
console.warn('[dialog-paths] failed to read dialog paths:', error);
}
}
cached = map;
return map;
})().finally(() => {
loading = null;
});
return loading;
}
return {
async resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
try {
const explicitDir = await resolveExistingDirectory(explicitPath);
if (explicitDir) return explicitDir;
const map = await loadMap();
const categoryPath = map.get(category);
if (categoryPath) {
const resolved = await resolveExistingDirectory(categoryPath);
if (resolved) return resolved;
}
const lastPath = map.get(LAST_KEY);
if (lastPath && lastPath !== categoryPath) {
const resolved = await resolveExistingDirectory(lastPath);
if (resolved) return resolved;
}
} catch (error) {
console.warn('[dialog-paths] failed to resolve default dialog path:', error);
}
return undefined;
},
async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
const dir = await resolveExistingDirectory(selectedPath);
if (!dir) return;
const operation = pending.then(async () => {
const map = await loadMap();
if (map.get(category) === dir && map.get(LAST_KEY) === dir) return;
map.set(category, dir);
map.set(LAST_KEY, dir);
const storePath = await resolveStorePath();
if (!storePath) return;
try {
await writeJsonAtomic(storePath, Object.fromEntries(map));
} catch (error) {
console.warn('[dialog-paths] failed to save dialog paths:', error);
}
});
pending = operation.then(() => undefined, () => undefined);
await operation;
},
};
}
async function defaultStorePath(): Promise<string | null> {
try {
const mod = await import('electron') as {
readonly app?: { getPath?: (name: 'userData') => string };
readonly default?: { app?: { getPath?: (name: 'userData') => string } };
};
const electronApp = mod.app ?? mod.default?.app;
if (typeof electronApp?.getPath !== 'function') return null;
return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME);
} catch {
return null;
}
}
const defaultStore = createDialogPathStore(defaultStorePath);
export function resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
return defaultStore.resolveDialogDefaultPath(category, explicitPath);
}
export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
return defaultStore.rememberDialogPath(category, selectedPath);
}
@@ -5,16 +5,22 @@ interface FolderFieldProps {
readonly path: string | null;
/** Title of the folder dialog. */
readonly dialogTitle: string;
/** Optional starting directory when no path is chosen yet. */
readonly defaultPath?: string | null | undefined;
readonly disabled?: boolean;
readonly onChosen: (path: string) => void;
readonly onError: (error: unknown) => void;
}
/** A chosen folder and the button that opens the folder dialog. */
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) {
export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) {
const { t } = useTranslation();
const choose = (): void => {
ipcInvoke('dialog:pickFolder', { title: dialogTitle })
const startPath = path ?? defaultPath;
ipcInvoke('dialog:pickFolder', {
title: dialogTitle,
...(startPath ? { defaultPath: startPath } : {}),
})
.then(({ path: chosen }) => {
if (chosen) onChosen(chosen);
})
@@ -97,7 +97,9 @@
},
"decals": {
"source": "Decal source",
"hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
"hint": "Select the online game root folder, cache, or cache/content for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
"autoDetectedNotice": "Online decal cache detected automatically and will be imported during installation. Click the button above if you prefer placeholder decals.",
"importFromSource": "Import from online source",
"choose": "Choose decal cache…",
"useDefault": "Use placeholder decals",
"importing": "Importing decal cache",
@@ -158,7 +160,8 @@
"copy": "Copy installation (recommended)",
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
"spaceSaving": "Space-saving copy",
"spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.",
"spaceSavingBody": "Resource packs are shared with the online client via same-volume hard links, requiring only about {{size}} of additional copying. Windows Explorer Properties counts shared files toward both folders, but only the newly copied files use extra disk space. An in-place update to the online client can change shared files.",
"spaceSavingBreakdown": "Estimated copy: about {{copy}} · Shared via hard links: about {{shared}} (no extra disk space)",
"spaceSavingPending": "Calculating how much space can be saved.",
"spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.",
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
@@ -214,6 +217,8 @@
"recording": "Finishing installation"
},
"copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
"copiedActual": "Copied to disk: {{copied}} / {{copyTotal}} ({{copiedFiles}} / {{copyTotalFiles}} files)",
"linkedShared": "Shared via hard links (no extra space): {{linked}} / {{linkTotal}} ({{linkedFiles}} / {{linkTotalFiles}} resource packs)",
"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",
@@ -258,16 +263,31 @@
"repair": "Repair client",
"repairAction": "Repair",
"repairHint": "Restore the original files from the backup. Game files will be generated again at launch.",
"delete": "Delete client",
"deleteAction": "Delete…",
"deleteHint": "The data folder is kept by default.",
"unlink": "Remove registration",
"unlinkAction": "Remove…",
"unlinkHint": "The launcher keeps the Steam game files and data folder in place.",
"unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.",
"deleteLocation": "Delete the offline client at {{path}}?",
"deleteData": "Also delete the data folder at {{path}}",
"confirm": "Confirm deletion",
"remove": "Remove client",
"removeAction": "Remove…",
"removeCopyHint": "Removes from the launcher list by default without deleting files on disk.",
"removeRestoreHint": "Removes from the launcher list by default; optionally restores original files and removes offline patch files while keeping the base game.",
"removeUnlinkHint": "Removes only from the launcher list without deleting game files on disk.",
"removeSteamHint": "Removes only from the launcher list. Steam game files and the data folder stay in place.",
"removeCopyNotice": "Removes {{path}} from the launcher list. All game files and data on disk are kept by default.",
"removeListOnlyNotice": "Removes {{path}} from the launcher list only. Game files on disk will not be deleted.",
"removeSteamNotice": "Removes {{path}} from the launcher list only. Steam game files and data on disk will not be deleted.",
"originCopy": "Detected client type: full copy (created as an independent copy by the launcher).",
"originHardlink": "Detected client type: space-saving hard-linked copy (read-only resource packs are shared; deleting this copy does not affect the original game folder).",
"originInPlace": "Detected client type: in-place installation (full folder deletion is disabled to protect the base game).",
"originUnknown": "Detected client type: existing folder of unknown origin (no client identity marker found; full folder deletion is disabled for safety).",
"originUnknownHardlinked": "Detected client type: existing folder of unknown origin (hard-linked resources were detected without a client identity marker; full folder deletion is disabled for safety).",
"deleteFiles": "Also delete the client folder at {{path}}",
"deleteHardlinkHint": "Note: This client shares read-only resource packs via hard links; deleting the copy folder will not affect the original game folder.",
"deleteFilesWarning": "This will permanently delete all files in the copied client folder at {{path}}. This action cannot be undone.",
"deleteHardlinkWarning": "This will permanently delete all files in the hard-linked copy folder at {{path}} (the original game folder is unaffected). This action cannot be undone.",
"restoreStock": "Restore original files and remove offline patch files (keep base game)",
"restoreStockHint": "Restores the 4 original core files from wtoffline\\stock and removes wtoffline\\ along with network hook files (wto_ws.dll / wto_ws.cfg / wto_ws.log). No base game files are deleted.",
"deleteData": "Also delete the data folder at {{path}} (contains saves, settings, and logs)",
"openFolder": "Open folder",
"confirmRemove": "Remove from list",
"confirmRestore": "Restore and remove",
"confirmDelete": "Confirm deletion",
"phase": {
"checking": "Checking the client",
"copying": "Copying changed files",
@@ -280,7 +300,7 @@
"repair": "Original files restored.",
"update": "Client updated.",
"compact": "Space-saving conversion complete.",
"delete": "Client deleted.",
"delete": "Client removed.",
"cancelled": "Maintenance cancelled."
}
},
@@ -1118,7 +1138,7 @@
"copy_not_found": "The selected client is no longer available.",
"copies_write_failed": "The client registry could not be saved.",
"copy_location_in_use": "The client or data location overlaps an existing client.",
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose cache/content (or cache).",
"decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose the online game root folder, cache, or cache/content.",
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
"maintenance_location": "The operation would affect files outside the registered client or data folder.",
@@ -97,7 +97,9 @@
},
"decals": {
"source": "贴花来源",
"hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
"hint": "可直接选择在线版游戏根目录、cache 或 cache/content,同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
"autoDetectedNotice": "已自动检测到在线版贴花缓存,安装时将一并导入。如需使用占位贴花,可点击上方按钮取消。",
"importFromSource": "从在线版来源导入",
"choose": "选择贴花缓存…",
"useDefault": "使用占位贴花",
"importing": "正在导入贴花缓存",
@@ -158,7 +160,8 @@
"copy": "复制安装(推荐)",
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
"spaceSaving": "节省空间的复制",
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
"spaceSavingBody": "资源包通过同盘硬链接与在线版共享,仅需额外复制约 {{size}};Windows 资源管理器「属性」会重复统计共享文件大小,实际只占新增复制的磁盘空间。原版就地更新可能改变共享文件。",
"spaceSavingBreakdown": "预计实际复制约 {{copy}} · 硬链接共享约 {{shared}}(不额外占用磁盘空间)",
"spaceSavingPending": "正在估算可节省的空间。",
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
@@ -214,6 +217,8 @@
"recording": "完成安装"
},
"copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
"copiedActual": "实际复制:已复制 {{copied}} / {{copyTotal}}({{copiedFiles}} / {{copyTotalFiles}} 个文件)",
"linkedShared": "硬链接共享(不额外占空间):已链接共享 {{linked}} / {{linkTotal}}({{linkedFiles}} / {{linkTotalFiles}} 个资源包)",
"verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
"prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
"cancelHint": "可随时取消,已复制的文件将被删除",
@@ -258,16 +263,31 @@
"repair": "修复客户端",
"repairAction": "修复",
"repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。",
"delete": "删除客户端",
"deleteAction": "删除…",
"deleteHint": "默认保留数据目录。",
"unlink": "解除登记",
"unlinkAction": "解除登记…",
"unlinkHint": "Steam 游戏文件和数据目录将留在原处。",
"unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。",
"deleteLocation": "确认删除 {{path}} 中的离线客户端?",
"deleteData": "同时删除 {{path}} 中的数据",
"confirm": "确认删除",
"remove": "移除客户端",
"removeAction": "移除…",
"removeCopyHint": "默认仅从启动器列表移除,不会删除磁盘文件。",
"removeRestoreHint": "默认仅从启动器列表移除;也可选还原为原版并清理离线补丁文件(保留游戏本体)。",
"removeUnlinkHint": "仅从启动器列表移除,不会删除磁盘上的游戏文件。",
"removeSteamHint": "仅从启动器列表移除,Steam 游戏文件和数据目录将留在原处。",
"removeCopyNotice": "将从启动器列表移除 {{path}}。默认保留磁盘上的所有游戏文件和数据。",
"removeListOnlyNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的游戏文件。",
"removeSteamNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的 Steam 游戏文件和数据目录。",
"originCopy": "识别结果:完整复制副本(由启动器独立复制创建)。",
"originHardlink": "识别结果:省空间硬链接副本(只读资源包与原版共享,删除副本不会影响原版游戏目录)。",
"originInPlace": "识别结果:原位安装目录(为保护原版游戏本体,不支持直接删除整个文件夹)。",
"originUnknown": "识别结果:未知来源的已有目录(缺少客户端身份标记,为保护游戏文件不支持直接删除整个文件夹)。",
"originUnknownHardlinked": "识别结果:未知来源的已有目录(检测到硬链接资源包,但缺少客户端身份标记;为保护原版目录不支持直接删除整个文件夹)。",
"deleteFiles": "同时删除客户端文件夹 {{path}}",
"deleteHardlinkHint": "提示:此客户端使用同盘硬链接共享资源包,删除副本文件夹不会影响原版游戏目录。",
"deleteFilesWarning": "将永久删除客户端副本文件夹 {{path}} 中的全部文件,此操作无法撤销。",
"deleteHardlinkWarning": "将永久删除硬链接副本文件夹 {{path}} 中的全部文件(不会影响原版游戏目录),此操作无法撤销。",
"restoreStock": "还原为原版并清理离线补丁文件(保留游戏本体)",
"restoreStockHint": "将从 wtoffline\\stock 恢复原版 4 个核心文件,并删除 wtoffline\\ 目录与网络钩子文件(wto_ws.dll / wto_ws.cfg / wto_ws.log),绝不删除其他游戏本体文件。",
"deleteData": "同时删除数据文件夹 {{path}}(包含存档、配置与日志)",
"openFolder": "打开所在文件夹",
"confirmRemove": "从列表移除",
"confirmRestore": "还原并移除",
"confirmDelete": "确认删除",
"phase": {
"checking": "正在检查客户端",
"copying": "正在复制有变化的文件",
@@ -280,7 +300,7 @@
"repair": "原版文件已还原。",
"update": "客户端已更新。",
"compact": "省空间转换已完成。",
"delete": "客户端已删除。",
"delete": "客户端已移除。",
"cancelled": "维护已取消。"
}
},
@@ -1118,7 +1138,7 @@
"copy_not_found": "所选客户端已不可用。",
"copies_write_failed": "无法保存客户端记录。",
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版游戏根目录、cache 或 cache/content。",
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
@@ -20,6 +20,10 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
useEffect(() => {
setRemoval(null);
}, [record.id]);
useEffect(() => {
let mounted = true;
setInfo(null);
@@ -60,7 +64,8 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
busy={busy}
options={removal}
onOptionsChange={setRemoval}
onRemove={(deleteData) => run('delete', { deleteData })}
onRemove={(options) => run('delete', options)}
onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }}
/>
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
@@ -69,44 +69,112 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSour
}
export interface CopyRemovalOptions {
readonly deleteFiles: boolean;
readonly restoreStock: boolean;
readonly deleteData: boolean;
}
interface CopyRemovalProps extends CopyMaintenanceControlsProps {
readonly options: CopyRemovalOptions | null;
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
readonly onRemove: (deleteData: boolean) => void;
readonly onRemove: (options: CopyRemovalOptions) => void;
readonly onOpenFolder: () => void;
}
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) {
function clientOriginNoteKey(info: MaintenanceInfo): string {
if (info.clientOrigin === 'copy') return 'copies.maintenance.originCopy';
if (info.clientOrigin === 'hardlink') return 'copies.maintenance.originHardlink';
if (info.clientOrigin === 'in-place') return 'copies.maintenance.originInPlace';
return info.hasHardlinkedResources
? 'copies.maintenance.originUnknownHardlinked'
: 'copies.maintenance.originUnknown';
}
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove, onOpenFolder }: CopyRemovalProps) {
const { t } = useTranslation();
const steam = info?.steamLocations;
const unlinkOnly = steam?.copyInSteam === true;
const canDeleteData = !unlinkOnly && !steam?.dataInSteam;
const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm');
const copyInSteam = steam?.copyInSteam === true;
const dataInSteam = steam?.dataInSteam === true;
const canDeleteFiles = info?.canDeleteFiles === true;
const isHardlinkCopy = info?.clientOrigin === 'hardlink';
const canRestoreAndRemove = info !== null && !canDeleteFiles && info.canRestoreAndRemove;
const canDeleteData = info !== null && !copyInSteam && !dataInSteam;
const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true;
const willRestoreStock = canRestoreAndRemove && options?.restoreStock === true;
const willDeleteData = canDeleteData && options?.deleteData === true;
const action = t(
willDeleteFiles || willDeleteData
? 'copies.maintenance.confirmDelete'
: willRestoreStock
? 'copies.maintenance.confirmRestore'
: 'copies.maintenance.confirmRemove',
);
const rowHint = copyInSteam
? t('copies.maintenance.removeSteamHint')
: canDeleteFiles
? t('copies.maintenance.removeCopyHint')
: canRestoreAndRemove
? t('copies.maintenance.removeRestoreHint')
: t('copies.maintenance.removeUnlinkHint');
const confirmNotice = copyInSteam
? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath })
: canDeleteFiles
? t('copies.maintenance.removeCopyNotice', { path: record.copyPath })
: t('copies.maintenance.removeListOnlyNotice', { path: record.copyPath });
return (
<>
<Row label={t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.delete')}
hint={t(unlinkOnly ? 'copies.maintenance.unlinkHint' : 'copies.maintenance.deleteHint')}>
<button type="button" className="button" disabled={busy || !info}
onClick={() => onOptionsChange({ deleteData: false })}>
{t(unlinkOnly ? 'copies.maintenance.unlinkAction' : 'copies.maintenance.deleteAction')}
<Row label={t('copies.maintenance.remove')} hint={rowHint}>
<button type="button" className="button" disabled={busy}
onClick={() => onOptionsChange({ deleteFiles: false, restoreStock: false, deleteData: false })}>
{t('copies.maintenance.removeAction')}
</button>
</Row>
{options && (
<section className="maintenance-confirm" role="group" aria-label={action}>
<p>{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}</p>
<p>{confirmNotice}</p>
{info && <p className="small">{t(clientOriginNoteKey(info))}</p>}
{canDeleteFiles && (
<>
<label className="check">
<input type="checkbox" checked={options.deleteFiles} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, deleteFiles: event.target.checked, restoreStock: false })} />
{t('copies.maintenance.deleteFiles', { path: record.copyPath })}
</label>
{isHardlinkCopy && <p className="small">{t('copies.maintenance.deleteHardlinkHint')}</p>}
</>
)}
{willDeleteFiles && (
<Notice tone="warning">
<p>{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}</p>
</Notice>
)}
{canRestoreAndRemove && (
<>
<label className="check">
<input type="checkbox" checked={options.restoreStock} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, restoreStock: event.target.checked, deleteFiles: false })} />
{t('copies.maintenance.restoreStock')}
</label>
<p className="small">{t('copies.maintenance.restoreStockHint')}</p>
</>
)}
{canDeleteData && (
<label className="check">
<input type="checkbox" checked={options.deleteData} disabled={busy}
onChange={(event) => onOptionsChange({ deleteData: event.target.checked })} />
onChange={(event) => onOptionsChange({ ...options, deleteData: event.target.checked })} />
{t('copies.maintenance.deleteData', { path: record.dataPath })}
</label>
)}
<div className="copy-list-actions">
{!canDeleteFiles && (
<button type="button" className="button" disabled={busy || record.folderMissing === true} onClick={onOpenFolder}>
{t('copies.maintenance.openFolder')}
</button>
)}
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={busy} onClick={() => onRemove(canDeleteData && options.deleteData)}>
<button type="button" className="button button-primary" disabled={busy}
onClick={() => onRemove({ deleteFiles: willDeleteFiles, restoreStock: willRestoreStock, deleteData: willDeleteData })}>
{action}
</button>
</div>
@@ -20,13 +20,46 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
const { t, i18n } = useTranslation();
const [name, setName] = useState(record.name);
const [importing, setImporting] = useState(false);
const [detectedSourceDecals, setDetectedSourceDecals] = useState<string | null>(null);
useEffect(() => setName(record.name), [record.id, record.name]);
// Read-only probe of the copy's registered online source for a usable decal cache.
useEffect(() => {
setDetectedSourceDecals(null);
if (!record.sourcePath) return;
let current = true;
ipcInvoke('decals:detectSource', { path: record.sourcePath })
.then(({ path }) => {
if (current) setDetectedSourceDecals(path);
})
.catch(() => {
if (current) setDetectedSourceDecals(null);
});
return () => {
current = false;
};
}, [record.id, record.sourcePath]);
const missing = missingFeatures(record).length;
const verified = isVerified(record.gameVersion, supportedVersions);
const importFromSource = async (): Promise<void> => {
if (!detectedSourceDecals) return;
setImporting(true);
try {
await ipcInvoke('copies:setDecalSource', { id: record.id, path: detectedSourceDecals });
} catch (error) {
onError(error);
} finally {
setImporting(false);
}
};
const applyDecals = async (chooseFolder: boolean): Promise<void> => {
setImporting(true);
try {
const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null;
const path = chooseFolder
? (await ipcInvoke('dialog:pickFolder', {
title: t('decals.choose'),
...(record.sourcePath ? { defaultPath: record.sourcePath } : {}),
})).path
: null;
if (chooseFolder && path === null) return;
await ipcInvoke('copies:setDecalSource', { id: record.id, path });
} catch (error) {
@@ -71,6 +104,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
<Row label={t('decals.source')} hint={t('decals.hint')}>
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
{detectedSourceDecals && (
<button type="button" className="button" disabled={importing} onClick={() => { void importFromSource(); }}>
{t('decals.importFromSource')}
</button>
)}
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
{t('decals.choose')}
</button>
@@ -4,7 +4,10 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
export type MaintenanceOperation = MaintenanceRequest['operation'];
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations' | 'sourcePath'>;
export type MaintenanceOptions = Pick<
IpcInput<'copies:maintain'>,
'deleteFiles' | 'restoreStock' | 'deleteData' | 'steamLocations' | 'sourcePath'
>;
export interface MaintenanceOutcome {
readonly copyId: string;
@@ -8,6 +8,8 @@ interface DataStepProps {
readonly dataPath: string;
readonly dataProblem: DataFolderProblem | null;
readonly decalSource: string | null;
readonly decalAutoDetected: boolean;
readonly defaultDecalPath?: string | null | undefined;
readonly steamDataPath: string | null;
readonly steamDataConfirmed: boolean;
readonly onSteamDataConfirmed: (confirmed: boolean) => void;
@@ -17,7 +19,19 @@ interface DataStepProps {
}
/** Step 3: where saves, caches and logs of the offline version are kept. */
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
export function DataStep({
dataPath,
dataProblem,
decalSource,
decalAutoDetected,
defaultDecalPath,
steamDataPath,
steamDataConfirmed,
onSteamDataConfirmed,
onDataPath,
onDecalSource,
onError,
}: DataStepProps) {
const { t } = useTranslation();
return (
<>
@@ -35,9 +49,16 @@ export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, st
</Notice>
)}
<Row label={t('decals.source')} hint={t('decals.hint')}>
<FolderField path={decalSource} dialogTitle={t('decals.choose')} onChosen={onDecalSource} onError={onError} />
<FolderField
path={decalSource}
defaultPath={defaultDecalPath}
dialogTitle={t('decals.choose')}
onChosen={onDecalSource}
onError={onError}
/>
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
</Row>
{decalAutoDetected && decalSource && <Notice tone="info">{t('decals.autoDetectedNotice')}</Notice>}
</>
);
}
@@ -89,6 +89,14 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
: t('method.spaceSavingPending')}
onSelect={() => choose('hardlink')}
>
{sourceSize && savingAvailable && (
<p className="small">
{t('method.spaceSavingBreakdown', {
copy: formatBytes(bytesToCopy(sourceSize, 'hardlink')),
shared: formatBytes(sourceSize.linkableBytes ?? 0),
})}
</p>
)}
{targetPicker}
</Choice>
<Choice
@@ -19,6 +19,27 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
const current = phases.indexOf(phase);
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
const hardlinkStats = phase === 'copying'
&& useHardLinks
&& progress !== null
&& progress.copiedBytes !== undefined
&& progress.copyTotalBytes !== undefined
&& progress.linkedBytes !== undefined
&& progress.linkTotalBytes !== undefined
&& progress.linkedFiles !== undefined
&& progress.linkTotalFiles !== undefined
&& progress.linkTotalFiles > 0
? {
copiedBytes: progress.copiedBytes,
copyTotalBytes: progress.copyTotalBytes,
linkedBytes: progress.linkedBytes,
linkTotalBytes: progress.linkTotalBytes,
linkedFiles: progress.linkedFiles,
linkTotalFiles: progress.linkTotalFiles,
copiedFiles: Math.max(0, progress.doneFiles - progress.linkedFiles),
copyTotalFiles: Math.max(0, progress.totalFiles - progress.linkTotalFiles),
}
: null;
return (
<>
{phases.map((name, position) => {
@@ -32,14 +53,35 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
})}
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
{tracking && (
<div className="progress-caption">
{t(caption, {
done: formatBytes(progress.doneBytes),
total: formatBytes(progress.totalBytes),
doneFiles: progress.doneFiles.toLocaleString(),
totalFiles: progress.totalFiles.toLocaleString(),
})}
</div>
hardlinkStats ? (
<>
<div className="progress-caption">
{t('progress.copiedActual', {
copied: formatBytes(hardlinkStats.copiedBytes),
copyTotal: formatBytes(hardlinkStats.copyTotalBytes),
copiedFiles: hardlinkStats.copiedFiles.toLocaleString(),
copyTotalFiles: hardlinkStats.copyTotalFiles.toLocaleString(),
})}
</div>
<div className="progress-caption">
{t('progress.linkedShared', {
linked: formatBytes(hardlinkStats.linkedBytes),
linkTotal: formatBytes(hardlinkStats.linkTotalBytes),
linkedFiles: hardlinkStats.linkedFiles.toLocaleString(),
linkTotalFiles: hardlinkStats.linkTotalFiles.toLocaleString(),
})}
</div>
</>
) : (
<div className="progress-caption">
{t(caption, {
done: formatBytes(progress.doneBytes),
total: formatBytes(progress.totalBytes),
doneFiles: progress.doneFiles.toLocaleString(),
totalFiles: progress.totalFiles.toLocaleString(),
})}
</div>
)
)}
</>
);
@@ -44,6 +44,8 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
steamDataConfirmed={wizard.steamDataConfirmed}
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
decalSource={wizard.decalSource}
decalAutoDetected={wizard.decalAutoDetected}
defaultDecalPath={wizard.decalProbePath}
onDataPath={wizard.setDataPath}
onDecalSource={wizard.setDecalSource}
onError={wizard.report}
@@ -40,7 +40,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
problem: DataFolderProblem | null;
confirmed: boolean;
} | null>(null);
const [decalSource, setDecalSource] = useState<string | null>(null);
const [decalSource, setDecalSourceState] = useState<string | null>(null);
const [decalAutoDetected, setDecalAutoDetected] = useState(false);
const [decalManuallyEdited, setDecalManuallyEdited] = useState(false);
const [check, setCheck] = useState<PatchCheck | null>(null);
const [missingAccepted, setMissingAccepted] = useState(false);
const [progress, setProgress] = useState<InstallProgress | null>(null);
@@ -66,8 +68,34 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
? (source?.path ?? null)
: null;
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
const decalProbePath = stockSource?.path ?? source?.path ?? null;
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
// Read-only probe of the player-selected source folder for a usable decal cache.
useEffect(() => {
if (!active || !decalProbePath || decalManuallyEdited) return;
let current = true;
ipcInvoke('decals:detectSource', { path: decalProbePath })
.then(({ path }) => {
if (!current) return;
if (path) {
setDecalSourceState(path);
setDecalAutoDetected(true);
} else {
setDecalSourceState(null);
setDecalAutoDetected(false);
}
})
.catch(() => {
if (!current) return;
setDecalSourceState(null);
setDecalAutoDetected(false);
});
return () => {
current = false;
};
}, [active, decalProbePath, decalManuallyEdited]);
useEffect(() => {
if (!active || !dataPath) return;
let current = true;
@@ -119,6 +147,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
useEffect(() => ipcOn('event:install-progress', setProgress), []);
const resetDecals = (): void => {
setDecalSourceState(null);
setDecalAutoDetected(false);
setDecalManuallyEdited(false);
};
const start = (): void => {
clear();
setMode('new');
@@ -130,7 +164,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
setDraftId(null);
setDataPath('');
setDataInspection(null);
setDecalSource(null);
resetDecals();
setActive(true);
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
setDraftId(id);
@@ -145,11 +179,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
setStockSource(null);
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
setName('');
resetDecals();
};
const chooseSource = (found: GameFolderInspection | null): void => {
setSource(found);
setStockSource(null);
resetDecals();
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
const defaultMethod = isExisting ? 'existing' : 'copy';
setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
@@ -166,6 +202,17 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
}
};
const chooseStockSource = (found: GameFolderInspection | null): void => {
setStockSource(found);
resetDecals();
};
const setDecalSource = (path: string | null): void => {
setDecalSourceState(path);
setDecalAutoDetected(false);
setDecalManuallyEdited(true);
};
const install = (): void => {
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
@@ -230,9 +277,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
};
return {
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, decalAutoDetected, decalProbePath, check, missingAccepted, progress, cancelling, message, canGoOn,
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource: chooseStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
};
}
+2
View File
@@ -14,6 +14,8 @@ export const IPC_CHANNEL_PREFIXES = [
'install:',
/** Listing and managing installed copies. */
'copies:',
/** Read-only detection of decal cache folders in player-selected or registered sources. */
'decals:',
/** Settings shared by the saves of a game copy. */
'tuning:',
/** Additive mods repository, per-copy ordering/toggles, and presets. */
+10 -2
View File
@@ -65,8 +65,11 @@ export const ipcContract = {
output: z.object({ path: z.string().nullable() }),
},
'dialog:pickFolder': {
/** The dialog title, already translated by the window. */
input: z.object({ title: z.string().optional() }),
/** The dialog title, already translated by the window, and an optional starting path. */
input: z.object({
title: z.string().optional(),
defaultPath: z.string().optional(),
}),
/** The chosen folder, or null when the player cancelled. */
output: z.object({ path: z.string().nullable() }),
},
@@ -167,6 +170,11 @@ export const ipcContract = {
input: z.void(),
output: z.void(),
},
'decals:detectSource': {
/** Read-only check for a usable decal cache inside a player-chosen or registered folder. */
input: z.object({ path: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'saves:list': {
input: z.object({ copyId: CopyIdSchema }),
output: SaveListSchema,
@@ -1,5 +1,10 @@
import { z } from 'zod';
/** Self-described origin of an offline client folder recorded in wtoffline/client.json. */
export const CLIENT_ORIGINS = ['copy', 'hardlink', 'in-place'] as const;
export const ClientOriginSchema = z.enum(CLIENT_ORIGINS);
export type ClientOrigin = z.output<typeof ClientOriginSchema>;
/** What the launcher found in a folder the player chose as their War Thunder installation. */
export const GameFolderInspectionSchema = z.object({
path: z.string(),
@@ -16,6 +21,10 @@ export const GameFolderInspectionSchema = z.object({
hasOfflineBackup: z.boolean(),
/** True when the folder is already patched for offline use but lacks a wtoffline/stock backup. */
needsStockSource: z.boolean(),
/** Client origin recorded in wtoffline/client.json when present and valid, or null otherwise. */
clientOrigin: ClientOriginSchema.nullable().optional(),
/** True when at least one eligible read-only resource pack has multiple hard links (nlink >= 2). */
hasHardlinkedResources: z.boolean().optional(),
});
export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>;
@@ -143,6 +152,18 @@ export const InstallProgressSchema = z.object({
totalBytes: z.number(),
doneFiles: z.number(),
totalFiles: z.number(),
/** Actual bytes written to disk during copying (excludes hard-linked files). */
copiedBytes: z.number().nonnegative().optional(),
/** Total bytes planned to be written to disk during copying (excludes hard-linked files). */
copyTotalBytes: z.number().nonnegative().optional(),
/** Bytes shared via hard links so far (occupies no extra disk space). */
linkedBytes: z.number().nonnegative().optional(),
/** Total bytes planned to be shared via hard links. */
linkTotalBytes: z.number().nonnegative().optional(),
/** Number of hard-linked files created so far. */
linkedFiles: z.number().nonnegative().optional(),
/** Total number of files planned to be shared via hard links. */
linkTotalFiles: z.number().nonnegative().optional(),
});
export type InstallProgress = z.output<typeof InstallProgressSchema>;
@@ -173,6 +194,8 @@ export const InstallRecordSchema = z.object({
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(),
/** Client origin read from wtoffline/client.json when registering an existing folder. */
detectedOrigin: ClientOriginSchema.optional(),
/** Runtime check hydrated when listing copies (never persisted to copies.json): true if copyPath or core game files are missing on disk. */
folderMissing: z.boolean().optional(),
});
@@ -1,10 +1,12 @@
import { z } from 'zod';
import { CopyIdSchema } from './install.ts';
import { ClientOriginSchema, CopyIdSchema } from './install.ts';
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']);
export const MaintenanceRequestSchema = z.object({
id: CopyIdSchema,
operation: MaintenanceOperationSchema,
deleteFiles: z.boolean().default(false),
restoreStock: z.boolean().default(false),
deleteData: z.boolean().default(false),
sourcePath: z.string().min(1).optional(),
steamLocations: z.object({
@@ -24,6 +26,10 @@ export const MaintenanceInfoSchema = z.object({
copyInSteam: z.boolean(),
dataInSteam: z.boolean(),
}).nullable(),
clientOrigin: ClientOriginSchema.nullable(),
hasHardlinkedResources: z.boolean(),
canDeleteFiles: z.boolean(),
canRestoreAndRemove: z.boolean(),
});
export const MaintenanceProgressSchema = z.object({
id: CopyIdSchema,