feat(launcher): support registering existing offline clients without copying

This commit is contained in:
N0VAN0M4LY committed 2026-11-30 19:32:24 +08:00
1 parent 7cb1011f0d
commit cae69a6446
11 files changed
+107 -30

No files matched your search

@@ -3,11 +3,12 @@ import { 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 { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
/**
* Look at a folder the player chose as their War Thunder installation: is it one, which version,
* and is it a Steam library. Only reads.
* whether it already has an offline stock backup, and whether it is inside a Steam library. Only reads.
*/
export async function inspectGameFolder(path: string): Promise<GameFolderInspection> {
await requireFolder(path);
@@ -17,14 +18,26 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
for (const file of required) {
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
}
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
let hasOfflineBackup = true;
for (const file of required) {
if (!(await exists(join(stockRoot, file)))) {
hasOfflineBackup = false;
break;
}
}
const resources = resourcePaths();
const executablePath = hasOfflineBackup
? join(stockRoot, GAME_FILES.executable)
: join(resolved, GAME_FILES.executable);
return {
path,
resolvedPath: resolved,
missingFiles,
version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(resolved, GAME_FILES.executable)),
version: !hasOfflineBackup && missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(executablePath),
verifiedVersions: recordedGameVersions(resources.patches),
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
hasOfflineBackup,
};
}
@@ -88,7 +88,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = request.method === 'in-place' && stock.refresh
const stockBackup = (request.method === 'in-place' || request.method === 'existing') && stock.refresh
? await refreshStockBackup(copyPath)
: await backUpStockFiles(copyPath);
+10 -3
View File
@@ -108,7 +108,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
};
const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-exited', 'game-exited'].includes(launch.phase);
const launchStatus: LaunchState = perCopyStatus && launch.copyId && launch.copyId !== record?.id ? { phase: 'ready' } : launch;
const home = homeBar(record, launchStatus, t, wizard.start, {
const home = homeBar(record, launchStatus, t, () => wizard.start('new'), {
start: () => { ipcInvoke('launch:start').catch(report); },
stop: () => { ipcInvoke('launch:stop').catch(report); },
checkVersion: () => go({ page: 'copies', section: 'features' }),
@@ -166,7 +166,11 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') {
return { side, main: <CopyList registry={registry} supportedVersions={supported} onSelect={selectCopy} onAdd={wizard.start} />, bar: home };
return {
side,
main: <CopyList registry={registry} supportedVersions={supported} onSelect={selectCopy} onAdd={() => wizard.start('new')} onAddExisting={() => wizard.start('existing')} />,
bar: home,
};
}
if (!record) {
return {
@@ -174,7 +178,10 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
main: (
<Sheet title={t(`copies.sections.${route.copies}`)}>
<p className="lead">{t('copies.none')}</p>
<button type="button" className="button button-primary" onClick={wizard.start}>{t('bar.install')}</button>
<div className="copy-list-actions">
<button type="button" className="button button-primary" onClick={() => wizard.start('new')}>{t('bar.install')}</button>
<button type="button" className="button" onClick={() => wizard.start('existing')}>{t('copies.addExisting')}</button>
</div>
</Sheet>
),
bar: home,
@@ -129,6 +129,9 @@
"source": {
"body": "Select the folder where War Thunder is installed.",
"dialogTitle": "Select the War Thunder installation folder",
"existingBody": "Select an existing offline client folder.",
"existingDialogTitle": "Select an existing offline client folder",
"offlineBackupDetected": "An existing offline original-file backup (wtoffline\\stock) was detected. This client can be added directly without copying.",
"notAGame": "The selected folder is not a War Thunder installation. Missing: {{files}}",
"versionVerified": "Game version {{version}} (verified)",
"versionUnverified": "Game version {{version}} has no check record yet. Installing still tries every patch; the patch check shows which features are available.",
@@ -146,7 +149,10 @@
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
"targetTitle": "Select a folder for the copy",
"inPlace": "In-place installation",
"inPlaceBody": "Uses the selected game folder as the copy. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.",
"inPlaceBody": "Uses the selected game folder directly as the client. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.",
"existing": "Add existing client",
"existingBody": "Registers the selected existing game folder directly without copying files. If no original backup exists yet, one will be created in wtoffline\\stock.",
"existingBodyWithBackup": "Registers the existing offline client directly, preserving its wtoffline\\stock original-file backup without copying game files.",
"room": "Free space on target drive: {{free}}",
"noRoom": "Not enough free space: {{needed}} required, {{free}} available on the target drive.",
"problem": {
@@ -200,7 +206,8 @@
"features": "Feature status",
"maintain": "Maintenance"
},
"add": "Add a copy",
"add": "Add a client",
"addExisting": "Add existing client",
"list": { "current": "Current", "select": "Set as current" },
"none": "The offline edition is not installed yet.",
"maintenance": {
@@ -257,7 +264,8 @@
"methods": {
"copy": "Copy installation",
"hardlink": "Space-saving copy",
"in-place": "In-place installation"
"in-place": "In-place installation",
"existing": "Existing client"
},
"stock": "Original file backup",
"stockHint": "Patched files are generated from it at each launch",
@@ -129,6 +129,9 @@
"source": {
"body": "选择已安装的战争雷霆文件夹。",
"dialogTitle": "选择战争雷霆安装文件夹",
"existingBody": "选择已准备好的离线客户端文件夹。",
"existingDialogTitle": "选择已有离线客户端文件夹",
"offlineBackupDetected": "已检测到离线客户端的原版文件备份(wtoffline\\stock),可直接添加,无需重新复制。",
"notAGame": "所选文件夹不是战争雷霆的安装文件夹,缺少:{{files}}",
"versionVerified": "游戏版本 {{version}}(已核对)",
"versionUnverified": "游戏版本 {{version}} 还没有核对记录。安装时仍会逐个尝试全部补丁,可用功能以补丁检查结果为准。",
@@ -146,7 +149,10 @@
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
"targetTitle": "选择存放副本的文件夹",
"inPlace": "原位安装",
"inPlaceBody": "使用所选游戏文件夹作为副本。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。",
"inPlaceBody": "使用所选游戏文件夹作为客户端。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。",
"existing": "添加已有客户端",
"existingBody": "直接登记所选的已有游戏文件夹,不复制游戏文件;如尚未建立原版备份将自动备份至 wtoffline\\stock。",
"existingBodyWithBackup": "直接登记已存在的离线客户端,保留现有的 wtoffline\\stock 原版文件备份,不复制游戏文件。",
"room": "目标磁盘可用空间:{{free}}",
"noRoom": "可用空间不足:需要 {{needed}},目标磁盘仅剩 {{free}}。",
"problem": {
@@ -200,7 +206,8 @@
"features": "功能状态",
"maintain": "维护"
},
"add": "添加副本",
"add": "添加客户端",
"addExisting": "添加已有客户端",
"list": { "current": "当前", "select": "设为当前" },
"none": "尚未安装离线版。",
"maintenance": {
@@ -257,7 +264,8 @@
"methods": {
"copy": "复制安装",
"hardlink": "节省空间的复制",
"in-place": "原位安装"
"in-place": "原位安装",
"existing": "已有客户端"
},
"stock": "原版文件备份",
"stockHint": "每次启动时据此生成补丁文件",
@@ -8,9 +8,10 @@ interface CopyListProps {
readonly supportedVersions: readonly string[];
readonly onSelect: (id: string, detail?: boolean) => void;
readonly onAdd: () => void;
readonly onAddExisting: () => void;
}
export function CopyList({ registry, supportedVersions, onSelect, onAdd }: CopyListProps) {
export function CopyList({ registry, supportedVersions, onSelect, onAdd, onAddExisting }: CopyListProps) {
const { t } = useTranslation();
return (
<Sheet title={t('copies.sections.list')}>
@@ -45,6 +46,7 @@ export function CopyList({ registry, supportedVersions, onSelect, onAdd }: CopyL
);
})}
<button type="button" className="button copy-list-add" onClick={onAdd}>{t('copies.add')}</button>
<button type="button" className="button copy-list-add" onClick={onAddExisting}>{t('copies.addExisting')}</button>
</div>
</Sheet>
);
@@ -34,7 +34,8 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
.then((target) => onChoice((current) => ({ ...current, target, steamConfirmed: false })))
.catch(onError);
};
const folder = choice.method === 'in-place' ? source : choice.target;
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
const folder = directFolder ? source : choice.target;
const steamWarning = folder?.inSteamLibrary
? <SteamWarning method={choice.method} path={folder.resolvedPath} confirmed={choice.steamConfirmed}
onConfirmed={(steamConfirmed) => onChoice({ ...choice, steamConfirmed })} />
@@ -47,8 +48,19 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
</>
);
const savingAvailable = (sourceSize?.linkableBytes ?? 0) > 0;
const existingChoice = (
<Choice
selected={choice.method === 'existing'}
title={t('method.existing')}
body={t(source.hasOfflineBackup ? 'method.existingBodyWithBackup' : 'method.existingBody')}
onSelect={() => choose('existing')}
>
{steamWarning}
</Choice>
);
return (
<>
{source.hasOfflineBackup && existingChoice}
<Choice
selected={choice.method === 'copy'}
title={t('method.copy')}
@@ -78,6 +90,7 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
>
{steamWarning}
</Choice>
{!source.hasOfflineBackup && existingChoice}
</>
);
}
@@ -124,9 +137,10 @@ function TargetVerdict({ target, sourceSize, method }: {
function SteamWarning({ method, path, confirmed, onConfirmed }: { readonly method: Method; readonly path: string; readonly confirmed: boolean; readonly onConfirmed: (confirmed: boolean) => void }) {
const { t } = useTranslation();
const isDirect = method === 'in-place' || method === 'existing';
return (
<Notice tone="warning">
<p>{t(method === 'in-place' ? 'steam.inPlaceWarning' : 'steam.copyWarning')}</p>
<p>{t(isDirect ? 'steam.inPlaceWarning' : 'steam.copyWarning')}</p>
<p className="small">{path}</p>
<label className="check">
<input type="checkbox" checked={confirmed} onChange={(event) => onConfirmed(event.target.checked)} />
@@ -137,13 +151,13 @@ function SteamWarning({ method, path, confirmed, onConfirmed }: { readonly metho
}
function steamLibraryInvolved(source: GameFolderInspection, choice: MethodChoice): boolean {
return choice.method === 'in-place' ? source.inSteamLibrary : (choice.target?.inSteamLibrary ?? false);
return choice.method === 'in-place' || choice.method === 'existing' ? source.inSteamLibrary : (choice.target?.inSteamLibrary ?? false);
}
/** Whether the wizard may go past step 2. */
export function methodUsable(source: GameFolderInspection, sourceSize: FolderSize | null, choice: MethodChoice): boolean {
if (steamLibraryInvolved(source, choice) && !choice.steamConfirmed) return false;
if (choice.method === 'in-place') return true;
if (choice.method === 'in-place' || choice.method === 'existing') return true;
const target = choice.target;
if (!target || target.problem || !sourceSize) return false;
if (choice.method === 'hardlink' && (!target.sameDriveAsStock || !sourceSize.linkableBytes)) return false;
@@ -6,7 +6,10 @@ import { formatBytes } from '../../format.ts';
import { ipcInvoke } from '../../ipc.ts';
import { isVerified } from '../../versions.ts';
import type { WizardMode } from './useInstallWizard.ts';
interface SourceStepProps {
readonly mode: WizardMode;
readonly source: GameFolderInspection | null;
/** Null while the folder is measured. */
readonly sourceSize: FolderSize | null;
@@ -16,7 +19,7 @@ interface SourceStepProps {
}
/** Step 1: the player's War Thunder installation, its version and the adaptation used for it. */
export function SourceStep({ source, sourceSize, supportedVersions, onSource, onError }: SourceStepProps) {
export function SourceStep({ mode, source, sourceSize, supportedVersions, onSource, onError }: SourceStepProps) {
const { t } = useTranslation();
const inspect = (path: string): void => {
onSource(null);
@@ -24,8 +27,13 @@ export function SourceStep({ source, sourceSize, supportedVersions, onSource, on
};
return (
<>
<p className="lead">{t('source.body')}</p>
<FolderField path={source?.path ?? null} dialogTitle={t('source.dialogTitle')} onChosen={inspect} onError={onError} />
<p className="lead">{t(mode === 'existing' ? 'source.existingBody' : 'source.body')}</p>
<FolderField
path={source?.path ?? null}
dialogTitle={t(mode === 'existing' ? 'source.existingDialogTitle' : 'source.dialogTitle')}
onChosen={inspect}
onError={onError}
/>
{source && <SourceVerdict source={source} sourceSize={sourceSize} supportedVersions={supportedVersions} />}
</>
);
@@ -37,11 +45,13 @@ function SourceVerdict({ source, sourceSize, supportedVersions }: { readonly sou
return <Notice tone="error">{t('source.notAGame', { files: source.missingFiles.join(', ') })}</Notice>;
}
const size = sourceSize ? t('source.size', { size: formatBytes(sourceSize.bytes), files: sourceSize.files.toLocaleString() }) : t('source.measuring');
const backupNote = source.hasOfflineBackup ? <p className="small">{t('source.offlineBackupDetected')}</p> : null;
if (isVerified(source.version, supportedVersions)) {
return (
<Notice tone="info">
<p>{t('source.versionVerified', { version: source.version })}</p>
<p className="small">{size}</p>
{backupNote}
</Notice>
);
}
@@ -51,6 +61,7 @@ function SourceVerdict({ source, sourceSize, supportedVersions }: { readonly sou
{t('source.versionUnverified', { version: source.version ?? t('source.versionUnknown') })}
</p>
<p className="small">{size}</p>
{backupNote}
</Notice>
);
}
@@ -15,7 +15,7 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
return (
<Sheet title={t(`wizard.steps.${step}`)} aside={t('wizard.stepOf', { index: wizard.index + 1, total: WIZARD_STEPS.length })}>
{step === 'source' && (
<SourceStep source={source} sourceSize={wizard.sourceSize} supportedVersions={supportedVersions} onSource={wizard.chooseSource} onError={wizard.report} />
<SourceStep mode={wizard.mode} source={source} sourceSize={wizard.sourceSize} supportedVersions={supportedVersions} onSource={wizard.chooseSource} onError={wizard.report} />
)}
{step === 'method' && sourceUsable(source) && (
<>
@@ -8,6 +8,7 @@ import { sourceUsable } from './SourceStep.tsx';
export const WIZARD_STEPS = ['source', 'method', 'data', 'check', 'installing'] as const;
export type WizardStep = (typeof WIZARD_STEPS)[number];
export type WizardMode = 'new' | 'existing';
const NO_CHOICE: MethodChoice = { method: 'copy', target: null, steamConfirmed: false };
@@ -23,6 +24,7 @@ interface WizardOptions {
export function useInstallWizard({ onInstalled }: WizardOptions) {
const { message, report, clear } = useErrorMessage();
const [active, setActive] = useState(false);
const [mode, setMode] = useState<WizardMode>('new');
const [step, setStep] = useState<WizardStep>('source');
const [source, setSource] = useState<GameFolderInspection | null>(null);
const [sourceSize, setSourceSize] = useState<FolderSize | null>(null);
@@ -90,11 +92,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
useEffect(() => ipcOn('event:install-progress', setProgress), []);
const start = (): void => {
const start = (nextMode: WizardMode = 'new'): void => {
clear();
setMode(nextMode);
setStep('source');
setSource(null);
setChoice(NO_CHOICE);
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
setName('');
setDraftId(null);
setDataPath('');
@@ -109,13 +112,15 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
const chooseSource = (found: GameFolderInspection | null): void => {
setSource(found);
setChoice(NO_CHOICE);
const defaultMethod = mode === 'existing' || found?.hasOfflineBackup ? 'existing' : 'copy';
setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
setName(found?.path.split(/[\\/]/).filter(Boolean).at(-1) ?? '');
};
const install = (): void => {
if (!sourceUsable(source) || !draftId || !dataReady) return;
const copyFolder = choice.method === 'in-place' ? source : choice.target;
const directFolder = choice.method === 'in-place' || choice.method === 'existing';
const copyFolder = directFolder ? source : choice.target;
const choices = {
id: draftId, name, dataPath,
...(choice.steamConfirmed && copyFolder ? { confirmedSteamCopyPath: copyFolder.resolvedPath } : {}),
@@ -125,7 +130,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
};
const request: InstallRequest = choice.method === 'in-place'
? { method: 'in-place', gamePath: source.path, ...choices }
: { method: 'copy', useHardLinks: choice.method === 'hardlink', sourcePath: source.path, copyPath: choice.target!.path, ...choices };
: choice.method === 'existing'
? { method: 'existing', gamePath: source.path, ...choices }
: { method: 'copy', useHardLinks: choice.method === 'hardlink', sourcePath: source.path, copyPath: choice.target!.path, ...choices };
clear();
setProgress(null);
setCancelling(false);
@@ -172,7 +179,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
};
return {
active, step, index, source, sourceSize, choice, name, dataPath, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
active, mode, step, index, source, sourceSize, choice, name, dataPath, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
start, back, next, cancel, report, chooseSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
};
+10 -3
View File
@@ -12,6 +12,8 @@ export const GameFolderInspectionSchema = z.object({
verifiedVersions: z.array(z.string()),
/** The folder lies in a Steam library: installing into it needs the player's confirmation. */
inSteamLibrary: z.boolean(),
/** True when the folder already holds a complete wtoffline/stock backup from an offline setup. */
hasOfflineBackup: z.boolean(),
});
export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>;
@@ -74,10 +76,10 @@ export type PatchCheck = z.output<typeof PatchCheckSchema>;
/**
* copy: the stock installation is copied to a new folder and only read.
* in-place: the player's own prepared folder is used as the copy; its stock files are kept in
* the backup folder inside it.
* in-place: the player's own prepared folder is used directly; its stock files are backed up inside it.
* existing: an already prepared offline client folder is registered directly without copying.
*/
export const INSTALL_METHODS = ['copy', 'in-place'] as const;
export const INSTALL_METHODS = ['copy', 'in-place', 'existing'] as const;
export type InstallMethod = (typeof INSTALL_METHODS)[number];
export const CopyIdSchema = z.uuid();
@@ -110,6 +112,11 @@ export const InstallRequestSchema = z.discriminatedUnion('method', [
/** The player's prepared game folder, used as the game copy. */
gamePath: z.string().min(1),
}),
InstallChoicesSchema.extend({
method: z.literal('existing'),
/** An already prepared offline client folder registered directly without copying. */
gamePath: z.string().min(1),
}),
]);
export type InstallRequest = z.output<typeof InstallRequestSchema>;