Merge branch 'ap/launcher-ui' into round2
profile.rs: both fields kept, Compare's named `aa` and the launcher's `[engine]` table. `aa` is treated like the other named engine settings (named_for, NAMED_ENGINE_KEYS, forced()), so a later layer wins whichever way it sets anti-aliasing and the launcher's row drops the older named key; new test. Compare's --aa planner test no longer expects --hz 60 (launcher-ui passes no --hz when the profile sets no multiplier).
No files matched your search
@@ -4278,6 +4278,7 @@ name = "summit-gui"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"serde_json",
|
||||
"slint",
|
||||
"slint-build",
|
||||
"summit-core",
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/media/summit-unfiltered.png" width="49%" alt="Summit Unfiltered: a list grouped by source, each entry with the reasons it was detected">
|
||||
<img src="docs/media/summit-settings.png" width="49%" alt="Summit settings: layout, six theme swatches, interface size, animation speed and style, clip lengths">
|
||||
<img src="docs/media/summit-settings.png" width="49%" alt="Summit settings: presets and the quick engine settings on top, a list of sections on the left, the Launcher section with layout, six theme swatches, interface size and animation settings, and a detail panel on the right">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -97,11 +97,15 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
|
||||
| `summit doctor` readiness list | **Working** (KDE Wayland) / **Tested** | Says whether the engine, its venv, torch with CUDA, the model, `ffmpeg`, `xrandr`, `xdg-open` and a file dialog are there, and what each missing one turns off. On Wayland also XWayland, the ScreenCast and GlobalShortcuts portals, `summit.desktop` for the app id (the warning's wording is hedged after the re-run: the portal worked once without it), PipeWire and GStreamer's `pipewiresrc`, KWin, the monitor tool and the GPU. Run on the KDE Wayland desktop, twice (all ok, torch 2.11+cu128 on the RTX 5080; the second time from an installed copy) and on the build machine; unit tests. |
|
||||
| Pin to Home, custom artwork | **Working** / **Tested** | Pins from the CLI and the launcher; `summit art`. **New since the RC run**: the launcher's **Change artwork** opens the desktop's file dialog (kdialog on KDE, zenity elsewhere) and the cover and backdrop change at once: checked on Xvfb with a stand-in zenity, not on a real desktop. |
|
||||
| Display profile applied at launch (monitor, resolution, refresh) and put back | **Working on X11 and KDE Wayland** | KDE Wayland: `summit run` switched HDMI-A-1 from 1920x1080 @ 119.98 to @ 60 Hz and back, four times, with `kscreen-doctor` picking the mode by id (that monitor has two modes named `1920x1080@120`, so the old name-based plan could restore the wrong one). X11, earlier: from a custom mode to 1280x800 @ 74.99 Hz and back. wlroots: unit tests only. GNOME Wayland: skipped with a message. |
|
||||
| Per-game profile editor (Profile on a game's page) | **Working** (earlier run) | Listed the monitor's real xrandr modes; every change is written to the profile. Not opened in this run. |
|
||||
| Launcher defaults with per-game overrides (Settings > Default launch profile; every setting: monitor and mode, window mode, focus, Enhance, upscaler and its quality, frame generation, model, motion detail, AI engine, Steady HUD, output rate, fill, VSync, watermark, launch arguments, environment) | **Tested** | New. Profiles are layered: `default.toml` holds the defaults, a game's file only what it changes; in the editor each game row starts with "Default · <value>". Unit tests cover the layering, the old-file migration and the editor rows; the CLI was run against a scratch config, and the editor was rendered headless and driven with keys (a choice changed, one reset with Delete, an environment variable typed and saved). The new engine flags (`--fsr-sharpness`, `--vsr-quality`, `--vfg-quality`, `--scale`, `--engine`, `--steady-hud`, `--fill`, `--vsync`) are checked as argv only, **not with a running engine**. |
|
||||
| Settings page built from the engine's settings registry: every engine setting in its section, a section list, search, the quick settings on top, help, picture/speed lines, Experimental tags, greyed with the reason when not used, a dot and reset for changed rows | **Tested** (headless) | New. The launcher asks the engine (`python -m framegen.settings`) and keeps no copy: a copy of the engine with an invented section, new settings, a new impact line and a setting without choices was rendered and showed all of them (`docs/media/launcher-ui/`, and a unit test). Rendered headless with the software renderer and driven with keys: a preset, a quick tile, a row, Delete, a typed search, the theme and the replay lengths each changed the real file (`settings.json`, `ui.toml`), which the engine's own `Settings.load` then read back. **Not run in a window on a desktop, not with a mouse, not with a controller**; animations were only seen as static frames. |
|
||||
| Engine presets (Quality, Balanced, Performance, Lowest delay), global or for one game, "Custom" once a value differs | **Tested** (headless) | New. One table (`crates/summit-core/src/presets.rs`); a test checks every value against the engine's registry. Applied with keys in a headless render, globally and to a game's profile. What each one costs is taken from the engine's own notes, **not measured for the presets**. |
|
||||
| A game's profile (Profile on its page): the same rows as Settings, each "Global" until the game sets its own | **Tested** (headless) | Rewritten. A game's engine settings go into an `[engine]` table in its profile and reach the engine as `--set KEY=VALUE` (new engine flag); `summit enhance --dry-run` printed them and the engine's parser took each. **No game was started with them.** Monitor modes were listed from xrandr in an earlier live run; not opened on a desktop in this one. |
|
||||
| A game's Statistics: time played, and the engine's session summaries | **Tested** / **Experimental** | New. Reads `*.json` under the engine's and Summit's `sessions` and `stats` folders as they are and shows the fields they hold. The engine's summaries come from another branch: **no real one was read**, only sample files and the empty state. |
|
||||
| Compare (a game's page): start with the engine's `--compare` | **Experimental** | New. Disabled with a note while the engine has no `--compare` (this branch's does not). Against a copy of the engine with a placeholder flag, a headless run built `summit run <id> --compare=hz:60,90,120,150 --enhance`. The value spelling is a guess until the engine's side exists; **never run with a game**. |
|
||||
| Global settings with per-game overrides (launch settings: monitor and mode, window mode, focus, Enhance, launch arguments, environment; and every engine setting) | **Tested** | Profiles are layered: `default.toml` holds the game defaults (Settings > Game defaults), a game's file only what it changes. Engine settings are global in the engine's `settings.json` and per game in the profile's `[engine]` table. Unit tests cover the layering, the old-file migration, the rows and the argv; the CLI was run against a scratch config. Older profiles' named engine settings (`upscaler`, `framegen`...) still work and are replaced key by key as they are changed. With no multiplier in a profile, Summit now passes no `--hz`, so the engine's saved Frame multiplier counts. Checked as argv and with the engine's parser, **not with a running engine**. |
|
||||
| Window mode (windowed / borderless / fullscreen), monitor and focus applied to the game's own window | **Working on KDE Plasma Wayland** / **Experimental elsewhere** | New. On the owner's Plasma Wayland desktop, `summit run` started an XWayland `xterm` from a launch script and a KWin script placed it: borderless covered HDMI-A-1 exactly (0,251 1920×1080), fullscreen moved it onto DP-1 and covered that, and windowed gave it a normal frame back. Other X11 desktops use `wmctrl` (unit tests only). A native Wayland game window, a Steam game (window class `steam_app_<id>`) and KDE X11 were **not run**. |
|
||||
| `summit enhance clip.mp4` (RIFE on a file) | **Working** (earlier run) | 30 fps 1080p to 60 fps at 14 ms per generated frame on the RTX 3090. |
|
||||
| Game controller navigation | **Experimental** | Reads `/dev/input/js*`; decoding and mapping unit tested, no real controller. The launcher listens to a pad only while its own window has the keyboard, and not at all while a game started from it runs (below). |
|
||||
| Game controller navigation | **Experimental** | Reads `/dev/input/js*`; decoding and mapping unit tested, no real controller. Y resets the focused setting, LB/RB change section in a profile. The launcher listens to a pad only while its own window has the keyboard, and not at all while a game started from it runs (below). |
|
||||
| Play: a loading screen, then "now playing", and the launcher back when the game closes | **Working on X11; not yet tried on KDE Wayland or with a real Steam game** | Run for real in a private X server: Play on a game Summit starts itself put the loading screen up, then "now playing"; keys pressed in the launcher meanwhile changed nothing; Stop the game ended it; Esc took the launcher back with the game still running; when the game closed the launcher was back with the session counted. A Steam-style start (a stand-in `steam` command that hands the game off and returns, the game's processes marked as Steam marks them) showed Starting until the game's process appeared and the launcher was back about 3 s after it was gone. Not checked: a real Steam, Lutris or Heroic game, a real controller, and bringing the launcher's window to the front through KWin when the game ends. |
|
||||
| Steam, Lutris, Heroic games started from the launcher | **Experimental** | Command lines are built and unit tested; no Steam, Lutris or Heroic on the test machines. Heroic (new): Epic and GOG games start through `xdg-open heroic://launch?appName=..&runner=..` (the format in Heroic's source), and the Flatpak Heroic's games are now found too. No Enhance for Lutris and Heroic games. Folders found on disk are not started directly: their button is **ADD** (see the Add a game row). |
|
||||
| Compare settings live (C), anti-aliasing (`--aa`) | **Experimental** | New. Run in the engine's own window on the GPU test machine (RTX 3090 shared with another job, **software OpenGL** for the display) on recorded Voidrunner footage, started with `--compare`: four anti-aliasing strips, frame generation Off against 2x (30 and 61 fps measured), and the upscaler strips fullscreen (RTX VSR shown as unavailable, with why); the overlay's Compare tab was opened with injected keys and seen. Anti-aliasing measured there at 720p, GPU, steady state: FXAA 0.53, SMAA-style 0.69, CAS 0.33 ms a frame on average. Upscaler and look times there are software OpenGL's and mean nothing. **Not run**: a real game (over a game, C stays the game's key), RTX VSR in a strip, the divider drag, Compare in clips, a GPU-rendered display, Windows. |
|
||||
@@ -133,8 +137,8 @@ A game's page has Play, an **Enhance** toggle and **Profile**. With Enhance on,
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
| Profile editor: monitor, resolution and refresh from xrandr | After Play: RIFE + FSR on the game's 720p window, full screen |
|
||||
|  |  |
|
||||
| A game's profile, Launch section (headless render; the modes were listed from xrandr in an earlier live run) | After Play: RIFE + FSR on the game's 720p window, full screen |
|
||||
|
||||
### Steam accounts
|
||||
|
||||
@@ -187,17 +191,30 @@ summit run custom:voidrunner --enhance # start the game and enhance its
|
||||
summit enhance window:Voidrunner # or: enhance a game that is already running, by window title
|
||||
```
|
||||
|
||||
### Launch profiles: defaults and per-game overrides
|
||||
### Settings, presets and a game's profile
|
||||
|
||||
Every setting a game launches with lives in a profile, and profiles are layered. **Settings > Default launch profile** (`~/.config/summit/profiles/default.toml`) holds the launcher's defaults; a game's **Profile** (its page) stores only what that game changes, so a new default reaches every game that has not set its own. In a game's editor each setting's first choice is "Default · <what the defaults say>", the settings the game sets itself have an accent mark, **Delete** puts one back to the default and **Follow defaults** clears them all. From the command line: `summit profile set default ...`, `summit profile set <id> ...`, `summit profile show <id>` (`--own` for the game's file alone) and `summit profile reset <id> [settings]`.
|
||||
|
||||
| Group | Settings |
|
||||
| | |
|
||||
|---|---|
|
||||
| Display | monitor (switched at launch and put back), resolution, refresh rate, **window mode** (as the game opens it, windowed, borderless window, fullscreen), focus |
|
||||
| Upscaling | Enhance on Play, upscaler (FSR, RTX VSR, bilinear, off), FSR sharpening, RTX VSR quality, fill (fit, zoom, stretch, panorama) |
|
||||
| Frame generation | on/off, model (RIFE 4.22 lite, 4.25 lite, 4.25, 4.26, NVIDIA VFG), VFG quality, motion detail, AI engine, Steady HUD, output rate |
|
||||
| Engine window | VSync, watermark |
|
||||
| Launch | launch arguments, environment variables (a game's keys win over the defaults') |
|
||||
|  |  |
|
||||
| Settings > Frame generation: the engine's own sections, help and choices | Search across every section |
|
||||
|  |  |
|
||||
| A game's profile: "Global" until the game sets its own (dotted) | Not used right now: greyed, with why |
|
||||
|  |  |
|
||||
| Presets say exactly what they set | Statistics (the two sessions are sample files, see below) |
|
||||
|
||||
These are headless renders of the real window (software renderer, invented demo library), each a settled frame: **animations are not shown and were only checked as static frames**. `docs/demo/launcher-ui-shots.sh` makes them again; all of them, in two themes each, are in `docs/media/launcher-ui/`.
|
||||
|
||||
**Settings** (the gear) has a section list on the left: **Launcher** (layout, theme, size, motion, the overlay key, the clips folder, NVIDIA's runtime), **Game defaults** (the launch settings every game starts with), then the engine's own sections, exactly as the engine lists them. The launcher has no copy of the engine's settings: it asks the engine, so a setting the engine gains shows up by itself, in its section, with its help. Each row shows its help, what it does to the picture and to speed, an Experimental tag where the engine says so, and is greyed out with the reason when it is not used now (FSR sharpening while the upscaler is RTX VSR). A dot marks a row that is not the default; **Delete** (Y on a pad) puts it back, and each section ends with a reset for the whole section. `/` searches every section. The focused row's whole help text, every choice with its line, and the default are in the panel on the right.
|
||||
|
||||
Where things are saved: the launcher's own settings in `~/.config/summit/ui.toml`, launch settings in `~/.config/summit/profiles/`, and the engine's global settings in the engine's own `settings.json` (the same file its in-game overlay writes), key by key. The two instant-replay lengths are in `ui.toml`, since Summit passes them on every start. Fullscreen is decided by **Window mode** once that is chosen, and the row says so.
|
||||
|
||||
**Presets** (Quality, Balanced, Performance, Lowest delay) set six engine settings and nothing else; the panel lists them. "Now:" names the preset in use, or **Custom** once any of the six differs. In a game's profile a preset is set for that game only.
|
||||
|
||||
**A game's Profile** (its page) is the same page for that game: **Launch** first (monitor and mode, window mode, focus, Enhance on Play, launch arguments, environment, the game's window), then the engine's sections, where every row starts as "Global · <the global value>" and becomes the game's own (dotted) when changed. Delete, or the first choice, gives it back to the global setting. From the command line: `summit profile set default ...`, `summit profile set <id> ...`, `summit profile show <id>` (`--own` for the game's file alone) and `summit profile reset <id> [settings]`; a game's engine settings are an `[engine]` table in its file, e.g. `overlay_style = "graphs"`.
|
||||
|
||||
**Statistics** (a game's page) shows the time played, the sessions Summit counted and their average length, and lists the session summaries the engine has written for the game: the duration, frame rates and settings a file holds, and every field of the selected one. The engine's summaries are being added on another branch; until an engine writes them the list says "No sessions yet". The two sessions in the picture above are sample files written by the screenshot script.
|
||||
|
||||
**Compare** (a game's page, Experimental) starts the game with Enhance and the engine's live comparison of one setting's values. It is disabled, with a note, while the engine has no `--compare`.
|
||||
|
||||
Window mode and focus are applied to the game's own window once it opens: on KDE Plasma by a KWin script (Wayland and X11), on other X11 desktops with `wmctrl`. A Wayland desktop other than Plasma gives Summit no way to place another program's window, so there the game keeps its own. With Enhance on, the window mode is the engine's picture (windowed over the game's window, or covering the monitor) and the game's window is only moved and focused. Profiles written by older versions are read as layers: values that only meant "nothing chosen" (`false`, `""`, `0`) follow the defaults, and `fullscreen = true` becomes `window_mode = "borderless"`.
|
||||
|
||||
@@ -338,8 +355,8 @@ Headless renders of every style with made-up numbers (labelled on the picture) c
|
||||
- **Home**: the focused game as a hero, over shelves: Jump back in (recently played), Pinned, Most played. Hours come from Steam's own playtime for Steam games and from Summit's sessions for everything else.
|
||||
- **Library**: every game, installed or not. Cover grid or dense list, filter, sort, search, **+ Add a game**.
|
||||
- **Unfiltered**: everything on this machine, grouped by source, with the reason each entry was detected.
|
||||
- **A game's page** (Enter on a game): stats, launch profile, detection reasons, Play, Pin.
|
||||
- **Settings** (the gear): layout, theme, interface size, animation speed and style, clip lengths and the clips folder, the in-game overlay's key, default upscaler and frame generation for `summit enhance`.
|
||||
- **A game's page** (Enter on a game): stats, launch profile, detection reasons, Play, Enhance, Compare (Experimental), Pin, Profile, Statistics, artwork.
|
||||
- **Settings** (the gear): the launcher's own settings, the game defaults, engine presets and every engine setting (see Settings, presets and a game's profile).
|
||||
- If a game started from the launcher fails (`summit run` ends with an error), a toast says why; the full output is in `~/.cache/summit/last-run.log`.
|
||||
|
||||
**While you play.** Play puts up a loading screen, then a small "now playing" card, and that is all the launcher is until the game is gone: no menus behind it to steer by accident. The game's window gets the keyboard once it opens (KDE Plasma, or X11 with wmctrl), and when the game closes the launcher comes back by itself, in front.
|
||||
@@ -355,12 +372,15 @@ Headless renders of every style with made-up numbers (labelled on the picture) c
|
||||
| Esc | B | Back, or Home |
|
||||
| Tab, Shift+Tab | RB, LB | Next, previous section |
|
||||
| P | X | Pin or unpin the focused game |
|
||||
| / | | Search the library |
|
||||
| / | | Search the library; in Settings or a profile, search the settings |
|
||||
| Left, Right | d-pad, left stick | In Settings or a profile: change the focused setting |
|
||||
| Delete | Y | Reset the focused setting (in a profile: use the global one) |
|
||||
| Page Up, Page Down | LB, RB in a profile | Previous, next section of the settings |
|
||||
| F11 | | Fullscreen |
|
||||
|
||||
The window uses Slint's OpenGL renderer (FemtoVG) and falls back to its software renderer. To add a theme, append one palette to `Theme.palettes` in `crates/summit-gui/ui/theme.slint`.
|
||||
|
||||
Headless renders, for screenshots and for checking the UI without a display: `SUMMIT_SHOT=<dir>` writes a PNG and exits. `SUMMIT_VIEW`, `SUMMIT_LAYOUT`, `SUMMIT_THEME`, `SUMMIT_DETAIL`, `SUMMIT_KEYS`, `SUMMIT_SIZE` and `SUMMIT_SCALE` choose what is drawn; they are described at the top of `crates/summit-gui/src/shot.rs`.
|
||||
Headless renders, for screenshots and for checking the UI without a display: `SUMMIT_SHOT=<dir>` writes a PNG and exits. `SUMMIT_VIEW`, `SUMMIT_LAYOUT`, `SUMMIT_THEME`, `SUMMIT_DETAIL`, `SUMMIT_KEYS`, `SUMMIT_SIZE` and `SUMMIT_SCALE` choose what is drawn, and `SUMMIT_SECTION`, `SUMMIT_SEARCH`, `SUMMIT_ZONE`, `SUMMIT_EDITOR`, `SUMMIT_STATS` and `SUMMIT_COMPARE` where the settings pane and a game's overlays are; they are described at the top of `crates/summit-gui/src/shot.rs`.
|
||||
|
||||
## Credits
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ enum Cmd {
|
||||
#[arg(long, default_value_t = 60)] wait: u32,
|
||||
/// With --enhance: hide the "summit - git.molberg.cloud/alex/summit" line in the corner
|
||||
#[arg(long)] no_watermark: bool,
|
||||
/// With --enhance: the engine's live comparison, `<setting>:<value>,<value>,...` (e.g. scaler:off,fsr).
|
||||
/// Experimental: needs an engine that has --compare.
|
||||
#[arg(long)] compare: Option<String>,
|
||||
/// The command hands the game to another program and returns at once (`steam steam://rungameid/N`).
|
||||
/// With --enhance, Summit then waits for the engine (the game's window) instead of the command.
|
||||
#[arg(long)] detached: bool,
|
||||
@@ -341,7 +344,9 @@ fn main() -> Result<()> {
|
||||
let missing = checks.iter().filter(|c| c.status == doctor::Status::Missing).count();
|
||||
if missing == 0 { println!("all set"); } else { println!("{missing} missing: see the lines marked MISS"); }
|
||||
}
|
||||
Cmd::Run { id, enhance, window, wait, no_watermark, detached, focus, title, mut cmd } => {
|
||||
Cmd::Run { id, enhance, window, wait, no_watermark, compare, detached, focus, title, mut cmd } => {
|
||||
let compare = compare.map(|c| engine::parse_compare(&c).map_err(|e| anyhow::anyhow!("--compare: {e}"))).transpose()?;
|
||||
anyhow::ensure!(compare.is_none() || enhance, "--compare needs --enhance: the comparison is drawn by the engine");
|
||||
// From here on a signal to summit stops the game and the engine and puts the display mode back.
|
||||
signals::install();
|
||||
let st = state::load();
|
||||
@@ -402,7 +407,7 @@ fn main() -> Result<()> {
|
||||
let status = if let (Some(eng), true) = (&eng, remote_play) {
|
||||
// The engine first: it has to see the stream start (the codec header comes once, as the stream's
|
||||
// first packet), so chiaki-ng is started once the engine says it is waiting on the frame tap.
|
||||
let live = engine::Live { wait_secs: 0, watermark: if no_watermark { Some(false) } else { None } };
|
||||
let live = engine::Live { wait_secs: 0, watermark: if no_watermark { Some(false) } else { None }, compare: compare.clone() };
|
||||
let mut args = engine::plan(eng, &engine::Source::Ps5, &p, true, None, None);
|
||||
args.extend(engine::live_args(&live));
|
||||
{
|
||||
@@ -441,7 +446,7 @@ fn main() -> Result<()> {
|
||||
} else if let Some(eng) = eng {
|
||||
let mut game = child.spawn().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))?;
|
||||
placer = start_placer(s, d, &p, true, place_target(&id, window.as_deref(), game.id()), wait);
|
||||
let live = engine::Live { wait_secs: wait, watermark: if no_watermark { Some(false) } else { None } };
|
||||
let live = engine::Live { wait_secs: wait, watermark: if no_watermark { Some(false) } else { None }, compare: compare.clone() };
|
||||
let mut args = engine::run_enhance_plan(&eng, game.id(), window.as_deref(), &p, &live);
|
||||
{
|
||||
let ui = summit_core::ui::load();
|
||||
|
||||
@@ -87,9 +87,9 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option
|
||||
if let Some(v) = p.aa.as_deref().filter(|v| crate::profile::AA.contains(v)) { a.push(opt("aa", v)); }
|
||||
if display {
|
||||
a.push("--display".into());
|
||||
// the frame multiplier N: the engine shows N frames for each real one of a 30 fps game, 30 x N fps
|
||||
let hz = 30 * u32::from(p.multiplier().unwrap_or(2));
|
||||
a.push("--hz".into()); a.push(hz.to_string());
|
||||
// the frame multiplier N: the engine shows N frames for each real one of a 30 fps game, 30 x N fps.
|
||||
// Not set in the profile: no flag, so the engine's own saved Frame multiplier is used (2x unless changed).
|
||||
if let Some(m) = p.multiplier() { a.push("--hz".into()); a.push((30 * u32::from(m)).to_string()); }
|
||||
if let Some(g) = p.game_fps.as_deref().filter(|g| crate::profile::GAME_FPS.contains(g)) { a.push(opt("game-fps", g)); }
|
||||
if let Some((w, h)) = p.output_res.as_deref().and_then(crate::profile::parse_res) { a.push(format!("--output-res={w}x{h}")); }
|
||||
match p.window_mode.as_str() {
|
||||
@@ -101,6 +101,11 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option
|
||||
if let Some(f) = &p.fill { a.push(opt("fill", f)); }
|
||||
if let Some(v) = p.vsync { a.push(if v { "--vsync" } else { "--no-vsync" }.into()); }
|
||||
} else if let Some(o) = out { a.push(opt("out", &o.to_string_lossy())); }
|
||||
// Engine settings by key (the profile's `engine` table): `--set=KEY=<JSON>`, read after the flags above, so
|
||||
// these win. One the engine does not know (an older engine) is said in its log and left out.
|
||||
for (k, v) in &p.engine {
|
||||
if k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !k.is_empty() { a.push(format!("--set={k}={}", crate::registry::from_toml(v))); }
|
||||
}
|
||||
if let Some(t) = max_ticks { a.push("--max-ticks".into()); a.push(t.to_string()); }
|
||||
a
|
||||
}
|
||||
@@ -180,14 +185,35 @@ pub struct Live {
|
||||
pub wait_secs: u32,
|
||||
/// The "summit - git.molberg.cloud/alex/summit" line in a corner. None leaves the engine's saved setting (on by default).
|
||||
pub watermark: Option<bool>,
|
||||
/// The engine's live comparison: `<dimension>:<v1>,<v2>,...` ([`parse_compare`]), passed on as `--compare`.
|
||||
/// None: no comparison. Experimental: the engine's side of this is on another branch.
|
||||
pub compare: Option<String>,
|
||||
}
|
||||
impl Default for Live { fn default() -> Self { Self { wait_secs: 60, watermark: None, compare: None } } }
|
||||
|
||||
/// Check a comparison as the engine's `--compare` takes it: `<dimension>:<v1>,<v2>,...`, a setting's key (letters,
|
||||
/// digits, `_`, `-`) and at least two values. Returns it trimmed, with no spaces around the values.
|
||||
pub fn parse_compare(s: &str) -> Result<String, String> {
|
||||
let how = "a comparison is <setting>:<value>,<value>,... (e.g. scaler:off,fsr)";
|
||||
let (dim, values) = s.split_once(':').ok_or(how)?;
|
||||
let dim = dim.trim();
|
||||
if !dim.starts_with(|c: char| c.is_ascii_alphanumeric()) || !dim.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') { return Err(how.into()); }
|
||||
let v: Vec<&str> = values.split(',').map(str::trim).collect();
|
||||
if v.len() < 2 || v.iter().any(|x| x.is_empty()) { return Err(format!("{how}: at least two values")); }
|
||||
Ok(format!("{dim}:{}", v.join(",")))
|
||||
}
|
||||
|
||||
/// Whether this engine has the live comparison (its run.py knows `--compare`): the launcher only offers it then.
|
||||
pub fn has_compare(engine: &Path) -> bool {
|
||||
std::fs::read_to_string(engine.join("run.py")).is_ok_and(|t| t.contains("\"--compare\""))
|
||||
}
|
||||
impl Default for Live { fn default() -> Self { Self { wait_secs: 60, watermark: None } } }
|
||||
|
||||
/// Extra engine flags for a live window, after `plan()`'s.
|
||||
pub fn live_args(l: &Live) -> Vec<String> {
|
||||
let mut a = vec![];
|
||||
if l.wait_secs > 0 { a.push("--window-wait".to_string()); a.push(l.wait_secs.to_string()); }
|
||||
if let Some(w) = l.watermark { a.push("--watermark".into()); a.push(if w { "on" } else { "off" }.into()); }
|
||||
if let Some(c) = l.compare.as_deref().and_then(|c| parse_compare(c).ok()) { a.push(format!("--compare={c}")); }
|
||||
a
|
||||
}
|
||||
|
||||
@@ -404,6 +430,9 @@ mod tests {
|
||||
#[test] fn ps5_display_plan() {
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &p(), true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --model=4.25 --scaler vsr --display --hz 120 --fullscreen --monitor=HDMI-A-1");
|
||||
// no multiplier in the profile: no --hz, so the engine's saved Frame multiplier counts
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &Profile::default(), true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --display");
|
||||
}
|
||||
#[test] fn file_to_out_plan() {
|
||||
// upscaler "none" (the editor's Off): the engine shows the picture at its own size
|
||||
@@ -426,7 +455,7 @@ mod tests {
|
||||
#[test] fn window_plan_names_the_source() {
|
||||
let pr = Profile { framegen: "rife".into(), upscaler: "fsr".into(), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("Voidrunner".into()), &pr, true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --display --hz 60");
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --display");
|
||||
}
|
||||
#[test] fn parse_source_kinds() {
|
||||
assert_eq!(parse_source("ps5"), Ok(Source::Ps5));
|
||||
@@ -442,7 +471,7 @@ mod tests {
|
||||
#[test] fn anti_aliasing_goes_through_when_the_profile_has_one() {
|
||||
let pr = Profile { upscaler: "fsr".into(), aa: Some("smaa".into()), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("Voidrunner".into()), &pr, true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --aa=smaa --display --hz 60");
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --aa=smaa --display"); // (no --hz: the profile sets no multiplier, see ap/launcher-ui)
|
||||
for aa in [None, Some("dlaa".to_string())] { // unset, or a value the engine has no such choice for: left out
|
||||
let pr = Profile { aa, ..Default::default() };
|
||||
assert!(!plan(Path::new("/e"), &Source::Window("x".into()), &pr, true, None, None).iter().any(|s| s.starts_with("--aa")));
|
||||
@@ -456,12 +485,12 @@ mod tests {
|
||||
}
|
||||
#[test] fn run_enhance_window_override_and_watermark_off() {
|
||||
let pr = Profile { framegen: "none".into(), upscaler: "fsr".into(), ..Default::default() };
|
||||
let a = run_enhance_plan(Path::new("/e"), 1, Some("class:steam_app_620"), &pr, &Live { wait_secs: 0, watermark: Some(false) });
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=class:steam_app_620 --off --scaler fsr --display --hz 60 --watermark off");
|
||||
let a = run_enhance_plan(Path::new("/e"), 1, Some("class:steam_app_620"), &pr, &Live { wait_secs: 0, watermark: Some(false), compare: None });
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=class:steam_app_620 --off --scaler fsr --display --watermark off");
|
||||
}
|
||||
#[test] fn live_args_leave_the_saved_watermark_alone_by_default() {
|
||||
assert_eq!(live_args(&Live::default()).join(" "), "--window-wait 60");
|
||||
assert_eq!(live_args(&Live { wait_secs: 5, watermark: Some(true) }).join(" "), "--window-wait 5 --watermark on");
|
||||
assert_eq!(live_args(&Live { wait_secs: 5, watermark: Some(true), compare: None }).join(" "), "--window-wait 5 --watermark on");
|
||||
}
|
||||
#[test] fn extra_args_split_on_spaces() {
|
||||
assert_eq!(extra_args(Some(" --no-graph --fp32 ")), vec!["--no-graph", "--fp32"]);
|
||||
@@ -584,7 +613,7 @@ mod tests {
|
||||
let pr = Profile { framegen: "rife".into(), model: Some("vfg".into()), vfg_quality: Some("high".into()), motion: Some("half".into()), ai_engine: Some("trt".into()),
|
||||
steady_hud: Some(true), upscaler: "fsr".into(), fsr_sharpness: Some(0.25), vsr_quality: Some(4), window_mode: "windowed".into(), fill: Some("zoom".into()), vsync: Some(false), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --model=vfg --vfg-quality=high --scale=0.5 --engine=trt --steady-hud --scaler fsr --fsr-sharpness=0.25 --display --hz 60 --no-fullscreen --fill=zoom --no-vsync");
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --model=vfg --vfg-quality=high --scale=0.5 --engine=trt --steady-hud --scaler fsr --fsr-sharpness=0.25 --display --no-fullscreen --fill=zoom --no-vsync");
|
||||
// VSR quality only with VSR, VFG quality only with VFG
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &Profile { upscaler: "rtx-vsr".into(), vsr_quality: Some(3), vfg_quality: Some("low".into()), ..Default::default() }, true, None, None);
|
||||
assert!(a.contains(&"--vsr-quality=3".to_string()) && !a.iter().any(|x| x.starts_with("--vfg-quality")), "{a:?}");
|
||||
@@ -596,6 +625,39 @@ mod tests {
|
||||
assert!(run_enhance_plan(Path::new("/e"), 1, None, &w, &Live { watermark: Some(true), ..Live::default() }).ends_with(&["--watermark".to_string(), "on".to_string()]));
|
||||
}
|
||||
#[test] fn dlss_is_not_an_engine_scaler() { assert_eq!(scaler_arg("dlss"), None); }
|
||||
#[test] fn the_engine_table_goes_as_set_flags_after_the_named_ones() {
|
||||
let mut pr = Profile { upscaler: "fsr".into(), ..Default::default() };
|
||||
pr.engine.insert("overlay_style".into(), toml::Value::String("graphs".into()));
|
||||
pr.engine.insert("hz".into(), toml::Value::Integer(120));
|
||||
pr.engine.insert("interp".into(), toml::Value::Boolean(false));
|
||||
pr.engine.insert("fsr_sharpness".into(), toml::Value::Float(0.25));
|
||||
pr.engine.insert("bad key --x".into(), toml::Value::Integer(1));
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --scaler fsr --display --set=fsr_sharpness=0.25 --set=hz=120 --set=interp=false --set=overlay_style=\"graphs\"");
|
||||
// a value can never become another option: it stays inside its --set=
|
||||
pr.engine.clear();
|
||||
pr.engine.insert("look".into(), toml::Value::String("--out /etc/x".into()));
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None);
|
||||
assert_eq!(a.last().unwrap(), "--set=look=\"--out /etc/x\"");
|
||||
}
|
||||
#[test] fn compare_is_passed_through_only_when_asked_and_well_formed() {
|
||||
assert_eq!(live_args(&Live::default()).join(" "), "--window-wait 60"); // None: nothing
|
||||
let l = Live { compare: Some(" scaler : off, fsr ,vsr ".into()), ..Live::default() };
|
||||
assert_eq!(live_args(&l).join(" "), "--window-wait 60 --compare=scaler:off,fsr,vsr");
|
||||
let a = run_enhance_plan(Path::new("/e"), 7, None, &Profile::default(), &Live { compare: Some("hz:60,120".into()), ..Live::default() });
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=pid:7 --display --window-wait 60 --compare=hz:60,120");
|
||||
assert_eq!(parse_compare("fsr_sharpness:0,0.5,2").as_deref(), Ok("fsr_sharpness:0,0.5,2"));
|
||||
for bad in ["scaler", "scaler:fsr", ":a,b", "scaler:a,,b", "sc aler:a,b", "--x:a,b", ""] { assert!(parse_compare(bad).is_err(), "{bad}"); }
|
||||
// one that is not well formed is never passed on
|
||||
assert_eq!(live_args(&Live { compare: Some("nonsense".into()), ..Live::default() }).join(" "), "--window-wait 60");
|
||||
let d = std::env::temp_dir().join(format!("summit-has-compare-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::write(d.join("run.py"), "ap.add_argument(\"--hz\")\n").unwrap();
|
||||
assert!(!has_compare(&d));
|
||||
std::fs::write(d.join("run.py"), "ap.add_argument(\"--compare\", metavar=\"SPEC\")\n").unwrap();
|
||||
assert!(has_compare(&d));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
#[test] fn framegen_none_turns_interp_off() {
|
||||
let pr = Profile { framegen: "none".into(), ..Default::default() };
|
||||
assert!(plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None).contains(&"--off".to_string()));
|
||||
@@ -631,7 +693,7 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn game_frame_rate_and_output_resolution_reach_the_engine() {
|
||||
let p = Profile { framegen: "rife".into(), game_fps: Some("60".into()), output_res: Some("2560 x 1440".into()), ..Default::default() };
|
||||
let p = Profile { framegen: "rife".into(), framegen_multiplier: 2, game_fps: Some("60".into()), output_res: Some("2560 x 1440".into()), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("pid:1".into()), &p, true, None, None).join(" ");
|
||||
assert!(a.contains("--hz 60 --game-fps=60 --output-res=2560x1440"), "{a}");
|
||||
let p = Profile { game_fps: Some("120".into()), output_res: Some("huge".into()), ..Default::default() };
|
||||
|
||||
@@ -179,6 +179,15 @@ pub fn with_focus(mut argv: Vec<String>) -> Vec<String> {
|
||||
argv
|
||||
}
|
||||
|
||||
/// `summit run ... --enhance` with the engine's live comparison on (`<setting>:<v1>,<v2>,...`). Only a plan that goes
|
||||
/// through `summit run` with Enhance can carry it; any other is returned as it is.
|
||||
pub fn with_compare(mut argv: Vec<String>, compare: &str) -> Vec<String> {
|
||||
let head = |a: &str| argv.iter().take_while(|x| x.as_str() != "--").any(|x| x == a);
|
||||
let ours = argv.len() >= 3 && argv[1] == "run" && head("--enhance") && !argv.iter().take_while(|x| x.as_str() != "--").any(|x| x.starts_with("--compare"));
|
||||
if ours { argv.insert(3, format!("--compare={compare}")); }
|
||||
argv
|
||||
}
|
||||
|
||||
/// True when Play would install rather than start (owned Steam game that is not on disk).
|
||||
pub fn is_install(e: &Entry) -> bool { e.source == Source::Steam && !e.installed && e.steam_app_id.is_some() }
|
||||
|
||||
@@ -204,6 +213,14 @@ mod tests {
|
||||
// a game whose own arguments say --focus still gets ours
|
||||
let own = vec!["/s".to_string(), "run".into(), "custom:x".into(), "--".into(), "/g".into(), "--focus".into()];
|
||||
assert_eq!(with_focus(own)[3], "--focus");
|
||||
// the comparison: only on a plan that runs the engine, once, and before the game's command
|
||||
let enh: Vec<String> = ["/b/summit", "run", "steam:1", "--enhance", "--", "steam", "--compare=x"].iter().map(|s| s.to_string()).collect();
|
||||
let c = with_compare(enh.clone(), "scaler:off,fsr");
|
||||
assert_eq!(c[3], "--compare=scaler:off,fsr");
|
||||
assert_eq!(with_compare(c.clone(), "hz:60,120"), c);
|
||||
let no_enh: Vec<String> = ["/b/summit", "run", "steam:1", "--", "steam"].iter().map(|s| s.to_string()).collect();
|
||||
assert_eq!(with_compare(no_enh.clone(), "scaler:off,fsr"), no_enh);
|
||||
assert_eq!(with_compare(plain.clone(), "scaler:off,fsr"), plain);
|
||||
}
|
||||
#[test]
|
||||
fn steam_installed_goes_through_summit_run() {
|
||||
|
||||
@@ -10,9 +10,12 @@ pub mod launch;
|
||||
pub mod lutris;
|
||||
pub mod model;
|
||||
pub mod names;
|
||||
pub mod presets;
|
||||
pub mod profile;
|
||||
pub mod registry;
|
||||
pub mod running;
|
||||
pub mod scan;
|
||||
pub mod sessions;
|
||||
pub mod sgdb;
|
||||
pub mod shortcuts;
|
||||
pub mod signals;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Engine presets: a few named sets of engine settings. This table is the only place they are defined; the
|
||||
//! launcher's Settings page, a game's profile and `summit preset` all read it.
|
||||
//!
|
||||
//! A preset only sets the keys listed here and leaves everything else alone. Every preset sets the same keys, so
|
||||
//! exactly one of them (or none: "Custom") matches at any time. The descriptions say what changes; the numbers in
|
||||
//! them are the engine's own notes (framegen/settings.py `impact`, measured on the engine author's PC), not
|
||||
//! something measured for these presets.
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum V { B(bool), I(i64), S(&'static str) }
|
||||
impl V { pub fn json(self) -> Value { match self { V::B(b) => Value::Bool(b), V::I(i) => Value::from(i), V::S(s) => Value::String(s.into()) } } }
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Preset {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
/// One line: who it is for.
|
||||
pub summary: &'static str,
|
||||
/// What it changes and what that costs, in plain words.
|
||||
pub detail: &'static str,
|
||||
/// Registry key -> value. The same keys in every preset, in the same order.
|
||||
pub set: &'static [(&'static str, V)],
|
||||
}
|
||||
|
||||
impl Preset {
|
||||
pub fn values(&self) -> Vec<(&'static str, Value)> { self.set.iter().map(|(k, v)| (*k, v.json())).collect() }
|
||||
}
|
||||
|
||||
pub const PRESETS: &[Preset] = &[
|
||||
Preset {
|
||||
id: "quality", name: "Quality",
|
||||
summary: "The best picture the engine makes, for a card with headroom.",
|
||||
detail: "Frame generation on at 2x with motion detail Full (sharpest on fast detail, the slowest), FSR 1 upscaling straight to the screen's size, VSync on (no tear lines; up to one refresh more delay).",
|
||||
set: &[("interp", V::B(true)), ("hz", V::I(60)), ("motion", V::S("full")), ("scaler", V::S("fsr")), ("output_res", V::S("screen")), ("vsync", V::B(true))],
|
||||
},
|
||||
Preset {
|
||||
id: "balanced", name: "Balanced",
|
||||
summary: "The engine's own defaults.",
|
||||
detail: "Frame generation on at 2x with motion detail Auto (Full, dropping to Half only at high frame rates or big captures), FSR 1 upscaling to the screen's size, VSync off (lowest delay; fast turns can tear without G-Sync or FreeSync).",
|
||||
set: &[("interp", V::B(true)), ("hz", V::I(60)), ("motion", V::S("auto")), ("scaler", V::S("fsr")), ("output_res", V::S("screen")), ("vsync", V::B(false))],
|
||||
},
|
||||
Preset {
|
||||
id: "performance", name: "Performance",
|
||||
summary: "The lightest for the graphics card, for when frames get left out.",
|
||||
detail: "Frame generation on at 2x with motion detail Half (about 40% less time per AI frame, a little softer on small fast details), upscaling to 1080p and stretching that to the screen (softer on a 1440p or 4K screen), VSync off.",
|
||||
set: &[("interp", V::B(true)), ("hz", V::I(60)), ("motion", V::S("half")), ("scaler", V::S("fsr")), ("output_res", V::S("1920x1080")), ("vsync", V::B(false))],
|
||||
},
|
||||
Preset {
|
||||
id: "lowest-delay", name: "Lowest delay",
|
||||
summary: "Upscaling only: nothing that waits for the next frame.",
|
||||
detail: "Frame generation off, so the game's frames are shown as they come (generation is what adds about 20 to 40 ms), FSR 1 upscaling to the screen's size, VSync off. Motion is only as smooth as the game itself.",
|
||||
set: &[("interp", V::B(false)), ("hz", V::I(60)), ("motion", V::S("auto")), ("scaler", V::S("fsr")), ("output_res", V::S("screen")), ("vsync", V::B(false))],
|
||||
},
|
||||
];
|
||||
|
||||
/// The keys presets set (the same for each).
|
||||
pub fn keys() -> Vec<&'static str> { PRESETS[0].set.iter().map(|(k, _)| *k).collect() }
|
||||
|
||||
pub fn by_id(id: &str) -> Option<&'static Preset> { PRESETS.iter().find(|p| p.id.eq_ignore_ascii_case(id) || p.name.eq_ignore_ascii_case(id)) }
|
||||
|
||||
/// The preset the current values are, or None ("Custom"). `value_of` gives the value in use for a key.
|
||||
pub fn current(value_of: &dyn Fn(&str) -> Value) -> Option<&'static Preset> {
|
||||
PRESETS.iter().find(|p| p.set.iter().all(|(k, v)| crate::registry::same(&value_of(k), &v.json())))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn every_preset_sets_the_same_keys_and_no_two_are_alike() {
|
||||
let k = keys();
|
||||
for p in PRESETS {
|
||||
assert_eq!(p.set.iter().map(|(k, _)| *k).collect::<Vec<_>>(), k, "{}", p.id);
|
||||
assert!(!p.summary.is_empty() && !p.detail.is_empty());
|
||||
}
|
||||
for (i, a) in PRESETS.iter().enumerate() { for b in &PRESETS[i + 1..] { assert_ne!(a.set, b.set, "{} and {}", a.id, b.id); } }
|
||||
assert_eq!(by_id("Lowest delay").map(|p| p.id), Some("lowest-delay"));
|
||||
assert_eq!(by_id("PERFORMANCE").map(|p| p.id), Some("performance"));
|
||||
assert!(by_id("ultra").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_preset_is_custom_once_a_value_differs() {
|
||||
let mut v: BTreeMap<&str, Value> = by_id("quality").unwrap().values().into_iter().collect();
|
||||
let look = |v: &BTreeMap<&str, Value>| current(&|k| v.get(k).cloned().unwrap_or(Value::Null)).map(|p| p.id);
|
||||
assert_eq!(look(&v), Some("quality"));
|
||||
v.insert("vsync", Value::Bool(false));
|
||||
assert_eq!(look(&v), None);
|
||||
v.insert("motion", Value::String("auto".into()));
|
||||
assert_eq!(look(&v), Some("balanced"));
|
||||
v.insert("hz", Value::from(120));
|
||||
assert_eq!(look(&v), None);
|
||||
// the settings file may hold 60.0 for 60
|
||||
v.insert("hz", serde_json::json!(60.0));
|
||||
assert_eq!(look(&v), Some("balanced"));
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,9 @@ pub struct Profile {
|
||||
/// Which window Enhance takes, in the engine's `--window` form (`class:NAME`, part of the title, `dir:FOLDER`,
|
||||
/// alternatives split by "|"). None: Summit works it out (launch::window_query), and asks when it can't.
|
||||
pub window: Option<String>,
|
||||
/// Engine settings by the engine's own key (engine/framegen/settings.py), for anything the fields above do not
|
||||
/// name: passed as `--set KEY=VALUE`, and winning over them. Empty: the engine's saved settings.
|
||||
pub engine: BTreeMap<String, toml::Value>,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
@@ -145,6 +148,8 @@ pub struct Layer {
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub game_fps: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub output_res: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub aa: Option<String>,
|
||||
/// `[engine]`: engine settings by the engine's key (the launcher's settings rows write here). See [`Profile::engine`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub engine: Option<BTreeMap<String, toml::Value>>,
|
||||
/// Files from before layers: `fullscreen = true` is `window_mode = "borderless"` (the engine's picture over the
|
||||
/// whole monitor, which is what it did). Read, never written.
|
||||
#[serde(skip_serializing)] pub fullscreen: Option<bool>,
|
||||
@@ -155,8 +160,11 @@ pub const KEYS: &[&str] = &[
|
||||
"monitor", "width", "height", "refresh_hz", "window_mode", "focus", "enhance", "upscaler", "fsr_sharpness",
|
||||
"vsr_quality", "framegen", "framegen_multiplier", "target_hz", "model", "vfg_quality", "motion", "ai_engine",
|
||||
"steady_hud", "fill", "vsync", "watermark", "launch_args", "env", "window", "game_fps", "output_res",
|
||||
"aa",
|
||||
"aa", "engine",
|
||||
];
|
||||
/// The engine's setting keys that a named profile setting also decides (crate::registry::named_for).
|
||||
const NAMED_ENGINE_KEYS: &[&str] = &["interp", "hz", "game_fps", "output_res", "model", "vfg_quality", "motion", "engine", "steady_hud",
|
||||
"scaler", "fsr_sharpness", "vsr_quality", "fill", "vsync", "watermark", "aa"];
|
||||
|
||||
/// The engine's anti-aliasing choices (`--aa`, framegen/aa.py).
|
||||
pub const AA: &[&str] = &["off", "fxaa", "smaa", "cas"];
|
||||
@@ -215,6 +223,10 @@ impl Layer {
|
||||
if let Some(v) = &self.game_fps { p.game_fps = text(v); }
|
||||
if let Some(v) = &self.output_res { p.output_res = text(v).filter(|r| r != "screen"); }
|
||||
if let Some(v) = &self.aa { p.aa = text(v); }
|
||||
// A later layer wins whichever way it says it: a named setting here replaces the same engine key from the
|
||||
// layer below, and this layer's own engine table goes on top.
|
||||
for k in NAMED_ENGINE_KEYS { if crate::registry::named_for(k).iter().any(|n| self.has(n)) { p.engine.remove(*k); } }
|
||||
if let Some(v) = &self.engine { for (k, val) in v { p.engine.insert(k.clone(), val.clone()); } }
|
||||
}
|
||||
|
||||
/// Whether this layer sets `key` (one of [`KEYS`]).
|
||||
@@ -231,6 +243,7 @@ impl Layer {
|
||||
"env" => self.env.is_some(), "window" => self.window.is_some(),
|
||||
"game_fps" => self.game_fps.is_some(), "output_res" => self.output_res.is_some(),
|
||||
"aa" => self.aa.is_some(),
|
||||
"engine" => self.engine.as_ref().is_some_and(|m| !m.is_empty()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -250,6 +263,7 @@ impl Layer {
|
||||
"launch_args" => self.launch_args = None, "env" => self.env = None, "window" => self.window = None,
|
||||
"game_fps" => self.game_fps = None, "output_res" => self.output_res = None,
|
||||
"aa" => self.aa = None,
|
||||
"engine" => self.engine = None,
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
@@ -455,4 +469,25 @@ mod tests {
|
||||
let old = Layer { framegen_multiplier: Some(2), target_hz: Some(120), ..Default::default() };
|
||||
assert_eq!(resolve(&[&old]).multiplier(), Some(4));
|
||||
}
|
||||
#[test]
|
||||
fn the_engine_table_layers_like_everything_else() {
|
||||
let t = |s: &str| toml::Value::String(s.into());
|
||||
let d = parse_layer("version = 2\nupscaler = \"fsr\"\n\n[engine]\noverlay_style = \"graphs\"\nscaler = \"vsr\"\nhz = 90\n").unwrap();
|
||||
assert_eq!(d.engine.as_ref().unwrap().get("hz"), Some(&toml::Value::Integer(90)));
|
||||
let g = Layer { engine: Some([("overlay_style".to_string(), t("minimal")), ("vsync".to_string(), toml::Value::Boolean(true))].into()), ..Default::default() };
|
||||
let p = resolve(&[&d, &g]);
|
||||
assert_eq!(p.engine.get("overlay_style"), Some(&t("minimal"))); // the game's own
|
||||
assert_eq!(p.engine.get("scaler"), Some(&t("vsr"))); // the defaults'
|
||||
assert_eq!(p.engine.get("vsync"), Some(&toml::Value::Boolean(true)));
|
||||
// a game that still names the upscaler the older way wins over the defaults' engine table
|
||||
let old = Layer { upscaler: Some("bilinear".into()), ..Default::default() };
|
||||
let p = resolve(&[&d, &old]);
|
||||
assert!(!p.engine.contains_key("scaler") && p.upscaler == "bilinear");
|
||||
assert!(g.has("engine") && !Layer::default().has("engine"));
|
||||
let mut g2 = g.clone();
|
||||
assert!(g2.unset("engine") && g2.is_empty());
|
||||
// written and read back
|
||||
let text = toml::to_string_pretty(&Layer { version: Some(LAYER_VERSION), monitor: Some("DP-1".into()), ..g.clone() }).unwrap();
|
||||
assert_eq!(parse_layer(&text).unwrap().engine, g.engine, "{text}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
//! The engine's settings registry, as the launcher reads it: `python -m framegen.settings` prints every setting
|
||||
//! (engine/framegen/settings.py SPECS) as JSON, so the launcher keeps no copy of the labels, choices or help.
|
||||
//! Parsed leniently: a field that is missing or of another type than expected is left empty, a setting without a key
|
||||
//! is skipped, and a setting this version has never heard of is shown like any other.
|
||||
//!
|
||||
//! Also here: the saved values (the engine's settings.json, read and written key by key so anything else in the
|
||||
//! file is kept) and how a launch profile's settings map onto the registry's keys ([`forced`]).
|
||||
use crate::profile::{Layer, Profile};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Choice { pub value: Value, pub name: String, pub hint: String }
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Spec {
|
||||
pub key: String,
|
||||
pub label: String,
|
||||
/// Section ("" in the JSON becomes "Other").
|
||||
pub group: String,
|
||||
/// Heading inside the section ("" for none).
|
||||
pub sub: String,
|
||||
pub help: String,
|
||||
pub default: Value,
|
||||
/// Applies at once; false: at the next start.
|
||||
pub live: bool,
|
||||
/// Written to the settings file; false: one session only, so the launcher cannot set it.
|
||||
pub saved: bool,
|
||||
pub later: String,
|
||||
pub quick: bool,
|
||||
/// "picture" and "speed" lines (any other name the engine adds is kept and shown too).
|
||||
pub impact: Vec<(String, String)>,
|
||||
pub experimental: bool,
|
||||
/// Only used with these sources (empty: all).
|
||||
pub sources: Vec<String>,
|
||||
/// Source kind -> why it is not used there ("" for any other source).
|
||||
pub elsewhere: BTreeMap<String, String>,
|
||||
/// Only used while setting `.0` has one of the values `.1`.
|
||||
pub applies: Option<(String, Vec<Value>)>,
|
||||
pub choices: Vec<Choice>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Registry {
|
||||
/// The engine's settings file.
|
||||
pub path: PathBuf,
|
||||
/// The PC the numbers in the impact lines were measured on.
|
||||
pub impact_pc: String,
|
||||
pub specs: Vec<Spec>,
|
||||
}
|
||||
|
||||
/// Two JSON values that mean the same choice: numbers by value (1 and 1.0), everything else exactly.
|
||||
pub fn same(a: &Value, b: &Value) -> bool {
|
||||
match (a.as_f64(), b.as_f64()) { (Some(x), Some(y)) => (x - y).abs() < 1e-9, _ => a == b }
|
||||
}
|
||||
|
||||
/// A value as text, for a choice the registry gives no name for.
|
||||
pub fn plain(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(true) => "On".into(), Value::Bool(false) => "Off".into(),
|
||||
Value::Null => "Not set".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn text(v: Option<&Value>) -> String { v.and_then(Value::as_str).unwrap_or_default().to_string() }
|
||||
fn flag(v: Option<&Value>, default: bool) -> bool { v.and_then(Value::as_bool).unwrap_or(default) }
|
||||
|
||||
impl Spec {
|
||||
fn parse(v: &Value) -> Option<Spec> {
|
||||
let o = v.as_object()?;
|
||||
let key = text(o.get("key"));
|
||||
if key.is_empty() { return None; }
|
||||
let label = match text(o.get("label")) { l if l.is_empty() => key.clone(), l => l };
|
||||
let group = match text(o.get("group")) { g if g.trim().is_empty() => "Other".to_string(), g => g };
|
||||
// choices: [{value, name, hint}], or bare values
|
||||
let choices: Vec<Choice> = o.get("choices").and_then(Value::as_array).map(|a| a.iter().map(|c| match c.as_object() {
|
||||
Some(c) if c.contains_key("value") => {
|
||||
let value = c.get("value").cloned().unwrap_or(Value::Null);
|
||||
let name = match text(c.get("name")) { n if n.is_empty() => plain(&value), n => n };
|
||||
Choice { name, hint: text(c.get("hint")), value }
|
||||
}
|
||||
_ => Choice { name: plain(c), hint: String::new(), value: c.clone() },
|
||||
}).collect()).unwrap_or_default();
|
||||
let mut impact: Vec<(String, String)> = o.get("impact").and_then(Value::as_object)
|
||||
.map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).filter(|(_, v)| !v.is_empty()).collect()).unwrap_or_default();
|
||||
impact.sort_by_key(|(k, _)| match k.as_str() { "picture" => 0, "speed" => 1, _ => 2 });
|
||||
let applies = o.get("applies").and_then(Value::as_object).and_then(|a| {
|
||||
let k = text(a.get("key"));
|
||||
let vals = a.get("values").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
(!k.is_empty()).then_some((k, vals))
|
||||
});
|
||||
Some(Spec {
|
||||
key, label, group, sub: text(o.get("sub")), help: text(o.get("help")), default: o.get("default").cloned().unwrap_or(Value::Null),
|
||||
live: flag(o.get("live"), true), saved: flag(o.get("saved"), true), later: text(o.get("later")), quick: flag(o.get("quick"), false),
|
||||
impact, experimental: flag(o.get("experimental"), false),
|
||||
sources: o.get("sources").and_then(Value::as_array).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default(),
|
||||
elsewhere: o.get("elsewhere").and_then(Value::as_object).map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default(),
|
||||
applies, choices,
|
||||
})
|
||||
}
|
||||
|
||||
/// The index of `v` among the choices.
|
||||
pub fn position(&self, v: &Value) -> Option<usize> { self.choices.iter().position(|c| same(&c.value, v)) }
|
||||
|
||||
/// What a value is called: the choice's name, else what the engine's own naming gives for a custom value (a
|
||||
/// frame multiplier, an output size), else the value as text.
|
||||
pub fn name_of(&self, v: &Value) -> String {
|
||||
if let Some(i) = self.position(v) { return self.choices[i].name.clone(); }
|
||||
match (self.key.as_str(), v) {
|
||||
("hz", Value::Number(n)) if n.as_u64().is_some_and(|hz| hz % 30 == 0 && hz > 0) => format!("{}x", n.as_u64().unwrap_or(0) / 30),
|
||||
("output_res", Value::String(s)) => crate::profile::parse_res(s).map(|(w, h)| format!("{w} x {h}")).unwrap_or_else(|| s.clone()),
|
||||
_ => plain(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the setting is not used with these values (the setting it depends on has another value), or None.
|
||||
pub fn unused_now(&self, reg: &Registry, value_of: &dyn Fn(&str) -> Value) -> Option<String> {
|
||||
let (key, values) = self.applies.as_ref()?;
|
||||
let cur = value_of(key);
|
||||
if values.iter().any(|v| same(v, &cur)) { return None; }
|
||||
let (label, names) = match reg.get(key) {
|
||||
Some(dep) => (dep.label.clone(), values.iter().map(|v| dep.name_of(v)).collect::<Vec<_>>()),
|
||||
None => (key.clone(), values.iter().map(plain).collect()),
|
||||
};
|
||||
let now = reg.get(key).map(|d| d.name_of(&cur)).unwrap_or_else(|| plain(&cur));
|
||||
let want = match names.as_slice() {
|
||||
[] => "set".to_string(),
|
||||
[one] => one.clone(),
|
||||
many if many.len() > 3 => format!("{}, {} or another of {}", many[0], many[1], many.len()),
|
||||
many => format!("{} or {}", many[..many.len() - 1].join(", "), many[many.len() - 1]),
|
||||
};
|
||||
Some(format!("Only used while {label} is {want} (now {now})."))
|
||||
}
|
||||
|
||||
/// Why the setting is not used with frames from `source` (the engine's kinds: "window", "chiaki", "capture",
|
||||
/// "tap", "file"), or None if it is.
|
||||
pub fn unused_with(&self, source: &str) -> Option<String> {
|
||||
if self.sources.is_empty() || self.sources.iter().any(|s| s == source) { return None; }
|
||||
Some(self.elsewhere.get(source).or_else(|| self.elsewhere.get("")).cloned().filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| format!("Only used with these sources: {}.", self.sources.join(", "))))
|
||||
}
|
||||
|
||||
/// The note for a setting that only some sources use, where no source is known (the Settings page).
|
||||
pub fn source_note(&self) -> Option<String> {
|
||||
if self.sources.is_empty() { return None; }
|
||||
Some(self.elsewhere.get("").cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Only used with these sources: {}.", self.sources.join(", "))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// Parse what `python -m framegen.settings` printed.
|
||||
pub fn parse(json: &str) -> Result<Registry, String> {
|
||||
let v: Value = serde_json::from_str(json.trim()).map_err(|e| format!("not JSON: {e}"))?;
|
||||
let o = v.as_object().ok_or("not a JSON object")?;
|
||||
let mut specs: Vec<Spec> = o.get("specs").and_then(Value::as_array).ok_or("no \"specs\" list")?.iter().filter_map(Spec::parse).collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
specs.retain(|s| seen.insert(s.key.clone()));
|
||||
Ok(Registry { path: PathBuf::from(text(o.get("path"))), impact_pc: text(o.get("impact_pc")), specs })
|
||||
}
|
||||
|
||||
/// Ask the engine (a few hundredths of a second: it loads no GPU library).
|
||||
pub fn load(engine: &Path) -> Result<Registry, String> {
|
||||
let out = std::process::Command::new(crate::engine::python(engine)).current_dir(engine).args(["-m", "framegen.settings"])
|
||||
.stdin(std::process::Stdio::null()).output().map_err(|e| format!("could not run the engine's Python: {e}"))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(format!("the engine could not list its settings: {}", err.lines().last().unwrap_or("no output").trim()));
|
||||
}
|
||||
let mut reg = Self::parse(&String::from_utf8_lossy(&out.stdout))?;
|
||||
if reg.path.as_os_str().is_empty() { return Err("the engine did not say where its settings file is".into()); }
|
||||
if let Some(p) = std::env::var_os("SUMMIT_ENGINE_SETTINGS").filter(|p| !p.is_empty()) { reg.path = p.into(); }
|
||||
Ok(reg)
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<&Spec> { self.specs.iter().find(|s| s.key == key) }
|
||||
|
||||
/// The sections in the order the registry first names them, each with its settings in registry order.
|
||||
pub fn groups(&self) -> Vec<(String, Vec<&Spec>)> {
|
||||
let mut out: Vec<(String, Vec<&Spec>)> = vec![];
|
||||
for s in &self.specs {
|
||||
match out.iter_mut().find(|(g, _)| *g == s.group) { Some((_, v)) => v.push(s), None => out.push((s.group.clone(), vec![s])) }
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The values saved in the engine's settings file. A missing or damaged file is no values (the engine then uses its
|
||||
/// defaults, and so does the launcher).
|
||||
pub fn read_values(path: &Path) -> BTreeMap<String, Value> {
|
||||
std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.and_then(|v| v.as_object().map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Set (or with None remove, which is the engine's default) values in the settings file, keeping everything else
|
||||
/// in it. Written whole and renamed into place, as the engine's own save is one write.
|
||||
pub fn write_values(path: &Path, changes: &[(&str, Option<Value>)]) -> anyhow::Result<()> {
|
||||
let mut all = read_values(path);
|
||||
for (k, v) in changes {
|
||||
match v { Some(v) => { all.insert(k.to_string(), v.clone()); } None => { all.remove(*k); } }
|
||||
}
|
||||
let obj: serde_json::Map<String, Value> = all.into_iter().collect();
|
||||
crate::state::write_atomic(path, serde_json::to_string_pretty(&Value::Object(obj))?.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn to_toml(v: &Value) -> Option<toml::Value> {
|
||||
Some(match v {
|
||||
Value::Bool(b) => toml::Value::Boolean(*b),
|
||||
Value::Number(n) => match n.as_i64() { Some(i) => toml::Value::Integer(i), None => toml::Value::Float(n.as_f64()?) },
|
||||
Value::String(s) => toml::Value::String(s.clone()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn from_toml(v: &toml::Value) -> Value {
|
||||
match v {
|
||||
toml::Value::Boolean(b) => Value::Bool(*b),
|
||||
toml::Value::Integer(i) => Value::from(*i),
|
||||
toml::Value::Float(f) => serde_json::Number::from_f64(*f).map(Value::Number).unwrap_or(Value::Null),
|
||||
toml::Value::String(s) => Value::String(s.clone()),
|
||||
other => Value::String(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a resolved profile makes the engine use, by registry key: exactly what [`crate::engine::plan`] passes on
|
||||
/// the command line (the older named settings first, then the profile's `engine` table, which wins). A key that is
|
||||
/// not here is left to the engine's saved setting.
|
||||
pub fn forced(p: &Profile) -> BTreeMap<String, Value> {
|
||||
let mut m: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let s = |v: &str| Value::String(v.to_string());
|
||||
if p.framegen == "none" { m.insert("interp".into(), Value::Bool(false)); }
|
||||
if let Some(x) = p.multiplier() { m.insert("hz".into(), Value::from(30 * u32::from(x))); }
|
||||
if let Some(g) = p.game_fps.as_deref().filter(|g| crate::profile::GAME_FPS.contains(g)) { m.insert("game_fps".into(), s(g)); }
|
||||
if let Some((w, h)) = p.output_res.as_deref().and_then(crate::profile::parse_res) { m.insert("output_res".into(), s(&format!("{w}x{h}"))); }
|
||||
if let Some(x) = &p.model { m.insert("model".into(), s(x)); }
|
||||
if let (Some("vfg"), Some(q)) = (p.model.as_deref(), &p.vfg_quality) { m.insert("vfg_quality".into(), s(q)); }
|
||||
if let Some(x @ ("full" | "half")) = p.motion.as_deref() { m.insert("motion".into(), s(x)); }
|
||||
if let Some(x) = &p.ai_engine { m.insert("engine".into(), s(x)); }
|
||||
if let Some(x) = p.steady_hud { m.insert("steady_hud".into(), Value::Bool(x)); }
|
||||
if let Some(sc) = crate::engine::scaler_arg(&p.upscaler) {
|
||||
m.insert("scaler".into(), s(sc));
|
||||
if let (Some(v), "fsr") = (p.fsr_sharpness, sc) { m.insert("fsr_sharpness".into(), Value::from(v as f64)); }
|
||||
if let (Some(q), "vsr") = (p.vsr_quality, sc) { m.insert("vsr_quality".into(), Value::from(q)); }
|
||||
}
|
||||
match p.window_mode.as_str() {
|
||||
"windowed" => { m.insert("fullscreen".into(), Value::Bool(false)); }
|
||||
_ if p.fullscreen() => { m.insert("fullscreen".into(), Value::Bool(true)); }
|
||||
_ => {}
|
||||
}
|
||||
if let Some(x) = &p.fill { m.insert("fill".into(), s(x)); }
|
||||
if let Some(x) = p.vsync { m.insert("vsync".into(), Value::Bool(x)); }
|
||||
if let Some(x) = p.watermark { m.insert("watermark".into(), Value::Bool(x)); }
|
||||
if let Some(x) = p.aa.as_deref().filter(|v| crate::profile::AA.contains(v)) { m.insert("aa".into(), s(x)); }
|
||||
for (k, v) in &p.engine { m.insert(k.clone(), from_toml(v)); }
|
||||
m
|
||||
}
|
||||
|
||||
/// The older named profile settings that say the same as registry key `key` (cleared when the key is set through
|
||||
/// the `engine` table, so two places never disagree). "fullscreen" has none: that is the window mode, a launch setting.
|
||||
pub fn named_for(key: &str) -> &'static [&'static str] {
|
||||
match key {
|
||||
"interp" => &["framegen"], "hz" => &["framegen_multiplier", "target_hz"], "game_fps" => &["game_fps"],
|
||||
"output_res" => &["output_res"], "model" => &["model"], "vfg_quality" => &["vfg_quality"], "motion" => &["motion"],
|
||||
"engine" => &["ai_engine"], "steady_hud" => &["steady_hud"], "scaler" => &["upscaler"], "fsr_sharpness" => &["fsr_sharpness"],
|
||||
"vsr_quality" => &["vsr_quality"], "fill" => &["fill"], "vsync" => &["vsync"], "watermark" => &["watermark"],
|
||||
"aa" => &["aa"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
/// Set registry key `key` in this layer (None: stop setting it, so the layer below or the engine's saved
|
||||
/// setting decides). The older named setting for the same thing is dropped.
|
||||
pub fn set_engine(&mut self, key: &str, value: Option<&Value>) {
|
||||
for k in named_for(key) { self.unset(k); }
|
||||
let mut map = self.engine.take().unwrap_or_default();
|
||||
match value.and_then(to_toml) { Some(v) => { map.insert(key.to_string(), v); } None => { map.remove(key); } }
|
||||
self.engine = (!map.is_empty()).then_some(map);
|
||||
}
|
||||
|
||||
/// Whether this layer by itself decides registry key `key` (through the `engine` table or an older named setting).
|
||||
pub fn sets_engine(&self, key: &str) -> bool {
|
||||
self.engine.as_ref().is_some_and(|m| m.contains_key(key)) || forced(&crate::profile::resolve(&[self])).contains_key(key)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
const SAMPLE: &str = r#"{"path": "/tmp/x/settings.json", "impact_pc": "a PC", "specs": [
|
||||
{"key": "interp", "label": "Frame generation", "group": "Frame generation", "sub": "Basics", "help": "h", "default": true, "live": true, "saved": true,
|
||||
"later": "", "quick": true, "impact": {"speed": "Adds delay.", "picture": "Smoother."}, "experimental": false, "sources": null, "elsewhere": null, "applies": null,
|
||||
"choices": [{"value": true, "name": "On", "hint": ""}, {"value": false, "name": "Off", "hint": "No new frames."}]},
|
||||
{"key": "hz", "label": "Frame multiplier", "group": "Frame generation", "sub": "Basics", "default": 60, "quick": true,
|
||||
"applies": {"key": "interp", "values": [true]}, "choices": [{"value": 60, "name": "2x", "hint": ""}, {"value": 90, "name": "3x", "hint": ""}]},
|
||||
{"key": "capture_size", "label": "Capture card resolution", "group": "Sources", "default": "1080p", "experimental": true, "live": false,
|
||||
"sources": ["capture"], "elsewhere": {"chiaki": "Remote Play is 1080p.", "": "Only used with a capture card."},
|
||||
"choices": [{"value": "1080p", "name": "1080p", "hint": ""}, {"value": "2160p", "name": "4K", "hint": ""}]},
|
||||
{"key": "fsr_sharpness", "label": "FSR sharpening", "group": "Upscaling", "default": 0.5,
|
||||
"choices": [{"value": 0.0, "name": "Max"}, {"value": 0.5, "name": "Medium"}, {"value": 1.0, "name": "Low"}]}
|
||||
]}"#;
|
||||
|
||||
#[test]
|
||||
fn parses_what_the_engine_prints() {
|
||||
let r = Registry::parse(SAMPLE).unwrap();
|
||||
assert_eq!(r.path, PathBuf::from("/tmp/x/settings.json"));
|
||||
assert_eq!(r.specs.len(), 4);
|
||||
let i = r.get("interp").unwrap();
|
||||
assert_eq!((i.label.as_str(), i.group.as_str(), i.sub.as_str(), i.quick, i.saved, i.live), ("Frame generation", "Frame generation", "Basics", true, true, true));
|
||||
assert_eq!(i.impact, vec![("picture".to_string(), "Smoother.".to_string()), ("speed".to_string(), "Adds delay.".to_string())]);
|
||||
assert_eq!(i.choices[1], Choice { value: json!(false), name: "Off".into(), hint: "No new frames.".into() });
|
||||
assert_eq!(r.get("hz").unwrap().applies, Some(("interp".to_string(), vec![json!(true)])));
|
||||
let c = r.get("capture_size").unwrap();
|
||||
assert!(c.experimental && !c.live && c.sources == vec!["capture"]);
|
||||
assert_eq!(r.groups().iter().map(|(g, v)| (g.as_str(), v.len())).collect::<Vec<_>>(), vec![("Frame generation", 2), ("Sources", 1), ("Upscaling", 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_registry_from_a_newer_engine_still_reads() {
|
||||
// an unknown section, fields this version has never seen, a new kind of setting without choices, choices as
|
||||
// bare values, wrong types, a spec without a key, the same key twice
|
||||
let r = Registry::parse(r#"{"path": "/s.json", "new_top_level": 1, "specs": [
|
||||
{"key": "aa", "label": "Anti-aliasing", "group": "Anti-aliasing", "sub": 7, "default": "off", "kind": "enum", "min": 1,
|
||||
"impact": {"picture": "Smoother edges.", "memory": "More VRAM.", "bad": 3}, "choices": ["off", "fxaa", 2, true]},
|
||||
{"key": "strength", "label": "Strength", "group": "", "default": 0.4, "type": "range", "range": [0, 1], "choices": null},
|
||||
{"label": "no key"}, 17, {"key": "aa", "label": "again"},
|
||||
{"key": "odd", "impact": "fast", "applies": {"key": "", "values": 3}, "sources": "all", "quick": "yes", "default": {"a": 1}}
|
||||
]}"#).unwrap();
|
||||
assert_eq!(r.specs.iter().map(|s| s.key.as_str()).collect::<Vec<_>>(), vec!["aa", "strength", "odd"]);
|
||||
let aa = r.get("aa").unwrap();
|
||||
assert_eq!(aa.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["off", "fxaa", "2", "On"]);
|
||||
assert_eq!(aa.impact, vec![("picture".to_string(), "Smoother edges.".to_string()), ("memory".to_string(), "More VRAM.".to_string())]);
|
||||
assert_eq!(aa.sub, "");
|
||||
let s = r.get("strength").unwrap();
|
||||
assert!(s.choices.is_empty() && s.group == "Other");
|
||||
assert_eq!(s.name_of(&json!(0.4)), "0.4");
|
||||
let odd = r.get("odd").unwrap();
|
||||
assert!(odd.label == "odd" && odd.applies.is_none() && odd.sources.is_empty() && !odd.quick && odd.impact.is_empty());
|
||||
assert_eq!(r.groups().iter().map(|(g, _)| g.as_str()).collect::<Vec<_>>(), vec!["Anti-aliasing", "Other"]);
|
||||
assert!(Registry::parse("[]").is_err() && Registry::parse("{}").is_err() && Registry::parse("nope").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_compare_by_meaning_and_custom_ones_get_a_name() {
|
||||
let r = Registry::parse(SAMPLE).unwrap();
|
||||
assert!(same(&json!(1), &json!(1.0)) && !same(&json!(true), &json!(1)) && !same(&json!("1"), &json!(1)));
|
||||
assert_eq!(r.get("fsr_sharpness").unwrap().position(&json!(1)), Some(2));
|
||||
let hz = r.get("hz").unwrap();
|
||||
assert_eq!((hz.name_of(&json!(90)).as_str(), hz.name_of(&json!(210)).as_str()), ("3x", "7x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn says_why_a_setting_is_not_used() {
|
||||
let r = Registry::parse(SAMPLE).unwrap();
|
||||
let off = |k: &str| if k == "interp" { json!(false) } else { Value::Null };
|
||||
let on = |k: &str| if k == "interp" { json!(true) } else { Value::Null };
|
||||
let hz = r.get("hz").unwrap();
|
||||
assert_eq!(hz.unused_now(&r, &off).as_deref(), Some("Only used while Frame generation is On (now Off)."));
|
||||
assert_eq!(hz.unused_now(&r, &on), None);
|
||||
let c = r.get("capture_size").unwrap();
|
||||
assert_eq!(c.unused_with("capture"), None);
|
||||
assert_eq!(c.unused_with("chiaki").as_deref(), Some("Remote Play is 1080p."));
|
||||
assert_eq!(c.unused_with("window").as_deref(), Some("Only used with a capture card."));
|
||||
assert_eq!(c.source_note().as_deref(), Some("Only used with a capture card."));
|
||||
assert_eq!(hz.source_note(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_settings_file_is_changed_key_by_key() {
|
||||
let d = std::env::temp_dir().join(format!("summit-registry-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let f = d.join("deep/settings.json");
|
||||
assert!(read_values(&f).is_empty());
|
||||
write_values(&f, &[("scaler", Some(json!("vsr"))), ("hz", Some(json!(120)))]).unwrap();
|
||||
// something the launcher does not know stays in the file
|
||||
let mut v = read_values(&f);
|
||||
v.insert("from_a_newer_engine".into(), json!([1, 2]));
|
||||
std::fs::write(&f, serde_json::to_string(&v).unwrap()).unwrap();
|
||||
write_values(&f, &[("hz", None), ("vsync", Some(json!(true)))]).unwrap();
|
||||
let v = read_values(&f);
|
||||
assert_eq!(v.get("scaler"), Some(&json!("vsr")));
|
||||
assert_eq!(v.get("vsync"), Some(&json!(true)));
|
||||
assert_eq!(v.get("from_a_newer_engine"), Some(&json!([1, 2])));
|
||||
assert!(!v.contains_key("hz"));
|
||||
std::fs::write(&f, "not json").unwrap();
|
||||
assert!(read_values(&f).is_empty());
|
||||
write_values(&f, &[("hz", Some(json!(90)))]).unwrap(); // a damaged file is replaced, not a reason to fail
|
||||
assert_eq!(read_values(&f).get("hz"), Some(&json!(90)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_forces_what_the_planner_passes() {
|
||||
let p = Profile { framegen: "none".into(), upscaler: "rtx-vsr".into(), vsr_quality: Some(3), fsr_sharpness: Some(0.25), framegen_multiplier: 4,
|
||||
window_mode: "borderless".into(), watermark: Some(false), motion: Some("half".into()), ..Default::default() };
|
||||
let f = forced(&p);
|
||||
assert_eq!(f.get("interp"), Some(&json!(false)));
|
||||
assert_eq!(f.get("hz"), Some(&json!(120)));
|
||||
assert_eq!(f.get("scaler"), Some(&json!("vsr")));
|
||||
assert_eq!(f.get("vsr_quality"), Some(&json!(3)));
|
||||
assert!(!f.contains_key("fsr_sharpness")); // only with FSR, as the planner
|
||||
assert_eq!(f.get("fullscreen"), Some(&json!(true)));
|
||||
assert_eq!(f.get("watermark"), Some(&json!(false)));
|
||||
assert_eq!(f.get("motion"), Some(&json!("half")));
|
||||
assert!(forced(&Profile::default()).is_empty());
|
||||
// the engine table wins over the older named setting
|
||||
let mut p = Profile { upscaler: "fsr".into(), ..Default::default() };
|
||||
p.engine.insert("scaler".into(), toml::Value::String("bilinear".into()));
|
||||
p.engine.insert("overlay_style".into(), toml::Value::String("graphs".into()));
|
||||
let f = forced(&p);
|
||||
assert_eq!((f.get("scaler"), f.get("overlay_style")), (Some(&json!("bilinear")), Some(&json!("graphs"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_a_key_in_a_layer_drops_the_older_named_setting() {
|
||||
let mut l = Layer { upscaler: Some("rtx-vsr".into()), framegen_multiplier: Some(4), target_hz: Some(120), ..Default::default() };
|
||||
assert!(l.sets_engine("scaler") && l.sets_engine("hz") && !l.sets_engine("vsync"));
|
||||
l.set_engine("scaler", Some(&json!("fsr")));
|
||||
assert_eq!(l.upscaler, None);
|
||||
assert_eq!(l.engine.as_ref().unwrap().get("scaler"), Some(&toml::Value::String("fsr".into())));
|
||||
l.set_engine("hz", None);
|
||||
assert_eq!((l.framegen_multiplier, l.target_hz), (None, None));
|
||||
assert!(!l.sets_engine("hz"));
|
||||
l.set_engine("fsr_sharpness", Some(&json!(0.25)));
|
||||
l.set_engine("vsr_quality", Some(&json!(4)));
|
||||
l.set_engine("overlay", Some(&json!(false)));
|
||||
let text = toml::to_string_pretty(&l).unwrap();
|
||||
let back: Layer = toml::from_str(&text).unwrap();
|
||||
assert_eq!(back, l, "{text}");
|
||||
let f = forced(&crate::profile::resolve(&[&back]));
|
||||
assert_eq!((f.get("fsr_sharpness"), f.get("vsr_quality"), f.get("overlay")), (Some(&json!(0.25)), Some(&json!(4)), Some(&json!(false))));
|
||||
l.set_engine("scaler", None); l.set_engine("fsr_sharpness", None); l.set_engine("vsr_quality", None); l.set_engine("overlay", None);
|
||||
assert!(l.is_empty(), "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_anti_aliasing_profile_field_and_the_engine_table_agree() {
|
||||
// Compare's named `aa` and the launcher's `[engine] aa` are one setting: the later layer wins either way
|
||||
let named = Layer { aa: Some("smaa".into()), ..Default::default() };
|
||||
let mut table = Layer::default();
|
||||
table.set_engine("aa", Some(&json!("fxaa")));
|
||||
assert!(named.sets_engine("aa") && table.sets_engine("aa"));
|
||||
let p = crate::profile::resolve(&[&table, &named]);
|
||||
assert_eq!(forced(&p).get("aa"), Some(&json!("smaa")));
|
||||
assert!(!p.engine.contains_key("aa"), "the named setting above replaces the table's key below");
|
||||
let p = crate::profile::resolve(&[&named, &table]);
|
||||
assert_eq!(forced(&p).get("aa"), Some(&json!("fxaa")));
|
||||
// the planner then passes --aa=smaa and, after it, --set=aa="fxaa": the engine applies --set last
|
||||
let mut l = named.clone();
|
||||
l.set_engine("aa", Some(&json!("cas")));
|
||||
assert_eq!(l.aa, None, "the launcher's row drops the older named setting");
|
||||
assert!(forced(&Profile { aa: Some("dlaa".into()), ..Default::default() }).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_real_engine_registry_reads_when_python_is_here() {
|
||||
let engine = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../engine");
|
||||
let Ok(r) = Registry::load(&engine) else { eprintln!("skipped: no python3 to ask the engine"); return };
|
||||
assert!(r.specs.len() > 30 && r.get("scaler").is_some() && r.get("hz").is_some());
|
||||
assert!(r.specs.iter().all(|s| !s.label.is_empty() && !s.group.is_empty()));
|
||||
assert!(r.specs.iter().filter(|s| s.quick).count() >= 4);
|
||||
// every preset names a real setting and one of its choices
|
||||
for p in crate::presets::PRESETS {
|
||||
for (k, v) in p.values() {
|
||||
let s = r.get(k).unwrap_or_else(|| panic!("preset {}: no setting {k}", p.id));
|
||||
assert!(s.position(&v).is_some(), "preset {}: {k} has no choice {v}", p.id);
|
||||
}
|
||||
}
|
||||
// every key the launch profile can force is a real setting, of the registry's type
|
||||
for k in ["interp", "hz", "game_fps", "output_res", "model", "vfg_quality", "motion", "engine", "steady_hud", "scaler", "fsr_sharpness", "vsr_quality", "fullscreen", "fill", "vsync", "watermark", "replay", "replay_clip", "aa"] {
|
||||
assert!(r.get(k).is_some(), "the engine has no setting {k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Session summaries the engine writes after a run (JSON files), for a game's Statistics view.
|
||||
//!
|
||||
//! The format belongs to the engine and is not fixed here: every `*.json` in the sessions folders is read as it
|
||||
//! is, and what is shown is what the file holds (its fields, flattened). Only the names of a few fields are
|
||||
//! guessed, to pick a headline: a duration, an average frame rate, the lows, which game it was. A file that is
|
||||
//! not a JSON object is skipped; a missing folder is no sessions.
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Summary {
|
||||
pub file: PathBuf,
|
||||
/// When it ended, as far as the file says (a "ended"/"end"/"time"/"timestamp" field in seconds), else the
|
||||
/// file's modification time. Seconds since 1970; 0 if unknown.
|
||||
pub when: u64,
|
||||
/// The game it says it was for ("game", "title", "game_title", "name", "game_id", "id"), if it says.
|
||||
pub game: Option<String>,
|
||||
/// Every scalar in the file as (dotted name, text), sorted by name; lists of scalars joined, other lists
|
||||
/// counted.
|
||||
pub fields: Vec<(String, String)>,
|
||||
pub duration_s: Option<f64>,
|
||||
pub fps_avg: Option<f64>,
|
||||
/// (the field's own name, value): "1% low", "0.1% low", "min"...
|
||||
pub lows: Vec<(String, f64)>,
|
||||
/// The fields under a "settings" object (or any name ending in "settings"), as (key, text).
|
||||
pub settings: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Where summaries are looked for: $SUMMIT_SESSIONS_DIR, then `sessions` and `stats` folders under the engine's
|
||||
/// and Summit's data, state, cache and config folders. Folders that do not exist are fine.
|
||||
pub fn dirs() -> Vec<PathBuf> {
|
||||
let mut v: Vec<PathBuf> = vec![];
|
||||
if let Some(d) = std::env::var_os("SUMMIT_SESSIONS_DIR").filter(|d| !d.is_empty()) { v.push(d.into()); }
|
||||
let roots = [::dirs::data_dir(), ::dirs::state_dir(), ::dirs::cache_dir(), ::dirs::config_dir()];
|
||||
for root in roots.into_iter().flatten() {
|
||||
for app in ["smoovplay", "summit"] { for sub in ["sessions", "stats"] { v.push(root.join(app).join(sub)); } }
|
||||
}
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
fn scalar(v: &Value) -> Option<String> {
|
||||
match v {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Bool(b) => Some(if *b { "yes" } else { "no" }.into()),
|
||||
Value::Number(n) => Some(match n.as_f64() { Some(f) if n.is_f64() => trim_num(f), _ => n.to_string() }),
|
||||
Value::Null => None,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn trim_num(f: f64) -> String {
|
||||
let s = format!("{f:.2}");
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
fn flatten(prefix: &str, v: &Value, depth: u8, out: &mut Vec<(String, String)>) {
|
||||
match v {
|
||||
Value::Object(o) if depth < 4 => for (k, v) in o { flatten(&if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") }, v, depth + 1, out); },
|
||||
Value::Object(o) => out.push((prefix.to_string(), format!("{} fields", o.len()))),
|
||||
Value::Array(a) => {
|
||||
let parts: Vec<String> = a.iter().filter_map(scalar).collect();
|
||||
if parts.len() == a.len() && a.len() <= 12 { out.push((prefix.to_string(), parts.join(", "))); }
|
||||
else { out.push((prefix.to_string(), format!("{} values", a.len()))); }
|
||||
}
|
||||
other => if let Some(s) = scalar(other) { out.push((prefix.to_string(), s)); },
|
||||
}
|
||||
}
|
||||
|
||||
fn last(name: &str) -> String { name.rsplit('.').next().unwrap_or(name).to_lowercase() }
|
||||
|
||||
/// Read one summary from JSON text. None if it is not a JSON object.
|
||||
pub fn parse(text: &str, file: &Path, mtime: u64) -> Option<Summary> {
|
||||
let v: Value = serde_json::from_str(text).ok()?;
|
||||
let o = v.as_object()?;
|
||||
let mut fields = vec![];
|
||||
flatten("", &v, 0, &mut fields);
|
||||
let num = |name: &str| -> Option<f64> { fields.iter().find(|(k, _)| k == name).and_then(|(_, v)| v.parse::<f64>().ok()) };
|
||||
let pick = |test: &dyn Fn(&str) -> bool| -> Option<(String, f64)> {
|
||||
fields.iter().find(|(k, v)| test(&k.to_lowercase()) && v.parse::<f64>().is_ok()).map(|(k, v)| (k.clone(), v.parse().unwrap_or(0.0)))
|
||||
};
|
||||
let game = ["game", "title", "game_title", "name", "game_id", "id"].iter()
|
||||
.find_map(|k| o.get(*k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from));
|
||||
let when = ["ended", "ended_at", "end", "end_time", "time", "timestamp", "started", "start"].iter()
|
||||
.find_map(|k| num(k)).filter(|t| *t > 1.0e9 && *t < 1.0e11).map(|t| t as u64).unwrap_or(mtime);
|
||||
// seconds unless the name says otherwise
|
||||
let duration_s = pick(&|k| { let l = last(k); l.contains("duration") || l.contains("elapsed") || l == "seconds" || l == "length_s" || l == "playtime" })
|
||||
.map(|(k, v)| { let l = last(&k); if l.ends_with("_ms") { v / 1000.0 } else if l.ends_with("_min") || l.ends_with("minutes") { v * 60.0 } else { v } });
|
||||
let is_fps = |k: &str| k.contains("fps") || k.contains("frame_rate") || k.contains("framerate");
|
||||
let fps_avg = pick(&|k| is_fps(k) && (k.contains("avg") || k.contains("average") || k.contains("mean")))
|
||||
.or_else(|| pick(&|k| { let l = last(k); l == "fps" || l == "output_fps" || l == "fps_out" })).map(|(_, v)| v);
|
||||
let lows: Vec<(String, f64)> = fields.iter().filter(|(k, _)| { let k = k.to_lowercase(); (k.contains("low") || k.contains("p1") || k.contains("p01") || k.contains("min_fps") || k.contains("fps_min")) && !k.contains("settings") })
|
||||
.filter_map(|(k, v)| Some((last(k).replace('_', " "), v.parse::<f64>().ok()?))).take(4).collect();
|
||||
let settings: Vec<(String, String)> = fields.iter().filter_map(|(k, v)| {
|
||||
let (head, rest) = k.split_once('.')?;
|
||||
head.to_lowercase().ends_with("settings").then(|| (rest.to_string(), v.clone()))
|
||||
}).collect();
|
||||
Some(Summary { file: file.to_path_buf(), when, game, fields, duration_s, fps_avg, lows, settings })
|
||||
}
|
||||
|
||||
/// Every summary in `dirs` (and one folder level below, for a folder per game), newest first. At most `max` files
|
||||
/// are read, and none bigger than 1 MB.
|
||||
pub fn read(dirs: &[PathBuf], max: usize) -> Vec<Summary> {
|
||||
let mut files: Vec<(PathBuf, u64, Option<String>)> = vec![];
|
||||
let scan = |dir: &Path, folder: Option<String>, files: &mut Vec<(PathBuf, u64, Option<String>)>| -> Vec<PathBuf> {
|
||||
let mut subs = vec![];
|
||||
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let p = e.path();
|
||||
let Ok(meta) = e.metadata() else { continue };
|
||||
if meta.is_dir() { subs.push(p); continue; }
|
||||
if p.extension().and_then(|x| x.to_str()) != Some("json") || meta.len() > 1_000_000 { continue; }
|
||||
let mtime = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0);
|
||||
files.push((p, mtime, folder.clone()));
|
||||
}
|
||||
subs
|
||||
};
|
||||
for d in dirs {
|
||||
for sub in scan(d, None, &mut files) {
|
||||
let name = sub.file_name().map(|n| n.to_string_lossy().into_owned());
|
||||
scan(&sub, name, &mut files);
|
||||
}
|
||||
}
|
||||
files.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
files.dedup_by(|a, b| a.0 == b.0);
|
||||
files.truncate(max);
|
||||
let mut out: Vec<Summary> = files.into_iter().filter_map(|(p, mtime, folder)| {
|
||||
let mut s = parse(&std::fs::read_to_string(&p).ok()?, &p, mtime)?;
|
||||
if s.game.is_none() { s.game = folder; } // a folder per game names it
|
||||
Some(s)
|
||||
}).collect();
|
||||
out.sort_by(|a, b| b.when.cmp(&a.when));
|
||||
out
|
||||
}
|
||||
|
||||
fn norm(s: &str) -> String { s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() }
|
||||
|
||||
/// Whether a summary is for the game with this id and title: it names one of them (letters and digits compared,
|
||||
/// so "Void Runner" is "voidrunner"). A summary that names no game belongs to none.
|
||||
pub fn is_for(s: &Summary, id: &str, title: &str) -> bool {
|
||||
let Some(g) = s.game.as_deref().map(norm).filter(|g| !g.is_empty()) else { return false };
|
||||
g == norm(title) || g == norm(id) || id.rsplit(':').next().is_some_and(|tail| g == norm(tail))
|
||||
}
|
||||
|
||||
/// "1 h 12 min", "4 min 5 s", "42 s".
|
||||
pub fn duration_label(s: f64) -> String {
|
||||
let t = s.max(0.0).round() as u64;
|
||||
match (t / 3600, (t % 3600) / 60, t % 60) {
|
||||
(0, 0, s) => format!("{s} s"),
|
||||
(0, m, s) => format!("{m} min {s} s"),
|
||||
(h, m, _) => format!("{h} h {m} min"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A time as the wall clock here shows it: "2026-11-26 14:05". Seconds since 1970; "" for 0.
|
||||
pub fn stamp(t: u64) -> String {
|
||||
if t == 0 { return String::new(); }
|
||||
let secs = t as libc::time_t;
|
||||
let mut tm: libc::tm = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: localtime_r only writes the tm it is given.
|
||||
if unsafe { libc::localtime_r(&secs, &mut tm) }.is_null() { return String::new(); }
|
||||
format!("{:04}-{:02}-{:02} {:02}:{:02}", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shows_what_is_in_the_file_whatever_its_shape() {
|
||||
let s = parse(r#"{"game": "Voidrunner", "ended": 1795000000, "duration_s": 754.4, "fps": {"avg": 118.26, "low_1": 96.5, "low_01": 71},
|
||||
"settings": {"scaler": "fsr", "hz": 120, "interp": true}, "dropped": [1, 2, 3], "notes": null}"#, Path::new("a.json"), 5).unwrap();
|
||||
assert_eq!(s.game.as_deref(), Some("Voidrunner"));
|
||||
assert_eq!(s.when, 1795000000);
|
||||
assert_eq!(s.duration_s, Some(754.4));
|
||||
assert_eq!(s.fps_avg, Some(118.26));
|
||||
assert_eq!(s.lows, vec![("low 01".to_string(), 71.0), ("low 1".to_string(), 96.5)]);
|
||||
assert_eq!(s.settings, vec![("hz".to_string(), "120".to_string()), ("interp".to_string(), "yes".to_string()), ("scaler".to_string(), "fsr".to_string())]);
|
||||
assert!(s.fields.contains(&("dropped".to_string(), "1, 2, 3".to_string())));
|
||||
assert!(s.fields.contains(&("fps.avg".to_string(), "118.26".to_string())));
|
||||
assert!(!s.fields.iter().any(|(k, _)| k == "notes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_names_and_nothing_at_all() {
|
||||
let s = parse(r#"{"title": "X", "elapsed_ms": 90000, "average_fps": 59.9, "one_percent_low_fps": 48}"#, Path::new("b.json"), 77).unwrap();
|
||||
assert_eq!((s.duration_s, s.fps_avg, s.when), (Some(90.0), Some(59.9), 77));
|
||||
assert_eq!(s.lows, vec![("one percent low fps".to_string(), 48.0)]);
|
||||
// nothing recognisable: still a summary, with its fields, and no made-up numbers
|
||||
let s = parse(r#"{"a": 1, "b": {"c": "d"}}"#, Path::new("c.json"), 3).unwrap();
|
||||
assert_eq!((s.duration_s, s.fps_avg, s.game.clone(), s.lows.len(), s.settings.len()), (None, None, None, 0, 0));
|
||||
assert_eq!(s.fields, vec![("a".to_string(), "1".to_string()), ("b.c".to_string(), "d".to_string())]);
|
||||
assert!(parse("[1, 2]", Path::new("d.json"), 0).is_none());
|
||||
assert!(parse("{broken", Path::new("e.json"), 0).is_none());
|
||||
assert!(parse("", Path::new("f.json"), 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_folders_defensively_and_matches_games() {
|
||||
let d = std::env::temp_dir().join(format!("summit-sessions-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert!(read(&[d.clone(), d.join("nope")], 50).is_empty());
|
||||
std::fs::create_dir_all(d.join("Voidrunner")).unwrap();
|
||||
std::fs::write(d.join("one.json"), r#"{"game": "Void Runner", "ended": 1795000100, "duration": 60}"#).unwrap();
|
||||
std::fs::write(d.join("Voidrunner/two.json"), r#"{"ended": 1795000200, "fps_avg": 90}"#).unwrap();
|
||||
std::fs::write(d.join("other.json"), r#"{"game": "Else", "ended": 1795000300}"#).unwrap();
|
||||
std::fs::write(d.join("junk.json"), "not json").unwrap();
|
||||
std::fs::write(d.join("list.json"), "[]").unwrap();
|
||||
std::fs::write(d.join("readme.txt"), "{}").unwrap();
|
||||
let all = read(&[d.clone()], 50);
|
||||
assert_eq!(all.iter().map(|s| s.when).collect::<Vec<_>>(), vec![1795000300, 1795000200, 1795000100]);
|
||||
let mine: Vec<&Summary> = all.iter().filter(|s| is_for(s, "custom:voidrunner", "Voidrunner")).collect();
|
||||
assert_eq!(mine.len(), 2);
|
||||
assert_eq!(mine[0].game.as_deref(), Some("Voidrunner")); // from its folder
|
||||
assert!(!is_for(&Summary::default(), "x", "X"));
|
||||
assert_eq!(read(&[d.clone()], 1).len(), 1);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamps_are_dates() {
|
||||
assert_eq!(stamp(0), "");
|
||||
let s = stamp(1_795_000_000);
|
||||
assert!(s.len() == 16 && s.starts_with("2026-11-1"), "{s}"); // (the hour depends on the time zone)
|
||||
}
|
||||
#[test]
|
||||
fn durations_read_naturally() {
|
||||
assert_eq!((duration_label(42.4).as_str(), duration_label(245.0).as_str(), duration_label(4330.0).as_str()), ("42 s", "4 min 5 s", "1 h 12 min"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
summit-core = { path = "../summit-core" }
|
||||
serde_json.workspace = true
|
||||
# renderer-femtovg (OpenGL) is what a normal run uses; renderer-software is the fallback and the headless screenshot mode.
|
||||
slint = { version = "1.19", default-features = false, features = ["std", "backend-winit", "renderer-femtovg", "renderer-software", "software-renderer-systemfonts", "compat-1-2", "unstable-winit-030"] }
|
||||
# unstable-winit-030: whether the launcher's window has the keyboard (winit's has_focus), so a controller is only
|
||||
|
||||
@@ -188,7 +188,6 @@ fn rates(p: &Profile, outs: &[Output]) -> Vec<f32> {
|
||||
}
|
||||
|
||||
fn enc_bool(v: Option<bool>) -> Option<String> { v.map(|b| if b { "on".into() } else { "off".into() }) }
|
||||
fn enc_num<T: ToString>(v: Option<T>) -> Option<String> { v.map(|n| n.to_string()) }
|
||||
|
||||
/// A layer's value for a row, encoded as that row's choices are.
|
||||
pub fn enc_get(l: &Layer, key: &str) -> Option<String> {
|
||||
@@ -197,24 +196,7 @@ pub fn enc_get(l: &Layer, key: &str) -> Option<String> {
|
||||
"resolution" => match (l.width, l.height) { (Some(w), Some(h)) if w > 0 && h > 0 => Some(format!("{w}x{h}")), (Some(_), _) | (_, Some(_)) => Some(String::new()), _ => None },
|
||||
"refresh_hz" => l.refresh_hz.map(|r| if r > 0.0 { format!("{r}") } else { String::new() }),
|
||||
"window_mode" => l.window_mode.clone(),
|
||||
"focus" => enc_bool(l.focus), "enhance" => enc_bool(l.enhance), "steady_hud" => enc_bool(l.steady_hud),
|
||||
"vsync" => enc_bool(l.vsync), "watermark" => enc_bool(l.watermark),
|
||||
"upscaler" => l.upscaler.as_deref().map(|u| if u == "vsr" { "rtx-vsr".into() } else { u.to_string() }),
|
||||
"fsr_sharpness" => l.fsr_sharpness.map(|v| if v < 0.0 { String::new() } else { format!("{v}") }),
|
||||
"vsr_quality" => l.vsr_quality.map(|v| if v == 0 { String::new() } else { v.to_string() }),
|
||||
"framegen" => l.framegen.clone(),
|
||||
"target_hz" => l.target_hz.map(|v| if v == 0 { String::new() } else { v.to_string() }),
|
||||
// the multiplier, or an older file's output rate read as one (120 Hz is 4x); "" a game's "engine setting"
|
||||
"framegen_multiplier" => match (l.framegen_multiplier, l.target_hz) {
|
||||
(Some(m), _) if summit_core::profile::MULTIPLIER_RANGE.contains(&m) => Some(m.to_string()),
|
||||
(_, Some(0)) | (Some(_), None) => Some(String::new()),
|
||||
(_, Some(hz)) => Some((hz / 30).to_string()),
|
||||
(None, None) => None,
|
||||
},
|
||||
"model" => l.model.clone(), "vfg_quality" => l.vfg_quality.clone(), "motion" => l.motion.clone(),
|
||||
"ai_engine" => l.ai_engine.clone(), "fill" => l.fill.clone(),
|
||||
"game_fps" => l.game_fps.clone(),
|
||||
"output_res" => l.output_res.as_deref().map(|r| summit_core::profile::parse_res(r).map(|(w, h)| format!("{w}x{h}")).unwrap_or_default()),
|
||||
"focus" => enc_bool(l.focus), "enhance" => enc_bool(l.enhance),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -235,22 +217,7 @@ pub fn enc_set(l: &mut Layer, key: &str, v: Option<&str>) {
|
||||
}
|
||||
"refresh_hz" => l.refresh_hz = v.map(|t| t.parse().unwrap_or(0.0)),
|
||||
"window_mode" => l.window_mode = s(v),
|
||||
"focus" => l.focus = b(v), "enhance" => l.enhance = b(v), "steady_hud" => l.steady_hud = b(v),
|
||||
"vsync" => l.vsync = b(v), "watermark" => l.watermark = b(v),
|
||||
"upscaler" => l.upscaler = s(v),
|
||||
"fsr_sharpness" => l.fsr_sharpness = v.map(|t| t.parse().unwrap_or(-1.0)),
|
||||
"vsr_quality" => l.vsr_quality = v.map(|t| t.parse().unwrap_or(0)),
|
||||
"framegen" => l.framegen = s(v),
|
||||
"target_hz" => l.target_hz = v.map(|t| t.parse().unwrap_or(0)),
|
||||
"framegen_multiplier" => match v.map(str::parse::<u8>) {
|
||||
None => { l.framegen_multiplier = None; l.target_hz = None; }
|
||||
Some(Ok(m)) => { l.framegen_multiplier = Some(m); l.target_hz = None; }
|
||||
Some(Err(_)) => { l.framegen_multiplier = None; l.target_hz = Some(0); } // "": the engine's own
|
||||
},
|
||||
"model" => l.model = s(v), "vfg_quality" => l.vfg_quality = s(v), "motion" => l.motion = s(v),
|
||||
"ai_engine" => l.ai_engine = s(v), "fill" => l.fill = s(v),
|
||||
"game_fps" => l.game_fps = s(v),
|
||||
"output_res" => l.output_res = s(v),
|
||||
"focus" => l.focus = b(v), "enhance" => l.enhance = b(v),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -281,7 +248,6 @@ fn label_of(choices: &[Choice], v: &Option<String>) -> String {
|
||||
fn choices(key: &str, eff: &Profile, base: &Profile, outs: &[Output], own: &Layer) -> (Vec<Choice>, Option<String>) {
|
||||
let c = |v: &str, l: &str| (Some(v.to_string()), l.to_string());
|
||||
let unset = |l: &str| (None, l.to_string());
|
||||
let bool3 = |l: &str| vec![unset(l), c("off", "Off"), c("on", "On")];
|
||||
let opt = |v: Option<String>| Some(v.unwrap_or_default());
|
||||
match key {
|
||||
"monitor" => {
|
||||
@@ -303,30 +269,6 @@ fn choices(key: &str, eff: &Profile, base: &Profile, outs: &[Output], own: &Laye
|
||||
"window_mode" => (vec![unset("As the game opens it"), c("windowed", "Windowed"), c("borderless", "Borderless window"), c("fullscreen", "Fullscreen")], opt(Some(base.window_mode.clone()))),
|
||||
"focus" => (vec![unset("Off"), c("on", "On")], Some(if base.focus { "on".into() } else { String::new() })),
|
||||
"enhance" => (vec![unset("Off"), c("on", "On")], Some(if base.enhance { "on".into() } else { String::new() })),
|
||||
"upscaler" => (vec![unset("Engine setting (FSR)"), c("none", "Off (no upscaling)"), c("fsr", "AMD FSR 1"), c("rtx-vsr", "NVIDIA RTX VSR"), c("bilinear", "Bilinear")], opt(Some(if base.upscaler == "vsr" { "rtx-vsr".into() } else { base.upscaler.clone() }))),
|
||||
"fsr_sharpness" => (vec![unset("Engine setting"), c("0", "Max"), c("0.25", "High"), c("0.5", "Medium"), c("1", "Low"), c("2", "Minimal")], opt(base.fsr_sharpness.map(|v| format!("{v}")))),
|
||||
"vsr_quality" => (vec![unset("Engine setting"), c("1", "Low"), c("2", "Medium"), c("3", "High"), c("4", "Ultra")], opt(enc_num(base.vsr_quality))),
|
||||
"framegen" => (vec![unset("Engine setting (on)"), c("none", "Off"), c("rife", "On")], opt(Some(base.framegen.clone()))),
|
||||
"model" => (vec![unset("Engine setting"), c("4.22.lite", "RIFE 4.22 lite"), c("4.25.lite", "RIFE 4.25 lite"), c("4.25", "RIFE 4.25"), c("4.26", "RIFE 4.26"), c("vfg", "NVIDIA VFG")], opt(base.model.clone())),
|
||||
"vfg_quality" => (vec![unset("Engine setting"), c("low", "Low"), c("medium", "Medium"), c("high", "High")], opt(base.vfg_quality.clone())),
|
||||
"motion" => (vec![unset("Auto"), c("full", "Full"), c("half", "Half")], opt(base.motion.clone())),
|
||||
"ai_engine" => (vec![unset("Engine setting"), c("auto", "Auto"), c("trt", "TensorRT"), c("torch", "PyTorch")], opt(base.ai_engine.clone())),
|
||||
"target_hz" => (vec![unset("Engine setting"), c("60", "60 Hz"), c("90", "90 Hz"), c("120", "120 Hz")], opt(enc_num(base.target_hz))),
|
||||
"game_fps" => (vec![unset("Engine setting (Auto)"), c("auto", "Auto"), c("30", "30 fps"), c("60", "60 fps")], opt(base.game_fps.clone())),
|
||||
"output_res" => {
|
||||
let mut v = vec![unset("Same as the screen")];
|
||||
v.extend(summit_core::profile::OUTPUT_SIZES.iter().map(|r| c(r, &res_label(r))));
|
||||
(v, opt(base.output_res.clone()))
|
||||
}
|
||||
"framegen_multiplier" => {
|
||||
let mut v = vec![unset("Engine setting (2×)")];
|
||||
v.extend(summit_core::profile::MULTIPLIERS.iter().map(|m| c(&m.to_string(), &multiplier_label(*m))));
|
||||
(v, opt(base.multiplier().map(|m| m.to_string())))
|
||||
}
|
||||
"steady_hud" => (bool3("Engine setting"), Some(base.steady_hud.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
"fill" => (vec![unset("Engine setting"), c("fit", "Fit (bars)"), c("zoom", "Zoom (crop)"), c("stretch", "Stretch"), c("panorama", "Panorama")], opt(base.fill.clone())),
|
||||
"vsync" => (bool3("Engine setting"), Some(base.vsync.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
"watermark" => (bool3("Engine setting (on)"), Some(base.watermark.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
_ => (vec![], None),
|
||||
}
|
||||
}
|
||||
@@ -335,41 +277,14 @@ fn choices(key: &str, eff: &Profile, base: &Profile, outs: &[Output], own: &Laye
|
||||
fn effective(cx: &EditCtx) -> Profile { let mut p = cx.base.clone(); cx.own.apply(&mut p); p }
|
||||
|
||||
/// A row's choices for the layer being edited. On a game "not chosen" becomes a value of its own (Some(""): e.g.
|
||||
/// never switch monitors, whatever the defaults say), and a first choice follows the defaults. Engine on/off
|
||||
/// settings have no "not chosen" a game can store, so a game picks Off or On there.
|
||||
fn layer_choices(key: &str, mut ch: Vec<Choice>, defaults: bool, base_label: &str) -> Vec<Choice> {
|
||||
/// never switch monitors, whatever the defaults say), and a first choice follows the defaults.
|
||||
fn layer_choices(_key: &str, mut ch: Vec<Choice>, defaults: bool, base_label: &str) -> Vec<Choice> {
|
||||
if defaults { return ch; }
|
||||
if matches!(key, "steady_hud" | "vsync" | "watermark") { ch.retain(|c| c.0.is_some()); }
|
||||
for c in ch.iter_mut() { if c.0.is_none() { c.0 = Some(String::new()); } }
|
||||
ch.insert(0, (None, format!("Default · {base_label}")));
|
||||
ch
|
||||
}
|
||||
|
||||
/// "4× (120 fps)": a frame multiplier and the rate it makes of a 30 fps game.
|
||||
pub fn multiplier_label(m: u8) -> String { format!("{m}×") }
|
||||
|
||||
/// "1440p" for the presets, "2560 × 1080" for any other size.
|
||||
pub fn res_label(r: &str) -> String {
|
||||
match summit_core::profile::parse_res(r) {
|
||||
Some((3840, 2160)) => "4K (3840 × 2160)".into(),
|
||||
Some((w, h)) if summit_core::profile::OUTPUT_SIZES.contains(&format!("{w}x{h}").as_str()) => format!("{h}p ({w} × {h})"),
|
||||
Some((w, h)) => format!("{w} × {h}"),
|
||||
None => r.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer's output resolution when it isn't one of the editor's choices (typed in Custom output resolution).
|
||||
fn custom_res(l: &Layer) -> Option<String> {
|
||||
let (w, h) = summit_core::profile::parse_res(l.output_res.as_deref()?)?;
|
||||
let r = format!("{w}x{h}");
|
||||
(!summit_core::profile::OUTPUT_SIZES.contains(&r.as_str())).then_some(r)
|
||||
}
|
||||
|
||||
/// The layer's multiplier when it isn't one of the editor's choices (typed in Custom multiplier).
|
||||
fn custom_multiplier(l: &Layer) -> Option<u8> {
|
||||
l.framegen_multiplier.filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m) && !summit_core::profile::MULTIPLIERS.contains(m))
|
||||
}
|
||||
|
||||
/// Text rows: launch arguments and environment variables, as one line each.
|
||||
fn text_of(l: &Layer, key: &str) -> Option<String> {
|
||||
match key {
|
||||
@@ -380,14 +295,12 @@ fn text_of(l: &Layer, key: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows, in order, with headers. Rows that cannot matter with the other choices (FSR sharpening with RTX VSR,
|
||||
/// VFG quality with RIFE) are left out.
|
||||
/// The rows, in order, with headers: what belongs to the launch itself (monitor, window, arguments). The engine's
|
||||
/// settings are rows of their own, from the engine's registry (rows.rs).
|
||||
pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
let eff = effective(cx);
|
||||
let mut rows = vec![];
|
||||
let header = |t: &str| EditRow { key: "", kind: RowKind::Header, label: t.into(), hint: String::new(), options: vec![], value: 0, text: String::new(), placeholder: String::new(), own: false };
|
||||
let up = eff.upscaler.as_str();
|
||||
let rife = !matches!(eff.model.as_deref(), Some("vfg")) && eff.framegen != "none";
|
||||
let mon_hint = match cx.list_err {
|
||||
Some(e) => format!("Monitors could not be listed: {e}."),
|
||||
None => format!("Switched with {} when Summit starts the game and put back when it ends. The game's window is moved there too{}.", if cx.tool.is_empty() { "the desktop's tool" } else { cx.tool }, if cx.placer.is_ok() { "" } else { " (not on this desktop)" }),
|
||||
@@ -400,27 +313,8 @@ pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
("refresh_hz", "Refresh rate", if eff.width.is_none() { "Pick a resolution first.".into() } else { "Rates this mode offers.".into() }),
|
||||
("window_mode", "Window mode", format!("The game's window, windowed, as a borderless window over the monitor, or fullscreen. {place_note} With Enhance it is the engine's picture instead, and the game is left at its size.")),
|
||||
("focus", "Focus the game", format!("Raise the game's window and give it the keyboard once it opens. {place_note}")),
|
||||
("#", "ENHANCE: UPSCALING", String::new()),
|
||||
("enhance", "Enhance on Play", "Play also runs Summit's engine on the game's window: the upscaler and frame generation below.".into()),
|
||||
("upscaler", "Upscaler", "Enlarges the game's picture to the window or monitor. FSR is almost free and was run on the test machine; RTX VSR is wired but untested.".into()),
|
||||
("fsr_sharpness", "FSR sharpening", "How strongly FSR 1 sharpens. Less keeps compression blocks from standing out.".into()),
|
||||
("vsr_quality", "RTX VSR quality", "Higher is cleaner and asks more of the GPU.".into()),
|
||||
("output_res", "Output resolution", "The size the upscaler makes the picture, then fitted to the screen: smaller is lighter, bigger than the screen sharpens (supersampling).".into()),
|
||||
("output_res_custom", "Custom output resolution", "Any size, e.g. 2560x1080 (from 320x240 to 7680x4320). Enter to type it, Enter to save; empty goes back to the choice above.".into()),
|
||||
("fill", "Fill the screen", "On a screen that is not 16:9: bars, crop, stretch, or panorama.".into()),
|
||||
("#", "ENHANCE: FRAME GENERATION", String::new()),
|
||||
("framegen", "Frame generation", "AI in-between frames. Needs an NVIDIA GPU and the engine's Python environment.".into()),
|
||||
("model", "Model", "RIFE 4.22 lite is the one the engine is tuned and tested with. NVIDIA VFG is a separate download (RTX 40/50).".into()),
|
||||
("vfg_quality", "VFG quality", "How much work NVIDIA VFG puts into each frame.".into()),
|
||||
("motion", "Motion detail", "How finely RIFE tracks movement. Half is about 40% faster and a little softer.".into()),
|
||||
("ai_engine", "AI engine", "TensorRT is about 12% faster at full motion detail; its first start takes a minute or two.".into()),
|
||||
("steady_hud", "Steady HUD", "Keeps still parts of the picture (map, health bar) exactly as the game drew them.".into()),
|
||||
("framegen_multiplier", "Frame multiplier", "Frames shown for each one the game draws: 2× makes 30 fps 60 and 60 fps 120. Needs a display that fast; more needs a faster card.".into()),
|
||||
("multiplier_custom", "Custom multiplier", "Any whole number from 2 to 10. Enter to type it, Enter to save; empty goes back to the choice above.".into()),
|
||||
("game_fps", "Game frame rate", "Auto works it out as the game plays. 60 fps: the multiplier works from 60 (2× is 120 fps). 30 fps: every other frame is new.".into()),
|
||||
("#", "ENGINE WINDOW", String::new()),
|
||||
("vsync", "VSync", "Sync the engine's picture to the display (G-Sync/FreeSync).".into()),
|
||||
("watermark", "Watermark", "The \"summit - git.molberg.cloud/alex/summit\" line in a corner of the picture.".into()),
|
||||
("#", "ENHANCE", String::new()),
|
||||
("enhance", "Enhance on Play", "Play also runs Summit's engine on the game's window: frame generation and the upscaler, with the engine settings in the other sections.".into()),
|
||||
("#", "LAUNCH", String::new()),
|
||||
("launch_args", "Launch arguments", "Added after the game's command, e.g. -windowed -dx11. Quotes group words. Enter to edit, Enter to save.".into()),
|
||||
("env", "Environment", "KEY=VALUE pairs, e.g. MANGOHUD=1 PROTON_ENABLE_NVAPI=1. A game's keys win over the defaults'. Enter to edit.".into()),
|
||||
@@ -431,34 +325,10 @@ pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
// a window belongs to one game: not a default
|
||||
if cx.defaults && (key == "window" || label == "GAME WINDOW") { continue; }
|
||||
if key == "#" { rows.push(header(label)); continue; }
|
||||
let skip = match key {
|
||||
"fsr_sharpness" => !matches!(up, "" | "fsr"),
|
||||
"vsr_quality" => !matches!(up, "rtx-vsr" | "vsr"),
|
||||
"vfg_quality" => eff.model.as_deref() != Some("vfg") || eff.framegen == "none",
|
||||
"model" | "framegen_multiplier" | "multiplier_custom" | "game_fps" | "steady_hud" => eff.framegen == "none",
|
||||
"motion" | "ai_engine" => !rife,
|
||||
_ => false,
|
||||
};
|
||||
if skip && !cx.own.has(key) && key != "multiplier_custom" { continue; }
|
||||
if skip && key == "multiplier_custom" { continue; }
|
||||
if key == "output_res_custom" {
|
||||
let text = custom_res(cx.own).unwrap_or_default();
|
||||
let placeholder = match eff.output_res.as_deref() { Some(r) => format!("Now {}", res_label(r)), None => "e.g. 2560x1080".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text, placeholder, own: !cx.defaults && custom_res(cx.own).is_some() });
|
||||
continue;
|
||||
}
|
||||
let own = !cx.defaults && match key {
|
||||
"resolution" => cx.own.width.is_some() || cx.own.height.is_some(),
|
||||
"framegen_multiplier" => cx.own.framegen_multiplier.is_some() || cx.own.target_hz.is_some(),
|
||||
"multiplier_custom" => custom_multiplier(cx.own).is_some(),
|
||||
k => cx.own.has(k),
|
||||
};
|
||||
if key == "multiplier_custom" {
|
||||
let text = custom_multiplier(cx.own).map(|m| m.to_string()).unwrap_or_default();
|
||||
let placeholder = match eff.multiplier() { Some(m) => format!("Now {}", multiplier_label(m)), None => "e.g. 7".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text, placeholder, own });
|
||||
continue;
|
||||
}
|
||||
if key == "window" {
|
||||
let placeholder = match cx.auto_window { Some(q) => format!("Automatic: {q}"), None => "Automatic: asks you to pick it".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text: text_of(cx.own, key).unwrap_or_default(), placeholder, own });
|
||||
@@ -477,15 +347,8 @@ pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
let cur = if cx.defaults { cur.filter(|v| !v.is_empty()) } else { cur };
|
||||
let value = match ch.iter().position(|c| c.0 == cur || (key == "refresh_hz" && c.0.as_deref().zip(cur.as_deref()).is_some_and(|(a, b)| a.parse::<f32>().ok().zip(b.parse::<f32>().ok()).is_some_and(|(a, b)| same_rate(a, b))))) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
// a value the list doesn't have: a custom multiplier, or something a newer Summit (or the CLI) wrote
|
||||
let l = match (key, cur.as_deref().and_then(|c| c.parse::<u8>().ok())) {
|
||||
("framegen_multiplier", Some(m)) => format!("{} (custom)", multiplier_label(m)),
|
||||
("output_res", _) if cur.as_deref().is_some_and(|c| !c.is_empty()) => format!("{} (custom)", res_label(cur.as_deref().unwrap_or_default())),
|
||||
_ => cur.clone().unwrap_or_default(),
|
||||
};
|
||||
ch.push((cur, l)); ch.len() - 1
|
||||
}
|
||||
// a value the list doesn't have (something a newer Summit, or the CLI, wrote)
|
||||
None => { let l = cur.clone().unwrap_or_default(); ch.push((cur, l)); ch.len() - 1 }
|
||||
};
|
||||
rows.push(EditRow { key, kind: RowKind::Choice, label: label.into(), hint, options: ch.iter().map(|c| c.1.clone()).collect(), value, text: String::new(), placeholder: String::new(), own });
|
||||
}
|
||||
@@ -510,24 +373,6 @@ pub fn edit_text(own: &Layer, key: &str, text: &str) -> Result<Layer, String> {
|
||||
"launch_args" => l.launch_args = if t.is_empty() { None } else { Some(summit_core::profile::split_args(t)) },
|
||||
"env" => l.env = if t.is_empty() { None } else { Some(summit_core::profile::parse_env_line(t)?) },
|
||||
"window" => l.window = if t.is_empty() { None } else { Some(t.to_string()) },
|
||||
"output_res_custom" => {
|
||||
if t.is_empty() {
|
||||
if custom_res(&l).is_some() { l.output_res = None; } // back to the choice above
|
||||
} else {
|
||||
let (w, h) = summit_core::profile::parse_res(t).ok_or_else(|| "A size like 2560x1440, from 320x240 to 7680x4320".to_string())?;
|
||||
l.output_res = Some(format!("{w}x{h}"));
|
||||
}
|
||||
}
|
||||
"multiplier_custom" => {
|
||||
if t.is_empty() {
|
||||
if custom_multiplier(&l).is_some() { l.framegen_multiplier = None; } // back to the choice above
|
||||
} else {
|
||||
let m = t.trim_end_matches(['x', 'X', '×']).trim().parse::<u8>().ok().filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m))
|
||||
.ok_or_else(|| "The multiplier is a whole number from 2 to 10".to_string())?;
|
||||
l.framegen_multiplier = Some(m);
|
||||
l.target_hz = None;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(l)
|
||||
@@ -725,9 +570,11 @@ mod tests {
|
||||
let q = set(&l, &base, true, &o, "monitor", "Don't switch");
|
||||
assert_eq!((q.monitor, q.width, q.refresh_hz), (None, None, None));
|
||||
// the defaults store nothing for their first choice
|
||||
let l = set(&Layer::default(), &base, true, &o, "upscaler", "AMD FSR 1");
|
||||
assert_eq!(l.upscaler.as_deref(), Some("fsr"));
|
||||
assert_eq!(set(&l, &base, true, &o, "upscaler", "Engine setting (FSR)").upscaler, None);
|
||||
let l = set(&Layer::default(), &base, true, &o, "window_mode", "Borderless window");
|
||||
assert_eq!(l.window_mode.as_deref(), Some("borderless"));
|
||||
assert_eq!(set(&l, &base, true, &o, "window_mode", "As the game opens it").window_mode, None);
|
||||
// the engine's settings are not rows here any more: they come from the engine's registry (rows.rs)
|
||||
assert!(!rows.iter().any(|r| matches!(r.key, "upscaler" | "framegen" | "model" | "vsync")));
|
||||
}
|
||||
#[test]
|
||||
fn a_game_follows_the_defaults_or_overrides_them() {
|
||||
@@ -736,8 +583,6 @@ mod tests {
|
||||
let base = summit_core::profile::resolve(&[&d]);
|
||||
let g = Layer::default();
|
||||
let rows = edit_rows(&cx(&g, &base, false, &o));
|
||||
let up = row(&rows, "upscaler");
|
||||
assert_eq!((up.options[0].as_str(), up.value, up.own), ("Default · AMD FSR 1", 0, false));
|
||||
assert_eq!(row(&rows, "window_mode").options[0], "Default · Borderless window");
|
||||
assert_eq!(row(&rows, "monitor").options[0], "Default · Virtual-1");
|
||||
assert_eq!(row(&rows, "enhance").options[0], "Default · On");
|
||||
@@ -745,17 +590,13 @@ mod tests {
|
||||
let g2 = set(&g, &base, false, &o, "monitor", "Don't switch");
|
||||
assert_eq!(g2.monitor.as_deref(), Some(""));
|
||||
assert_eq!(summit_core::profile::resolve(&[&d, &g2]).monitor, None);
|
||||
let g3 = set(&g, &base, false, &o, "upscaler", "NVIDIA RTX VSR");
|
||||
let g3 = set(&g, &base, false, &o, "window_mode", "Windowed");
|
||||
let rows = edit_rows(&cx(&g3, &base, false, &o));
|
||||
assert!(row(&rows, "upscaler").own);
|
||||
assert!(rows.iter().any(|r| r.key == "vsr_quality") && !rows.iter().any(|r| r.key == "fsr_sharpness"));
|
||||
assert!(row(&rows, "window_mode").own);
|
||||
// back to Default: left out of the file again
|
||||
assert!(set(&g3, &base, false, &o, "upscaler", "Default · AMD FSR 1").is_empty());
|
||||
assert!(set(&g3, &base, false, &o, "window_mode", "Default · Borderless window").is_empty());
|
||||
let g4 = set(&g, &base, false, &o, "enhance", "Off");
|
||||
assert_eq!(g4.enhance, Some(false));
|
||||
// engine on/off settings: Default, Off or On on a game
|
||||
assert_eq!(row(&edit_rows(&cx(&g, &base, false, &o)), "vsync").options, vec!["Default · Engine setting", "Off", "On"]);
|
||||
assert_eq!(set(&g, &base, false, &o, "vsync", "Off").vsync, Some(false));
|
||||
}
|
||||
#[test]
|
||||
fn a_game_on_its_own_monitor_offers_that_monitors_modes() {
|
||||
@@ -768,19 +609,6 @@ mod tests {
|
||||
assert_eq!((g.width, g.height), (Some(1280), Some(720)));
|
||||
}
|
||||
#[test]
|
||||
fn frame_generation_rows_follow_the_choices() {
|
||||
let o = outs();
|
||||
let base = Profile::default();
|
||||
let l = set(&Layer::default(), &base, true, &o, "framegen", "Off");
|
||||
let rows = edit_rows(&cx(&l, &base, true, &o));
|
||||
assert!(!rows.iter().any(|r| r.key == "model" || r.key == "motion"));
|
||||
let l = set(&Layer::default(), &base, true, &o, "model", "NVIDIA VFG");
|
||||
let rows = edit_rows(&cx(&l, &base, true, &o));
|
||||
assert!(rows.iter().any(|r| r.key == "vfg_quality") && !rows.iter().any(|r| r.key == "motion"));
|
||||
let l = set(&l, &base, true, &o, "vfg_quality", "High");
|
||||
assert_eq!(l.vfg_quality.as_deref(), Some("high"));
|
||||
}
|
||||
#[test]
|
||||
fn text_rows_for_arguments_and_environment() {
|
||||
let d = Layer { env: Some([("MANGOHUD".to_string(), "1".to_string())].into()), ..Default::default() };
|
||||
let base = summit_core::profile::resolve(&[&d]);
|
||||
@@ -821,52 +649,4 @@ mod tests {
|
||||
assert_eq!(window_wait("[window] waiting for a window matching 'class:a' (up to 300 s)\n"), WindowWait::Waiting { asking: false });
|
||||
assert_eq!(window_wait("[window] waiting for a window matching 'class:a'\nError: no window matches 'class:a' after 300 s\n"), WindowWait::GaveUp);
|
||||
}
|
||||
#[test]
|
||||
fn frame_multiplier_rows() {
|
||||
let base = Profile { framegen: "rife".into(), target_hz: Some(120), ..Default::default() }; // the defaults: 4x
|
||||
let g = Layer::default();
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
let r = row(&rows, "framegen_multiplier");
|
||||
assert_eq!(r.options[r.value], "Default · 4×");
|
||||
assert!(r.options.contains(&"8×".to_string()));
|
||||
// picking 6x: the game's own, and no older output rate left beside it
|
||||
let six = r.options.iter().position(|o| o.starts_with("6×")).unwrap();
|
||||
let g = edit_apply(&cx(&g, &base, false, &[]), "framegen_multiplier", six);
|
||||
assert_eq!((g.framegen_multiplier, g.target_hz), (Some(6), None));
|
||||
// a custom 7x: typed, shown as custom in the choice row, cleared again with an empty line
|
||||
let g = edit_text(&g, "multiplier_custom", " 7x ").unwrap();
|
||||
assert_eq!(g.framegen_multiplier, Some(7));
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
assert_eq!(row(&rows, "multiplier_custom").text, "7");
|
||||
let r = row(&rows, "framegen_multiplier");
|
||||
assert_eq!(r.options[r.value], "7× (custom)");
|
||||
assert!(edit_text(&g, "multiplier_custom", "11").is_err() && edit_text(&g, "multiplier_custom", "1.5").is_err());
|
||||
assert_eq!(edit_text(&g, "multiplier_custom", "").unwrap().framegen_multiplier, None);
|
||||
// frame generation off: neither row
|
||||
let off = Profile { framegen: "none".into(), ..Default::default() };
|
||||
let rows = edit_rows(&cx(&Layer::default(), &off, false, &[]));
|
||||
assert!(!rows.iter().any(|r| r.key == "framegen_multiplier" || r.key == "multiplier_custom"));
|
||||
}
|
||||
#[test]
|
||||
fn game_frame_rate_and_output_resolution_rows() {
|
||||
let base = Profile { framegen: "rife".into(), ..Default::default() };
|
||||
let g = Layer::default();
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
let fps = row(&rows, "game_fps");
|
||||
let sixty = fps.options.iter().position(|o| o == "60 fps").unwrap();
|
||||
assert_eq!(edit_apply(&cx(&g, &base, false, &[]), "game_fps", sixty).game_fps.as_deref(), Some("60"));
|
||||
let r = row(&rows, "output_res");
|
||||
assert!(r.options.contains(&"1440p (2560 × 1440)".to_string()) && r.options.contains(&"4K (3840 × 2160)".to_string()));
|
||||
let k = r.options.iter().position(|o| o.starts_with("1440p")).unwrap();
|
||||
assert_eq!(edit_apply(&cx(&g, &base, false, &[]), "output_res", k).output_res.as_deref(), Some("2560x1440"));
|
||||
// any size, typed: shown as custom in the choice row
|
||||
let g = edit_text(&g, "output_res_custom", " 2560 x 1080 ").unwrap();
|
||||
assert_eq!(g.output_res.as_deref(), Some("2560x1080"));
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
assert_eq!(row(&rows, "output_res_custom").text, "2560x1080");
|
||||
let r = row(&rows, "output_res");
|
||||
assert_eq!(r.options[r.value], "2560 × 1080 (custom)");
|
||||
assert!(edit_text(&g, "output_res_custom", "99x99").is_err() && edit_text(&g, "output_res_custom", "big").is_err());
|
||||
assert_eq!(edit_text(&g, "output_res_custom", "").unwrap().output_res, None);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ mod accounts;
|
||||
mod art;
|
||||
mod data;
|
||||
mod pad;
|
||||
mod pane;
|
||||
mod rows;
|
||||
mod shot;
|
||||
|
||||
use slint::{ComponentHandle, Image, Model, ModelRc, SharedString, VecModel};
|
||||
@@ -40,9 +42,14 @@ pub struct App {
|
||||
pub headless: bool,
|
||||
base_scale: Cell<f32>,
|
||||
fullscreen: Cell<bool>,
|
||||
save_timer: slint::Timer,
|
||||
/// What the profile editor is editing, if it is open.
|
||||
editing: RefCell<Option<Editing>>,
|
||||
/// The settings pane (the Settings page, or a game's profile): pane.rs.
|
||||
pane: RefCell<pane::Pane>,
|
||||
/// The engine's settings registry, asked for once (None: not asked yet).
|
||||
registry: RefCell<Option<Result<summit_core::registry::Registry, String>>>,
|
||||
rows_model: Rc<VecModel<SRow>>,
|
||||
quick_model: Rc<VecModel<SRow>>,
|
||||
/// The comparisons the Compare dialog lists, as the engine's --compare takes them, in the list's order.
|
||||
cmp_specs: RefCell<Vec<String>>,
|
||||
/// Folders given on the command line, scanned again when the library reloads.
|
||||
folders: Vec<PathBuf>,
|
||||
/// Bumped when the library reloads: a cover loaded for the old list is dropped, not put on the wrong row.
|
||||
@@ -111,17 +118,6 @@ struct Playing {
|
||||
#[derive(Clone)]
|
||||
enum AddAction { Capture(console::CaptureDevice), Remote(console::Registered), Open(String), Refresh, LinkInChiaki }
|
||||
|
||||
/// The monitors listed when the profile editor opened, or why there is no list.
|
||||
type Outputs = Result<Vec<display::Output>, String>;
|
||||
|
||||
/// The profile editor: a game's own settings (an index into the entries) or the launcher's defaults (None), the
|
||||
/// monitors listed when it opened, and the setting behind each row now on screen ("" for a header).
|
||||
struct Editing { game: Option<usize>, outs: Outputs, keys: Vec<&'static str> }
|
||||
|
||||
/// The defaults page's quick choices (Settings > Enhance defaults), as stored in the defaults layer.
|
||||
const QUICK_UPSCALERS: [&str; 4] = ["", "none", "fsr", "rtx-vsr"];
|
||||
const QUICK_FRAMEGENS: [&str; 3] = ["", "none", "rife"];
|
||||
|
||||
impl App {
|
||||
// Art the user set in Summit first, then the launcher's own (artwork.rs says where, per source).
|
||||
fn cover_path(&self, e: &Entry) -> Option<PathBuf> {
|
||||
@@ -285,8 +281,10 @@ impl App {
|
||||
pub fn open_detail(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
let own = profile::load_layer(&e.id).unwrap_or_default();
|
||||
let own_n = profile::KEYS.iter().filter(|k| own.has(k)).count();
|
||||
let own_n = profile::KEYS.iter().filter(|k| **k != "engine" && own.has(k)).count() + own.engine.as_ref().map_or(0, |m| m.len());
|
||||
let p = data::profile_summary(&profile::load(&e.id).unwrap_or_default(), own_n);
|
||||
// the upscaler and frame generation in use: the engine's saved settings with the profile's on top
|
||||
let engine_lines = self.engine_summary(&e).unwrap_or_else(|| (p.upscaler.clone(), p.framegen.clone()));
|
||||
let con = if e.source == Source::Console { self.console_of(&e.id) } else { None };
|
||||
let console_play = con.as_ref().map(|c| self.console_play(c));
|
||||
let st = self.state.borrow();
|
||||
@@ -315,11 +313,12 @@ impl App {
|
||||
console::Link::RemotePlay { nickname, .. } => format!("chiaki-ng · {nickname}"),
|
||||
console::Link::Capture { device } => format!("capture device · {device}"),
|
||||
}).or(e.path.clone()).unwrap_or_default()).into(),
|
||||
monitor: p.monitor.into(), mode: p.mode.into(), upscaler: p.upscaler.into(), framegen: p.framegen.into(), window: p.window.into(), profile_set: p.set,
|
||||
profile_note: if own_n == 0 { "Follows the launcher's defaults (Settings).".into() } else { format!("{own_n} setting{} of its own; the rest from the launcher's defaults (Settings).", if own_n == 1 { "" } else { "s" }).into() },
|
||||
monitor: p.monitor.into(), mode: p.mode.into(), upscaler: engine_lines.0.into(), framegen: engine_lines.1.into(), window: p.window.into(), profile_set: p.set,
|
||||
profile_note: if own_n == 0 { "Follows the global settings (Settings).".into() } else { format!("{own_n} setting{} of its own; the rest follow the global settings (Settings).", if own_n == 1 { "" } else { "s" }).into() },
|
||||
play_label: label.into(), play_note: play_note.into(), can_play: can,
|
||||
enhance: prof.enhance && can_enhance, can_enhance, enhance_note: enhance_note.into(),
|
||||
has_account, account, account_note: account_note.into(),
|
||||
compare_note: self.compare_state(&e, can_enhance).1.into(),
|
||||
});
|
||||
drop(st);
|
||||
self.want_cover(idx as usize);
|
||||
@@ -386,14 +385,17 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn play(&self, idx: i32) {
|
||||
fn play(&self, idx: i32) { self.play_with(idx, None); }
|
||||
|
||||
/// Play; with `compare` (the engine's `--compare`), Enhance is on for this start whatever the profile says.
|
||||
fn play_with(&self, idx: i32, compare: Option<String>) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
if e.source == Source::Heuristic { return self.add_game(idx); }
|
||||
// Checked for this entry: Play on Home's hero is not the game whose page was opened last.
|
||||
let prof = profile::load(&e.id).unwrap_or_default();
|
||||
let enhance = prof.enhance && self.enhance_available(&e).0;
|
||||
let enhance = (prof.enhance || compare.is_some()) && self.enhance_available(&e).0;
|
||||
let argv = match launch::plan_with(&e, self.cli().as_deref(), enhance, prof.window.as_deref()) {
|
||||
launch::Plan::Run(argv) => argv,
|
||||
launch::Plan::Run(argv) => match &compare { Some(c) => launch::with_compare(argv, c), None => argv },
|
||||
launch::Plan::Unsupported(why) => return self.toast(format!("Cannot start {}: {why}", e.title)),
|
||||
};
|
||||
// Said before it starts: `summit run` changes the account Steam signs in with.
|
||||
@@ -429,7 +431,7 @@ impl App {
|
||||
else if install { format!("Asked Steam to install {}", e.title) }
|
||||
else { match e.source { Source::Steam => "Opening through Steam".to_string(), Source::Lutris => "Opening through Lutris".into(), Source::Heroic => "Opening through Heroic".into(), _ => "Opening".into() } };
|
||||
let how = match &switching { Some(n) => format!("{n}, then {}{}", how[..1].to_lowercase(), &how[1..]), None => how };
|
||||
let how = if enhance { format!("{how}, with Enhance") } else { how };
|
||||
let how = if compare.is_some() { format!("{how}, with Enhance and the comparison") } else if enhance { format!("{how}, with Enhance") } else { how };
|
||||
// An install is Steam's dialog, not a game: the launcher stays as it is. A game takes over: the
|
||||
// launcher shows a loading screen, then "now playing", and takes no input until it is gone.
|
||||
let seq = self.play_seq.get() + 1;
|
||||
@@ -1094,125 +1096,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn open_profile(&self, idx: i32) {
|
||||
if idx < 0 || idx as usize >= self.entries.borrow().len() { return; }
|
||||
self.open_editor(Some(idx as usize));
|
||||
}
|
||||
|
||||
/// Settings > Default launch profile: the same editor, on the defaults every game follows.
|
||||
fn open_defaults(&self) { self.open_editor(None); }
|
||||
|
||||
fn open_editor(&self, game: Option<usize>) {
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
*self.editing.borrow_mut() = Some(Editing { game, outs: display::outputs(s, d), keys: vec![] });
|
||||
let lib = self.ui.global::<Lib>();
|
||||
lib.set_editor_defaults(game.is_none());
|
||||
lib.set_editor_typing(false);
|
||||
self.fill_editor();
|
||||
// the first row that is a setting, not a header
|
||||
let first = self.editing.borrow().as_ref().and_then(|ed| ed.keys.iter().position(|k| !k.is_empty())).unwrap_or(0);
|
||||
lib.set_editor_row(first as i32);
|
||||
lib.set_editor_open(true);
|
||||
}
|
||||
|
||||
/// The id of the profile being edited.
|
||||
fn editing_id(&self) -> Option<String> {
|
||||
let ed = self.editing.borrow();
|
||||
let ed = ed.as_ref()?;
|
||||
match ed.game { Some(i) => self.entries.borrow().get(i).map(|e| e.id.clone()), None => Some(profile::DEFAULT_ID.to_string()) }
|
||||
}
|
||||
|
||||
fn fill_editor(&self) {
|
||||
let Some(id) = self.editing_id() else { return };
|
||||
let mut ed = self.editing.borrow_mut();
|
||||
let Some(ed) = ed.as_mut() else { return };
|
||||
let own = profile::load_layer(&id).unwrap_or_else(|e| { self.toast(format!("Could not read the profile: {e}")); profile::Layer::default() });
|
||||
let base = if ed.game.is_none() { profile::Profile::default() } else { profile::load_defaults().unwrap_or_default() };
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
let tool = match (s, d) {
|
||||
(display::Session::X11, _) => "xrandr", (_, display::Desktop::Kde) => "kscreen-doctor", (_, display::Desktop::Wlroots) => "wlr-randr", _ => "",
|
||||
};
|
||||
let placer = summit_core::winmode::backend(s, d, summit_core::doctor::on_path);
|
||||
let placer = match &placer { Ok(summit_core::winmode::Backend::KWin) => Ok("a KWin script"), Ok(_) => Ok("wmctrl"), Err(e) => Err(e.as_str()) };
|
||||
let (list, err) = match &ed.outs { Ok(o) => (o.as_slice(), None), Err(e) => (&[][..], Some(e.as_str())) };
|
||||
let auto = ed.game.and_then(|i| self.entries.borrow().get(i).and_then(launch::window_query));
|
||||
let cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: err, tool, placer, auto_window: auto.as_deref() };
|
||||
let rows = data::edit_rows(&cx);
|
||||
ed.keys = rows.iter().map(|r| r.key).collect();
|
||||
let own_n = rows.iter().filter(|r| r.own).count();
|
||||
let rows: Vec<PRow> = rows.into_iter().map(|r| PRow {
|
||||
label: r.label.into(), hint: r.hint.into(), value: r.value as i32,
|
||||
options: ModelRc::new(VecModel::from(r.options.into_iter().map(SharedString::from).collect::<Vec<_>>())),
|
||||
kind: match r.kind { data::RowKind::Choice => 0, data::RowKind::Text => 1, data::RowKind::Header => 2 },
|
||||
text: r.text.into(), placeholder: r.placeholder.into(), own: r.own,
|
||||
}).collect();
|
||||
let lib = self.ui.global::<Lib>();
|
||||
lib.set_prof_rows(ModelRc::new(VecModel::from(rows)));
|
||||
lib.set_prof_file(profile::file(&id).map(|f| tilde(&f)).unwrap_or_default().into());
|
||||
let title = match ed.game { Some(i) => self.entries.borrow().get(i).map(|e| e.title.clone()).unwrap_or_default(), None => "Launcher defaults".into() };
|
||||
lib.set_prof_title(title.into());
|
||||
lib.set_prof_note(match ed.game {
|
||||
None => "Every game uses these unless it sets its own on its page (Profile).".into(),
|
||||
Some(_) if own_n == 0 => "Every setting follows the launcher's defaults.".into(),
|
||||
Some(_) => format!("{own_n} setting{} of its own (marked); the rest follow the launcher's defaults.", if own_n == 1 { "" } else { "s" }).into(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Save a changed layer, then show it: the editor's rows, the game's page, the settings page's quick choices.
|
||||
fn save_edit(&self, id: &str, new: &profile::Layer) {
|
||||
if let Err(err) = profile::save_layer(id, new) { return self.toast(format!("Could not save the profile: {err}")); }
|
||||
let game = self.editing.borrow().as_ref().and_then(|e| e.game);
|
||||
self.fill_editor();
|
||||
match game { Some(i) => self.open_detail(i as i32), None => self.load_defaults_into_ui() }
|
||||
}
|
||||
|
||||
fn prof_set(&self, row: i32, value: i32) {
|
||||
let Some(id) = self.editing_id() else { return };
|
||||
let Some(key) = self.editing.borrow().as_ref().and_then(|e| e.keys.get(row.max(0) as usize).copied()).filter(|k| !k.is_empty()) else { return };
|
||||
let own = profile::load_layer(&id).unwrap_or_default();
|
||||
let new = {
|
||||
let ed = self.editing.borrow();
|
||||
let Some(ed) = ed.as_ref() else { return };
|
||||
let base = if ed.game.is_none() { profile::Profile::default() } else { profile::load_defaults().unwrap_or_default() };
|
||||
let list = ed.outs.as_ref().map(|o| o.as_slice()).unwrap_or(&[]);
|
||||
let cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: None, tool: "", placer: Ok(""), auto_window: None };
|
||||
data::edit_apply(&cx, key, value.max(0) as usize)
|
||||
};
|
||||
if new != own { self.save_edit(&id, &new); }
|
||||
}
|
||||
|
||||
fn prof_text(&self, row: i32, text: &str) {
|
||||
let Some(id) = self.editing_id() else { return };
|
||||
let Some(key) = self.editing.borrow().as_ref().and_then(|e| e.keys.get(row.max(0) as usize).copied()) else { return };
|
||||
let own = profile::load_layer(&id).unwrap_or_default();
|
||||
match data::edit_text(&own, key, text) {
|
||||
Ok(new) if new != own => self.save_edit(&id, &new),
|
||||
Ok(_) => {}
|
||||
Err(e) => { self.toast(format!("Not saved: {e}")); self.fill_editor(); }
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget everything the profile being edited sets (a game follows the defaults again; the defaults go back to
|
||||
/// the built-in values).
|
||||
fn prof_reset(&self) {
|
||||
let Some(id) = self.editing_id() else { return };
|
||||
self.save_edit(&id, &profile::Layer::default());
|
||||
self.toast(if id == profile::DEFAULT_ID { "Defaults back to Summit's own".to_string() } else { "This game follows the launcher's defaults again".to_string() });
|
||||
}
|
||||
|
||||
/// The settings page's quick choices and summary line, from the defaults layer.
|
||||
fn load_defaults_into_ui(&self) {
|
||||
let p = self.ui.global::<Prefs>();
|
||||
let l = profile::load_layer(profile::DEFAULT_ID).unwrap_or_default();
|
||||
let d = profile::resolve(&[&l]);
|
||||
let up = if d.upscaler == "vsr" { "rtx-vsr" } else { d.upscaler.as_str() };
|
||||
p.set_upscaler(QUICK_UPSCALERS.iter().position(|u| *u == up).unwrap_or(0) as i32);
|
||||
p.set_framegen(QUICK_FRAMEGENS.iter().position(|u| *u == d.framegen).unwrap_or(0) as i32);
|
||||
let s = data::profile_summary(&d, 0);
|
||||
let mode = if s.mode == "Default" { String::new() } else { format!(" at {}", s.mode) };
|
||||
p.set_defaults_note(format!("Monitor {}{mode} · window {} · Enhance {} · {} + {}", s.monitor, s.window, if d.enhance { "on" } else { "off" }, s.upscaler, s.framegen).into());
|
||||
}
|
||||
|
||||
fn refresh_row(&self, idx: usize) {
|
||||
let old = self.games.row_data(idx);
|
||||
let row = self.row(&self.entries.borrow()[idx], old.as_ref());
|
||||
@@ -1244,68 +1127,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- settings ----
|
||||
fn load_settings_into_ui(&self) {
|
||||
let s = self.settings.borrow();
|
||||
self.ui.set_layout(s.layout_index() as i32);
|
||||
self.ui.set_theme(self.theme_keys.iter().position(|k| *k == s.theme).unwrap_or(0) as i32);
|
||||
self.ui.set_anim_speed(s.anim_speed);
|
||||
self.ui.set_anim_style(s.anim_style_index() as i32);
|
||||
let p = self.ui.global::<Prefs>();
|
||||
p.set_scale(nearest(prefs::UI_SCALES, s.ui_scale) as i32);
|
||||
// the row's choices: Off, then the lengths
|
||||
p.set_replay(if s.replay_seconds == 0 { 0 } else { prefs::CLIP_LENGTHS.iter().position(|c| *c == s.replay_seconds).unwrap_or(2) as i32 + 1 });
|
||||
p.set_clip(prefs::CLIP_LENGTHS.iter().position(|c| *c == s.clip_seconds).unwrap_or(1) as i32);
|
||||
p.set_clip_lengths(ModelRc::new(VecModel::from(prefs::CLIP_LENGTHS.iter().map(|c| prefs::clip_label(*c).into()).collect::<Vec<SharedString>>())));
|
||||
let keys = s.overlay_key_choices();
|
||||
p.set_overlay_key(keys.iter().position(|k| *k == s.overlay_key).unwrap_or(0) as i32);
|
||||
p.set_overlay_keys(ModelRc::new(VecModel::from(keys.into_iter().map(SharedString::from).collect::<Vec<SharedString>>())));
|
||||
p.set_scales(ModelRc::new(VecModel::from(prefs::UI_SCALES.iter().map(|c| format!("{:.0}%", c * 100.0).into()).collect::<Vec<SharedString>>())));
|
||||
p.set_file(prefs::path().map(|f| tilde(&f)).unwrap_or_default().into());
|
||||
drop(s);
|
||||
self.load_defaults_into_ui();
|
||||
}
|
||||
|
||||
fn settings_from_ui(&self) -> prefs::UiSettings {
|
||||
let p = self.ui.global::<Prefs>();
|
||||
let pick = |v: i32, n: usize| (v.max(0) as usize).min(n - 1);
|
||||
prefs::UiSettings {
|
||||
layout: prefs::LAYOUTS[pick(self.ui.get_layout(), 3)].into(),
|
||||
theme: self.theme_keys.get(self.ui.get_theme().max(0) as usize).cloned().unwrap_or_else(|| "midnight".into()),
|
||||
anim_speed: self.ui.get_anim_speed(),
|
||||
anim_style: prefs::ANIM_STYLES[pick(self.ui.get_anim_style(), 3)].into(),
|
||||
ui_scale: prefs::UI_SCALES[pick(p.get_scale(), prefs::UI_SCALES.len())],
|
||||
replay_seconds: match pick(p.get_replay(), 7) { 0 => 0, r => prefs::CLIP_LENGTHS[r - 1] },
|
||||
clip_seconds: prefs::CLIP_LENGTHS[pick(p.get_clip(), 6)],
|
||||
// the row's choices are the usual keys, then the saved one when it was set by hand (ui.toml)
|
||||
overlay_key: { let keys = self.settings.borrow().overlay_key_choices(); keys[pick(p.get_overlay_key(), keys.len())].clone() },
|
||||
shortcuts: prefs::load().shortcuts,
|
||||
}.sanitized()
|
||||
}
|
||||
|
||||
fn settings_changed(&self) {
|
||||
let new = self.settings_from_ui();
|
||||
let scale_changed = new.ui_scale != self.settings.borrow().ui_scale;
|
||||
if new != *self.settings.borrow() {
|
||||
*self.settings.borrow_mut() = new;
|
||||
if self.headless { self.save_settings(); } else {
|
||||
// a slider drag changes the value many times a second: write once it settles
|
||||
self.save_timer.start(slint::TimerMode::SingleShot, std::time::Duration::from_millis(350), || with_app(|a| a.save_settings()));
|
||||
}
|
||||
}
|
||||
if scale_changed { self.apply_scale(); }
|
||||
let p = self.ui.global::<Prefs>();
|
||||
let (up, fg) = (QUICK_UPSCALERS[p.get_upscaler().clamp(0, 3) as usize], QUICK_FRAMEGENS[p.get_framegen().clamp(0, 2) as usize]);
|
||||
let d = profile::load_layer(profile::DEFAULT_ID).unwrap_or_default();
|
||||
let enc = |v: &str| if v.is_empty() { None } else { Some(v.to_string()) };
|
||||
if d.upscaler.clone().filter(|v| !v.is_empty()) != enc(up) || d.framegen.clone().filter(|v| !v.is_empty()) != enc(fg) {
|
||||
match profile::update_layer(profile::DEFAULT_ID, |l| { l.upscaler = enc(up); l.framegen = enc(fg); }) {
|
||||
Ok(_) => self.load_defaults_into_ui(),
|
||||
Err(err) => self.toast(format!("Could not save the default profile: {err}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- settings (the rows are in pane.rs) ----
|
||||
fn save_settings(&self) {
|
||||
if let Err(err) = prefs::save(&self.settings.borrow()) { self.toast(format!("Could not save settings: {err}")); }
|
||||
}
|
||||
@@ -1338,9 +1160,6 @@ fn raise_window() {
|
||||
});
|
||||
}
|
||||
|
||||
fn nearest(all: &[f32], v: f32) -> usize {
|
||||
(0..all.len()).min_by(|a, b| (all[*a] - v).abs().total_cmp(&(all[*b] - v).abs())).unwrap_or(0)
|
||||
}
|
||||
/// ~/.cache/summit/last-run.log: the output of the last game started from the launcher.
|
||||
fn dirs_log() -> Option<PathBuf> {
|
||||
let d = std::env::var_os("XDG_CACHE_HOME").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))?.join("summit");
|
||||
@@ -1379,7 +1198,8 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
requested: Default::default(), loaded: Default::default(), keep: Default::default(),
|
||||
backdrop_seq: Cell::new(0), backdrop_for: Cell::new(-1),
|
||||
settings: RefCell::new(prefs::load()),
|
||||
theme_keys, headless, base_scale: Cell::new(1.0), fullscreen: Cell::new(false), save_timer: slint::Timer::default(), editing: RefCell::new(None),
|
||||
theme_keys, headless, base_scale: Cell::new(1.0), fullscreen: Cell::new(false), pane: Default::default(), registry: Default::default(),
|
||||
rows_model: Rc::new(VecModel::default()), quick_model: Rc::new(VecModel::default()), cmp_specs: Default::default(),
|
||||
folders: scan_folders, gen: Cell::new(0),
|
||||
add_actions: Default::default(), remote_found: Default::default(), discover_seq: Cell::new(0), chiaki_tap: Default::default(),
|
||||
steam_accounts: Default::default(),
|
||||
@@ -1398,7 +1218,7 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
_ => "OpenGL renderer (FemtoVG), software fallback".into(),
|
||||
}.into());
|
||||
app.fill_static();
|
||||
app.load_settings_into_ui();
|
||||
app.apply_ui_settings();
|
||||
|
||||
lib.on_want_cover(|i| with_app(|a| a.want_cover(i.max(0) as usize)));
|
||||
lib.on_focus_game(|i| with_app(|a| a.focus_game(i)));
|
||||
@@ -1406,7 +1226,6 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
lib.on_open_detail(|i| with_app(|a| a.open_detail(i)));
|
||||
lib.on_play(|i| with_app(|a| a.play(i)));
|
||||
lib.on_toggle_pin(|i| with_app(|a| a.toggle_pin(i)));
|
||||
lib.on_settings_changed(|| with_app(|a| a.settings_changed()));
|
||||
lib.on_toggle_fullscreen(|| with_app(|a| a.toggle_fullscreen()));
|
||||
lib.on_toggle_enhance(|i| with_app(|a| a.toggle_enhance(i)));
|
||||
lib.on_open_profile(|i| with_app(|a| a.open_profile(i)));
|
||||
@@ -1419,10 +1238,11 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
lib.on_open_accounts(|i| with_app(|a| a.open_accounts(i)));
|
||||
lib.on_pick_account(|r| with_app(|a| a.pick_account(r)));
|
||||
lib.set_clips_dir(summit_core::engine::clips_dir().map(|d| tilde(&d)).unwrap_or_default().into());
|
||||
lib.on_prof_set(|r, v| with_app(|a| a.prof_set(r, v)));
|
||||
lib.on_prof_text(|r, t| with_app(|a| a.prof_text(r, &t)));
|
||||
lib.on_prof_reset(|| with_app(|a| a.prof_reset()));
|
||||
lib.on_open_defaults(|| with_app(|a| a.open_defaults()));
|
||||
lib.on_close_profile(|| with_app(|a| a.close_profile()));
|
||||
lib.on_open_stats(|i| with_app(|a| a.open_stats(i)));
|
||||
lib.on_open_compare(|i| with_app(|a| a.open_compare(i)));
|
||||
lib.on_compare_start(|i| with_app(|a| a.compare_start(i)));
|
||||
pane::wire(&app);
|
||||
lib.on_play_back(|| with_app(|a| a.play_back()));
|
||||
lib.on_play_stop(|| with_app(|a| a.play_stop()));
|
||||
lib.on_pick_show(|| with_app(|a| a.pick_show()));
|
||||
@@ -1436,23 +1256,28 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
// Overrides for screenshots and testing. They are not written to ui.toml unless a setting is changed afterwards.
|
||||
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
|
||||
let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
if let Some(v) = env("SUMMIT_LAYOUT").and_then(|v| pick(&v, &names(prefs::LAYOUTS))) { app.ui.set_layout(v.clamp(0, 2)); }
|
||||
if let Some(v) = env("SUMMIT_THEME").and_then(|v| pick(&v, &app.theme_keys)) { app.ui.set_theme(v.clamp(0, app.theme_keys.len() as i32 - 1)); }
|
||||
if let Some(v) = env("SUMMIT_ANIM").and_then(|v| v.parse::<f32>().ok()) { app.ui.set_anim_speed(v.clamp(0.0, 2.0)); }
|
||||
if let Some(v) = env("SUMMIT_LAYOUT").and_then(|v| pick(&v, &names(prefs::LAYOUTS))) { app.settings.borrow_mut().layout = prefs::LAYOUTS[v.clamp(0, 2) as usize].into(); }
|
||||
if let Some(v) = env("SUMMIT_THEME").and_then(|v| pick(&v, &app.theme_keys)) { let k = app.theme_keys[v.clamp(0, app.theme_keys.len() as i32 - 1) as usize].clone(); app.settings.borrow_mut().theme = k; }
|
||||
if let Some(v) = env("SUMMIT_ANIM").and_then(|v| v.parse::<f32>().ok()) { app.settings.borrow_mut().anim_speed = v.clamp(0.0, 2.0); }
|
||||
app.apply_ui_settings();
|
||||
if let Some(v) = env("SUMMIT_SCALE").and_then(|v| v.parse::<f32>().ok()) { app.settings.borrow_mut().ui_scale = v.clamp(0.5, 3.0); }
|
||||
app.rebuild_shelves();
|
||||
app.requery();
|
||||
app.nvidia_refresh();
|
||||
if let Some(v) = env("SUMMIT_VIEW").or_else(|| env("SUMMIT_TAB")).and_then(|v| pick(&v, &names(&["home", "library", "unfiltered", "settings"]))) { app.ui.invoke_goto(v.clamp(0, 3)); }
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { app.ui.set_lib_focus(v); app.ui.set_unf_focus(v); app.ui.set_settings_row(v.clamp(0, 12)); }
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { app.ui.set_lib_focus(v); app.ui.set_unf_focus(v); }
|
||||
if let Some(want) = env("SUMMIT_DETAIL") {
|
||||
let w = want.to_lowercase();
|
||||
let hit = app.entries.borrow().iter().position(|e| e.id.to_lowercase() == w).or_else(|| app.entries.borrow().iter().position(|e| e.title.to_lowercase().contains(&w)));
|
||||
if let Some(i) = hit {
|
||||
app.open_detail(i as i32);
|
||||
if env("SUMMIT_EDITOR").is_some() { app.open_profile(i as i32); }
|
||||
if env("SUMMIT_STATS").is_some() { app.open_stats(i as i32); }
|
||||
if env("SUMMIT_COMPARE").is_some() { app.open_compare(i as i32); }
|
||||
}
|
||||
}
|
||||
// SUMMIT_SECTION, SUMMIT_SEARCH, SUMMIT_ZONE, SUMMIT_FOCUS, SUMMIT_PRESET: where the settings pane is (shot.rs)
|
||||
app.pane_overrides(&env);
|
||||
// SUMMIT_PLAYING=0|1|2: the "now playing" screen for the focused game (starting, running, stopping), for renders.
|
||||
if let Some(phase) = env("SUMMIT_PLAYING").and_then(|v| v.parse::<i32>().ok()) {
|
||||
let idx = (app.ui.global::<Lib>().get_detail().idx.max(0) as usize).min(app.entries.borrow().len().saturating_sub(1));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Game controller input through the kernel's joystick devices (/dev/input/js*), with no extra libraries.
|
||||
//! A pad drives the same navigation as the keyboard: d-pad or left stick = arrows, A = Enter, B = Esc,
|
||||
//! X = pin, LB/RB = previous/next section.
|
||||
//! X = pin, Y = reset the focused setting (Delete), LB/RB = previous/next section.
|
||||
//!
|
||||
//! The kernel gives a pad's presses to every program that has the device open, whatever window is in front. So
|
||||
//! the launcher only acts on them while its own window has the keyboard, and not while a game started from it
|
||||
@@ -55,7 +55,7 @@ pub fn listen(playing: bool, window_focused: bool) -> Listen {
|
||||
|
||||
/// Key name (as understood by `shot::press`) for a button press.
|
||||
pub fn button_key(number: u8) -> Option<&'static str> {
|
||||
match number { 0 => Some("Enter"), 1 => Some("Esc"), 2 => Some("p"), 4 => Some("Backtab"), 5 => Some("Tab"), _ => None }
|
||||
match number { 0 => Some("Enter"), 1 => Some("Esc"), 2 => Some("p"), 3 => Some("Delete"), 4 => Some("Backtab"), 5 => Some("Tab"), _ => None }
|
||||
}
|
||||
|
||||
/// Which way the pad points: left stick (axes 0, 1) and d-pad hat (axes 6, 7) together.
|
||||
@@ -175,6 +175,7 @@ mod tests {
|
||||
#[test]
|
||||
fn buttons_map_to_navigation_keys() {
|
||||
assert_eq!((button_key(0), button_key(1), button_key(2), button_key(4), button_key(5), button_key(9)), (Some("Enter"), Some("Esc"), Some("p"), Some("Backtab"), Some("Tab"), None));
|
||||
assert_eq!(button_key(3), Some("Delete")); // Y: reset the focused setting
|
||||
}
|
||||
#[test]
|
||||
fn direction_from_hat_and_stick() {
|
||||
|
||||
@@ -0,0 +1,536 @@
|
||||
//! The settings pane (ui/pane.slint): what it shows and what its rows do. The rows themselves are built in rows.rs;
|
||||
//! this file reads the files they come from, writes a change to the file it belongs in, and builds the pane again
|
||||
//! from the files, so what is on screen is always what was read back.
|
||||
//!
|
||||
//! the launcher's own settings ~/.config/summit/ui.toml
|
||||
//! launch profiles (and a game's own) ~/.config/summit/profiles/<id>.toml
|
||||
//! the engine's global settings the engine's settings.json (the registry says where)
|
||||
use crate::rows::{self, Kind, Row, Section};
|
||||
use crate::{data, short, tilde, with_app, App, CmpRow, Lib, SNav, SPreset, SRow, SessField, SessRow, StatTile, Sx};
|
||||
use serde_json::Value;
|
||||
use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel};
|
||||
use std::collections::BTreeMap;
|
||||
use summit_core::model::{Entry, Source};
|
||||
use summit_core::registry::{self, Registry};
|
||||
use summit_core::{console, display, launch, presets, profile, sessions, ui as prefs};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Scope { #[default] Settings, Game(usize) }
|
||||
|
||||
/// What the pane is showing: whose settings, its sections as last built, and what each row on screen is.
|
||||
#[derive(Default)]
|
||||
pub struct Pane {
|
||||
pub scope: Scope,
|
||||
sections: Vec<Section>,
|
||||
/// The key of each row on screen (rows::Row::key), and of each tile of the quick strip.
|
||||
keys: Vec<String>,
|
||||
quick: Vec<String>,
|
||||
/// The monitors, listed once when the pane opens (or why there is no list).
|
||||
outs: Option<Result<Vec<display::Output>, String>>,
|
||||
}
|
||||
|
||||
type Map = BTreeMap<String, Value>;
|
||||
|
||||
/// Everything an engine row needs, read from the files.
|
||||
struct Engine { reg: Registry, saved: Map, base: Map, own: Option<(Map, String)>, locked: BTreeMap<String, String> }
|
||||
impl Engine {
|
||||
fn cx(&self) -> rows::EngineCx<'_> {
|
||||
rows::EngineCx { reg: &self.reg, saved: &self.saved, base: &self.base, game: self.own.as_ref().map(|(m, s)| (m, s.as_str())), locked: &self.locked }
|
||||
}
|
||||
}
|
||||
|
||||
fn focusable(r: &Row) -> bool { matches!(r.kind, Kind::Choice | Kind::Text | Kind::Action | Kind::Theme) }
|
||||
|
||||
fn strings(v: &[String]) -> ModelRc<SharedString> { ModelRc::new(VecModel::from(v.iter().map(SharedString::from).collect::<Vec<_>>())) }
|
||||
|
||||
fn srows(list: &[Row]) -> (Vec<SRow>, f32) {
|
||||
let (at, total) = rows::layout(list);
|
||||
let v = list.iter().enumerate().map(|(i, r)| {
|
||||
let line = |name: &str| r.impact.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()).unwrap_or_default();
|
||||
let more = r.impact.iter().filter(|(k, _)| k != "Picture" && k != "Speed").map(|(k, v)| format!("{k}: {v}")).collect::<Vec<_>>().join(" · ");
|
||||
SRow {
|
||||
kind: match r.kind { Kind::Choice => 0, Kind::Text => 1, Kind::Heading => 2, Kind::Action => 3, Kind::Theme => 4, Kind::Note => 5 },
|
||||
label: r.label.as_str().into(), help: r.help.as_str().into(), picture: line("Picture").into(), speed: line("Speed").into(), more: more.into(),
|
||||
options: strings(&r.options), hints: strings(&r.hints), value: r.value as i32, text: r.text.as_str().into(), placeholder: r.placeholder.as_str().into(),
|
||||
changed: r.changed, experimental: r.experimental, off: r.off, locked: r.locked, why: r.why.as_str().into(), note: r.note.as_str().into(),
|
||||
tag: r.tag.as_str().into(), seg: r.seg, button: r.button.as_str().into(), base: r.base.as_str().into(),
|
||||
y: at[i].0, h: at[i].1,
|
||||
up: list[..i].iter().rposition(focusable).map_or(-1, |j| j as i32),
|
||||
down: list[i + 1..].iter().position(focusable).map_or(-1, |j| (i + 1 + j) as i32),
|
||||
}
|
||||
}).collect();
|
||||
(v, total)
|
||||
}
|
||||
|
||||
/// Put `new` into a model that stays: rows are updated in place when the list keeps its length, so a row keeps its
|
||||
/// place on screen (and the keyboard) while its value changes.
|
||||
fn sync(model: &VecModel<SRow>, new: Vec<SRow>) {
|
||||
if model.row_count() == new.len() { for (i, r) in new.into_iter().enumerate() { model.set_row_data(i, r); } } else { model.set_vec(new); }
|
||||
}
|
||||
|
||||
/// The engine's kind of source for an entry (framegen/sources.py): a console streams or is captured, a game is a window.
|
||||
fn source_kind(app: &App, e: &Entry) -> &'static str {
|
||||
match (e.source == Source::Console).then(|| app.console_of(&e.id)).flatten().map(|c| c.link) {
|
||||
Some(console::Link::RemotePlay { .. }) => "chiaki",
|
||||
Some(console::Link::Capture { .. }) => "capture",
|
||||
None => "window",
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The engine's registry, asked for once. An error says why there are no engine rows.
|
||||
pub fn registry(&self) -> Result<Registry, String> {
|
||||
if let Some(r) = self.registry.borrow().as_ref() { return r.clone(); }
|
||||
let r = match summit_core::engine::find_engine() {
|
||||
Some(e) => Registry::load(&e),
|
||||
None => Err("Summit's engine was not found: run install.sh (or set SUMMIT_ENGINE to the engine folder).".to_string()),
|
||||
};
|
||||
*self.registry.borrow_mut() = Some(r.clone());
|
||||
r
|
||||
}
|
||||
|
||||
/// What the engine rows are built from, for the Settings page (None) or a game.
|
||||
fn engine(&self, game: Option<&Entry>) -> Result<Engine, String> {
|
||||
let reg = self.registry()?;
|
||||
let mut saved = registry::read_values(®.path);
|
||||
// The two replay lengths are the launcher's: it passes them on every start, once there is a ui.toml.
|
||||
if prefs::path().is_ok_and(|p| p.exists()) {
|
||||
let ui = self.settings.borrow();
|
||||
saved.insert("replay".into(), Value::from(ui.replay_seconds));
|
||||
saved.insert("replay_clip".into(), Value::from(ui.clip_seconds));
|
||||
}
|
||||
let defaults = profile::load_defaults().unwrap_or_default();
|
||||
let mut base = registry::forced(&defaults);
|
||||
let mut locked = BTreeMap::new();
|
||||
// Fullscreen is the launch profile's Window mode once that is chosen: one place decides it.
|
||||
if base.remove("fullscreen").is_some() && game.is_none() {
|
||||
locked.insert("fullscreen".to_string(), format!("Decided by Window mode in Game defaults ({}).", data::window_mode_label(&defaults.window_mode)));
|
||||
}
|
||||
let own = game.map(|e| {
|
||||
let layer = profile::load_layer(&e.id).unwrap_or_default();
|
||||
let mut m = registry::forced(&profile::resolve(&[&layer]));
|
||||
m.remove("fullscreen");
|
||||
let p = profile::load(&e.id).unwrap_or_default();
|
||||
if !p.window_mode.is_empty() { locked.insert("fullscreen".to_string(), format!("Decided by this game's Window mode in Launch ({}).", data::window_mode_label(&p.window_mode))); }
|
||||
(m, source_kind(self, e).to_string())
|
||||
});
|
||||
Ok(Engine { reg, saved, base, own, locked })
|
||||
}
|
||||
|
||||
fn pane_entry(&self) -> Option<Entry> {
|
||||
match self.pane.borrow().scope { Scope::Game(i) => self.entries.borrow().get(i).cloned(), Scope::Settings => None }
|
||||
}
|
||||
/// The profile the pane's launch rows edit.
|
||||
fn pane_profile_id(&self) -> String { self.pane_entry().map(|e| e.id).unwrap_or_else(|| profile::DEFAULT_ID.to_string()) }
|
||||
|
||||
/// The launch rows' context, handed to `f` (monitors, the window tools of this desktop).
|
||||
fn with_edit<T>(&self, f: impl FnOnce(&data::EditCtx) -> T) -> T {
|
||||
let game = self.pane_entry();
|
||||
let id = self.pane_profile_id();
|
||||
let own = profile::load_layer(&id).unwrap_or_else(|e| { self.toast(format!("Could not read the profile: {e}")); profile::Layer::default() });
|
||||
let base = if game.is_none() { profile::Profile::default() } else { profile::load_defaults().unwrap_or_default() };
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
if self.pane.borrow().outs.is_none() { self.pane.borrow_mut().outs = Some(display::outputs(s, d)); }
|
||||
let pane = self.pane.borrow();
|
||||
let (list, err) = match pane.outs.as_ref() { Some(Ok(o)) => (o.as_slice(), None), Some(Err(e)) => (&[][..], Some(e.as_str())), None => (&[][..], None) };
|
||||
let tool = match (s, d) { (display::Session::X11, _) => "xrandr", (_, display::Desktop::Kde) => "kscreen-doctor", (_, display::Desktop::Wlroots) => "wlr-randr", _ => "" };
|
||||
let placer = summit_core::winmode::backend(s, d, summit_core::doctor::on_path);
|
||||
let placer = match &placer { Ok(summit_core::winmode::Backend::KWin) => Ok("a KWin script"), Ok(_) => Ok("wmctrl"), Err(e) => Err(e.as_str()) };
|
||||
let auto = game.as_ref().and_then(launch::window_query);
|
||||
f(&data::EditCtx { own: &own, base: &base, defaults: game.is_none(), outs: list, list_err: err, tool, placer, auto_window: auto.as_deref() })
|
||||
}
|
||||
|
||||
fn launcher_info(&self) -> rows::LauncherInfo {
|
||||
let lib = self.ui.global::<Lib>();
|
||||
let themes = self.ui.get_palettes().iter().map(|p| (p.key.to_string(), p.name.to_string())).collect();
|
||||
let engine = match self.registry() { Ok(r) => format!("engine settings in {}", tilde(&r.path)), Err(e) => format!("engine settings not available ({e})") };
|
||||
rows::LauncherInfo {
|
||||
themes, clips_dir: lib.get_clips_dir().into(), hotkey: lib.get_hotkey_status().into(), nvidia: lib.get_nvidia_status().into(),
|
||||
nvidia_button: if lib.get_nvidia_busy() { "Working..." } else if lib.get_nvidia_installed() { "Manage" } else { "Set up" }.into(),
|
||||
nvidia_ok: !lib.get_nvidia_busy() && (lib.get_nvidia_ok() || lib.get_nvidia_installed()),
|
||||
about: format!("{} · {} · {}", lib.get_stats(), lib.get_session(), lib.get_renderer()),
|
||||
files: format!("Launcher settings in {} · launch profiles in {} · {engine}. Each is saved as you change it.",
|
||||
prefs::path().map(|f| tilde(&f)).unwrap_or_default(), profile::dir().map(|d| tilde(&d)).unwrap_or_default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the pane from the files and put it on screen, keeping the section and the focused row where they are.
|
||||
pub fn fill_pane(&self) {
|
||||
let game = self.pane_entry();
|
||||
let sx = self.ui.global::<Sx>();
|
||||
let mut sections: Vec<Section> = vec![];
|
||||
if game.is_none() { sections.push(rows::launcher_section(&self.settings.borrow(), &self.launcher_info())); }
|
||||
let mut launch = rows::launch_section(if game.is_some() { "Launch" } else { "Game defaults" }, self.with_edit(data::edit_rows), game.is_none());
|
||||
let own_all = profile::load_layer(&self.pane_profile_id()).map(|l| !l.is_empty()).unwrap_or(false);
|
||||
launch.rows.push(Row {
|
||||
kind: Kind::Action, key: "act:reset-all".into(), off: !own_all, locked: !own_all, button: if game.is_some() { "Use global".into() } else { "Reset".into() },
|
||||
label: if game.is_some() { "Use global for everything".into() } else { "Reset the game defaults".into() },
|
||||
help: match (game.is_some(), own_all) {
|
||||
(true, false) => "This game sets nothing of its own.".into(),
|
||||
(true, true) => "Forget everything this game sets itself: the launch settings above and every engine setting in the other sections.".into(),
|
||||
(false, false) => "Nothing is set: games open as they are.".into(),
|
||||
(false, true) => "Forget every game default above (and engine settings an older Summit stored with them).".into(),
|
||||
}, ..Default::default()
|
||||
});
|
||||
sections.push(launch);
|
||||
let engine = self.engine(game.as_ref());
|
||||
let (mut quick, mut preset_views, mut state) = (vec![], vec![], String::new());
|
||||
match &engine {
|
||||
Ok(en) => {
|
||||
let cx = en.cx();
|
||||
sections.extend(cx.sections());
|
||||
quick = cx.quick();
|
||||
(preset_views, state) = cx.presets();
|
||||
}
|
||||
Err(e) => sections.push(Section { title: "Engine".into(), rows: vec![rows::note(format!("The engine's settings can't be shown: {e}"))] }),
|
||||
}
|
||||
sx.set_engine_note(engine.as_ref().err().cloned().unwrap_or_default().into());
|
||||
sx.set_game(game.is_some());
|
||||
sx.set_title(match &game { Some(e) => format!("Profile · {}", e.title), None => "Settings".into() }.into());
|
||||
sx.set_subtitle(match &game {
|
||||
Some(e) => {
|
||||
let n: usize = sections.iter().map(|s| s.changed()).sum();
|
||||
format!("{} · saved to {}", if n == 0 { "Everything follows the global settings".to_string() } else { format!("{n} setting{} of its own (dotted); the rest follow Settings", if n == 1 { "" } else { "s" }) },
|
||||
profile::file(&e.id).map(|f| tilde(&f)).unwrap_or_default())
|
||||
}
|
||||
None => "For every game, unless a game's profile sets its own. Saved as you change them.".to_string(),
|
||||
}.into());
|
||||
sx.set_nav(ModelRc::new(VecModel::from(sections.iter().map(|s| SNav { label: s.title.as_str().into(), changed: s.changed() as i32, count: s.settings() as i32 }).collect::<Vec<_>>())));
|
||||
sx.set_presets(ModelRc::new(VecModel::from(preset_views.iter().map(|p| SPreset { name: p.name.as_str().into(), summary: p.summary.as_str().into(), detail: p.detail.as_str().into(), sets: strings(&p.sets), active: p.active }).collect::<Vec<_>>())));
|
||||
sx.set_preset_state(state.into());
|
||||
if sx.get_preset_sel() >= preset_views.len() as i32 { sx.set_preset_sel(0); }
|
||||
let section = (sx.get_section().max(0) as usize).min(sections.len().saturating_sub(1));
|
||||
sx.set_section(section as i32);
|
||||
let search = sx.get_search().to_string();
|
||||
let shown: Vec<Row> = if search.trim().is_empty() { sections[section].rows.clone() } else { rows::search(§ions, &search) };
|
||||
let (list, total) = srows(&shown);
|
||||
sync(&self.rows_model, list);
|
||||
sx.set_rows_h(total);
|
||||
// the focused row: where it was, or the nearest one that can take the focus
|
||||
let want = (sx.get_row().max(0) as usize).min(shown.len().saturating_sub(1));
|
||||
let at = if shown.get(want).is_some_and(focusable) { Some(want) } else { shown[want.min(shown.len())..].iter().position(focusable).map(|j| want + j).or_else(|| shown.iter().position(focusable)) };
|
||||
sx.set_row(at.unwrap_or(0) as i32);
|
||||
if at.is_none() && sx.get_zone() == 3 { sx.set_zone(2); }
|
||||
sync(&self.quick_model, srows(&quick).0);
|
||||
if sx.get_quick_sel() >= quick.len() as i32 { sx.set_quick_sel(0); }
|
||||
let mut pane = self.pane.borrow_mut();
|
||||
pane.keys = shown.iter().map(|r| r.key.clone()).collect();
|
||||
pane.quick = quick.iter().map(|r| r.key.clone()).collect();
|
||||
pane.sections = sections;
|
||||
}
|
||||
|
||||
/// Show the pane for the Settings page or a game, from its first section.
|
||||
fn open_pane(&self, scope: Scope) {
|
||||
{ let mut p = self.pane.borrow_mut(); p.scope = scope; p.outs = None; }
|
||||
let sx = self.ui.global::<Sx>();
|
||||
sx.set_section(0); sx.set_row(0); sx.set_zone(2); sx.set_search("".into()); sx.set_typing(false); sx.set_quick_sel(0); sx.set_preset_sel(0);
|
||||
self.fill_pane();
|
||||
}
|
||||
|
||||
pub fn open_profile(&self, idx: i32) {
|
||||
if idx < 0 || idx as usize >= self.entries.borrow().len() { return; }
|
||||
self.open_pane(Scope::Game(idx as usize));
|
||||
self.ui.global::<Lib>().set_editor_open(true);
|
||||
}
|
||||
|
||||
/// The profile closes: the pane is the Settings page's again.
|
||||
pub fn close_profile(&self) {
|
||||
self.ui.global::<Lib>().set_editor_open(false);
|
||||
self.open_pane(Scope::Settings);
|
||||
}
|
||||
|
||||
/// After a change: the pane again from the files, and whatever else shows the same values.
|
||||
fn changed(&self) {
|
||||
self.fill_pane();
|
||||
if let Scope::Game(i) = self.pane.borrow().scope { self.open_detail(i as i32); }
|
||||
}
|
||||
|
||||
/// Store engine settings where the pane's scope keeps them (None: stop setting it).
|
||||
fn store_engine(&self, changes: &[(String, Option<Value>)]) {
|
||||
let result: Result<(), String> = (|| {
|
||||
if let Some(e) = self.pane_entry() {
|
||||
return profile::update_layer(&e.id, |l| for (k, v) in changes { l.set_engine(k, v.as_ref()); }).map(|_| ()).map_err(|e| format!("{e:#}"));
|
||||
}
|
||||
let reg = self.registry()?;
|
||||
let (ours, engines): (Vec<_>, Vec<_>) = changes.iter().partition(|(k, _)| k == "replay" || k == "replay_clip");
|
||||
if !ours.is_empty() {
|
||||
let mut s = self.settings.borrow().clone();
|
||||
for (k, v) in ours {
|
||||
let n = v.as_ref().and_then(Value::as_u64).map(|n| n as u32);
|
||||
// (None: the engine's default, which is no replay and a 30 second clip)
|
||||
if k == "replay" { s.replay_seconds = n.unwrap_or(0); } else { s.clip_seconds = n.unwrap_or(30); }
|
||||
}
|
||||
let s = s.sanitized();
|
||||
prefs::save(&s).map_err(|e| format!("{e:#}"))?;
|
||||
*self.settings.borrow_mut() = s;
|
||||
}
|
||||
if !engines.is_empty() {
|
||||
let list: Vec<(&str, Option<Value>)> = engines.iter().map(|(k, v)| (k.as_str(), v.clone())).collect();
|
||||
registry::write_values(®.path, &list).map_err(|e| format!("{e:#}"))?;
|
||||
// A value the default launch profile still carries would win over the file on every start: it goes.
|
||||
let d = profile::load_layer(profile::DEFAULT_ID).unwrap_or_default();
|
||||
if engines.iter().any(|(k, _)| d.sets_engine(k)) {
|
||||
profile::update_layer(profile::DEFAULT_ID, |l| for (k, _) in &engines { if l.sets_engine(k) { l.set_engine(k, None); } }).map_err(|e| format!("{e:#}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result { self.toast(format!("Not saved: {e}")); }
|
||||
self.changed();
|
||||
}
|
||||
|
||||
fn row_key(&self, row: i32, quick: bool) -> Option<String> {
|
||||
let p = self.pane.borrow();
|
||||
(if quick { &p.quick } else { &p.keys }).get(row.max(0) as usize).cloned().filter(|k| !k.is_empty())
|
||||
}
|
||||
|
||||
/// A row's value was picked (`option`), or it was reset (None).
|
||||
fn pane_set(&self, key: &str, option: Option<usize>) {
|
||||
let Some((kind, name)) = key.split_once(':') else { return };
|
||||
match kind {
|
||||
"ui" => {
|
||||
let mut s = self.settings.borrow().clone();
|
||||
if !rows::launcher_pick(&mut s, name, option, &self.launcher_info()) { return; }
|
||||
self.set_ui_settings(s.sanitized());
|
||||
self.fill_pane();
|
||||
}
|
||||
"prof" => {
|
||||
let id = self.pane_profile_id();
|
||||
let own = profile::load_layer(&id).unwrap_or_default();
|
||||
let new = match option {
|
||||
Some(o) => self.with_edit(|cx| data::edit_apply(cx, name, o)),
|
||||
None => { let mut l = own.clone(); if name == "resolution" { l.unset("width"); l.unset("height"); l.unset("refresh_hz"); } else { l.unset(name); } l }
|
||||
};
|
||||
if new != own { if let Err(e) = profile::save_layer(&id, &new) { self.toast(format!("Could not save the profile: {e}")); } }
|
||||
self.changed();
|
||||
}
|
||||
"eng" | "engtext" => {
|
||||
let Ok(en) = self.engine(self.pane_entry().as_ref()) else { return };
|
||||
let store = match option { Some(o) if kind == "eng" => en.cx().pick(name, o), Some(_) => None, None => (!en.locked.contains_key(name)).then_some(None) };
|
||||
if let Some(v) = store { self.store_engine(&[(name.to_string(), v)]); }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn pane_text(&self, key: &str, text: &str) {
|
||||
let Some((kind, name)) = key.split_once(':') else { return };
|
||||
match kind {
|
||||
"prof" => {
|
||||
let id = self.pane_profile_id();
|
||||
let own = profile::load_layer(&id).unwrap_or_default();
|
||||
match data::edit_text(&own, name, text) {
|
||||
Ok(new) if new != own => { if let Err(e) = profile::save_layer(&id, &new) { self.toast(format!("Could not save the profile: {e}")); } }
|
||||
Ok(_) => {}
|
||||
Err(e) => self.toast(format!("Not saved: {e}")),
|
||||
}
|
||||
self.changed();
|
||||
}
|
||||
"engtext" => {
|
||||
let Ok(en) = self.engine(self.pane_entry().as_ref()) else { return };
|
||||
match en.cx().typed(name, text) {
|
||||
Ok(Some(v)) => self.store_engine(&[(name.to_string(), v)]),
|
||||
Ok(None) => self.fill_pane(),
|
||||
Err(e) => { self.toast(format!("Not saved: {e}")); self.fill_pane(); }
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn pane_act(&self, key: &str) {
|
||||
let lib = self.ui.global::<Lib>();
|
||||
match key {
|
||||
"act:clips" => self.open_clips(),
|
||||
"act:nvidia" => { lib.set_nvidia_btn(if lib.get_nvidia_installed() { 2 } else { 0 }); lib.set_nvidia_open(true); }
|
||||
"act:reset-all" => {
|
||||
let id = self.pane_profile_id();
|
||||
match profile::save_layer(&id, &profile::Layer::default()) {
|
||||
Ok(_) => self.toast(if id == profile::DEFAULT_ID { "The game defaults are Summit's own again".to_string() } else { "This game follows the global settings again".to_string() }),
|
||||
Err(e) => self.toast(format!("Could not save the profile: {e}")),
|
||||
}
|
||||
self.changed();
|
||||
}
|
||||
k => if let Some(title) = k.strip_prefix("act:reset:") {
|
||||
if title == "Launcher" {
|
||||
let mut s = self.settings.borrow().clone();
|
||||
for k in rows::LAUNCHER_KEYS { rows::launcher_pick(&mut s, k, None, &self.launcher_info()); }
|
||||
self.set_ui_settings(s.sanitized());
|
||||
return self.fill_pane();
|
||||
}
|
||||
let keys: Vec<(String, Option<Value>)> = self.pane.borrow().sections.iter().filter(|s| s.title == title).flat_map(|s| &s.rows)
|
||||
.filter(|r| r.changed && !r.locked).filter_map(|r| r.key.strip_prefix("eng:").map(|k| (k.to_string(), None))).collect();
|
||||
if !keys.is_empty() { self.store_engine(&keys); }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply preset `i`: its settings, nothing else, to the engine's file or to this game's profile.
|
||||
fn apply_preset(&self, i: i32) {
|
||||
let Some(p) = presets::PRESETS.get(i.max(0) as usize) else { return };
|
||||
let Ok(en) = self.engine(self.pane_entry().as_ref()) else { return };
|
||||
let game = en.own.is_some();
|
||||
let changes: Vec<(String, Option<Value>)> = p.values().into_iter().filter_map(|(k, v)| {
|
||||
let spec = en.reg.get(k)?; // (a setting this engine does not have is left out, and the preset's list says so)
|
||||
Some((k.to_string(), if !game && registry::same(&v, &spec.default) { None } else { Some(v) }))
|
||||
}).collect();
|
||||
self.store_engine(&changes);
|
||||
self.toast(format!("{}: {}", p.name, if game { "set for this game" } else { "set for every game without its own" }));
|
||||
}
|
||||
|
||||
/// The launcher's own settings changed: the window follows, and ui.toml is written.
|
||||
fn set_ui_settings(&self, new: prefs::UiSettings) {
|
||||
let scale = new.ui_scale != self.settings.borrow().ui_scale;
|
||||
if new == *self.settings.borrow() { return; }
|
||||
*self.settings.borrow_mut() = new;
|
||||
self.apply_ui_settings();
|
||||
self.save_settings();
|
||||
if scale { self.apply_scale(); }
|
||||
}
|
||||
|
||||
/// Layout, theme and motion, from the settings to the window.
|
||||
pub fn apply_ui_settings(&self) {
|
||||
let s = self.settings.borrow();
|
||||
self.ui.set_layout(s.layout_index() as i32);
|
||||
self.ui.set_theme(self.theme_keys.iter().position(|k| *k == s.theme).unwrap_or(0) as i32);
|
||||
self.ui.set_anim_speed(s.anim_speed);
|
||||
self.ui.set_anim_style(s.anim_style_index() as i32);
|
||||
}
|
||||
|
||||
/// The upscaler and frame generation a game runs with, in the registry's words (None without the registry).
|
||||
pub fn engine_summary(&self, e: &Entry) -> Option<(String, String)> {
|
||||
let en = self.engine(Some(e)).ok()?;
|
||||
let cx = en.cx();
|
||||
let name = |k: &str| en.reg.get(k).map(|s| s.name_of(&cx.value(s)));
|
||||
let up = name("scaler")?;
|
||||
let fg = if cx.value_of("interp") == Value::Bool(false) { "Off".to_string() } else { format!("{} {}", name("model")?, name("hz")?) };
|
||||
Some((up, fg))
|
||||
}
|
||||
|
||||
// ---- a game's statistics ----
|
||||
pub fn open_stats(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
let lib = self.ui.global::<Lib>();
|
||||
let tracked = self.state.borrow().tracked.get(&e.id).cloned();
|
||||
let steam = e.source == Source::Steam;
|
||||
let tile = |label: &str, value: String, note: &str| StatTile { label: label.into(), value: value.into(), note: note.into() };
|
||||
let now = crate::now();
|
||||
let avg = tracked.as_ref().filter(|t| t.sessions > 0).map(|t| sessions::duration_label(t.seconds as f64 / t.sessions as f64));
|
||||
lib.set_stat_tiles(ModelRc::new(VecModel::from(vec![
|
||||
tile("PLAYED", data::hours_long(e.playtime_minutes), if steam { "As Steam counts it" } else { "Counted when Summit starts it" }),
|
||||
tile("SESSIONS", if steam { "–".into() } else { tracked.as_ref().map_or(0, |t| t.sessions).to_string() }, if steam { "Steam does not report sessions" } else { "Starts from Summit" }),
|
||||
tile("AVERAGE SESSION", if steam { "–".into() } else { avg.unwrap_or_else(|| "–".into()) }, if steam { "Steam does not report sessions" } else { "Played time by sessions" }),
|
||||
tile("LAST PLAYED", match data::ago(e.last_played, now) { a if a.is_empty() => "Never".into(), a => a }, &e.last_played.filter(|t| *t > 0).map(sessions::stamp).unwrap_or_default()),
|
||||
])));
|
||||
let dirs = sessions::dirs();
|
||||
let all = sessions::read(&dirs, 400);
|
||||
let mine: Vec<&sessions::Summary> = all.iter().filter(|s| sessions::is_for(s, &e.id, &e.title)).collect();
|
||||
let rows: Vec<SessRow> = mine.iter().map(|s| {
|
||||
let mut head: Vec<String> = vec![];
|
||||
if let Some(d) = s.duration_s { head.push(sessions::duration_label(d)); }
|
||||
if let Some(f) = s.fps_avg { head.push(format!("{f:.1} fps on average")); }
|
||||
head.extend(s.lows.iter().map(|(k, v)| format!("{k} {v:.1}")));
|
||||
SessRow {
|
||||
when: match (sessions::stamp(s.when), data::ago(Some(s.when).filter(|t| *t > 0), now)) { (st, a) if a.is_empty() => st, (st, a) => format!("{st} · {a}") }.into(),
|
||||
headline: if head.is_empty() { "No duration or frame rate in this file".into() } else { head.join(" · ").into() },
|
||||
settings: s.settings.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(" · ").into(),
|
||||
file: tilde(&s.file).into(),
|
||||
fields: ModelRc::new(VecModel::from(s.fields.iter().map(|(k, v)| SessField { name: k.as_str().into(), value: short(v).into() }).collect::<Vec<_>>())),
|
||||
}
|
||||
}).collect();
|
||||
// (the first folder by name; the rest are the same two names under the other data, state, cache and config folders)
|
||||
let first = dirs.iter().find(|d| d.to_string_lossy().contains("smoovplay")).or(dirs.first()).map(|d| tilde(d)).unwrap_or_default();
|
||||
lib.set_sess_empty(format!("The engine writes a summary when a session with Enhance ends; an engine that does not write them yet leaves this empty. {} for other games. Looked in {first} and {} more folders (\"sessions\" and \"stats\" under the engine's and Summit's data, state, cache and config folders; SUMMIT_SESSIONS_DIR adds one).",
|
||||
match all.len() - mine.len() { 0 => "None found".to_string(), 1 => "1 summary found".to_string(), n => format!("{n} summaries found") }, dirs.len().saturating_sub(1)).into());
|
||||
lib.set_stats_note(if rows.is_empty() { "Time played, as Summit and the game's launcher count it.".into() } else { format!("Time played, and {} session summar{} the engine wrote, shown as the files have them.", rows.len(), if rows.len() == 1 { "y" } else { "ies" }).into() });
|
||||
lib.set_sess(ModelRc::new(VecModel::from(rows)));
|
||||
lib.set_sess_sel(0);
|
||||
lib.set_stats_title(e.title.as_str().into());
|
||||
lib.set_stats_open(true);
|
||||
}
|
||||
|
||||
// ---- compare ----
|
||||
/// Whether Compare can start this game, and the line its page shows about it.
|
||||
pub fn compare_state(&self, e: &Entry, can_enhance: bool) -> (bool, String) {
|
||||
let what = "Compare (Experimental): starts the game with Enhance and the engine's live comparison, the same picture with each value of one setting side by side.";
|
||||
let has = summit_core::engine::find_engine().is_some_and(|eng| summit_core::engine::has_compare(&eng));
|
||||
if !has { return (false, format!("{what} This engine has no --compare yet (it is being added on another branch), so nothing can be started from here.")); }
|
||||
if e.source == Source::Console { return (false, format!("{what} Not for consoles yet: only for a game Summit starts with Enhance on its window.")); }
|
||||
if !can_enhance { return (false, format!("{what} Not available here: Enhance cannot run for this game.")); }
|
||||
(true, format!("{what} Passed to the engine as --compare; not verified from the launcher yet."))
|
||||
}
|
||||
|
||||
pub fn open_compare(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
let lib = self.ui.global::<Lib>();
|
||||
let (ok, note) = self.compare_state(&e, self.enhance_available(&e).0);
|
||||
let (mut rows, mut specs) = (vec![], vec![]);
|
||||
match self.registry() {
|
||||
Ok(reg) => for s in reg.specs.iter().filter(|s| s.saved && s.choices.len() >= 2 && (s.quick || s.impact.iter().any(|(k, _)| k == "picture"))) {
|
||||
let take: Vec<®istry::Choice> = s.choices.iter().take(4).collect();
|
||||
let values: Vec<String> = take.iter().map(|c| match &c.value { Value::String(v) => v.clone(), v => v.to_string() }).collect();
|
||||
let Ok(spec) = summit_core::engine::parse_compare(&format!("{}:{}", s.key, values.join(","))) else { continue };
|
||||
rows.push(CmpRow { label: s.label.replace("SmoovPlay", "Summit").into(), detail: format!("{} --compare {spec}", take.iter().map(|c| c.name.as_str()).collect::<Vec<_>>().join(" | ")).into() });
|
||||
specs.push(spec);
|
||||
},
|
||||
Err(err) => rows.push(CmpRow { label: "The engine's settings can't be listed".into(), detail: err.into() }),
|
||||
}
|
||||
let ok = ok && !specs.is_empty();
|
||||
*self.cmp_specs.borrow_mut() = specs;
|
||||
lib.set_cmp_rows(ModelRc::new(VecModel::from(rows)));
|
||||
lib.set_cmp_note(note.replace("Compare (Experimental): starts the game with Enhance and the engine's live comparison, the same picture with each value of one setting side by side. ", "").into());
|
||||
lib.set_cmp_ok(ok);
|
||||
lib.set_cmp_sel(0);
|
||||
lib.set_cmp_title(e.title.as_str().into());
|
||||
lib.set_cmp_open(true);
|
||||
}
|
||||
|
||||
pub fn compare_start(&self, i: i32) {
|
||||
let lib = self.ui.global::<Lib>();
|
||||
if !lib.get_cmp_ok() { return; }
|
||||
let Some(spec) = self.cmp_specs.borrow().get(i.max(0) as usize).cloned() else { return };
|
||||
lib.set_cmp_open(false);
|
||||
self.play_with(lib.get_detail().idx, Some(spec));
|
||||
}
|
||||
|
||||
/// SUMMIT_SECTION (a section's name or number), SUMMIT_SEARCH, SUMMIT_ZONE (0 presets, 1 quick strip, 2 sections,
|
||||
/// 3 rows), SUMMIT_FOCUS (row), SUMMIT_PRESET, SUMMIT_QUICK: where the settings pane is, for renders and tests.
|
||||
pub fn pane_overrides(&self, env: &dyn Fn(&str) -> Option<String>) {
|
||||
let sx = self.ui.global::<Sx>();
|
||||
if !self.ui.global::<Lib>().get_editor_open() { self.open_pane(Scope::Settings); }
|
||||
if let Some(want) = env("SUMMIT_SECTION") {
|
||||
let w = want.trim().to_lowercase();
|
||||
let hit = self.pane.borrow().sections.iter().position(|s| s.title.to_lowercase() == w).or_else(|| self.pane.borrow().sections.iter().position(|s| s.title.to_lowercase().contains(&w))).or_else(|| w.parse().ok());
|
||||
if let Some(i) = hit { sx.set_section(i as i32); sx.set_row(0); }
|
||||
}
|
||||
if let Some(q) = env("SUMMIT_SEARCH") { sx.set_search(q.into()); sx.set_row(0); }
|
||||
if let Some(z) = env("SUMMIT_ZONE").and_then(|v| v.parse::<i32>().ok()) { sx.set_zone(z.clamp(0, 3)); }
|
||||
if let Some(v) = env("SUMMIT_PRESET").and_then(|v| v.parse::<i32>().ok()) { sx.set_preset_sel(v.max(0)); }
|
||||
if let Some(v) = env("SUMMIT_QUICK").and_then(|v| v.parse::<i32>().ok()) { sx.set_quick_sel(v.max(0)); }
|
||||
self.fill_pane();
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { sx.set_row(v.max(0)); self.fill_pane(); }
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect the pane's callbacks.
|
||||
pub fn wire(app: &App) {
|
||||
let sx = app.ui.global::<Sx>();
|
||||
sx.set_rows(ModelRc::from(app.rows_model.clone()));
|
||||
sx.set_quick(ModelRc::from(app.quick_model.clone()));
|
||||
sx.on_enter(|| with_app(|a| if !a.ui.global::<Lib>().get_editor_open() { a.fill_pane(); }));
|
||||
sx.on_pick_section(|i| with_app(|a| {
|
||||
let sx = a.ui.global::<Sx>();
|
||||
sx.set_search("".into()); sx.set_section(i); sx.set_row(0);
|
||||
a.fill_pane();
|
||||
}));
|
||||
sx.on_search_changed(|_| with_app(|a| { a.ui.global::<Sx>().set_row(0); a.fill_pane(); }));
|
||||
sx.on_set(|row, option| with_app(|a| if let Some(k) = a.row_key(row, false) { a.pane_set(&k, Some(option.max(0) as usize)); }));
|
||||
sx.on_set_quick(|row, option| with_app(|a| if let Some(k) = a.row_key(row, true) { a.pane_set(&k, Some(option.max(0) as usize)); }));
|
||||
sx.on_reset(|row| with_app(|a| if let Some(k) = a.row_key(row, false) {
|
||||
if k.starts_with("engtext:") || k.starts_with("prof:") && a.pane.borrow().sections.iter().flat_map(|s| &s.rows).any(|r| r.key == k && r.kind == Kind::Text) { a.pane_text(&k, ""); } else { a.pane_set(&k, None); }
|
||||
}));
|
||||
sx.on_reset_quick(|row| with_app(|a| if let Some(k) = a.row_key(row, true) { a.pane_set(&k, None); }));
|
||||
sx.on_text(|row, text| with_app(|a| if let Some(k) = a.row_key(row, false) { a.pane_text(&k, &text); }));
|
||||
sx.on_act(|row| with_app(|a| if let Some(k) = a.row_key(row, false) { a.pane_act(&k); }));
|
||||
sx.on_apply_preset(|i| with_app(|a| a.apply_preset(i)));
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
//! The rows of the Settings page and of a game's profile, built from data. No UI types here, so it is unit tested.
|
||||
//!
|
||||
//! Engine rows come from the engine's registry (summit_core::registry): the launcher has no copy of their labels,
|
||||
//! choices or help, so a setting the engine adds shows up by itself, in its own section. What the launcher does
|
||||
//! know is where a value lives: the engine's settings.json for the global value, a profile's `[engine]` table for
|
||||
//! a game's own, and ui.toml for the two instant-replay lengths the launcher passes on every start.
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use summit_core::presets;
|
||||
use summit_core::registry::{same, Registry, Spec};
|
||||
use summit_core::ui::UiSettings;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Kind { #[default] Choice, Text, Heading, Action, Theme, Note }
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Row {
|
||||
pub kind: Kind,
|
||||
/// What the row is: "eng:<registry key>", "engtext:<key>" (a typed custom value), "ui:<field>", "prof:<profile
|
||||
/// key>", "act:<action>", "" for headings and notes.
|
||||
pub key: String,
|
||||
pub label: String,
|
||||
pub help: String,
|
||||
/// ("Picture", "..."), ("Speed", "...")
|
||||
pub impact: Vec<(String, String)>,
|
||||
pub options: Vec<String>,
|
||||
/// A line for each option (may be empty).
|
||||
pub hints: Vec<String>,
|
||||
pub value: usize,
|
||||
pub text: String,
|
||||
pub placeholder: String,
|
||||
/// Not the default (Settings), or set by the game itself (a game's profile).
|
||||
pub changed: bool,
|
||||
pub experimental: bool,
|
||||
/// Not used right now: drawn greyed, with `why`.
|
||||
pub off: bool,
|
||||
/// Cannot be changed here at all (`why` says where instead).
|
||||
pub locked: bool,
|
||||
pub why: String,
|
||||
/// Something to know that is not a reason for anything: "Only used with a capture card."
|
||||
pub note: String,
|
||||
/// A short label next to the name: "Next start".
|
||||
pub tag: String,
|
||||
/// Few short options: drawn side by side.
|
||||
pub seg: bool,
|
||||
/// An action row's button.
|
||||
pub button: String,
|
||||
/// "Default: 2x" (Settings) or "Global: 2x" (a game).
|
||||
pub base: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Section { pub title: String, pub rows: Vec<Row> }
|
||||
|
||||
impl Section {
|
||||
pub fn changed(&self) -> usize { self.rows.iter().filter(|r| r.changed && !r.key.starts_with("engtext:")).count() }
|
||||
pub fn settings(&self) -> usize { self.rows.iter().filter(|r| matches!(r.kind, Kind::Choice | Kind::Text | Kind::Theme)).count() }
|
||||
}
|
||||
|
||||
/// The engine's texts name it by its own name; in the launcher it is Summit's engine.
|
||||
fn brand(s: &str) -> String { s.replace("SmoovPlay's", "Summit's").replace("SmoovPlay", "Summit") }
|
||||
|
||||
fn heading(t: &str) -> Row { Row { kind: Kind::Heading, label: t.to_uppercase(), ..Default::default() } }
|
||||
pub fn note(t: impl Into<String>) -> Row { Row { kind: Kind::Note, help: t.into(), ..Default::default() } }
|
||||
|
||||
// ---- engine settings ----
|
||||
|
||||
/// Everything an engine row is built from.
|
||||
pub struct EngineCx<'a> {
|
||||
pub reg: &'a Registry,
|
||||
/// The global values as saved: the engine's settings.json, with the launcher's own (ui.toml) on top.
|
||||
pub saved: &'a BTreeMap<String, Value>,
|
||||
/// What the default launch profile forces (summit_core::registry::forced): it wins over `saved` on every start.
|
||||
pub base: &'a BTreeMap<String, Value>,
|
||||
/// A game's profile: what the game's own layer sets, and the engine's kind of source for it ("window",
|
||||
/// "chiaki", "capture"). None: the Settings page.
|
||||
pub game: Option<(&'a BTreeMap<String, Value>, &'a str)>,
|
||||
/// Rows the launcher decides elsewhere: key -> where.
|
||||
pub locked: &'a BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The two settings whose value may be something the choices do not list (the engine takes any multiple of 30 fps
|
||||
/// from 60 to 300, and any size from 320x240 to 7680x4320).
|
||||
fn custom_ok(key: &str, v: &Value) -> bool {
|
||||
match key {
|
||||
"hz" => v.as_u64().is_some_and(|hz| (60..=300).contains(&hz) && hz % 30 == 0),
|
||||
"output_res" => v.as_str().is_some_and(|s| summit_core::profile::parse_res(s).is_some()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl EngineCx<'_> {
|
||||
fn usable(spec: &Spec, v: &Value) -> bool { spec.choices.is_empty() || spec.position(v).is_some() || custom_ok(&spec.key, v) }
|
||||
|
||||
/// The global value: what a game without its own gets.
|
||||
pub fn global(&self, spec: &Spec) -> Value {
|
||||
if let Some(v) = self.base.get(&spec.key) { return v.clone(); }
|
||||
self.saved.get(&spec.key).filter(|v| spec.saved && Self::usable(spec, v)).cloned().unwrap_or_else(|| spec.default.clone())
|
||||
}
|
||||
pub fn own(&self, key: &str) -> Option<&Value> { self.game.and_then(|(own, _)| own.get(key)) }
|
||||
/// The value in use here.
|
||||
pub fn value(&self, spec: &Spec) -> Value { self.own(&spec.key).cloned().unwrap_or_else(|| self.global(spec)) }
|
||||
pub fn value_of(&self, key: &str) -> Value { self.reg.get(key).map(|s| self.value(s)).unwrap_or(Value::Null) }
|
||||
|
||||
fn row(&self, spec: &Spec) -> Row {
|
||||
let game = self.game.is_some();
|
||||
let g = self.global(spec);
|
||||
let own = self.own(&spec.key).cloned();
|
||||
let cur = own.clone().unwrap_or_else(|| g.clone());
|
||||
let (mut options, mut hints): (Vec<String>, Vec<String>) = (vec![], vec![]);
|
||||
if game { options.push(format!("Global · {}", spec.name_of(&g))); hints.push("Follows the global setting (Settings).".into()); }
|
||||
for c in &spec.choices { options.push(c.name.clone()); hints.push(brand(&c.hint)); }
|
||||
let first = usize::from(game);
|
||||
let value = if game && own.is_none() { 0 } else {
|
||||
match spec.position(&cur) {
|
||||
Some(i) => first + i,
|
||||
None => {
|
||||
options.push(if spec.choices.is_empty() { spec.name_of(&cur) } else { format!("{} (custom)", spec.name_of(&cur)) });
|
||||
hints.push(if spec.choices.is_empty() { String::new() } else { "A value that is not one of the listed choices.".into() });
|
||||
options.len() - 1
|
||||
}
|
||||
}
|
||||
};
|
||||
let (locked, lock_why) = if !spec.saved {
|
||||
(true, "This session only: it is never saved, so it cannot be set from here. Turn it on in the in-game overlay.".to_string())
|
||||
} else if let Some(w) = self.locked.get(&spec.key) { (true, w.clone()) }
|
||||
else if spec.choices.is_empty() { (true, "The launcher cannot show this kind of setting yet: change it in the in-game overlay.".to_string()) }
|
||||
else { (false, String::new()) };
|
||||
let unused = spec.unused_now(self.reg, &|k| self.value_of(k)).or_else(|| self.game.and_then(|(_, src)| spec.unused_with(src)));
|
||||
let (off, why) = match (locked, unused) { (true, _) => (true, lock_why), (false, Some(w)) => (true, brand(&w)), (false, None) => (false, String::new()) };
|
||||
let mut notes: Vec<String> = vec![];
|
||||
if !game { notes.extend(spec.source_note().map(|n| brand(&n))); }
|
||||
if !spec.later.is_empty() { notes.push(brand(&spec.later)); }
|
||||
Row {
|
||||
kind: Kind::Choice, key: format!("eng:{}", spec.key), label: brand(&spec.label), help: brand(&spec.help),
|
||||
impact: spec.impact.iter().map(|(k, v)| (capital(k), brand(v))).collect(),
|
||||
options, hints, value, changed: if game { own.is_some() } else { !same(&g, &spec.default) },
|
||||
experimental: spec.experimental, off, locked, why, note: notes.join(" "),
|
||||
tag: if spec.live { String::new() } else { "Next start".into() },
|
||||
base: if game { format!("Global: {}", spec.name_of(&g)) } else { format!("Default: {}", spec.name_of(&spec.default)) },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed value for a setting that takes more than its listed choices.
|
||||
fn text_row(&self, spec: &Spec) -> Option<Row> {
|
||||
let cur = self.value(spec);
|
||||
let custom = spec.position(&cur).is_none() && custom_ok(&spec.key, &cur);
|
||||
let mine = if self.game.is_some() { self.own(&spec.key).is_some() } else { true };
|
||||
let (label, help, text, eg) = match spec.key.as_str() {
|
||||
"hz" => ("Custom multiplier", "Any whole number from 2 to 10. Enter to type it, Enter to save; empty goes back to the choice above.",
|
||||
cur.as_u64().map(|hz| (hz / 30).to_string()).unwrap_or_default(), "e.g. 7"),
|
||||
"output_res" => ("Custom output resolution", "Any size, e.g. 2560x1080 (from 320x240 to 7680x4320). Enter to type it, Enter to save; empty goes back to the choice above.",
|
||||
cur.as_str().unwrap_or_default().to_string(), "e.g. 2560x1080"),
|
||||
_ => return None,
|
||||
};
|
||||
let unused = spec.unused_now(self.reg, &|k| self.value_of(k));
|
||||
Some(Row {
|
||||
kind: Kind::Text, key: format!("engtext:{}", spec.key), label: label.into(), help: help.into(),
|
||||
text: if custom && mine { text } else { String::new() }, placeholder: format!("Now {} ({eg})", spec.name_of(&cur)),
|
||||
changed: custom && mine, off: unused.is_some(), why: unused.map(|w| brand(&w)).unwrap_or_default(), ..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// The engine's sections, in the registry's order: each with its headings, rows and a reset row.
|
||||
pub fn sections(&self) -> Vec<Section> {
|
||||
self.reg.groups().into_iter().map(|(title, specs)| {
|
||||
let mut rows = vec![];
|
||||
let mut sub = "";
|
||||
for s in specs {
|
||||
if s.sub != sub { sub = &s.sub; if !sub.is_empty() { rows.push(heading(&brand(sub))); } }
|
||||
rows.push(self.row(s));
|
||||
rows.extend(self.text_row(s));
|
||||
}
|
||||
let n = rows.iter().filter(|r| r.changed && r.kind == Kind::Choice).count(); // (a typed value is its choice row's)
|
||||
rows.push(Row {
|
||||
kind: Kind::Action, key: format!("act:reset:{title}"), off: n == 0, locked: n == 0,
|
||||
label: if self.game.is_some() { "Use global for this section".into() } else { "Reset this section".into() },
|
||||
help: match (self.game.is_some(), n) {
|
||||
(true, 0) => "Every setting here follows the global one.".into(),
|
||||
(false, 0) => "Every setting here is the engine's default.".into(),
|
||||
(true, n) => format!("{n} setting{} here {} the game's own: back to the global one.", plural(n), if n == 1 { "is" } else { "are" }),
|
||||
(false, n) => format!("{n} setting{} here {} not the default: back to the engine's default.", plural(n), if n == 1 { "is" } else { "are" }),
|
||||
},
|
||||
button: if self.game.is_some() { "Use global".into() } else { "Reset".into() }, ..Default::default()
|
||||
});
|
||||
Section { title: brand(&title), rows }
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// The few big choices, for the strip at the top.
|
||||
pub fn quick(&self) -> Vec<Row> { self.reg.specs.iter().filter(|s| s.quick).map(|s| self.row(s)).collect() }
|
||||
|
||||
/// What picking option `option` of a choice row stores: None: nothing to do; Some(None): stop setting it (the
|
||||
/// engine's default on the Settings page, the global value in a game); Some(Some(v)): store v.
|
||||
pub fn pick(&self, key: &str, option: usize) -> Option<Option<Value>> {
|
||||
let spec = self.reg.get(key)?;
|
||||
if !spec.saved || self.locked.contains_key(key) { return None; }
|
||||
if self.game.is_some() {
|
||||
if option == 0 { return Some(None); }
|
||||
return spec.choices.get(option - 1).map(|c| Some(c.value.clone()));
|
||||
}
|
||||
let v = &spec.choices.get(option)?.value;
|
||||
Some(if same(v, &spec.default) { None } else { Some(v.clone()) })
|
||||
}
|
||||
|
||||
/// What a typed custom value stores (as [`Self::pick`]), or why it cannot be used.
|
||||
pub fn typed(&self, key: &str, text: &str) -> Result<Option<Option<Value>>, String> {
|
||||
let Some(spec) = self.reg.get(key) else { return Ok(None) };
|
||||
let t = text.trim();
|
||||
if t.is_empty() {
|
||||
let cur = self.value(spec);
|
||||
return Ok((spec.position(&cur).is_none()).then_some(None)); // back to the choice above
|
||||
}
|
||||
let v = match key {
|
||||
"hz" => {
|
||||
let m = t.trim_end_matches(['x', 'X', '×']).trim().parse::<u8>().ok().filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m))
|
||||
.ok_or_else(|| "The multiplier is a whole number from 2 to 10".to_string())?;
|
||||
Value::from(30 * u32::from(m))
|
||||
}
|
||||
"output_res" => {
|
||||
let (w, h) = summit_core::profile::parse_res(t).ok_or_else(|| "A size like 2560x1440, from 320x240 to 7680x4320".to_string())?;
|
||||
Value::String(format!("{w}x{h}"))
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(if self.game.is_none() && same(&v, &spec.default) { None } else { Some(v) }))
|
||||
}
|
||||
|
||||
/// The presets, each with what it sets in this registry's words, and what the values are now: a preset's name,
|
||||
/// "Custom", or (a game that sets none of them) "Follows global (...)".
|
||||
pub fn presets(&self) -> (Vec<PresetView>, String) {
|
||||
let now = presets::current(&|k| self.value_of(k));
|
||||
let views = presets::PRESETS.iter().map(|p| PresetView {
|
||||
id: p.id, name: p.name.into(), summary: p.summary.into(), detail: p.detail.into(), active: now.is_some_and(|n| n.id == p.id),
|
||||
sets: p.values().iter().map(|(k, v)| match self.reg.get(k) { Some(s) => format!("{}: {}", brand(&s.label), s.name_of(v)), None => format!("{k}: not a setting of this engine") }).collect(),
|
||||
}).collect();
|
||||
let name = |p: Option<&presets::Preset>| p.map_or("Custom", |p| p.name).to_string();
|
||||
let own_any = presets::keys().iter().any(|k| self.own(k).is_some());
|
||||
let state = match self.game { Some(_) if !own_any => format!("Follows global ({})", name(now)), _ => name(now) };
|
||||
(views, state)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PresetView { pub id: &'static str, pub name: String, pub summary: String, pub detail: String, pub sets: Vec<String>, pub active: bool }
|
||||
|
||||
fn capital(s: &str) -> String { let mut c = s.chars(); c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default() }
|
||||
fn plural(n: usize) -> &'static str { if n == 1 { "" } else { "s" } }
|
||||
|
||||
// ---- the launcher's own settings (ui.toml) ----
|
||||
|
||||
pub const ANIM_SPEEDS: &[f32] = &[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0];
|
||||
const LAYOUT_NAMES: &[&str] = &["Big picture", "Grid", "List"];
|
||||
const STYLE_NAMES: &[&str] = &["Smooth", "Snappy", "Bouncy"];
|
||||
|
||||
fn nearest(all: &[f32], v: f32) -> usize { (0..all.len()).min_by(|a, b| (all[*a] - v).abs().total_cmp(&(all[*b] - v).abs())).unwrap_or(0) }
|
||||
|
||||
/// What the launcher section shows besides ui.toml's values.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LauncherInfo {
|
||||
/// (key, name) of each theme, in the UI's order.
|
||||
pub themes: Vec<(String, String)>,
|
||||
pub clips_dir: String,
|
||||
pub hotkey: String,
|
||||
pub nvidia: String,
|
||||
pub nvidia_button: String,
|
||||
pub nvidia_ok: bool,
|
||||
pub about: String,
|
||||
pub files: String,
|
||||
}
|
||||
|
||||
/// The option index of each ui.toml row for `s`.
|
||||
fn ui_index(s: &UiSettings, key: &str, info: &LauncherInfo) -> usize {
|
||||
match key {
|
||||
"layout" => s.layout_index(),
|
||||
"theme" => info.themes.iter().position(|(k, _)| *k == s.theme).unwrap_or(0),
|
||||
"scale" => nearest(summit_core::ui::UI_SCALES, s.ui_scale),
|
||||
"anim_speed" => nearest(ANIM_SPEEDS, s.anim_speed),
|
||||
"anim_style" => s.anim_style_index(),
|
||||
"overlay_key" => s.overlay_key_choices().iter().position(|k| *k == s.overlay_key).unwrap_or(0),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn launcher_section(s: &UiSettings, info: &LauncherInfo) -> Section {
|
||||
let d = UiSettings::default();
|
||||
let choice = |key: &str, label: &str, help: &str, options: Vec<String>, seg: bool| {
|
||||
let (value, def) = (ui_index(s, key, info), ui_index(&d, key, info));
|
||||
Row { kind: if key == "theme" { Kind::Theme } else { Kind::Choice }, key: format!("ui:{key}"), label: label.into(), help: help.into(),
|
||||
base: format!("Default: {}", options.get(def).cloned().unwrap_or_default()), hints: vec![String::new(); options.len()], options, value, changed: value != def, seg, ..Default::default() }
|
||||
};
|
||||
let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let rows = vec![
|
||||
heading("Appearance"),
|
||||
choice("layout", "Layout", "Big picture is cover first and made for a TV and a controller. List is a dense table.", names(LAYOUT_NAMES), true),
|
||||
choice("theme", "Theme", "Colours of the whole launcher.", info.themes.iter().map(|(_, n)| n.clone()).collect(), false),
|
||||
choice("scale", "Interface size", "Scales the whole launcher, on top of your system's display scale.", summit_core::ui::UI_SCALES.iter().map(|c| format!("{:.0}%", c * 100.0)).collect(), true),
|
||||
heading("Motion"),
|
||||
choice("anim_speed", "Animation speed", "How fast everything moves. Off turns every animation off.", ANIM_SPEEDS.iter().map(|v| if *v < 0.01 { "Off".to_string() } else { format!("{:.0}%", v * 100.0) }).collect(), false),
|
||||
choice("anim_style", "Animation style", "Smooth eases out gently, Snappy is short and sharp, Bouncy overshoots a little.", names(STYLE_NAMES), true),
|
||||
heading("In-game overlay"),
|
||||
choice("overlay_key", "Overlay key", "Opens Summit's overlay while you play. Esc is never taken from the game.", s.overlay_key_choices(), true),
|
||||
heading("Clips"),
|
||||
Row { kind: Kind::Action, key: "act:clips".into(), label: "Clips folder".into(), help: format!("{}/<game>/ · {}", info.clips_dir, info.hotkey), button: "Open".into(), ..Default::default() },
|
||||
heading("NVIDIA"),
|
||||
Row { kind: Kind::Action, key: "act:nvidia".into(), label: "NVIDIA VFG and RTX VSR".into(), help: info.nvidia.clone(), button: info.nvidia_button.clone(), locked: !info.nvidia_ok, ..Default::default() },
|
||||
heading("About"),
|
||||
note(info.about.clone()),
|
||||
note(info.files.clone()),
|
||||
{
|
||||
let n = [("layout"), ("theme"), ("scale"), ("anim_speed"), ("anim_style"), ("overlay_key")].iter().filter(|k| ui_index(s, k, info) != ui_index(&d, k, info)).count();
|
||||
Row { kind: Kind::Action, key: "act:reset:Launcher".into(), label: "Reset this section".into(), off: n == 0, locked: n == 0, button: "Reset".into(),
|
||||
help: if n == 0 { "Every setting here is Summit's default.".into() } else { format!("{n} setting{} here {} not the default: back to Summit's own.", plural(n), if n == 1 { "is" } else { "are" }) }, ..Default::default() }
|
||||
},
|
||||
];
|
||||
Section { title: "Launcher".into(), rows }
|
||||
}
|
||||
|
||||
/// Set a ui.toml row to option `option` (None: its default). False for a row that is not one of these.
|
||||
pub fn launcher_pick(s: &mut UiSettings, key: &str, option: Option<usize>, info: &LauncherInfo) -> bool {
|
||||
let d = UiSettings::default();
|
||||
let i = option.unwrap_or_else(|| ui_index(&d, key, info));
|
||||
match key {
|
||||
"layout" => s.layout = summit_core::ui::LAYOUTS.get(i).unwrap_or(&"bigpicture").to_string(),
|
||||
"theme" => if let Some((k, _)) = info.themes.get(i) { s.theme = k.clone(); },
|
||||
"scale" => s.ui_scale = *summit_core::ui::UI_SCALES.get(i).unwrap_or(&1.0),
|
||||
"anim_speed" => s.anim_speed = *ANIM_SPEEDS.get(i).unwrap_or(&1.0),
|
||||
"anim_style" => s.anim_style = summit_core::ui::ANIM_STYLES.get(i).unwrap_or(&"smooth").to_string(),
|
||||
"overlay_key" => if let Some(k) = s.overlay_key_choices().get(i) { s.overlay_key = k.clone(); },
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
pub const LAUNCHER_KEYS: &[&str] = &["layout", "theme", "scale", "anim_speed", "anim_style", "overlay_key"];
|
||||
|
||||
// ---- a launch profile's own rows (monitor, window, arguments): data::edit_rows, as rows ----
|
||||
|
||||
pub fn launch_section(title: &str, rows: Vec<crate::data::EditRow>, defaults: bool) -> Section {
|
||||
let rows = rows.into_iter().map(|r| match r.kind {
|
||||
crate::data::RowKind::Header => heading(&r.label),
|
||||
crate::data::RowKind::Choice => Row { kind: Kind::Choice, key: format!("prof:{}", r.key), label: r.label, help: r.hint, hints: vec![String::new(); r.options.len()],
|
||||
changed: if defaults { r.value != 0 } else { r.own }, base: r.options.first().map(|o| if defaults { format!("Not set: {o}") } else { o.clone() }).unwrap_or_default(),
|
||||
options: r.options, value: r.value, ..Default::default() },
|
||||
crate::data::RowKind::Text => Row { kind: Kind::Text, key: format!("prof:{}", r.key), label: r.label, help: r.hint, changed: if defaults { !r.text.is_empty() } else { r.own },
|
||||
text: r.text, placeholder: r.placeholder, ..Default::default() },
|
||||
}).collect();
|
||||
Section { title: title.into(), rows }
|
||||
}
|
||||
|
||||
// ---- search and layout ----
|
||||
|
||||
fn matches(r: &Row, section: &str, words: &[String]) -> bool {
|
||||
if !matches!(r.kind, Kind::Choice | Kind::Text | Kind::Theme | Kind::Action) || r.key.starts_with("act:reset") { return false; }
|
||||
let hay = format!("{} {} {} {} {} {}", r.label, r.help, r.key.rsplit(':').next().unwrap_or(""), r.options.join(" "), section, r.impact.iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>().join(" ")).to_lowercase();
|
||||
words.iter().all(|w| hay.contains(w))
|
||||
}
|
||||
|
||||
/// The rows that match the search, from every section, each section's under its title. Every word has to be in
|
||||
/// the row's name, help, choices or section. Nothing found: one note saying so.
|
||||
pub fn search(sections: &[Section], query: &str) -> Vec<Row> {
|
||||
let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
|
||||
let mut out = vec![];
|
||||
for s in sections {
|
||||
let hits: Vec<Row> = s.rows.iter().filter(|r| matches(r, &s.title, &words)).cloned().collect();
|
||||
if hits.is_empty() { continue; }
|
||||
out.push(heading(&s.title));
|
||||
out.extend(hits);
|
||||
}
|
||||
if out.is_empty() { out.push(note(format!("No setting matches \"{}\". Search looks in names, help texts, choices and section names.", query.trim()))); }
|
||||
out
|
||||
}
|
||||
|
||||
pub const GAP: f32 = 8.0;
|
||||
/// Height of a row in logical pixels.
|
||||
pub fn height(r: &Row) -> f32 {
|
||||
match r.kind {
|
||||
Kind::Heading => 36.0,
|
||||
Kind::Theme => 148.0,
|
||||
Kind::Note => 30.0 + 18.0 * (r.help.chars().count() / 110) as f32,
|
||||
_ => if r.impact.is_empty() { 64.0 } else { 82.0 },
|
||||
}
|
||||
}
|
||||
/// Where each row goes: (y, height), and the height of them all.
|
||||
pub fn layout(rows: &[Row]) -> (Vec<(f32, f32)>, f32) {
|
||||
let mut y = 0.0;
|
||||
let v = rows.iter().map(|r| { let h = height(r); let at = (y, h); y += h + GAP; at }).collect();
|
||||
(v, y)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
const REG: &str = r#"{"path": "/tmp/s.json", "specs": [
|
||||
{"key": "interp", "label": "Frame generation", "group": "Frame generation", "sub": "Basics", "help": "SmoovPlay draws new frames.", "default": true, "quick": true,
|
||||
"impact": {"picture": "Smoother motion.", "speed": "Adds delay."}, "choices": [{"value": true, "name": "On", "hint": ""}, {"value": false, "name": "Off", "hint": "No new frames."}]},
|
||||
{"key": "hz", "label": "Frame multiplier", "group": "Frame generation", "sub": "Basics", "default": 60, "quick": true, "applies": {"key": "interp", "values": [true]},
|
||||
"choices": [{"value": 60, "name": "2x", "hint": ""}, {"value": 90, "name": "3x", "hint": ""}, {"value": 120, "name": "4x", "hint": ""}]},
|
||||
{"key": "model", "label": "Interpolation model", "group": "Frame generation", "sub": "AI model", "default": "4.22.lite", "live": false,
|
||||
"choices": [{"value": "4.22.lite", "name": "RIFE 4.22 lite", "hint": ""}, {"value": "vfg", "name": "NVIDIA VFG", "hint": ""}]},
|
||||
{"key": "motion", "label": "Motion detail", "group": "Frame generation", "sub": "AI model", "default": "auto", "applies": {"key": "model", "values": ["4.22.lite"]},
|
||||
"choices": [{"value": "auto", "name": "Auto", "hint": ""}, {"value": "full", "name": "Full", "hint": ""}, {"value": "half", "name": "Half", "hint": ""}]},
|
||||
{"key": "scaler", "label": "Upscaler", "group": "Upscaling", "default": "fsr", "quick": true,
|
||||
"choices": [{"value": "off", "name": "Off", "hint": ""}, {"value": "fsr", "name": "AMD FSR 1", "hint": ""}, {"value": "vsr", "name": "NVIDIA RTX VSR", "hint": ""}]},
|
||||
{"key": "output_res", "label": "Output resolution", "group": "Upscaling", "default": "screen",
|
||||
"choices": [{"value": "screen", "name": "Same as the screen", "hint": ""}, {"value": "1920x1080", "name": "1080p", "hint": ""}]},
|
||||
{"key": "vsync", "label": "VSync", "group": "Display", "default": false, "choices": [{"value": false, "name": "Off", "hint": ""}, {"value": true, "name": "On", "hint": ""}]},
|
||||
{"key": "fullscreen", "label": "Fullscreen", "group": "Display", "default": false, "choices": [{"value": false, "name": "Off", "hint": ""}, {"value": true, "name": "On", "hint": ""}]},
|
||||
{"key": "capture_size", "label": "Capture card resolution", "group": "Sources", "default": "1080p", "experimental": true, "sources": ["capture"],
|
||||
"elsewhere": {"": "Only used with a capture card."}, "choices": [{"value": "1080p", "name": "1080p", "hint": ""}, {"value": "2160p", "name": "4K", "hint": ""}]},
|
||||
{"key": "simulate_30", "label": "Simulate a 30 fps game", "group": "Sources", "default": false, "saved": false, "choices": [{"value": false, "name": "Off", "hint": ""}, {"value": true, "name": "On", "hint": ""}]},
|
||||
{"key": "aa", "label": "Anti-aliasing", "group": "Anti-aliasing", "default": "off", "choices": ["off", "fxaa", "smaa"]},
|
||||
{"key": "strength", "label": "Strength", "group": "Anti-aliasing", "default": 0.5, "type": "range"}
|
||||
]}"#;
|
||||
|
||||
type Map = BTreeMap<String, Value>;
|
||||
fn map(v: &[(&str, Value)]) -> Map { v.iter().map(|(k, v)| (k.to_string(), v.clone())).collect() }
|
||||
fn row<'a>(s: &'a [Section], key: &str) -> &'a Row { s.iter().flat_map(|s| &s.rows).find(|r| r.key == key).unwrap_or_else(|| panic!("no row {key}")) }
|
||||
|
||||
#[test]
|
||||
fn every_setting_of_the_registry_gets_a_row_in_its_section() {
|
||||
let reg = Registry::parse(REG).unwrap();
|
||||
let (saved, base, locked) = (Map::new(), Map::new(), BTreeMap::<String, String>::new());
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
let s = cx.sections();
|
||||
assert_eq!(s.iter().map(|s| s.title.as_str()).collect::<Vec<_>>(), vec!["Frame generation", "Upscaling", "Display", "Sources", "Anti-aliasing"]);
|
||||
for spec in ®.specs { let _ = row(&s, &format!("eng:{}", spec.key)); }
|
||||
// headings where the sub heading changes, a reset row at the end
|
||||
let fg: Vec<&str> = s[0].rows.iter().map(|r| if r.kind == Kind::Heading { r.label.as_str() } else { r.key.as_str() }).collect();
|
||||
assert_eq!(fg, vec!["BASICS", "eng:interp", "eng:hz", "engtext:hz", "AI MODEL", "eng:model", "eng:motion", "act:reset:Frame generation"]);
|
||||
let i = row(&s, "eng:interp");
|
||||
assert_eq!((i.label.as_str(), i.help.as_str(), i.value, i.changed, i.off), ("Frame generation", "Summit draws new frames.", 0, false, false));
|
||||
assert_eq!(i.impact, vec![("Picture".to_string(), "Smoother motion.".to_string()), ("Speed".to_string(), "Adds delay.".to_string())]);
|
||||
assert_eq!((i.options.clone(), i.hints[1].as_str(), i.base.as_str()), (vec!["On".to_string(), "Off".to_string()], "No new frames.", "Default: On"));
|
||||
assert_eq!(row(&s, "eng:model").tag, "Next start");
|
||||
// a section and a kind of setting this launcher has never heard of
|
||||
let aa = row(&s, "eng:aa");
|
||||
assert_eq!((aa.options.clone(), aa.locked), (vec!["off".to_string(), "fxaa".to_string(), "smaa".to_string()], false));
|
||||
let st = row(&s, "eng:strength");
|
||||
assert!(st.locked && st.off && st.options == vec!["0.5"] && st.why.contains("in-game overlay"));
|
||||
// only one session: cannot be set from here; a capture card's: said, not greyed, on the Settings page
|
||||
assert!(row(&s, "eng:simulate_30").locked);
|
||||
let c = row(&s, "eng:capture_size");
|
||||
assert!(c.experimental && !c.off && c.note == "Only used with a capture card.");
|
||||
assert_eq!(cx.quick().iter().map(|r| r.key.as_str()).collect::<Vec<_>>(), vec!["eng:interp", "eng:hz", "eng:scaler"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_show_what_is_saved_and_say_when_a_setting_is_not_used() {
|
||||
let reg = Registry::parse(REG).unwrap();
|
||||
let saved = map(&[("interp", json!(false)), ("scaler", json!("vsr")), ("hz", json!(210)), ("vsync", json!("yes")), ("model", json!("vfg"))]);
|
||||
let (base, locked) = (Map::new(), BTreeMap::from([("fullscreen".to_string(), "Follows Window mode.".to_string())]));
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
let s = cx.sections();
|
||||
let sc = row(&s, "eng:scaler");
|
||||
assert_eq!((sc.options[sc.value].as_str(), sc.changed), ("NVIDIA RTX VSR", true));
|
||||
let hz = row(&s, "eng:hz");
|
||||
assert_eq!((hz.options[hz.value].as_str(), hz.off, hz.why.as_str()), ("7x (custom)", true, "Only used while Frame generation is On (now Off)."));
|
||||
assert_eq!((row(&s, "engtext:hz").text.as_str(), row(&s, "engtext:hz").changed), ("7", true));
|
||||
assert_eq!(row(&s, "eng:motion").why, "Only used while Interpolation model is RIFE 4.22 lite (now NVIDIA VFG).");
|
||||
// a value the engine would not take is the default, as in the engine
|
||||
assert_eq!((row(&s, "eng:vsync").value, row(&s, "eng:vsync").changed), (0, false));
|
||||
let f = row(&s, "eng:fullscreen");
|
||||
assert!(f.locked && f.why == "Follows Window mode.");
|
||||
assert_eq!(cx.pick("fullscreen", 1), None);
|
||||
assert!(row(&s, "act:reset:Frame generation").help.starts_with("3 settings"));
|
||||
assert!(row(&s, "act:reset:Display").locked);
|
||||
// what picking stores: the default is "not in the file"
|
||||
assert_eq!(cx.pick("scaler", 0), Some(Some(json!("off"))));
|
||||
assert_eq!(cx.pick("scaler", 1), Some(None));
|
||||
assert_eq!(cx.pick("scaler", 9), None);
|
||||
assert_eq!(cx.pick("simulate_30", 1), None);
|
||||
// the default launch profile forcing a value is what games get, whatever the file says
|
||||
let base = map(&[("scaler", json!("off"))]);
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
let sc = cx.sections(); let sc = row(&sc, "eng:scaler");
|
||||
assert_eq!(sc.options[sc.value], "Off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_follows_the_global_setting_or_sets_its_own() {
|
||||
let reg = Registry::parse(REG).unwrap();
|
||||
let saved = map(&[("scaler", json!("vsr"))]);
|
||||
let (base, locked) = (Map::new(), BTreeMap::<String, String>::new());
|
||||
let own = map(&[("vsync", json!(true)), ("hz", json!(210))]);
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: Some((&own, "window")), locked: &locked };
|
||||
let s = cx.sections();
|
||||
let sc = row(&s, "eng:scaler");
|
||||
assert_eq!((sc.options[0].as_str(), sc.value, sc.changed, sc.base.as_str()), ("Global · NVIDIA RTX VSR", 0, false, "Global: NVIDIA RTX VSR"));
|
||||
let v = row(&s, "eng:vsync");
|
||||
assert_eq!((v.options.clone(), v.value, v.changed), (vec!["Global · Off".to_string(), "Off".to_string(), "On".to_string()], 2, true));
|
||||
assert_eq!(row(&s, "eng:hz").options.last().unwrap(), "7x (custom)");
|
||||
assert_eq!(cx.pick("scaler", 0), Some(None)); // use global: left out of the game's file
|
||||
assert_eq!(cx.pick("scaler", 2), Some(Some(json!("fsr")))); // the default too is the game's own choice
|
||||
// a capture card's setting on a game that is a window: greyed, with the engine's reason
|
||||
let c = row(&s, "eng:capture_size");
|
||||
assert!(c.off && !c.locked && c.why == "Only used with a capture card." && c.note.is_empty());
|
||||
let cap = EngineCx { game: Some((&own, "capture")), ..EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked } };
|
||||
assert!(!row(&cap.sections(), "eng:capture_size").off);
|
||||
assert!(row(&s, "act:reset:Display").help.starts_with("1 setting here is the game's own"));
|
||||
assert_eq!(row(&s, "act:reset:Display").button, "Use global");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_custom_values() {
|
||||
let reg = Registry::parse(REG).unwrap();
|
||||
let (saved, base, locked) = (Map::new(), Map::new(), BTreeMap::<String, String>::new());
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
assert_eq!(cx.typed("hz", " 7x "), Ok(Some(Some(json!(210)))));
|
||||
assert_eq!(cx.typed("hz", "2"), Ok(Some(None))); // the default: nothing stored
|
||||
assert!(cx.typed("hz", "11").is_err() && cx.typed("hz", "1.5").is_err());
|
||||
assert_eq!(cx.typed("output_res", " 2560 x 1080 "), Ok(Some(Some(json!("2560x1080")))));
|
||||
assert!(cx.typed("output_res", "99x99").is_err() && cx.typed("output_res", "big").is_err());
|
||||
assert_eq!(cx.typed("hz", ""), Ok(None)); // nothing custom to clear
|
||||
let saved = map(&[("output_res", json!("2560x1080"))]);
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
assert_eq!(cx.typed("output_res", " "), Ok(Some(None))); // empty: back to the choice above
|
||||
let s = cx.sections();
|
||||
assert_eq!(row(&s, "eng:output_res").options.last().unwrap(), "2560 x 1080 (custom)");
|
||||
assert_eq!(row(&s, "engtext:output_res").text, "2560x1080");
|
||||
// in a game the default is a value of its own too
|
||||
let own = Map::new();
|
||||
let g = EngineCx { game: Some((&own, "window")), ..EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked } };
|
||||
assert_eq!(g.typed("hz", "2"), Ok(Some(Some(json!(60)))));
|
||||
assert_eq!(row(&g.sections(), "engtext:output_res").text, ""); // the global custom size is not the game's own
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_say_what_they_set_and_turn_custom() {
|
||||
let reg = Registry::parse(REG).unwrap();
|
||||
let (base, locked) = (Map::new(), BTreeMap::<String, String>::new());
|
||||
let saved = Map::new();
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
let (views, state) = cx.presets();
|
||||
assert_eq!(state, "Balanced"); // the engine's defaults
|
||||
assert_eq!(views.iter().filter(|v| v.active).map(|v| v.name.as_str()).collect::<Vec<_>>(), vec!["Balanced"]);
|
||||
assert!(views[0].sets.contains(&"Motion detail: Full".to_string()) && views[0].sets.contains(&"VSync: On".to_string()));
|
||||
let saved = map(&[("vsync", json!(true))]);
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
assert_eq!(cx.presets().1, "Custom");
|
||||
let saved = map(&[("vsync", json!(true)), ("motion", json!("full"))]);
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
assert_eq!(cx.presets().1, "Quality");
|
||||
// a game: follows the global one until it sets one of the preset's settings itself
|
||||
let own = Map::new();
|
||||
let g = EngineCx { game: Some((&own, "window")), ..EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked } };
|
||||
assert_eq!(g.presets().1, "Follows global (Quality)");
|
||||
let own = map(&[("interp", json!(false))]);
|
||||
let g = EngineCx { game: Some((&own, "window")), ..EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked } };
|
||||
assert_eq!(g.presets().1, "Custom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_finds_rows_across_sections() {
|
||||
let reg = Registry::parse(REG).unwrap();
|
||||
let (saved, base, locked) = (Map::new(), Map::new(), BTreeMap::<String, String>::new());
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
let mut s = vec![launcher_section(&UiSettings::default(), &LauncherInfo { themes: vec![("midnight".into(), "Midnight".into())], ..Default::default() })];
|
||||
s.extend(cx.sections());
|
||||
let keys = |q: &str| search(&s, q).iter().filter(|r| r.kind != Kind::Heading).map(|r| r.key.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(keys("vsync"), vec!["eng:vsync"]);
|
||||
assert_eq!(keys("FRAME multi"), vec!["eng:hz", "engtext:hz"]); // every word, any case
|
||||
assert_eq!(keys("rtx"), vec!["act:nvidia", "eng:scaler"]); // an action's name, a choice's name
|
||||
assert_eq!(keys("anti"), vec!["eng:aa", "eng:strength"]); // a section's name
|
||||
assert_eq!(keys("theme"), vec!["ui:theme"]);
|
||||
assert_eq!(search(&s, "upscal")[0].label, "UPSCALING"); // under its section's title
|
||||
let none = search(&s, "zzz");
|
||||
assert!(none.len() == 1 && none[0].kind == Kind::Note && none[0].help.contains("zzz"));
|
||||
assert!(!keys("reset").iter().any(|k| k.starts_with("act:reset")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launcher_rows_read_and_write_ui_toml_values() {
|
||||
let info = LauncherInfo { themes: vec![("midnight".into(), "Midnight".into()), ("steam".into(), "Steam blue".into())], ..Default::default() };
|
||||
let mut s = UiSettings::default();
|
||||
let sec = launcher_section(&s, &info);
|
||||
assert!(sec.rows.iter().all(|r| !r.changed) && sec.changed() == 0);
|
||||
assert!(launcher_pick(&mut s, "theme", Some(1), &info) && launcher_pick(&mut s, "anim_speed", Some(0), &info) && launcher_pick(&mut s, "layout", Some(2), &info));
|
||||
assert_eq!((s.theme.as_str(), s.anim_speed, s.layout.as_str()), ("steam", 0.0, "list"));
|
||||
let sec = launcher_section(&s, &info);
|
||||
let r = |k: &str| sec.rows.iter().find(|r| r.key == k).unwrap();
|
||||
assert_eq!((r("ui:theme").value, r("ui:theme").changed, r("ui:theme").kind), (1, true, Kind::Theme));
|
||||
assert_eq!(r("ui:anim_speed").options[r("ui:anim_speed").value], "Off");
|
||||
assert_eq!(sec.changed(), 3);
|
||||
assert!(r("act:reset:Launcher").help.starts_with("3 settings"));
|
||||
for k in LAUNCHER_KEYS { assert!(launcher_pick(&mut s, k, None, &info)); } // back to the default
|
||||
assert_eq!(s, UiSettings::default());
|
||||
assert!(!launcher_pick(&mut s, "nonsense", Some(0), &info));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_are_laid_out_one_under_the_other() {
|
||||
let rows = vec![heading("A"), Row::default(), Row { impact: vec![("Speed".into(), "x".into())], ..Default::default() }, Row { kind: Kind::Theme, ..Default::default() }];
|
||||
let (at, total) = layout(&rows);
|
||||
assert_eq!(at, vec![(0.0, 36.0), (44.0, 64.0), (116.0, 82.0), (206.0, 148.0)]);
|
||||
assert_eq!(total, 362.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_real_registry_makes_rows_when_python_is_here() {
|
||||
let engine = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../engine");
|
||||
let Ok(reg) = Registry::load(&engine) else { eprintln!("skipped: no python3 to ask the engine"); return };
|
||||
let (saved, base, locked) = (Map::new(), Map::new(), BTreeMap::<String, String>::new());
|
||||
let cx = EngineCx { reg: ®, saved: &saved, base: &base, game: None, locked: &locked };
|
||||
let s = cx.sections();
|
||||
assert_eq!(s.iter().map(|s| s.settings()).sum::<usize>(), reg.specs.len() + 2); // every setting, and the two typed ones
|
||||
assert!(s.iter().all(|s| s.changed() == 0), "the defaults are not 'changed'");
|
||||
assert_eq!(cx.presets().1, "Balanced");
|
||||
assert!(s.iter().flat_map(|s| &s.rows).all(|r| !r.label.contains("SmoovPlay") && !r.help.contains("SmoovPlay")));
|
||||
assert!(cx.quick().len() >= 4);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,16 @@
|
||||
//! SUMMIT_SIZE=1600x900 window size in pixels
|
||||
//! SUMMIT_VIEW=home|library|unfiltered|settings SUMMIT_LAYOUT=bigpicture|grid|list SUMMIT_THEME=<key>
|
||||
//! SUMMIT_DETAIL=<entry id or part of a title> open that game's page
|
||||
//! SUMMIT_FOCUS=<n> focused item in the library, unfiltered list or settings
|
||||
//! SUMMIT_FOCUS=<n> focused item in the library or unfiltered list; focused row of the settings pane
|
||||
//! SUMMIT_EDITOR=1 with SUMMIT_DETAIL: the game's profile (the settings pane for that game)
|
||||
//! SUMMIT_STATS=1 with SUMMIT_DETAIL: the game's Statistics view
|
||||
//! SUMMIT_COMPARE=1 with SUMMIT_DETAIL: the Compare dialog
|
||||
//! The settings pane (the Settings page, or a profile with SUMMIT_EDITOR):
|
||||
//! SUMMIT_SECTION=<name or number> its section ("launcher", "frame generation", "upscaling"...)
|
||||
//! SUMMIT_SEARCH=<text> what is typed in its search box
|
||||
//! SUMMIT_ZONE=0|1|2|3 where the focus is: presets, the quick strip, the section list, the rows
|
||||
//! SUMMIT_PRESET=<n>, SUMMIT_QUICK=<n> the focused preset and quick tile
|
||||
//! (SUMMIT_ENGINE_SETTINGS=<file> reads and writes that file instead of the engine's own settings.json.)
|
||||
//! SUMMIT_KEYS="Down Right Enter" press keys before the render
|
||||
//! SUMMIT_SCALE=1.25 interface scale
|
||||
//!
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
// Summit launcher window: navbar, the four views, a game's page, the art backdrop and keyboard navigation.
|
||||
import { Theme, Palette } from "theme.slint";
|
||||
import { Lib, Prefs, Game, URow, Detail, PRow, PickRow, AddItem, SteamAccount, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint";
|
||||
import { Lib, Game, URow, Detail, PickRow, AddItem, SteamAccount, StatTile, SessRow, SessField, CmpRow, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint";
|
||||
import { AddDialog } from "add.slint";
|
||||
import { HomeView } from "home.slint";
|
||||
import { LibraryView, UnfilteredView } from "library.slint";
|
||||
import { DetailView } from "detail.slint";
|
||||
import { SettingsView } from "settings.slint";
|
||||
import { Sx, SRow, SNav, SPreset } from "pane.slint";
|
||||
import { PlayingView } from "playing.slint";
|
||||
import { Splash } from "splash.slint";
|
||||
export { Lib, Prefs, Game, URow, Detail, PRow, PickRow, AddItem, SteamAccount, Palette }
|
||||
export { Lib, Sx, SRow, SNav, SPreset, Game, URow, Detail, PickRow, AddItem, SteamAccount, StatTile, SessRow, SessField, CmpRow, Palette }
|
||||
|
||||
component NavTab inherits Rectangle {
|
||||
in property <string> label;
|
||||
@@ -77,7 +78,6 @@ export component MainWindow inherits Window {
|
||||
in-out property <int> lib-focus <=> library.sel;
|
||||
in-out property <int> lib-zone <=> library.zone;
|
||||
in-out property <int> unf-focus <=> unfiltered.sel;
|
||||
in-out property <int> settings-row <=> settings.srow;
|
||||
out property <int> hero-idx: home.hero-idx;
|
||||
property <length> navbar-h: Theme.big ? 76px : 60px;
|
||||
property <length> hint-h: Theme.big ? 40px : 0px;
|
||||
@@ -87,10 +87,13 @@ export component MainWindow inherits Window {
|
||||
public function goto(v: int) {
|
||||
root.view = v;
|
||||
if (v == 0) { home.sync(); Lib.focus-game(home.hero-idx); }
|
||||
if (v == 3) { Sx.enter(); }
|
||||
}
|
||||
public function close-detail() {
|
||||
root.detail-open = false;
|
||||
Lib.editor-open = false;
|
||||
if (Lib.editor-open) { Lib.close-profile(); }
|
||||
Lib.stats-open = false;
|
||||
Lib.cmp-open = false;
|
||||
Lib.accounts-open = false;
|
||||
if (root.view == 0) { Lib.focus-game(home.hero-idx); }
|
||||
}
|
||||
@@ -111,15 +114,15 @@ export component MainWindow inherits Window {
|
||||
// a game is running: only the "now playing" screen takes keys
|
||||
if (Lib.playing) { playing.key(e); return accept; }
|
||||
if (Lib.add-open) { return add.key(e) || e.text == Key.Tab || e.text == Key.Backtab ? accept : reject; }
|
||||
if (root.detail-open) {
|
||||
if (e.text == Key.Tab || e.text == Key.Backtab) { return accept; }
|
||||
return detail.key(e) ? accept : reject;
|
||||
}
|
||||
// the defaults editor (Settings) keeps the keys while it is open
|
||||
if (Lib.editor-open && Lib.editor-defaults) { return settings.key(e) ? accept : (e.text == Key.Tab || e.text == Key.Backtab ? accept : reject); }
|
||||
// a game's page: its overlays take Tab too (LB / RB change section in the profile)
|
||||
if (root.detail-open) { return detail.key(e) ? accept : reject; }
|
||||
if (root.view == 3 && Lib.nvidia-open) { return settings.key(e) ? accept : reject; }
|
||||
if (e.text == Key.Backtab || (e.text == Key.Tab && e.modifiers.shift)) { root.goto(Math.mod(root.view + 3, 4)); root.zone = 1; return accept; }
|
||||
if (e.text == Key.Tab) { root.goto(Math.mod(root.view + 1, 4)); root.zone = 1; return accept; }
|
||||
if (e.text == "/" || (e.modifiers.control && e.text == "f")) { root.goto(1); root.zone = 1; library.focus-search(); return accept; }
|
||||
if (e.text == "/" || (e.modifiers.control && e.text == "f")) {
|
||||
if (root.view == 3) { root.zone = 1; settings.focus-search(); } else { root.goto(1); root.zone = 1; library.focus-search(); }
|
||||
return accept;
|
||||
}
|
||||
if (root.zone == 0) {
|
||||
if (e.text == Key.LeftArrow) { root.goto(Math.max(0, root.view - 1)); return accept; }
|
||||
if (e.text == Key.RightArrow) { root.goto(Math.min(3, root.view + 1)); return accept; }
|
||||
@@ -216,7 +219,8 @@ export component MainWindow inherits Window {
|
||||
VerticalLayout { alignment: center; KeyCap { key: "Enter"; label: root.detail-open || Lib.add-open ? "Activate" : "Select"; } }
|
||||
if !root.detail-open && !Lib.add-open: VerticalLayout { alignment: center; KeyCap { key: "Tab"; label: "Next section"; } }
|
||||
if root.view != 3 || root.detail-open: VerticalLayout { alignment: center; KeyCap { key: "P"; label: "Pin"; } }
|
||||
if root.view == 1 && !root.detail-open: VerticalLayout { alignment: center; KeyCap { key: "/"; label: "Search"; } }
|
||||
if root.view == 3 && !root.detail-open: VerticalLayout { alignment: center; KeyCap { key: "Del"; label: "Reset"; } }
|
||||
if (root.view == 1 || root.view == 3) && !root.detail-open: VerticalLayout { alignment: center; KeyCap { key: "/"; label: "Search"; } }
|
||||
if root.detail-open || root.view != 0: VerticalLayout { alignment: center; KeyCap { key: "Esc"; label: root.detail-open ? "Back" : "Home"; } }
|
||||
if root.width >= 1100px: VerticalLayout { alignment: center; KeyCap { key: "F11"; label: "Fullscreen"; } }
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// A game's page: art, stats, why Summit lists it, its launch profile and the actions.
|
||||
import { Theme } from "theme.slint";
|
||||
import { Lib, Game, Detail, PRow, Icon, Icons, Btn, Tag, CoverArt, FocusRing, Avatar } from "widgets.slint";
|
||||
import { Lib, Game, Detail, Icon, Icons, Btn, Tag, CoverArt, FocusRing, Avatar } from "widgets.slint";
|
||||
import { ProfileEditor } from "editor.slint";
|
||||
import { AccountPicker } from "accounts.slint";
|
||||
import { StatsView, CompareDialog } from "extras.slint";
|
||||
|
||||
component Stat inherits Rectangle {
|
||||
in property <string> label;
|
||||
@@ -38,7 +39,7 @@ component Field inherits Rectangle {
|
||||
|
||||
export component DetailView inherits Rectangle {
|
||||
in property <bool> open;
|
||||
in-out property <int> btn: 0; // 0 play, 1 enhance, 2 pin, 3 profile, 4 artwork, 5 Steam account
|
||||
in-out property <int> btn: 0; // 0 play, 1 enhance, 2 compare, 3 pin, 4 profile, 5 statistics, 6 artwork, 7 Steam account
|
||||
callback close();
|
||||
callback refocus(); // give the keyboard back to the window (the editor's text rows)
|
||||
property <Detail> d: Lib.detail;
|
||||
@@ -49,24 +50,31 @@ export component DetailView inherits Rectangle {
|
||||
property <length> rw: root.width - root.rx - root.pad;
|
||||
property <bool> wide: root.rw >= 720px;
|
||||
property <bool> compact: root.rw < 660px;
|
||||
property <bool> roomy: root.rw >= 1104px; // room for the buttons' names (Statistics only with more: roomier)
|
||||
property <bool> roomier: root.rw >= 1230px;
|
||||
property <length> reasons-h: 56px + root.d.reasons.length * 26px + 44px;
|
||||
property <length> profile-h: 56px + 5 * 28px + 92px;
|
||||
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (Lib.editor-open && !Lib.editor-defaults) { return editor.key(e); }
|
||||
if (Lib.editor-open) { return editor.key(e); }
|
||||
if (Lib.stats-open) { return stats.key(e); }
|
||||
if (Lib.cmp-open) { return compare.key(e); }
|
||||
if (Lib.accounts-open) { return picker.key(e); }
|
||||
if (e.text == Key.Tab || e.text == Key.Backtab) { return true; }
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
|
||||
else if (e.text == Key.RightArrow) { root.btn = Math.min(root.d.has-account ? 5 : 4, root.btn + 1); }
|
||||
else if (e.text == Key.RightArrow) { root.btn = Math.min(root.d.has-account ? 7 : 6, root.btn + 1); }
|
||||
else if (e.text == Key.LeftArrow) { root.btn = Math.max(0, root.btn - 1); }
|
||||
else if (e.text == Key.DownArrow) { body.content-y = Math.max(Math.min(0px, body.height - body.content-height), body.content-y - 96px); }
|
||||
else if (e.text == Key.UpArrow) { body.content-y = Math.min(0px, body.content-y + 96px); }
|
||||
else if (e.text == Key.Return || e.text == " ") {
|
||||
if (root.btn == 0) { if (root.d.can-play) { Lib.play(root.d.idx); } }
|
||||
else if (root.btn == 1) { if (root.d.can-enhance) { Lib.toggle-enhance(root.d.idx); } }
|
||||
else if (root.btn == 2) { Lib.toggle-pin(root.d.idx); }
|
||||
else if (root.btn == 3) { Lib.open-profile(root.d.idx); }
|
||||
else if (root.btn == 4) { Lib.change-art(root.d.idx); }
|
||||
else if (root.btn == 5) { Lib.open-accounts(root.d.idx); }
|
||||
else if (root.btn == 2) { Lib.open-compare(root.d.idx); }
|
||||
else if (root.btn == 3) { Lib.toggle-pin(root.d.idx); }
|
||||
else if (root.btn == 4) { Lib.open-profile(root.d.idx); }
|
||||
else if (root.btn == 5) { Lib.open-stats(root.d.idx); }
|
||||
else if (root.btn == 6) { Lib.change-art(root.d.idx); }
|
||||
else if (root.btn == 7) { Lib.open-accounts(root.d.idx); }
|
||||
} else if (e.text == "p" || e.text == "P") { Lib.toggle-pin(root.d.idx); }
|
||||
else if (e.text == "e" || e.text == "E") { if (root.d.can-enhance) { Lib.toggle-enhance(root.d.idx); } }
|
||||
else { return false; }
|
||||
@@ -105,15 +113,17 @@ export component DetailView inherits Rectangle {
|
||||
focused: root.open && root.btn == 0; clicked => { Lib.play(root.d.idx); } }
|
||||
Btn { h: 56px; enabled: root.d.can-enhance; text: root.compact ? "" : (root.d.enhance ? "Enhance on" : "Enhance off"); icon: Icons.sparkle; icon-solid: root.d.enhance;
|
||||
badge: root.d.can-enhance ? "" : "N/A"; focused: root.open && root.btn == 1; clicked => { Lib.toggle-enhance(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.g.pinned ? "Unpin" : "Pin"; icon: Icons.pin; icon-solid: root.g.pinned; focused: root.open && root.btn == 2; clicked => { Lib.toggle-pin(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.compact ? "" : "Profile"; icon: Icons.sliders; focused: root.open && root.btn == 3; clicked => { Lib.open-profile(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.compact || !root.wide ? "" : "Change artwork"; icon: Icons.picture; focused: root.open && root.btn == 4; clicked => { Lib.change-art(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.roomy ? "Compare" : ""; icon: Icons.layers; badge: root.roomy ? "Experimental" : ""; focused: root.open && root.btn == 2; clicked => { root.btn = 2; Lib.open-compare(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.roomy ? (root.g.pinned ? "Unpin" : "Pin") : ""; icon: Icons.pin; icon-solid: root.g.pinned; focused: root.open && root.btn == 3; clicked => { Lib.toggle-pin(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.compact ? "" : "Profile"; icon: Icons.sliders; focused: root.open && root.btn == 4; clicked => { root.btn = 4; Lib.open-profile(root.d.idx); } }
|
||||
Btn { h: 56px; text: root.roomier ? "Statistics" : ""; icon: Icons.clock; focused: root.open && root.btn == 5; clicked => { root.btn = 5; Lib.open-stats(root.d.idx); } }
|
||||
Btn { h: 56px; text: ""; icon: Icons.picture; focused: root.open && root.btn == 6; clicked => { Lib.change-art(root.d.idx); } }
|
||||
}
|
||||
if root.d.has-account: Rectangle {
|
||||
height: 76px; border-radius: Theme.r-md;
|
||||
background: root.btn == 5 && root.open ? Theme.p.raised : acct-ta.has-hover ? Theme.p.raised.with-alpha(0.7) : Theme.p.surface.with-alpha(Theme.p.dark ? 0.78 : 0.92);
|
||||
background: root.btn == 7 && root.open ? Theme.p.raised : acct-ta.has-hover ? Theme.p.raised.with-alpha(0.7) : Theme.p.surface.with-alpha(Theme.p.dark ? 0.78 : 0.92);
|
||||
border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
acct-ta := TouchArea { mouse-cursor: pointer; clicked => { root.btn = 5; Lib.open-accounts(root.d.idx); } }
|
||||
acct-ta := TouchArea { mouse-cursor: pointer; clicked => { root.btn = 7; Lib.open-accounts(root.d.idx); } }
|
||||
Avatar { x: 14px; y: (parent.height - self.height) / 2; size: 48px; a: root.d.account; icon: root.d.account.login == "" ? Icons.user : ""; }
|
||||
Text { x: 76px; y: 12px; text: "STEAM ACCOUNT"; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
HorizontalLayout { x: 76px; y: 28px; width: parent.width - 76px - 130px; height: 22px; spacing: 10px; alignment: start;
|
||||
@@ -123,12 +133,15 @@ export component DetailView inherits Rectangle {
|
||||
Text { x: 76px; y: 52px; width: parent.width - 76px - 130px; text: root.d.account-note; color: root.d.account.warn != "" ? #e0a43a : Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
Text { x: parent.width - 120px; width: 100px; height: parent.height; horizontal-alignment: right; vertical-alignment: center;
|
||||
text: "Change ›"; color: Theme.p.accent; font-size: Theme.t-sm; font-weight: 800; }
|
||||
FocusRing { on: root.open && root.btn == 5; radius: Theme.r-md; }
|
||||
FocusRing { on: root.open && root.btn == 7; radius: Theme.r-md; }
|
||||
}
|
||||
Text {
|
||||
text: root.btn == 5 ? "Which Steam account this game is played on. Play switches Steam to it first (Steam closes and starts again signed in as it). Automatic: the account it was last played on."
|
||||
: root.btn == 4 ? "Pick a cover image (PNG, JPEG or WebP; portrait 2:3 looks best). Summit keeps a link to the file, so leave it where it is."
|
||||
: root.btn == 3 ? "Everything this game launches with: monitor and mode, window mode, focus, the upscaler and frame generation and their settings, launch arguments and environment. Each one follows the launcher's defaults (Settings) until you change it here."
|
||||
text: root.btn == 7 ? "Which Steam account this game is played on. Play switches Steam to it first (Steam closes and starts again signed in as it). Automatic: the account it was last played on."
|
||||
: root.btn == 6 ? "Change artwork: pick a cover image (PNG, JPEG or WebP; portrait 2:3 looks best). Summit keeps a link to the file, so leave it where it is."
|
||||
: root.btn == 5 ? "Statistics: the time played and the sessions Summit counted, and the session summaries the engine has written for this game (duration, frame rates, the settings it ran with)."
|
||||
: root.btn == 4 ? "Profile: everything this game launches with. Monitor and mode, window mode, focus, launch arguments and environment, and every engine setting (frame generation, upscaling, overlay, clips), each following the global one in Settings until you change it here. Presets too."
|
||||
: root.btn == 3 ? "Pinned games get a shelf of their own on Home."
|
||||
: root.btn == 2 ? root.d.compare-note
|
||||
: root.btn == 1 ? root.d.enhance-note
|
||||
: root.d.play-note + (root.d.enhance && root.d.can-enhance ? " Enhance is on: " + root.d.framegen + " + " + root.d.upscaler + "." : "");
|
||||
color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; min-height: 18px;
|
||||
@@ -175,9 +188,19 @@ export component DetailView inherits Rectangle {
|
||||
visible: Lib.accounts-open; opacity: self.visible ? 1 : 0;
|
||||
}
|
||||
|
||||
stats := StatsView {
|
||||
visible: Lib.stats-open; opacity: self.visible ? 1 : 0;
|
||||
close => { Lib.stats-open = false; }
|
||||
}
|
||||
|
||||
compare := CompareDialog {
|
||||
visible: Lib.cmp-open; opacity: self.visible ? 1 : 0;
|
||||
close => { Lib.cmp-open = false; }
|
||||
}
|
||||
|
||||
editor := ProfileEditor {
|
||||
visible: Lib.editor-open && !Lib.editor-defaults; opacity: self.visible ? 1 : 0;
|
||||
close => { Lib.editor-open = false; Lib.editor-typing = false; }
|
||||
visible: Lib.editor-open; opacity: self.visible ? 1 : 0;
|
||||
close => { Lib.close-profile(); }
|
||||
refocus => { root.refocus(); }
|
||||
}
|
||||
}
|
||||
@@ -1,135 +1,35 @@
|
||||
// The launch profile editor, over a game's page or the settings page (the launcher's defaults). Up/Down picks a
|
||||
// row, Left/Right changes it, Enter edits a text row; every change is saved. On a game each row's first choice is
|
||||
// "Default · ...": the game follows the launcher's defaults for it. Rows the game sets itself are marked.
|
||||
// A game's profile, over its page: the same settings pane as the Settings page (pane.slint), for this game. The
|
||||
// first section is what belongs to the launch itself (monitor, window, arguments); the others are the engine's
|
||||
// settings, each following the global one until the game sets its own. Every change is saved at once.
|
||||
import { Theme } from "theme.slint";
|
||||
import { Lib, PRow, Icon, Icons, Btn, FocusRing } from "widgets.slint";
|
||||
|
||||
component Picker inherits Rectangle {
|
||||
in property <PRow> r;
|
||||
in property <bool> focused;
|
||||
in property <bool> typing; // the text row has the keyboard (Enter pressed on it)
|
||||
callback set(int);
|
||||
callback pick();
|
||||
callback text-done(string);
|
||||
callback text-cancel();
|
||||
height: 64px;
|
||||
changed typing => { if (root.typing) { input.text = root.r.text; input.focus(); } }
|
||||
|
||||
if root.r.kind == 2: Text {
|
||||
x: 4px; y: 34px; text: root.r.label; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2px;
|
||||
}
|
||||
Rectangle {
|
||||
visible: root.r.kind != 2;
|
||||
border-radius: Theme.r-md;
|
||||
background: root.focused ? Theme.p.raised : Theme.p.surface.with-alpha(0.7);
|
||||
border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
TouchArea { clicked => { root.pick(); } }
|
||||
if root.r.own: Rectangle { x: 0; y: 14px; width: 4px; height: parent.height - 28px; border-radius: 2px; background: Theme.p.accent; }
|
||||
Text { x: 18px; y: 12px; text: root.r.label; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; }
|
||||
Text { x: 18px; y: 36px; width: parent.width - 460px; text: root.r.hint; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
|
||||
|
||||
// a value picked from a list
|
||||
Rectangle { visible: root.r.kind == 0;
|
||||
x: parent.width - 370px; y: 12px; width: 352px; height: 40px; border-radius: 20px; background: Theme.p.surface; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
Text { x: 14px; width: 24px; height: parent.height; text: "‹"; font-size: 22px; vertical-alignment: center; color: root.r.value > 0 ? Theme.p.text : Theme.p.faint; }
|
||||
Text { x: 40px; width: parent.width - 80px; height: parent.height; text: root.r.value < root.r.options.length ? root.r.options[root.r.value] : "";
|
||||
horizontal-alignment: center; vertical-alignment: center; color: root.r.value == 0 ? Theme.p.dim : Theme.p.text; font-size: Theme.t-sm; font-weight: 700; overflow: elide; }
|
||||
Text { x: parent.width - 32px; width: 24px; height: parent.height; text: "›"; font-size: 22px; vertical-alignment: center; color: root.r.value < root.r.options.length - 1 ? Theme.p.text : Theme.p.faint; }
|
||||
TouchArea { x: 0; width: 48px; mouse-cursor: pointer; clicked => { if (root.r.value > 0) { root.set(root.r.value - 1); } } }
|
||||
TouchArea { x: parent.width - 48px; width: 48px; mouse-cursor: pointer; clicked => { if (root.r.value < root.r.options.length - 1) { root.set(root.r.value + 1); } } }
|
||||
}
|
||||
|
||||
// a line of text
|
||||
box := Rectangle { visible: root.r.kind == 1;
|
||||
x: parent.width - 440px; y: 12px; width: 422px; height: 40px; border-radius: 10px; background: Theme.p.surface;
|
||||
border-width: input.has-focus ? 2px : Theme.p.border-w; border-color: input.has-focus ? Theme.p.accent : Theme.p.border;
|
||||
if input.text == "" && !input.has-focus: Text { x: 12px; width: parent.width - 24px; height: parent.height; text: root.r.placeholder; color: Theme.p.faint; font-size: Theme.t-sm; vertical-alignment: center; overflow: elide; }
|
||||
input := TextInput {
|
||||
x: 12px; width: parent.width - 24px; height: parent.height; vertical-alignment: center; single-line: true;
|
||||
text: root.r.text; color: Theme.p.text; font-size: Theme.t-sm; selection-background-color: Theme.p.accent; selection-foreground-color: Theme.p.on-accent;
|
||||
accepted => { root.text-done(self.text); }
|
||||
key-pressed(e) => {
|
||||
if (e.text == Key.Escape) { self.text = root.r.text; root.text-cancel(); return accept; }
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
}
|
||||
FocusRing { on: root.focused && !input.has-focus; radius: Theme.r-md; }
|
||||
}
|
||||
}
|
||||
import { Lib, Icons, Btn } from "widgets.slint";
|
||||
import { SettingsPane, Sx } from "pane.slint";
|
||||
|
||||
export component ProfileEditor inherits Rectangle {
|
||||
callback close();
|
||||
callback refocus(); // give the keyboard back to the window (after editing text)
|
||||
property <length> step: 74px; // row height + gap
|
||||
property <PRow> cur: Lib.prof-rows[Lib.editor-row];
|
||||
|
||||
function move(d: int) {
|
||||
let n = Lib.prof-rows.length;
|
||||
let i = Math.clamp(Lib.editor-row + d, 0, n - 1);
|
||||
// headers are never next to each other; one at the very top is skipped by staying put
|
||||
if (Lib.prof-rows[i].kind == 2) {
|
||||
if (i + d >= 0 && i + d < n) { Lib.editor-row = i + d; }
|
||||
} else { Lib.editor-row = i; }
|
||||
root.reveal();
|
||||
}
|
||||
function reveal() {
|
||||
let y = Lib.editor-row * root.step;
|
||||
// show the section header above a row too
|
||||
let top = Math.max(0px, y - root.step);
|
||||
if (top + list.content-y < 0px) { list.content-y = -top; }
|
||||
else if (y + 64px + list.content-y > list.height) { list.content-y = list.height - y - 64px; }
|
||||
}
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
|
||||
else if (e.text == Key.DownArrow) { root.move(1); }
|
||||
else if (e.text == Key.UpArrow) { root.move(-1); }
|
||||
else if (root.cur.kind == 1 && (e.text == Key.Return || e.text == " " || e.text == Key.RightArrow)) { Lib.editor-typing = true; }
|
||||
else if (e.text == Key.Delete) {
|
||||
// back to the defaults (a game) or to Summit's own value (the defaults)
|
||||
if (root.cur.kind == 0 && root.cur.value != 0) { Lib.prof-set(Lib.editor-row, 0); }
|
||||
else if (root.cur.kind == 1 && root.cur.text != "") { Lib.prof-text(Lib.editor-row, ""); }
|
||||
}
|
||||
else if (root.cur.kind == 0 && (e.text == Key.RightArrow || e.text == Key.Return || e.text == " ")) {
|
||||
if (root.cur.value < root.cur.options.length - 1) { Lib.prof-set(Lib.editor-row, root.cur.value + 1); }
|
||||
else if (e.text != Key.RightArrow) { Lib.prof-set(Lib.editor-row, 0); }
|
||||
}
|
||||
else if (root.cur.kind == 0 && e.text == Key.LeftArrow) { if (root.cur.value > 0) { Lib.prof-set(Lib.editor-row, root.cur.value - 1); } }
|
||||
else if (e.text == Key.LeftArrow || e.text == Key.RightArrow || e.text == Key.Return || e.text == " ") { }
|
||||
else { return false; }
|
||||
return true;
|
||||
if (pane.key(e)) { return true; }
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); return true; }
|
||||
return e.text == Key.LeftArrow || e.text == Key.RightArrow || e.text == Key.UpArrow || e.text == Key.DownArrow || e.text == Key.Return || e.text == " ";
|
||||
}
|
||||
changed visible => { if (self.visible) { list.content-y = 0; root.reveal(); } }
|
||||
|
||||
background: Theme.p.bg.with-alpha(0.82);
|
||||
TouchArea { clicked => { root.close(); } }
|
||||
panel := Rectangle {
|
||||
property <length> w: Math.min(root.width - 48px, 1100px);
|
||||
Rectangle {
|
||||
property <length> w: Math.min(root.width - 32px, 1800px);
|
||||
x: (root.width - self.w) / 2; width: self.w; y: 16px; height: root.height - 32px;
|
||||
border-radius: Theme.r-lg; background: Theme.p.bg2; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
drop-shadow-blur: 40px; drop-shadow-color: #00000090;
|
||||
TouchArea { }
|
||||
Icon { x: 24px; y: 26px; size: 20px; color: Theme.p.accent; commands: Icons.sliders; }
|
||||
Text { x: 56px; y: 20px; width: parent.width - 420px; text: (Lib.editor-defaults ? "Default launch profile" : "Launch profile · " + Lib.prof-title); color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; overflow: elide; }
|
||||
Text { x: 56px; y: 50px; width: parent.width - 420px; text: Lib.prof-note; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
|
||||
Text { x: 56px; y: 68px; width: parent.width - 420px; text: "Saved to " + Lib.prof-file + " as you change it."; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
Btn { x: parent.width - self.width - 20px; y: 18px; h: 40px; text: "Done"; clicked => { root.close(); } }
|
||||
Btn { x: parent.width - self.width - 128px; y: 18px; h: 40px; width: 200px; text: Lib.editor-defaults ? "Reset to Summit's" : "Follow defaults"; icon: Icons.back;
|
||||
clicked => { Lib.prof-reset(); } }
|
||||
list := Flickable {
|
||||
x: 20px; y: 100px; width: parent.width - 40px; height: parent.height - 100px - 40px;
|
||||
content-width: self.width; content-height: Lib.prof-rows.length * root.step;
|
||||
animate content-y { duration: Theme.ms(180); easing: ease-out; }
|
||||
for r[i] in Lib.prof-rows: Picker {
|
||||
x: 0; y: i * root.step; width: parent.width; r: r; focused: Lib.editor-row == i && r.kind != 2;
|
||||
typing: Lib.editor-typing && Lib.editor-row == i;
|
||||
pick => { Lib.editor-row = i; }
|
||||
set(v) => { Lib.editor-row = i; Lib.prof-set(i, v); }
|
||||
text-done(t) => { Lib.editor-row = i; Lib.editor-typing = false; Lib.prof-text(i, t); root.refocus(); }
|
||||
text-cancel => { Lib.editor-typing = false; root.refocus(); }
|
||||
}
|
||||
pane := SettingsPane {
|
||||
x: 0; y: 12px; width: parent.width; height: parent.height - 12px - 32px;
|
||||
active: root.visible; overlay: true; head-right: 112px;
|
||||
exit-up => { }
|
||||
refocus => { root.refocus(); }
|
||||
}
|
||||
Text { x: 20px; y: parent.height - 30px; width: parent.width - 40px; horizontal-alignment: center; color: Theme.p.faint; font-size: Theme.t-xs;
|
||||
text: "Up / Down: setting · Left / Right: change · Enter: edit text · Delete: " + (Lib.editor-defaults ? "Summit's own" : "back to the default") + " · Esc: done"; }
|
||||
Btn { x: parent.width - self.width - 24px; y: 24px; h: 40px; text: "Done"; clicked => { root.close(); } }
|
||||
Text { x: 24px; y: parent.height - 28px; width: parent.width - 48px; horizontal-alignment: center; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide;
|
||||
text: "Up / Down: move · Left / Right: change · Enter: next value, type, press · Delete: use global · LB / RB, Page Up / Down: section · / : search · Esc: back, done"; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// Two overlays of a game's page: its statistics (playtime, and the session summaries the engine has written), and
|
||||
// starting it with the engine's live comparison on.
|
||||
import { Theme } from "theme.slint";
|
||||
import { Lib, StatTile, SessRow, CmpRow, Icon, Icons, Btn, KeyCap, FocusRing } from "widgets.slint";
|
||||
|
||||
component Tile inherits Rectangle {
|
||||
in property <StatTile> t;
|
||||
height: 88px; border-radius: Theme.r-md;
|
||||
background: Theme.p.surface.with-alpha(Theme.p.dark ? 0.78 : 0.92); border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
Text { x: 18px; y: 14px; width: parent.width - 36px; text: root.t.label; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; overflow: elide; }
|
||||
Text { x: 18px; y: 34px; width: parent.width - 36px; text: root.t.value; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; overflow: elide; }
|
||||
Text { x: 18px; y: 67px; width: parent.width - 36px; text: root.t.note; color: Theme.p.faint; font-size: 10px; overflow: elide; }
|
||||
}
|
||||
|
||||
export component StatsView inherits Rectangle {
|
||||
callback close();
|
||||
property <SessRow> cur: Lib.sess[Lib.sess-sel];
|
||||
property <length> row-h: 72px;
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace || e.text == Key.Return) { root.close(); }
|
||||
else if (e.text == Key.DownArrow) { Lib.sess-sel = Math.min(Math.max(0, Lib.sess.length - 1), Lib.sess-sel + 1); root.reveal(); }
|
||||
else if (e.text == Key.UpArrow) { Lib.sess-sel = Math.max(0, Lib.sess-sel - 1); root.reveal(); }
|
||||
else if (e.text == Key.PageDown) { fields.content-y = Math.max(Math.min(0px, fields.height - fields.content-height), fields.content-y - 160px); }
|
||||
else if (e.text == Key.PageUp) { fields.content-y = Math.min(0px, fields.content-y + 160px); }
|
||||
return true;
|
||||
}
|
||||
function reveal() {
|
||||
let y = Lib.sess-sel * root.row-h;
|
||||
if (y + list.content-y < 0px) { list.content-y = -y; }
|
||||
else if (y + root.row-h + list.content-y > list.height) { list.content-y = list.height - y - root.row-h; }
|
||||
fields.content-y = 0;
|
||||
}
|
||||
changed visible => { if (self.visible) { list.content-y = 0; } }
|
||||
|
||||
background: Theme.p.bg.with-alpha(0.82);
|
||||
TouchArea { clicked => { root.close(); } }
|
||||
panel := Rectangle {
|
||||
property <length> w: Math.min(root.width - 32px, 1280px);
|
||||
property <length> in-w: self.w - 48px;
|
||||
property <int> n: Math.max(1, Lib.stat-tiles.length);
|
||||
property <length> list-y: 96px + 88px + 28px + 30px;
|
||||
property <length> list-h: self.height - self.list-y - 44px;
|
||||
property <length> left-w: self.in-w >= 860px ? self.in-w * 0.46 : self.in-w;
|
||||
x: (root.width - self.w) / 2; width: self.w; y: 16px; height: root.height - 32px;
|
||||
border-radius: Theme.r-lg; background: Theme.p.bg2; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
drop-shadow-blur: 40px; drop-shadow-color: #00000090;
|
||||
TouchArea { }
|
||||
Icon { x: 24px; y: 26px; size: 20px; color: Theme.p.accent; commands: Icons.clock; }
|
||||
Text { x: 56px; y: 20px; width: parent.width - 220px; text: "Statistics · " + Lib.stats-title; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; overflow: elide; }
|
||||
Text { x: 56px; y: 50px; width: parent.width - 220px; text: Lib.stats-note; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
|
||||
Btn { x: parent.width - self.width - 24px; y: 20px; h: 40px; text: "Done"; clicked => { root.close(); } }
|
||||
|
||||
for t[i] in Lib.stat-tiles: Tile {
|
||||
x: 24px + i * ((parent.in-w + 12px) / parent.n); y: 96px; width: (parent.in-w + 12px) / parent.n - 12px; t: t;
|
||||
}
|
||||
Text { x: 28px; y: 96px + 88px + 28px; text: "ENGINE SESSIONS" + (Lib.sess.length > 0 ? " · " + Lib.sess.length : ""); color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2px; }
|
||||
|
||||
// nothing written yet: say so, and where it is looked for
|
||||
if Lib.sess.length == 0: Rectangle {
|
||||
x: 24px; y: parent.list-y; width: parent.in-w; height: parent.list-h; border-radius: Theme.r-md;
|
||||
background: Theme.p.surface.with-alpha(0.5); border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
VerticalLayout { alignment: center; spacing: 10px; padding: 32px;
|
||||
HorizontalLayout { alignment: center; Icon { size: 30px; color: Theme.p.faint; commands: Icons.clock; } }
|
||||
Text { text: "No sessions yet"; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; horizontal-alignment: center; }
|
||||
Text { text: Lib.sess-empty; color: Theme.p.dim; font-size: Theme.t-sm; horizontal-alignment: center; wrap: word-wrap; }
|
||||
}
|
||||
}
|
||||
list := Flickable {
|
||||
visible: Lib.sess.length > 0;
|
||||
x: 24px; y: parent.list-y; width: parent.left-w; height: parent.left-w < parent.in-w ? parent.list-h : parent.list-h * 0.5;
|
||||
content-width: self.width; content-height: Lib.sess.length * root.row-h;
|
||||
animate content-y { duration: Theme.ms(180); easing: ease-out; }
|
||||
for s[i] in Lib.sess: Rectangle {
|
||||
x: 3px; y: i * root.row-h + 3px; width: parent.width - 6px; height: root.row-h - 8px; border-radius: Theme.r-md;
|
||||
background: i == Lib.sess-sel ? Theme.p.raised : sta.has-hover ? Theme.p.raised.with-alpha(0.55) : Theme.p.surface.with-alpha(0.7);
|
||||
border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
Text { x: 16px; y: 9px; width: parent.width - 32px; text: s.when; color: Theme.p.dim; font-size: Theme.t-xs; font-weight: 700; overflow: elide; }
|
||||
Text { x: 16px; y: 26px; width: parent.width - 32px; text: s.headline; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; overflow: elide; }
|
||||
Text { x: 16px; y: 46px; width: parent.width - 32px; text: s.settings; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
FocusRing { on: i == Lib.sess-sel; radius: Theme.r-md; gap: 0px; }
|
||||
sta := TouchArea { mouse-cursor: pointer; clicked => { Lib.sess-sel = i; fields.content-y = 0; } }
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
visible: Lib.sess.length > 0;
|
||||
x: parent.left-w < parent.in-w ? 24px + parent.left-w + 16px : 24px; y: parent.left-w < parent.in-w ? parent.list-y + 3px : parent.list-y + parent.list-h * 0.5 + 8px;
|
||||
width: parent.left-w < parent.in-w ? parent.in-w - parent.left-w - 16px : parent.in-w; height: parent.left-w < parent.in-w ? parent.list-h - 6px : parent.list-h * 0.5 - 8px;
|
||||
border-radius: Theme.r-md; clip: true;
|
||||
background: Theme.p.surface.with-alpha(Theme.p.dark ? 0.55 : 0.8); border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
fields := Flickable {
|
||||
content-width: self.width; content-height: Math.max(self.height, fcol.preferred-height + 8px);
|
||||
fcol := VerticalLayout {
|
||||
x: 0; y: 0; width: parent.width; padding: 18px; spacing: 5px; alignment: start;
|
||||
Text { text: "IN THE FILE"; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
Text { text: root.cur.file; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
|
||||
Rectangle { height: 4px; }
|
||||
for f in root.cur.fields: HorizontalLayout { spacing: 12px;
|
||||
Text { width: 42%; text: f.name; color: Theme.p.dim; font-size: Theme.t-sm; overflow: elide; }
|
||||
Text { text: f.value; color: Theme.p.text; font-size: Theme.t-sm; font-weight: 600; wrap: word-wrap; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text { x: 24px; y: parent.height - 30px; width: parent.width - 48px; horizontal-alignment: center; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide;
|
||||
text: Lib.sess.length > 0 ? "Up / Down: session · Page Up / Down: scroll its fields · Esc: done" : "Esc: done"; }
|
||||
}
|
||||
}
|
||||
|
||||
export component CompareDialog inherits Rectangle {
|
||||
callback close();
|
||||
property <length> row-h: 62px;
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
|
||||
else if (e.text == Key.DownArrow) { Lib.cmp-sel = Math.min(Math.max(0, Lib.cmp-rows.length - 1), Lib.cmp-sel + 1); }
|
||||
else if (e.text == Key.UpArrow) { Lib.cmp-sel = Math.max(0, Lib.cmp-sel - 1); }
|
||||
else if (e.text == Key.Return || e.text == " ") { if (Lib.cmp-ok && Lib.cmp-rows.length > 0) { Lib.compare-start(Lib.cmp-sel); } }
|
||||
return true;
|
||||
}
|
||||
background: Theme.p.bg.with-alpha(0.86);
|
||||
TouchArea { clicked => { root.close(); } }
|
||||
box := Rectangle {
|
||||
property <length> w: Math.min(root.width - 2 * Theme.pad, 820px);
|
||||
property <length> list-h: Math.min(root.height - 330px, Math.max(1, Lib.cmp-rows.length) * root.row-h);
|
||||
x: (parent.width - self.w) / 2; y: (parent.height - self.height) / 2; width: self.w; height: col.preferred-height;
|
||||
background: Theme.p.surface; border-radius: Theme.r-md; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
TouchArea { }
|
||||
col := VerticalLayout {
|
||||
padding: 24px; spacing: 12px;
|
||||
HorizontalLayout { alignment: start; spacing: 10px;
|
||||
Text { text: "COMPARE"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px; vertical-alignment: center; }
|
||||
Rectangle { height: 18px; width: ex.preferred-width + 14px; border-radius: 9px; background: Theme.p.accent.with-alpha(0.16); border-width: 1px; border-color: Theme.p.accent.with-alpha(0.55);
|
||||
ex := Text { text: "EXPERIMENTAL"; color: Theme.p.accent; font-size: 10px; font-weight: 800; letter-spacing: 0.6px; horizontal-alignment: center; vertical-alignment: center; } }
|
||||
}
|
||||
Text { text: "Starts " + Lib.cmp-title + " with Enhance and the engine's live comparison: the same picture with each value of one setting, side by side."; color: Theme.p.text; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
Text { text: Lib.cmp-note; color: Lib.cmp-ok ? Theme.p.dim : Theme.p.text; font-size: Theme.t-sm; font-italic: !Lib.cmp-ok; wrap: word-wrap; }
|
||||
Flickable {
|
||||
height: box.list-h; content-height: Lib.cmp-rows.length * root.row-h;
|
||||
content-y: Math.min(0px, Math.max(self.height - self.content-height, -(Lib.cmp-sel * root.row-h) + self.height / 2 - root.row-h / 2));
|
||||
for r[i] in Lib.cmp-rows: Rectangle {
|
||||
x: 3px; y: i * root.row-h + 3px; width: parent.width - 6px; height: root.row-h - 8px; border-radius: Theme.r-md;
|
||||
background: i == Lib.cmp-sel ? Theme.p.raised : cta.has-hover ? Theme.p.raised.with-alpha(0.6) : transparent;
|
||||
opacity: Lib.cmp-ok ? 1 : 0.6;
|
||||
Text { x: 14px; y: 8px; width: parent.width - 28px; text: r.label; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; overflow: elide; }
|
||||
Text { x: 14px; y: 30px; width: parent.width - 28px; text: r.detail; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
FocusRing { on: i == Lib.cmp-sel; radius: Theme.r-md; gap: 0px; }
|
||||
cta := TouchArea { mouse-cursor: pointer; clicked => { Lib.cmp-sel = i; if (Lib.cmp-ok) { Lib.compare-start(i); } } }
|
||||
}
|
||||
}
|
||||
HorizontalLayout { alignment: end; spacing: 24px;
|
||||
if Lib.cmp-ok: KeyCap { key: "Enter"; label: "Start with this comparison"; }
|
||||
KeyCap { key: "Esc"; label: "Cancel"; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
// The settings pane: presets, the quick strip, a section list, a search box, the rows and a detail panel for the
|
||||
// focused row. The Settings page shows it for the global settings, a game's profile for the game's own. Every row
|
||||
// comes from Rust (rows.rs); engine rows are built from the engine's registry, so nothing about them is fixed here.
|
||||
//
|
||||
// Keys: Up/Down move, Left/Right change a value (or move along the presets and the quick strip), Enter cycles a
|
||||
// value, starts typing or presses a button, Delete resets the row, Esc goes from the rows back to the section list,
|
||||
// Page Up/Down (LB/RB in a profile) change section, "/" searches.
|
||||
import { Theme, Palette } from "theme.slint";
|
||||
import { Icon, Icons, FocusRing, Btn, Chip } from "widgets.slint";
|
||||
|
||||
// kind: 0 a choice, 1 a line of text, 2 a heading, 3 a button, 4 the theme swatches, 5 a note
|
||||
export struct SRow {
|
||||
kind: int,
|
||||
label: string,
|
||||
help: string,
|
||||
picture: string, // impact lines ("" when the engine gives none)
|
||||
speed: string,
|
||||
more: string, // any other impact line a newer engine adds, as "Name: text"
|
||||
options: [string],
|
||||
hints: [string],
|
||||
value: int,
|
||||
text: string,
|
||||
placeholder: string,
|
||||
changed: bool, // not the default / the game's own
|
||||
experimental: bool,
|
||||
off: bool, // not used now: greyed, with why
|
||||
locked: bool, // cannot be changed here
|
||||
why: string,
|
||||
note: string,
|
||||
tag: string, // "Next start"
|
||||
seg: bool, // options side by side
|
||||
button: string,
|
||||
base: string, // "Default: 2x", "Global: 2x"
|
||||
y: length,
|
||||
h: length,
|
||||
up: int, // the row Up and Down go to (-1: none)
|
||||
down: int,
|
||||
}
|
||||
export struct SNav { label: string, changed: int, count: int }
|
||||
export struct SPreset { name: string, summary: string, detail: string, sets: [string], active: bool }
|
||||
|
||||
export global Sx {
|
||||
in property <string> title;
|
||||
in property <string> subtitle;
|
||||
in property <bool> game; // a game's profile, not the Settings page
|
||||
in property <[SNav]> nav;
|
||||
in-out property <int> section;
|
||||
in property <[SRow]> rows; // the section's rows, or the search results
|
||||
in property <length> rows-h;
|
||||
in-out property <int> row;
|
||||
in property <[SRow]> quick;
|
||||
in-out property <int> quick-sel;
|
||||
in property <[SPreset]> presets; // empty: the engine's settings could not be read
|
||||
in property <string> preset-state; // "Balanced", "Custom", "Follows global (Balanced)"
|
||||
in-out property <int> preset-sel;
|
||||
in-out property <int> zone: 2; // 0 presets, 1 quick strip, 2 section list, 3 rows
|
||||
in-out property <string> search;
|
||||
in-out property <bool> typing; // a text row has the keyboard
|
||||
in property <string> engine-note; // why there are no engine rows, when there are none
|
||||
callback enter(); // the Settings page is shown: fill the pane
|
||||
callback pick-section(int);
|
||||
callback set(int, int); // row, option
|
||||
callback set-quick(int, int);
|
||||
callback text(int, string);
|
||||
callback reset(int); // row: back to the default / the global setting
|
||||
callback reset-quick(int);
|
||||
callback act(int); // a button row
|
||||
callback apply-preset(int);
|
||||
callback search-changed(string);
|
||||
}
|
||||
|
||||
component Swatch inherits Rectangle {
|
||||
in property <Palette> p;
|
||||
in property <bool> active;
|
||||
callback clicked;
|
||||
border-radius: Theme.r-md;
|
||||
background: root.p.bg; border-width: root.active ? 3px : 1px; border-color: root.active ? Theme.p.accent : Theme.p.border;
|
||||
Rectangle { x: 10px; y: 10px; width: parent.width - 20px; height: 34px; border-radius: 6px; background: root.p.surface; border-width: 1px; border-color: root.p.border;
|
||||
Rectangle { x: 8px; y: 9px; width: 16px; height: 16px; border-radius: 8px; background: @linear-gradient(120deg, root.p.accent 0%, root.p.accent2 100%); }
|
||||
Rectangle { x: 32px; y: 11px; width: parent.width * 0.4; height: 4px; border-radius: 2px; background: root.p.text; }
|
||||
Rectangle { x: 32px; y: 20px; width: parent.width * 0.26; height: 4px; border-radius: 2px; background: root.p.dim; }
|
||||
}
|
||||
Text { x: 12px; y: parent.height - 28px; width: parent.width - 24px; text: root.p.name; color: root.p.text; font-size: Theme.t-sm - 1px; font-weight: 700; overflow: elide; }
|
||||
TouchArea { mouse-cursor: pointer; clicked => { root.clicked(); } }
|
||||
}
|
||||
|
||||
component Pill inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <color> tint: Theme.p.dim;
|
||||
height: 18px; width: t.preferred-width + 14px; border-radius: 9px;
|
||||
background: root.tint.with-alpha(0.16); border-width: 1px; border-color: root.tint.with-alpha(0.55);
|
||||
t := Text { text: root.text; color: root.tint; font-size: 10px; font-weight: 800; letter-spacing: 0.6px; horizontal-alignment: center; vertical-alignment: center; }
|
||||
}
|
||||
|
||||
// ‹ value ›
|
||||
component Stepper inherits Rectangle {
|
||||
in property <SRow> r;
|
||||
callback set(int);
|
||||
property <bool> can: !root.r.locked;
|
||||
height: 40px; border-radius: 20px; background: Theme.p.surface; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
Text { x: 14px; width: 24px; height: parent.height; text: "‹"; font-size: 22px; vertical-alignment: center; color: root.can && root.r.value > 0 ? Theme.p.text : Theme.p.faint; }
|
||||
Text { x: 40px; width: parent.width - 80px; height: parent.height; text: root.r.value < root.r.options.length ? root.r.options[root.r.value] : "";
|
||||
horizontal-alignment: center; vertical-alignment: center; color: root.r.off ? Theme.p.faint : Theme.p.text; font-size: Theme.t-sm; font-weight: 700; overflow: elide; }
|
||||
Text { x: parent.width - 32px; width: 24px; height: parent.height; text: "›"; font-size: 22px; vertical-alignment: center; color: root.can && root.r.value < root.r.options.length - 1 ? Theme.p.text : Theme.p.faint; }
|
||||
TouchArea { x: 0; width: 48px; enabled: root.can; mouse-cursor: pointer; clicked => { if (root.r.value > 0) { root.set(root.r.value - 1); } } }
|
||||
TouchArea { x: parent.width - 48px; width: 48px; enabled: root.can; mouse-cursor: pointer; clicked => { if (root.r.value < root.r.options.length - 1) { root.set(root.r.value + 1); } } }
|
||||
}
|
||||
|
||||
// the options side by side (never assigns its own value: Rust sends the row back)
|
||||
component Seg inherits Rectangle {
|
||||
in property <SRow> r;
|
||||
callback set(int);
|
||||
property <length> cell: (root.width - 8px) / Math.max(1, root.r.options.length);
|
||||
height: 40px; border-radius: 20px; background: Theme.p.surface; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
Rectangle {
|
||||
x: 4px + root.r.value * root.cell; y: 4px; width: root.cell; height: parent.height - 8px; border-radius: self.height / 2;
|
||||
background: @linear-gradient(100deg, Theme.p.accent 0%, Theme.p.accent2 100%);
|
||||
animate x { duration: Theme.ms(220); easing: Theme.ease; }
|
||||
}
|
||||
for o[i] in root.r.options: Rectangle {
|
||||
x: 4px + i * root.cell; y: 4px; width: root.cell; height: parent.height - 8px;
|
||||
Text { text: o; width: parent.width - 4px; x: 2px; color: i == root.r.value ? Theme.p.on-accent : Theme.p.text; font-size: Theme.t-sm; font-weight: i == root.r.value ? 700 : 500; horizontal-alignment: center; vertical-alignment: center; overflow: elide;
|
||||
animate color { duration: Theme.ms(160); } }
|
||||
TouchArea { mouse-cursor: pointer; clicked => { if (root.r.value != i) { root.set(i); } } }
|
||||
}
|
||||
}
|
||||
|
||||
component SettingRow inherits Rectangle {
|
||||
in property <SRow> r;
|
||||
in property <bool> focused;
|
||||
in property <bool> typing;
|
||||
callback pick();
|
||||
callback set(int);
|
||||
callback act();
|
||||
callback text-done(string);
|
||||
callback text-cancel();
|
||||
property <length> ctl-w: root.r.kind == 3 ? 176px : root.r.kind == 1 ? Math.min(400px, root.width * 0.46) : root.r.seg ? Math.min(root.width * 0.52, root.r.options.length * 92px + 8px) : Math.min(300px, root.width * 0.42);
|
||||
property <length> text-w: root.r.kind == 4 ? root.width - 44px : root.width - root.ctl-w - 60px;
|
||||
property <bool> three: root.r.picture != "" || root.r.speed != "" || root.r.more != "";
|
||||
changed typing => { if (root.typing) { input.text = root.r.text; input.focus(); } }
|
||||
|
||||
if root.r.kind == 2: Text {
|
||||
x: 4px; y: parent.height - 20px; width: parent.width - 8px; text: root.r.label; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2px; overflow: elide;
|
||||
}
|
||||
if root.r.kind == 5: Text {
|
||||
x: 4px; y: 4px; width: parent.width - 8px; height: parent.height - 4px; text: root.r.help; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; overflow: elide;
|
||||
}
|
||||
Rectangle {
|
||||
visible: root.r.kind != 2 && root.r.kind != 5;
|
||||
border-radius: Theme.r-md;
|
||||
background: root.focused ? Theme.p.raised : ta.has-hover ? Theme.p.raised.with-alpha(0.55) : Theme.p.surface.with-alpha(0.7);
|
||||
border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
animate background { duration: Theme.ms(140); }
|
||||
ta := TouchArea { clicked => { root.pick(); } }
|
||||
// changed from the default (or the game's own): a dot, and Delete puts it back
|
||||
if root.r.changed: Rectangle { x: 9px; y: 19px; width: 8px; height: 8px; border-radius: 4px; background: Theme.p.accent; }
|
||||
HorizontalLayout {
|
||||
x: 24px; y: 11px; width: root.text-w; height: 24px; spacing: 8px; alignment: start;
|
||||
Text { text: root.r.label; color: root.r.off ? Theme.p.dim : Theme.p.text; font-size: Theme.t-md; font-weight: 700; vertical-alignment: center; overflow: elide; }
|
||||
if root.r.experimental: VerticalLayout { alignment: center; Pill { text: "EXPERIMENTAL"; tint: Theme.p.accent; } }
|
||||
if root.r.tag != "": VerticalLayout { alignment: center; Pill { text: root.r.tag; } }
|
||||
}
|
||||
Text { x: 24px; y: 37px; width: root.text-w; text: root.r.off ? root.r.why : root.r.help; color: root.r.off ? Theme.p.dim : Theme.p.dim; font-size: Theme.t-xs; font-italic: root.r.off; overflow: elide; }
|
||||
if root.three && root.r.kind != 4: Text {
|
||||
x: 24px; y: 56px; width: root.text-w; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide;
|
||||
text: (root.r.picture != "" ? "Picture: " + root.r.picture : "") + (root.r.picture != "" && root.r.speed != "" ? " · " : "") + (root.r.speed != "" ? "Speed: " + root.r.speed : "") + (root.r.more != "" ? " · " + root.r.more : "");
|
||||
}
|
||||
|
||||
if root.r.kind == 0 && !root.r.seg: Stepper { x: parent.width - self.width - 16px; y: (parent.height - 40px) / 2; width: root.ctl-w; r: root.r; opacity: root.r.off ? 0.6 : 1; set(v) => { root.pick(); root.set(v); } }
|
||||
if root.r.kind == 0 && root.r.seg: Seg { x: parent.width - self.width - 16px; y: (parent.height - 40px) / 2; width: root.ctl-w; r: root.r; set(v) => { root.pick(); root.set(v); } }
|
||||
if root.r.kind == 3: Btn { x: parent.width - self.width - 16px; y: (parent.height - 44px) / 2; h: 44px; width: root.ctl-w; text: root.r.button; enabled: !root.r.locked; clicked => { root.pick(); root.act(); } }
|
||||
if root.r.kind == 4: Rectangle {
|
||||
x: 24px; y: 60px; width: parent.width - 48px; height: 76px;
|
||||
for p[i] in Theme.palettes: Swatch {
|
||||
property <length> sw: Math.min(168px, (parent.width - (Theme.palettes.length - 1) * 12px) / Theme.palettes.length);
|
||||
x: i * (self.sw + 12px); y: 0; width: self.sw; height: parent.height; p: p; active: root.r.value == i;
|
||||
clicked => { root.pick(); root.set(i); }
|
||||
}
|
||||
}
|
||||
if root.r.kind == 4: Text { x: parent.width - 16px - 240px; y: 11px; width: 240px; height: 24px; horizontal-alignment: right; vertical-alignment: center;
|
||||
text: root.r.value < root.r.options.length ? root.r.options[root.r.value] : ""; color: Theme.p.text; font-size: Theme.t-sm; font-weight: 700; }
|
||||
|
||||
// a line of text
|
||||
box := Rectangle { visible: root.r.kind == 1;
|
||||
x: parent.width - root.ctl-w - 16px; y: (parent.height - 40px) / 2; width: root.ctl-w; height: 40px; border-radius: 10px; background: Theme.p.surface;
|
||||
border-width: input.has-focus ? 2px : Theme.p.border-w; border-color: input.has-focus ? Theme.p.accent : Theme.p.border;
|
||||
if input.text == "" && !input.has-focus: Text { x: 12px; width: parent.width - 24px; height: parent.height; text: root.r.placeholder; color: Theme.p.faint; font-size: Theme.t-sm; vertical-alignment: center; overflow: elide; }
|
||||
input := TextInput {
|
||||
x: 12px; width: parent.width - 24px; height: parent.height; vertical-alignment: center; single-line: true;
|
||||
text: root.r.text; color: Theme.p.text; font-size: Theme.t-sm; selection-background-color: Theme.p.accent; selection-foreground-color: Theme.p.on-accent;
|
||||
accepted => { root.text-done(self.text); }
|
||||
key-pressed(e) => {
|
||||
if (e.text == Key.Escape) { self.text = root.r.text; root.text-cancel(); return accept; }
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
}
|
||||
FocusRing { on: root.focused && !input.has-focus; radius: Theme.r-md; }
|
||||
}
|
||||
}
|
||||
|
||||
component QuickTile inherits Rectangle {
|
||||
in property <SRow> r;
|
||||
in property <bool> focused;
|
||||
callback pick();
|
||||
callback set(int);
|
||||
border-radius: Theme.r-md;
|
||||
background: root.focused ? Theme.p.raised : ta.has-hover ? Theme.p.raised.with-alpha(0.55) : Theme.p.surface.with-alpha(0.7);
|
||||
border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
animate background { duration: Theme.ms(140); }
|
||||
ta := TouchArea { clicked => { root.pick(); } }
|
||||
if root.r.changed: Rectangle { x: 10px; y: 16px; width: 8px; height: 8px; border-radius: 4px; background: Theme.p.accent; }
|
||||
Text { x: root.r.changed ? 24px : 14px; y: 10px; width: parent.width - 28px; text: root.r.label; color: Theme.p.dim; font-size: Theme.t-xs; font-weight: 700; letter-spacing: 0.4px; overflow: elide; }
|
||||
Text { x: 14px; y: 30px; width: parent.width - 28px - (root.focused || ta.has-hover ? 52px : 0px); text: root.r.value < root.r.options.length ? root.r.options[root.r.value] : "";
|
||||
color: root.r.off ? Theme.p.faint : Theme.p.text; font-size: Theme.t-md; font-weight: 800; overflow: elide; }
|
||||
if root.r.off: Text { x: 14px; y: 52px; width: parent.width - 28px; text: "Not used now"; color: Theme.p.faint; font-size: 10px; font-italic: true; overflow: elide; }
|
||||
if (root.focused || ta.has-hover) && !root.r.locked: Rectangle {
|
||||
x: parent.width - 60px; y: 24px; width: 52px; height: 28px;
|
||||
Text { x: 0; width: 26px; height: parent.height; text: "‹"; font-size: 20px; horizontal-alignment: center; vertical-alignment: center; color: root.r.value > 0 ? Theme.p.text : Theme.p.faint; }
|
||||
Text { x: 26px; width: 26px; height: parent.height; text: "›"; font-size: 20px; horizontal-alignment: center; vertical-alignment: center; color: root.r.value < root.r.options.length - 1 ? Theme.p.text : Theme.p.faint; }
|
||||
TouchArea { x: 0; width: 26px; mouse-cursor: pointer; clicked => { root.pick(); if (root.r.value > 0) { root.set(root.r.value - 1); } } }
|
||||
TouchArea { x: 26px; width: 26px; mouse-cursor: pointer; clicked => { root.pick(); if (root.r.value < root.r.options.length - 1) { root.set(root.r.value + 1); } } }
|
||||
}
|
||||
FocusRing { on: root.focused; radius: Theme.r-md; }
|
||||
}
|
||||
|
||||
// What the focused thing is: the whole help text, what it costs, every choice with its line.
|
||||
component Details inherits Rectangle {
|
||||
in property <SRow> r;
|
||||
in property <bool> show-row;
|
||||
in property <SPreset> preset;
|
||||
in property <bool> show-preset;
|
||||
in property <SNav> nav;
|
||||
callback set(int);
|
||||
border-radius: Theme.r-lg; clip: true;
|
||||
background: Theme.p.surface.with-alpha(Theme.p.dark ? 0.55 : 0.8); border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
Flickable {
|
||||
x: 0; y: 0; width: parent.width; height: parent.height;
|
||||
content-width: self.width; content-height: Math.max(self.height, col.preferred-height + 8px);
|
||||
col := VerticalLayout {
|
||||
x: 0; y: 0; width: parent.width; padding: 20px; spacing: 10px; alignment: start;
|
||||
if root.show-preset: Text { text: "PRESET"; color: Theme.p.accent; font-size: 10px; font-weight: 800; letter-spacing: 2px; }
|
||||
if root.show-preset: Text { text: root.preset.name + (root.preset.active ? " (in use)" : ""); color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; wrap: word-wrap; }
|
||||
if root.show-preset: Text { text: root.preset.summary; color: Theme.p.text; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if root.show-preset: Text { text: root.preset.detail; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if root.show-preset: Text { text: "SETS"; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
if root.show-preset: VerticalLayout { spacing: 4px;
|
||||
for s in root.preset.sets: Text { text: "• " + s; color: Theme.p.text; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
}
|
||||
if root.show-preset: Text { text: "Nothing else is changed. Enter applies it; change any of these afterwards and the state reads Custom."; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
|
||||
|
||||
if root.show-row: Text { text: root.r.label; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; wrap: word-wrap; }
|
||||
if root.show-row && (root.r.experimental || root.r.tag != "" || root.r.changed): HorizontalLayout { alignment: start; spacing: 6px;
|
||||
if root.r.experimental: Pill { text: "EXPERIMENTAL"; tint: Theme.p.accent; }
|
||||
if root.r.tag != "": Pill { text: root.r.tag; }
|
||||
if root.r.changed: Pill { text: Sx.game ? "THIS GAME'S OWN" : "CHANGED"; tint: Theme.p.accent; }
|
||||
}
|
||||
if root.show-row && root.r.off: Text { text: root.r.why; color: Theme.p.text; font-size: Theme.t-sm; font-italic: true; wrap: word-wrap; }
|
||||
if root.show-row && root.r.help != "": Text { text: root.r.help; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if root.show-row && root.r.picture != "": Text { text: "PICTURE"; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
if root.show-row && root.r.picture != "": Text { text: root.r.picture; color: Theme.p.text; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if root.show-row && root.r.speed != "": Text { text: "SPEED AND DELAY"; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
if root.show-row && root.r.speed != "": Text { text: root.r.speed; color: Theme.p.text; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if root.show-row && root.r.more != "": Text { text: root.r.more; color: Theme.p.text; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if root.show-row && (root.r.kind == 0 || root.r.kind == 4) && root.r.options.length > 1: Text { text: "CHOICES"; color: Theme.p.dim; font-size: 10px; font-weight: 800; letter-spacing: 1.6px; }
|
||||
if root.show-row && (root.r.kind == 0 || root.r.kind == 4) && root.r.options.length > 1: VerticalLayout { spacing: 6px;
|
||||
for o[i] in root.r.options: Rectangle {
|
||||
height: ol.preferred-height;
|
||||
Rectangle { x: 0; y: 6px; width: 6px; height: 6px; border-radius: 3px; background: i == root.r.value ? Theme.p.accent : Theme.p.faint.with-alpha(0.5); }
|
||||
ol := VerticalLayout { x: 16px; width: parent.width - 16px; spacing: 1px;
|
||||
Text { text: o; color: i == root.r.value ? Theme.p.accent : Theme.p.text; font-size: Theme.t-sm; font-weight: i == root.r.value ? 800 : 600; wrap: word-wrap; }
|
||||
if i < root.r.hints.length && root.r.hints[i] != "": Text { text: root.r.hints[i]; color: Theme.p.dim; font-size: Theme.t-xs; wrap: word-wrap; }
|
||||
}
|
||||
TouchArea { enabled: !root.r.locked; mouse-cursor: pointer; clicked => { if (i != root.r.value) { root.set(i); } } }
|
||||
}
|
||||
}
|
||||
if root.show-row && root.r.note != "": Text { text: root.r.note; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
|
||||
if root.show-row && root.r.base != "": Text { text: root.r.base + (root.r.changed ? (Sx.game ? " · Delete: use global" : " · Delete: reset") : ""); color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
|
||||
|
||||
if !root.show-row && !root.show-preset: Text { text: root.nav.label; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; wrap: word-wrap; }
|
||||
if !root.show-row && !root.show-preset: Text {
|
||||
text: root.nav.count + (root.nav.count == 1 ? " setting" : " settings") + (root.nav.changed > 0 ? ", " + root.nav.changed + (Sx.game ? " the game's own" : " changed") : "");
|
||||
color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if !root.show-row && !root.show-preset: Text {
|
||||
text: "Right or Enter opens the section. In a row, Left and Right change the value, Delete puts it back, Esc comes back here. Page Up and Page Down change section from anywhere; / searches every section.";
|
||||
color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export component SettingsPane inherits Rectangle {
|
||||
in property <bool> active; // it has the keys
|
||||
in property <bool> overlay; // inside a game's profile panel
|
||||
in property <length> head-right: 0px; // room kept free at the top right (a profile's Done button)
|
||||
callback exit-up();
|
||||
callback refocus(); // give the keyboard back to the window (after typing)
|
||||
property <length> pad: root.overlay ? 24px : Theme.pad;
|
||||
property <bool> top: Sx.presets.length > 0 && root.height >= 520px;
|
||||
property <length> head-h: 72px;
|
||||
property <length> body-y: root.head-h + (root.top ? 40px + 12px + 76px + 16px : 0px);
|
||||
property <length> nav-w: root.width < 1000px ? 168px : 208px;
|
||||
property <bool> wide: root.width - 2 * root.pad >= 1080px;
|
||||
property <length> det-w: root.wide ? Math.min(360px, (root.width - 2 * root.pad) * 0.27) : 0px;
|
||||
property <length> list-x: root.pad + root.nav-w + 20px;
|
||||
property <length> list-w: root.width - root.pad - root.list-x - (root.wide ? root.det-w + 20px : 0px);
|
||||
property <length> body-h: root.height - root.body-y - 12px;
|
||||
property <SRow> cur: Sx.rows[Sx.row];
|
||||
property <SRow> qcur: Sx.quick[Sx.quick-sel];
|
||||
property <bool> searching: Sx.search != "";
|
||||
|
||||
public function focus-search() { find.focus(); }
|
||||
function reveal() {
|
||||
if (root.cur.up < 0) { list.content-y = 0; }
|
||||
else if (root.cur.y - 44px + list.content-y < 0px) { list.content-y = -Math.max(0px, root.cur.y - 44px); }
|
||||
else if (root.cur.y + root.cur.h + 8px + list.content-y > list.height) { list.content-y = list.height - root.cur.y - root.cur.h - 8px; }
|
||||
}
|
||||
function go-section(i: int) {
|
||||
if (i == Sx.section && !root.searching) { return; }
|
||||
Sx.pick-section(i);
|
||||
list.content-y = 0;
|
||||
if (i * 44px + nav.content-y < 0px) { nav.content-y = -i * 44px; }
|
||||
else if (i * 44px + 40px + nav.content-y > nav.height) { nav.content-y = nav.height - i * 44px - 40px; }
|
||||
}
|
||||
function can-rows() -> bool { return Sx.rows.length > 0 && Sx.row < Sx.rows.length && root.cur.kind != 2 && root.cur.kind != 5; }
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (e.text == "/" || (e.modifiers.control && e.text == "f")) { root.focus-search(); return true; }
|
||||
if (e.text == Key.PageDown || (root.overlay && e.text == Key.Tab && !e.modifiers.shift)) { root.go-section(Math.min(Sx.nav.length - 1, Sx.section + 1)); return true; }
|
||||
if (e.text == Key.PageUp || (root.overlay && (e.text == Key.Backtab || e.text == Key.Tab))) { root.go-section(Math.max(0, Sx.section - 1)); return true; }
|
||||
if (Sx.zone == 0 && !root.top) { Sx.zone = 2; }
|
||||
if (Sx.zone == 1 && (!root.top || Sx.quick.length == 0)) { Sx.zone = 2; }
|
||||
if (Sx.zone == 0) {
|
||||
if (e.text == Key.LeftArrow) { Sx.preset-sel = Math.max(0, Sx.preset-sel - 1); }
|
||||
else if (e.text == Key.RightArrow) { Sx.preset-sel = Math.min(Sx.presets.length - 1, Sx.preset-sel + 1); }
|
||||
else if (e.text == Key.Return || e.text == " ") { Sx.apply-preset(Sx.preset-sel); }
|
||||
else if (e.text == Key.DownArrow) { Sx.zone = Sx.quick.length > 0 ? 1 : 2; }
|
||||
else if (e.text == Key.UpArrow) { root.exit-up(); }
|
||||
else { return false; }
|
||||
return true;
|
||||
}
|
||||
if (Sx.zone == 1) {
|
||||
if (e.text == Key.LeftArrow) { Sx.quick-sel = Math.max(0, Sx.quick-sel - 1); }
|
||||
else if (e.text == Key.RightArrow) { Sx.quick-sel = Math.min(Sx.quick.length - 1, Sx.quick-sel + 1); }
|
||||
else if (e.text == Key.Return || e.text == " ") { if (!root.qcur.locked && root.qcur.options.length > 0) { Sx.set-quick(Sx.quick-sel, Math.mod(root.qcur.value + 1, root.qcur.options.length)); } }
|
||||
else if (e.text == Key.Delete) { Sx.reset-quick(Sx.quick-sel); }
|
||||
else if (e.text == Key.DownArrow) { Sx.zone = 2; }
|
||||
else if (e.text == Key.UpArrow) { Sx.zone = 0; }
|
||||
else { return false; }
|
||||
return true;
|
||||
}
|
||||
if (Sx.zone == 2) {
|
||||
if (e.text == Key.UpArrow) { if (Sx.section == 0 || root.searching) { if (root.top) { Sx.zone = 1; } else { root.exit-up(); } } else { root.go-section(Sx.section - 1); } }
|
||||
else if (e.text == Key.DownArrow) { root.go-section(Math.min(Sx.nav.length - 1, root.searching ? Sx.section : Sx.section + 1)); }
|
||||
else if (e.text == Key.RightArrow || e.text == Key.Return || e.text == " ") { if (root.can-rows()) { Sx.zone = 3; root.reveal(); } }
|
||||
else { return false; }
|
||||
return true;
|
||||
}
|
||||
// the rows
|
||||
if (!root.can-rows()) { Sx.zone = 2; return false; }
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { Sx.zone = 2; }
|
||||
else if (e.text == Key.DownArrow) { if (root.cur.down >= 0) { Sx.row = root.cur.down; root.reveal(); } }
|
||||
else if (e.text == Key.UpArrow) { if (root.cur.up >= 0) { Sx.row = root.cur.up; root.reveal(); } else if (root.top) { Sx.zone = 1; } else { root.exit-up(); } }
|
||||
else if (e.text == Key.Delete) { Sx.reset(Sx.row); }
|
||||
else if (root.cur.kind == 1) { if (e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) { Sx.typing = true; } else if (e.text != Key.LeftArrow) { return false; } }
|
||||
else if (root.cur.kind == 3) { if (e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) { if (!root.cur.locked) { Sx.act(Sx.row); } } else if (e.text != Key.LeftArrow) { return false; } }
|
||||
else if (e.text == Key.RightArrow) { if (!root.cur.locked && root.cur.value < root.cur.options.length - 1) { Sx.set(Sx.row, root.cur.value + 1); } }
|
||||
else if (e.text == Key.LeftArrow) { if (!root.cur.locked && root.cur.value > 0) { Sx.set(Sx.row, root.cur.value - 1); } }
|
||||
else if (e.text == Key.Return || e.text == " ") { if (!root.cur.locked && root.cur.options.length > 0) { Sx.set(Sx.row, Math.mod(root.cur.value + 1, root.cur.options.length)); } }
|
||||
else { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- title and search ----
|
||||
Text { x: root.pad; y: 8px; width: root.width - 2 * root.pad - 320px - root.head-right; text: Sx.title; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; overflow: elide; }
|
||||
Text { x: root.pad; y: 42px; width: root.width - 2 * root.pad - 320px - root.head-right; text: Sx.subtitle; color: Theme.p.dim; font-size: Theme.t-sm; overflow: elide; }
|
||||
Rectangle {
|
||||
x: root.width - root.pad - root.head-right - self.width; y: 12px; width: Math.min(296px, root.width * 0.3); height: 40px; border-radius: 20px;
|
||||
background: Theme.p.surface; border-width: find.has-focus ? 2px : Theme.p.border-w; border-color: find.has-focus ? Theme.p.accent : Theme.p.border;
|
||||
Icon { x: 13px; y: 11px; size: 18px; color: find.has-focus ? Theme.p.accent : Theme.p.dim; commands: Icons.search; }
|
||||
if find.text == "": Text { x: 40px; width: parent.width - 52px; height: parent.height; text: find.has-focus ? "Search settings" : "Search settings ( / )"; color: Theme.p.faint; font-size: Theme.t-sm; vertical-alignment: center; overflow: elide; }
|
||||
find := TextInput {
|
||||
x: 40px; width: parent.width - 76px; height: parent.height; vertical-alignment: center; single-line: true;
|
||||
text <=> Sx.search; color: Theme.p.text; font-size: Theme.t-sm; selection-background-color: Theme.p.accent; selection-foreground-color: Theme.p.on-accent;
|
||||
edited => { Sx.search-changed(self.text); list.content-y = 0; }
|
||||
accepted => { root.refocus(); if (root.can-rows()) { Sx.zone = 3; } }
|
||||
key-pressed(e) => {
|
||||
if (e.text == Key.Escape) { if (self.text != "") { self.text = ""; Sx.search-changed(""); } root.refocus(); return accept; }
|
||||
if (e.text == Key.DownArrow) { root.refocus(); if (root.can-rows()) { Sx.zone = 3; } return accept; }
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
if find.text != "": Rectangle { x: parent.width - 34px; y: 8px; width: 24px; height: 24px; border-radius: 12px; background: xt.has-hover ? Theme.p.raised : transparent;
|
||||
Icon { x: 5px; y: 5px; size: 14px; color: Theme.p.dim; commands: Icons.close; }
|
||||
xt := TouchArea { mouse-cursor: pointer; clicked => { find.text = ""; Sx.search-changed(""); root.refocus(); } }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- presets, then the quick strip ----
|
||||
if root.top: HorizontalLayout {
|
||||
x: root.pad; y: root.head-h; width: root.width - 2 * root.pad; height: 40px; spacing: 10px; alignment: start;
|
||||
VerticalLayout { alignment: center; Text { text: "PRESET"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2px; } }
|
||||
for p[i] in Sx.presets: VerticalLayout { alignment: center;
|
||||
Chip { text: p.name; active: p.active; focused: root.active && Sx.zone == 0 && Sx.preset-sel == i; clicked => { Sx.zone = 0; Sx.preset-sel = i; Sx.apply-preset(i); } }
|
||||
}
|
||||
VerticalLayout { alignment: center; Text { text: "Now: " + Sx.preset-state; color: Theme.p.dim; font-size: Theme.t-sm; font-weight: 600; overflow: elide; } }
|
||||
}
|
||||
if root.top: Rectangle {
|
||||
x: root.pad; y: root.head-h + 52px; width: root.width - 2 * root.pad; height: 76px;
|
||||
for q[i] in Sx.quick: QuickTile {
|
||||
property <length> tw: (parent.width - (Sx.quick.length - 1) * 12px) / Math.max(1, Sx.quick.length);
|
||||
x: i * (self.tw + 12px); y: 0; width: self.tw; height: parent.height; r: q;
|
||||
focused: root.active && Sx.zone == 1 && Sx.quick-sel == i;
|
||||
pick => { Sx.zone = 1; Sx.quick-sel = i; }
|
||||
set(v) => { Sx.set-quick(i, v); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- sections ----
|
||||
nav := Flickable {
|
||||
x: root.pad; y: root.body-y; width: root.nav-w; height: root.body-h;
|
||||
content-width: self.width; content-height: Sx.nav.length * 44px;
|
||||
animate content-y { duration: Theme.ms(180); easing: ease-out; }
|
||||
for n[i] in Sx.nav: Rectangle {
|
||||
property <bool> on: Sx.section == i && !root.searching;
|
||||
x: 0; y: i * 44px; width: parent.width; height: 40px; border-radius: Theme.r-md;
|
||||
background: self.on ? Theme.p.raised : nta.has-hover ? Theme.p.raised.with-alpha(0.5) : transparent;
|
||||
border-width: self.on ? Theme.p.border-w : 0px; border-color: Theme.p.border;
|
||||
animate background { duration: Theme.ms(140); }
|
||||
Rectangle { x: 0; y: 10px; width: 3px; height: 20px; border-radius: 2px; background: Theme.p.accent; opacity: parent.on ? 1 : 0; }
|
||||
Text { x: 16px; width: parent.width - 16px - (n.changed > 0 ? 40px : 10px); height: parent.height; text: n.label; color: parent.on ? Theme.p.text : Theme.p.dim; font-size: Theme.t-md; font-weight: parent.on ? 700 : 500; vertical-alignment: center; overflow: elide; }
|
||||
if n.changed > 0: Rectangle { x: parent.width - 34px; y: 10px; width: 24px; height: 20px; border-radius: 10px; background: Theme.p.accent.with-alpha(0.18);
|
||||
Text { text: n.changed; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; horizontal-alignment: center; vertical-alignment: center; } }
|
||||
FocusRing { on: root.active && Sx.zone == 2 && parent.on; radius: Theme.r-md; gap: 0px; }
|
||||
nta := TouchArea { mouse-cursor: pointer; clicked => { if (root.searching) { find.text = ""; Sx.search-changed(""); } Sx.zone = 2; root.go-section(i); } }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- rows ----
|
||||
list := Flickable {
|
||||
x: root.list-x; y: root.body-y; width: root.list-w; height: root.body-h;
|
||||
content-width: self.width; content-height: Sx.rows-h + 16px;
|
||||
animate content-y { duration: Theme.ms(200); easing: ease-out; }
|
||||
for r[i] in Sx.rows: SettingRow {
|
||||
x: 3px; y: r.y + 3px; width: parent.width - 6px; height: r.h; r: r;
|
||||
focused: root.active && Sx.zone == 3 && Sx.row == i;
|
||||
typing: Sx.typing && Sx.row == i;
|
||||
pick => { Sx.zone = 3; Sx.row = i; }
|
||||
set(v) => { Sx.set(i, v); }
|
||||
act => { Sx.act(i); }
|
||||
text-done(t) => { Sx.row = i; Sx.typing = false; Sx.text(i, t); root.refocus(); }
|
||||
text-cancel => { Sx.typing = false; root.refocus(); }
|
||||
}
|
||||
}
|
||||
// (an empty section: the engine's settings could not be read, or a search found nothing; Rust says which in a note row)
|
||||
|
||||
if root.wide: Details {
|
||||
x: root.width - root.pad - root.det-w; y: root.body-y + 3px; width: root.det-w; height: root.body-h - 6px;
|
||||
r: Sx.zone == 1 && root.top ? root.qcur : root.cur;
|
||||
show-row: (Sx.zone == 1 && root.top && Sx.quick.length > 0) || (Sx.zone == 3 && root.can-rows());
|
||||
preset: Sx.presets[Sx.preset-sel]; show-preset: Sx.zone == 0 && root.top;
|
||||
nav: Sx.nav[Sx.section];
|
||||
set(v) => { if (Sx.zone == 1) { Sx.set-quick(Sx.quick-sel, v); } else { Sx.set(Sx.row, v); } }
|
||||
}
|
||||
}
|
||||
@@ -1,81 +1,15 @@
|
||||
// Settings: layout, theme, UI scale, motion, clip lengths, the in-game overlay's key and the default enhance profile.
|
||||
import { Theme, Palette } from "theme.slint";
|
||||
import { Lib, Prefs, Icon, Icons, Segmented, SliderBar, FocusRing, Btn } from "widgets.slint";
|
||||
import { ProfileEditor } from "editor.slint";
|
||||
|
||||
component Section inherits Rectangle {
|
||||
in property <string> title;
|
||||
in property <string> icon;
|
||||
height: 48px;
|
||||
Icon { x: 0; y: 20px; size: 18px; color: Theme.p.accent; commands: root.icon; }
|
||||
Text { x: 28px; y: 20px; text: root.title; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2px; }
|
||||
}
|
||||
|
||||
component Row inherits Rectangle {
|
||||
in property <string> label;
|
||||
in property <string> hint;
|
||||
in property <bool> focused;
|
||||
callback hit;
|
||||
height: 72px; border-radius: Theme.r-md;
|
||||
background: root.focused ? Theme.p.raised : Theme.p.surface.with-alpha(0.7);
|
||||
border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
animate background { duration: Theme.ms(140); }
|
||||
TouchArea { clicked => { root.hit(); } }
|
||||
Text { x: 20px; y: root.hint == "" ? 26px : 15px; text: root.label; color: Theme.p.text; font-size: Theme.t-md; font-weight: 600; }
|
||||
Text { x: 20px; y: 39px; width: parent.width - 40px; text: root.hint; color: Theme.p.dim; font-size: Theme.t-sm - 1px; overflow: elide; }
|
||||
FocusRing { on: root.focused; radius: Theme.r-md; }
|
||||
@children
|
||||
}
|
||||
|
||||
component Swatch inherits Rectangle {
|
||||
in property <Palette> p;
|
||||
in property <bool> active;
|
||||
callback clicked;
|
||||
height: 84px; border-radius: Theme.r-md;
|
||||
background: root.p.bg; border-width: root.active ? 3px : 1px; border-color: root.active ? Theme.p.accent : Theme.p.border;
|
||||
Rectangle { x: 10px; y: 10px; width: parent.width - 20px; height: 34px; border-radius: 6px; background: root.p.surface; border-width: 1px; border-color: root.p.border;
|
||||
Rectangle { x: 8px; y: 9px; width: 16px; height: 16px; border-radius: 8px; background: @linear-gradient(120deg, root.p.accent 0%, root.p.accent2 100%); }
|
||||
Rectangle { x: 32px; y: 11px; width: parent.width * 0.4; height: 4px; border-radius: 2px; background: root.p.text; }
|
||||
Rectangle { x: 32px; y: 20px; width: parent.width * 0.26; height: 4px; border-radius: 2px; background: root.p.dim; }
|
||||
}
|
||||
Text { x: 12px; y: 54px; width: parent.width - 24px; text: root.p.name; color: root.p.text; font-size: Theme.t-sm - 1px; font-weight: 700; overflow: elide; }
|
||||
TouchArea { mouse-cursor: pointer; clicked => { root.clicked(); } }
|
||||
}
|
||||
// Settings: the settings pane (pane.slint) for the launcher's own settings, the default launch profile and every
|
||||
// engine setting, plus the NVIDIA runtime's licence dialog.
|
||||
import { Theme } from "theme.slint";
|
||||
import { Lib, Icons, Btn } from "widgets.slint";
|
||||
import { SettingsPane, Sx } from "pane.slint";
|
||||
|
||||
export component SettingsView inherits Rectangle {
|
||||
in property <bool> active;
|
||||
in-out property <int> srow: 0;
|
||||
callback exit-up();
|
||||
callback refocus(); // give the keyboard back to the window (the editor's text rows)
|
||||
property <length> cw: Math.min(root.width - 2 * Theme.pad, 1040px);
|
||||
property <length> cx: Math.max(Theme.pad, (root.width - root.cw) / 2);
|
||||
pure function ry(i: int) -> length {
|
||||
return i == 0 ? 136px : i == 1 ? 216px : i == 2 ? 384px : i == 3 ? 520px : i == 4 ? 600px : i == 5 ? 736px : i == 6 ? 816px : i == 7 ? 896px : i == 8 ? 1032px : i == 9 ? 1168px : i == 10 ? 1248px : i == 11 ? 1328px : 1464px;
|
||||
}
|
||||
pure function rh(i: int) -> length { return i == 1 ? 160px : 72px; }
|
||||
function reveal() {
|
||||
if (root.srow == 0) { flick.content-y = 0; }
|
||||
else if (root.ry(root.srow) - 56px < -flick.content-y) { flick.content-y = -(root.ry(root.srow) - 56px); }
|
||||
else if (root.ry(root.srow) + root.rh(root.srow) + 24px > -flick.content-y + flick.height) { flick.content-y = -(root.ry(root.srow) + root.rh(root.srow) + 24px - flick.height); }
|
||||
}
|
||||
function save() { Lib.settings-changed(); }
|
||||
function adjust(d: int) {
|
||||
if (root.srow == 0) { Theme.layout = Math.clamp(Theme.layout + d, 0, 2); }
|
||||
else if (root.srow == 1) { Theme.id = Math.mod(Theme.id + d + Theme.palettes.length, Theme.palettes.length); }
|
||||
else if (root.srow == 2) { Prefs.scale = Math.clamp(Prefs.scale + d, 0, Prefs.scales.length - 1); }
|
||||
else if (root.srow == 3) { Theme.speed = Math.clamp(Math.round((Theme.speed + d * 0.25) * 4) / 4, 0, 2); }
|
||||
else if (root.srow == 4) { Theme.style = Math.clamp(Theme.style + d, 0, 2); }
|
||||
else if (root.srow == 5) { Prefs.replay = Math.clamp(Prefs.replay + d, 0, 6); Prefs.clip = Math.max(0, Math.min(Prefs.clip, Prefs.replay - 1)); }
|
||||
else if (root.srow == 6) { if (Prefs.replay == 0) { return; } Prefs.clip = Math.clamp(Prefs.clip + d, 0, Prefs.replay - 1); }
|
||||
else if (root.srow == 7) { return; }
|
||||
else if (root.srow == 8) { Prefs.overlay-key = Math.clamp(Prefs.overlay-key + d, 0, Prefs.overlay-keys.length - 1); }
|
||||
else if (root.srow == 9) { Prefs.upscaler = Math.clamp(Prefs.upscaler + d, 0, 3); }
|
||||
else if (root.srow == 10) { Prefs.framegen = Math.clamp(Prefs.framegen + d, 0, 2); }
|
||||
else { return; }
|
||||
root.save();
|
||||
}
|
||||
callback refocus(); // give the keyboard back to the window (after typing in a row or the search)
|
||||
public function focus-search() { pane.focus-search(); }
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (Lib.editor-open && Lib.editor-defaults) { return editor.key(e); }
|
||||
if (Lib.nvidia-open) {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { Lib.nvidia-open = false; }
|
||||
else if (e.text == Key.LeftArrow) { Lib.nvidia-btn = Math.max(0, Lib.nvidia-btn - 1); }
|
||||
@@ -83,92 +17,13 @@ export component SettingsView inherits Rectangle {
|
||||
else if (e.text == Key.Return || e.text == " ") { Lib.nvidia-act(Lib.nvidia-btn); }
|
||||
return true;
|
||||
}
|
||||
if ((e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) && root.srow == 12) { Lib.nvidia-btn = Lib.nvidia-installed ? 2 : 0; Lib.nvidia-open = true; return true; }
|
||||
if (e.text == Key.DownArrow) { root.srow = Math.min(12, root.srow + 1); }
|
||||
else if ((e.text == Key.Return || e.text == " ") && root.srow == 7) { Lib.open-clips(); }
|
||||
else if ((e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) && root.srow == 11) { Lib.open-defaults(); }
|
||||
else if (e.text == Key.UpArrow) { if (root.srow == 0) { root.exit-up(); } else { root.srow -= 1; } }
|
||||
else if (e.text == Key.RightArrow) { root.adjust(1); }
|
||||
else if (e.text == Key.LeftArrow) { root.adjust(-1); }
|
||||
else { return false; }
|
||||
root.reveal();
|
||||
return true;
|
||||
return pane.key(e);
|
||||
}
|
||||
|
||||
flick := Flickable {
|
||||
width: root.width; height: root.height; content-width: root.width; content-height: 1612px;
|
||||
animate content-y { duration: Theme.ms(220); easing: ease-out; }
|
||||
Text { x: root.cx; y: 20px; text: "Settings"; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; }
|
||||
Text { x: root.cx; y: 58px; width: root.cw; text: "Saved to " + Prefs.file + " as you change them."; color: Theme.p.dim; font-size: Theme.t-sm; overflow: elide; }
|
||||
|
||||
Section { x: root.cx; y: 88px; width: root.cw; title: "APPEARANCE"; icon: Icons.grid; }
|
||||
Row { x: root.cx; y: root.ry(0); width: root.cw; label: "Layout"; hint: "Big picture is cover first and made for a TV and a controller. List is a dense table."; focused: root.active && root.srow == 0; hit => { root.srow = 0; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 112px + 8px; options: ["Big picture", "Grid", "List"]; value <=> Theme.layout; changed => { root.srow = 0; root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(1); width: root.cw; height: 160px; label: "Theme"; hint: ""; focused: root.active && root.srow == 1; hit => { root.srow = 1; }
|
||||
for p[i] in Theme.palettes: Swatch {
|
||||
property <length> sw: Math.min(160px, (parent.width - 40px - (Theme.palettes.length - 1) * 12px) / Theme.palettes.length);
|
||||
x: 20px + i * (self.sw + 12px); y: 60px; width: self.sw; p: p; active: Theme.id == i;
|
||||
clicked => { Theme.id = i; root.srow = 1; root.save(); }
|
||||
}
|
||||
Text { x: 20px + 64px; y: 28px; text: Theme.p.name; color: Theme.p.dim; font-size: Theme.t-sm; }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(2); width: root.cw; label: "Interface size"; hint: "Scales the whole launcher, on top of your system's display scale."; focused: root.active && root.srow == 2; hit => { root.srow = 2; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.scales; value <=> Prefs.scale; changed => { root.srow = 2; root.save(); } }
|
||||
}
|
||||
|
||||
Section { x: root.cx; y: 472px; width: root.cw; title: "MOTION"; icon: Icons.sparkle; }
|
||||
Row { x: root.cx; y: root.ry(3); width: root.cw; label: "Animation speed"; hint: "Drag to zero to turn every animation off."; focused: root.active && root.srow == 3; hit => { root.srow = 3; }
|
||||
Text { x: parent.width - 16px - 280px - 96px; width: 80px; height: parent.height; horizontal-alignment: right; vertical-alignment: center;
|
||||
text: Theme.speed < 0.01 ? "Off" : Math.round(Theme.speed * 100) + "%"; color: Theme.speed < 0.01 ? Theme.p.faint : Theme.p.text; font-size: Theme.t-md; font-weight: 700; }
|
||||
SliderBar { x: parent.width - self.width - 16px; y: 16px; minimum: 0; maximum: 2; value <=> Theme.speed; focused: false; changed => { root.srow = 3; root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(4); width: root.cw; label: "Animation style"; hint: "Smooth eases out gently, Snappy is short and sharp, Bouncy overshoots a little."; focused: root.active && root.srow == 4; hit => { root.srow = 4; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 112px + 8px; options: ["Smooth", "Snappy", "Bouncy"]; value <=> Theme.style; changed => { root.srow = 4; root.save(); } }
|
||||
}
|
||||
|
||||
Section { x: root.cx; y: 688px; width: root.cw; title: "CLIPS"; icon: Icons.film; }
|
||||
Row { x: root.cx; y: root.ry(5); width: root.cw; label: "Keep the last";
|
||||
hint: Prefs.replay == 0 ? "Off: nothing is recorded, so it costs no performance." : "Instant replay buffer (--replay). Off records nothing.";
|
||||
focused: root.active && root.srow == 5; hit => { root.srow = 5; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 7 * 72px + 8px; options: Prefs.replay-options; value <=> Prefs.replay; changed => { root.srow = 5; Prefs.clip = Math.max(0, Math.min(Prefs.clip, Prefs.replay - 1)); root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(6); width: root.cw; label: "A save writes"; hint: Prefs.replay == 0 ? "Instant replay is off, so there is nothing to save." : "Passed as --clip-length. " + Lib.hotkey-status; focused: root.active && root.srow == 6; hit => { root.srow = 6; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.clip-lengths; limit: Prefs.replay - 1; value <=> Prefs.clip; changed => { root.srow = 6; root.save(); } }
|
||||
}
|
||||
|
||||
Row { x: root.cx; y: root.ry(7); width: root.cw; label: "Clips folder"; hint: Lib.clips-dir + "/<game>/ (Enter opens it)"; focused: root.active && root.srow == 7; hit => { root.srow = 7; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 160px; text: "Open"; icon: Icons.film; focused: root.active && root.srow == 7; clicked => { root.srow = 7; Lib.open-clips(); } }
|
||||
}
|
||||
|
||||
Section { x: root.cx; y: 984px; width: root.cw; title: "IN-GAME OVERLAY"; icon: Icons.gamepad; }
|
||||
Row { x: root.cx; y: root.ry(8); width: root.cw; label: "Overlay key"; hint: "Opens Summit's overlay while you play. Esc is never taken from the game."; focused: root.active && root.srow == 8; hit => { root.srow = 8; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: Prefs.overlay-keys.length * 76px + 8px; options: Prefs.overlay-keys; value <=> Prefs.overlay-key; changed => { root.srow = 8; root.save(); } }
|
||||
}
|
||||
|
||||
Section { x: root.cx; y: 1120px; width: root.cw; title: "DEFAULT LAUNCH PROFILE"; icon: Icons.monitor; }
|
||||
Row { x: root.cx; y: root.ry(9); width: root.cw; label: "Default upscaler"; hint: "Every game uses this unless it sets its own (its page > Profile). Auto: the engine's own setting (FSR)."; focused: root.active && root.srow == 9; hit => { root.srow = 9; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 4 * 96px + 8px; options: ["Auto", "Off", "FSR", "RTX VSR"]; value <=> Prefs.upscaler; changed => { root.srow = 9; root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(10); width: root.cw; label: "Default frame generation"; hint: "RIFE needs an NVIDIA GPU and the engine's Python environment. Auto: the engine's own setting (on)."; focused: root.active && root.srow == 10; hit => { root.srow = 10; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 96px + 8px; options: ["Auto", "Off", "RIFE"]; value <=> Prefs.framegen; changed => { root.srow = 10; root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(11); width: root.cw; label: "Every default setting"; hint: Prefs.defaults-note; focused: root.active && root.srow == 11; hit => { root.srow = 11; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 160px; text: "Edit"; icon: Icons.sliders; focused: root.active && root.srow == 11; clicked => { root.srow = 11; Lib.open-defaults(); } }
|
||||
}
|
||||
Section { x: root.cx; y: 1416px; width: root.cw; title: "NVIDIA"; icon: Icons.download; }
|
||||
Row { x: root.cx; y: root.ry(12); width: root.cw; label: "NVIDIA VFG and RTX VSR"; hint: Lib.nvidia-status; focused: root.active && root.srow == 12; hit => { root.srow = 12; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 200px; enabled: !Lib.nvidia-busy && (Lib.nvidia-ok || Lib.nvidia-installed);
|
||||
text: Lib.nvidia-busy ? "Working..." : Lib.nvidia-installed ? "Manage" : "Set up"; icon: Icons.download; focused: root.active && root.srow == 12;
|
||||
clicked => { root.srow = 12; Lib.nvidia-btn = Lib.nvidia-installed ? 2 : 0; Lib.nvidia-open = true; } }
|
||||
}
|
||||
Text { x: root.cx; y: 1556px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
}
|
||||
|
||||
editor := ProfileEditor {
|
||||
width: root.width; height: root.height;
|
||||
visible: Lib.editor-open && Lib.editor-defaults; opacity: self.visible ? 1 : 0;
|
||||
close => { Lib.editor-open = false; Lib.editor-typing = false; }
|
||||
pane := SettingsPane {
|
||||
x: 0; y: 12px; width: root.width; height: root.height - 12px;
|
||||
active: root.active && !Lib.nvidia-open && !Lib.editor-open;
|
||||
exit-up => { root.exit-up(); }
|
||||
refocus => { root.refocus(); }
|
||||
}
|
||||
|
||||
@@ -184,7 +39,7 @@ export component SettingsView inherits Rectangle {
|
||||
col := VerticalLayout {
|
||||
padding: 28px; spacing: 14px;
|
||||
Text { text: "NVIDIA VFG AND RTX VSR"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px; }
|
||||
Text { text: Lib.nvidia-installed ? "Installed. NVIDIA VFG (frame generation) and RTX VSR (upscaling) can be picked in a game's profile and in the in-game overlay."
|
||||
Text { text: Lib.nvidia-installed ? "Installed. NVIDIA VFG (frame generation) and RTX VSR (upscaling) can be picked in Settings, in a game's profile and in the in-game overlay."
|
||||
: "NVIDIA VFG (AI frame generation) and RTX VSR (AI upscaling) run on NVIDIA's own runtime, which Summit can't ship. Summit downloads it for you from NVIDIA's package index (about 540 MB, an exact version checked by its hash) into your home folder."; color: Theme.p.text; font-size: Theme.t-md; wrap: word-wrap; }
|
||||
if !Lib.nvidia-installed: Text { text: "It comes under these NVIDIA licences. Read them; downloading means you accept them:"; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if !Lib.nvidia-installed: VerticalLayout { spacing: 6px;
|
||||
|
||||
@@ -70,30 +70,18 @@ export struct Detail {
|
||||
has-account: bool, // a Steam game on a PC that remembers more than one Steam account
|
||||
account: SteamAccount, // the account Play starts it on (login "": whichever account Steam is on)
|
||||
account-note: string, // why that one
|
||||
compare-note: string, // what Compare does here, or why it cannot
|
||||
}
|
||||
|
||||
// One row of the profile editor. kind 0: a value picked from options; 1: a line of text; 2: a section header.
|
||||
// own: the game sets this itself (not following the launcher's defaults).
|
||||
// A window in the "pick the game's window" list: what it shows, and whether it opened after Play was pressed.
|
||||
export struct PickRow { title: string, detail: string, fresh: bool }
|
||||
|
||||
export struct PRow { label: string, hint: string, options: [string], value: int, kind: int, text: string, placeholder: string, own: bool }
|
||||
|
||||
// Preferences edited on the settings page (layout, theme and motion live in Theme). Rust saves them to ui.toml.
|
||||
export global Prefs {
|
||||
in-out property <int> scale: 2; // index into scales
|
||||
in property <[string]> scales: ["80%", "90%", "100%", "110%", "125%", "150%"];
|
||||
in-out property <int> replay: 3; // index into replay-options: 0 off, then clip-lengths
|
||||
in-out property <int> clip: 1;
|
||||
in property <[string]> clip-lengths: ["15 s", "30 s", "1 min", "3 min", "5 min", "10 min"];
|
||||
in property <[string]> replay-options: ["Off", "15 s", "30 s", "1 min", "3 min", "5 min", "10 min"];
|
||||
in-out property <int> overlay-key: 0; // index into overlay-keys: the key that opens the in-game overlay
|
||||
in property <[string]> overlay-keys: ["Insert", "Home", "End", "Pause", "F9", "F10"];
|
||||
in-out property <int> upscaler: 0; // auto (engine setting), none, fsr, rtx-vsr
|
||||
in-out property <int> framegen: 0; // auto (engine setting), none, rife
|
||||
in property <string> defaults-note; // the default launch profile in one line
|
||||
in property <string> file; // where the settings are stored, for display
|
||||
}
|
||||
// A game's Statistics view: a tile, and one session summary the engine wrote (shown as the file has it).
|
||||
export struct StatTile { label: string, value: string, note: string }
|
||||
export struct SessField { name: string, value: string }
|
||||
export struct SessRow { when: string, headline: string, settings: string, file: string, fields: [SessField] }
|
||||
// One comparison the Compare dialog offers: a setting and the values to put side by side.
|
||||
export struct CmpRow { label: string, detail: string }
|
||||
|
||||
export global Lib {
|
||||
in property <[Game]> games;
|
||||
@@ -117,22 +105,29 @@ export global Lib {
|
||||
callback open-detail(int);
|
||||
callback play(int);
|
||||
callback toggle-pin(int);
|
||||
callback settings-changed();
|
||||
callback toggle-fullscreen();
|
||||
// profile editor
|
||||
in property <[PRow]> prof-rows;
|
||||
in property <string> prof-file;
|
||||
in property <string> prof-title;
|
||||
in property <string> prof-note;
|
||||
// a game's profile (editor.slint): the settings pane, for that game
|
||||
in-out property <bool> editor-open;
|
||||
in-out property <bool> editor-defaults; // editing the launcher's defaults (Settings), not a game
|
||||
in-out property <bool> editor-typing; // a text row has the keyboard
|
||||
in-out property <int> editor-row;
|
||||
callback open-profile(int);
|
||||
callback open-defaults();
|
||||
callback prof-set(int, int); // row, option index
|
||||
callback prof-text(int, string); // row, new text
|
||||
callback prof-reset();
|
||||
callback close-profile();
|
||||
// a game's statistics (extras.slint)
|
||||
in-out property <bool> stats-open;
|
||||
in property <string> stats-title;
|
||||
in property <string> stats-note;
|
||||
in property <[StatTile]> stat-tiles;
|
||||
in property <[SessRow]> sess;
|
||||
in property <string> sess-empty; // where summaries are looked for, when there are none
|
||||
in-out property <int> sess-sel;
|
||||
callback open-stats(int);
|
||||
// start a game with the engine's live comparison (extras.slint)
|
||||
in-out property <bool> cmp-open;
|
||||
in property <string> cmp-title;
|
||||
in property <[CmpRow]> cmp-rows;
|
||||
in property <string> cmp-note;
|
||||
in property <bool> cmp-ok; // this engine has --compare and the game can be enhanced
|
||||
in-out property <int> cmp-sel;
|
||||
callback open-compare(int);
|
||||
callback compare-start(int);
|
||||
callback toggle-enhance(int);
|
||||
callback change-art(int);
|
||||
callback add-game(int); // -1: Add a game; an entry found on disk: add that folder's game
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# launcher-ui: settings from the engine's registry, presets, per-game parity, statistics, Compare
|
||||
|
||||
Branch `ap/launcher-ui`. Everything below was done on CT110 (no GPU) unless it says otherwise.
|
||||
|
||||
## What I found first
|
||||
|
||||
The task assumed the launcher already read the engine's setting registry (`python -m framegen.settings`). It did
|
||||
not: nothing under `crates/` called it. The Settings page had 13 hand-placed rows and the profile editor carried a
|
||||
hard-coded copy of the engine's choices (`data.rs`), so a new engine setting would not have appeared anywhere. The
|
||||
registry JSON also left out `sub`. So the registry-driven page was built, not just verified.
|
||||
|
||||
## What changed
|
||||
|
||||
**Engine (shared files, small local additions)**
|
||||
- `engine/framegen/settings.py`: `specs_json()` now carries `"sub"`; new `parse_set("KEY=VALUE")`.
|
||||
- `engine/run.py`: `--set KEY=VALUE` (repeatable): any setting by its key for one run, applied after the named
|
||||
flags; a bad one is printed and left out. This is how a game's own engine settings reach the engine.
|
||||
- `engine/tests/test_settings_registry.py`: the JSON's shape, `sub`, `parse_set` (every choice of every setting).
|
||||
|
||||
**summit-core**
|
||||
- `registry.rs`: reads the registry leniently (unknown sections, unknown fields, choices as bare values, settings
|
||||
without choices, wrong types, duplicate keys all read), the engine's `settings.json` key by key (anything else in
|
||||
the file is kept), `applies`/`sources` reasons, and `forced()`: which engine keys a launch profile decides.
|
||||
- `presets.rs`: Quality, Balanced, Performance, Lowest delay as one table (six keys each), with what each changes.
|
||||
- `sessions.rs`: session summary JSON files, read as they are (see Statistics below).
|
||||
- `profile.rs`: a profile layer gets an `[engine]` table (any engine setting by key), layered like everything else.
|
||||
- `engine.rs`: the `[engine]` table goes out as `--set=KEY=<json>`; `Live.compare: Option<String>` becomes
|
||||
`--compare=<spec>` (`parse_compare`, `has_compare`); **no `--hz` when the profile sets no multiplier** (before, 2x
|
||||
was always passed, which overrode the engine's saved Frame multiplier; three test expectations changed with it).
|
||||
- `launch.rs`: `with_compare()`. `summit-cli`: `summit run --compare <spec>` (needs `--enhance`).
|
||||
|
||||
**summit-gui**
|
||||
- `ui/pane.slint` (new): one settings pane: presets row, quick strip, section list, search box, rows, and a detail
|
||||
panel (whole help text, picture / speed lines, every choice with its hint, default, why it is greyed).
|
||||
- `ui/settings.slint`, `ui/editor.slint` rewritten around it: the Settings page (sections Launcher, Game defaults,
|
||||
then the engine's own groups) and a game's Profile (Launch, then the engine's groups with "Global" per row).
|
||||
- `ui/extras.slint` (new): a game's Statistics view and the Compare dialog. `ui/detail.slint`: Compare and
|
||||
Statistics buttons.
|
||||
- `src/rows.rs` (new, unit tested): builds every row from data. `src/pane.rs` (new): reads the files, writes a
|
||||
change where it belongs, rebuilds the pane from the files (so what is shown is what was read back).
|
||||
- `src/data.rs`: the hard-coded engine rows are gone; it keeps the launch rows (monitor, mode, window, focus,
|
||||
Enhance, arguments, environment, game window).
|
||||
- `src/pad.rs`: Y = Delete (reset the focused setting). `src/shot.rs` + `main.rs`: `SUMMIT_SECTION`,
|
||||
`SUMMIT_SEARCH`, `SUMMIT_ZONE`, `SUMMIT_PRESET`, `SUMMIT_QUICK`, `SUMMIT_STATS`, `SUMMIT_COMPARE`.
|
||||
- `docs/demo/launcher-ui-shots.sh`: makes every screenshot below again.
|
||||
|
||||
**Where a value is saved** (no row is a fake; each was changed with keys and the file read afterwards)
|
||||
|
||||
| Rows | File |
|
||||
|---|---|
|
||||
| Launcher (layout, theme, size, motion, overlay key) | `~/.config/summit/ui.toml` |
|
||||
| Instant replay length, default clip length | `ui.toml` too: Summit passes them on every start, so the engine's file would lose |
|
||||
| Game defaults / a game's Launch rows | `~/.config/summit/profiles/default.toml` / `<id>.toml` |
|
||||
| Engine settings, global | the engine's `settings.json` (the path the registry reports), key by key; the default is "not in the file" |
|
||||
| Engine settings, one game | `[engine]` in the game's profile, sent as `--set` |
|
||||
|
||||
Rows that cannot be set from here say why and are locked: session-only settings (`saved: false`), Fullscreen once
|
||||
a Window mode is chosen, and any setting without choices (a kind the launcher cannot draw yet).
|
||||
|
||||
Older profiles' named engine settings (`upscaler`, `framegen`, `model`...) still work. When a row is changed, the
|
||||
value moves to the new place and the old name is dropped; changing a global row also drops that key from
|
||||
`default.toml`, because it would otherwise win over `settings.json` on every start.
|
||||
|
||||
## What I verified, and how
|
||||
|
||||
- **Tests**: `cargo test --workspace`: 175 (core) + 34 (gui) + 1 pass. Engine `pytest tests -q`: 120 passed, 1
|
||||
skipped. New tests cover the registry parser (including a "newer engine" registry), the settings file, presets
|
||||
(each value checked against the real registry when python3 is there), sessions, the `[engine]` layering, `--set`
|
||||
and `--compare` argv, and the rows (sections, greyed reasons, game vs global, typed values, search, layout).
|
||||
- **New engine settings appear by themselves**: a temporary copy of the engine got two invented sections
|
||||
("Anti-aliasing", "Comparison"), three settings, a third impact line ("memory") and a setting with no choices.
|
||||
The unchanged launcher showed all of them, put the `quick` one in the top strip, changed one (it landed in
|
||||
`settings.json` as `"aa": "fxaa"`), and locked the choice-less one with a reason. Seen in a headless render (not
|
||||
committed as a screenshot: the settings were invented for the test).
|
||||
- **Every control writes and is read back** (headless render driven with `SUMMIT_KEYS`, then the files printed):
|
||||
preset Performance (global) -> `motion: half, output_res: 1920x1080`; quick strip Upscaler -> `scaler: vsr`; a
|
||||
row -> `overlay_style: graphs`, Delete removed it; theme -> `ui.toml`; replay length -> `ui.toml`; typed search
|
||||
`/vsync` then Right -> `vsync: true`. The engine's own `Settings.load()` then read that file: `vsr half
|
||||
1920x1080 True`.
|
||||
- **Per game**: preset Lowest delay in Voidrunner's profile wrote the six keys under `[engine]`; `summit enhance
|
||||
--profile custom:voidrunner --dry-run` printed `--set=hz=60 --set=interp=false ... --set=scaler="fsr"`, and
|
||||
`parse_set` + `Settings.override` accepted each. **No engine run was made with `--set`.**
|
||||
- **Compare**: with this branch's engine (no `--compare`) the dialog is disabled with a note. Against a copy of
|
||||
the engine with a placeholder `--compare` argument, Enter built
|
||||
`summit run custom:voidrunner --focus --compare=hz:60,90,120,150 --enhance ...` (headless, nothing started).
|
||||
- **A real window, once**: the same debug build ran fullscreen on the GPU VM's KDE X11 desktop (software OpenGL
|
||||
there). The Settings page came up from the VM's own python3 registry and six synthetic keys moved the focus to
|
||||
the right row (`live-vm-settings-x11.png`). Two later runs to check a write in a real window did not come up:
|
||||
another agent's screenshot tool was holding the shared display. So **writes are verified headless only**.
|
||||
- **Layouts and themes**: all six themes, Big picture and List layouts, 1600x900, 1280x800 and 1024x640 rendered
|
||||
and looked at.
|
||||
- **Animation speed**: every `animate` in the UI already goes through `Theme.ms()`, including the new files; the one
|
||||
ticking animation checks `Theme.motion`. Checked by reading the code and as static frames only.
|
||||
|
||||
## Screenshots (`docs/media/launcher-ui/`)
|
||||
|
||||
All but the last are **headless renders** of the real UI (Slint software renderer, 1600x900 unless named) over the
|
||||
invented demo library of `docs/demo/make_demo_home.py`. Settled frames: no animation is shown. Each exists as
|
||||
`-midnight` and in the second theme named.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `settings-launcher-{midnight,daylight}` | Settings, Launcher section, focus on the section list |
|
||||
| `settings-engine-{midnight,steam}` | Settings > Frame generation, a row focused, detail panel |
|
||||
| `settings-greyed-{midnight,violet}` | Upscaling: FSR sharpening greyed with the reason (upscaler is RTX VSR) |
|
||||
| `settings-search-{midnight,daylight}` | search "overlay": rows from two sections |
|
||||
| `settings-search-none-{midnight,oled}` | a search that finds nothing |
|
||||
| `settings-presets-{midnight,contrast}` | the Performance preset focused, what it sets |
|
||||
| `settings-quick-{midnight,daylight}` | the quick strip focused (Upscaler) |
|
||||
| `settings-defaults-{midnight,steam}` | Settings > Game defaults |
|
||||
| `settings-small-contrast`, `settings-deck-midnight` | 1024x640 in List layout; 1280x800 |
|
||||
| `profile-engine-{midnight,daylight}` | a game's profile: its own Frame multiplier, the rest Global |
|
||||
| `profile-launch-{midnight,violet}` | a game's profile, Launch section |
|
||||
| `profile-presets-{midnight,steam}` | presets in a game's profile |
|
||||
| `stats-{midnight,daylight}` | Statistics with two sessions: **sample JSON files written by the screenshot script**, not engine output |
|
||||
| `stats-empty-{midnight,steam}` | Statistics with no sessions |
|
||||
| `compare-{midnight,daylight}` | the Compare dialog, disabled: this engine has no `--compare` |
|
||||
| `game-page-{midnight,oled}` | a game's page with the Compare and Statistics buttons |
|
||||
| `live-vm-settings-x11.png` | **real window** on the GPU VM (KDE X11, llvmpipe), cropped at the right to cut desktop notification popups, which covered the detail panel. The library is empty there (no demo data). |
|
||||
|
||||
`docs/media/summit-settings.png` (README, top) was replaced by the new Settings render.
|
||||
|
||||
## Not done, or not tested
|
||||
|
||||
- **Not run by a person**: no mouse, no real controller, no real desktop session beyond the one VM run. Mouse
|
||||
handlers exist for every control but none was clicked.
|
||||
- **Compare from the "now playing" screen** is not there: the launcher has no way to reconfigure a running engine.
|
||||
Compare is only on a game's page. The values' spelling in `--compare` (`true,false`, bare strings) is a guess
|
||||
until the engine's side lands; `has_compare()` looks for `"--compare"` in `run.py`.
|
||||
- **Statistics has read no real engine summary**: the format is another branch's. The reader shows whatever fields
|
||||
a file has and guesses only the headline fields by name (duration, average fps, lows, a `settings` object, the
|
||||
game). If that branch writes somewhere other than a `sessions` or `stats` folder under the engine's or Summit's
|
||||
data, state, cache or config folders, `sessions::dirs()` needs that path (or `SUMMIT_SESSIONS_DIR`).
|
||||
- **Search cannot be typed with a controller** (no on-screen keyboard).
|
||||
- **Presets' costs are not measured**: the descriptions quote the engine's own impact notes.
|
||||
- A game's Launch rows still say "Default · ..." where engine rows say "Global · ...".
|
||||
- `summit profile set` has no flag for the `[engine]` table (edit the file, or use the launcher).
|
||||
- The old Settings rows "Default upscaler" and "Default frame generation" are gone: the quick strip does that now,
|
||||
in `settings.json`.
|
||||
- `docs/media/live/gui-profile-editor.png` (the old editor, live) is no longer referenced by the README; left in place.
|
||||
- Test functions in `data.rs` for rows that no longer exist (`frame_generation_rows_follow_the_choices`,
|
||||
`frame_multiplier_rows`, `game_frame_rate_and_output_resolution_rows`, and the upscaler / VSync parts of two
|
||||
others) were removed with those rows; `rows.rs` tests the same behaviour on the new rows.
|
||||
- Debug builds only; no release build was made.
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/bin/sh
|
||||
# Regenerate docs/media/launcher-ui/: headless renders (software renderer, no display needed) of the settings page,
|
||||
# presets, a game's profile, its Statistics view and the Compare dialog, each in two themes. Static frames: no
|
||||
# animation is shown or checked by these.
|
||||
# docs/demo/launcher-ui-shots.sh [path/to/summit-gui] (default: the debug build in $CARGO_TARGET_DIR or target/)
|
||||
# The demo library is invented (make_demo_home.py). The two session files under "sessions" are SAMPLE input written
|
||||
# here so the Statistics view has something to list: the engine's own summaries may look different, and the view
|
||||
# shows whatever fields a file has.
|
||||
set -e
|
||||
cd "$(dirname "$0")/../.."
|
||||
ROOT=$PWD
|
||||
BIN=${1:-${CARGO_TARGET_DIR:-$ROOT/target}/debug/summit-gui}
|
||||
DEMO=${SUMMIT_DEMO_HOME:-/tmp/summit-launcher-ui-demo}
|
||||
OUT=$ROOT/docs/media/launcher-ui
|
||||
PY=${PYTHON:-python3}
|
||||
$PY docs/demo/make_demo_home.py "$DEMO" >/dev/null
|
||||
mkdir -p "$OUT" "$DEMO/.local/share/smoovplay/sessions"
|
||||
cat > "$DEMO/.local/share/smoovplay/sessions/sample-1.json" <<'JSON'
|
||||
{"game": "Voidrunner", "ended": 1795100000, "duration_s": 1843.2, "fps": {"avg": 118.4, "low_1": 97.2, "low_01": 74.0}, "game_fps": 59.8, "delay_ms": 21.5,
|
||||
"settings": {"interp": true, "hz": 120, "scaler": "fsr", "model": "4.22.lite"}}
|
||||
JSON
|
||||
cat > "$DEMO/.local/share/smoovplay/sessions/sample-2.json" <<'JSON'
|
||||
{"game": "Voidrunner", "ended": 1795013600, "duration_s": 412, "fps": {"avg": 59.9, "low_1": 55.1}, "settings": {"interp": false, "scaler": "bilinear"}}
|
||||
JSON
|
||||
run() { # run <name> VAR=value...
|
||||
n=$1; shift
|
||||
env HOME="$DEMO" XDG_CONFIG_HOME="$DEMO/.config" XDG_DATA_HOME="$DEMO/.local/share" XDG_CACHE_HOME="$DEMO/.cache" XDG_STATE_HOME="$DEMO/.local/state" \
|
||||
SUMMIT_ENGINE="$ROOT/engine" SUMMIT_SHOT="$OUT" SUMMIT_NAME="$n" "$@" "$BIN" "$DEMO/Games" >/dev/null
|
||||
}
|
||||
both() { # both <name> <theme2> VAR=value...: midnight and one more theme
|
||||
name=$1; t2=$2; shift 2
|
||||
run "$name-midnight" SUMMIT_THEME=midnight "$@"
|
||||
run "$name-$t2" SUMMIT_THEME=$t2 "$@"
|
||||
}
|
||||
G=custom:voidrunner
|
||||
# a few real changes first, made through the UI itself (keys), so the renders show dots, "Custom" and a game's own:
|
||||
run _setup SUMMIT_VIEW=settings SUMMIT_SECTION=overlay SUMMIT_ZONE=3 SUMMIT_KEYS="Down Right Right" # Stats overlay style: Graphs
|
||||
run _setup SUMMIT_VIEW=settings SUMMIT_SECTION=upscaling SUMMIT_ZONE=3 SUMMIT_KEYS="Right" # Upscaler: NVIDIA RTX VSR
|
||||
run _setup SUMMIT_DETAIL=$G SUMMIT_EDITOR=1 SUMMIT_SECTION="frame generation" SUMMIT_ZONE=3 SUMMIT_KEYS="Down Left" # this game: its own Frame multiplier, one step down (3x)
|
||||
rm -f "$OUT/_setup.png"
|
||||
|
||||
both settings-launcher daylight SUMMIT_VIEW=settings
|
||||
both settings-engine steam SUMMIT_VIEW=settings SUMMIT_SECTION="frame generation" SUMMIT_ZONE=3 SUMMIT_KEYS="Down Down Down Down"
|
||||
both settings-greyed violet SUMMIT_VIEW=settings SUMMIT_SECTION=upscaling SUMMIT_ZONE=3 SUMMIT_KEYS="Down"
|
||||
both settings-search daylight SUMMIT_VIEW=settings SUMMIT_SEARCH="overlay" SUMMIT_ZONE=3 SUMMIT_KEYS="Down Down"
|
||||
both settings-search-none oled SUMMIT_VIEW=settings SUMMIT_SEARCH="ray tracing"
|
||||
both settings-presets contrast SUMMIT_VIEW=settings SUMMIT_ZONE=0 SUMMIT_PRESET=2
|
||||
both settings-quick daylight SUMMIT_VIEW=settings SUMMIT_ZONE=1 SUMMIT_QUICK=4
|
||||
both settings-defaults steam SUMMIT_VIEW=settings SUMMIT_SECTION="game defaults" SUMMIT_ZONE=3 SUMMIT_KEYS="Down Down Down"
|
||||
both profile-engine daylight SUMMIT_DETAIL=$G SUMMIT_EDITOR=1 SUMMIT_SECTION="frame generation" SUMMIT_ZONE=3 SUMMIT_KEYS="Down"
|
||||
both profile-launch violet SUMMIT_DETAIL=$G SUMMIT_EDITOR=1 SUMMIT_ZONE=3 SUMMIT_KEYS="Down Down Down"
|
||||
both profile-presets steam SUMMIT_DETAIL=$G SUMMIT_EDITOR=1 SUMMIT_ZONE=0 SUMMIT_PRESET=3
|
||||
both stats daylight SUMMIT_DETAIL=$G SUMMIT_STATS=1
|
||||
both stats-empty steam SUMMIT_DETAIL="hollow tide" SUMMIT_STATS=1
|
||||
both compare daylight SUMMIT_DETAIL=$G SUMMIT_COMPARE=1 XDG_SESSION_TYPE=x11 DISPLAY=:99
|
||||
both game-page oled SUMMIT_DETAIL=$G SUMMIT_KEYS="Right Right" XDG_SESSION_TYPE=x11 DISPLAY=:99
|
||||
run settings-small-contrast SUMMIT_THEME=contrast SUMMIT_LAYOUT=list SUMMIT_SIZE=1024x640 SUMMIT_VIEW=settings SUMMIT_SECTION=display SUMMIT_ZONE=3 SUMMIT_KEYS="Down Down"
|
||||
run settings-deck-midnight SUMMIT_THEME=midnight SUMMIT_SIZE=1280x800 SUMMIT_VIEW=settings SUMMIT_SECTION=clips SUMMIT_ZONE=3
|
||||
ls "$OUT"
|
||||
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 182 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 244 KiB |
|
After Width: | Height: | Size: 237 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 180 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 191 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 207 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 161 KiB |
|
After Width: | Height: | Size: 158 KiB |
|
After Width: | Height: | Size: 176 KiB |
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 216 KiB |
|
After Width: | Height: | Size: 207 KiB |
|
After Width: | Height: | Size: 205 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 305 KiB After Width: | Height: | Size: 158 KiB |
@@ -96,6 +96,29 @@ def valid_hz(value: Any) -> bool:
|
||||
return isinstance(value, int) and not isinstance(value, bool) and HZ_MIN <= value <= HZ_MAX and value % 30 == 0
|
||||
|
||||
|
||||
def parse_set(text: str) -> tuple[str, Any]:
|
||||
""" "KEY=VALUE" from `run.py --set` (Summit's per-game profile): any setting of the registry by its key, with the
|
||||
value as JSON (true, 90, 0.5, "fsr"; a bare word is taken as a string). Raises ValueError with the reason when the
|
||||
key is unknown or the value is not one the setting accepts."""
|
||||
key, sep, raw = text.partition("=")
|
||||
key = key.strip()
|
||||
if not sep or key not in BY_KEY:
|
||||
raise ValueError(f"{text!r}: KEY=VALUE with a setting's key (python -m framegen.settings lists them)")
|
||||
spec = BY_KEY[key]
|
||||
try:
|
||||
tries = [json.loads(raw), raw.strip()]
|
||||
except ValueError:
|
||||
tries = [raw.strip()]
|
||||
for value in tries:
|
||||
if isinstance(value, bool) != isinstance(spec.default, bool): # JSON true is not the number 1 here
|
||||
continue
|
||||
if isinstance(value, int) and isinstance(spec.default, float):
|
||||
value = float(value)
|
||||
if spec.accepts(value):
|
||||
return key, value
|
||||
raise ValueError(f"{key}: {raw.strip()!r} is not one of {spec.choices}")
|
||||
|
||||
|
||||
ON_OFF = {True: "On", False: "Off"}
|
||||
|
||||
|
||||
@@ -653,6 +676,7 @@ def specs_json(specs: tuple[Spec, ...] = SPECS) -> dict:
|
||||
"path": str(DEFAULT_PATH),
|
||||
"impact_pc": IMPACT_PC,
|
||||
"specs": [{"key": s.key, "label": s.label, "group": s.group, "help": s.help, "default": s.default,
|
||||
"sub": s.sub,
|
||||
"live": s.live, "saved": s.saved, "later": s.later, "quick": s.quick, "impact": s.impact,
|
||||
"experimental": s.experimental,
|
||||
"sources": list(s.sources) or None,
|
||||
|
||||
@@ -320,6 +320,9 @@ def main() -> int:
|
||||
ap.add_argument("--settings", default=str(DEFAULT_PATH), metavar="JSON",
|
||||
help="settings file the menu loads and saves (default %(default)s); 'none' = defaults, unsaved")
|
||||
# These override the saved settings for this run (not saved); the menu can change them live.
|
||||
ap.add_argument("--set", dest="set_values", action="append", default=[], metavar="KEY=VALUE",
|
||||
help="any setting by its key, for this run only (repeatable): --set overlay_style=graphs. "
|
||||
"Summit passes a game's own settings this way; they win over the flags above")
|
||||
ap.add_argument("--vsync", action=argparse.BooleanOptionalAction, default=None,
|
||||
help="vsync the window (use with G-Sync/FreeSync displays)")
|
||||
ap.add_argument("--fullscreen", action=argparse.BooleanOptionalAction, default=None, help="start fullscreen")
|
||||
@@ -515,6 +518,12 @@ def main() -> int:
|
||||
test_model = a.model if a.model is not None and a.model not in BY_KEY["model"].choices else None
|
||||
if a.model is not None and test_model is None:
|
||||
settings.override("model", a.model)
|
||||
for text in a.set_values: # --set KEY=VALUE: this run only; one that can't be used is said and left out
|
||||
from framegen.settings import parse_set
|
||||
try:
|
||||
settings.override(*parse_set(text))
|
||||
except ValueError as e:
|
||||
print(f"[settings] --set ignored: {e}")
|
||||
if test is not None: # the menu's "Simulate a 30 fps game" switches test mode live
|
||||
settings.watch(lambda key: test.set_on(settings.simulate_30) if key == "simulate_30" else None)
|
||||
if settings.hz > 60 and (a.out or not a.display):
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""The registry as the launcher reads it (python -m framegen.settings) and `run.py --set KEY=VALUE`."""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from framegen import settings as S
|
||||
|
||||
|
||||
def test_specs_json_is_plain_json_with_what_the_launcher_draws():
|
||||
reg = json.loads(json.dumps(S.specs_json()))
|
||||
assert reg["path"].endswith("settings.json")
|
||||
keys = [s["key"] for s in reg["specs"]]
|
||||
assert keys == [s.key for s in S.SPECS] and len(set(keys)) == len(keys)
|
||||
for s in reg["specs"]:
|
||||
for field in ("label", "group", "sub", "help", "default", "live", "saved", "quick", "impact", "experimental",
|
||||
"applies", "sources", "choices"):
|
||||
assert field in s, (s["key"], field)
|
||||
assert s["group"], s["key"] # every setting has a section
|
||||
values = [c["value"] for c in s["choices"]]
|
||||
assert s["default"] in values, s["key"]
|
||||
if s["applies"]: # what it depends on is a setting, and the values are that setting's
|
||||
dep = S.BY_KEY[s["applies"]["key"]]
|
||||
assert all(dep.accepts(v) for v in s["applies"]["values"]), s["key"]
|
||||
|
||||
|
||||
def test_sub_headings_follow_the_layout():
|
||||
by = {s["key"]: s for s in S.specs_json()["specs"]}
|
||||
assert (by["hz"]["group"], by["hz"]["sub"]) == ("Frame generation", "Basics")
|
||||
assert (by["output_res"]["group"], by["output_res"]["sub"]) == ("Upscaling", "Output")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text,want", [
|
||||
("interp=false", ("interp", False)), ("hz=90", ("hz", 90)), ("hz=210", ("hz", 210)),
|
||||
("scaler=vsr", ("scaler", "vsr")), ('scaler="fsr"', ("scaler", "fsr")), ("fsr_sharpness=1", ("fsr_sharpness", 1.0)),
|
||||
("overlay_scale=1.25", ("overlay_scale", 1.25)), ("output_res=2560x1080", ("output_res", "2560x1080")),
|
||||
("game_fps=60", ("game_fps", "60")), ('game_fps="60"', ("game_fps", "60")),
|
||||
("overlay_style=graphs", ("overlay_style", "graphs")), ("replay=0", ("replay", 0)),
|
||||
])
|
||||
def test_parse_set_takes_json_values_and_bare_words(text, want):
|
||||
assert S.parse_set(text) == want
|
||||
assert type(S.parse_set(text)[1]) is type(want[1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["nonsense=1", "hz", "hz=45", "interp=1", "vsr_quality=true", "scaler=dlss", "=1",
|
||||
"fill=[1]"])
|
||||
def test_parse_set_refuses_what_the_setting_does_not_accept(text):
|
||||
with pytest.raises(ValueError):
|
||||
S.parse_set(text)
|
||||
|
||||
|
||||
def test_every_choice_of_every_setting_goes_through_parse_set():
|
||||
for spec in S.SPECS:
|
||||
for v in spec.choices:
|
||||
assert S.parse_set(f"{spec.key}={json.dumps(v)}") == (spec.key, v)
|
||||