diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 514c5ff..9f1d3f9 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -9,10 +9,11 @@ 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 { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts'; -import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts'; +import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts'; +import { cancelInstall, checkGameFolder, installGame, installationInProgress } from '../services/install/install-game.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 { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts'; import { changeSaveAccount, changeSaveResearch, createSave, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; @@ -97,9 +98,15 @@ export function registerIpcHandlers(): void { return registry; }); + handle('copies:setDecalSource', async ({ id, path }) => { + if (launchInProgress() || maintenanceInProgress() || installationInProgress()) throw new AppError('maintenance_busy'); + const updated = await changeDecalSource(id, path); + broadcast('event:copies-changed', updated); + return updated; + }); handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id)); handle('copies:maintain', async (request) => { - if (saveWriteInProgress()) throw new AppError('maintenance_busy'); + if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy'); const updated = await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)); broadcast('event:copies-changed', updated); return updated; @@ -138,7 +145,7 @@ export function registerIpcHandlers(): void { handle('launch:getState', () => getLaunchState()); handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); handle('launch:start', () => { - if (maintenanceInProgress() || saveWriteInProgress()) throw new AppError('maintenance_busy'); + if (maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy'); return startLaunch((state) => broadcast('event:launch-state', state)); }); handle('launch:stop', async () => { await stopLaunch(); }); diff --git a/apps/launcher/src/main/services/install/decals.ts b/apps/launcher/src/main/services/install/decals.ts new file mode 100644 index 0000000..c383d80 --- /dev/null +++ b/apps/launcher/src/main/services/install/decals.ts @@ -0,0 +1,103 @@ +import { randomUUID } from 'node:crypto'; +import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises'; +import { dirname, isAbsolute, join, relative } from 'node:path'; +import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import type { Copies } from '@shared/schemas/install.ts'; +import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from './install-record.ts'; + +const CACHE_FOLDER = 'decal-cache'; +let changing = false; + +export function decalImportInProgress(): boolean { + return changing; +} + +export function decalCachePath(dataPath: string, cacheId: string): string { + return join(dataPath, CACHE_FOLDER, cacheId); +} + +async function cacheRoot(dataPath: string): Promise { + if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed'); + const data = await canonicalCopyPath(dataPath); + const root = join(data, CACHE_FOLDER); + if (isInSteamLibrary(data) || relative(root, await canonicalCopyPath(root)) !== '') { + throw new AppError('decal_import_failed'); + } + return root; +} + +/** Import the selected cache as its own snapshot so a later build can use the copy's data alone. */ +export async function importDecalCache( + dataPath: string, sourcePath: string, signal?: AbortSignal, +): Promise { + if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid'); + const source = await realpath(sourcePath).catch(() => null); + if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid'); + + const root = await cacheRoot(dataPath); + if (copyPathContains(source, root) || copyPathContains(root, source)) { + throw new AppError('decal_source_invalid'); + } + const id = randomUUID(); + const target = join(root, id); + try { + await mkdir(root, { recursive: true }); + await cp(source, target, { + recursive: true, + force: false, + errorOnExist: true, + filter: async (path) => { + signal?.throwIfAborted(); + const entry = await lstat(path); + if (!entry.isDirectory() && !entry.isFile()) throw new AppError('decal_source_invalid'); + return true; + }, + }); + signal?.throwIfAborted(); + if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid'); + return id; + } catch (error) { + await discardDecalCache(dataPath, id); + if (signal?.aborted || error instanceof AppError) throw error; + console.error('[decals] could not import the cache:', error); + throw new AppError('decal_import_failed'); + } +} + +export async function discardDecalCache(dataPath: string, id: string): Promise { + try { + const root = await cacheRoot(dataPath); + const target = decalCachePath(dataPath, id); + const actual = await realpath(target).catch(() => null); + if (actual && relative(root, dirname(actual)) === '' && relative(join(root, id), actual) === '') { + await rm(actual, { recursive: true, force: true }); + } + } catch (error) { + console.warn('[decals] could not remove the replaced cache:', error); + } +} + +export async function changeDecalSource(id: string, source: string | null): Promise { + if (changing) throw new AppError('maintenance_busy'); + changing = true; + try { + const record = (await listCopies()).copies.find((copy) => copy.id === id); + if (!record) throw new AppError('copy_not_found'); + const cacheId = source === null ? undefined : await importDecalCache(record.dataPath, source); + let copies: Copies; + try { + copies = await updateCopyRecord(id, (current) => { + const { decalCacheId, ...other } = current; + return cacheId === undefined ? other : { ...other, decalCacheId: cacheId }; + }); + } catch (error) { + if (cacheId) await discardDecalCache(record.dataPath, cacheId); + throw error; + } + if (record.decalCacheId) await discardDecalCache(record.dataPath, record.decalCacheId); + return copies; + } finally { + changing = false; + } +} diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index 52b33dd..3f1bcff 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -1,11 +1,13 @@ import type { BigIntStats } from 'node:fs'; import { access, mkdir } from 'node:fs/promises'; import { join } from 'node:path'; +import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts'; import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts'; +import { discardDecalCache, importDecalCache } from './decals.ts'; import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts'; import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts'; import { checkPatches } from './patch-check.ts'; @@ -91,6 +93,14 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary; if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed'); + if (request.decalSourcePath) { + const dataPath = await canonicalCopyPath(request.dataPath); + if (isInSteamLibrary(dataPath) || + (request.method === 'copy' && copyPathContains(await canonicalCopyPath(gameFolder), dataPath))) { + throw new AppError('decal_import_failed'); + } + } + report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); await mkdir(request.dataPath, { recursive: true }); const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath); @@ -99,30 +109,41 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted'); signal.throwIfAborted(); - const copied = request.method === 'copy' - ? await copyGame(request.sourcePath, copyPath, target!.freeBytes, useHardLinks ? game.version : null, signal, report) - : undefined; + let decalCacheId: string | undefined; + if (request.decalSourcePath) { + report({ phase: 'importing-decals', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); + decalCacheId = await importDecalCache(request.dataPath, request.decalSourcePath, signal); + } + try { + const copied = request.method === 'copy' + ? await copyGame(request.sourcePath, copyPath, target!.freeBytes, useHardLinks ? game.version : null, signal, report) + : undefined; - report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); - const stockBackup = await backUpStockFiles(copyPath); + report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); + const stockBackup = await backUpStockFiles(copyPath); - 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, - stockBackupPath: stockBackup, - gameVersion: game.version, - unavailablePatches: check.unavailable, - installedAt: new Date().toISOString(), - lastCheckedAt: new Date().toISOString(), - ...copied, - }; - await writeInstallRecord(record); - return record; + 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, + stockBackupPath: stockBackup, + gameVersion: game.version, + unavailablePatches: check.unavailable, + installedAt: new Date().toISOString(), + lastCheckedAt: new Date().toISOString(), + ...(decalCacheId ? { decalCacheId } : {}), + ...copied, + }; + await writeInstallRecord(record); + return record; + } catch (error) { + if (decalCacheId) await discardDecalCache(request.dataPath, decalCacheId); + throw error; + } } async function copyGame( diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index 5f6d1d1..1db3d3d 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -7,6 +7,7 @@ import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import { ORDINARY_LAUNCH_ENABLED, type LaunchState } from '@shared/schemas/launch.ts'; import { getSettings } from '../config/settings-store.ts'; +import { decalCachePath } from '../install/decals.ts'; import { copyPathContains, readInstallRecord } from '../install/install-record.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; import { saveBackup } from '../saves/save-archive.ts'; @@ -153,6 +154,7 @@ async function launch(job: LaunchJob): Promise { dataPath, port, ...resourcePaths(), + ...(record.decalCacheId ? { decalCache: decalCachePath(record.dataPath, record.decalCacheId) } : {}), acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), }, signal, (filesWritten, filesTotal, file) => { if (!signal.aborted) update(job, { diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index 4c87af6..592e203 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -8,6 +8,7 @@ export interface BuildRequest { readonly port: number; readonly patches: string; readonly networkHookLibrary: string; + readonly decalCache?: string; readonly acceptedUnavailable: readonly string[]; } diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index f4fa3d1..44896b5 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -1,24 +1,37 @@ -import { readFileSync } from 'node:fs'; +import { readFileSync, realpathSync } from 'node:fs'; +import { relative } from 'node:path'; import type { MessageEvent } from 'electron'; -import { assertWritableCopy, buildGameCopy, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; +import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; import { multiVehiclePackIds } from '@wto/server'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; -let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[] } | null = null; +let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[]; readonly decalCache: string | undefined } | null = null; function send(reply: BuildReply): void { process.parentPort.postMessage(reply); } +function importedDecals(path: string | undefined): string | undefined { + if (!path) return undefined; + try { + const imported = realpathSync(path); + if (relative(path, imported) === '' && !playerDecalCacheProblem(imported)) return imported; + } catch (error) { + console.warn('[build] the imported decal cache is unavailable:', error); + } + return undefined; +} + function build(request: BuildRequest): void { assertWritableCopy(request.stockPath, request.copyPath); + const decalCache = importedDecals(request.decalCache); const result = buildGameCopy({ stock: readStockGameFiles(request.stockPath), patches: request.patches, networkHookLibrary: readFileSync(request.networkHookLibrary), port: request.port, multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), - placeholderDecals: true, + placeholderDecals: decalCache === undefined, }); const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const accepted = new Set(request.acceptedUnavailable); @@ -27,7 +40,7 @@ function build(request: BuildRequest): void { send({ kind: 'failed', error: 'launch_build_unavailable' }); return; } - prepared = { copyPath: request.copyPath, files: result.files }; + prepared = { copyPath: request.copyPath, files: result.files, decalCache }; send({ kind: 'prepared', total: prepared.files.length }); } @@ -39,8 +52,9 @@ process.parentPort.on('message', (event: MessageEvent) => { return; } if (!prepared) throw new Error('No build is ready to write.'); - const { copyPath, files } = prepared; + const { copyPath, files, decalCache } = prepared; prepared = null; + if (decalCache) copyPlayerDecalCache(decalCache, copyPath); for (const [index, file] of files.entries()) { writeGameCopy(copyPath, [file]); send({ kind: 'progress', written: index + 1, total: files.length, file: file.path }); diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index a2acef2..310da35 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -88,6 +88,15 @@ "port-busy": "Port {{port}} is already in use", "server-exited": "The local server exited unexpectedly" }, + "decals": { + "source": "Decal source", + "hint": "Import the game's cache/content folder. The copy uses placeholder decals when no cache is available.", + "choose": "Choose decal cache…", + "useDefault": "Use placeholder decals", + "importing": "Importing decal cache", + "imported": "Imported cache", + "default": "Placeholder decals" + }, "folder": { "none": "Not selected", "choose": "Browse…", @@ -165,6 +174,7 @@ "measuring": "Counting files", "verifying": "Verifying resources to share", "copying": "Copying game files", + "importing-decals": "Importing decal cache", "backing-up": "Backing up original files", "recording": "Finishing installation" }, @@ -597,6 +607,8 @@ "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.", + "decal_source_invalid": "The selected folder does not contain a usable decal cache.", + "decal_import_failed": "The decal cache could not be imported into the copy's data folder. See the launcher log.", "maintenance_busy": "Maintenance requires the game, local server and other copy operations to be stopped.", "maintenance_location": "The operation would affect files outside the registered copy or data folder.", "maintenance_no_update": "A newer version is unavailable at the installation source.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index c7e9877..0e77ef7 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -88,6 +88,15 @@ "port-busy": "端口 {{port}} 已被占用", "server-exited": "本地服务器意外退出" }, + "decals": { + "source": "贴花来源", + "hint": "可导入正版游戏的 cache/content。未导入时使用占位贴花。", + "choose": "选择贴花缓存…", + "useDefault": "使用占位贴花", + "importing": "正在导入贴花缓存", + "imported": "已导入缓存", + "default": "占位贴花" + }, "folder": { "none": "未选择", "choose": "浏览…", @@ -165,6 +174,7 @@ "measuring": "统计文件", "verifying": "核对可共用的资源", "copying": "复制游戏文件", + "importing-decals": "正在导入贴花缓存", "backing-up": "备份原版文件", "recording": "完成安装" }, @@ -597,6 +607,8 @@ "copy_not_found": "所选副本已不可用。", "copies_write_failed": "无法保存副本记录。", "copy_location_in_use": "副本位置或数据目录与已有副本重叠。", + "decal_source_invalid": "选定的目录缺少有效的贴花缓存。", + "decal_import_failed": "无法把贴花缓存导入副本数据目录。请查看启动器日志。", "maintenance_busy": "维护前需结束游戏、本地服务器和其他副本操作。", "maintenance_location": "操作会影响登记的副本或数据目录之外的文件。", "maintenance_no_update": "安装来源没有可用的新版本。", diff --git a/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx b/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx index 759ee1c..dcf1a1c 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx @@ -18,9 +18,22 @@ interface CopySummaryProps { export function CopySummary({ record, supportedVersions, onShowFeatures, onError }: CopySummaryProps) { const { t, i18n } = useTranslation(); const [name, setName] = useState(record.name); + const [importing, setImporting] = useState(false); useEffect(() => setName(record.name), [record.id, record.name]); const missing = missingFeatures(record).length; const verified = isVerified(record.gameVersion, supportedVersions); + const applyDecals = async (chooseFolder: boolean): Promise => { + setImporting(true); + try { + const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null; + if (chooseFolder && path === null) return; + await ipcInvoke('copies:setDecalSource', { id: record.id, path }); + } catch (error) { + onError(error); + } finally { + setImporting(false); + } + }; const folder = (path: string) => ( <> {path} @@ -44,6 +57,17 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onError {record.sourcePath && {folder(record.sourcePath)}} {folder(record.stockBackupPath)} {folder(record.dataPath)} + + {t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')} + + {record.decalCacheId && ( + + )} + {new Date(record.installedAt).toLocaleString(i18n.language)} {missing === 0 ? ( diff --git a/apps/launcher/src/renderer/src/pages/install/DataStep.tsx b/apps/launcher/src/renderer/src/pages/install/DataStep.tsx index 3166b2a..d456e51 100644 --- a/apps/launcher/src/renderer/src/pages/install/DataStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/DataStep.tsx @@ -1,19 +1,26 @@ import { useTranslation } from 'react-i18next'; import { FolderField } from '../../components/FolderField.tsx'; +import { Row } from '../../components/Row.tsx'; interface DataStepProps { readonly dataPath: string; + readonly decalSource: string | null; + readonly onDecalSource: (path: string | null) => void; readonly onDataPath: (path: string) => void; readonly onError: (error: unknown) => void; } /** Step 3: where saves, caches and logs of the offline version are kept. */ -export function DataStep({ dataPath, onDataPath, onError }: DataStepProps) { +export function DataStep({ dataPath, decalSource, onDataPath, onDecalSource, onError }: DataStepProps) { const { t } = useTranslation(); return ( <>

{t('data.body')}

+ + + {decalSource && } + ); } diff --git a/apps/launcher/src/renderer/src/pages/install/ProgressStep.tsx b/apps/launcher/src/renderer/src/pages/install/ProgressStep.tsx index 7072e53..cc5594e 100644 --- a/apps/launcher/src/renderer/src/pages/install/ProgressStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/ProgressStep.tsx @@ -7,13 +7,15 @@ import { formatBytes } from '../../format.ts'; * Step 5: the installation running, phase by phase. Resource verification and copying can be * cancelled from the bottom bar. */ -export function ProgressStep({ progress, useHardLinks }: { +export function ProgressStep({ progress, useHardLinks, importDecals }: { readonly progress: InstallProgress | null; readonly useHardLinks: boolean; + readonly importDecals: boolean; }) { const { t } = useTranslation(); const phase = progress?.phase ?? 'checking'; - const phases: readonly InstallProgress['phase'][] = useHardLinks ? INSTALL_PHASES : INSTALL_PHASES.filter((name) => name !== 'verifying'); + const phases = INSTALL_PHASES.filter((name) => + (useHardLinks || name !== 'verifying') && (importDecals || name !== 'importing-decals')); const current = phases.indexOf(phase); const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null; const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied'; diff --git a/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx b/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx index c7d8814..1a2bcf0 100644 --- a/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx +++ b/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx @@ -25,9 +25,17 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins )} - {step === 'data' && } + {step === 'data' && ( + + )} {step === 'check' && } - {step === 'installing' && } + {step === 'installing' && } {wizard.message &&

{wizard.message}

} ); diff --git a/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts b/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts index f3b131f..20ffb57 100644 --- a/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts +++ b/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts @@ -30,6 +30,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { const [draftId, setDraftId] = useState(null); const [name, setName] = useState(''); const [dataPath, setDataPath] = useState(''); + const [decalSource, setDecalSource] = useState(null); const [check, setCheck] = useState(null); const [missingAccepted, setMissingAccepted] = useState(false); const [progress, setProgress] = useState(null); @@ -76,6 +77,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { setName(''); setDraftId(null); setDataPath(''); + setDecalSource(null); setActive(true); ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => { setDraftId(id); @@ -91,7 +93,11 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { const install = (): void => { if (!sourceUsable(source) || !draftId) return; - const choices = { id: draftId, name, dataPath, steamLibraryConfirmed: choice.steamConfirmed, missingFeaturesAccepted: missingAccepted }; + const choices = { + id: draftId, name, dataPath, + steamLibraryConfirmed: choice.steamConfirmed, missingFeaturesAccepted: missingAccepted, + ...(decalSource ? { decalSourcePath: decalSource } : {}), + }; 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 }; @@ -141,8 +147,8 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { }; return { - active, step, index, source, sourceSize, choice, name, dataPath, check, missingAccepted, progress, cancelling, message, canGoOn, - start, back, next, cancel, report, chooseSource, setChoice, setName, setDataPath, setMissingAccepted, + active, step, index, source, sourceSize, choice, name, dataPath, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn, + start, back, next, cancel, report, chooseSource, setChoice, setName, setDataPath, setDecalSource, setMissingAccepted, }; } diff --git a/apps/launcher/src/renderer/src/pages/install/wizard-bar.ts b/apps/launcher/src/renderer/src/pages/install/wizard-bar.ts index bc91812..d0ea298 100644 --- a/apps/launcher/src/renderer/src/pages/install/wizard-bar.ts +++ b/apps/launcher/src/renderer/src/pages/install/wizard-bar.ts @@ -11,10 +11,11 @@ export function wizardBar(wizard: InstallWizard, t: TFunction): BarModel { if (step === 'installing') { const phase = progress?.phase ?? 'checking'; const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null; + const cancellable = tracking || phase === 'importing-decals'; return { tone: 'busy', title: t(`progress.phase.${phase}`), - detail: tracking ? t('progress.cancelHint') : stepOf, + detail: cancellable ? t('progress.cancelHint') : stepOf, progress: tracking ? { value: progress.doneBytes, @@ -24,7 +25,7 @@ export function wizardBar(wizard: InstallWizard, t: TFunction): BarModel { } : { value: 0, max: null }, primary: { label: t('wizard.installing'), disabled: true }, - ...(tracking ? { secondary: { label: cancelling ? t('progress.cancelling') : t('progress.cancel'), disabled: cancelling, onClick: wizard.cancel } } : {}), + ...(cancellable ? { secondary: { label: cancelling ? t('progress.cancelling') : t('progress.cancel'), disabled: cancelling, onClick: wizard.cancel } } : {}), }; } diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 521c5dd..a0d5f37 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -38,6 +38,8 @@ export const APP_ERROR_CODES = [ 'maintenance_failed', 'maintenance_source_changed', 'copy_location_in_use', + 'decal_source_invalid', + 'decal_import_failed', 'launch_no_copy', 'launch_busy', 'launch_failed', diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 55fff64..d500fdc 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -118,6 +118,10 @@ export const ipcContract = { input: z.object({ id: CopyIdSchema, name: CopyNameSchema }), output: CopiesSchema, }, + 'copies:setDecalSource': { + input: z.object({ id: CopyIdSchema, path: z.string().min(1).nullable() }), + output: CopiesSchema, + }, 'copies:maintenanceInfo': { input: z.object({ id: CopyIdSchema }), output: MaintenanceInfoSchema, diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts index 6b2592d..04acfdb 100644 --- a/apps/launcher/src/shared/schemas/install.ts +++ b/apps/launcher/src/shared/schemas/install.ts @@ -86,6 +86,7 @@ const InstallChoicesSchema = z.object({ name: CopyNameSchema, /** Where the local server keeps saves, caches and logs. */ dataPath: z.string().min(1), + decalSourcePath: z.string().min(1).optional(), /** The player confirmed installing into a Steam library after the warning. */ steamLibraryConfirmed: z.boolean(), /** The player chose to go on without the features of the unavailable patches. */ @@ -109,7 +110,7 @@ export const InstallRequestSchema = z.discriminatedUnion('method', [ ]); export type InstallRequest = z.output; -export const INSTALL_PHASES = ['checking', 'measuring', 'verifying', 'copying', 'backing-up', 'recording'] as const; +export const INSTALL_PHASES = ['checking', 'importing-decals', 'measuring', 'verifying', 'copying', 'backing-up', 'recording'] as const; export const InstallProgressSchema = z.object({ phase: z.enum(INSTALL_PHASES), @@ -137,6 +138,7 @@ export const InstallRecordSchema = z.object({ installedAt: z.string(), lastCheckedAt: z.string().optional(), currentSaveId: z.string().regex(/^\d+$/).optional(), + decalCacheId: z.uuid().optional(), /** Relative paths read from the installation source during the last copy or update. */ sourceFiles: z.array(z.string().min(1)).optional(), /** Relative resource paths linked to the source and detached on a version update. */ diff --git a/packages/patcher/src/decals/player-decal-cache.ts b/packages/patcher/src/decals/player-decal-cache.ts index 8af5b92..27eda57 100644 --- a/packages/patcher/src/decals/player-decal-cache.ts +++ b/packages/patcher/src/decals/player-decal-cache.ts @@ -19,8 +19,8 @@ * With a player source the build leaves the vromfs index (offline-decal-index.ts) out of * char.vromfs.bin, because the client takes the vromfs index first and then skips the web cache. */ -import { cpSync, existsSync, readdirSync, statSync } from 'node:fs'; -import { join, relative, resolve } from 'node:path'; +import { cpSync, existsSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs'; +import { dirname, isAbsolute, join, relative, sep } from 'node:path'; export const WEB_CACHE_FOLDER = join('cache', 'content'); const INDEX_LIST_FILE = 'dldata_s.info'; @@ -34,21 +34,44 @@ export interface PlayerDecalCache { /** Check that the folder looks like an online client's web cache; returns the problem or undefined. */ export function playerDecalCacheProblem(source: string): string | undefined { if (!existsSync(source) || !statSync(source).isDirectory()) return `${source} is not a folder`; - if (!existsSync(join(source, INDEX_LIST_FILE))) return `${source} has no ${INDEX_LIST_FILE} (expected the cache/content folder of an online installation)`; + if (!statSync(join(source, INDEX_LIST_FILE), { throwIfNoEntry: false })?.isFile()) return `${source} has no ${INDEX_LIST_FILE} (expected the cache/content folder of an online installation)`; if (decalIndexes(source).length === 0) return `${source} has no downloadable_decals..blk`; return undefined; } /** Copy the player's web cache folder into /cache/content; the source is only read. */ export function copyPlayerDecalCache(source: string, copyFolder: string): PlayerDecalCache { - const target = join(copyFolder, WEB_CACHE_FOLDER); - const from = resolve(source); - const to = resolve(target); - if (from === to || !relative(from, to).startsWith('..')) throw new Error(`the decal source ${source} contains the game copy's web cache`); - cpSync(from, to, { recursive: true, force: true }); - return { copiedTo: target, decalIndexes: decalIndexes(source) }; + const from = realpathSync(source); + const target = join(realpathSync(copyFolder), WEB_CACHE_FOLDER); + if (contains(from, target) || contains(target, from)) { + throw new Error('The decal source and game copy cache overlap.'); + } + if (lstatSync(dirname(target), { throwIfNoEntry: false })?.isSymbolicLink()) { + throw new Error('The game cache folder is redirected.'); + } + cpSync(from, target, { + recursive: true, + force: true, + filter: (input, output) => { + const entry = lstatSync(input); + const existing = lstatSync(output, { throwIfNoEntry: false }); + if ((!entry.isFile() && !entry.isDirectory()) || existing?.isSymbolicLink() || + (existing?.isFile() && existing.nlink > 1)) { + throw new Error('The decal cache contains a redirected or shared entry.'); + } + return true; + }, + }); + return { copiedTo: target, decalIndexes: decalIndexes(from) }; +} + +function contains(parent: string, child: string): boolean { + const path = relative(parent, child); + return path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path); } function decalIndexes(folder: string): string[] { - return readdirSync(folder).filter((name) => DECALS_INDEX_FILE.test(name)); + return readdirSync(folder, { withFileTypes: true }) + .filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name)) + .map((entry) => entry.name); }