Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(games): graphics & performance up to 5K / unlimited FPS, keybind combos, a new look (#975)
Ruben Lütkef5cd6fe54472
diff --git a/docs/game-settings.md b/docs/game-settings.mdindex f6fa1b02e9..90c4c1fe40 100644--- a/docs/game-settings.md+++ b/docs/game-settings.md@@ -1,9 +1,44 @@# Game settingsSettings → **Game settings** keeps a player's own settings for each game in-one place: mouse sensitivity, keybinds, audio, video and gameplay. A converter-carries a hip-fire sensitivity from one game to every other game at the same-cm/360.+one place: graphics and performance, mouse sensitivity, keybinds, audio and+gameplay. A converter carries a hip-fire sensitivity from one game to every+other game at the same cm/360.++## Graphics & performance++Every game gets the same block (`dodaios/games/performance.py`, keys+`perf_*`): resolution from 1280×720 to 5120×2880 including ultrawides,+display mode, refresh rate up to 540 Hz, FPS limit up to **Unlimited**,+V-Sync, G-Sync/FreeSync, HDR, quality preset, render scale (50–200 %),+upscaler (DLSS, FSR, XeSS, TSR) and its mode, sharpening, frame generation,+low latency (Reflex / Anti-Lag), every detail level, anti-aliasing,+anisotropic filtering, ambient occlusion, ray tracing (up to path tracing)+and the post effects. The game's own video options follow under the names+the game uses; the ones the block already covers (display mode, resolution+typed as text) are dropped.++Four presets fill the block in one click: **Competitive** (unlimited FPS,+lowest latency, low detail), **Balanced**, **Quality** and **Epic** (path+tracing, frame generation, HDR). A preset that says `"monitor"` for the FPS+limit takes the detected monitor's refresh rate; resolution and refresh rate+follow the monitor.++`GET /api/games/system` (`dodaios/games/system.py`) reads the GPU (NVIDIA+via NVML / nvidia-smi, any vendor on Windows by name), CPU, RAM and every+monitor's current mode plus the highest refresh rate at that resolution.+From the GPU it picks a class (entry, mid, high, enthusiast) and the+recommended preset. When Windows runs the monitor below what it can do, the+page says so.++## Keybinds++Each action has a primary and a secondary bind. A bind is a key, a mouse+button, the wheel, or a combination joined with ` + ` (`Ctrl + Shift + F`,+`Shift + Mouse 4`); a modifier pressed and released alone binds itself+(`Left Shift`). Actions like sprint, crouch, aim, walk and lean can be set to+hold or toggle. Players add their own actions (emotes, macros, comms). A+keyboard and a mouse panel light up every bound input and mark collisions.## Games@@ -45,9 +80,10 @@ checked against the catalog before they are written.|--------|------|------|| GET | `/api/games` | games, which have a profile, default DPI || GET | `/api/games/{id}` | one game's definition and profile |-| PUT | `/api/games/{id}/profile` | merge `values`, `keybinds`, `dpi` (`reset_dpi`), `notes`; `null` resets a field |+| PUT | `/api/games/{id}/profile` | merge `values`, `keybinds`, `alt_keybinds`, `bind_modes`, `dpi` (`reset_dpi`), `notes`; replace `custom_binds`; `null` resets a field || DELETE | `/api/games/{id}/profile` | forget the profile || PUT | `/api/games/dpi` | default mouse DPI |+| GET | `/api/games/system` | GPU, CPU, RAM, monitors, recommended preset || POST | `/api/games/convert` | `{game_id, sens, dpi?, to_dpi?}` → the same cm/360 in every linear game |The app does not write into the games' own config files; the page showsdiff --git a/dodaios/games/catalog.py b/dodaios/games/catalog.pyindex 42f6fa1d6f..d61d30e9a0 100644--- a/dodaios/games/catalog.py+++ b/dodaios/games/catalog.py@@ -10,21 +10,54 @@ where they could not be verified; the UI then shows the field empty.from __future__ import annotationsimport json+import refrom functools import lru_cachefrom pathlib import Pathfrom typing import Any+from dodaios.games.performance import performance_sections, presets+CATALOG_PATH = Path(__file__).with_name("catalog.json")-SECTION_IDS = ("mouse", "audio", "video", "gameplay")+PERF_SECTION_IDS = (+ "perf_display",+ "perf_rendering",+ "perf_detail",+ "perf_raytracing",+ "perf_effects",+)+SECTION_IDS = (*PERF_SECTION_IDS, "mouse", "audio", "video", "gameplay")SETTING_TYPES = ("slider", "number", "select", "toggle", "text")+# A game's own video settings that the shared performance block already+# covers better: the display mode, and resolution typed as free text.+_DISPLAY_MODE = re.compile(r"^(window|display|screen) mode$", re.I)+++def _duplicate(setting: dict[str, Any]) -> bool:+ label = setting["label"]+ if _DISPLAY_MODE.match(label):+ return True+ return setting["type"] == "text" and "resolution" in label.lower()+++def _compose(game: dict[str, Any]) -> dict[str, Any]:+ sections = []+ for section in game["sections"]:+ settings = section["settings"]+ if section["id"] == "video":+ settings = [s for s in settings if not _duplicate(s)]+ sections.append({**section, "settings": settings})+ return {**game, "sections": [*performance_sections(), *sections]}+@lru_cache(maxsize=1)def load_catalog() -> dict[str, Any]:- """The whole catalog, parsed once per process."""+ """The whole catalog, parsed once per process, with the performance block+ added to every game."""with CATALOG_PATH.open(encoding="utf-8") as fh:- return json.load(fh)+ raw = json.load(fh)+ return {**raw, "games": [_compose(g) for g in raw["games"]], "presets": presets()}def list_games() -> list[dict[str, Any]]:diff --git a/dodaios/games/performance.py b/dodaios/games/performance.pynew file mode 100644index 0000000000..14bdee55b1--- /dev/null+++ b/dodaios/games/performance.py@@ -0,0 +1,398 @@+"""Graphics & performance settings every game gets, plus one-click presets.++The per-game catalog lists each game's own video options under the names the+game prints. On top of that every game gets this one block: the target the+player tunes for (resolution up to 5K, FPS cap up to unlimited, upscaler,+frame generation, latency, every detail level), grouped so the page can draw+it as display / rendering / detail / effects, and four presets that fill it+in one click.++All keys start with ``perf_`` so they never collide with a game's own keys.+"""++from __future__ import annotations++import copy+from typing import Any++QUALITY = ["Low", "Medium", "High", "Ultra", "Epic"]++#: (width, height, short name) from HD to 5K, ultrawides included.+RESOLUTIONS: list[tuple[int, int, str]] = [+ (1280, 720, "HD"),+ (1600, 900, "HD+"),+ (1920, 1080, "Full HD"),+ (2560, 1080, "UW Full HD"),+ (2560, 1440, "QHD"),+ (3440, 1440, "UWQHD"),+ (3840, 1600, "UW4K"),+ (3840, 2160, "4K UHD"),+ (5120, 1440, "DQHD"),+ (5120, 2160, "5K2K"),+ (5120, 2880, "5K"),+]+++def resolution_value(width: int, height: int) -> str:+ return f"{width}x{height}"+++REFRESH_RATES = [+ "60 Hz",+ "75 Hz",+ "120 Hz",+ "144 Hz",+ "165 Hz",+ "180 Hz",+ "240 Hz",+ "280 Hz",+ "360 Hz",+ "480 Hz",+ "540 Hz",+]+FPS_CAPS = ["30", "60", "90", "120", "144", "165", "180", "240", "300", "360", "480", "Unlimited"]++UNLIMITED = "Unlimited"+++def _select(+ key: str, label: str, options: list[str], default: str | None, note: str = ""+) -> dict[str, Any]:+ out: dict[str, Any] = {+ "key": key,+ "label": label,+ "type": "select",+ "options": options,+ "default": default,+ }+ if note:+ out["note"] = note+ return out+++def _toggle(key: str, label: str, default: bool, note: str = "") -> dict[str, Any]:+ out: dict[str, Any] = {"key": key, "label": label, "type": "toggle", "default": default}+ if note:+ out["note"] = note+ return out+++def _slider(+ key: str, label: str, low: float, high: float, step: float, default: float, note: str = ""+) -> dict[str, Any]:+ out: dict[str, Any] = {+ "key": key,+ "label": label,+ "type": "slider",+ "min": low,+ "max": high,+ "step": step,+ "default": default,+ }+ if note:+ out["note"] = note+ return out+++def _quality(key: str, label: str, note: str = "") -> dict[str, Any]:+ return _select(key, label, QUALITY, "High", note)+++#: The block, in display order. ``group`` is what the page draws a card for.+PERFORMANCE_GROUPS: list[dict[str, Any]] = [+ {+ "id": "display",+ "settings": [+ _select(+ "perf_resolution",+ "Resolution",+ [resolution_value(w, h) for w, h, _ in RESOLUTIONS],+ "1920x1080",+ ),+ _select(+ "perf_display_mode",+ "Display Mode",+ ["Fullscreen", "Borderless", "Windowed"],+ "Fullscreen",+ "Fullscreen gives the lowest input latency on most PCs.",+ ),+ _select(+ "perf_refresh_rate", "Refresh Rate", REFRESH_RATES, None, "Match your monitor."+ ),+ _select(+ "perf_fps_cap",+ "FPS Limit",+ FPS_CAPS,+ None,+ "Unlimited lets the game render as many frames as your PC can.",+ ),+ _select(+ "perf_vsync",+ "V-Sync",+ ["Off", "On", "Adaptive"],+ "Off",+ "Off for the lowest latency.",+ ),+ _toggle("perf_vrr", "G-Sync / FreeSync", True),+ _toggle("perf_hdr", "HDR", False),+ _slider("perf_brightness", "Brightness", 0, 100, 1, 50),+ ],+ },+ {+ "id": "rendering",+ "settings": [+ _select("perf_preset", "Quality Preset", [*QUALITY, "Custom"], "High"),+ _slider(+ "perf_render_scale",+ "Render Scale",+ 50,+ 200,+ 5,+ 100,+ "Percent of your resolution the game renders at. Above 100 % supersamples.",+ ),+ _select(+ "perf_upscaler",+ "Upscaler",+ ["Off", "DLSS", "FSR", "XeSS", "TSR"],+ "Off",+ "DLSS needs an NVIDIA RTX card; FSR and XeSS run on any GPU.",+ ),+ _select(+ "perf_upscaler_mode",+ "Upscaler Mode",+ ["Native AA", "Quality", "Balanced", "Performance", "Ultra Performance"],+ "Quality",+ ),+ _slider("perf_sharpening", "Sharpening", 0, 100, 1, 50),+ _toggle(+ "perf_frame_gen",+ "Frame Generation",+ False,+ "More frames on screen, slightly more latency. Not for competitive play.",+ ),+ _select(+ "perf_low_latency",+ "Low Latency (Reflex / Anti-Lag)",+ ["Off", "On", "On + Boost"],+ "On",+ ),+ _select(+ "perf_gpu_priority",+ "Prioritize",+ ["Balanced", "Frame Rate", "Image Quality"],+ "Balanced",+ ),+ ],+ },+ {+ "id": "detail",+ "settings": [+ _quality(+ "perf_textures", "Texture Quality", "Uses VRAM, barely affects FPS when it fits."+ ),+ _quality("perf_shadows", "Shadow Quality"),+ _quality("perf_effects", "Effects Quality"),+ _quality("perf_post", "Post-Processing"),+ _quality("perf_view_distance", "View Distance"),+ _quality("perf_foliage", "Foliage / Vegetation"),+ _quality("perf_geometry", "Mesh / Model Detail"),+ _quality("perf_volumetrics", "Volumetric Fog & Clouds"),+ _select(+ "perf_aa",+ "Anti-Aliasing",+ ["Off", "FXAA", "SMAA", "TAA", "MSAA 2x", "MSAA 4x", "MSAA 8x"],+ "TAA",+ ),+ _select("perf_af", "Anisotropic Filtering", ["Off", "2x", "4x", "8x", "16x"], "16x"),+ _select("perf_ao", "Ambient Occlusion", ["Off", "SSAO", "HBAO+", "Ray Traced"], "SSAO"),+ ],+ },+ {+ "id": "raytracing",+ "settings": [+ _select(+ "perf_rt",+ "Ray Tracing",+ ["Off", "Low", "Medium", "High", "Ultra", "Path Tracing"],+ "Off",+ ),+ _select(+ "perf_rt_reflections", "RT Reflections", ["Off", "Low", "Medium", "High"], "Off"+ ),+ _select(+ "perf_rt_gi", "RT Global Illumination", ["Off", "Low", "Medium", "High"], "Off"+ ),+ _toggle("perf_ray_reconstruction", "Ray Reconstruction", False, "DLSS 3.5+ only."),+ ],+ },+ {+ "id": "effects",+ "settings": [+ _toggle("perf_motion_blur", "Motion Blur", False),+ _toggle("perf_dof", "Depth of Field", False),+ _toggle("perf_film_grain", "Film Grain", False),+ _toggle("perf_chromatic", "Chromatic Aberration", False),+ _toggle("perf_lens_flare", "Lens Flare", False),+ _toggle("perf_bloom", "Bloom", True),+ _toggle("perf_vignette", "Vignette", False),+ ],+ },+]++_DETAIL_KEYS = [+ "perf_textures",+ "perf_shadows",+ "perf_effects",+ "perf_post",+ "perf_view_distance",+ "perf_foliage",+ "perf_geometry",+ "perf_volumetrics",+]+_EFFECT_KEYS = [+ "perf_motion_blur",+ "perf_dof",+ "perf_film_grain",+ "perf_chromatic",+ "perf_lens_flare",+ "perf_vignette",+]+++def _details(level: str, **overrides: str) -> dict[str, Any]:+ out: dict[str, Any] = {key: level for key in _DETAIL_KEYS}+ out.update(overrides)+ return out+++def _effects(on: bool) -> dict[str, Any]:+ return {key: on for key in _EFFECT_KEYS}+++#: One-click bundles. Resolution, refresh rate and the FPS cap of a preset+#: that says "native"/"monitor" are filled from the detected monitor by the page.+PRESETS: list[dict[str, Any]] = [+ {+ "id": "competitive",+ "values": {+ "perf_preset": "Custom",+ "perf_display_mode": "Fullscreen",+ "perf_fps_cap": UNLIMITED,+ "perf_vsync": "Off",+ "perf_vrr": False,+ "perf_render_scale": 100,+ "perf_upscaler": "Off",+ "perf_frame_gen": False,+ "perf_low_latency": "On + Boost",+ "perf_gpu_priority": "Frame Rate",+ **_details("Low", perf_textures="Medium", perf_view_distance="High"),+ "perf_aa": "FXAA",+ "perf_af": "8x",+ "perf_ao": "Off",+ "perf_rt": "Off",+ "perf_rt_reflections": "Off",+ "perf_rt_gi": "Off",+ "perf_ray_reconstruction": False,+ **_effects(False),+ "perf_bloom": False,+ "perf_sharpening": 60,+ },+ },+ {+ "id": "balanced",+ "values": {+ "perf_preset": "High",+ "perf_display_mode": "Fullscreen",+ "perf_fps_cap": "monitor",+ "perf_vsync": "Off",+ "perf_vrr": True,+ "perf_render_scale": 100,+ "perf_upscaler": "DLSS",+ "perf_upscaler_mode": "Quality",+ "perf_frame_gen": False,+ "perf_low_latency": "On",+ "perf_gpu_priority": "Balanced",+ **_details("High", perf_shadows="Medium", perf_volumetrics="Medium"),+ "perf_aa": "TAA",+ "perf_af": "16x",+ "perf_ao": "SSAO",+ "perf_rt": "Off",+ "perf_rt_reflections": "Off",+ "perf_rt_gi": "Off",+ **_effects(False),+ "perf_bloom": True,+ "perf_sharpening": 50,+ },+ },+ {+ "id": "quality",+ "values": {+ "perf_preset": "Ultra",+ "perf_display_mode": "Fullscreen",+ "perf_fps_cap": "monitor",+ "perf_vsync": "Off",+ "perf_vrr": True,+ "perf_render_scale": 100,+ "perf_upscaler": "DLSS",+ "perf_upscaler_mode": "Native AA",+ "perf_frame_gen": False,+ "perf_low_latency": "On",+ "perf_gpu_priority": "Image Quality",+ **_details("Ultra"),+ "perf_aa": "TAA",+ "perf_af": "16x",+ "perf_ao": "HBAO+",+ "perf_rt": "Medium",+ "perf_rt_reflections": "Medium",+ "perf_rt_gi": "Medium",+ "perf_ray_reconstruction": True,+ **_effects(False),+ "perf_bloom": True,+ "perf_dof": True,+ "perf_sharpening": 40,+ },+ },+ {+ "id": "epic",+ "values": {+ "perf_preset": "Epic",+ "perf_display_mode": "Fullscreen",+ "perf_fps_cap": UNLIMITED,+ "perf_vsync": "Off",+ "perf_vrr": True,+ "perf_render_scale": 100,+ "perf_upscaler": "DLSS",+ "perf_upscaler_mode": "Quality",+ "perf_frame_gen": True,+ "perf_low_latency": "On + Boost",+ "perf_gpu_priority": "Image Quality",+ **_details("Epic"),+ "perf_aa": "TAA",+ "perf_af": "16x",+ "perf_ao": "Ray Traced",+ "perf_rt": "Path Tracing",+ "perf_rt_reflections": "High",+ "perf_rt_gi": "High",+ "perf_ray_reconstruction": True,+ **_effects(False),+ "perf_bloom": True,+ "perf_dof": True,+ "perf_lens_flare": True,+ "perf_hdr": True,+ "perf_sharpening": 35,+ },+ },+]+++def performance_sections() -> list[dict[str, Any]]:+ """A fresh copy of the block as catalog sections (``perf_<group>``)."""+ return [+ {"id": f"perf_{group['id']}", "settings": copy.deepcopy(group["settings"])}+ for group in PERFORMANCE_GROUPS+ ]+++def presets() -> list[dict[str, Any]]:+ return copy.deepcopy(PRESETS)diff --git a/dodaios/games/store.py b/dodaios/games/store.pyindex 566e1bd382..21bf034c85 100644--- a/dodaios/games/store.py+++ b/dodaios/games/store.py@@ -5,8 +5,14 @@ Lives at ``<DATA_DIR>/games/profiles.json``::{"version": 1, "dpi": 800,"games": {"fortnite": {"values": {"mouse_sens_x": 6.4},"keybinds": {"jump": "Space"},+ "alt_keybinds": {"jump": "Mouse Wheel Down"},+ "bind_modes": {"sprint": "toggle"},+ "custom_binds": [{"id": "c1", "action": "Quick build",+ "key": "Shift + Mouse 4", "alt": ""}],"dpi": null, "notes": "", "updated_at": "..."}}}+A key is one key or a combination joined with " + " ("Ctrl + Shift + F").+``dpi`` at the top is the mouse DPI every game uses unless its profile setsits own. Values are checked against the catalog before they are written, andthe file is replaced atomically so a crash never leaves half a file.@@ -29,7 +35,10 @@ log = logging.getLogger(__name__)DEFAULT_DPI = 800MIN_DPI, MAX_DPI = 50, 64000-MAX_KEY_LEN = 40+MAX_KEY_LEN = 60+MAX_ACTION_LEN = 60+MAX_CUSTOM_BINDS = 60+BIND_MODES = ("hold", "toggle")MAX_TEXT_LEN = 200MAX_NOTES_LEN = 4000@@ -127,7 +136,43 @@ def _game_or_raise(game_id: str) -> dict[str, Any]:def _blank_profile() -> dict[str, Any]:- return {"values": {}, "keybinds": {}, "dpi": None, "notes": "", "updated_at": None}+ return {+ "values": {},+ "keybinds": {},+ "alt_keybinds": {},+ "bind_modes": {},+ "custom_binds": [],+ "dpi": None,+ "notes": "",+ "updated_at": None,+ }+++def check_custom_binds(value: Any) -> list[dict[str, str]]:+ """The player's own actions: a list of ``{id, action, key, alt}``."""+ if not isinstance(value, list) or len(value) > MAX_CUSTOM_BINDS:+ raise ValueError(f"Custom actions are a list of at most {MAX_CUSTOM_BINDS}")+ out: list[dict[str, str]] = []+ seen: set[str] = set()+ for row in value:+ if not isinstance(row, dict):+ raise ValueError("A custom action needs an id, a name and a key")+ row_id = row.get("id")+ action = row.get("action")+ if not isinstance(row_id, str) or not row_id or len(row_id) > 40 or row_id in seen:+ raise ValueError("Each custom action needs its own id")+ if not isinstance(action, str) or len(action.strip()) > MAX_ACTION_LEN:+ raise ValueError(f"A custom action name is text up to {MAX_ACTION_LEN} characters")+ seen.add(row_id)+ out.append(+ {+ "id": row_id,+ "action": action.strip(),+ "key": check_key(row.get("key", "")),+ "alt": check_key(row.get("alt", "")),+ }+ )+ return outclass GameProfileStore:@@ -159,6 +204,9 @@ class GameProfileStore:*,values: dict[str, Any] | None = None,keybinds: dict[str, Any] | None = None,+ alt_keybinds: dict[str, Any] | None = None,+ bind_modes: dict[str, Any] | None = None,+ custom_binds: list[Any] | None = None,dpi: Any = ...,notes: str | None = None,) -> dict[str, Any]:@@ -177,11 +225,25 @@ class GameProfileStore:if key not in settings:raise ValueError(f"Unknown setting: {key}")clean_values[key] = check_value(settings[key], value)- clean_binds: dict[str, str | None] = {}- for key, value in (keybinds or {}).items():++ def clean_map(raw: dict[str, Any] | None) -> dict[str, str | None]:+ out: dict[str, str | None] = {}+ for key, value in (raw or {}).items():+ if key not in binds:+ raise ValueError(f"Unknown keybind: {key}")+ out[key] = None if value is None else check_key(value)+ return out++ clean_binds = clean_map(keybinds)+ clean_alts = clean_map(alt_keybinds)+ clean_modes: dict[str, str | None] = {}+ for key, value in (bind_modes or {}).items():if key not in binds:raise ValueError(f"Unknown keybind: {key}")- clean_binds[key] = None if value is None else check_key(value)+ if value is not None and value not in BIND_MODES:+ raise ValueError("A keybind mode is hold or toggle")+ clean_modes[key] = value+ clean_custom = None if custom_binds is None else check_custom_binds(custom_binds)clean_dpi = None if dpi is None or dpi is ... else check_dpi(dpi)if notes is not None and (not isinstance(notes, str) or len(notes) > MAX_NOTES_LEN):raise ValueError(f"Notes are text up to {MAX_NOTES_LEN} characters")@@ -194,11 +256,19 @@ class GameProfileStore:profile["values"].pop(key, None)else:profile["values"][key] = value- for key, value in clean_binds.items():- if value is None:- profile["keybinds"].pop(key, None)- else:- profile["keybinds"][key] = value+ for field, changes in (+ ("keybinds", clean_binds),+ ("alt_keybinds", clean_alts),+ ("bind_modes", clean_modes),+ ):+ target = profile.setdefault(field, {})+ for key, value in changes.items():+ if value is None:+ target.pop(key, None)+ else:+ target[key] = value+ if clean_custom is not None:+ profile["custom_binds"] = clean_customif dpi is not ...:profile["dpi"] = clean_dpiif notes is not None:diff --git a/dodaios/games/system.py b/dodaios/games/system.pynew file mode 100644index 0000000000..1fd439b039--- /dev/null+++ b/dodaios/games/system.py@@ -0,0 +1,272 @@+"""What this PC can do for games: GPU, CPU, RAM and the monitors.++Read once per process and cached: none of it changes while the app runs+often enough to matter, and the probes (nvidia-smi, PowerShell) take a moment.+Every probe fails soft to ``None`` so a headless or non-Windows host still+answers.+"""++from __future__ import annotations++import logging+import platform+import re+import subprocess+import sys+from functools import lru_cache+from typing import Any++log = logging.getLogger(__name__)+++def _cpu_name() -> str | None:+ if sys.platform == "win32":+ try:+ import winreg++ key = winreg.OpenKey(+ winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0"+ )+ value, _ = winreg.QueryValueEx(key, "ProcessorNameString")+ return str(value).strip() or None+ except OSError:+ log.debug("games.system: CPU name not in the registry", exc_info=True)+ return platform.processor() or None+++def _gpus() -> list[dict[str, Any]]:+ from dodaios.hardware.detection import _detect_nvidia_gpus++ found = [{"name": g.name, "vram_gb": round(g.vram_mb / 1024, 1)} for g in _detect_nvidia_gpus()]+ if found or sys.platform != "win32":+ return found+ # Any vendor on Windows. AdapterRAM is a 32-bit field (caps at 4 GB), so+ # VRAM is left out rather than reported wrong.+ try:+ out = subprocess.run(+ [+ "powershell",+ "-NoProfile",+ "-Command",+ "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name",+ ],+ capture_output=True,+ text=True,+ timeout=10,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ ).stdout+ except (OSError, subprocess.SubprocessError):+ log.debug("games.system: video controller query failed", exc_info=True)+ return []+ names = [line.strip() for line in out.splitlines() if line.strip()]+ skip = re.compile(r"basic display|remote|virtual|parsec|meta", re.I)+ return [{"name": name, "vram_gb": None} for name in names if not skip.search(name)]+++def _ram_gb() -> float | None:+ try:+ import psutil++ return round(psutil.virtual_memory().total / 1024**3)+ except ImportError: # psutil is optional; the page shows RAM as unknown+ return None+++def _monitors_windows() -> list[dict[str, Any]]:+ import ctypes+ from ctypes import wintypes++ class DISPLAY_DEVICEW(ctypes.Structure): # noqa: N801 - Win32 name+ _fields_ = [+ ("cb", wintypes.DWORD),+ ("DeviceName", wintypes.WCHAR * 32),+ ("DeviceString", wintypes.WCHAR * 128),+ ("StateFlags", wintypes.DWORD),+ ("DeviceID", wintypes.WCHAR * 128),+ ("DeviceKey", wintypes.WCHAR * 128),+ ]++ class DEVMODEW(ctypes.Structure): # noqa: N801 - Win32 name+ _fields_ = [+ ("dmDeviceName", wintypes.WCHAR * 32),+ ("dmSpecVersion", wintypes.WORD),+ ("dmDriverVersion", wintypes.WORD),+ ("dmSize", wintypes.WORD),+ ("dmDriverExtra", wintypes.WORD),+ ("dmFields", wintypes.DWORD),+ ("dmPositionX", wintypes.LONG),+ ("dmPositionY", wintypes.LONG),+ ("dmDisplayOrientation", wintypes.DWORD),+ ("dmDisplayFixedOutput", wintypes.DWORD),+ ("dmColor", wintypes.SHORT),+ ("dmDuplex", wintypes.SHORT),+ ("dmYResolution", wintypes.SHORT),+ ("dmTTOption", wintypes.SHORT),+ ("dmCollate", wintypes.SHORT),+ ("dmFormName", wintypes.WCHAR * 32),+ ("dmLogPixels", wintypes.WORD),+ ("dmBitsPerPel", wintypes.DWORD),+ ("dmPelsWidth", wintypes.DWORD),+ ("dmPelsHeight", wintypes.DWORD),+ ("dmDisplayFlags", wintypes.DWORD),+ ("dmDisplayFrequency", wintypes.DWORD),+ ("dmICMMethod", wintypes.DWORD),+ ("dmICMIntent", wintypes.DWORD),+ ("dmMediaType", wintypes.DWORD),+ ("dmDitherType", wintypes.DWORD),+ ("dmReserved1", wintypes.DWORD),+ ("dmReserved2", wintypes.DWORD),+ ("dmPanningWidth", wintypes.DWORD),+ ("dmPanningHeight", wintypes.DWORD),+ ]++ user32 = ctypes.windll.user32+ attached = 0x1+ primary = 0x4+ current = -1 # ENUM_CURRENT_SETTINGS+ monitors: list[dict[str, Any]] = []+ index = 0+ while True:+ device = DISPLAY_DEVICEW()+ device.cb = ctypes.sizeof(device)+ if not user32.EnumDisplayDevicesW(None, index, ctypes.byref(device), 0):+ break+ index += 1+ if not device.StateFlags & attached:+ continue+ mode = DEVMODEW()+ mode.dmSize = ctypes.sizeof(mode)+ if not user32.EnumDisplaySettingsW(device.DeviceName, current, ctypes.byref(mode)):+ continue+ max_w, max_h, max_hz = mode.dmPelsWidth, mode.dmPelsHeight, mode.dmDisplayFrequency+ n = 0+ probe = DEVMODEW()+ probe.dmSize = ctypes.sizeof(probe)+ while user32.EnumDisplaySettingsW(device.DeviceName, n, ctypes.byref(probe)):+ n += 1+ if probe.dmPelsWidth * probe.dmPelsHeight > max_w * max_h:+ max_w, max_h = probe.dmPelsWidth, probe.dmPelsHeight+ # Highest refresh at the resolution in use, not at some lower mode.+ same_size = (probe.dmPelsWidth, probe.dmPelsHeight) == (+ mode.dmPelsWidth,+ mode.dmPelsHeight,+ )+ if same_size and probe.dmDisplayFrequency > max_hz:+ max_hz = probe.dmDisplayFrequency+ if n > 2000:+ break+ monitors.append(+ {+ "name": f"Display {len(monitors) + 1}",+ "primary": bool(device.StateFlags & primary),+ "width": int(mode.dmPelsWidth),+ "height": int(mode.dmPelsHeight),+ "refresh_hz": _nominal_hz(int(mode.dmDisplayFrequency)),+ "max_width": int(max_w),+ "max_height": int(max_h),+ "max_refresh_hz": _nominal_hz(int(max_hz)),+ }+ )+ monitors.sort(key=lambda m: not m["primary"])+ return monitors+++def _nominal_hz(hz: int) -> int:+ """59 -> 60, 143 -> 144: Windows reports fractional rates rounded down."""+ common = {+ 24,+ 30,+ 48,+ 60,+ 75,+ 90,+ 100,+ 120,+ 144,+ 165,+ 170,+ 180,+ 200,+ 240,+ 280,+ 300,+ 360,+ 480,+ 540,+ }+ return hz + 1 if hz not in common and hz + 1 in common else hz+++def _monitors() -> list[dict[str, Any]]:+ if sys.platform != "win32":+ return []+ try:+ return _monitors_windows()+ except (OSError, AttributeError, ValueError):+ log.debug("games.system: monitor enumeration failed", exc_info=True)+ return []+++def gpu_tier(gpus: list[dict[str, Any]]) -> str | None:+ """A rough class for picking a preset: entry, mid, high or enthusiast.++ From VRAM when it is known, else from the model number in the name+ (RTX 4090 / RX 7900 → enthusiast). ``None`` when nothing says.+ """+ best: str | None = None+ order = ["entry", "mid", "high", "enthusiast"]+ for gpu in gpus:+ tier = _tier_of(gpu)+ if tier and (best is None or order.index(tier) > order.index(best)):+ best = tier+ return best+++def _rank(value: float, steps: tuple[float, float, float]) -> str:+ """entry / mid / high / enthusiast for ``value`` against three thresholds."""+ mid, high, top = steps+ if value >= top:+ return "enthusiast"+ if value >= high:+ return "high"+ return "mid" if value >= mid else "entry"+++def _tier_of(gpu: dict[str, Any]) -> str | None:+ name = str(gpu.get("name") or "").lower()+ vram = gpu.get("vram_gb")+ m = re.search(r"(?:rtx|gtx)\s*(\d{4})", name) or re.search(r"rx\s*(\d{4})", name)+ if m:+ model = int(m.group(1))+ series, rank = model // 1000, model % 100+ if "rx" in name and "rtx" not in name:+ # RX 7900 / 7600: the class is the hundreds digit.+ return _rank((model % 1000) // 10, (60, 70, 90))+ if series >= 3:+ return _rank(rank, (60, 70, 80))+ return "mid" if rank >= 70 else "entry"+ if isinstance(vram, (int, float)):+ return _rank(vram, (6, 10, 16))+ return None+++@lru_cache(maxsize=1)+def system_info() -> dict[str, Any]:+ gpus = _gpus()+ monitors = _monitors()+ tier = gpu_tier(gpus)+ recommended = {+ "enthusiast": "epic",+ "high": "quality",+ "mid": "balanced",+ "entry": "competitive",+ }+ return {+ "os": platform.system(),+ "cpu": _cpu_name(),+ "ram_gb": _ram_gb(),+ "gpus": gpus,+ "monitors": monitors,+ "gpu_tier": tier,+ "recommended_preset": recommended.get(tier or "", None),+ }diff --git a/dodaios/ui/web/frontend/src/components/games/GameControls.tsx b/dodaios/ui/web/frontend/src/components/games/GameControls.tsxindex 31fb28fc64..ae6ce3ecd4 100644--- a/dodaios/ui/web/frontend/src/components/games/GameControls.tsx+++ b/dodaios/ui/web/frontend/src/components/games/GameControls.tsx@@ -1,18 +1,27 @@/**- * The building blocks of Settings → Game settings: one row per game setting- * (slider, number, choice, switch or text) and the keybind capture button.+ * The building blocks of Settings → Game settings: one row per setting+ * (segmented choice, filled slider, number, switch, text) and the keybind+ * capture button that records combinations ("Shift + Mouse 4").** Rows keep a local draft while the user drags or types and hand the value* up only when it is settled (pointer up, blur, Enter), so a slider drag is* one save, not fifty.*/-import { useEffect, useRef, useState, type ReactNode } from "react";+import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";import { RotateCcw } from "lucide-react";import { Input } from "@/components/ui/input";import { BrandedSelect } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";import { useT } from "@/i18n";-import { keyNameFromCode, mouseButtonName, wheelName } from "@/lib/gameKeys";+import {+ MODIFIER_CODES,+ comboName,+ comboParts,+ keyNameFromCode,+ mouseButtonName,+ wheelName,+ type HeldModifiers,+} from "@/lib/gameKeys";import type { GameSetting, GameSettingValue } from "@/lib/gamesApi";import { cn } from "@/lib/utils";@@ -23,6 +32,59 @@ function formatDefault(setting: GameSetting, t: (key: string) => string): stringreturn String(value);}+/** A choice short enough to show every option at once instead of a dropdown. */+export function fitsSegmented(options: readonly string[]): boolean {+ return options.length >= 2 && options.length <= 7 && options.join("").length <= 64;+}++export function Segmented({+ options,+ value,+ onChange,+ label,+ className,+}: {+ options: readonly { value: string; label: string }[];+ value: string | null;+ onChange: (value: string) => void;+ label: string;+ className?: string;+}) {+ return (+ <div+ role="radiogroup"+ aria-label={label}+ className={cn(+ "inline-flex max-w-full flex-wrap gap-0.5 rounded-lg border border-border bg-background/60 p-0.5",+ className,+ )}+ >+ {options.map((option) => {+ const active = option.value === value;+ return (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => onChange(option.value)}+ className={cn(+ "rounded-md px-2.5 py-1 text-xs font-medium transition-all",+ // Inside a game's page the active segment wears the game's hue;+ // anywhere else it falls back to the app's signal colour.+ active+ ? "bg-[var(--game-accent,hsl(var(--accent)))] font-semibold text-black shadow-[0_0_12px_var(--game-accent-glow,hsl(var(--accent)/0.45))]"+ : "text-muted-foreground hover:bg-secondary hover:text-foreground",+ )}+ >+ {option.label}+ </button>+ );+ })}+ </div>+ );+}+function SettingShell({setting,saved,@@ -39,14 +101,12 @@ function SettingShell({return (<divdata-testid={`game-setting-${setting.key}`}- className="flex flex-col gap-2 border-b border-border/60 py-3 last:border-b-0 sm:flex-row sm:items-center sm:gap-6"+ className="group flex flex-col gap-2 border-b border-border/50 py-3 last:border-b-0 md:flex-row md:items-center md:gap-6">- <div className="min-w-0 sm:w-[42%]">+ <div className="min-w-0 md:w-[38%]"><div className="flex items-center gap-2"><span className="text-sm font-medium text-foreground">{setting.label}</span>- {saved && (- <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />- )}+ {saved && <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-accent" />}</div>{(setting.note || fallback) && (<p className="mt-0.5 text-xs text-muted-foreground">@@ -82,7 +142,7 @@ function toNumber(raw: string): number | null {return Number.isFinite(value) ? value : null;}-function NumberField({+export function NumberField({value,setting,onCommit,@@ -120,6 +180,55 @@ function NumberField({);}+/**+ * A range input whose track fills up to the thumb in the signal colour. The+ * fill is a background gradient driven by one CSS variable, so it follows+ * the drag without React re-rendering the track.+ */+export function FilledRange({+ min,+ max,+ step,+ value,+ label,+ dim,+ onDraft,+ onCommit,+}: {+ min: number;+ max: number;+ step?: number;+ value: number;+ label: string;+ dim?: boolean;+ onDraft: (value: number) => void;+ onCommit: () => void;+}) {+ const pct = max > min ? ((value - min) / (max - min)) * 100 : 0;+ return (+ <input+ type="range"+ min={min}+ max={max}+ step={step ?? "any"}+ value={value}+ aria-label={label}+ onChange={(event) => onDraft(Number(event.currentTarget.value))}+ onPointerUp={onCommit}+ onKeyUp={onCommit}+ onBlur={onCommit}+ style={{ "--fill": `${pct}%` } as CSSProperties}+ className={cn(+ "h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full",+ "bg-[linear-gradient(to_right,hsl(var(--accent))_var(--fill),hsl(var(--border))_var(--fill))]",+ "[&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-accent [&::-webkit-slider-thumb]:bg-background [&::-webkit-slider-thumb]:shadow-[0_0_10px_hsl(var(--accent)/0.6)]",+ "[&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-2 [&::-moz-range-thumb]:border-accent [&::-moz-range-thumb]:bg-background",+ dim && "opacity-50",+ )}+ />+ );+}+export function GameSettingRow({setting,value,@@ -148,16 +257,27 @@ export function GameSettingRow({}if (setting.type === "select") {+ const options = setting.options ?? [];+ const current = typeof effective === "string" ? effective : null;return (<SettingShell setting={setting} saved={saved} onReset={reset}>- <BrandedSelect- value={typeof effective === "string" ? effective : ""}- options={(setting.options ?? []).map((option) => ({ value: option, label: option }))}- onValueChange={(next) => onChange(next)}- ariaLabel={setting.label}- placeholder={t("games.unset")}- className="h-8 w-full max-w-xs"- />+ {fitsSegmented(options) ? (+ <Segmented+ label={setting.label}+ value={current}+ options={options.map((option) => ({ value: option, label: option }))}+ onChange={(next) => onChange(next)}+ />+ ) : (+ <BrandedSelect+ value={current ?? ""}+ options={options.map((option) => ({ value: option, label: option }))}+ onValueChange={(next) => onChange(next)}+ ariaLabel={setting.label}+ placeholder={t("games.unset")}+ className="h-8 w-full max-w-xs"+ />+ )}</SettingShell>);}@@ -180,7 +300,12 @@ export function GameSettingRow({{setting.type === "slider" ? (<SliderField setting={setting} value={numeric} saved={saved} onCommit={onChange} />) : (- <NumberField setting={setting} value={saved ? numeric : null} onCommit={onChange} className="max-w-[10rem]" />+ <NumberField+ setting={setting}+ value={saved ? numeric : null}+ onCommit={onChange}+ className="max-w-[10rem]"+ />)}</SettingShell>);@@ -202,28 +327,24 @@ function SliderField({const [draft, setDraft] = useState<number>(value ?? min);const dirty = useRef(false);useEffect(() => setDraft(value ?? min), [value, min]);- const commit = () => {- if (!dirty.current) return;- dirty.current = false;- onCommit(draft);- };return (<div className="flex items-center gap-3">- <input- type="range"+ <FilledRangemin={min}max={max}- step={setting.step ?? "any"}+ step={setting.step}value={draft}- aria-label={setting.label}- onChange={(event) => {+ label={setting.label}+ dim={!saved && value === null}+ onDraft={(next) => {dirty.current = true;- setDraft(Number(event.currentTarget.value));+ setDraft(next);+ }}+ onCommit={() => {+ if (!dirty.current) return;+ dirty.current = false;+ onCommit(draft);}}- onPointerUp={commit}- onKeyUp={commit}- onBlur={commit}- className={cn("h-1 min-w-0 flex-1 cursor-pointer accent-primary", !saved && value === null && "opacity-50")}/><NumberFieldsetting={setting}@@ -261,83 +382,134 @@ function TextField({);}+/** A bind drawn as keycaps: "Shift + Mouse 4" → [Shift] + [Mouse 4]. */+export function Keycaps({ combo, empty }: { combo: string; empty: string }) {+ const parts = comboParts(combo);+ if (parts.length === 0) return <span className="text-muted-foreground">{empty}</span>;+ return (+ <span className="inline-flex items-center gap-1">+ {parts.map((part, index) => (+ <span key={`${part}-${index}`} className="inline-flex items-center gap-1">+ {index > 0 && <span className="text-muted-foreground/60">+</span>}+ <kbd className="rounded border border-border-strong bg-background px-1.5 py-0.5 font-mono text-[11px] text-foreground shadow-[inset_0_-2px_0_hsl(var(--border))]">+ {part}+ </kbd>+ </span>+ ))}+ </span>+ );+}+/**- * A button that shows the bound key; click it, then press a key, click a- * mouse button or turn the wheel to bind. Escape cancels. While listening,- * the press is swallowed so app shortcuts do not fire.+ * A button that shows the bound key; click it, then press a key, a mouse+ * button or turn the wheel — while holding Ctrl / Shift / Alt for a+ * combination. A modifier pressed and released alone binds itself ("Left+ * Shift" for sprint). Escape cancels. While listening, presses are swallowed+ * so app shortcuts do not fire.*/export function KeyCaptureButton({value,label,onCapture,+ compact,}: {value: string;label: string;onCapture: (key: string) => void;+ compact?: boolean;}) {const t = useT();const [listening, setListening] = useState(false);- const buttonRef = useRef<HTMLButtonElement>(null);+ const [held, setHeld] = useState<HeldModifiers>({ ctrl: false, shift: false, alt: false });+ const captureRef = useRef(onCapture);+ captureRef.current = onCapture;useEffect(() => {if (!listening) return;+ let mods: HeldModifiers = { ctrl: false, shift: false, alt: false };+ let lastModifier: string | null = null;const finish = (key: string | null) => {setListening(false);- if (key) onCapture(key);+ setHeld({ ctrl: false, shift: false, alt: false });+ if (key) captureRef.current(key);};- const onKey = (event: KeyboardEvent) => {+ const swallow = (event: Event) => {event.preventDefault();event.stopPropagation();+ };+ const onKeyDown = (event: KeyboardEvent) => {+ swallow(event);if (event.code === "Escape") return finish(null);- finish(keyNameFromCode(event.code));+ if (MODIFIER_CODES.has(event.code)) {+ mods = { ctrl: event.ctrlKey, shift: event.shiftKey, alt: event.altKey };+ lastModifier = keyNameFromCode(event.code);+ setHeld(mods);+ return;+ }+ const name = keyNameFromCode(event.code);+ if (name) finish(comboName({ ctrl: event.ctrlKey, shift: event.shiftKey, alt: event.altKey }, name));+ };+ const onKeyUp = (event: KeyboardEvent) => {+ swallow(event);+ // A modifier pressed and let go on its own binds the modifier itself.+ if (MODIFIER_CODES.has(event.code) && lastModifier === keyNameFromCode(event.code)) {+ const others = { ...mods };+ if (/Ctrl$/.test(lastModifier ?? "")) others.ctrl = false;+ if (/Shift$/.test(lastModifier ?? "")) others.shift = false;+ if (/Alt$/.test(lastModifier ?? "")) others.alt = false;+ finish(comboName(others, lastModifier as string));+ }};const onMouse = (event: MouseEvent) => {- event.preventDefault();- event.stopPropagation();- finish(mouseButtonName(event.button));+ swallow(event);+ const name = mouseButtonName(event.button);+ if (name) finish(comboName({ ctrl: event.ctrlKey, shift: event.shiftKey, alt: event.altKey }, name));};const onWheel = (event: WheelEvent) => {- event.preventDefault();- event.stopPropagation();- if (event.deltaY !== 0) finish(wheelName(event.deltaY));- };- const block = (event: Event) => {- event.preventDefault();- event.stopPropagation();+ swallow(event);+ if (event.deltaY !== 0) {+ finish(comboName({ ctrl: event.ctrlKey, shift: event.shiftKey, alt: event.altKey }, wheelName(event.deltaY)));+ }};// Registered on the next tick so the click that started listening is not// itself taken as the binding.const timer = window.setTimeout(() => {- window.addEventListener("keydown", onKey, true);+ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("keyup", onKeyUp, true);window.addEventListener("mousedown", onMouse, true);window.addEventListener("wheel", onWheel, { capture: true, passive: false });- window.addEventListener("contextmenu", block, true);+ window.addEventListener("contextmenu", swallow, true);}, 0);return () => {window.clearTimeout(timer);- window.removeEventListener("keydown", onKey, true);+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("keyup", onKeyUp, true);window.removeEventListener("mousedown", onMouse, true);window.removeEventListener("wheel", onWheel, true);- window.removeEventListener("contextmenu", block, true);+ window.removeEventListener("contextmenu", swallow, true);};- }, [listening, onCapture]);+ }, [listening]);+ const heldText = comboParts(comboName(held, "")).join(" + ");return (<button- ref={buttonRef}type="button"aria-label={`${label}: ${value || t("games.keybind_unbound")}`}aria-pressed={listening}onClick={() => setListening(true)}className={cn(- "flex h-8 min-w-[7.5rem] items-center justify-center rounded-md border px-3 font-mono text-xs transition-colors",+ "flex h-9 items-center justify-center rounded-md border px-2.5 text-xs transition-all",+ compact ? "min-w-[6.5rem]" : "min-w-[9rem]",listening- ? "border-primary bg-primary/10 text-foreground"- : "border-border bg-muted text-foreground hover:border-border-strong",- !value && !listening && "text-muted-foreground",+ ? "animate-pulse border-accent bg-accent/10 text-foreground shadow-[0_0_14px_hsl(var(--accent)/0.5)]"+ : "border-border bg-muted/60 hover:border-border-strong hover:bg-muted",)}>- {listening ? t("games.keybind_press") : value || t("games.keybind_unbound")}+ {listening ? (+ <span className="font-mono">{heldText ? `${heldText} + …` : t("games.keybind_press")}</span>+ ) : (+ <Keycaps combo={value} empty={t("games.keybind_unbound")} />+ )}</button>);}diff --git a/dodaios/ui/web/frontend/src/components/games/KeybindPanel.tsx b/dodaios/ui/web/frontend/src/components/games/KeybindPanel.tsxnew file mode 100644index 0000000000..0395e42b02--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/games/KeybindPanel.tsx@@ -0,0 +1,391 @@+/**+ * Keybinds for one game: a keyboard and a mouse that light up where an+ * action is bound (amber where two actions collide), then every action with+ * a primary and a secondary bind — single keys or combinations like+ * "Shift + Mouse 4" — hold or toggle for actions where games offer both, and+ * the player's own extra actions.+ */+import { useState } from "react";+import { Keyboard, Mouse, Plus, Search, Trash2, X } from "lucide-react";+import { KeyCaptureButton, Segmented } from "@/components/games/GameControls";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { useT } from "@/i18n";+import { bindUsesKey, keyConflicts } from "@/lib/gameKeys";+import type { BindMode, CustomBind, GameDefinition, GameProfile, ProfilePatch } from "@/lib/gamesApi";+import { cn } from "@/lib/utils";++/** [key name, width in key units, short label]. */+type KeyCap = [string, number, string?];++const KEYBOARD: KeyCap[][] = [+ [["Escape", 1, "Esc"], ["F1", 1], ["F2", 1], ["F3", 1], ["F4", 1], ["F5", 1], ["F6", 1], ["F7", 1], ["F8", 1], ["F9", 1], ["F10", 1], ["F11", 1], ["F12", 1]],+ [["`", 1], ["1", 1], ["2", 1], ["3", 1], ["4", 1], ["5", 1], ["6", 1], ["7", 1], ["8", 1], ["9", 1], ["0", 1], ["-", 1], ["=", 1], ["Backspace", 2, "Bksp"]],+ [["Tab", 1.5], ["Q", 1], ["W", 1], ["E", 1], ["R", 1], ["T", 1], ["Y", 1], ["U", 1], ["I", 1], ["O", 1], ["P", 1], ["[", 1], ["]", 1], ["\\", 1.5]],+ [["Caps Lock", 1.75, "Caps"], ["A", 1], ["S", 1], ["D", 1], ["F", 1], ["G", 1], ["H", 1], ["J", 1], ["K", 1], ["L", 1], [";", 1], ["'", 1], ["Enter", 2.25]],+ [["Left Shift", 2.25, "Shift"], ["Z", 1], ["X", 1], ["C", 1], ["V", 1], ["B", 1], ["N", 1], ["M", 1], [",", 1], [".", 1], ["/", 1], ["Right Shift", 2.75, "Shift"]],+ [["Left Ctrl", 1.5, "Ctrl"], ["Left Win", 1.25, "Win"], ["Left Alt", 1.25, "Alt"], ["Space", 6.5], ["Right Alt", 1.25, "Alt"], ["Right Ctrl", 1.5, "Ctrl"]],+];++const MOUSE_INPUTS = ["Left Mouse", "Right Mouse", "Middle Mouse", "Mouse 4", "Mouse 5", "Mouse Wheel Up", "Mouse Wheel Down"];++/** Actions games commonly let you hold or toggle. */+const MODE_ACTIONS = /sprint|crouch|aim|ads|walk|lean|prone|scope|zoom|slide|run|boost|crawl/i;++interface Bound {+ id: string;+ action: string;+ key: string;+}++function newId(): string {+ return `c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;+}++export function KeybindPanel({+ game,+ profile,+ onPatch,+}: {+ game: GameDefinition;+ profile: GameProfile;+ onPatch: (patch: ProfilePatch) => void;+}) {+ const t = useT();+ const [filter, setFilter] = useState("");+ const [focusKey, setFocusKey] = useState<string | null>(null);+ const custom = profile.custom_binds ?? [];++ const rows = game.keybinds.map((bind) => ({+ ...bind,+ primary: profile.keybinds[bind.id] ?? bind.default,+ alt: profile.alt_keybinds?.[bind.id] ?? "",+ mode: profile.bind_modes?.[bind.id] ?? null,+ saved:+ bind.id in profile.keybinds ||+ bind.id in (profile.alt_keybinds ?? {}) ||+ bind.id in (profile.bind_modes ?? {}),+ }));++ // Every bind on one list, so a clash between a game action and the+ // player's own action is caught too.+ const bound: Bound[] = [+ ...rows.flatMap((r) => [+ { id: `${r.id}:p`, action: r.action, key: r.primary },+ { id: `${r.id}:a`, action: r.action, key: r.alt },+ ]),+ ...custom.flatMap((c) => [+ { id: `${c.id}:p`, action: c.action || t("games.keys.custom_unnamed"), key: c.key },+ { id: `${c.id}:a`, action: c.action || t("games.keys.custom_unnamed"), key: c.alt },+ ]),+ ];+ const conflicts = keyConflicts(bound);+ const actionsOn = (keyName: string) =>+ bound.filter((b) => b.key && bindUsesKey(b.key, keyName)).map((b) => b.action);+ const clashOn = (keyName: string) =>+ bound.some((b) => b.key && bindUsesKey(b.key, keyName) && conflicts.has(b.id));++ const needle = filter.trim().toLowerCase();+ const visible = rows.filter((r) => {+ if (focusKey && !bindUsesKey(r.primary, focusKey) && !bindUsesKey(r.alt, focusKey)) return false;+ return needle === "" || r.action.toLowerCase().includes(needle) || r.primary.toLowerCase().includes(needle);+ });++ const setCustom = (next: CustomBind[]) => onPatch({ custom_binds: next });+ const boundCount = bound.filter((b) => b.key).length;++ return (+ <div className="flex flex-col gap-5" data-testid="games-keybinds">+ <div className="grid gap-4 xl:grid-cols-[minmax(0,5fr)_minmax(0,2fr)]">+ <section className="rounded-xl border border-border bg-card/80 p-4">+ <header className="mb-3 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Keyboard className="h-4 w-4 text-[var(--game-accent)]" aria-hidden />+ <p className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">+ {t("games.keys.keyboard")}+ </p>+ </div>+ <p className="font-mono text-[11px] text-muted-foreground">+ {t("games.keys.bound_count").replace("{0}", String(boundCount))}+ </p>+ </header>+ <div className="overflow-x-auto pb-1">+ <div className="flex min-w-[640px] flex-col gap-1" data-testid="games-keyboard">+ {KEYBOARD.map((row, index) => (+ <div key={index} className={cn("flex gap-1", index === 0 && "mb-1.5")}>+ {row.map(([name, width, short]) => {+ const actions = actionsOn(name);+ const clash = clashOn(name);+ const focused = focusKey === name;+ return (+ <button+ key={name}+ type="button"+ title={actions.length ? `${name}: ${actions.join(", ")}` : name}+ data-testid={`games-key-${name}`}+ data-bound={actions.length > 0}+ onClick={() => setFocusKey(focused ? null : name)}+ style={{ flex: `${width} 1 0` }}+ className={cn(+ "relative h-9 min-w-0 truncate rounded-md border px-1 font-mono text-[10px] transition-all",+ clash+ ? "border-warning bg-warning/20 text-foreground-strong"+ : actions.length+ ? "border-[var(--game-accent)] bg-[var(--game-accent-soft)] text-foreground-strong shadow-[0_0_10px_var(--game-accent-glow)]"+ : "border-border bg-background/60 text-muted-foreground hover:border-border-strong",+ focused && "ring-2 ring-[var(--game-accent)] ring-offset-1 ring-offset-background",+ )}+ >+ {short ?? name}+ {actions.length > 1 && (+ <span className="absolute right-0.5 top-0 text-[8px] text-[var(--game-accent)]">+ {actions.length}+ </span>+ )}+ </button>+ );+ })}+ </div>+ ))}+ </div>+ </div>+ </section>++ <section className="rounded-xl border border-border bg-card/80 p-4" data-testid="games-mouse">+ <header className="mb-3 flex items-center gap-2">+ <Mouse className="h-4 w-4 text-[var(--game-accent)]" aria-hidden />+ <p className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">+ {t("games.keys.mouse")}+ </p>+ </header>+ <ul className="flex flex-col gap-1">+ {MOUSE_INPUTS.map((name) => {+ const actions = actionsOn(name);+ const focused = focusKey === name;+ return (+ <li key={name}>+ <button+ type="button"+ onClick={() => setFocusKey(focused ? null : name)}+ className={cn(+ "flex w-full items-center justify-between gap-3 rounded-md border px-2.5 py-1.5 text-left transition-colors",+ clashOn(name)+ ? "border-warning bg-warning/15"+ : actions.length+ ? "border-[var(--game-accent)]/50 bg-[var(--game-accent-soft)]"+ : "border-transparent hover:bg-secondary/60",+ focused && "ring-2 ring-[var(--game-accent)]",+ )}+ >+ <span className="font-mono text-[11px] text-muted-foreground">{name}</span>+ <span className="truncate text-xs text-foreground-strong">{actions.join(", ") || "—"}</span>+ </button>+ </li>+ );+ })}+ </ul>+ </section>+ </div>++ <section className="rounded-xl border border-border bg-card/80 px-4 pb-2 pt-4">+ <div className="flex flex-wrap items-center gap-3">+ <div className="relative min-w-[12rem] flex-1">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" aria-hidden />+ <Input+ value={filter}+ onChange={(event) => setFilter(event.currentTarget.value)}+ placeholder={t("games.keys.search")}+ aria-label={t("games.keys.search")}+ className="h-8 pl-8"+ />+ </div>+ {focusKey && (+ <Button type="button" variant="outline" size="sm" onClick={() => setFocusKey(null)}>+ <X aria-hidden />+ {t("games.keys.showing_key").replace("{0}", focusKey)}+ </Button>+ )}+ </div>+ <p className="mt-2 text-xs text-muted-foreground">{t("games.keybind_hint")}</p>++ <div className="mt-2 hidden grid-cols-[minmax(0,1fr)_auto_auto_7.5rem_4.5rem] gap-3 border-b border-border/60 pb-2 font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground md:grid">+ <span>{t("games.keys.action")}</span>+ <span className="w-[9rem]">{t("games.keys.primary")}</span>+ <span className="w-[9rem]">{t("games.keys.secondary")}</span>+ <span>{t("games.keys.mode")}</span>+ <span />+ </div>+ {visible.map((row) => {+ const clashP = row.primary ? conflicts.get(`${row.id}:p`) : undefined;+ const clashA = row.alt ? conflicts.get(`${row.id}:a`) : undefined;+ const clash = [...(clashP ?? []), ...(clashA ?? [])];+ return (+ <div+ key={row.id}+ data-testid={`game-keybind-${row.id}`}+ className="grid grid-cols-1 items-center gap-2 border-b border-border/50 py-2 last:border-b-0 md:grid-cols-[minmax(0,1fr)_auto_auto_7.5rem_4.5rem] md:gap-3"+ >+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm text-foreground">{row.action}</span>+ {row.saved && <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-accent" />}+ </div>+ {clash.length > 0 ? (+ <p className="text-xs text-warning">+ {t("games.keybind_conflict").replace("{0}", [...new Set(clash)].join(", "))}+ </p>+ ) : (+ row.note && <p className="text-xs text-muted-foreground">{row.note}</p>+ )}+ </div>+ <div className="flex items-center gap-1">+ <KeyCaptureButton+ value={row.primary}+ label={row.action}+ onCapture={(key) => onPatch({ keybinds: { [row.id]: key } })}+ />+ {row.primary && (+ <button+ type="button"+ aria-label={`${t("games.keybind_clear")}: ${row.action}`}+ title={t("games.keybind_clear")}+ onClick={() => onPatch({ keybinds: { [row.id]: "" } })}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"+ >+ <X className="h-3.5 w-3.5" aria-hidden />+ </button>+ )}+ </div>+ <div className="flex items-center gap-1">+ <KeyCaptureButton+ value={row.alt}+ label={`${row.action} (${t("games.keys.secondary")})`}+ onCapture={(key) => onPatch({ alt_keybinds: { [row.id]: key } })}+ />+ {row.alt && (+ <button+ type="button"+ aria-label={`${t("games.keybind_clear")}: ${row.action}`}+ onClick={() => onPatch({ alt_keybinds: { [row.id]: null } })}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"+ >+ <X className="h-3.5 w-3.5" aria-hidden />+ </button>+ )}+ </div>+ <div>+ {MODE_ACTIONS.test(row.action) ? (+ <Segmented+ label={`${row.action}: ${t("games.keys.mode")}`}+ value={row.mode ?? "hold"}+ options={[+ { value: "hold", label: t("games.keys.hold") },+ { value: "toggle", label: t("games.keys.toggle") },+ ]}+ onChange={(mode) => onPatch({ bind_modes: { [row.id]: mode as BindMode } })}+ />+ ) : (+ <span className="text-xs text-muted-foreground/50">—</span>+ )}+ </div>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className={cn("text-xs", !row.saved && "invisible")}+ onClick={() =>+ onPatch({+ keybinds: { [row.id]: null },+ alt_keybinds: { [row.id]: null },+ bind_modes: { [row.id]: null },+ })+ }+ title={row.default ? t("games.default_value").replace("{0}", row.default) : undefined}+ >+ {t("games.keybind_reset")}+ </Button>+ </div>+ );+ })}+ {visible.length === 0 && (+ <p className="py-6 text-center text-sm text-muted-foreground">{t("games.keys.nothing_found")}</p>+ )}+ </section>++ <section className="rounded-xl border border-border bg-card/80 px-4 pb-3 pt-4" data-testid="games-custom-binds">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div>+ <p className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">+ {t("games.keys.custom_eyebrow")}+ </p>+ <h3 className="text-sm font-semibold text-foreground-strong">{t("games.keys.custom_title")}</h3>+ <p className="mt-0.5 text-xs text-muted-foreground">{t("games.keys.custom_hint")}</p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ data-testid="games-add-custom"+ disabled={custom.length >= 60}+ onClick={() => setCustom([...custom, { id: newId(), action: "", key: "", alt: "" }])}+ >+ <Plus aria-hidden />+ {t("games.keys.custom_add")}+ </Button>+ </div>+ {custom.map((row, index) => (+ <CustomRow+ key={row.id}+ row={row}+ onChange={(next) => setCustom(custom.map((c, i) => (i === index ? next : c)))}+ onRemove={() => setCustom(custom.filter((_, i) => i !== index))}+ />+ ))}+ </section>+ </div>+ );+}++function CustomRow({+ row,+ onChange,+ onRemove,+}: {+ row: CustomBind;+ onChange: (row: CustomBind) => void;+ onRemove: () => void;+}) {+ const t = useT();+ const [name, setName] = useState(row.action);+ return (+ <div className="mt-2 flex flex-wrap items-center gap-2 border-t border-border/50 pt-2">+ <Input+ value={name}+ maxLength={60}+ placeholder={t("games.keys.custom_name")}+ aria-label={t("games.keys.custom_name")}+ onChange={(event) => setName(event.currentTarget.value)}+ onBlur={() => name.trim() !== row.action && onChange({ ...row, action: name.trim() })}+ className="h-9 min-w-[10rem] flex-1"+ />+ <KeyCaptureButton+ value={row.key}+ label={name || t("games.keys.custom_unnamed")}+ onCapture={(key) => onChange({ ...row, key })}+ />+ <KeyCaptureButton+ value={row.alt}+ label={`${name || t("games.keys.custom_unnamed")} (${t("games.keys.secondary")})`}+ onCapture={(alt) => onChange({ ...row, alt })}+ />+ <button+ type="button"+ aria-label={`${t("games.keys.custom_remove")}: ${name}`}+ onClick={onRemove}+ className="rounded-md p-2 text-muted-foreground hover:bg-destructive/15 hover:text-destructive"+ >+ <Trash2 className="h-4 w-4" aria-hidden />+ </button>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/games/PerformancePanel.tsx b/dodaios/ui/web/frontend/src/components/games/PerformancePanel.tsxnew file mode 100644index 0000000000..6988ac2f8b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/games/PerformancePanel.tsx@@ -0,0 +1,460 @@+/**+ * Graphics & performance for one game: what this PC is, four one-click+ * presets, resolution tiles from HD to 5K, the FPS limit up to unlimited,+ * and every rendering, detail, ray-tracing and effect setting in cards.+ * The game's own video options (as the game names them) close the page.+ */+import type { ReactNode } from "react";+import {+ Cpu,+ Crown,+ Gauge,+ Info,+ MemoryStick,+ Monitor,+ MonitorPlay,+ Sparkles,+ Sun,+ Wand2,+ Zap,+ type LucideIcon,+} from "lucide-react";+import { GameSettingRow } from "@/components/games/GameControls";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { useGameSystem } from "@/hooks/useGames";+import { useT } from "@/i18n";+import type {+ GameDefinition,+ GamePreset,+ GameProfile,+ GameSetting,+ GameSettingValue,+ ProfilePatch,+ SystemInfo,+} from "@/lib/gamesApi";+import { cn } from "@/lib/utils";++const RESOLUTION_NAMES: Record<string, string> = {+ "1280x720": "HD",+ "1600x900": "HD+",+ "1920x1080": "Full HD",+ "2560x1080": "UW Full HD",+ "2560x1440": "QHD",+ "3440x1440": "UWQHD",+ "3840x1600": "UW4K",+ "3840x2160": "4K UHD",+ "5120x1440": "DQHD",+ "5120x2160": "5K2K",+ "5120x2880": "5K",+};++const PRESET_ICONS: Record<GamePreset["id"], LucideIcon> = {+ competitive: Zap,+ balanced: Gauge,+ quality: Sparkles,+ epic: Crown,+};++/** Settings drawn by hand at the top of the display card, not as rows. */+const CUSTOM_DRAWN = new Set(["perf_resolution", "perf_fps_cap", "perf_refresh_rate"]);++type Values = Record<string, GameSettingValue>;++function primaryMonitor(system: SystemInfo | undefined) {+ return system?.monitors.find((m) => m.primary) ?? system?.monitors[0] ?? null;+}++/**+ * A preset's values for THIS PC: "monitor" becomes the highest FPS option the+ * monitor can show, and the resolution and refresh rate follow the monitor.+ */+export function resolvePreset(+ preset: GamePreset,+ settings: Record<string, GameSetting>,+ system: SystemInfo | undefined,+): Values {+ const monitor = primaryMonitor(system);+ const out: Values = {};+ for (const [key, value] of Object.entries(preset.values)) {+ if (value === "monitor") {+ const hz = monitor?.max_refresh_hz ?? null;+ const options = settings[key]?.options ?? [];+ const fitting = options.filter((o) => Number(o) > 0 && hz !== null && Number(o) <= hz);+ if (fitting.length > 0) out[key] = fitting[fitting.length - 1];+ continue;+ }+ out[key] = value;+ }+ if (monitor) {+ const native = `${monitor.width}x${monitor.height}`;+ if (settings.perf_resolution?.options?.includes(native)) out.perf_resolution = native;+ const hz = `${monitor.max_refresh_hz} Hz`;+ if (settings.perf_refresh_rate?.options?.includes(hz)) out.perf_refresh_rate = hz;+ }+ return out;+}++function matchesPreset(resolved: Values, effective: (key: string) => GameSettingValue | null): boolean {+ return Object.entries(resolved).every(([key, value]) => effective(key) === value);+}++function Card({+ eyebrow,+ title,+ icon: Icon,+ children,+ className,+ testId,+}: {+ eyebrow: string;+ title: string;+ icon: LucideIcon;+ children: ReactNode;+ className?: string;+ testId?: string;+}) {+ return (+ <section+ data-testid={testId}+ className={cn(+ "relative overflow-hidden rounded-xl border border-border bg-card/80 px-5 pb-2 pt-4",+ "before:absolute before:inset-y-0 before:left-0 before:w-[3px] before:bg-[var(--game-accent)]",+ className,+ )}+ >+ <header className="mb-1 flex items-center gap-2.5">+ <Icon className="h-4 w-4 text-[var(--game-accent)]" aria-hidden />+ <div>+ <p className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">{eyebrow}</p>+ <h3 className="text-sm font-semibold text-foreground-strong">{title}</h3>+ </div>+ </header>+ {children}+ </section>+ );+}++export function PerformancePanel({+ game,+ profile,+ presets,+ onPatch,+}: {+ game: GameDefinition;+ profile: GameProfile;+ presets: GamePreset[];+ onPatch: (patch: ProfilePatch) => void;+}) {+ const t = useT();+ const system = useGameSystem();+ const settings: Record<string, GameSetting> = Object.fromEntries(+ game.sections.flatMap((s) => s.settings).map((s) => [s.key, s]),+ );+ const effective = (key: string): GameSettingValue | null =>+ profile.values[key] ?? settings[key]?.default ?? null;+ const set = (key: string, value: GameSettingValue | null) => onPatch({ values: { [key]: value } });+ const section = (id: string) => game.sections.find((s) => s.id === id)?.settings ?? [];+ const monitor = primaryMonitor(system.data);+ const resolved = presets.map((preset) => ({+ preset,+ values: resolvePreset(preset, settings, system.data),+ }));+ const activePreset = resolved.find((r) => matchesPreset(r.values, effective))?.preset.id ?? null;+ const recommended = system.data?.recommended_preset ?? null;++ const applyPreset = (id: GamePreset["id"]) => {+ const match = resolved.find((r) => r.preset.id === id);+ if (match) onPatch({ values: match.values });+ };++ const rows = (id: string, skip: Set<string> = new Set()) =>+ section(id)+ .filter((s) => !skip.has(s.key))+ .map((s) => (+ <GameSettingRow key={s.key} setting={s} value={profile.values[s.key]} onChange={(v) => set(s.key, v)} />+ ));++ const resolution = String(effective("perf_resolution") ?? "");+ const fps = String(effective("perf_fps_cap") ?? "");+ const refresh = String(effective("perf_refresh_rate") ?? "");+ const native = monitor ? `${monitor.width}x${monitor.height}` : null;++ return (+ <div className="flex flex-col gap-5" data-testid="games-performance">+ <SystemStrip+ system={system.data}+ loading={system.isLoading}+ recommended={recommended}+ onApplyRecommended={() => recommended && applyPreset(recommended)}+ />++ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4" role="radiogroup" aria-label={t("games.perf.presets")}>+ {resolved.map(({ preset }) => {+ const Icon = PRESET_ICONS[preset.id];+ const active = activePreset === preset.id;+ return (+ <button+ key={preset.id}+ type="button"+ role="radio"+ aria-checked={active}+ data-testid={`games-preset-${preset.id}`}+ onClick={() => applyPreset(preset.id)}+ className={cn(+ "group relative overflow-hidden rounded-xl border p-4 text-left transition-all",+ active+ ? "border-[var(--game-accent)] bg-[var(--game-accent-soft)] shadow-[0_0_24px_var(--game-accent-glow)]"+ : "border-border bg-card/70 hover:-translate-y-0.5 hover:border-border-strong",+ )}+ >+ <div+ aria-hidden+ className="pointer-events-none absolute -right-6 -top-6 h-24 w-24 rounded-full bg-[var(--game-accent-glow)] opacity-0 blur-2xl transition-opacity group-hover:opacity-100"+ />+ <div className="flex items-center justify-between">+ <Icon+ className={cn("h-5 w-5", active ? "text-[var(--game-accent)]" : "text-muted-foreground")}+ aria-hidden+ />+ {recommended === preset.id && (+ <span className="rounded-full border border-[var(--game-accent)] px-2 py-0.5 font-mono text-[9px] uppercase tracking-[0.14em] text-[var(--game-accent)]">+ {t("games.perf.recommended")}+ </span>+ )}+ </div>+ <p className="mt-3 text-base font-semibold text-foreground-strong">+ {t(`games.perf.preset_${preset.id}`)}+ </p>+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">+ {t(`games.perf.preset_${preset.id}_hint`)}+ </p>+ </button>+ );+ })}+ </div>++ <Card eyebrow={t("games.perf.eyebrow_display")} title={t("games.perf.display")} icon={Monitor} testId="games-perf-display">+ <p className="mb-2 mt-3 text-xs font-medium text-muted-foreground">{t("games.perf.resolution")}</p>+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4 2xl:grid-cols-6" role="radiogroup" aria-label={t("games.perf.resolution")}>+ {(settings.perf_resolution?.options ?? []).map((value) => {+ const [w, h] = value.split("x");+ const active = resolution === value;+ const isNative = native === value;+ return (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={active}+ data-testid={`games-res-${value}`}+ onClick={() => set("perf_resolution", value)}+ className={cn(+ "relative rounded-lg border px-3 py-2.5 text-left transition-all",+ active+ ? "border-[var(--game-accent)] bg-[var(--game-accent-soft)] shadow-[0_0_16px_var(--game-accent-glow)]"+ : "border-border bg-background/50 hover:border-border-strong",+ )}+ >+ <span className="block text-sm font-semibold text-foreground-strong">{RESOLUTION_NAMES[value] ?? value}</span>+ <span className="block font-mono text-[11px] tabular-nums text-muted-foreground">+ {w} × {h}+ </span>+ {isNative && (+ <span className="absolute right-2 top-2 font-mono text-[9px] uppercase tracking-[0.12em] text-[var(--game-accent)]">+ {t("games.perf.your_monitor")}+ </span>+ )}+ </button>+ );+ })}+ </div>++ <div className="mt-5 grid gap-5 lg:grid-cols-2">+ <div>+ <p className="mb-2 text-xs font-medium text-muted-foreground">{t("games.perf.fps_limit")}</p>+ <ChipRow+ label={t("games.perf.fps_limit")}+ options={settings.perf_fps_cap?.options ?? []}+ value={fps}+ highlight={(o) => o === "Unlimited"}+ format={(o) => (o === "Unlimited" ? t("games.perf.unlimited") : o)}+ onChange={(o) => set("perf_fps_cap", o)}+ />+ <p className="mt-2 text-xs text-muted-foreground">{t("games.perf.fps_hint")}</p>+ </div>+ <div>+ <p className="mb-2 text-xs font-medium text-muted-foreground">{t("games.perf.refresh")}</p>+ <ChipRow+ label={t("games.perf.refresh")}+ options={settings.perf_refresh_rate?.options ?? []}+ value={refresh}+ highlight={(o) => monitor !== null && o === `${monitor.max_refresh_hz} Hz`}+ onChange={(o) => set("perf_refresh_rate", o)}+ />+ </div>+ </div>+ <div className="mt-3">{rows("perf_display", CUSTOM_DRAWN)}</div>+ </Card>++ <div className="grid gap-5 2xl:grid-cols-2">+ <Card eyebrow={t("games.perf.eyebrow_rendering")} title={t("games.perf.rendering")} icon={Wand2}>+ {rows("perf_rendering")}+ </Card>+ <Card eyebrow={t("games.perf.eyebrow_raytracing")} title={t("games.perf.raytracing")} icon={Sun}>+ {rows("perf_raytracing")}+ </Card>+ </div>++ <Card eyebrow={t("games.perf.eyebrow_detail")} title={t("games.perf.detail")} icon={Sparkles}>+ {rows("perf_detail")}+ </Card>++ <Card eyebrow={t("games.perf.eyebrow_effects")} title={t("games.perf.effects")} icon={MonitorPlay}>+ <div className="grid gap-x-6 py-2 sm:grid-cols-2 lg:grid-cols-3">+ {section("perf_effects").map((s) => (+ <label key={s.key} className="flex items-center justify-between gap-3 border-b border-border/50 py-2.5">+ <span className="text-sm text-foreground">{s.label}</span>+ <Switch+ checked={effective(s.key) === true}+ aria-label={s.label}+ onCheckedChange={(next) => set(s.key, next)}+ />+ </label>+ ))}+ </div>+ </Card>++ {section("video").length > 0 && (+ <Card+ eyebrow={t("games.perf.eyebrow_ingame")}+ title={t("games.perf.ingame").replace("{0}", game.name)}+ icon={Info}+ >+ <p className="text-xs text-muted-foreground">{t("games.perf.ingame_hint")}</p>+ {rows("video")}+ </Card>+ )}+ </div>+ );+}++function ChipRow({+ label,+ options,+ value,+ onChange,+ highlight,+ format,+}: {+ label: string;+ options: string[];+ value: string;+ onChange: (value: string) => void;+ highlight?: (option: string) => boolean;+ format?: (option: string) => string;+}) {+ return (+ <div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label={label}>+ {options.map((option) => {+ const active = option === value;+ return (+ <button+ key={option}+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => onChange(option)}+ className={cn(+ "rounded-md border px-2.5 py-1.5 font-mono text-xs tabular-nums transition-all",+ active+ ? "border-[var(--game-accent)] bg-[var(--game-accent)] font-semibold text-black shadow-[0_0_14px_var(--game-accent-glow)]"+ : highlight?.(option)+ ? "border-[var(--game-accent)]/60 text-[var(--game-accent)] hover:bg-[var(--game-accent-soft)]"+ : "border-border text-muted-foreground hover:border-border-strong hover:text-foreground",+ )}+ >+ {format ? format(option) : option}+ </button>+ );+ })}+ </div>+ );+}++function SystemStrip({+ system,+ loading,+ recommended,+ onApplyRecommended,+}: {+ system: SystemInfo | undefined;+ loading: boolean;+ recommended: GamePreset["id"] | null;+ onApplyRecommended: () => void;+}) {+ const t = useT();+ const monitor = primaryMonitor(system);+ const gpu = system?.gpus[0];+ const items: { icon: LucideIcon; label: string; value: string }[] = [+ {+ icon: MonitorPlay,+ label: t("games.perf.gpu"),+ value: gpu ? `${gpu.name}${gpu.vram_gb ? ` · ${Math.round(gpu.vram_gb)} GB` : ""}` : "—",+ },+ { icon: Cpu, label: t("games.perf.cpu"), value: system?.cpu ?? "—" },+ { icon: MemoryStick, label: t("games.perf.ram"), value: system?.ram_gb ? `${system.ram_gb} GB` : "—" },+ {+ icon: Monitor,+ label: t("games.perf.monitor"),+ value: monitor+ ? `${monitor.width} × ${monitor.height} · ${monitor.refresh_hz} Hz`+ : "—",+ },+ ];+ const lowRefresh = monitor !== null && monitor.max_refresh_hz > monitor.refresh_hz + 5;++ return (+ <section+ data-testid="games-system"+ className="rounded-xl border border-border bg-gradient-to-br from-card to-background p-4"+ >+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">+ {loading ? t("games.perf.detecting") : t("games.perf.your_pc")}+ </p>+ {recommended && (+ <Button type="button" size="sm" onClick={onApplyRecommended} data-testid="games-apply-recommended">+ <Sparkles aria-hidden />+ {t("games.perf.apply_recommended").replace("{0}", t(`games.perf.preset_${recommended}`))}+ </Button>+ )}+ </div>+ <dl className="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {items.map(({ icon: Icon, label, value }) => (+ <div key={label} className="flex min-w-0 items-start gap-2.5">+ <Icon className="mt-0.5 h-4 w-4 shrink-0 text-[var(--game-accent)]" aria-hidden />+ <div className="min-w-0">+ <dt className="text-[11px] text-muted-foreground">{label}</dt>+ <dd className="truncate text-sm font-medium text-foreground-strong" title={value}>+ {value}+ </dd>+ </div>+ </div>+ ))}+ </dl>+ {lowRefresh && monitor && (+ <p+ role="note"+ data-testid="games-refresh-tip"+ className="mt-3 rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground"+ >+ {t("games.perf.refresh_tip")+ .replace("{0}", String(monitor.refresh_hz))+ .replace("{1}", String(monitor.max_refresh_hz))}+ </p>+ )}+ </section>+ );+}+diff --git a/dodaios/ui/web/frontend/src/hooks/useGames.ts b/dodaios/ui/web/frontend/src/hooks/useGames.tsindex ac21770a4e..b0f7f6f63c 100644--- a/dodaios/ui/web/frontend/src/hooks/useGames.ts+++ b/dodaios/ui/web/frontend/src/hooks/useGames.ts@@ -6,6 +6,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import {fetchGame,fetchGames,+ fetchSystem,resetGameProfile,saveDefaultDpi,saveGameProfile,@@ -29,6 +30,16 @@ export function useGameDetail(gameId: string | null) {});}+/** This PC's GPU, CPU, RAM and monitors; read once, it does not change. */+export function useGameSystem() {+ return useQuery({+ queryKey: ["games", "system"],+ queryFn: fetchSystem,+ staleTime: Infinity,+ retry: false,+ });+}+export function useSaveGameProfile() {const client = useQueryClient();return useMutation({diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex e5a7e3046f..f365507669 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -10823,7 +10823,7 @@"cm360_hint": "Mausweg für eine volle Drehung.","edpi": "eDPI","not_convertible": "Die Sensitivity dieses Spiels ist nicht linear und lässt sich daher nicht umrechnen.",- "keybind_hint": "Klicke auf eine Taste und drücke dann eine Taste, eine Maustaste oder dreh am Mausrad. Esc bricht ab.",+ "keybind_hint": "Klicke auf ein Feld und drücke dann eine Taste, eine Maustaste oder dreh am Mausrad. Halte Strg, Shift oder Alt für eine Kombination; eine Modifier-Taste allein belegt sich selbst. Esc bricht ab.","keybind_press": "Taste drücken…","keybind_unbound": "Nicht belegt","keybind_clear": "Leeren",@@ -10857,7 +10857,68 @@"audio": "Audio","video": "Grafik","gameplay": "Gameplay",- "converter": "Umrechner"+ "converter": "Umrechner",+ "performance": "Grafik & Leistung"+ },+ "perf": {+ "presets": "Presets",+ "recommended": "Empfohlen",+ "apply_recommended": "{0} anwenden",+ "your_pc": "Dein PC",+ "detecting": "PC wird erkannt…",+ "gpu": "Grafikkarte",+ "cpu": "Prozessor",+ "ram": "Arbeitsspeicher",+ "monitor": "Monitor",+ "refresh_tip": "Windows betreibt deinen Monitor mit {0} Hz, er schafft aber {1} Hz. Stell das in den Windows-Anzeigeeinstellungen (Erweiterte Anzeige) höher, damit du jedes Bild siehst.",+ "display": "Anzeige",+ "eyebrow_display": "Ausgabe",+ "resolution": "Auflösung",+ "your_monitor": "Dein Monitor",+ "fps_limit": "FPS-Limit",+ "fps_hint": "Unbegrenzt rendert so viele Bilder, wie dein PC schafft. Ein Limit knapp unter deiner Bildwiederholrate hält die Latenz mit G-Sync / FreeSync stabil.",+ "unlimited": "Unbegrenzt",+ "refresh": "Bildwiederholrate",+ "rendering": "Rendering",+ "eyebrow_rendering": "Pipeline",+ "raytracing": "Raytracing",+ "eyebrow_raytracing": "Beleuchtung",+ "detail": "Details",+ "eyebrow_detail": "Qualität",+ "effects": "Effekte",+ "eyebrow_effects": "Post-FX",+ "ingame": "Optionen in {0}",+ "eyebrow_ingame": "So heißt es im Spiel",+ "ingame_hint": "Die genauen Optionen im Menü des Spiels, unter den Namen, die es selbst verwendet.",+ "preset_competitive": "Competitive",+ "preset_competitive_hint": "Jedes Bild, das drin ist, niedrigste Eingabelatenz, klares Bild ohne Unschärfe.",+ "preset_balanced": "Ausgewogen",+ "preset_balanced_hint": "Hohe Details bei der Bildwiederholrate deines Monitors, DLSS Qualität für Reserve.",+ "preset_quality": "Qualität",+ "preset_quality_hint": "Ultra-Details, Kantenglättung in nativer Auflösung und Raytracing.",+ "preset_epic": "Episch",+ "preset_epic_hint": "Alles auf Maximum: Path Tracing, Frame Generation, HDR. Für eine starke Grafikkarte."+ },+ "keys": {+ "keyboard": "Tastatur",+ "mouse": "Maus",+ "bound_count": "{0} Eingaben belegt",+ "search": "Aktionen oder Tasten suchen",+ "showing_key": "Taste: {0}",+ "action": "Aktion",+ "primary": "Primär",+ "secondary": "Sekundär",+ "mode": "Modus",+ "hold": "Halten",+ "toggle": "Umschalten",+ "nothing_found": "Keine Aktion passt.",+ "custom_eyebrow": "Eigene",+ "custom_title": "Eigene Aktionen",+ "custom_hint": "Alles, was in der Liste fehlt: Emotes, Makros, Kommunikation, Bau-Binds.",+ "custom_add": "Aktion hinzufügen",+ "custom_name": "Name der Aktion",+ "custom_unnamed": "Unbenannte Aktion",+ "custom_remove": "Entfernen"}}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 7188909d7f..9f57b4e976 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -10823,7 +10823,7 @@"cm360_hint": "Mouse travel for one full turn.","edpi": "eDPI","not_convertible": "This game's sensitivity is not linear, so it cannot be converted.",- "keybind_hint": "Click a key, then press a key, a mouse button or turn the wheel. Esc cancels.",+ "keybind_hint": "Click a field, then press a key, a mouse button or turn the wheel. Hold Ctrl, Shift or Alt for a combination; press a modifier alone to bind it. Esc cancels.","keybind_press": "Press a key…","keybind_unbound": "Unbound","keybind_clear": "Clear",@@ -10857,7 +10857,68 @@"audio": "Audio","video": "Video","gameplay": "Gameplay",- "converter": "Converter"+ "converter": "Converter",+ "performance": "Graphics & Performance"+ },+ "perf": {+ "presets": "Presets",+ "recommended": "Recommended",+ "apply_recommended": "Apply {0}",+ "your_pc": "Your PC",+ "detecting": "Detecting your PC…",+ "gpu": "Graphics card",+ "cpu": "Processor",+ "ram": "Memory",+ "monitor": "Monitor",+ "refresh_tip": "Windows runs your monitor at {0} Hz, but it can do {1} Hz. Raise it in the Windows display settings (Advanced display) to see every frame.",+ "display": "Display",+ "eyebrow_display": "Output",+ "resolution": "Resolution",+ "your_monitor": "Your monitor",+ "fps_limit": "FPS limit",+ "fps_hint": "Unlimited renders as many frames as your PC can. A cap a few FPS under your refresh rate keeps latency steady with G-Sync / FreeSync.",+ "unlimited": "Unlimited",+ "refresh": "Refresh rate",+ "rendering": "Rendering",+ "eyebrow_rendering": "Pipeline",+ "raytracing": "Ray tracing",+ "eyebrow_raytracing": "Lighting",+ "detail": "Detail",+ "eyebrow_detail": "Quality",+ "effects": "Effects",+ "eyebrow_effects": "Post FX",+ "ingame": "{0} in-game options",+ "eyebrow_ingame": "As the game names them",+ "ingame_hint": "The exact options in the game's own menu, under the names it uses.",+ "preset_competitive": "Competitive",+ "preset_competitive_hint": "Every frame you can get, lowest input latency, clean picture without blur.",+ "preset_balanced": "Balanced",+ "preset_balanced_hint": "High detail at your monitor's refresh rate, DLSS Quality for headroom.",+ "preset_quality": "Quality",+ "preset_quality_hint": "Ultra detail, native-resolution anti-aliasing and ray tracing.",+ "preset_epic": "Epic",+ "preset_epic_hint": "Everything maxed: path tracing, frame generation, HDR. Made for a strong GPU."+ },+ "keys": {+ "keyboard": "Keyboard",+ "mouse": "Mouse",+ "bound_count": "{0} inputs bound",+ "search": "Search actions or keys",+ "showing_key": "Key: {0}",+ "action": "Action",+ "primary": "Primary",+ "secondary": "Secondary",+ "mode": "Mode",+ "hold": "Hold",+ "toggle": "Toggle",+ "nothing_found": "No action matches.",+ "custom_eyebrow": "Your own",+ "custom_title": "Custom actions",+ "custom_hint": "Anything the list is missing: emotes, macros, comms, build binds.",+ "custom_add": "Add action",+ "custom_name": "Action name",+ "custom_unnamed": "Unnamed action",+ "custom_remove": "Remove"}}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex 4a1f31a4c2..69b70affb1 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -10823,7 +10823,7 @@"cm360_hint": "Recorrido del ratón para un giro completo.","edpi": "eDPI","not_convertible": "La sensibilidad de este juego no es lineal, así que no se puede convertir.",- "keybind_hint": "Haz clic en una tecla y luego pulsa una tecla, un botón del ratón o gira la rueda. Esc cancela.",+ "keybind_hint": "Haz clic en un campo y pulsa una tecla, un botón del ratón o gira la rueda. Mantén Ctrl, Shift o Alt para una combinación; un modificador solo se asigna a sí mismo. Esc cancela.","keybind_press": "Pulsa una tecla…","keybind_unbound": "Sin asignar","keybind_clear": "Quitar",@@ -10857,7 +10857,68 @@"audio": "Audio","video": "Vídeo","gameplay": "Jugabilidad",- "converter": "Conversor"+ "converter": "Conversor",+ "performance": "Gráficos y rendimiento"+ },+ "perf": {+ "presets": "Preajustes",+ "recommended": "Recomendado",+ "apply_recommended": "Aplicar {0}",+ "your_pc": "Tu PC",+ "detecting": "Detectando tu PC…",+ "gpu": "Tarjeta gráfica",+ "cpu": "Procesador",+ "ram": "Memoria",+ "monitor": "Monitor",+ "refresh_tip": "Windows usa tu monitor a {0} Hz, pero admite {1} Hz. Súbelo en la configuración de pantalla de Windows (Pantalla avanzada) para ver cada fotograma.",+ "display": "Pantalla",+ "eyebrow_display": "Salida",+ "resolution": "Resolución",+ "your_monitor": "Tu monitor",+ "fps_limit": "Límite de FPS",+ "fps_hint": "Ilimitado renderiza tantos fotogramas como pueda tu PC. Un límite unos FPS por debajo de tu frecuencia mantiene estable la latencia con G-Sync / FreeSync.",+ "unlimited": "Ilimitado",+ "refresh": "Frecuencia de actualización",+ "rendering": "Renderizado",+ "eyebrow_rendering": "Pipeline",+ "raytracing": "Trazado de rayos",+ "eyebrow_raytracing": "Iluminación",+ "detail": "Detalle",+ "eyebrow_detail": "Calidad",+ "effects": "Efectos",+ "eyebrow_effects": "Post FX",+ "ingame": "Opciones de {0}",+ "eyebrow_ingame": "Como las llama el juego",+ "ingame_hint": "Las opciones exactas del menú del juego, con los nombres que usa.",+ "preset_competitive": "Competitivo",+ "preset_competitive_hint": "Todos los fotogramas posibles, latencia mínima, imagen limpia sin desenfoque.",+ "preset_balanced": "Equilibrado",+ "preset_balanced_hint": "Detalle alto a la frecuencia de tu monitor, DLSS Calidad para tener margen.",+ "preset_quality": "Calidad",+ "preset_quality_hint": "Detalle ultra, antialiasing a resolución nativa y trazado de rayos.",+ "preset_epic": "Épico",+ "preset_epic_hint": "Todo al máximo: path tracing, generación de fotogramas, HDR. Para una GPU potente."+ },+ "keys": {+ "keyboard": "Teclado",+ "mouse": "Ratón",+ "bound_count": "{0} entradas asignadas",+ "search": "Buscar acciones o teclas",+ "showing_key": "Tecla: {0}",+ "action": "Acción",+ "primary": "Principal",+ "secondary": "Secundaria",+ "mode": "Modo",+ "hold": "Mantener",+ "toggle": "Alternar",+ "nothing_found": "Ninguna acción coincide.",+ "custom_eyebrow": "Propias",+ "custom_title": "Acciones propias",+ "custom_hint": "Todo lo que falta en la lista: gestos, macros, comunicación, construcción.",+ "custom_add": "Añadir acción",+ "custom_name": "Nombre de la acción",+ "custom_unnamed": "Acción sin nombre",+ "custom_remove": "Quitar"}}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 4ce2a3be9c..bf5727b8a5 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -10823,7 +10823,7 @@"cm360_hint": "Distância do mouse para uma volta completa.","edpi": "eDPI","not_convertible": "A sensibilidade deste jogo não é linear, então não pode ser convertida.",- "keybind_hint": "Clique em uma tecla e depois pressione uma tecla, um botão do mouse ou gire a roda. Esc cancela.",+ "keybind_hint": "Clique em um campo e pressione uma tecla, um botão do mouse ou gire a roda. Segure Ctrl, Shift ou Alt para uma combinação; um modificador sozinho se atribui. Esc cancela.","keybind_press": "Pressione uma tecla…","keybind_unbound": "Sem atalho","keybind_clear": "Limpar",@@ -10857,7 +10857,68 @@"audio": "Áudio","video": "Vídeo","gameplay": "Jogabilidade",- "converter": "Conversor"+ "converter": "Conversor",+ "performance": "Gráficos e desempenho"+ },+ "perf": {+ "presets": "Predefinições",+ "recommended": "Recomendado",+ "apply_recommended": "Aplicar {0}",+ "your_pc": "Seu PC",+ "detecting": "Detectando seu PC…",+ "gpu": "Placa de vídeo",+ "cpu": "Processador",+ "ram": "Memória",+ "monitor": "Monitor",+ "refresh_tip": "O Windows usa seu monitor a {0} Hz, mas ele suporta {1} Hz. Aumente nas configurações de vídeo do Windows (Vídeo avançado) para ver cada quadro.",+ "display": "Tela",+ "eyebrow_display": "Saída",+ "resolution": "Resolução",+ "your_monitor": "Seu monitor",+ "fps_limit": "Limite de FPS",+ "fps_hint": "Ilimitado renderiza quantos quadros seu PC aguentar. Um limite alguns FPS abaixo da sua taxa mantém a latência estável com G-Sync / FreeSync.",+ "unlimited": "Ilimitado",+ "refresh": "Taxa de atualização",+ "rendering": "Renderização",+ "eyebrow_rendering": "Pipeline",+ "raytracing": "Ray tracing",+ "eyebrow_raytracing": "Iluminação",+ "detail": "Detalhes",+ "eyebrow_detail": "Qualidade",+ "effects": "Efeitos",+ "eyebrow_effects": "Pós FX",+ "ingame": "Opções de {0}",+ "eyebrow_ingame": "Como o jogo chama",+ "ingame_hint": "As opções exatas do menu do jogo, com os nomes que ele usa.",+ "preset_competitive": "Competitivo",+ "preset_competitive_hint": "Todos os quadros possíveis, menor latência, imagem limpa sem desfoque.",+ "preset_balanced": "Equilibrado",+ "preset_balanced_hint": "Detalhes altos na taxa do seu monitor, DLSS Qualidade para folga.",+ "preset_quality": "Qualidade",+ "preset_quality_hint": "Detalhes ultra, anti-aliasing em resolução nativa e ray tracing.",+ "preset_epic": "Épico",+ "preset_epic_hint": "Tudo no máximo: path tracing, geração de quadros, HDR. Para uma GPU forte."+ },+ "keys": {+ "keyboard": "Teclado",+ "mouse": "Mouse",+ "bound_count": "{0} entradas atribuídas",+ "search": "Buscar ações ou teclas",+ "showing_key": "Tecla: {0}",+ "action": "Ação",+ "primary": "Principal",+ "secondary": "Secundária",+ "mode": "Modo",+ "hold": "Segurar",+ "toggle": "Alternar",+ "nothing_found": "Nenhuma ação corresponde.",+ "custom_eyebrow": "Suas",+ "custom_title": "Ações próprias",+ "custom_hint": "Tudo o que falta na lista: emotes, macros, comunicação, construção.",+ "custom_add": "Adicionar ação",+ "custom_name": "Nome da ação",+ "custom_unnamed": "Ação sem nome",+ "custom_remove": "Remover"}}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 0d555a6a15..f516a68c2c 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -10823,7 +10823,7 @@"cm360_hint": "转一整圈所需的鼠标移动距离。","edpi": "eDPI","not_convertible": "这款游戏的灵敏度不是线性的,无法换算。",- "keybind_hint": "点击一个按键,然后按下键盘按键、鼠标按键或滚动滚轮。按 Esc 取消。",+ "keybind_hint": "点击一个字段,然后按下键盘按键、鼠标按键或滚动滚轮。按住 Ctrl、Shift 或 Alt 组成组合键;单独按下修饰键则绑定它本身。按 Esc 取消。","keybind_press": "请按键…","keybind_unbound": "未绑定","keybind_clear": "清除",@@ -10857,7 +10857,68 @@"audio": "音频","video": "画面","gameplay": "玩法",- "converter": "换算器"+ "converter": "换算器",+ "performance": "画面与性能"+ },+ "perf": {+ "presets": "预设",+ "recommended": "推荐",+ "apply_recommended": "应用{0}",+ "your_pc": "你的电脑",+ "detecting": "正在检测你的电脑…",+ "gpu": "显卡",+ "cpu": "处理器",+ "ram": "内存",+ "monitor": "显示器",+ "refresh_tip": "Windows 以 {0} Hz 运行你的显示器,但它支持 {1} Hz。在 Windows 显示设置(高级显示)中调高,才能看到每一帧。",+ "display": "显示",+ "eyebrow_display": "输出",+ "resolution": "分辨率",+ "your_monitor": "你的显示器",+ "fps_limit": "帧率上限",+ "fps_hint": "无限制会让电脑尽可能渲染更多帧。把上限设在刷新率下方几帧,可在 G-Sync / FreeSync 下保持延迟稳定。",+ "unlimited": "无限制",+ "refresh": "刷新率",+ "rendering": "渲染",+ "eyebrow_rendering": "管线",+ "raytracing": "光线追踪",+ "eyebrow_raytracing": "光照",+ "detail": "细节",+ "eyebrow_detail": "画质",+ "effects": "效果",+ "eyebrow_effects": "后期",+ "ingame": "{0} 游戏内选项",+ "eyebrow_ingame": "游戏中的名称",+ "ingame_hint": "游戏菜单中的确切选项,使用游戏自己的名称。",+ "preset_competitive": "竞技",+ "preset_competitive_hint": "尽可能多的帧数,最低输入延迟,画面清晰无模糊。",+ "preset_balanced": "均衡",+ "preset_balanced_hint": "在显示器刷新率下保持高细节,DLSS 质量模式留出余量。",+ "preset_quality": "画质",+ "preset_quality_hint": "极高细节、原生分辨率抗锯齿和光线追踪。",+ "preset_epic": "史诗",+ "preset_epic_hint": "全部拉满:路径追踪、帧生成、HDR。适合强劲的显卡。"+ },+ "keys": {+ "keyboard": "键盘",+ "mouse": "鼠标",+ "bound_count": "已绑定 {0} 个输入",+ "search": "搜索动作或按键",+ "showing_key": "按键:{0}",+ "action": "动作",+ "primary": "主键",+ "secondary": "副键",+ "mode": "模式",+ "hold": "按住",+ "toggle": "切换",+ "nothing_found": "没有匹配的动作。",+ "custom_eyebrow": "自定义",+ "custom_title": "自定义动作",+ "custom_hint": "列表中没有的都可以加:表情、宏、交流、建造按键。",+ "custom_add": "添加动作",+ "custom_name": "动作名称",+ "custom_unnamed": "未命名动作",+ "custom_remove": "移除"}}}diff --git a/dodaios/ui/web/frontend/src/lib/gameKeys.test.ts b/dodaios/ui/web/frontend/src/lib/gameKeys.test.tsindex 55a06893d6..0510a26409 100644--- a/dodaios/ui/web/frontend/src/lib/gameKeys.test.ts+++ b/dodaios/ui/web/frontend/src/lib/gameKeys.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from "vitest";-import { keyConflicts, keyNameFromCode, mouseButtonName, wheelName } from "@/lib/gameKeys";+import {+ bindUsesKey,+ comboName,+ comboParts,+ keyConflicts,+ keyNameFromCode,+ mouseButtonName,+ wheelName,+} from "@/lib/gameKeys";describe("game key names", () => {it("names keys the way game menus print them", () => {@@ -38,3 +46,19 @@ describe("keyConflicts", () => {expect(conflicts.has("a")).toBe(false);});});++describe("combinations", () => {+ it("orders modifiers and never repeats the main key as a modifier", () => {+ expect(comboName({ ctrl: true, shift: true, alt: false }, "Mouse 4")).toBe("Ctrl + Shift + Mouse 4");+ expect(comboName({ ctrl: false, shift: true, alt: false }, "Left Shift")).toBe("Left Shift");+ expect(comboName({ ctrl: true, shift: false, alt: false }, "Left Shift")).toBe("Ctrl + Left Shift");+ expect(comboParts("Alt + E")).toEqual(["Alt", "E"]);+ });++ it("matches a physical key inside a combo", () => {+ expect(bindUsesKey("Ctrl + F", "Left Ctrl")).toBe(true);+ expect(bindUsesKey("Ctrl + F", "F")).toBe(true);+ expect(bindUsesKey("Left Shift", "Right Shift")).toBe(false);+ expect(bindUsesKey("", "F")).toBe(false);+ });+});diff --git a/dodaios/ui/web/frontend/src/lib/gameKeys.ts b/dodaios/ui/web/frontend/src/lib/gameKeys.tsindex 8076816570..d95840af61 100644--- a/dodaios/ui/web/frontend/src/lib/gameKeys.ts+++ b/dodaios/ui/web/frontend/src/lib/gameKeys.ts@@ -94,3 +94,50 @@ export function keyConflicts(}return out;}++/** The browser codes of modifier keys; held, they become part of a combo. */+export const MODIFIER_CODES = new Set([+ "ShiftLeft",+ "ShiftRight",+ "ControlLeft",+ "ControlRight",+ "AltLeft",+ "AltRight",+ "MetaLeft",+ "MetaRight",+]);++export interface HeldModifiers {+ ctrl: boolean;+ shift: boolean;+ alt: boolean;+}++/** "Ctrl + Shift + Mouse 4": modifiers in a fixed order, then the main input. */+export function comboName(mods: HeldModifiers, main: string): string {+ const parts: string[] = [];+ if (mods.ctrl && !/Ctrl$/.test(main)) parts.push("Ctrl");+ if (mods.shift && !/Shift$/.test(main)) parts.push("Shift");+ if (mods.alt && !/Alt$/.test(main)) parts.push("Alt");+ return [...parts, main].join(" + ");+}++/** The single inputs of a bind: "Ctrl + F" → ["Ctrl", "F"]. */+export function comboParts(combo: string): string[] {+ return combo+ .split(" + ")+ .map((part) => part.trim())+ .filter(Boolean);+}++/**+ * Does a bind use this physical key? A combo's bare "Ctrl" counts for both+ * Ctrl keys; "Left Shift" only for the left one.+ */+export function bindUsesKey(combo: string, keyName: string): boolean {+ return comboParts(combo).some((part) => {+ if (part === keyName) return true;+ const generic = /^(Left|Right) (Ctrl|Shift|Alt)$/.exec(keyName);+ return generic !== null && part === generic[2];+ });+}diff --git a/dodaios/ui/web/frontend/src/lib/gameVisuals.ts b/dodaios/ui/web/frontend/src/lib/gameVisuals.tsnew file mode 100644index 0000000000..c6de874599--- /dev/null+++ b/dodaios/ui/web/frontend/src/lib/gameVisuals.ts@@ -0,0 +1,46 @@+/**+ * Each game's colour and monogram for Settings → Game settings. No brand+ * marks: a hue and two letters give every game its own face while staying+ * clear of anyone's logo.+ */++const HUES: Record<string, number> = {+ fortnite: 268,+ cod_bo6: 96,+ r6_siege_x: 205,+ valorant: 354,+ cs2: 36,+ apex: 8,+ overwatch2: 26,+ battlefield6: 188,+ pubg: 46,+ marvel_rivals: 340,+ the_finals: 318,+ tarkov: 62,+ destiny2: 196,+ arc_raiders: 78,+ rocket_league: 220,+};++/** A stable hue for any game id, from the table or a hash of the id. */+export function gameHue(id: string): number {+ if (id in HUES) return HUES[id];+ let hash = 0;+ for (const char of id) hash = (hash * 31 + char.charCodeAt(0)) % 360;+ return hash;+}++/** "Rainbow Six Siege X" → "RS", "Counter-Strike 2" → "CS", "Valorant" → "VA". */+export function gameMonogram(name: string): string {+ const words = name+ .replace(/[:/].*$/, "")+ .split(/[\s-]+/)+ .filter((word) => /^[A-Z0-9]/.test(word));+ if (words.length === 0) return "?";+ if (words.length === 1) return words[0].slice(0, 2).toUpperCase();+ return (words[0][0] + words[words.length > 2 ? 1 : words.length - 1][0]).toUpperCase();+}++export function gameAccent(id: string, alpha = 1): string {+ return `hsl(${gameHue(id)} 85% 58% / ${alpha})`;+}diff --git a/dodaios/ui/web/frontend/src/lib/gamesApi.ts b/dodaios/ui/web/frontend/src/lib/gamesApi.tsindex 705a5e8b9e..5c27b75cf9 100644--- a/dodaios/ui/web/frontend/src/lib/gamesApi.ts+++ b/dodaios/ui/web/frontend/src/lib/gamesApi.ts@@ -7,7 +7,52 @@export type GameSettingType = "slider" | "number" | "select" | "toggle" | "text";export type GameSettingValue = number | string | boolean;-export type GameSectionId = "mouse" | "audio" | "video" | "gameplay";+export type GameSectionId =+ | "perf_display"+ | "perf_rendering"+ | "perf_detail"+ | "perf_raytracing"+ | "perf_effects"+ | "mouse"+ | "audio"+ | "video"+ | "gameplay";++export type BindMode = "hold" | "toggle";++export interface CustomBind {+ id: string;+ action: string;+ key: string;+ alt: string;+}++export interface GamePreset {+ id: "competitive" | "balanced" | "quality" | "epic";+ /** "monitor" in perf_fps_cap means: the detected monitor's refresh rate. */+ values: Record<string, GameSettingValue>;+}++export interface MonitorInfo {+ name: string;+ primary: boolean;+ width: number;+ height: number;+ refresh_hz: number;+ max_width: number;+ max_height: number;+ max_refresh_hz: number;+}++export interface SystemInfo {+ os: string;+ cpu: string | null;+ ram_gb: number | null;+ gpus: { name: string; vram_gb: number | null }[];+ monitors: MonitorInfo[];+ gpu_tier: "entry" | "mid" | "high" | "enthusiast" | null;+ recommended_preset: GamePreset["id"] | null;+}export interface GameSetting {key: string;@@ -46,6 +91,9 @@ export interface GameDefinition {export interface GameProfile {values: Record<string, GameSettingValue>;keybinds: Record<string, string>;+ alt_keybinds: Record<string, string>;+ bind_modes: Record<string, BindMode>;+ custom_binds: CustomBind[];dpi: number | null;notes: string;updated_at: string | null;@@ -63,6 +111,7 @@ export interface GameSummary {export interface GamesIndex {dpi: number;games: GameSummary[];+ presets: GamePreset[];}export interface GameDetail {@@ -74,6 +123,9 @@ export interface GameDetail {export interface ProfilePatch {values?: Record<string, GameSettingValue | null>;keybinds?: Record<string, string | null>;+ alt_keybinds?: Record<string, string | null>;+ bind_modes?: Record<string, BindMode | null>;+ custom_binds?: CustomBind[];dpi?: number;reset_dpi?: boolean;notes?: string;@@ -136,6 +188,10 @@ export function resetGameProfile(gameId: string): Promise<{ removed: boolean }>return request(`/api/games/${encodeURIComponent(gameId)}/profile`, { method: "DELETE" });}+export function fetchSystem(): Promise<SystemInfo> {+ return request<SystemInfo>("/api/games/system");+}+export function saveDefaultDpi(dpi: number): Promise<{ dpi: number }> {return sendJson("/api/games/dpi", "PUT", { dpi });}diff --git a/dodaios/ui/web/frontend/src/views/GamesView.test.tsx b/dodaios/ui/web/frontend/src/views/GamesView.test.tsxindex 55a25bfe04..01b3c42de7 100644--- a/dodaios/ui/web/frontend/src/views/GamesView.test.tsx+++ b/dodaios/ui/web/frontend/src/views/GamesView.test.tsx@@ -3,7 +3,12 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testiimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { GamesView, profileSummary } from "@/views/GamesView";-import type { GameDefinition, GameProfile } from "@/lib/gamesApi";+import { resolvePreset } from "@/components/games/PerformancePanel";+import type { GameDefinition, GamePreset, GameProfile, GameSetting, SystemInfo } from "@/lib/gamesApi";++const RESOLUTIONS = ["1920x1080", "2560x1440", "3840x2160", "5120x2880"];+const FPS = ["60", "144", "165", "240", "Unlimited"];+const HZ = ["60 Hz", "144 Hz", "165 Hz", "240 Hz"];const CS2: GameDefinition = {id: "cs2",@@ -16,37 +21,74 @@ const CS2: GameDefinition = {sources: [],sections: [{- id: "mouse",+ id: "perf_display",settings: [- { key: "sensitivity", label: "Mouse Sensitivity", type: "slider", min: 0.01, max: 8, step: 0.01, default: 1.25 },+ { key: "perf_resolution", label: "Resolution", type: "select", options: RESOLUTIONS, default: "1920x1080" },+ { key: "perf_refresh_rate", label: "Refresh Rate", type: "select", options: HZ, default: null },+ { key: "perf_fps_cap", label: "FPS Limit", type: "select", options: FPS, default: null },+ { key: "perf_vsync", label: "V-Sync", type: "select", options: ["Off", "On", "Adaptive"], default: "Off" },],},{- id: "audio",- settings: [{ key: "master", label: "Master Volume", type: "slider", min: 0, max: 100, step: 1, default: null }],+ id: "perf_rendering",+ settings: [+ { key: "perf_upscaler", label: "Upscaler", type: "select", options: ["Off", "DLSS", "FSR"], default: "Off" },+ ],},+ { id: "perf_detail", settings: [] },+ { id: "perf_raytracing", settings: [] },+ { id: "perf_effects", settings: [{ key: "perf_motion_blur", label: "Motion Blur", type: "toggle", default: false }] },{- id: "video",+ id: "mouse",settings: [- { key: "mode", label: "Display Mode", type: "select", options: ["Fullscreen", "Windowed"], default: "Fullscreen" },+ { key: "sensitivity", label: "Mouse Sensitivity", type: "slider", min: 0.01, max: 8, step: 0.01, default: 1.25 },],},+ {+ id: "audio",+ settings: [{ key: "master", label: "Master Volume", type: "slider", min: 0, max: 100, step: 1, default: null }],+ },+ { id: "video", settings: [] },{ id: "gameplay", settings: [{ key: "hud", label: "Show HUD", type: "toggle", default: true }] },],keybinds: [{ id: "jump", action: "Jump", default: "Space" },{ id: "crouch", action: "Crouch", default: "Left Ctrl" },+ { id: "sprint", action: "Sprint", default: "Left Shift" },],};+const PRESETS: GamePreset[] = [+ { id: "competitive", values: { perf_fps_cap: "Unlimited", perf_vsync: "Off", perf_upscaler: "Off" } },+ { id: "balanced", values: { perf_fps_cap: "monitor", perf_upscaler: "DLSS" } },+ { id: "quality", values: { perf_fps_cap: "monitor", perf_upscaler: "DLSS" } },+ { id: "epic", values: { perf_fps_cap: "Unlimited", perf_upscaler: "DLSS" } },+];++const SYSTEM: SystemInfo = {+ os: "Windows",+ cpu: "AMD Ryzen 7 7800X3D",+ ram_gb: 32,+ gpus: [{ name: "NVIDIA GeForce RTX 5070 Ti", vram_gb: 15.9 }],+ monitors: [+ { name: "Display 1", primary: true, width: 2560, height: 1440, refresh_hz: 60, max_width: 3840, max_height: 2160, max_refresh_hz: 165 },+ ],+ gpu_tier: "high",+ recommended_preset: "quality",+};++function blankProfile(): GameProfile {+ return { values: {}, keybinds: {}, alt_keybinds: {}, bind_modes: {}, custom_binds: [], dpi: null, notes: "", updated_at: null };+}+interface Call {method: string;url: string;- body: unknown;+ body: Record<string, unknown> | undefined;}function stubServer() {- const profile: GameProfile = { values: {}, keybinds: {}, dpi: null, notes: "", updated_at: null };+ const profile = blankProfile();const calls: Call[] = [];const json = (body: unknown, status = 200) => ({ ok: status < 400, status, json: async () => body });vi.stubGlobal(@@ -54,33 +96,37 @@ function stubServer() {vi.fn(async (input: unknown, init?: { method?: string; body?: string }) => {const url = String(input);const method = (init?.method ?? "GET").toUpperCase();- const body = init?.body ? JSON.parse(init.body) : undefined;+ const body = init?.body ? (JSON.parse(init.body) as Record<string, unknown>) : undefined;calls.push({ method, url, body });if (url === "/api/games") {return json({dpi: 800,+ presets: PRESETS,games: [{ id: "cs2", name: "Counter-Strike 2", publisher: "Valve", convertible: true, has_profile: false, updated_at: null },],});}+ if (url === "/api/games/system") return json(SYSTEM);if (url === "/api/games/cs2" && method === "GET") {return json({ game: CS2, profile, default_dpi: 800 });}- if (url === "/api/games/cs2/profile" && method === "PUT") {- Object.assign(profile.values, body.values ?? {});- Object.assign(profile.keybinds, body.keybinds ?? {});+ if (url === "/api/games/cs2/profile" && method === "PUT" && body) {+ for (const field of ["values", "keybinds", "alt_keybinds", "bind_modes"] as const) {+ Object.assign(profile[field], (body[field] as object | undefined) ?? {});+ }+ if (body.custom_binds) profile.custom_binds = body.custom_binds as GameProfile["custom_binds"];profile.updated_at = "2026-10-27T00:00:00+00:00";return json({ profile });}- if (url === "/api/games/convert") {+ if (url === "/api/games/convert" && body) {return json({game_id: "cs2",sens: body.sens,dpi: 800,to_dpi: 800,cm_per_360: 25.97,- edpi: body.sens * 800,+ edpi: Number(body.sens) * 800,results: [{ id: "valorant", name: "Valorant", sens_key: "aim_sens", sens: 0.3143, edpi: 251.4 }],});}@@ -99,6 +145,23 @@ function renderView() {);}+const putWith = (calls: Call[], body: Record<string, unknown>) =>+ calls.some((c) => c.method === "PUT" && c.url === "/api/games/cs2/profile" && JSON.stringify(c.body) === JSON.stringify(body));++async function openTab(name: RegExp) {+ await screen.findByTestId("game-panel-cs2");+ fireEvent.click(screen.getByRole("button", { name }));+}++async function pressAfterListening(events: Event[]) {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ });+ act(() => {+ for (const event of events) window.dispatchEvent(event);+ });+}+describe("GamesView", () => {let calls: Call[];beforeEach(() => {@@ -110,48 +173,109 @@ describe("GamesView", () => {window.localStorage.clear();});- it("opens the first game with its mouse settings and the cm/360 of its default", async () => {+ it("opens on graphics & performance with this PC and the low-refresh tip", async () => {renderView();- expect(await screen.findByTestId("game-panel-cs2")).toBeTruthy();- expect(screen.getByTestId("game-setting-sensitivity")).toBeTruthy();- // 1.25 default @ 800 DPI with yaw 0.022 → 41.6 cm.- expect(within(screen.getByTestId("games-mouse-summary")).getByText(/41[.,]6 cm/)).toBeTruthy();+ expect(await screen.findByTestId("games-performance")).toBeTruthy();+ const system = await screen.findByTestId("games-system");+ expect(within(system).getByText(/RTX 5070 Ti/)).toBeTruthy();+ expect(within(system).getByText(/2560 × 1440 · 60 Hz/)).toBeTruthy();+ expect(screen.getByTestId("games-refresh-tip").textContent).toMatch(/60.*165/);});- it("saves a typed sensitivity when the field loses focus", async () => {+ it("applies a preset with the monitor's resolution and refresh rate", async () => {renderView();- const setting = await screen.findByTestId("game-setting-sensitivity");+ await screen.findByTestId("games-system");+ await waitFor(() => expect(screen.getByTestId("games-apply-recommended")).toBeTruthy());+ fireEvent.click(screen.getByTestId("games-preset-balanced"));+ await waitFor(() =>+ expect(+ putWith(calls, {+ values: {+ perf_fps_cap: "165",+ perf_upscaler: "DLSS",+ perf_resolution: "2560x1440",+ perf_refresh_rate: "165 Hz",+ },+ }),+ ).toBe(true),+ );+ });++ it("picks 5K from the resolution tiles and unlimited FPS from the chips", async () => {+ renderView();+ fireEvent.click(await screen.findByTestId("games-res-5120x2880"));+ await waitFor(() => expect(putWith(calls, { values: { perf_resolution: "5120x2880" } })).toBe(true));+ const fps = screen.getByRole("radiogroup", { name: /FPS limit/ });+ fireEvent.click(within(fps).getByRole("radio", { name: "Unlimited" }));+ await waitFor(() => expect(putWith(calls, { values: { perf_fps_cap: "Unlimited" } })).toBe(true));+ });++ it("saves a typed sensitivity and shows its cm/360", async () => {+ renderView();+ await openTab(/^Mouse$/);+ expect(within(screen.getByTestId("games-mouse-summary")).getByText(/41[.,]6 cm/)).toBeTruthy();+ const setting = screen.getByTestId("game-setting-sensitivity");const input = within(setting).getByRole("textbox", { name: "Mouse Sensitivity" });fireEvent.change(input, { target: { value: "2" } });fireEvent.blur(input);- await waitFor(() =>- expect(calls.some((c) => c.method === "PUT" && JSON.stringify(c.body) === '{"values":{"sensitivity":2}}')).toBe(true),- );+ await waitFor(() => expect(putWith(calls, { values: { sensitivity: 2 } })).toBe(true));});- it("binds a key by pressing it and swallows the press", async () => {+ it("binds a combination while a modifier is held", async () => {renderView();- await screen.findByTestId("game-panel-cs2");- fireEvent.click(screen.getByRole("button", { name: /^Keybinds/ }));+ await openTab(/^Keybinds/);const row = await screen.findByTestId("game-keybind-jump");- fireEvent.click(within(row).getByRole("button", { name: /Jump/ }));- await act(async () => {- await new Promise((resolve) => setTimeout(resolve, 5));- });- const event = new KeyboardEvent("keydown", { code: "KeyF", bubbles: true, cancelable: true });- act(() => {- window.dispatchEvent(event);- });- expect(event.defaultPrevented).toBe(true);+ fireEvent.click(within(row).getByRole("button", { name: /^Jump:/ }));+ const key = new KeyboardEvent("keydown", { code: "KeyF", shiftKey: true, bubbles: true, cancelable: true });+ await pressAfterListening([+ new KeyboardEvent("keydown", { code: "ShiftLeft", shiftKey: true, bubbles: true, cancelable: true }),+ key,+ ]);+ expect(key.defaultPrevented).toBe(true);+ await waitFor(() => expect(putWith(calls, { keybinds: { jump: "Shift + F" } })).toBe(true));+ });++ it("binds a modifier on its own and a mouse button as the secondary bind", async () => {+ renderView();+ await openTab(/^Keybinds/);+ const row = await screen.findByTestId("game-keybind-crouch");+ fireEvent.click(within(row).getByRole("button", { name: /^Crouch:/ }));+ await pressAfterListening([+ new KeyboardEvent("keydown", { code: "AltLeft", altKey: true, bubbles: true, cancelable: true }),+ new KeyboardEvent("keyup", { code: "AltLeft", bubbles: true, cancelable: true }),+ ]);+ await waitFor(() => expect(putWith(calls, { keybinds: { crouch: "Left Alt" } })).toBe(true));++ fireEvent.click(within(row).getByRole("button", { name: /^Crouch \(Secondary\)/ }));+ await pressAfterListening([new MouseEvent("mousedown", { button: 4, bubbles: true, cancelable: true })]);+ await waitFor(() => expect(putWith(calls, { alt_keybinds: { crouch: "Mouse 5" } })).toBe(true));+ });++ it("switches sprint to toggle and adds a custom action", async () => {+ renderView();+ await openTab(/^Keybinds/);+ const sprint = await screen.findByTestId("game-keybind-sprint");+ fireEvent.click(within(sprint).getByRole("radio", { name: "Toggle" }));+ await waitFor(() => expect(putWith(calls, { bind_modes: { sprint: "toggle" } })).toBe(true));+ expect(within(screen.getByTestId("game-keybind-jump")).queryByRole("radio", { name: "Toggle" })).toBeNull();++ fireEvent.click(screen.getByTestId("games-add-custom"));await waitFor(() =>- expect(calls.some((c) => c.method === "PUT" && JSON.stringify(c.body) === '{"keybinds":{"jump":"F"}}')).toBe(true),+ expect(calls.some((c) => c.method === "PUT" && Array.isArray(c.body?.custom_binds) && c.body.custom_binds.length === 1)).toBe(true),);});+ it("lights up the keyboard keys that are bound", async () => {+ renderView();+ await openTab(/^Keybinds/);+ const keyboard = await screen.findByTestId("games-keyboard");+ expect(within(keyboard).getByTestId("games-key-Space").getAttribute("data-bound")).toBe("true");+ expect(within(keyboard).getByTestId("games-key-Q").getAttribute("data-bound")).toBe("false");+ });+it("converts the sensitivity to other games and applies one", async () => {renderView();- await screen.findByTestId("game-panel-cs2");- fireEvent.click(screen.getByRole("button", { name: /^Converter$/ }));+ await openTab(/^Converter$/);fireEvent.change(await screen.findByTestId("games-converter-sens"), { target: { value: "1" } });const table = await screen.findByTestId("games-converter-results");expect(within(table).getByText("Valorant")).toBeTruthy();@@ -164,15 +288,51 @@ describe("GamesView", () => {});});+describe("resolvePreset", () => {+ const settings = Object.fromEntries(+ CS2.sections.flatMap((s) => s.settings).map((s) => [s.key, s]),+ ) as Record<string, GameSetting>;++ it("caps FPS at the highest option the monitor shows", () => {+ expect(resolvePreset(PRESETS[1], settings, SYSTEM).perf_fps_cap).toBe("165");+ });++ it("leaves the monitor-dependent values out when the PC is unknown", () => {+ expect(resolvePreset(PRESETS[1], settings, undefined)).toEqual({ perf_upscaler: "DLSS" });+ });+});+describe("profileSummary", () => {- it("lists only what the player set", () => {+ it("lists only what the player set, with combos, secondary binds and custom actions", () => {const text = profileSummary(CS2,- { values: { sensitivity: 1.1, hud: false }, keybinds: { jump: "Mouse Wheel Down" }, dpi: 400, notes: "", updated_at: null },+ {+ ...blankProfile(),+ values: { sensitivity: 1.1, hud: false },+ keybinds: { jump: "Shift + Mouse 4" },+ alt_keybinds: { jump: "Mouse Wheel Down" },+ bind_modes: { jump: "hold" },+ custom_binds: [{ id: "c1", action: "Buy AK", key: "F5", alt: "" }],+ dpi: 400,+ },400,);expect(text).toBe(- ["Counter-Strike 2 — DPI 400", "", "[mouse]", "Mouse Sensitivity: 1.1", "", "[gameplay]", "Show HUD: Off", "", "[keybinds]", "Jump: Mouse Wheel Down"].join("\n"),+ [+ "Counter-Strike 2 — DPI 400",+ "",+ "[mouse]",+ "Mouse Sensitivity: 1.1",+ "",+ "[gameplay]",+ "Show HUD: Off",+ "",+ "[keybinds]",+ "Jump: Shift + Mouse 4 / Mouse Wheel Down (hold)",+ "",+ "[custom]",+ "Buy AK: F5",+ ].join("\n"),);});});diff --git a/dodaios/ui/web/frontend/src/views/GamesView.tsx b/dodaios/ui/web/frontend/src/views/GamesView.tsxindex 68acf5502c..6a98c2a011 100644--- a/dodaios/ui/web/frontend/src/views/GamesView.tsx+++ b/dodaios/ui/web/frontend/src/views/GamesView.tsx@@ -1,18 +1,37 @@/**- * Settings → Game settings: the player's own settings for each game —- * sensitivity, keybinds, audio, video, gameplay — in one place, plus a- * converter that carries a hip-fire sensitivity from one game to the others- * at the same cm/360 (docs/game-settings.md).+ * Settings → Game settings: the player's own setup for each game — graphics+ * and performance (presets, resolution up to 5K, FPS up to unlimited),+ * mouse, keybinds with combinations, audio, gameplay — plus a converter that+ * carries a hip-fire sensitivity to every other game at the same cm/360+ * (docs/game-settings.md).** Which settings a game has comes from the backend catalog- * (`dodaios/games/catalog.json`), so adding a game never touches this view.+ * (`dodaios/games/catalog.json` plus `dodaios/games/performance.py`), so+ * adding a game never touches this view. Each game wears its own hue+ * (`lib/gameVisuals`), passed down as CSS variables.*/-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useState, type CSSProperties, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";-import { Check, Copy, FileCog, Gamepad2, Loader2, Search, Trash2 } from "lucide-react";-import { GameSettingRow, KeyCaptureButton } from "@/components/games/GameControls";+import {+ Check,+ Copy,+ Crosshair,+ FileCog,+ Gamepad2,+ Keyboard,+ Loader2,+ MonitorCog,+ Repeat,+ Search,+ SlidersHorizontal,+ Trash2,+ Volume2,+ type LucideIcon,+} from "lucide-react";+import { GameSettingRow } from "@/components/games/GameControls";+import { KeybindPanel } from "@/components/games/KeybindPanel";+import { PerformancePanel } from "@/components/games/PerformancePanel";import { PageHeader } from "@/components/layout/PageHeader";-import { TabBar } from "@/components/layout/SectionTabBar";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Textarea } from "@/components/ui/textarea";@@ -25,20 +44,28 @@ import {} from "@/hooks/useGames";import { useT } from "@/i18n";import { robustCopy } from "@/lib/clipboard";-import { keyConflicts } from "@/lib/gameKeys";import {cmPer360,convertSensitivity,type GameDefinition,+ type GamePreset,type GameProfile,type GameSettingValue,type ProfilePatch,} from "@/lib/gamesApi";+import { gameAccent, gameMonogram } from "@/lib/gameVisuals";import { cn } from "@/lib/utils";import { useEventStore } from "@/store/events";-type TabId = "mouse" | "keybinds" | "audio" | "video" | "gameplay" | "converter";-const TABS: readonly TabId[] = ["mouse", "keybinds", "audio", "video", "gameplay", "converter"];+type TabId = "performance" | "mouse" | "keybinds" | "audio" | "gameplay" | "converter";+const TABS: readonly { id: TabId; icon: LucideIcon }[] = [+ { id: "performance", icon: MonitorCog },+ { id: "mouse", icon: Crosshair },+ { id: "keybinds", icon: Keyboard },+ { id: "audio", icon: Volume2 },+ { id: "gameplay", icon: SlidersHorizontal },+ { id: "converter", icon: Repeat },+];const LAST_GAME_KEY = "dodaios.games.last";function readLastGame(): string | null {@@ -61,6 +88,33 @@ function formatNumber(value: number, digits = 2): string {return value.toLocaleString(undefined, { maximumFractionDigits: digits });}+/** The CSS variables that colour one game's page. */+function accentVars(id: string): CSSProperties {+ return {+ "--game-accent": gameAccent(id),+ "--game-accent-soft": gameAccent(id, 0.12),+ "--game-accent-glow": gameAccent(id, 0.35),+ } as CSSProperties;+}++function Monogram({ id, name, size = "sm" }: { id: string; name: string; size?: "sm" | "lg" }) {+ return (+ <span+ aria-hidden+ style={{+ background: `linear-gradient(135deg, ${gameAccent(id, 0.95)}, ${gameAccent(id, 0.45)})`,+ boxShadow: `0 0 ${size === "lg" ? 28 : 12}px ${gameAccent(id, 0.35)}`,+ }}+ className={cn(+ "flex shrink-0 items-center justify-center rounded-lg font-mono font-bold text-black/85",+ size === "lg" ? "h-16 w-16 text-xl" : "h-9 w-9 text-xs",+ )}+ >+ {gameMonogram(name)}+ </span>+ );+}+export function GamesView() {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -68,7 +122,7 @@ export function GamesView() {const saveDpi = useSaveDefaultDpi();const [query, setQuery] = useState("");const [selected, setSelected] = useState<string | null>(() => readLastGame());- const [tab, setTab] = useState<TabId>("mouse");+ const [tab, setTab] = useState<TabId>("performance");const games = index.data?.games ?? [];useEffect(() => {@@ -94,7 +148,7 @@ export function GamesView() {data-testid="games-view"className="flex h-full flex-col overflow-y-auto bg-background px-4 pb-10 scrollbar-jarvis sm:px-8">- <div className="w-full max-w-[1400px]">+ <div className="w-full max-w-[1500px]"><PageHeadericon={<Gamepad2 />}title={t("games.title")}@@ -125,7 +179,7 @@ export function GamesView() {{index.data && (<div className="flex flex-col gap-6 lg:flex-row">- <aside className="lg:w-64 lg:shrink-0">+ <aside className="lg:w-60 lg:shrink-0"><div className="relative mb-3"><SearchclassName="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"@@ -139,35 +193,47 @@ export function GamesView() {className="h-8 pl-8"/></div>- <ul className="flex gap-1 overflow-x-auto pb-1 lg:flex-col lg:overflow-visible lg:pb-0" data-testid="games-list">- {visible.map((game) => (- <li key={game.id} className="shrink-0">- <button- type="button"- data-testid={`games-pick-${game.id}`}- aria-current={game.id === selected ? "true" : undefined}- onClick={() => choose(game.id)}- className={cn(- "flex w-full items-center gap-2 rounded-md px-3 py-2 text-left transition-colors",- game.id === selected- ? "bg-secondary text-foreground-strong"- : "text-foreground hover:bg-secondary/60",- )}- >- <span className="min-w-0 flex-1">- <span className="block truncate text-sm font-medium">{game.name}</span>- <span className="block truncate text-xs text-muted-foreground">{game.publisher}</span>- </span>- {game.has_profile && (- <span- className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"- title={t("games.saved_badge")}- aria-label={t("games.saved_badge")}- />- )}- </button>- </li>- ))}+ <ul+ className="flex gap-1.5 overflow-x-auto pb-1 lg:flex-col lg:overflow-visible lg:pb-0"+ data-testid="games-list"+ >+ {visible.map((game) => {+ const active = game.id === selected;+ return (+ <li key={game.id} className="shrink-0">+ <button+ type="button"+ data-testid={`games-pick-${game.id}`}+ aria-current={active ? "true" : undefined}+ onClick={() => choose(game.id)}+ style={active ? accentVars(game.id) : undefined}+ className={cn(+ "flex w-full items-center gap-3 rounded-lg border px-2.5 py-2 text-left transition-all",+ active+ ? "border-[var(--game-accent)] bg-[var(--game-accent-soft)]"+ : "border-transparent text-foreground hover:bg-secondary/60",+ )}+ >+ <Monogram id={game.id} name={game.name} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground-strong">+ {game.name}+ </span>+ <span className="block truncate text-[11px] text-muted-foreground">+ {game.publisher}+ </span>+ </span>+ {game.has_profile && (+ <span+ className="h-1.5 w-1.5 shrink-0 rounded-full bg-accent"+ title={t("games.saved_badge")}+ aria-label={t("games.saved_badge")}+ />+ )}+ </button>+ </li>+ );+ })}</ul></aside>@@ -177,6 +243,7 @@ export function GamesView() {key={selected}gameId={selected}defaultDpi={index.data.dpi}+ presets={index.data.presets ?? []}tab={tab}onTab={setTab}/>@@ -237,14 +304,25 @@ function DpiField({);}+function HeroStat({ label, value }: { label: string; value: string }) {+ return (+ <div className="min-w-0">+ <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">{label}</p>+ <p className="truncate font-mono text-lg font-semibold tabular-nums text-foreground-strong">{value}</p>+ </div>+ );+}+function GamePanel({gameId,defaultDpi,+ presets,tab,onTab,}: {gameId: string;defaultDpi: number;+ presets: GamePreset[];tab: TabId;onTab: (tab: TabId) => void;}) {@@ -277,87 +355,159 @@ function GamePanel({);}- const { game, profile } = detail.data;+ const { game, profile: raw } = detail.data;+ const profile: GameProfile = {+ ...raw,+ alt_keybinds: raw.alt_keybinds ?? {},+ bind_modes: raw.bind_modes ?? {},+ custom_binds: raw.custom_binds ?? [],+ };const dpi = profile.dpi ?? defaultDpi;- const section = game.sections.find((s) => s.id === tab);const hasProfile = profile.updated_at !== null;+ const allSettings = game.sections.flatMap((s) => s.settings);+ const effective = (key: string) =>+ profile.values[key] ?? allSettings.find((s) => s.key === key)?.default ?? null;+ const sensRaw = game.sens_key ? effective(game.sens_key) : null;+ const sens = typeof sensRaw === "number" ? sensRaw : null;+ const cm = game.yaw && sens ? cmPer360(game.yaw, sens, dpi) : null;+ const res = String(effective("perf_resolution") ?? "—").replace("x", " × ");+ const fps = String(effective("perf_fps_cap") ?? "—");const copySummary = async () => {const ok = await robustCopy(profileSummary(game, profile, dpi));pushToast(ok ? "success" : "error", ok ? t("games.copied") : t("games.copy_failed"));};+ const sectionRows = (id: string) => {+ const settings = game.sections.find((s) => s.id === id)?.settings ?? [];+ if (settings.length === 0) {+ return <p className="py-6 text-sm text-muted-foreground">{t("games.section_empty")}</p>;+ }+ return settings.map((setting) => (+ <GameSettingRow+ key={setting.key}+ setting={setting}+ value={profile.values[setting.key]}+ onChange={(value) => patch({ values: { [setting.key]: value } })}+ />+ ));+ };+return (- <div data-testid={`game-panel-${game.id}`}>- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h2 className="text-lg font-semibold text-foreground-strong">{game.name}</h2>- <p className="text-xs text-muted-foreground">{game.publisher}</p>+ <div data-testid={`game-panel-${game.id}`} style={accentVars(game.id)}>+ <header+ className="relative overflow-hidden rounded-2xl border border-border px-5 py-5 sm:px-6"+ style={{+ background: `radial-gradient(120% 140% at 0% 0%, ${gameAccent(game.id, 0.28)}, transparent 55%), radial-gradient(80% 120% at 100% 100%, ${gameAccent(game.id, 0.12)}, transparent 60%), hsl(var(--card))`,+ }}+ >+ <div+ aria-hidden+ className="pointer-events-none absolute inset-0 opacity-[0.07] [background-image:linear-gradient(hsl(var(--foreground))_1px,transparent_1px),linear-gradient(90deg,hsl(var(--foreground))_1px,transparent_1px)] [background-size:28px_28px]"+ />+ <div className="relative flex flex-wrap items-start justify-between gap-4">+ <div className="flex min-w-0 items-center gap-4">+ <Monogram id={game.id} name={game.name} size="lg" />+ <div className="min-w-0">+ <p className="font-mono text-[10px] uppercase tracking-[0.2em] text-[var(--game-accent)]">+ {game.publisher}+ </p>+ <h2 className="truncate text-2xl font-bold tracking-tight text-foreground-strong sm:text-3xl">+ {game.name}+ </h2>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Button type="button" variant="outline" size="sm" onClick={() => void copySummary()}>+ <Copy aria-hidden />+ {t("games.copy")}+ </Button>+ <Button+ type="button"+ variant={confirmReset ? "destructive" : "outline"}+ size="sm"+ disabled={!hasProfile || reset.isPending}+ onBlur={() => setConfirmReset(false)}+ onClick={() => {+ if (!confirmReset) return setConfirmReset(true);+ setConfirmReset(false);+ reset.mutate(game.id, {+ onSuccess: () => pushToast("success", t("games.reset_done").replace("{0}", game.name)),+ onError: (error) =>+ pushToast("error", t("games.save_error").replace("{0}", (error as Error).message)),+ });+ }}+ >+ <Trash2 aria-hidden />+ {confirmReset ? t("games.reset_confirm") : t("games.reset_profile")}+ </Button>+ </div></div>- <div className="flex items-center gap-2">- <Button type="button" variant="outline" size="sm" onClick={() => void copySummary()}>- <Copy aria-hidden />- {t("games.copy")}- </Button>- <Button- type="button"- variant={confirmReset ? "destructive" : "outline"}- size="sm"- disabled={!hasProfile || reset.isPending}- onBlur={() => setConfirmReset(false)}- onClick={() => {- if (!confirmReset) return setConfirmReset(true);- setConfirmReset(false);- reset.mutate(game.id, {- onSuccess: () => pushToast("success", t("games.reset_done").replace("{0}", game.name)),- onError: (error) =>- pushToast("error", t("games.save_error").replace("{0}", (error as Error).message)),- });- }}- >- <Trash2 aria-hidden />- {confirmReset ? t("games.reset_confirm") : t("games.reset_profile")}- </Button>+ <div className="relative mt-5 grid grid-cols-2 gap-4 sm:grid-cols-4" data-testid="games-hero-stats">+ <HeroStat label={t("games.perf.resolution")} value={res} />+ <HeroStat+ label={t("games.perf.fps_limit")}+ value={fps === "Unlimited" ? t("games.perf.unlimited") : fps}+ />+ <HeroStat label={t("games.cm360")} value={cm ? `${formatNumber(cm, 1)} cm` : "—"} />+ <HeroStat label={t("games.edpi")} value={sens ? formatNumber(sens * dpi, 0) : "—"} /></div>- </div>-- <TabBar- className="mt-4"- tabs={TABS.map((id) => ({- id,- label: t(`games.tabs.${id}`),- count: id === "keybinds" ? game.keybinds.length : undefined,- }))}- active={tab}- onChange={(id) => onTab(id as TabId)}- />-- <div className="mt-4 rounded-lg border border-border bg-card px-4">+ </header>++ <nav+ className="sticky top-0 z-10 -mx-1 mt-4 flex gap-1 overflow-x-auto rounded-xl border border-border bg-background/85 p-1 backdrop-blur"+ aria-label={game.name}+ >+ {TABS.map(({ id, icon: Icon }) => {+ const active = tab === id;+ return (+ <button+ key={id}+ type="button"+ aria-current={active ? "page" : undefined}+ onClick={() => onTab(id)}+ className={cn(+ "flex shrink-0 items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-all",+ active+ ? "bg-[var(--game-accent-soft)] text-foreground-strong shadow-[inset_0_-2px_0_var(--game-accent)]"+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",+ )}+ >+ <Icon className={cn("h-4 w-4", active && "text-[var(--game-accent)]")} aria-hidden />+ {t(`games.tabs.${id}`)}+ {id === "keybinds" && (+ <span className="font-mono text-[11px] text-muted-foreground">{game.keybinds.length}</span>+ )}+ </button>+ );+ })}+ </nav>++ <div className="mt-4">+ {tab === "performance" && (+ <PerformancePanel game={game} profile={profile} presets={presets} onPatch={patch} />+ )}{tab === "mouse" && (- <MouseSummary game={game} profile={profile} defaultDpi={defaultDpi} onPatch={patch} />+ <Panel>+ <MouseSummary game={game} profile={profile} defaultDpi={defaultDpi} onPatch={patch} />+ {sectionRows("mouse")}+ </Panel>+ )}+ {tab === "keybinds" && <KeybindPanel game={game} profile={profile} onPatch={patch} />}+ {tab === "audio" && <Panel>{sectionRows("audio")}</Panel>}+ {tab === "gameplay" && <Panel>{sectionRows("gameplay")}</Panel>}+ {tab === "converter" && (+ <Panel>+ <Converter game={game} profile={profile} dpi={dpi} />+ </Panel>)}- {section &&- (section.settings.length === 0 ? (- <p className="py-6 text-sm text-muted-foreground">{t("games.section_empty")}</p>- ) : (- section.settings.map((setting) => (- <GameSettingRow- key={setting.key}- setting={setting}- value={profile.values[setting.key]}- onChange={(value) => patch({ values: { [setting.key]: value } })}- />- ))- ))}- {tab === "keybinds" && <KeybindList game={game} profile={profile} onPatch={patch} />}- {tab === "converter" && <Converter game={game} profile={profile} dpi={dpi} />}</div><div className="mt-6 grid gap-4 md:grid-cols-2"><NotesField value={profile.notes} onCommit={(notes) => patch({ notes })} />- <div className="rounded-lg border border-border bg-card p-4">+ <div className="rounded-xl border border-border bg-card/80 p-4"><div className="flex items-center gap-2 text-sm font-medium text-foreground">- <FileCog className="h-4 w-4 text-muted-foreground" aria-hidden />+ <FileCog className="h-4 w-4 text-[var(--game-accent)]" aria-hidden />{t("games.config_file")}</div><p className="mt-2 break-words font-mono text-xs text-muted-foreground">{game.config_file}</p>@@ -367,6 +517,14 @@ function GamePanel({);}+function Panel({ children }: { children: ReactNode }) {+ return (+ <div className="relative overflow-hidden rounded-xl border border-border bg-card/80 px-5 before:absolute before:inset-y-0 before:left-0 before:w-[3px] before:bg-[var(--game-accent)]">+ {children}+ </div>+ );+}+function MouseSummary({game,profile,@@ -426,78 +584,6 @@ function Stat({ label, value, hint }: { label: string; value: string; hint?: str);}-function KeybindList({- game,- profile,- onPatch,-}: {- game: GameDefinition;- profile: GameProfile;- onPatch: (patch: ProfilePatch) => void;-}) {- const t = useT();- const rows = game.keybinds.map((bind) => ({- ...bind,- key: profile.keybinds[bind.id] ?? bind.default,- saved: bind.id in profile.keybinds,- }));- const conflicts = keyConflicts(rows);-- return (- <div data-testid="games-keybinds">- <p className="border-b border-border/60 py-3 text-xs text-muted-foreground">{t("games.keybind_hint")}</p>- {rows.map((row) => {- const clash = conflicts.get(row.id);- return (- <div- key={row.id}- data-testid={`game-keybind-${row.id}`}- className="flex flex-wrap items-center gap-3 border-b border-border/60 py-2 last:border-b-0"- >- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <span className="text-sm text-foreground">{row.action}</span>- {row.saved && <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-primary" />}- </div>- {clash && (- <p className="text-xs text-amber-500">- {t("games.keybind_conflict").replace("{0}", clash.join(", "))}- </p>- )}- {!clash && row.note && <p className="text-xs text-muted-foreground">{row.note}</p>}- </div>- <KeyCaptureButton- value={row.key}- label={row.action}- onCapture={(key) => onPatch({ keybinds: { [row.id]: key } })}- />- <Button- type="button"- variant="ghost"- size="sm"- className="text-xs"- onClick={() => onPatch({ keybinds: { [row.id]: "" } })}- disabled={row.key === ""}- >- {t("games.keybind_clear")}- </Button>- <Button- type="button"- variant="ghost"- size="sm"- className={cn("text-xs", !row.saved && "invisible")}- onClick={() => onPatch({ keybinds: { [row.id]: null } })}- title={row.default ? t("games.default_value").replace("{0}", row.default) : undefined}- >- {t("games.keybind_reset")}- </Button>- </div>- );- })}- </div>- );-}-function Converter({ game, profile, dpi }: { game: GameDefinition; profile: GameProfile; dpi: number }) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -581,7 +667,7 @@ function Converter({ game, profile, dpi }: { game: GameDefinition; profile: Game{result.data && (<div className="ml-auto text-right"><p className="text-xs text-muted-foreground">{t("games.cm360")}</p>- <p className="font-mono text-xl tabular-nums text-foreground-strong" data-testid="games-converter-cm">+ <p className="font-mono text-2xl font-semibold tabular-nums text-[var(--game-accent)]" data-testid="games-converter-cm">{formatNumber(result.data.cm_per_360, 1)} cm</p></div>@@ -597,7 +683,7 @@ function Converter({ game, profile, dpi }: { game: GameDefinition; profile: Game{result.data && (<table className="mt-4 w-full text-sm" data-testid="games-converter-results"><thead>- <tr className="text-left text-xs text-muted-foreground">+ <tr className="text-left font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground"><th className="py-2 font-normal">{t("games.converter_game")}</th><th className="py-2 text-right font-normal">{t("games.converter_sens")}</th><th className="hidden py-2 text-right font-normal sm:table-cell">{t("games.edpi")}</th>@@ -607,7 +693,12 @@ function Converter({ game, profile, dpi }: { game: GameDefinition; profile: Game<tbody>{result.data.results.map((row) => (<tr key={row.id} className="border-t border-border/60">- <td className="py-2 text-foreground">{row.name}</td>+ <td className="py-2">+ <span className="flex items-center gap-2.5 text-foreground">+ <Monogram id={row.id} name={row.name} />+ {row.name}+ </span>+ </td><td className="py-2 text-right font-mono tabular-nums text-foreground-strong">{formatNumber(row.sens, 3)}</td>@@ -641,7 +732,7 @@ function NotesField({ value, onCommit }: { value: string; onCommit: (notes: striconst [draft, setDraft] = useState(value);useEffect(() => setDraft(value), [value]);return (- <label className="flex flex-col gap-2 rounded-lg border border-border bg-card p-4">+ <label className="flex flex-col gap-2 rounded-xl border border-border bg-card/80 p-4"><span className="text-sm font-medium text-foreground">{t("games.notes")}</span><Textareavalue={draft}@@ -655,6 +746,10 @@ function NotesField({ value, onCommit }: { value: string; onCommit: (notes: stri);}+function valueText(value: GameSettingValue): string {+ return typeof value === "boolean" ? (value ? "On" : "Off") : String(value);+}+/** Plain-text summary of a profile, for pasting into chat or a note. */export function profileSummary(game: GameDefinition, profile: GameProfile, dpi: number): string {const lines = [`${game.name} — DPI ${dpi}`];@@ -662,15 +757,24 @@ export function profileSummary(game: GameDefinition, profile: GameProfile, dpi:const set = section.settings.filter((s) => profile.values[s.key] !== undefined);if (set.length === 0) continue;lines.push("", `[${section.id}]`);- for (const s of set) {- const value: GameSettingValue = profile.values[s.key];- lines.push(`${s.label}: ${typeof value === "boolean" ? (value ? "On" : "Off") : value}`);- }+ for (const s of set) lines.push(`${s.label}: ${valueText(profile.values[s.key])}`);}- const binds = game.keybinds.filter((b) => b.id in profile.keybinds);+ const binds = game.keybinds.filter(+ (b) => b.id in profile.keybinds || b.id in (profile.alt_keybinds ?? {}),+ );if (binds.length > 0) {lines.push("", "[keybinds]");- for (const b of binds) lines.push(`${b.action}: ${profile.keybinds[b.id] || "—"}`);+ for (const b of binds) {+ const primary = profile.keybinds[b.id] ?? b.default;+ const alt = profile.alt_keybinds?.[b.id];+ const mode = profile.bind_modes?.[b.id];+ lines.push(`${b.action}: ${primary || "—"}${alt ? ` / ${alt}` : ""}${mode ? ` (${mode})` : ""}`);+ }+ }+ const custom = (profile.custom_binds ?? []).filter((c) => c.action || c.key);+ if (custom.length > 0) {+ lines.push("", "[custom]");+ for (const c of custom) lines.push(`${c.action || "—"}: ${c.key || "—"}${c.alt ? ` / ${c.alt}` : ""}`);}if (profile.notes.trim()) lines.push("", profile.notes.trim());return lines.join("\n");diff --git a/dodaios/ui/web/games_routes.py b/dodaios/ui/web/games_routes.pyindex a48534bda1..ef34fc1b71 100644--- a/dodaios/ui/web/games_routes.py+++ b/dodaios/ui/web/games_routes.py@@ -9,6 +9,8 @@ Endpoints (mounted by the WebServer in ``_build_app()``):PUT /api/games/{id}/profile → merge values / keybinds / dpi / notes.DELETE /api/games/{id}/profile → forget the profile (back to defaults).PUT /api/games/dpi → the default mouse DPI.+ GET /api/games/system → GPU, CPU, RAM, monitors and the+ preset that suits this PC.POST /api/games/convert → a hip-fire sensitivity in every othergame with the same cm/360.@@ -24,7 +26,7 @@ from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModelfrom dodaios.games import sensitivity-from dodaios.games.catalog import get_game, list_games+from dodaios.games.catalog import get_game, list_games, load_catalogfrom dodaios.games.store import GameProfileStore, UnknownGameErrorrouter = APIRouter(prefix="/api/games", tags=["games"])@@ -53,9 +55,19 @@ def games_index() -> dict[str, Any]:return {"dpi": data["dpi"],"games": [_summary(g, data["games"]) for g in list_games()],+ "presets": load_catalog()["presets"],}[email protected]("/system")+def system() -> dict[str, Any]:+ # Sync on purpose: FastAPI runs it in the threadpool, and the first call+ # shells out to nvidia-smi / PowerShell (cached after that).+ from dodaios.games.system import system_info++ return system_info()++class DpiBody(BaseModel):dpi: int@@ -129,6 +141,9 @@ def game_detail(game_id: str) -> dict[str, Any]:class ProfileBody(BaseModel):values: dict[str, Any] | None = Nonekeybinds: dict[str, str | None] | None = None+ alt_keybinds: dict[str, str | None] | None = None+ bind_modes: dict[str, str | None] | None = None+ custom_binds: list[dict[str, Any]] | None = Nonedpi: int | None = None# Distinguishes "dpi": null (follow the default) from leaving dpi out.reset_dpi: bool = False@@ -144,7 +159,14 @@ def save_profile(game_id: str, body: ProfileBody) -> dict[str, Any]:dpi = body.dpitry:profile = _store().update(- game_id, values=body.values, keybinds=body.keybinds, dpi=dpi, notes=body.notes+ game_id,+ values=body.values,+ keybinds=body.keybinds,+ alt_keybinds=body.alt_keybinds,+ bind_modes=body.bind_modes,+ custom_binds=body.custom_binds,+ dpi=dpi,+ notes=body.notes,)except UnknownGameError as exc:raise HTTPException(status_code=404, detail="Unknown game") from excdiff --git a/tests/unit/games/test_games.py b/tests/unit/games/test_games.pyindex b8c41c8b7f..e250b3cf42 100644--- a/tests/unit/games/test_games.py+++ b/tests/unit/games/test_games.py@@ -240,3 +240,140 @@ def test_convert_refuses_non_linear_games_and_bad_input(client: TestClient) -> Nassert client.post("/api/games/convert", json={"game_id": "cs2", "sens": 0}).status_code == 400assert client.post("/api/games/convert", json={"game_id": "x", "sens": 1}).status_code == 404assert client.put("/api/games/dpi", json={"dpi": 1}).status_code == 400+++# --------------------------------------------------------------------------- v2: performance+++def test_every_game_gets_the_performance_block() -> None:+ for game in list_games():+ keys = {s["key"] for sec in game["sections"] for s in sec["settings"]}+ assert {"perf_resolution", "perf_fps_cap", "perf_upscaler", "perf_rt"} <= keys+++def test_resolutions_reach_5k_and_fps_reaches_unlimited() -> None:+ game = get_game("cs2")+ settings = {s["key"]: s for sec in game["sections"] for s in sec["settings"]}+ assert "1920x1080" in settings["perf_resolution"]["options"]+ assert "5120x2880" in settings["perf_resolution"]["options"]+ assert settings["perf_fps_cap"]["options"][-1] == "Unlimited"+++def test_duplicated_game_video_settings_are_dropped() -> None:+ labels = [+ s["label"]+ for sec in get_game("fortnite")["sections"]+ if sec["id"] == "video"+ for s in sec["settings"]+ ]+ assert "Window Mode" not in labels+ assert "Resolution" not in labels+ assert "3D Resolution" in labels+++def test_every_preset_value_is_valid() -> None:+ from dodaios.games.catalog import load_catalog+ from dodaios.games.store import check_value++ settings = {s["key"]: s for sec in get_game("cs2")["sections"] for s in sec["settings"]}+ presets = load_catalog()["presets"]+ assert [p["id"] for p in presets] == ["competitive", "balanced", "quality", "epic"]+ for preset in presets:+ for key, value in preset["values"].items():+ if value == "monitor": # filled in from the detected monitor by the page+ continue+ assert check_value(settings[key], value) == value, (preset["id"], key)+++ ("gpu", "tier"),+ [+ ({"name": "NVIDIA GeForce RTX 4090", "vram_gb": 24}, "enthusiast"),+ ({"name": "NVIDIA GeForce RTX 5070 Ti", "vram_gb": 15.9}, "high"),+ ({"name": "NVIDIA GeForce RTX 4060", "vram_gb": 8}, "mid"),+ ({"name": "NVIDIA GeForce GTX 1650", "vram_gb": 4}, "entry"),+ ({"name": "AMD Radeon RX 7900 XTX", "vram_gb": None}, "enthusiast"),+ ({"name": "AMD Radeon RX 6600", "vram_gb": None}, "mid"),+ ({"name": "Intel Arc A770", "vram_gb": 16}, "enthusiast"),+ ({"name": "Unknown", "vram_gb": None}, None),+ ],+)+def test_gpu_tier(gpu: dict, tier: str | None) -> None:+ from dodaios.games.system import gpu_tier++ assert gpu_tier([gpu]) == tier+++def test_nominal_refresh_rates() -> None:+ from dodaios.games.system import _nominal_hz++ assert [_nominal_hz(h) for h in (59, 119, 143, 144, 164, 239)] == [60, 120, 144, 144, 165, 240]+++# --------------------------------------------------------------------------- v2: keybinds+++def test_combos_alt_binds_modes_and_custom_actions(store: GameProfileStore) -> None:+ store.update(+ "fortnite",+ keybinds={"jump": "Ctrl + Shift + Mouse 4"},+ alt_keybinds={"jump": "Mouse Wheel Down"},+ bind_modes={"sprint": "toggle"},+ custom_binds=[{"id": "c1", "action": "Quick edit", "key": "Alt + E", "alt": ""}],+ )+ profile = store.profile("fortnite")+ assert profile["keybinds"] == {"jump": "Ctrl + Shift + Mouse 4"}+ assert profile["alt_keybinds"] == {"jump": "Mouse Wheel Down"}+ assert profile["bind_modes"] == {"sprint": "toggle"}+ assert profile["custom_binds"][0]["key"] == "Alt + E"+ store.update("fortnite", alt_keybinds={"jump": None}, bind_modes={"sprint": None})+ profile = store.profile("fortnite")+ assert profile["alt_keybinds"] == {}+ assert profile["bind_modes"] == {}+ assert len(profile["custom_binds"]) == 1 # left out = kept+++ ("change", "message"),+ [+ ({"bind_modes": {"sprint": "sometimes"}}, "hold or toggle"),+ ({"alt_keybinds": {"fly": "F"}}, "Unknown keybind"),+ ({"custom_binds": [{"id": "a", "action": "x", "key": "F"}] * 2}, "own id"),+ ({"custom_binds": "nope"}, "list"),+ ],+)+def test_bad_keybind_changes_are_refused(+ store: GameProfileStore, change: dict, message: str+) -> None:+ with pytest.raises(ValueError, match=message):+ store.update("fortnite", **change)+++def test_system_endpoint(client: TestClient, monkeypatch) -> None:+ import dodaios.games.system as system++ system.system_info.cache_clear()+ monkeypatch.setattr(+ system, "_gpus", lambda: [{"name": "NVIDIA GeForce RTX 4080", "vram_gb": 16}]+ )+ monkeypatch.setattr(system, "_monitors", lambda: [])+ body = client.get("/api/games/system").json()+ system.system_info.cache_clear()+ assert body["gpu_tier"] == "enthusiast"+ assert body["recommended_preset"] == "epic"+++def test_index_carries_presets_and_profile_saves_new_fields(client: TestClient) -> None:+ assert len(client.get("/api/games").json()["presets"]) == 4+ response = client.put(+ "/api/games/cs2/profile",+ json={+ "values": {"perf_resolution": "3840x2160", "perf_fps_cap": "Unlimited"},+ "alt_keybinds": {"jump": "Mouse Wheel Down"},+ "custom_binds": [{"id": "c1", "action": "Buy menu", "key": "B", "alt": ""}],+ },+ )+ assert response.status_code == 200+ profile = response.json()["profile"]+ assert profile["values"]["perf_resolution"] == "3840x2160"+ assert profile["custom_binds"][0]["action"] == "Buy menu"