diff --git a/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx b/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx index da8e2c2..6003417 100644 --- a/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/OfficialSaveImport.tsx @@ -108,6 +108,9 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport return Number.isNaN(parsed) ? iso : new Date(parsed).toLocaleString(i18n.language); }; + const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'; + const vehicleSeparator = language === 'zh' ? '、' : ', '; + const vehicleLabel = (id: string): string => preview?.vehicleNames[id]?.[language] ?? id; const canImportSelection = options.importSettings || options.unlockVehicles; return ( @@ -190,8 +193,10 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport {preview && (

{t('saves.official.summary', { files: preview.files.length, presets: preview.presets.length, vehicles: preview.vehicles.length })}

- {preview.presets.map((preset, index) =>

{preset.title} · {preset.vehicles.join(', ')}

)} - {preview.omitted.length > 0 &&

{t('saves.official.omitted', { names: preview.omitted.join(', ') })}

} + {preview.presets.map((preset, index) => ( +

{preset.title} · {preset.vehicles.map(vehicleLabel).join(vehicleSeparator)}

+ ))} + {preview.omitted.length > 0 &&

{t('saves.official.omitted', { names: preview.omitted.map(vehicleLabel).join(vehicleSeparator) })}

}
)} {imported &&

{t('saves.official.done')}

} diff --git a/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx b/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx index e7387dc..b7580f0 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx @@ -18,6 +18,10 @@ export function SaveAvatarField({ copyId, avatar, disabled, onError }: SaveAvata const [preview, setPreview] = useState<{ id: string; data: string } | null>(null); const canPreview = choices?.some(({ id }) => id === selected) ?? false; + useEffect(() => { + setSelected(avatar); + }, [avatar]); + useEffect(() => { let mounted = true; ipcInvoke('saves:avatars', { copyId }) diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx index a4ba2d8..b7c4875 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -90,45 +90,46 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag .catch(onError) .finally(() => setSaving(false)); }; - const submitEdits = (event: FormEvent): void => { - event.preventDefault(); - if (!userId) return; - const data = new FormData(event.currentTarget); - const values: CurrencyEdits = {}; - for (const name of CURRENCIES) { - const value = String(data.get(name) ?? '').trim(); - if (value) values[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value); - } - if (Object.keys(values).length === 0) return; - setSaving(true); - setMessage(''); - ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values }) - .then((updated) => { - updateDetails(updated); - setMessage(t('saves.saved')); - }) - .catch(onError) - .finally(() => setSaving(false)); - }; - - const submitAccount = (event: FormEvent): void => { + const submitOverview = (event: FormEvent): void => { event.preventDefault(); if (!details || !userId) return; const data = new FormData(event.currentTarget); + const nick = String(data.get('nick') ?? '').trim(); const days = String(data.get('premiumDays') ?? '').trim(); const avatar = String(data.get('avatar') ?? ''); const level = String(data.get('level') ?? '').trim(); - const edits: AccountEdits = {}; - if (nick !== details.save.nick) edits.nick = nick; - if (avatar && avatar !== details.save.avatar) edits.avatar = avatar; - if (level !== '' && Number(level) !== details.save.level) edits.level = Number(level); - if (days !== '' && Number(days) !== details.save.premiumDays) edits.premiumDays = Number(days); - if (Object.keys(edits).length === 0) return; + const accountEdits: AccountEdits = {}; + if (nick && nick !== details.save.nick) accountEdits.nick = nick; + if (avatar && avatar !== details.save.avatar) accountEdits.avatar = avatar; + if (level !== '' && Number(level) !== details.save.level) accountEdits.level = Number(level); + if (days !== '' && Number(days) !== details.save.premiumDays) accountEdits.premiumDays = Number(days); + + const currencyValues: CurrencyEdits = {}; + for (const name of CURRENCIES) { + const value = String(data.get(name) ?? '').trim(); + if (value) currencyValues[name] = name === 'gjnCents' ? Math.round(Number(value) * 100) : Number(value); + } + + const hasAccount = Object.keys(accountEdits).length > 0; + const hasCurrencies = Object.keys(currencyValues).length > 0; + if (!hasAccount && !hasCurrencies) return; + setSaving(true); setMessage(''); - ipcInvoke('saves:editAccount', { copyId: copy.id, userId, edits }) - .then((updated) => { updateDetails(updated); setMessage(t('saves.saved')); }) + (async () => { + let updated: SaveDetails | null = null; + if (hasAccount) { + updated = await ipcInvoke('saves:editAccount', { copyId: copy.id, userId, edits: accountEdits }); + } + if (hasCurrencies) { + updated = await ipcInvoke('saves:editCurrencies', { copyId: copy.id, userId, values: currencyValues }); + } + if (updated) { + updateDetails(updated); + setMessage(t('saves.saved')); + } + })() .catch(onError) .finally(() => setSaving(false)); }; @@ -238,13 +239,29 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag if (!details) return

{t(userId ? 'saves.loading' : 'saves.empty')}

; const { save } = details; + const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'; + const vehicleSeparator = language === 'zh' ? '、' : ', '; + const overviewKey = JSON.stringify([ + copy.id, + save.userId, + save.nick, + save.avatar, + save.level, + save.premiumDays, + save.currencies?.silverLions, + save.currencies?.goldenEagles, + save.currencies?.gjnCents, + save.currencies?.freeRp, + ]); return ( {section === 'overview' && ( <> {readOnly &&

{t('saves.readOnly')}

} {save.login} -
+ {format.format(save.vehicleCount)} + {format.format(save.battleCount)} + @@ -259,11 +276,6 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag - -
- {format.format(save.vehicleCount)} - {format.format(save.battleCount)} -
{CURRENCIES.map((name) => ( {save.currencies ? format.format(name === 'gjnCents' ? save.currencies[name] / 100 : save.currencies[name]) : '—'} @@ -271,19 +283,31 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag aria-label={t(`saves.${name}`)} disabled={readOnly || saving} /> ))} - - {message &&

{message}

} +
+ + {message &&

{message}

} +
)} {section === 'battles' && ( - details.battles.length === 0 ?

{t('saves.noBattles')}

: details.battles.map((battle) => ( - - {battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')} - {t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })} - {battle.vehicles.join(', ')} - - )) + details.battles.length === 0 ?

{t('saves.noBattles')}

: details.battles.map((battle) => { + const missionText = battle.missionName[language] || battle.mission || battle.mode; + const vehiclesText = battle.vehicleNames.map((entry) => entry[language]).join(vehicleSeparator); + return ( + +
+
+ + {battle.won === null ? '—' : t(battle.won ? 'saves.win' : 'saves.loss')} + + {t('saves.battleRewards', { sl: format.format(battle.silverLions), rp: format.format(battle.researchPoints) })} +
+ {vehiclesText &&
{vehiclesText}
} +
+
+ ); + }) )} {section === 'official' && ( diff --git a/apps/launcher/src/renderer/src/styles/controls.css b/apps/launcher/src/renderer/src/styles/controls.css index bf5409e..fc07c5e 100644 --- a/apps/launcher/src/renderer/src/styles/controls.css +++ b/apps/launcher/src/renderer/src/styles/controls.css @@ -162,6 +162,11 @@ border-top: 0; } +.row-label { + min-width: 0; + overflow-wrap: anywhere; +} + .row-label small { display: block; margin-top: 2px; diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index a00830a..610df00 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -311,6 +311,38 @@ margin-top: 16px; } +.save-overview-actions { + display: flex; + align-items: center; + gap: 12px; + margin-top: 14px; +} + +.save-overview-actions .small { + margin-top: 0; +} + +.battle-row { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.battle-summary { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} + +.battle-vehicles { + font-size: 12.5px; + color: var(--text-dim); + line-height: 1.45; + overflow-wrap: anywhere; +} + /* ===== About ===== */ .update-notes { white-space: pre-line; diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts index 218d103..92fbf1a 100644 --- a/apps/launcher/src/shared/schemas/saves.ts +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -4,10 +4,11 @@ import { CopyIdSchema } from './install.ts'; export const LocalUserIdSchema = z.string().regex(/^\d+$/); export const SaveKeysSchema = z.object({ copyId: CopyIdSchema, userId: LocalUserIdSchema }); +export const LocalizedNameSchema = z.object({ en: z.string(), zh: z.string() }); export const SaveAvatarIdSchema = z.string().regex(/^cardicon_[a-z0-9_]+$/); export const SaveAvatarChoicesSchema = z.array(z.object({ id: SaveAvatarIdSchema, - name: z.object({ en: z.string(), zh: z.string() }), + name: LocalizedNameSchema, })); export type SaveAvatarChoices = z.output; @@ -48,8 +49,10 @@ export const SaveDetailsSchema = z.object({ save: SaveSummarySchema, maxLevel: z.number().int().positive().nullable(), battles: z.array(z.object({ - id: z.string(), time: z.number(), won: z.boolean().nullable(), mission: z.string(), mode: z.string(), - vehicles: z.array(z.string()), silverLions: z.number(), researchPoints: z.number(), + id: z.string(), time: z.number(), won: z.boolean().nullable(), mission: z.string(), + missionName: LocalizedNameSchema, mode: z.string(), + vehicles: z.array(z.string()), vehicleNames: z.array(LocalizedNameSchema), + silverLions: z.number(), researchPoints: z.number(), })), owned: z.array(z.string()), research: z.array(z.object({ name: z.string(), points: z.number() })), @@ -87,6 +90,7 @@ export const OfficialPreviewSchema = z.object({ files: z.array(z.object({ name: z.string(), version: z.number().int() })), presets: z.array(z.object({ country: z.string(), title: z.string(), vehicles: z.array(z.string()) })), vehicles: z.array(z.string()), + vehicleNames: z.record(z.string(), LocalizedNameSchema), omitted: z.array(z.string()), }); export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) }); diff --git a/apps/server/src/game-data/datasets/dataset-cache.ts b/apps/server/src/game-data/datasets/dataset-cache.ts index 9abafa8..09a5098 100644 --- a/apps/server/src/game-data/datasets/dataset-cache.ts +++ b/apps/server/src/game-data/datasets/dataset-cache.ts @@ -162,5 +162,12 @@ function readEntry(path: string): CacheEntry | undefined { } function writeEntry(path: string, entry: CacheEntry): void { - writeFileAtomic(path, JSON.stringify(entry)); + try { + writeFileAtomic(path, JSON.stringify(entry)); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + // Another worker updating the same cache file on Windows can hold a brief lock; reading stays valid. + if (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') return; + throw error; + } } diff --git a/apps/server/src/saves/import/official-backup.ts b/apps/server/src/saves/import/official-backup.ts index a527c19..ba431dc 100644 --- a/apps/server/src/saves/import/official-backup.ts +++ b/apps/server/src/saves/import/official-backup.ts @@ -18,6 +18,7 @@ import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.t import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts'; import { loadTuning } from '../../tuning/tuning.ts'; import type { SaveLocation } from '../save-editor.ts'; +import { loadSaveLabels, localizeVehicleName } from '../save-labels.ts'; import { readBackupBlk } from './backup-blk.ts'; const TYPES = { @@ -152,12 +153,17 @@ function prepare(location: SaveLocation, paths: readonly string[]) { const presetVehicles = [...presetReferenced].filter((name) => known.has(name)).sort(); const omitted = [...presetReferenced].filter((name) => !known.has(name)).sort(); + const labels = loadSaveLabels(location.dataFolder, location.gameFolder); + const vehicleNames = Object.fromEntries( + [...presetReferenced].map((name) => [name, localizeVehicleName(name, labels)]), + ); return { files, presets, presetVehicles, known, gameFiles, datasets, preview: { files: files.map(({ name, version }) => ({ name, version })), presets: presets.map(({ country, title, units }) => ({ country, title, vehicles: units.map(({ vehicle }) => vehicle) })), vehicles: presetVehicles, + vehicleNames, omitted, }, }; diff --git a/apps/server/src/saves/save-editor.ts b/apps/server/src/saves/save-editor.ts index a9c18d7..2317996 100644 --- a/apps/server/src/saves/save-editor.ts +++ b/apps/server/src/saves/save-editor.ts @@ -18,6 +18,7 @@ import { serverTimeNow } from '../profile/server-time.ts'; import { setUpProfiles } from '../profiles-setup.ts'; import { loadTuning } from '../tuning/tuning.ts'; import { readSaveAvatar } from './save-avatars.ts'; +import { loadSaveLabels, localizeMissionName, localizeVehicleName, type SaveLabels } from './save-labels.ts'; export interface SaveLocation { readonly gameFolder: string; @@ -57,19 +58,24 @@ export function readSaveSnapshot(dataFolder: string, userId: string): BlkBlock | } } -function battleEntries(profile: BlkBlock) { +function battleEntries(profile: BlkBlock, labels?: SaveLabels) { return (findBlock(profile, 'userlogs')?.blocks ?? []) .filter((entry) => intField(entry, 'type') === EULT_SESSION_RESULT) .map((entry) => { const body = findBlock(entry, 'body'); const win = body && findParam(body, 'win')?.value; + const mission = stringField(body, 'locName') || stringField(body, 'mission'); + const mode = stringField(body, 'eventId'); + const vehicles = (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? []; return { id: entry.name, time: intField(entry, 'time'), won: win?.type === 'bool' ? win.value : null, - mission: stringField(body, 'locName') || stringField(body, 'mission'), - mode: stringField(body, 'eventId'), - vehicles: (body && findBlock(body, 'aircrafts')?.params.map(({ name }) => name)) ?? [], + mission, + missionName: labels ? localizeMissionName(mission || mode, labels) : { en: mission || mode, zh: mission || mode }, + mode, + vehicles, + vehicleNames: vehicles.map((unitId) => (labels ? localizeVehicleName(unitId, labels) : { en: unitId, zh: unitId })), silverLions: intField(body, 'wpEarned'), researchPoints: intField(body, 'xpEarned'), }; @@ -104,9 +110,10 @@ export function readSaveDetails(dataFolder: string, userId: string, gameFolder?: .filter(({ points }) => points > 0) : []; const thresholds = rankThresholds(dataFolder, gameFolder); + const labels = loadSaveLabels(dataFolder, gameFolder); return { save: summary(account, profile, thresholds), - battles: profile ? battleEntries(profile) : [], + battles: profile ? battleEntries(profile, labels) : [], owned, research, maxLevel: thresholds.length || null, diff --git a/apps/server/src/saves/save-labels.ts b/apps/server/src/saves/save-labels.ts new file mode 100644 index 0000000..ce994c9 --- /dev/null +++ b/apps/server/src/saves/save-labels.ts @@ -0,0 +1,100 @@ +import { DatasetCache } from '../game-data/datasets/dataset-cache.ts'; +import type { Dataset } from '../game-data/datasets/dataset.ts'; +import { parseLocalizedCsvMap, type LocalizedCsvText } from '../game-data/datasets/lang-csv.ts'; +import { GameFiles } from '../game-data/game-files.ts'; + +const LANGUAGE_PACK = 'lang.vromfs.bin'; +const UNIT_FILE = 'lang/units.csv'; +const MISSION_FILES = ['lang/missions_versus.csv', 'lang/missions_locations.csv', 'lang/missions_single.csv'] as const; +const UNIT_SHOP_SUFFIX = '_shop'; +/** Gaijin uses control-picture and private-use code points for in-game nation flag glyphs. */ +const GAME_FONT_GLYPHS = /[\u2400-\u243f\ue000-\uf8ff]/g; + +export interface SaveLabels { + readonly units: Readonly>; + readonly missions: Readonly>; +} + +const EMPTY_LABELS: SaveLabels = { units: {}, missions: {} }; + +const saveLabelsDataset: Dataset = { + id: 'save-labels', + version: 1, + extract: (source) => { + const available = new Set(source.listFiles(LANGUAGE_PACK)); + const units: Record = {}; + if (available.has(UNIT_FILE)) { + for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, UNIT_FILE))) { + if (!key.endsWith(UNIT_SHOP_SUFFIX)) continue; + const unitId = key.slice(0, -UNIT_SHOP_SUFFIX.length); + if (!unitId) continue; + units[unitId] = stripGlyphs(text, unitId); + } + } + + const missions: Record = {}; + for (const file of MISSION_FILES) { + if (!available.has(file)) continue; + for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, file))) { + if (!(key in missions)) missions[key] = stripGlyphs(text, key); + } + } + + return { units, missions }; + }, +}; + +export function loadSaveLabels(dataFolder: string, gameFolder: string | undefined): SaveLabels { + if (!gameFolder) return EMPTY_LABELS; + try { + return new DatasetCache(dataFolder, new GameFiles(gameFolder), () => {}).load(saveLabelsDataset); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return EMPTY_LABELS; + throw error; + } +} + +export function localizeVehicleName(unitId: string, labels: SaveLabels): LocalizedCsvText { + return labels.units[unitId] ?? { en: unitId, zh: unitId }; +} + +export function localizeMissionName(raw: string, labels: SaveLabels): LocalizedCsvText { + if (!raw) return { en: '', zh: '' }; + const exact = lookupMission(raw, labels); + if (exact) return exact; + + const parts = raw.split(';').map((part) => part.trim()).filter(Boolean); + if (parts.length <= 1) return { en: raw, zh: raw }; + + const resolved = parts.map((part) => lookupMission(part, labels) ?? { en: part, zh: part }); + return { + en: joinMissionParts(resolved.map(({ en }) => en), false), + zh: joinMissionParts(resolved.map(({ zh }) => zh), true), + }; +} + +function lookupMission(key: string, labels: SaveLabels): LocalizedCsvText | undefined { + return labels.missions[key] + ?? (key.startsWith('missions/') ? labels.missions[key.slice('missions/'.length)] : labels.missions[`missions/${key}`]); +} + +function joinMissionParts(parts: readonly string[], cjk: boolean): string { + let result = ''; + for (const part of parts) { + if (!part) continue; + if (!result) { + result = part; + } else if (cjk && (result.endsWith('】') || result.endsWith(']') || part.startsWith('【'))) { + result += part; + } else { + result += ` ${part}`; + } + } + return result; +} + +function stripGlyphs(text: LocalizedCsvText, fallback: string): LocalizedCsvText { + const en = text.en.replace(GAME_FONT_GLYPHS, '').trim() || fallback; + const zh = text.zh.replace(GAME_FONT_GLYPHS, '').trim() || en; + return { en, zh }; +} diff --git a/apps/server/src/storage/atomic-file.ts b/apps/server/src/storage/atomic-file.ts index f35d565..5c53135 100644 --- a/apps/server/src/storage/atomic-file.ts +++ b/apps/server/src/storage/atomic-file.ts @@ -2,12 +2,17 @@ * Write a file so that a crash leaves either the old or the new content, never a mix: * write a temporary file next to it, flush it to disk, then rename it over the target. */ -import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from 'node:fs'; import { dirname } from 'node:path'; +const TRANSIENT_RENAME_ERRORS = new Set(['EPERM', 'EBUSY', 'EACCES']); +const MAX_RENAME_ATTEMPTS = 6; +const WAIT_BUFFER = new Int32Array(new SharedArrayBuffer(4)); + export function writeFileAtomic(path: string, content: Uint8Array | string): void { mkdirSync(dirname(path), { recursive: true }); - const temporary = `${path}.${process.pid}.tmp`; + const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`; const fd = openSync(temporary, 'w'); try { writeSync(fd, typeof content === 'string' ? Buffer.from(content, 'utf8') : content); @@ -15,5 +20,23 @@ export function writeFileAtomic(path: string, content: Uint8Array | string): voi } finally { closeSync(fd); } - renameSync(temporary, path); + try { + renameWithRetry(temporary, path); + } catch (error) { + try { rmSync(temporary, { force: true }); } catch { /* ignore cleanup errors */ } + throw error; + } +} + +function renameWithRetry(source: string, target: string): void { + for (let attempt = 1; ; attempt += 1) { + try { + renameSync(source, target); + return; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (attempt >= MAX_RENAME_ATTEMPTS || !code || !TRANSIENT_RENAME_ERRORS.has(code)) throw error; + Atomics.wait(WAIT_BUFFER, 0, 0, attempt * 25); + } + } }