diff --git a/apps/launcher/package.json b/apps/launcher/package.json index c2d03db..4d4b591 100644 --- a/apps/launcher/package.json +++ b/apps/launcher/package.json @@ -15,6 +15,7 @@ "@fontsource/roboto-condensed": "^5.3.0", "@wto/patcher": "*", "@wto/server": "*", + "fflate": "^0.8.2", "i18next": "^26.3.6", "react": "^19.2.8", "react-dom": "^19.2.8", diff --git a/apps/launcher/src/main/index.ts b/apps/launcher/src/main/index.ts index d4f2310..cea8055 100644 --- a/apps/launcher/src/main/index.ts +++ b/apps/launcher/src/main/index.ts @@ -1,11 +1,13 @@ import { app } from 'electron'; import { registerIpcHandlers } from './ipc/handlers.ts'; +import { handleArtProtocol, registerArtScheme } from './services/background-art/art-protocol.ts'; import { createMainWindow, showMainWindow } from './services/main-window.ts'; /** * Main process entry. Order: - * 1. the user data folder (a scratch folder for development runs) and the single-instance lock; - * 2. IPC handlers; + * 1. the user data folder (a scratch folder for development runs), the background art scheme and + * the single-instance lock; + * 2. IPC handlers and the background art protocol; * 3. the window. */ @@ -15,6 +17,7 @@ const userDataOverride = process.env['WTO_LAUNCHER_USER_DATA']; if (userDataOverride) app.setPath('userData', userDataOverride); if (process.platform === 'win32') app.setAppUserModelId('com.wtoffline.launcher'); +registerArtScheme(); if (!app.requestSingleInstanceLock()) { app.quit(); @@ -24,6 +27,7 @@ if (!app.requestSingleInstanceLock()) { // A top-level await on whenReady deadlocks an ESM main entry on Windows. void app.whenReady().then(() => { registerIpcHandlers(); + handleArtProtocol(); createMainWindow(); }); } diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 0c642b1..b068d1c 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -1,6 +1,7 @@ import { app, BrowserWindow, dialog, shell } from 'electron'; import { patchFeatures, verifiedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; +import { listBackgroundPictures } from '../services/background-art/art-catalog.ts'; import { getSettings, updateSettings } from '../services/config/settings-store.ts'; import { measureFolder } from '../services/game-folder/folder-size.ts'; import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts'; @@ -22,6 +23,10 @@ export function registerIpcHandlers(): void { supportedGameVersions: verifiedGameVersions(resources.exePatches, resources.guiPatches), }; }); + handle('app:listBackgrounds', async () => { + const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); + return listBackgroundPictures(record?.copyPath ?? null, settings.officialWallpapers); + }); handle('app:openFolder', async ({ path }) => { await requireFolder(path); const failure = await shell.openPath(path); diff --git a/apps/launcher/src/main/services/background-art/art-cache.ts b/apps/launcher/src/main/services/background-art/art-cache.ts new file mode 100644 index 0000000..65a400a --- /dev/null +++ b/apps/launcher/src/main/services/background-art/art-cache.ts @@ -0,0 +1,7 @@ +import { join } from 'node:path'; +import { app } from 'electron'; + +/** Where background pictures are cached: `/cache/background-art/`. */ +export function artCacheFolder(source: 'game' | 'official'): string { + return join(app.getPath('userData'), 'cache', 'background-art', source); +} diff --git a/apps/launcher/src/main/services/background-art/art-catalog.ts b/apps/launcher/src/main/services/background-art/art-catalog.ts new file mode 100644 index 0000000..cbbe885 --- /dev/null +++ b/apps/launcher/src/main/services/background-art/art-catalog.ts @@ -0,0 +1,32 @@ +import type { BackgroundPicture } from '@shared/schemas/background.ts'; +import { gameArtUrl, officialWallpaperUrl } from './art-protocol.ts'; +import { listGameArt } from './game-art.ts'; +import { listOfficialWallpapers } from './official-wallpapers.ts'; + +/** + * Every background picture the window may show: the website's wallpapers (when the player allows + * fetching them) and the pictures of the installed game copy. Empty when neither is available; + * the window then draws its own background. + */ +export async function listBackgroundPictures(copyPath: string | null, officialWallpapers: boolean): Promise { + const [official, game] = await Promise.all([ + officialWallpapers ? listOfficialWallpapers() : Promise.resolve([]), + copyPath ? listGameArt(copyPath) : Promise.resolve([]), + ]); + return [ + ...official.map((wallpaper) => ({ + key: `official:${wallpaper.id}`, + source: 'official' as const, + label: wallpaper.title, + url: officialWallpaperUrl(wallpaper.id, false), + thumbnailUrl: officialWallpaperUrl(wallpaper.id, true), + })), + ...game.map((name) => ({ + key: `game:${name}`, + source: 'game' as const, + label: name, + url: gameArtUrl(name), + thumbnailUrl: gameArtUrl(name), + })), + ]; +} diff --git a/apps/launcher/src/main/services/background-art/art-protocol.ts b/apps/launcher/src/main/services/background-art/art-protocol.ts new file mode 100644 index 0000000..896ca7b --- /dev/null +++ b/apps/launcher/src/main/services/background-art/art-protocol.ts @@ -0,0 +1,50 @@ +import { pathToFileURL } from 'node:url'; +import { net, protocol } from 'electron'; +import { gameArtFile } from './game-art.ts'; +import { officialWallpaperFile } from './official-wallpapers.ts'; + +/** + * wto-art://: the cached background pictures. A custom scheme because the window loads from the + * development server or from a file, and neither may read the user data folder. + * + * wto-art://game/.jpg a picture from the game copy + * wto-art://official/.jpg a wallpaper from the website gallery + * wto-art://official/.thumb.jpg its thumbnail + */ + +export const ART_SCHEME = 'wto-art'; + +/** Before the app is ready. */ +export function registerArtScheme(): void { + protocol.registerSchemesAsPrivileged([{ scheme: ART_SCHEME, privileges: { standard: true, secure: true } }]); +} + +/** After the app is ready. */ +export function handleArtProtocol(): void { + protocol.handle(ART_SCHEME, async (request) => { + const url = new URL(request.url); + const file = await resolve(url.hostname, url.pathname); + if (!file) return new Response(null, { status: 404 }); + return net.fetch(pathToFileURL(file).toString()); + }); +} + +async function resolve(source: string, path: string): Promise { + if (source === 'game') { + const name = /^\/([a-z]+)\.jpg$/.exec(path)?.[1]; + return name ? gameArtFile(name) : null; + } + if (source === 'official') { + const match = /^\/([0-9a-f]{24})(\.thumb)?\.jpg$/.exec(path); + return match?.[1] ? officialWallpaperFile(match[1], match[2] !== undefined) : null; + } + return null; +} + +export function gameArtUrl(name: string): string { + return `${ART_SCHEME}://game/${name}.jpg`; +} + +export function officialWallpaperUrl(id: string, thumbnail: boolean): string { + return `${ART_SCHEME}://official/${id}${thumbnail ? '.thumb' : ''}.jpg`; +} diff --git a/apps/launcher/src/main/services/background-art/game-art.ts b/apps/launcher/src/main/services/background-art/game-art.ts new file mode 100644 index 0000000..0433ed0 --- /dev/null +++ b/apps/launcher/src/main/services/background-art/game-art.ts @@ -0,0 +1,91 @@ +import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { unzip, type Unzipped } from 'fflate'; +import { artCacheFolder } from './art-cache.ts'; + +/** + * Background pictures from the game copy: the game's own launcher keeps one per nation in + * `launcherr.dat` (a zip archive) next to the game. They are extracted into the cache once per + * archive version. The launcher ships no game pictures. + * + * img/main_window_bg_art.jpg -> default + * img/main_window_bg_art_.jpg -> + */ + +const ARCHIVE = 'launcherr.dat'; +const ENTRY = /^img\/main_window_bg_art(?:_([a-z]+))?\.jpg$/; +/** Picture names are entry suffixes only: lower-case letters. */ +export const GAME_ART_NAME = /^[a-z]+$/; +const DEFAULT_NAME = 'default'; + +function cacheRoot(): string { + return artCacheFolder('game'); +} + +let current: { folder: string; names: string[] } | null = null; + +/** The picture names available from the copy at `copyPath`; empty when it has no readable archive. */ +export async function listGameArt(copyPath: string): Promise { + const archive = join(copyPath, ARCHIVE); + let key: string; + try { + const info = await stat(archive); + // Size and modification time identify the archive version; a game update replaces it. + key = `${info.size}-${Math.floor(info.mtimeMs)}`; + } catch { + current = null; + return []; + } + const folder = join(cacheRoot(), key); + try { + if ((await cachedNames(folder)).length === 0) await extract(archive, folder); + current = { folder, names: await cachedNames(folder) }; + await removeOtherVersions(key); + return current.names; + } catch (error) { + console.warn('[background-art] extracting the game pictures failed:', error); + current = null; + return []; + } +} + +/** The cached file of a picture listed by the last listGameArt call, or null. */ +export function gameArtFile(name: string): string | null { + if (!current || !GAME_ART_NAME.test(name) || !current.names.includes(name)) return null; + return join(current.folder, `${name}.jpg`); +} + +async function cachedNames(folder: string): Promise { + try { + return (await readdir(folder)) + .filter((file) => file.endsWith('.jpg')) + .map((file) => file.slice(0, -4)) + .filter((name) => GAME_ART_NAME.test(name)) + .sort(); + } catch { + return []; + } +} + +async function extract(archive: string, folder: string): Promise { + const files = await unzipEntries(await readFile(archive)); + await mkdir(folder, { recursive: true }); + for (const [entry, bytes] of Object.entries(files)) { + const match = ENTRY.exec(entry); + if (match) await writeFile(join(folder, `${match[1] ?? DEFAULT_NAME}.jpg`), bytes); + } +} + +function unzipEntries(bytes: Uint8Array): Promise { + return new Promise((resolve, reject) => { + unzip(bytes, { filter: (file) => ENTRY.test(file.name) }, (error, files) => (error ? reject(error) : resolve(files))); + }); +} + +/** Pictures of archive versions other than `key` are stale. */ +async function removeOtherVersions(key: string): Promise { + const entries = await readdir(cacheRoot()).catch(() => [] as string[]); + for (const entry of entries) { + if (entry !== key) await rm(join(cacheRoot(), entry), { recursive: true, force: true }); + } +} diff --git a/apps/launcher/src/main/services/background-art/official-wallpapers.ts b/apps/launcher/src/main/services/background-art/official-wallpapers.ts new file mode 100644 index 0000000..87fd3f3 --- /dev/null +++ b/apps/launcher/src/main/services/background-art/official-wallpapers.ts @@ -0,0 +1,166 @@ +import { mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { net } from 'electron'; +import { z } from 'zod'; +import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; +import { artCacheFolder } from './art-cache.ts'; + +/** + * Background pictures from the game website's public wallpaper gallery (the player may turn this + * off). Only public pictures are fetched: no sign-in, no cookies. The list of the newest + * wallpapers is refreshed at most once a day; a picture is downloaded when it is first shown and + * kept in the cache, so pictures seen once stay available without a connection. + * + * Each gallery entry is a `showcase__item` with a `data-identity` id, a 279x157 thumbnail and a + * 1920x1080 download on staticfiles.warthunder.com. + */ + +const GALLERY_PAGES = ['https://warthunder.com/en/media/wallpapers/', 'https://warthunder.com/en/media/wallpapers/page/2']; +const PICTURE_HOST = 'staticfiles.warthunder.com'; +const LIST_MAX_AGE_MS = 24 * 60 * 60 * 1000; +const PAGE_TIMEOUT_MS = 4000; +const PICTURE_TIMEOUT_MS = 20000; +/** Downloaded pictures kept beyond the current list, newest first. */ +const KEEP_PICTURES = 40; + +/** Gallery entry ids are 24 hex digits. */ +export const OFFICIAL_ID = /^[0-9a-f]{24}$/; + +const OfficialWallpaperSchema = z.object({ + id: z.string().regex(OFFICIAL_ID), + /** The picture's name taken from its file name, e.g. "ztz 96b". */ + title: z.string(), + pictureUrl: z.string(), + thumbnailUrl: z.string(), +}); +export type OfficialWallpaper = z.output; + +const ListFileSchema = z.object({ + fetchedAt: z.number(), + wallpapers: z.array(OfficialWallpaperSchema), +}); +type ListFile = z.output; + +function folder(): string { + return artCacheFolder('official'); +} + +function listPath(): string { + return join(folder(), 'list.json'); +} + +let current: readonly OfficialWallpaper[] = []; + +/** + * The newest gallery wallpapers. A stale list is refreshed when the website answers in time; + * otherwise the cached list is used, reduced to the pictures already downloaded. + */ +export async function listOfficialWallpapers(): Promise { + const cached = await readCachedList(); + let list = cached?.wallpapers ?? []; + let online = cached !== null && Date.now() - cached.fetchedAt < LIST_MAX_AGE_MS; + if (!online) { + try { + list = await fetchGallery(); + await mkdir(folder(), { recursive: true }); + await writeJsonAtomic(listPath(), { fetchedAt: Date.now(), wallpapers: list } satisfies ListFile); + online = true; + } catch (error) { + console.warn('[background-art] the wallpaper gallery is not reachable:', String(error)); + } + } + const downloaded = new Set(await downloadedIds()); + current = online ? list : list.filter((wallpaper) => downloaded.has(wallpaper.id)); + await pruneDownloads(new Set(list.map((wallpaper) => wallpaper.id))); + return current; +} + +/** The cached picture (`thumbnail` for the small one), downloaded first when missing; null if unavailable. */ +export async function officialWallpaperFile(id: string, thumbnail: boolean): Promise { + const wallpaper = current.find((entry) => entry.id === id); + if (!wallpaper) return null; + const path = join(folder(), thumbnail ? `${id}.thumb.jpg` : `${id}.jpg`); + if (await stat(path).then(() => true, () => false)) return path; + try { + const bytes = await download(thumbnail ? wallpaper.thumbnailUrl : wallpaper.pictureUrl, PICTURE_TIMEOUT_MS); + await mkdir(folder(), { recursive: true }); + await writeFile(`${path}.part`, bytes); + await rename(`${path}.part`, path); + return path; + } catch (error) { + console.warn('[background-art] downloading a wallpaper failed:', id, String(error)); + return null; + } +} + +async function readCachedList(): Promise { + try { + const parsed = ListFileSchema.safeParse(await readJsonOr(listPath(), null)); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +async function fetchGallery(): Promise { + const found = new Map(); + for (const page of GALLERY_PAGES) { + const html = new TextDecoder().decode(await download(page, PAGE_TIMEOUT_MS)); + for (const wallpaper of parseGallery(html)) if (!found.has(wallpaper.id)) found.set(wallpaper.id, wallpaper); + } + if (found.size === 0) throw new Error('the gallery pages list no wallpapers'); + return [...found.values()]; +} + +/** The entries of one gallery page; entries without both picture sizes are skipped. */ +export function parseGallery(html: string): OfficialWallpaper[] { + const wallpapers: OfficialWallpaper[] = []; + const items = html.split('class="showcase__item').slice(1); + for (const item of items) { + const id = /data-identity="([0-9a-f]{24})"/.exec(item)?.[1]; + const thumbnailUrl = /data-src="(https:\/\/[^"]+\/_thumbs\/279x157\/[^"]+\.jpg)"/.exec(item)?.[1]; + // The first link is the 999x562 preview, which also carries "1920x1080_" in its file name. + const pictureUrl = [...item.matchAll(/href="(https:\/\/[^"]+\/1920x1080_[^"/]+\.jpg)"/g)] + .map((match) => match[1] ?? '') + .find((url) => !url.includes('/_thumbs/')); + if (!id || !thumbnailUrl || !pictureUrl || !onPictureHost(thumbnailUrl) || !onPictureHost(pictureUrl)) continue; + wallpapers.push({ id, title: titleOf(pictureUrl), pictureUrl, thumbnailUrl }); + } + return wallpapers; +} + +/** "…/1920x1080_ztz_96b_logo_657a….jpg" -> "ztz 96b"; a language suffix after "logo" goes too. */ +function titleOf(pictureUrl: string): string { + const file = pictureUrl.slice(pictureUrl.lastIndexOf('/') + 1); + return file + .replace(/^1920x1080_/, '') + .replace(/_[0-9a-f]{32}\.jpg$/, '') + .replace(/_logo(?:_[a-z]+)?$/, '') + .replace(/_/g, ' '); +} + +function onPictureHost(url: string): boolean { + return new URL(url).hostname === PICTURE_HOST; +} + +async function download(url: string, timeoutMs: number): Promise { + const response = await net.fetch(url, { credentials: 'omit', signal: AbortSignal.timeout(timeoutMs) }); + if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`); + return new Uint8Array(await response.arrayBuffer()); +} + +async function downloadedIds(): Promise { + const files = await readdir(folder()).catch(() => [] as string[]); + return files.filter((file) => /^[0-9a-f]{24}\.jpg$/.test(file)).map((file) => file.slice(0, 24)); +} + +/** Drop downloads that left the list, beyond the KEEP_PICTURES most recently downloaded. */ +async function pruneDownloads(listed: ReadonlySet): Promise { + const unlisted = (await downloadedIds()).filter((id) => !listed.has(id)); + const dated = await Promise.all(unlisted.map(async (id) => ({ id, time: (await stat(join(folder(), `${id}.jpg`))).mtimeMs }))); + dated.sort((a, b) => b.time - a.time); + for (const { id } of dated.slice(KEEP_PICTURES)) { + await rm(join(folder(), `${id}.jpg`), { force: true }); + await rm(join(folder(), `${id}.thumb.jpg`), { force: true }); + } +} diff --git a/apps/launcher/src/renderer/index.html b/apps/launcher/src/renderer/index.html index 21bda5f..6df38ba 100644 --- a/apps/launcher/src/renderer/index.html +++ b/apps/launcher/src/renderer/index.html @@ -2,7 +2,7 @@ - + WTOffline diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index ca9178b..b7a0a78 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -9,6 +9,7 @@ import { ipcOn } from './ipc.ts'; import { AboutPage } from './pages/about/AboutPage.tsx'; import { CopySummary } from './pages/copies/CopySummary.tsx'; import { FeatureStatus } from './pages/copies/FeatureStatus.tsx'; +import { BackgroundSwitch } from './pages/home/BackgroundSwitch.tsx'; import { HomeMain } from './pages/home/HomeMain.tsx'; import { HomeSide } from './pages/home/HomeSide.tsx'; import { homeBar } from './pages/home/home-bar.ts'; @@ -24,6 +25,7 @@ import { Footer } from './shell/Footer.tsx'; import { COPY_SECTIONS, navigate, SETTINGS_SECTIONS, START_ROUTE, type Destination, type Route } from './shell/navigation.ts'; import { SubNav } from './shell/SubNav.tsx'; import { TitleBar } from './shell/TitleBar.tsx'; +import { useBackgrounds } from './shell/useBackgrounds.ts'; import { useErrorMessage } from './useErrorMessage.ts'; interface AppProps { @@ -60,6 +62,8 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A }, }); + const backgrounds = useBackgrounds(record?.copyPath ?? null, settings, report); + useEffect(() => ipcOn('event:settings-changed', setSettings), []); useEffect(() => applyLanguage(resolveLanguage(settings.language, info.systemLocale)), [settings.language, info.systemLocale]); @@ -73,13 +77,22 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A const homeSide = ; switch (route.page) { case 'home': - return { side: homeSide, main: , bar: home }; + return { + side: homeSide, + main: ( + <> + + + + ), + bar: home, + }; case 'about': return { side: homeSide, main: , bar: home }; case 'settings': return { side: t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />, - main: , + main: , bar: home, }; case 'copies': { @@ -114,7 +127,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A const paged = wizard.active || route.page !== 'home'; return (
- + go({ page })} onError={report} />
diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 075b206..603f33a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -213,6 +213,32 @@ "language": "Language", "languageHint": "Display language of the launcher" }, + "background": { + "title": "Background", + "hint": "Website wallpapers come from the public wallpaper gallery of the War Thunder website; game pictures are read from the current copy. The launcher itself contains no game pictures.", + "official": "Website wallpapers", + "officialHint": "Requires a network connection. Only public pictures are downloaded; no sign-in and no account information is sent. Downloaded wallpapers remain available offline.", + "officialToggle": "Get wallpapers from the War Thunder website", + "officialItem": "Website · {{name}}", + "random": "Random", + "none": "No background pictures are available. Install a copy to use the game pictures, or turn on website wallpapers.", + "current": "Background: {{name}}", + "previous": "Previous", + "next": "Next", + "nations": { + "default": "General", + "usa": "USA", + "germany": "Germany", + "ussr": "USSR", + "uk": "Great Britain", + "japan": "Japan", + "china": "China", + "italy": "Italy", + "france": "France", + "sweden": "Sweden", + "israel": "Israel" + } + }, "about": { "launcher": "Launcher {{version}}", "supported": "Supported game versions: {{versions}}", 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 758fe7b..f45e8ce 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -213,6 +213,32 @@ "language": "语言", "languageHint": "启动器界面的显示语言" }, + "background": { + "title": "背景图", + "hint": "官网壁纸取自战争雷霆官网的公开壁纸库,游戏图片读取自当前副本。启动器本身不包含任何游戏图片。", + "official": "官网壁纸", + "officialHint": "需要联网。仅下载公开图片,不登录,不发送任何账号信息。已下载的壁纸离线时仍可使用。", + "officialToggle": "从战争雷霆官网获取壁纸", + "officialItem": "官网壁纸 · {{name}}", + "random": "随机", + "none": "暂无可用的背景图。安装后可使用游戏图片,或开启官网壁纸。", + "current": "背景:{{name}}", + "previous": "上一张", + "next": "下一张", + "nations": { + "default": "通用", + "usa": "美国", + "germany": "德国", + "ussr": "苏联", + "uk": "英国", + "japan": "日本", + "china": "中国", + "italy": "意大利", + "france": "法国", + "sweden": "瑞典", + "israel": "以色列" + } + }, "about": { "launcher": "启动器 {{version}}", "supported": "支持的游戏版本:{{versions}}", diff --git a/apps/launcher/src/renderer/src/pages/home/BackgroundSwitch.tsx b/apps/launcher/src/renderer/src/pages/home/BackgroundSwitch.tsx new file mode 100644 index 0000000..f0dd7b8 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/home/BackgroundSwitch.tsx @@ -0,0 +1,28 @@ +import { useTranslation } from 'react-i18next'; +import type { BackgroundPicture } from '@shared/schemas/background.ts'; +import { ipcInvoke } from '../../ipc.ts'; +import { backgroundLabel } from '../../shell/background-label.ts'; +import { neighbourPicture } from '../../shell/useBackgrounds.ts'; + +interface BackgroundSwitchProps { + readonly pictures: readonly BackgroundPicture[]; + readonly shown: BackgroundPicture | null; + readonly onError: (error: unknown) => void; +} + +/** The picture's name and previous / next, at the top right of the home page; a choice is kept in the settings. */ +export function BackgroundSwitch({ pictures, shown, onError }: BackgroundSwitchProps) { + const { t } = useTranslation(); + if (!shown || pictures.length === 0) return null; + const step = (direction: number): void => { + const next = neighbourPicture(pictures, shown, direction); + if (next) ipcInvoke('settings:update', { background: next.key }).catch(onError); + }; + return ( +
+ {t('background.current', { name: backgroundLabel(t, shown) })} + + +
+ ); +} diff --git a/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx index cd0c266..ddd603d 100644 --- a/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx +++ b/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx @@ -1,17 +1,66 @@ import { useTranslation } from 'react-i18next'; +import { BACKGROUND_RANDOM, type BackgroundPicture } from '@shared/schemas/background.ts'; import type { Settings } from '@shared/schemas/settings.ts'; import { Row } from '../../components/Row.tsx'; import { Sheet } from '../../components/Sheet.tsx'; +import { ipcInvoke } from '../../ipc.ts'; +import { backgroundLabel } from '../../shell/background-label.ts'; import { LanguageMenu } from '../../shell/LanguageMenu.tsx'; -/** General launcher settings. */ -export function GeneralSettings({ settings, onError }: { readonly settings: Settings; readonly onError: (error: unknown) => void }) { +interface GeneralSettingsProps { + readonly settings: Settings; + readonly pictures: readonly BackgroundPicture[]; + readonly onError: (error: unknown) => void; +} + +/** General launcher settings: language and background picture. */ +export function GeneralSettings({ settings, pictures, onError }: GeneralSettingsProps) { const { t } = useTranslation(); + const update = (patch: Partial): void => { + ipcInvoke('settings:update', patch).catch(onError); + }; + const official = pictures.filter((picture) => picture.source === 'official'); + const game = pictures.filter((picture) => picture.source === 'game'); + const thumb = (picture: BackgroundPicture) => ( + + ); return ( + + + +

{t('background.title')}

+

{t('background.hint')}

+ {pictures.length === 0 ? ( +

{t('background.none')}

+ ) : ( +
+ + {official.map(thumb)} + {game.map(thumb)} +
+ )}
); } diff --git a/apps/launcher/src/renderer/src/shell/background-label.ts b/apps/launcher/src/renderer/src/shell/background-label.ts new file mode 100644 index 0000000..601fe42 --- /dev/null +++ b/apps/launcher/src/renderer/src/shell/background-label.ts @@ -0,0 +1,8 @@ +import type { TFunction } from 'i18next'; +import type { BackgroundPicture } from '@shared/schemas/background.ts'; + +/** "Website · ztz 96b" for a wallpaper, the nation for a picture of the game copy. */ +export function backgroundLabel(t: TFunction, picture: BackgroundPicture): string { + if (picture.source === 'official') return t('background.officialItem', { name: picture.label }); + return t(`background.nations.${picture.label}`, { defaultValue: picture.label }); +} diff --git a/apps/launcher/src/renderer/src/shell/useBackgrounds.ts b/apps/launcher/src/renderer/src/shell/useBackgrounds.ts new file mode 100644 index 0000000..58964db --- /dev/null +++ b/apps/launcher/src/renderer/src/shell/useBackgrounds.ts @@ -0,0 +1,42 @@ +import { useEffect, useMemo, useState } from 'react'; +import type { BackgroundPicture } from '@shared/schemas/background.ts'; +import type { Settings } from '@shared/schemas/settings.ts'; +import { ipcInvoke } from '../ipc.ts'; + +/** + * The background pictures available and the one to show. The list is read again when the copy + * changes (an installation) or when the website wallpapers are turned on or off. With the random + * choice, one picture is drawn per list, so it stays the same until the launcher starts again. + */ +export function useBackgrounds(copyPath: string | null, settings: Settings, onError: (error: unknown) => void) { + const [pictures, setPictures] = useState([]); + const [randomKey, setRandomKey] = useState(null); + + useEffect(() => { + let current = true; + ipcInvoke('app:listBackgrounds') + .then((list) => { + if (!current) return; + setPictures(list); + setRandomKey(list[Math.floor(Math.random() * list.length)]?.key ?? null); + }) + .catch((error: unknown) => current && onError(error)); + return () => { + current = false; + }; + }, [copyPath, settings.officialWallpapers, onError]); + + const shown = useMemo( + () => pictures.find((picture) => picture.key === settings.background) ?? pictures.find((picture) => picture.key === randomKey) ?? null, + [pictures, settings.background, randomKey], + ); + + return { pictures, shown }; +} + +/** The picture next to `current` in the list (`step` 1 or -1), wrapping around. */ +export function neighbourPicture(pictures: readonly BackgroundPicture[], current: BackgroundPicture | null, step: number): BackgroundPicture | null { + if (pictures.length === 0) return null; + const index = current ? pictures.findIndex((picture) => picture.key === current.key) : -1; + return pictures[(index + step + pictures.length) % pictures.length] ?? null; +} diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index 7def7e9..bc47586 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -59,6 +59,105 @@ color: var(--white); } +.background-switch { + position: absolute; + top: 14px; + right: 16px; + max-width: 60%; + display: flex; + align-items: center; + gap: 8px; + padding: 4px 6px 4px 10px; + font-size: 12px; + color: rgba(255, 255, 255, 0.75); + background: rgba(10, 14, 16, 0.55); + border: 1px solid var(--line); + border-radius: var(--radius); +} + +.background-switch-label { + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-transform: capitalize; +} + +.background-switch button { + width: 22px; + height: 22px; + flex: none; + color: inherit; + background: none; + border: 0; + border-radius: 2px; + cursor: pointer; +} + +.background-switch button:hover { + color: var(--white); + background: rgba(255, 255, 255, 0.12); +} + +/* ===== Settings: background pictures ===== */ +.section-title-spaced { + margin-top: 22px; +} + +.check-inline { + margin-top: 0; +} + +.thumbs { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 8px; + margin-top: 10px; +} + +.thumb { + position: relative; + aspect-ratio: 16 / 10; + padding: 0; + overflow: hidden; + cursor: pointer; + background-color: var(--surface); + background-size: cover; + background-position: 60% 45%; + border: 2px solid transparent; + border-radius: var(--radius); +} + +.thumb:hover { + border-color: var(--line-strong); +} + +.thumb span { + position: absolute; + left: 0; + right: 0; + bottom: 0; + padding: 2px 6px; + font-size: 11px; + text-align: left; + text-transform: capitalize; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: var(--white); + background: rgba(0, 0, 0, 0.6); +} + +.thumb-random { + font: 500 14px var(--font-display); + color: var(--text); +} + +.thumb-selected, +.thumb-selected:hover { + border-color: var(--red); +} + /* ===== Feature status ===== */ .feature-group { margin-bottom: 14px; diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 0eebc72..68392cd 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { BackgroundPictureSchema } from '../schemas/background.ts'; import { FolderSizeSchema, GameFolderInspectionSchema, @@ -31,6 +32,11 @@ export const ipcContract = { supportedGameVersions: z.array(z.string()), }), }, + 'app:listBackgrounds': { + /** The website's wallpapers (when allowed in the settings) and the installed copy's pictures. */ + input: z.void(), + output: z.array(BackgroundPictureSchema), + }, 'app:openFolder': { /** Opens a folder in the file manager; refused unless it exists. */ input: z.object({ path: z.string().min(1) }), diff --git a/apps/launcher/src/shared/schemas/background.ts b/apps/launcher/src/shared/schemas/background.ts new file mode 100644 index 0000000..6c8253d --- /dev/null +++ b/apps/launcher/src/shared/schemas/background.ts @@ -0,0 +1,18 @@ +import { z } from 'zod'; + +/** + * A background picture the window may show. `key` is what the settings store for a fixed choice: + * `official:` for a website wallpaper, `game:` for a picture of the game copy. + */ +export const BackgroundPictureSchema = z.object({ + key: z.string(), + source: z.enum(['official', 'game']), + /** The nation for game pictures (translated by the window), the picture name for wallpapers. */ + label: z.string(), + url: z.string(), + thumbnailUrl: z.string(), +}); +export type BackgroundPicture = z.output; + +export const BACKGROUND_RANDOM = 'random'; +export const BackgroundChoiceSchema = z.string().regex(/^(random|game:[a-z]+|official:[0-9a-f]{24})$/); diff --git a/apps/launcher/src/shared/schemas/settings.ts b/apps/launcher/src/shared/schemas/settings.ts index df95dcb..5310bd7 100644 --- a/apps/launcher/src/shared/schemas/settings.ts +++ b/apps/launcher/src/shared/schemas/settings.ts @@ -1,11 +1,16 @@ import { z } from 'zod'; import { LANGUAGE_CHOICES } from '../languages.ts'; +import { BACKGROUND_RANDOM, BackgroundChoiceSchema } from './background.ts'; const LanguageChoiceSchema = z.enum(LANGUAGE_CHOICES); /** The launcher's own settings (not the game's, not the local service's tuning). */ export const SettingsSchema = z.object({ language: LanguageChoiceSchema.default('system'), + /** A new picture on every start, or one picture by its key (schemas/background.ts). */ + background: BackgroundChoiceSchema.default(BACKGROUND_RANDOM), + /** Fetch wallpapers from the game website's public gallery. */ + officialWallpapers: z.boolean().default(true), }); export type Settings = z.output; @@ -13,6 +18,8 @@ export type Settings = z.output; /** A change to some settings; the merged result is validated again before it is saved. */ export const SettingsPatchSchema = z.object({ language: LanguageChoiceSchema.optional(), + background: BackgroundChoiceSchema.optional(), + officialWallpapers: z.boolean().optional(), }); export type SettingsPatch = z.output; diff --git a/package-lock.json b/package-lock.json index 9cb60ab..4af76db 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "@fontsource/roboto-condensed": "^5.3.0", "@wto/patcher": "*", "@wto/server": "*", + "fflate": "^0.8.2", "i18next": "^26.3.6", "react": "^19.2.8", "react-dom": "^19.2.8", @@ -1690,6 +1691,12 @@ } } }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "license": "MIT" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",