diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 2934ea0..95df0ac 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -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))); diff --git a/apps/launcher/src/main/services/diagnostics/diagnostics.ts b/apps/launcher/src/main/services/diagnostics/diagnostics.ts index 40d9715..9338d97 100644 --- a/apps/launcher/src/main/services/diagnostics/diagnostics.ts +++ b/apps/launcher/src/main/services/diagnostics/diagnostics.ts @@ -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; @@ -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) { diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index 4f51d09..a9cd4d3 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -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, diff --git a/apps/launcher/src/main/services/install/install-record.ts b/apps/launcher/src/main/services/install/install-record.ts index 18507bd..3321f73 100644 --- a/apps/launcher/src/main/services/install/install-record.ts +++ b/apps/launcher/src/main/services/install/install-record.ts @@ -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, `/install.json`; null before the first installation. */ +export const COPIES_FILENAME = 'copies.json'; +const EMPTY: Copies = { formatVersion: 1, current: null, copies: [] }; + +let pending: Promise = Promise.resolve(); function recordPath(): string { - return join(app.getPath('userData'), 'install.json'); + return join(app.getPath('userData'), COPIES_FILENAME); +} + +async function readRegistry(): Promise { + return CopiesSchema.parse(await readJsonOr(recordPath(), EMPTY)); +} + +export async function listCopies(): Promise { + try { + return await readRegistry(); + } catch (error) { + console.warn('[copies] could not read the copy registry:', error); + return EMPTY; + } } export async function readInstallRecord(): Promise { - 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 { + await requireUniquePaths(await readRegistry(), id, copyPath, dataPath); } export async function writeInstallRecord(record: InstallRecord): Promise { - 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 { + 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 { + 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): Promise { + 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 { + 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 { + 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)); + } } diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index b27951e..6421849 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -19,6 +19,7 @@ interface LaunchJob { readonly stop: AbortController; readonly report: (state: LaunchState) => void; done: Promise; + 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 { } 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 { 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); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index 76ece19..ea5fc59 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -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({ phase: 'ready' }); const [route, setRoute] = useState(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: , main: , bar: wizardBar(wizard, t) }; } - const homeSide = ; + const homeSide = ; switch (route.page) { case 'home': return { @@ -126,14 +129,10 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A }; } case 'copies': { - const side = ( - <> - t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} /> -
- -
- - ); + const side = t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />; + if (route.copies === 'list') { + return { side, main: , bar: home }; + } if (!record) { return { side, @@ -148,7 +147,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A } const main = route.copies === 'features' ? - : go({ page: 'copies', section: 'features' })} onReinstall={wizard.start} onError={report} />; + : 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 &&

{message}

} -