feat(launcher)!: manage multiple game copies

BREAKING CHANGE: The launcher stores copy registrations in copies.json. Installations recorded only in install.json must be registered again.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:14:41 +08:00
1 parent e41b73aaa3
commit 7d68dc0548
24 files changed
+408 -97

No files matched your search

+20 -3
View File
@@ -8,7 +8,7 @@ import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts';
import { defaultDataPath, readInstallRecord } from '../services/install/install-record.ts';
import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
@@ -54,6 +54,7 @@ export function registerIpcHandlers(): void {
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
});
handle('install:prepareCopy', () => createCopyDraft());
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath));
handle('install:measureFolder', async ({ path }) => {
@@ -67,14 +68,30 @@ export function registerIpcHandlers(): void {
});
handle('install:checkPatches', ({ gamePath, dataPath }) => checkGameFolder(gamePath, dataPath));
handle('install:start', (request) => installGame(request, (progress) => broadcast('event:install-progress', progress)));
handle('install:start', async (request) => {
const record = await installGame(request, (progress) => broadcast('event:install-progress', progress));
broadcast('event:copies-changed', await listCopies());
return record;
});
handle('install:cancel', () => ({ cancelled: cancelInstall() }));
handle('install:getRecord', async () => ({ record: await readInstallRecord(), defaultDataPath: defaultDataPath() }));
handle('install:getRecord', async () => ({ record: await readInstallRecord() }));
handle('install:listFeatures', () => {
const resources = resourcePaths();
return patchFeatures(resources.patches).map((feature) => ({ ...feature, patchIds: [...feature.patchIds] }));
});
handle('copies:list', () => listCopies());
handle('copies:setCurrent', async ({ id }) => {
const registry = await setCurrentCopy(id);
broadcast('event:copies-changed', registry);
return registry;
});
handle('copies:rename', async ({ id, name }) => {
const registry = await renameCopy(id, name);
broadcast('event:copies-changed', registry);
return registry;
});
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => startLaunch((state) => broadcast('event:launch-state', state)));
@@ -5,7 +5,7 @@ import { app, dialog, shell, type BrowserWindow } from 'electron';
import { zipSync } from 'fflate';
import { AppError } from '@shared/errors.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
type ArchiveFiles = Record<string, Uint8Array>;
@@ -35,7 +35,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
const files: ArchiveFiles = {};
const userData = app.getPath('userData');
await addFile(files, 'settings.json', join(userData, 'settings.json'));
await addFile(files, 'install.json', join(userData, 'install.json'));
await addFile(files, COPIES_FILENAME, join(userData, COPIES_FILENAME));
const launcherLogs = launcherLogFolder();
if ((await ifPresent(() => lstat(launcherLogs)))?.isDirectory()) {
for (const name of LAUNCHER_LOG_FILES) {
@@ -4,7 +4,7 @@ import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
import { writeInstallRecord } from './install-record.ts';
import { requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
@@ -67,6 +67,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
const game = await requireGameFolder(gameFolder);
const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
await requireAvailableCopy(request.id, copyPath, request.dataPath);
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
@@ -88,6 +89,9 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = {
id: request.id,
name: request.name,
sourcePath: request.method === 'copy' ? request.sourcePath : null,
method: request.method,
copyPath,
dataPath: request.dataPath,
@@ -1,36 +1,110 @@
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { realpath } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { app } from 'electron';
import { InstallRecordSchema, type InstallRecord } from '@shared/schemas/install.ts';
import { AppError } from '@shared/errors.ts';
import { CopiesSchema, type Copies, type InstallRecord } from '@shared/schemas/install.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
/** The installed game copy, `<user data>/install.json`; null before the first installation. */
export const COPIES_FILENAME = 'copies.json';
const EMPTY: Copies = { formatVersion: 1, current: null, copies: [] };
let pending: Promise<void> = Promise.resolve();
function recordPath(): string {
return join(app.getPath('userData'), 'install.json');
return join(app.getPath('userData'), COPIES_FILENAME);
}
async function readRegistry(): Promise<Copies> {
return CopiesSchema.parse(await readJsonOr(recordPath(), EMPTY));
}
export async function listCopies(): Promise<Copies> {
try {
return await readRegistry();
} catch (error) {
console.warn('[copies] could not read the copy registry:', error);
return EMPTY;
}
}
export async function readInstallRecord(): Promise<InstallRecord | null> {
let raw: unknown;
try {
raw = await readJsonOr(recordPath(), null);
} catch (error) {
console.warn('[install] install.json is unreadable:', error);
return null;
}
if (raw === null) return null;
const parsed = InstallRecordSchema.safeParse(raw);
if (!parsed.success) {
console.warn('[install] install.json did not validate:', parsed.error.issues);
return null;
}
return parsed.data;
const registry = await listCopies();
return registry.copies.find(({ id }) => id === registry.current) ?? null;
}
export function createCopyDraft(): { id: string; dataPath: string } {
const id = randomUUID();
return { id, dataPath: join(app.getPath('userData'), 'copies', id, 'data') };
}
export async function requireAvailableCopy(id: string, copyPath: string, dataPath: string): Promise<void> {
await requireUniquePaths(await readRegistry(), id, copyPath, dataPath);
}
export async function writeInstallRecord(record: InstallRecord): Promise<void> {
await writeJsonAtomic(recordPath(), InstallRecordSchema.parse(record));
await changeRegistry(async (registry) => {
await requireUniquePaths(registry, record.id, record.copyPath, record.dataPath);
return { ...registry, current: record.id, copies: [...registry.copies, record] };
});
}
/** The data folder offered when the player does not choose one. */
export function defaultDataPath(): string {
return join(app.getPath('userData'), 'data');
export function setCurrentCopy(id: string): Promise<Copies> {
return changeRegistry((registry) => {
if (!registry.copies.some((copy) => copy.id === id)) throw new AppError('copy_not_found');
return { ...registry, current: id };
});
}
export function renameCopy(id: string, name: string): Promise<Copies> {
return changeRegistry((registry) => {
if (!registry.copies.some((copy) => copy.id === id)) throw new AppError('copy_not_found');
return { ...registry, copies: registry.copies.map((copy) => copy.id === id ? { ...copy, name } : copy) };
});
}
/** Serialize writes so switching, renaming and completing an installation preserve each other. */
function changeRegistry(change: (registry: Copies) => Promise<Copies> | Copies): Promise<Copies> {
const operation = pending.then(async () => {
try {
const updated = CopiesSchema.parse(await change(await readRegistry()));
await writeJsonAtomic(recordPath(), updated);
return updated;
} catch (error) {
if (error instanceof AppError) throw error;
console.error('[copies] could not update the copy registry:', error);
throw new AppError('copies_write_failed');
}
});
pending = operation.then(() => undefined, () => undefined);
return operation;
}
async function requireUniquePaths(registry: Copies, id: string, copyPath: string, dataPath: string): Promise<void> {
const paths = await Promise.all([canonical(copyPath), canonical(dataPath)]);
for (const existing of registry.copies) {
const used = await Promise.all([canonical(existing.copyPath), canonical(existing.dataPath)]);
if (id === existing.id || paths.some((path) => used.some((other) => overlaps(path, other)))) {
throw new AppError('copy_location_in_use');
}
}
}
function overlaps(left: string, right: string): boolean {
function contains(parent: string, child: string): boolean {
const remainder = relative(parent, child);
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
}
return contains(left, right) || contains(right, left);
}
/** Resolve junctions in a path even when its final folders have yet to be made. */
async function canonical(path: string): Promise<string> {
const absolute = resolve(path);
try {
return await realpath(absolute);
} catch {
const parent = dirname(absolute);
return parent === absolute ? absolute : join(await canonical(parent), relative(parent, absolute));
}
}
@@ -19,6 +19,7 @@ interface LaunchJob {
readonly stop: AbortController;
readonly report: (state: LaunchState) => void;
done: Promise<void>;
copyId?: string;
}
let active: LaunchJob | null = null;
@@ -30,7 +31,7 @@ export function getLaunchState(): LaunchState {
export function startLaunch(report: LaunchJob['report']): LaunchState {
if (active) throw new AppError('launch_busy');
const job = { stop: new AbortController(), report, done: Promise.resolve() };
const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() };
active = job;
update(job, { phase: 'checking' });
job.done = launch(job).catch((error: unknown) => {
@@ -75,14 +76,15 @@ export async function openServerStatus(): Promise<void> {
}
function update(job: LaunchJob, next: LaunchState): void {
state = next;
job.report(next);
state = job.copyId ? { ...next, copyId: job.copyId } : next;
job.report(state);
}
async function launch(job: LaunchJob): Promise<void> {
const signal = job.stop.signal;
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
if (!record) throw new AppError('launch_no_copy');
job.copyId = record.id;
if (!settings.developerMode) throw new AppError('launch_lab_required');
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
const currentVersion = await readVersion(record.copyPath, signal);
+23 -24
View File
@@ -1,13 +1,14 @@
import { useEffect, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import type { IpcOutput } from '@shared/ipc/contract.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { Copies } from '@shared/schemas/install.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import { Sheet } from './components/Sheet.tsx';
import { applyLanguage, resolveLanguage } from './i18n/index.ts';
import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopyList } from './pages/copies/CopyList.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
import { BackgroundSwitch } from './pages/home/BackgroundSwitch.tsx';
@@ -35,8 +36,7 @@ import { useErrorMessage } from './useErrorMessage.ts';
interface AppProps {
readonly info: IpcOutput<'app:getInfo'>;
readonly initialSettings: Settings;
readonly initialRecord: InstallRecord | null;
readonly defaultDataPath: string;
readonly initialCopies: Copies;
}
interface View {
@@ -50,26 +50,22 @@ interface View {
* panel and the main area; the bottom bar belongs to the current task (the install wizard while
* it runs, otherwise install / launch).
*/
export function App({ info, initialSettings, initialRecord, defaultDataPath }: AppProps) {
export function App({ info, initialSettings, initialCopies }: AppProps) {
const { t } = useTranslation();
const { message, report } = useErrorMessage();
const [settings, setSettings] = useState(initialSettings);
const [record, setRecord] = useState(initialRecord);
const [registry, setRegistry] = useState(initialCopies);
const record = registry.copies.find((copy) => copy.id === registry.current) ?? null;
const [launch, setLaunch] = useState<LaunchState>({ phase: 'ready' });
const [route, setRoute] = useState<Route>(START_ROUTE);
const supported = info.supportedGameVersions;
const wizard = useInstallWizard({
defaultDataPath: record?.dataPath ?? defaultDataPath,
onInstalled: (installed) => {
setRecord(installed);
setRoute(START_ROUTE);
},
});
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
const backgrounds = useBackgrounds(record?.copyPath ?? null, settings, report);
useEffect(() => ipcOn('event:settings-changed', setSettings), []);
useEffect(() => ipcOn('event:copies-changed', setRegistry), []);
useEffect(() => applyLanguage(resolveLanguage(settings.language, info.systemLocale)), [settings.language, info.systemLocale]);
useEffect(() => {
@@ -86,7 +82,14 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
}, [report]);
const go = (to: Destination): void => setRoute((current) => navigate(current, to));
const home = homeBar(record, launch, t, wizard.start, {
const selectCopy = (id: string, details = false): void => {
ipcInvoke('copies:setCurrent', { id }).then(() => {
if (details) go({ page: 'copies', section: 'summary' });
}).catch(report);
};
const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-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, {
start: () => { ipcInvoke('launch:start').catch(report); },
stop: () => { ipcInvoke('launch:stop').catch(report); },
checkVersion: () => go({ page: 'copies', section: 'features' }),
@@ -96,7 +99,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
if (wizard.active) {
return { side: <WizardSide step={wizard.step} />, main: <WizardMain wizard={wizard} supportedVersions={supported} />, bar: wizardBar(wizard, t) };
}
const homeSide = <HomeSide record={record} supportedVersions={supported} onNavigate={go} />;
const homeSide = <HomeSide record={record} copies={registry.copies} supportedVersions={supported} onNavigate={go} onSelectCopy={selectCopy} />;
switch (route.page) {
case 'home':
return {
@@ -126,14 +129,10 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
};
}
case 'copies': {
const side = (
<>
<SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />
<div className="side-foot">
<button type="button" className="button" onClick={wizard.start}>{record ? t('copies.reinstall') : t('bar.install')}</button>
</div>
</>
);
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 };
}
if (!record) {
return {
side,
@@ -148,7 +147,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
}
const main = route.copies === 'features'
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
: <CopySummary record={record} supportedVersions={supported} onShowFeatures={() => go({ page: 'copies', section: 'features' })} onReinstall={wizard.start} onError={report} />;
: <CopySummary record={record} supportedVersions={supported} onShowFeatures={() => go({ page: 'copies', section: 'features' })} onError={report} />;
return { side, main, bar: home };
}
}
@@ -165,7 +164,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
{message && <p className="app-error" role="alert">{message}</p>}
</main>
<BottomBar model={view.bar} />
<Footer launcherVersion={info.version} gameVersion={record?.gameVersion ?? null} installed={record !== null} />
<Footer launcherVersion={info.version} gameVersion={record?.gameVersion ?? null} copyName={record?.name ?? null} />
</div>
);
}
@@ -21,7 +21,7 @@
},
"footer": {
"launcher": "Launcher {{version}}",
"game": "Game {{version}}",
"game": "{{name}} · Game {{version}}",
"notInstalled": "Not installed"
},
"home": {
@@ -89,7 +89,7 @@
"change": "Change…"
},
"wizard": {
"title": "Install the offline edition",
"title": "Add a copy",
"steps": {
"source": "Game location",
"method": "Installation type",
@@ -97,7 +97,7 @@
"check": "Patch check",
"installing": "Install"
},
"barTitle": "Install · {{step}}",
"barTitle": "Add a copy · {{step}}",
"stepOf": "Step {{index}} of {{total}}",
"back": "Back",
"next": "Next",
@@ -164,12 +164,17 @@
},
"copies": {
"sections": {
"list": "All copies",
"summary": "Copy details",
"features": "Feature status"
},
"reinstall": "Reinstall…",
"add": "Add a copy",
"list": { "current": "Current", "select": "Set as current" },
"none": "The offline edition is not installed yet.",
"summary": {
"name": "Copy name",
"rename": "Rename",
"source": "Installation source",
"version": "Game version",
"adaptation": "Adaptation",
"adaptationHint": "Selected automatically by game version",
@@ -326,6 +331,9 @@
"internal_error": "An internal launcher error occurred.",
"logs_folder_open_failed": "The launcher log folder could not be opened.",
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
"copy_not_found": "The selected copy is no longer available.",
"copies_write_failed": "The copy registry could not be saved.",
"copy_location_in_use": "The copy or data location overlaps an existing copy.",
"launch_no_copy": "A game copy must be installed before launching.",
"launch_busy": "A launch is already in progress.",
"launch_lab_required": "Enable developer mode to launch through the isolated lab.",
@@ -21,7 +21,7 @@
},
"footer": {
"launcher": "启动器 {{version}}",
"game": "游戏 {{version}}",
"game": "{{name}} · 游戏 {{version}}",
"notInstalled": "未安装"
},
"home": {
@@ -89,7 +89,7 @@
"change": "更改…"
},
"wizard": {
"title": "安装离线版",
"title": "添加副本",
"steps": {
"source": "游戏位置",
"method": "安装方式",
@@ -97,7 +97,7 @@
"check": "补丁检查",
"installing": "安装"
},
"barTitle": "安装 · {{step}}",
"barTitle": "添加副本 · {{step}}",
"stepOf": "第 {{index}} 步,共 {{total}} 步",
"back": "上一步",
"next": "下一步",
@@ -164,12 +164,17 @@
},
"copies": {
"sections": {
"list": "全部副本",
"summary": "副本详情",
"features": "功能状态"
},
"reinstall": "重新安装…",
"add": "添加副本",
"list": { "current": "当前", "select": "设为当前" },
"none": "尚未安装离线版。",
"summary": {
"name": "副本名称",
"rename": "重命名",
"source": "安装来源",
"version": "游戏版本",
"adaptation": "适配版本",
"adaptationHint": "按游戏版本自动选择",
@@ -326,6 +331,9 @@
"internal_error": "启动器内部错误。",
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
"diagnostics_export_failed": "无法保存诊断信息。",
"copy_not_found": "所选副本已不可用。",
"copies_write_failed": "无法保存副本记录。",
"copy_location_in_use": "副本位置或数据目录与已有副本重叠。",
"launch_no_copy": "启动前需要安装游戏副本。",
"launch_busy": "启动流程正在运行。",
"launch_lab_required": "请启用开发模式以通过隔离实验副本启动。",
+2 -2
View File
@@ -12,7 +12,7 @@ import './styles/controls.css';
import './styles/pages.css';
async function start(): Promise<void> {
const [settings, info, install] = await Promise.all([ipcInvoke('settings:get'), ipcInvoke('app:getInfo'), ipcInvoke('install:getRecord')]);
const [settings, info, copies] = await Promise.all([ipcInvoke('settings:get'), ipcInvoke('app:getInfo'), ipcInvoke('copies:list')]);
const language = resolveLanguage(settings.language, info.systemLocale);
await initI18n(language);
document.documentElement.lang = language;
@@ -20,7 +20,7 @@ async function start(): Promise<void> {
if (!root) throw new Error('#root is missing from index.html');
createRoot(root).render(
<StrictMode>
<App info={info} initialSettings={settings} initialRecord={install.record} defaultDataPath={install.defaultDataPath} />
<App info={info} initialSettings={settings} initialCopies={copies} />
</StrictMode>,
);
}
@@ -0,0 +1,47 @@
import { useTranslation } from 'react-i18next';
import type { Copies } from '@shared/schemas/install.ts';
import { Sheet } from '../../components/Sheet.tsx';
import { adaptationFor } from '../../versions.ts';
interface CopyListProps {
readonly registry: Copies;
readonly supportedVersions: readonly string[];
readonly onSelect: (id: string, detail?: boolean) => void;
readonly onAdd: () => void;
}
export function CopyList({ registry, supportedVersions, onSelect, onAdd }: CopyListProps) {
const { t } = useTranslation();
return (
<Sheet title={t('copies.sections.list')}>
{registry.copies.length === 0 && <p className="lead">{t('copies.none')}</p>}
<div className="copy-list">
{registry.copies.map((copy) => {
const current = copy.id === registry.current;
const unknown = t('source.versionUnknown');
return (
<article key={copy.id} className={current ? 'copy-list-card copy-list-current' : 'copy-list-card'}>
<div className="copy-list-heading">
<strong>{copy.name}</strong>
{current && <span className="ok">{t('copies.list.current')}</span>}
</div>
<dl className="kv">
<dt>{t('copies.summary.version')}</dt>
<dd>{copy.gameVersion ?? unknown}</dd>
<dt>{t('copies.summary.adaptation')}</dt>
<dd>{adaptationFor(copy.gameVersion, supportedVersions) ?? unknown}</dd>
<dt>{t('copies.summary.location')}</dt>
<dd className="folder-path" title={copy.copyPath}>{copy.copyPath}</dd>
</dl>
<div className="copy-list-actions">
{!current && <button type="button" className="button button-primary" onClick={() => onSelect(copy.id)}>{t('copies.list.select')}</button>}
<button type="button" className="button" onClick={() => onSelect(copy.id, true)}>{t('side.details')}</button>
</div>
</article>
);
})}
<button type="button" className="button copy-list-add" onClick={onAdd}>{t('copies.add')}</button>
</div>
</Sheet>
);
}
@@ -1,3 +1,4 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { Row } from '../../components/Row.tsx';
@@ -10,13 +11,14 @@ interface CopySummaryProps {
readonly record: InstallRecord;
readonly supportedVersions: readonly string[];
readonly onShowFeatures: () => void;
readonly onReinstall: () => void;
readonly onError: (error: unknown) => void;
}
/** What is installed where: version, adaptation, folders, installation type. */
export function CopySummary({ record, supportedVersions, onShowFeatures, onReinstall, onError }: CopySummaryProps) {
export function CopySummary({ record, supportedVersions, onShowFeatures, onError }: CopySummaryProps) {
const { t, i18n } = useTranslation();
const [name, setName] = useState(record.name);
useEffect(() => setName(record.name), [record.id, record.name]);
const missing = missingFeatures(record).length;
const verified = isVerified(record.gameVersion, supportedVersions);
const folder = (path: string) => (
@@ -26,10 +28,13 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReins
</>
);
return (
<Sheet
title={t('copies.sections.summary')}
foot={<button type="button" className="button" onClick={onReinstall}>{t('copies.reinstall')}</button>}
>
<Sheet title={t('copies.sections.summary')} aside={record.name}>
<Row label={t('copies.summary.name')}>
<input className="input" aria-label={t('copies.summary.name')} value={name} onChange={(event) => setName(event.target.value)} />
<button type="button" className="button" disabled={name.trim().length === 0 || name.trim() === record.name} onClick={() => {
ipcInvoke('copies:rename', { id: record.id, name }).catch(onError);
}}>{t('copies.summary.rename')}</button>
</Row>
<Row label={t('copies.summary.version')}>{record.gameVersion ?? t('source.versionUnknown')}</Row>
<Row label={t('copies.summary.adaptation')} hint={t('copies.summary.adaptationHint')}>
{adaptationFor(record.gameVersion, supportedVersions) ?? t('source.versionUnknown')}
@@ -37,6 +42,7 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReins
</Row>
<Row label={t('copies.summary.location')}>{folder(record.copyPath)}</Row>
<Row label={t('copies.summary.method')}>{t(`copies.summary.methods.${record.method}`)}</Row>
{record.sourcePath && <Row label={t('copies.summary.source')}>{folder(record.sourcePath)}</Row>}
<Row label={t('copies.summary.stock')} hint={t('copies.summary.stockHint')}>{folder(record.stockBackupPath)}</Row>
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
<Row label={t('copies.summary.installedAt')}>{new Date(record.installedAt).toLocaleString(i18n.language)}</Row>
@@ -8,7 +8,7 @@ export function HomeMain({ record }: { readonly record: InstallRecord | null })
return (
<div className="hero">
<div className="hero-kicker">{t('home.installedKicker', { version: record.gameVersion ?? t('source.versionUnknown') })}</div>
<h1 className="hero-title">{t('app.title')}</h1>
<h1 className="hero-title">{record.name}</h1>
</div>
);
}
@@ -1,3 +1,4 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { Destination } from '../../shell/navigation.ts';
@@ -6,13 +7,16 @@ import { missingFeatures } from '../copies/missing-features.ts';
interface HomeSideProps {
readonly record: InstallRecord | null;
readonly copies: readonly InstallRecord[];
readonly onSelectCopy: (id: string) => void;
readonly supportedVersions: readonly string[];
readonly onNavigate: (to: Destination) => void;
}
/** The side panel of the home and about pages: requirements before installation, the current copy after. */
export function HomeSide({ record, supportedVersions, onNavigate }: HomeSideProps) {
export function HomeSide({ record, copies, supportedVersions, onNavigate, onSelectCopy }: HomeSideProps) {
const { t } = useTranslation();
const [choosingCopy, setChoosingCopy] = useState(false);
if (!record) {
return (
<>
@@ -35,10 +39,22 @@ export function HomeSide({ record, supportedVersions, onNavigate }: HomeSideProp
return (
<>
<h3 className="side-heading">{t('side.currentCopy')}</h3>
<div className="copy-card">
<div className="copy-card-name">{t('side.copyName')}</div>
<div className="copy-card-meta" title={record.copyPath}>{record.gameVersion ?? t('source.versionUnknown')} · {record.copyPath}</div>
</div>
<button type="button" className="copy-card copy-card-button" aria-expanded={choosingCopy} onClick={() => setChoosingCopy(!choosingCopy)}>
<span className="copy-card-name">{record.name}</span>
<span className="copy-card-meta" title={record.copyPath}>{record.gameVersion ?? t('source.versionUnknown')} · {record.copyPath}</span>
</button>
{choosingCopy && (
<div className="copy-picker">
{copies.map((copy) => (
<button key={copy.id} type="button" className="button" disabled={copy.id === record.id} onClick={() => {
setChoosingCopy(false);
onSelectCopy(copy.id);
}}>
{copy.name} · {copy.gameVersion ?? t('source.versionUnknown')}
</button>
))}
</div>
)}
<div className="side-block">
<dl className="kv">
<dt>{t('side.adaptation')}</dt>
@@ -1,4 +1,5 @@
import { useTranslation } from 'react-i18next';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { CheckStep } from './CheckStep.tsx';
import { DataStep } from './DataStep.tsx';
@@ -17,7 +18,12 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
<SourceStep source={source} sourceSize={wizard.sourceSize} supportedVersions={supportedVersions} onSource={wizard.chooseSource} onError={wizard.report} />
)}
{step === 'method' && sourceUsable(source) && (
<MethodStep source={source} sourceSize={wizard.sourceSize} choice={wizard.choice} onChoice={wizard.setChoice} onError={wizard.report} />
<>
<Row label={t('copies.summary.name')}>
<input className="input" aria-label={t('copies.summary.name')} value={wizard.name} onChange={(event) => wizard.setName(event.target.value)} />
</Row>
<MethodStep source={source} sourceSize={wizard.sourceSize} choice={wizard.choice} onChoice={wizard.setChoice} onError={wizard.report} />
</>
)}
{step === 'data' && <DataStep dataPath={wizard.dataPath} onDataPath={wizard.setDataPath} onError={wizard.report} />}
{step === 'check' && <CheckStep check={wizard.check} missingAccepted={wizard.missingAccepted} onMissingAccepted={wizard.setMissingAccepted} />}
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import type { FolderSize, GameFolderInspection, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import type { FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { ipcInvoke, ipcOn } from '../../ipc.ts';
import { useErrorMessage } from '../../useErrorMessage.ts';
import { checkUsable } from './CheckStep.tsx';
@@ -12,8 +12,7 @@ export type WizardStep = (typeof WIZARD_STEPS)[number];
const NO_CHOICE: MethodChoice = { method: 'copy', target: null, steamConfirmed: false };
interface WizardOptions {
readonly defaultDataPath: string;
readonly onInstalled: (record: InstallRecord) => void;
readonly onInstalled: () => void;
}
/**
@@ -21,14 +20,16 @@ interface WizardOptions {
* the side panel, the current step in the main area, and back / next in the bottom bar. The work
* is done by the main process over IPC.
*/
export function useInstallWizard({ defaultDataPath, onInstalled }: WizardOptions) {
export function useInstallWizard({ onInstalled }: WizardOptions) {
const { message, report, clear } = useErrorMessage();
const [active, setActive] = useState(false);
const [step, setStep] = useState<WizardStep>('source');
const [source, setSource] = useState<GameFolderInspection | null>(null);
const [sourceSize, setSourceSize] = useState<FolderSize | null>(null);
const [choice, setChoice] = useState<MethodChoice>(NO_CHOICE);
const [dataPath, setDataPath] = useState(defaultDataPath);
const [draftId, setDraftId] = useState<string | null>(null);
const [name, setName] = useState('');
const [dataPath, setDataPath] = useState('');
const [check, setCheck] = useState<PatchCheck | null>(null);
const [missingAccepted, setMissingAccepted] = useState(false);
const [progress, setProgress] = useState<InstallProgress | null>(null);
@@ -70,17 +71,27 @@ export function useInstallWizard({ defaultDataPath, onInstalled }: WizardOptions
const start = (): void => {
clear();
setStep('source');
setSource(null);
setChoice(NO_CHOICE);
setName('');
setDraftId(null);
setDataPath('');
setActive(true);
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
setDraftId(id);
setDataPath(folder);
}).catch(report);
};
const chooseSource = (found: GameFolderInspection | null): void => {
setSource(found);
setChoice(NO_CHOICE);
setName(found?.path.split(/[\\/]/).filter(Boolean).at(-1) ?? '');
};
const install = (): void => {
if (!sourceUsable(source)) return;
const choices = { dataPath, steamLibraryConfirmed: choice.steamConfirmed, missingFeaturesAccepted: missingAccepted };
if (!sourceUsable(source) || !draftId) return;
const choices = { id: draftId, name, dataPath, steamLibraryConfirmed: choice.steamConfirmed, missingFeaturesAccepted: missingAccepted };
const request: InstallRequest = choice.method === 'copy'
? { method: 'copy', sourcePath: source.path, copyPath: choice.target!.path, ...choices }
: { method: 'in-place', gamePath: source.path, ...choices };
@@ -89,9 +100,9 @@ export function useInstallWizard({ defaultDataPath, onInstalled }: WizardOptions
setCancelling(false);
setStep('installing');
ipcInvoke('install:start', request)
.then((record) => {
.then(() => {
setActive(false);
onInstalled(record);
onInstalled();
})
.catch((error: unknown) => {
report(error);
@@ -101,8 +112,8 @@ export function useInstallWizard({ defaultDataPath, onInstalled }: WizardOptions
const canGoOn = ((): boolean => {
switch (step) {
case 'source': return sourceUsable(source);
case 'method': return sourceUsable(source) && methodUsable(source, sourceSize, choice);
case 'source': return draftId !== null && sourceUsable(source);
case 'method': return name.trim().length > 0 && sourceUsable(source) && methodUsable(source, sourceSize, choice);
case 'data': return dataPath.length > 0;
case 'check': return checkUsable(check, missingAccepted);
case 'installing': return false;
@@ -130,8 +141,8 @@ export function useInstallWizard({ defaultDataPath, onInstalled }: WizardOptions
};
return {
active, step, index, source, sourceSize, choice, dataPath, check, missingAccepted, progress, cancelling, message, canGoOn,
start, back, next, cancel, report, chooseSource, setChoice, setDataPath, setMissingAccepted,
active, step, index, source, sourceSize, choice, name, dataPath, check, missingAccepted, progress, cancelling, message, canGoOn,
start, back, next, cancel, report, chooseSource, setChoice, setName, setDataPath, setMissingAccepted,
};
}
@@ -4,17 +4,17 @@ interface FooterProps {
readonly launcherVersion: string;
/** The installed copy's game version; null before installation, or when it is unknown. */
readonly gameVersion: string | null;
readonly installed: boolean;
readonly copyName: string | null;
}
/** Launcher and game versions along the bottom edge. */
export function Footer({ launcherVersion, gameVersion, installed }: FooterProps) {
export function Footer({ launcherVersion, gameVersion, copyName }: FooterProps) {
const { t } = useTranslation();
return (
<footer className="footer">
<span>{t('footer.launcher', { version: launcherVersion })}</span>
<span className="footer-separator">|</span>
<span>{installed ? t('footer.game', { version: gameVersion ?? t('source.versionUnknown') }) : t('footer.notInstalled')}</span>
<span>{copyName ? t('footer.game', { name: copyName, version: gameVersion ?? t('source.versionUnknown') }) : t('footer.notInstalled')}</span>
</footer>
);
}
@@ -6,7 +6,7 @@
export const PAGES = ['home', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number];
export const COPY_SECTIONS = ['summary', 'features'] as const;
export const COPY_SECTIONS = ['list', 'summary', 'features'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
export const SETTINGS_SECTIONS = ['general', 'launch', 'diag', 'dev'] as const;
@@ -18,7 +18,7 @@ export interface Route {
readonly settings: SettingsSection;
}
export const START_ROUTE: Route = { page: 'home', copies: 'summary', settings: 'general' };
export const START_ROUTE: Route = { page: 'home', copies: 'list', settings: 'general' };
/** Where a link points: a page, and for pages with sections, which one. */
export type Destination =
@@ -225,6 +225,66 @@
color: var(--text-dim);
}
/* ===== Copies ===== */
.copy-card-button {
display: block;
min-width: 0;
font: inherit;
color: inherit;
text-align: left;
cursor: pointer;
}
.copy-card-button span {
display: block;
overflow-wrap: anywhere;
}
.copy-picker {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 6px;
max-height: 260px;
margin: 0 20px 12px;
overflow-y: auto;
}
.copy-picker .button {
text-align: left;
white-space: normal;
overflow-wrap: anywhere;
}
.copy-list {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.copy-list-card {
display: grid;
gap: 10px;
padding: 12px;
border: 1px solid var(--line);
background: rgba(0, 0, 0, .14);
overflow-wrap: anywhere;
}
.copy-list-current {
border-color: var(--red);
}
.copy-list-heading, .copy-list-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.copy-list-add {
min-height: 84px;
}
/* ===== About ===== */
.about-head {
display: flex;
@@ -539,6 +539,13 @@
overflow: hidden;
}
.footer span:last-child {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.footer-separator {
opacity: 0.5;
}
+3
View File
@@ -16,6 +16,9 @@ export const APP_ERROR_CODES = [
'settings_write_failed',
'logs_folder_open_failed',
'diagnostics_export_failed',
'copy_not_found',
'copies_write_failed',
'copy_location_in_use',
'launch_no_copy',
'launch_busy',
'launch_lab_required',
+2
View File
@@ -12,6 +12,8 @@ export const IPC_CHANNEL_PREFIXES = [
'dialog:',
/** Installing the offline version: looking at the chosen folders, copying, patching. */
'install:',
/** Listing and managing installed copies. */
'copies:',
/** Starting and stopping the active copy. */
'launch:',
/** The launcher's own settings. */
+21 -1
View File
@@ -1,6 +1,9 @@
import { z } from 'zod';
import { BackgroundPictureSchema } from '../schemas/background.ts';
import {
CopiesSchema,
CopyIdSchema,
CopyNameSchema,
FolderSizeSchema,
GameFolderInspectionSchema,
InstallProgressSchema,
@@ -59,6 +62,10 @@ export const ipcContract = {
/** The chosen folder, or null when the player cancelled. */
output: z.object({ path: z.string().nullable() }),
},
'install:prepareCopy': {
input: z.void(),
output: z.object({ id: CopyIdSchema, dataPath: z.string() }),
},
'install:inspectGameFolder': {
input: z.object({ path: z.string().min(1) }),
output: GameFolderInspectionSchema,
@@ -88,13 +95,25 @@ export const ipcContract = {
},
'install:getRecord': {
input: z.void(),
output: z.object({ record: InstallRecordSchema.nullable(), defaultDataPath: z.string() }),
output: z.object({ record: InstallRecordSchema.nullable() }),
},
'install:listFeatures': {
/** Every feature the patches cover; which of them a copy lacks is in its install record. */
input: z.void(),
output: z.array(PatchFeatureSchema),
},
'copies:list': {
input: z.void(),
output: CopiesSchema,
},
'copies:setCurrent': {
input: z.object({ id: CopyIdSchema }),
output: CopiesSchema,
},
'copies:rename': {
input: z.object({ id: CopyIdSchema, name: CopyNameSchema }),
output: CopiesSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
@@ -137,6 +156,7 @@ export const ipcEvents = {
'event:settings-changed': SettingsSchema,
'event:install-progress': InstallProgressSchema,
'event:launch-state': LaunchStateSchema,
'event:copies-changed': CopiesSchema,
} as const;
export type IpcChannel = keyof typeof ipcContract;
@@ -77,7 +77,12 @@ export type PatchCheck = z.output<typeof PatchCheckSchema>;
export const INSTALL_METHODS = ['copy', 'in-place'] as const;
export type InstallMethod = (typeof INSTALL_METHODS)[number];
export const CopyIdSchema = z.uuid();
export const CopyNameSchema = z.string().trim().min(1);
const InstallChoicesSchema = z.object({
id: CopyIdSchema,
name: CopyNameSchema,
/** Where the local server keeps saves, caches and logs. */
dataPath: z.string().min(1),
/** The player confirmed installing into a Steam library after the warning. */
@@ -115,6 +120,10 @@ export type InstallProgress = z.output<typeof InstallProgressSchema>;
/** What the launcher knows about the installed game copy. */
export const InstallRecordSchema = z.object({
id: CopyIdSchema,
name: CopyNameSchema,
/** Recorded only for a separate source copied during installation. */
sourcePath: z.string().min(1).nullable(),
method: z.enum(INSTALL_METHODS),
copyPath: z.string(),
dataPath: z.string(),
@@ -126,3 +135,14 @@ export const InstallRecordSchema = z.object({
installedAt: z.string(),
});
export type InstallRecord = z.output<typeof InstallRecordSchema>;
export const CopiesSchema = z.object({
formatVersion: z.literal(1),
current: CopyIdSchema.nullable(),
copies: z.array(InstallRecordSchema),
}).refine(({ current, copies }) => {
const ids = new Set(copies.map((copy) => copy.id));
return ids.size === copies.length && (copies.length === 0 ? current === null : current !== null && ids.has(current));
});
export type Copies = z.output<typeof CopiesSchema>;
@@ -6,6 +6,7 @@ export const LaunchStateSchema = z.object({
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
'stopping', 'port-busy', 'version-changed', 'server-exited', 'failed',
]),
copyId: z.uuid().optional(),
port: z.number().int().min(1).max(65535).optional(),
filesWritten: z.number().int().nonnegative().optional(),
filesTotal: z.number().int().nonnegative().optional(),