Launcher: splash intro, new icon set, consoles, Lutris, Steam accounts, overlay

- Splash: Summit's icon rises in over an amber glow, the name follows, then it
  fades into the app (about a second, no keys taken, off when motion is off)
- install.sh: after installing icons, rebuild KDE's sycoca and send
  KIconLoader.iconChanged so a running Plasma shows the updated icon
- New app icon (SVG + rendered PNG sizes, render.sh), used by the packages and
  the engine's window
- Lutris scan, consoles (Remote Play via chiaki-ng frame tap, capture cards),
  Steam account switching, running-game tracking, window mode, artwork
- Library UI: add dialog, profile editor, accounts, "now playing" screen
- Engine: in-game overlay/HUD, overlay key, global key fixes

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
ZebraticandClaude Opus 5.5 committed 2026-11-25 01:53:49 +01:00
1 parent 7a147ec4c6
commit 7dc52a4a2e
89 files changed
+7934 -983

No files matched your search

Generated
+72 -2
View File
@@ -1091,6 +1091,18 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -1187,6 +1199,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -1577,6 +1595,15 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash 0.1.5",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -1585,7 +1612,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -1594,7 +1621,16 @@ version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
dependencies = [
"foldhash",
"foldhash 0.2.0",
]
[[package]]
name = "hashlink"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
dependencies = [
"hashbrown 0.15.5",
]
[[package]]
@@ -2408,6 +2444,17 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "libsqlite3-sys"
version = "0.35.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "libudev-sys"
version = "0.1.4"
@@ -3616,6 +3663,20 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "rusqlite"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
dependencies = [
"bitflags 2.13.2",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3928,6 +3989,7 @@ dependencies = [
"const-field-offset",
"i-slint-backend-linuxkms",
"i-slint-backend-selector",
"i-slint-backend-winit",
"i-slint-common",
"i-slint-core",
"i-slint-core-macros",
@@ -4203,10 +4265,12 @@ dependencies = [
"anyhow",
"dirs",
"libc",
"rusqlite",
"serde",
"serde_json",
"toml 0.8.23",
"ureq",
"zbus",
]
[[package]]
@@ -4773,6 +4837,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
+72 -13
View File
@@ -80,28 +80,34 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
| Layouts (Big picture, Grid, List) and six themes | **Working** | All three layouts and five of the six themes captured live from a saved `ui.toml`; Midnight is the default one. |
| Play from the launcher with Enhance | **Working** (X11 and KDE Wayland) | Voidrunner: Enhance toggled on with the keyboard, Play pressed: the launcher ran `summit run custom:voidrunner --enhance`, the game and the engine started. Both stopped when the game was killed, and the screen mode was unchanged afterwards. On KDE Wayland: Play on Voidrunner's page did the same (the launcher used to refuse Enhance there). If the engine can't capture (no window found, the share dialog cancelled), the game now goes on without it. |
| Live enhance (`--enhance`): RIFE frame generation + FSR upscaling on a running game's window | **Working on X11 and KDE Wayland** | **KDE Plasma 6.8 Wayland, RTX 5080**: Voidrunner (an XWayland game) read through XWayland, the picture over it on a chosen monitor at 60 fps, FSR draw 0.06 ms, 21 to 38 ms from a frame reaching the engine to the screen; the game kept the keyboard, also in its own fullscreen mode. Native Wayland windows through the ScreenCast portal and PipeWire: run with a test window only (the share dialog once, then restored for new windows with no dialog; about 50 frames a second, CPU copy). Other Wayland desktops untested. **X11**: The engine's picture covered the 1080p screen with the 1280x720 game window under it, the game kept the keyboard. **Slow on that machine**: output 32 to 40 fps while the game drew 52 to 58, because software OpenGL takes about 15 ms to draw a 1080p frame; delay 65 to 97 ms. Not measured on a GPU-driven display. |
| In-game overlay with the Summit watermark | **Working** | Stats line (top left) and `summit - git.molberg.cloud/alex/summit` (bottom left) are on screen in the engine's window. `--no-watermark` turns the watermark off (earlier check). Not drawn into saved clips. |
| In-game overlay (Insert): upscaling, frame generation and performance settings over the game | **Working on X11; not yet tried with a real game on KDE Wayland** | Run for real in a private X server with a stand-in game window that logs its input: with the overlay closed the game got every key (Esc included) and Summit kept running; with it open, Insert, the arrows, Tab, Esc and clicks went to the overlay and the game got none; when it closed, the game had its keys and clicks back. Stop Summit (asked twice) ended the engine. See [The in-game overlay](#the-in-game-overlay). Not checked: a real game through XWayland on a Wayland session, a native Wayland game (no key there), Windows. |
| Stats and the Summit watermark over the picture | **Working** | The stats (top left: Minimal, Detailed or Graphs) and `summit - git.molberg.cloud/alex/summit` (bottom left) are on screen in the engine's window. `--no-watermark` turns the watermark off (earlier check). Not drawn into saved clips. |
| Instant replay clips: global save key (Ctrl+Alt+R), clip lengths from Settings | **Working on X11 and KDE Wayland** | **KDE Wayland**: Ctrl+Alt+R through the GlobalShortcuts portal saved clips while the game had the keys (needs the installed `summit.desktop`, which gives Summit an app id; without it, an X11 key grab through XWayland works while an XWayland game has the keys, also run). **X11**: Buffer 60 s, clip 30 s: Ctrl+Alt+R during play saved a 30.1 s H.264 1280x720 MP4 that ffprobe reads and ffmpeg decodes. **This run found a bug and fixed it**: the global key used to save the whole buffer (60 s) and ignore the configured clip length. |
| `install.sh` | **Working (one machine)** / dry-run elsewhere | Real run into a scratch prefix (`SUMMIT_PREFIX`) on an Ubuntu 24.04 machine, with the checkout supplied through `SUMMIT_SRC_DIR` instead of the clone: built, copied the two binaries and the engine, made the venv; `import torch` there gave 2.11.0+cu128. **This run found a bug and fixed it**: with an NVIDIA GPU the venv got PyPI's torch 2.15+cu132 (CUDA 13.2; the test machine's driver stops at 13.0) and the cu128 step did nothing; torch is now installed from the cu128 index first. Not run on the neon test machine itself, not as a non-root user, not into `/usr/local`, and the engine on the test machine ran from its existing venv. Other distros: `--dry-run` only. |
| Steam scan (all library folders, installed or not), Steam playtime, "most played" | **Tested** | Sample libraries, including the demo one above. Not run against a real Steam install in this run. |
| Heroic (Epic, GOG) and Lutris detection | **Tested** | Sample files only. |
| Steam scan (all library folders, installed or not), Steam playtime, "most played" | **Working** (owner's desktop) / **Tested** | Run against the owner's real Steam install (2026-11-24; Arch, 32 games over three library folders, eight accounts): every game gets a cover. Newer Steam clients cache the covers as `library_capsule.jpg` and `library_header.jpg` (in hash folders), which Summit missed before; it now reads those, and art you set yourself in Steam (`userdata/<user>/config/grid`) comes first. |
| Non-Steam games added to Steam | **Working** (owner's desktop, scan and covers) | Read from every local account's `shortcuts.vdf` (hidden ones and Summit's own `steam-add` shortcuts left out), with their grid art, including animated WebP saved as `.png`. A game also listed by Lutris or added to Summit by hand shows once, as that entry. Play hands it to Steam (`steam://rungameid/<id>`); no Enhance. Not launched in this run. Fixed on the way: Summit's `shortcuts.vdf` reader rejected the byte Steam ends the file with, so `summit steam-add` failed on any account that already had shortcuts. |
| Lutris detection | **Working** (owner's desktop, scan and covers) | Read from Lutris's database (`pga.db`; the per-game YAML has no slug or runner in current Lutris, so the old reader found nothing): all 20 installed games on the owner's desktop, with Lutris's playtime, its cover art and the executable (for the Unfiltered reasons). Hidden games and Lutris's own Steam entries are left out. Play runs `lutris lutris:rungameid/<id>`; not launched in this run. |
| Heroic (Epic, GOG) detection | **Tested** | Sample files only. |
| A reason for every detected entry (Unfiltered); heuristic detection; Windows `.exe` outside a Wine prefix listed as Software | **Tested** | The Unfiltered screenshot shows the reasons for the demo library's Steam entries on the real window. Heuristic and `.exe` detection: unit tests and sample folders, not a real disk full of games. |
| Hours played: Steam's own for Steam games, Summit-tracked sessions for everything else | **Tested** | Unit tests and the demo library; Summit's own tracker ran with Voidrunner earlier. `state.json` is now changed under a file lock, so the launcher and `summit run` saving at once both keep their change (checked: 2 x 40 parallel `summit pin`). |
| Add a game from the launcher (Library > **+ Add a game**, or **ADD** on a folder found on disk) | **Tested** | New since the RC run: the desktop's file dialog picks the file that starts the game, a second dialog asks for its name (guessed from the folder, skipping `bin`, `x86_64` and the like), the library reloads and the game's page opens. Checked on Xvfb with a stand-in zenity, both ways in; not on a real desktop or with kdialog. |
| Hours played: Steam's own for Steam games, Lutris's own for Lutris games, Summit-tracked sessions for everything else | **Tested** | Unit tests and the demo library; Summit's own tracker ran with Voidrunner earlier. `state.json` is now changed under a file lock, so the launcher and `summit run` saving at once both keep their change (checked: 2 x 40 parallel `summit pin`). |
| Add a game from the launcher (Library > **+ Add a game or console** > A game on this PC, or **ADD** on a folder found on disk) | **Tested** | New since the RC run: the desktop's file dialog picks the file that starts the game, a second dialog asks for its name (guessed from the folder, skipping `bin`, `x86_64` and the like), the library reloads and the game's page opens. Checked on Xvfb with a stand-in zenity, both ways in; not on a real desktop or with kdialog. |
| `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, PipeWire and GStreamer's `pipewiresrc`, KWin, the monitor tool and the GPU. Run on the KDE Wayland desktop (all ok, torch 2.11+cu128 on the RTX 5080) 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. Focus is stored only (raising the game window is not built). |
| 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**. |
| 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. |
| 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). |
| 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). |
| RTX Video Super Resolution (`rtx-vsr`) | **Experimental** | Wired to the engine, not tested. |
| 90/120 Hz output, choosing a monitor by name | **Experimental** | Wired, one virtual display only. |
| PS5 Remote Play and capture cards | **Experimental** | Wired as `ps5` / `capture:<name>` sources, no hardware. |
| Consoles in the library: PlayStation Remote Play (chiaki-ng with SmoovPlay's frame tap) and capture cards | **Tested** / **Experimental** | New: **+ Add a game or console** opens an in-app chooser: a game on this PC (the file dialog, as before), a capture card (the V4L2 devices, cards before webcams) or PlayStation Remote Play (the consoles linked in chiaki-ng, each one's state from a live network search). The pick becomes a library entry with its own page, profile, Enhance toggle and tracked time. Play on Remote Play finds the console by name, wakes it from rest mode and runs chiaki-ng; with Enhance the engine starts first and chiaki-ng gets `CHIAKI_FRAMETAP=1` (see [packaging/chiaki-ng](packaging/chiaki-ng/README.md), which also has the patch and the PKGBUILD; `install.sh --with-remote-play` builds it). A capture card plays through the engine. **Checked on the owner's desktop**: `summit console list` read two consoles linked in chiaki-ng, found one of them in rest mode on the network (at a different address than chiaki-ng had saved), found the Live Gamer MINI and a webcam, and saw the frame tap in the installed `chiaki`. Unit tests cover chiaki-ng's settings file, the discovery and wake-up packets, the stream command and the launch plans. **Not run**: a stream started from Summit, the wake-up, a capture card session. |
| Wayland on GNOME, sway, Hyprland; a real native Wayland game; fractional scaling | **Experimental** | Written for any desktop with the ScreenCast portal, run only on KDE Plasma at scale 1 with a native test window. Without KWin the engine can't tell which native window is the game (the share dialog picks it) or where it is (the picture covers the `--monitor` screen). |
| `.deb` (`packaging/deb/build.sh`) | **Tested** | Builds, contents checked with `dpkg-deb`; never installed. |
| AUR PKGBUILD, AppImage | **Experimental** | Not built or run. |
| One-click "Add to Steam" with SteamGridDB artwork, "My PS5" / "Capture Card" entries, lsfg-vk, DLSS, Flatpak | **Planned** | |
| One-click "Add to Steam" with SteamGridDB artwork, lsfg-vk, DLSS, Flatpak | **Planned** | |
## Clips
@@ -126,6 +132,10 @@ A game's page has Play, an **Enhance** toggle and **Profile**. With Enhance on,
| ![The launch profile editor listing the monitor's real modes](docs/media/live/gui-profile-editor.png) | ![Voidrunner running with RIFE and FSR after Play](docs/media/live/gui-play-enhanced.png) |
| Profile editor: monitor, resolution and refresh from xrandr | After Play: RIFE + FSR on the game's 720p window, full screen |
### Steam accounts
When Steam remembers more than one account on this PC, a Steam game's page shows a **Steam account** card (avatar, display name and login name). **Change** picks the account the game is played on; **Automatic** (the default) is the account it was last played on, read from each account's `localconfig.vdf`. On Play, `summit run` checks which account Steam is on. If it is another one, Summit closes Steam (`steam -shutdown`), sets `AutoLoginUser` in `~/.steam/registry.vdf`, marks the account as the most recent one in `config/loginusers.vdf` (both files are copied to `*.summit-backup` first), and Steam starts again signed in as that account, with the game. The choice is stored in `~/.local/share/summit/state.json` under `steam_accounts`. An account without a saved sign-in ("Remember me" off) makes Steam ask for its password.
## Try the CLI
```sh
@@ -136,11 +146,18 @@ cargo build --release
./target/release/summit home # most played
./target/release/summit run my-game -- ./game.sh # applies the profile, runs it, tracks the time
./target/release/summit add "My Game" ~/Games/mygame/run.sh # add anything by hand (--software for apps)
./target/release/summit console list # consoles linked in chiaki-ng (and which answer), capture devices
./target/release/summit console add-remote-play PS5-829 # PlayStation Remote Play to a linked console
./target/release/summit console add-capture "Live Gamer MINI" # a capture card
./target/release/summit pin steam:620 # show on Home
./target/release/summit art steam:620 cover.png # custom artwork
./target/release/summit doctor # what is missing for Enhance, profiles, clips, artwork
./target/release/summit doctor my-game # also: the display commands this game's profile would run
./target/release/summit profile set my-game --monitor HDMI-A-1 --width 3840 --height 2160 --refresh 60 --fullscreen true --focus true
./target/release/summit profile set default --upscaler fsr --window-mode borderless --env MANGOHUD=1 # what every game uses
./target/release/summit profile set my-game --monitor HDMI-A-1 --width 3840 --height 2160 --refresh 60 --window-mode fullscreen --focus true
./target/release/summit profile set my-game --args '-windowed -dx11' --env DXVK_HUD=fps
./target/release/summit profile show my-game # what it launches with, and which settings are its own
./target/release/summit profile reset my-game upscaler # follow the defaults again (no names: everything)
```
## Frame generation and upscaling
@@ -161,11 +178,25 @@ The engine needs an NVIDIA GPU and its own Python environment (`engine/`, torch
```sh
summit add Voidrunner ~/Games/Voidrunner/top_down_shooter
summit profile set custom:voidrunner --framegen rife --upscaler fsr --fullscreen true --target-hz 60
summit profile set custom:voidrunner --framegen rife --upscaler fsr --window-mode borderless --target-hz 60
summit run custom:voidrunner --enhance # start the game and enhance its window, live
summit enhance window:Voidrunner # or: enhance a game that is already running, by window title
```
### Launch profiles: defaults and per-game overrides
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') |
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"`.
`summit run <id> --enhance` starts the game, waits for its window (up to `--wait` seconds), starts the engine on it with the game's profile (monitor, fullscreen, upscaler, frame generation, model, `target_hz`), and stops both when either one exits. A window can also be named with `--window` (`class:NAME`, `pid:N`, `xid:N` or part of the title) for games whose window belongs to another process.
How it works on Wayland (run on KDE Plasma 6.8, see [docs/WAYLAND_REPORT.md](docs/WAYLAND_REPORT.md)): the engine looks for the game among XWayland windows and, on KDE, among KWin's own window list. An **XWayland** game (Proton, Wine and most older games) is read exactly as on X11, through XWayland, with no dialog. A **native Wayland** game goes through the desktop's ScreenCast portal: the desktop asks once which window to share, Summit keeps the permission (`~/.config/summit/screencast-token`) and later runs, also of a restarted game, start without asking. Its frames come over PipeWire through GStreamer (`gst-launch-1.0 pipewiresrc`, a CPU copy, about 18 % of one core at 1080p). In both cases the picture is an XWayland window that KWin keeps above the game, fullscreen games included, and that never takes the keyboard. `summit doctor` lists what is missing. Gamescope was tried (it runs and upscales with its own FSR on that desktop) but is not used: it has no frame generation.
@@ -192,7 +223,29 @@ What was measured, and what was not (test VM: RTX 3090 shared with another job,
- Fullscreen with FSR to 1080p: only about 33 output frames a second, because software OpenGL takes 15 ms to draw each one. **On that VM fullscreen is slower than the game itself.** With a real GPU-driven display this step is expected to take well under a millisecond, but that has not been measured.
- Not tested: a real 30 fps game (Voidrunner ran at about 50), 90/120 Hz output, two monitors and `--monitor`, a compositor with direct scanout, games started through Steam or Proton, exclusive-fullscreen games, mouse-driven games in fullscreen mode (clicks go through to whatever is under the pointer, and the picture is scaled, so the pointer does not line up).
Limits: needs the `ffmpeg` program. The grab polls, so it does not know when the game draws: a 60 fps game can show an occasional repeated or skipped frame. While the picture sits over a game the engine has no keys of its own (they all go to the game): close the game to stop. SIGTERM, SIGINT or SIGHUP to `summit` itself stops the game and the engine and puts the monitor's mode back (exit code 128 + the signal; SIGKILL cannot be caught). Checked with stand-in processes; the mode restore after a signal has not been tried on a real display yet. `SUMMIT_ENGINE_ARGS` passes extra flags to the engine, e.g. `SUMMIT_ENGINE_ARGS=--no-graph` on a GPU short of memory.
Limits: needs the `ffmpeg` program. The grab polls, so it does not know when the game draws: a 60 fps game can show an occasional repeated or skipped frame. While the picture sits over a game, the game has every key but one: the overlay's (Insert by default, see [The in-game overlay](#the-in-game-overlay)). Esc is the game's and never stops Summit; close the game, or pick Stop Summit in the overlay. SIGTERM, SIGINT or SIGHUP to `summit` itself stops the game and the engine and puts the monitor's mode back (exit code 128 + the signal; SIGKILL cannot be caught). Checked with stand-in processes; the mode restore after a signal has not been tried on a real display yet. `SUMMIT_ENGINE_ARGS` passes extra flags to the engine, e.g. `SUMMIT_ENGINE_ARGS=--no-graph` on a GPU short of memory.
## The in-game overlay
<p align="center">
<img src="docs/media/overlay.png" width="100%" alt="Summit's overlay open on the right of a stand-in game: tabs Home, Smoothness, Picture, Looks, Display, Clips and Remote Play, rows with switches and choices for frame generation and the output frame rate, a help card for the highlighted row, the keys along the bottom, and the performance pill in the top left corner">
</p>
Press **Insert** while you play. The overlay opens over the game with the engine's settings: frame generation and the output frame rate, the upscaler and its quality, looks, the performance overlay (off, a small line, details, or graphs like MangoHud's), clips, and Stop Summit. Changes apply as you make them; the ones that need it offer Restart now.
| Key | Mouse | Does |
|---|---|---|
| Insert | | Open or close the overlay (the key is yours to pick, below) |
| Up, Down | wheel, hover | Pick a row. Up from the first row goes to the tabs |
| Left, Right, Enter | click a choice or an arrow; right-click a row for the choice before | Change the value |
| Tab, Shift+Tab, Page Up/Down | click a tab | Next, previous tab |
| Esc, Backspace | click outside, or the cross | Close the overlay |
- **Esc never closes Summit or the game.** It only closes the overlay while that is open; the rest of the time it goes to the game, as every other key does. To stop, pick Quit (Stop Summit over a game) on the overlay's Home tab and press Enter twice, or close the game.
- **The game keeps its keys.** Over a PC game Summit takes one key, the overlay's, with an X key grab (on X11, and through XWayland on Wayland, where Proton and Wine games run). Only while the overlay is open are the keyboard and the mouse Summit's; if Summit's video loop ever stalls with the overlay open, the keyboard goes back to the game after two seconds by itself.
- **Pick the key** in the launcher: Settings > In-game overlay > Overlay key (Insert, Home, End, Pause, F9, F10). `overlay_key` in `~/.config/summit/ui.toml` takes others too (`"F12"`, `"Ctrl+Shift+O"`): a key that types nothing can stand alone, a letter or digit needs Ctrl, Alt or Super, and Esc, Enter, Backspace and the arrows are refused. If another program already holds the key, Summit says so over the picture.
- In the video window (Remote Play, a capture card), which has the keyboard to itself, M, Tab and a right-click open the overlay too, the one-letter keys still work (F fullscreen, S stats, U upscaler...), and Ctrl+Q quits.
- Limits: a native Wayland game window cannot be given a key this way (no X grab reaches it), so there the overlay does not open; a game that grabs the whole keyboard for itself (rare) keeps the overlay's key too, so the overlay does not open there; a game that locks the mouse keeps it, and the overlay is used with the keys.
## The launcher
@@ -206,9 +259,15 @@ Limits: needs the `ffmpeg` program. The grab polls, so it does not know when the
- **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, default upscaler and frame generation for `summit enhance`.
- **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`.
- 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.
- A controller reaches every program that reads it, whatever window is in front, which is how a pad in a game used to move the launcher behind it. Now the launcher listens to a pad only while its own window has the keyboard, and never while a game started from it runs. `SUMMIT_PAD_ALWAYS=1` brings the old behaviour back, should a desktop never report the launcher's window as focused.
- A game Summit starts itself (added by hand, a console) is followed as its own process. One that Steam, Lutris or Heroic starts is followed by its processes in `/proc` (Steam marks them with `SteamAppId`, Lutris with `LUTRIS_GAME_UUID`, Heroic with `HEROIC_APP_NAME`). If none turns up within two minutes the launcher comes back and says so.
- To get the launcher back while the game still runs: switch to its window and press Esc or click Back to the launcher (on a pad, hold B for a second). Stop the game is there for games Summit started itself.
| Key | Controller | Does |
|---|---|---|
| Arrows | d-pad, left stick | Move focus |
+380 -32
View File
@@ -1,6 +1,6 @@
use anyhow::Result;
use clap::{Parser, Subcommand};
use summit_core::{display, doctor, engine, model::Entry, profile, scan, signals, state};
use summit_core::{console, display, doctor, engine, model::Entry, profile, scan, signals, state};
#[derive(Parser)]
#[command(name = "summit", version, about = "One launcher for every game and app on Linux")]
@@ -35,6 +35,9 @@ enum Cmd {
/// 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,
/// Give the game's window the keyboard once it opens, whatever its profile says (the launcher's Play
/// does this: it steps aside for the game). KDE Plasma, and X11 desktops with wmctrl.
#[arg(long)] focus: bool,
/// The game's name, for the clips folder (Videos/Summit/<title>). Default: the title it was added
/// with (`summit add`), else the id.
#[arg(long)] title: Option<String>,
@@ -70,6 +73,8 @@ enum Cmd {
},
/// Per-game profile
Profile { #[command(subcommand)] cmd: ProfileCmd },
/// Consoles in the library: PlayStation Remote Play (through chiaki-ng with SmoovPlay's frame tap) and capture cards
Console { #[command(subcommand)] cmd: ConsoleCmd },
/// Add a non-Steam shortcut (from ~/.config/summit/ui.toml `[[shortcuts]]`, default: "ps5", "capture")
SteamAdd {
id: String,
@@ -86,27 +91,80 @@ enum Cmd {
},
}
#[derive(Subcommand)]
enum ConsoleCmd {
/// What can be added: the consoles chiaki-ng has registered (and whether they answer now), the capture devices,
/// and the console entries already in the library
List,
/// Add PlayStation Remote Play to a console registered in chiaki-ng, by its nickname
AddRemotePlay { nickname: String, #[arg(long)] title: Option<String> },
/// Add a capture card, by the name `summit console list` shows (or a /dev/videoN path)
AddCapture { device: String, #[arg(long)] title: Option<String> },
/// Remove a console entry (its playtime and pin stay, for when it is added again)
Remove { id: String },
}
/// Profiles are layered: `default` holds the launcher's defaults, a game's own profile only what it changes.
#[derive(Subcommand)]
enum ProfileCmd {
Show { id: String },
/// What the entry launches with (the defaults with its own settings on top); `--own`: only its own settings
Show { id: String, #[arg(long)] own: bool },
/// Change settings. Use the id `default` for the launcher's defaults, which every game follows until it sets
/// its own value. An empty text value ("") or 0 means "not chosen" (e.g. `--monitor ""`: never switch monitors).
Set {
id: String,
/// Output name (e.g. DP-1, HDMI-A-1); "" = do not switch
#[arg(long)] monitor: Option<String>,
#[arg(long)] width: Option<u32>,
#[arg(long)] height: Option<u32>,
#[arg(long)] refresh: Option<f32>,
#[arg(long)] fullscreen: Option<bool>,
/// "" (leave the game's choice), windowed, borderless or fullscreen
#[arg(long)] window_mode: Option<String>,
/// Older spelling: true is --window-mode borderless, false is --window-mode ""
#[arg(long, hide = true)] fullscreen: Option<bool>,
/// Raise and focus the game's window once it opens
#[arg(long)] focus: Option<bool>,
/// Play from the launcher also runs the engine on the game's window
#[arg(long)] enhance: Option<bool>,
/// "" (engine setting), none, fsr, rtx-vsr or bilinear
#[arg(long)] upscaler: Option<String>,
/// FSR sharpening: 0 (max), 0.25, 0.5, 1 or 2 (minimal)
#[arg(long)] fsr_sharpness: Option<f32>,
/// RTX VSR quality: 1 (low) to 4 (ultra)
#[arg(long)] vsr_quality: Option<u8>,
/// "" (engine default), none or rife
#[arg(long)] framegen: Option<String>,
#[arg(long)] multiplier: Option<u8>,
/// Engine output rate: 60, 90 or 120
#[arg(long)] target_hz: Option<u32>,
/// RIFE model for the engine, e.g. 4.22.lite
/// Interpolation model: 4.22.lite, 4.25.lite, 4.25, 4.26 or vfg ("" = the engine's setting)
#[arg(long)] model: Option<String>,
/// Play from the launcher also runs the engine on the game's window
#[arg(long)] enhance: Option<bool>,
/// NVIDIA VFG quality: low, medium or high
#[arg(long)] vfg_quality: Option<String>,
/// RIFE motion detail: full or half ("" = auto)
#[arg(long)] motion: Option<String>,
/// auto, trt or torch
#[arg(long)] ai_engine: Option<String>,
#[arg(long)] steady_hud: Option<bool>,
/// fit, zoom, stretch or panorama
#[arg(long)] fill: Option<String>,
#[arg(long)] vsync: Option<bool>,
#[arg(long)] watermark: Option<bool>,
/// Launch arguments added after the game's command, as one line (quotes group words)
#[arg(long, allow_hyphen_values = true)] args: Option<String>,
/// An environment variable for the game, KEY=VALUE (repeat for more)
#[arg(long = "env", value_name = "KEY=VALUE")] env: Vec<String>,
/// Remove one of this profile's environment variables
#[arg(long = "unset-env", value_name = "KEY")] unset_env: Vec<String>,
},
/// Forget settings, so the defaults decide again: the ones named (e.g. `upscaler window_mode`), or all of them
Reset { id: String, keys: Vec<String> },
}
/// `value` if it is one of `allowed` (or "" when `empty_ok`), else an error naming the choices.
fn pick(flag: &str, value: String, allowed: &[&str], empty_ok: bool) -> Result<String> {
if (empty_ok && value.is_empty()) || allowed.contains(&value.as_str()) { return Ok(value); }
anyhow::bail!("--{flag} is one of: {}{}", allowed.iter().filter(|a| !a.is_empty()).copied().collect::<Vec<_>>().join(", "), if empty_ok { " (or \"\")" } else { "" })
}
/// Runs its closure when dropped. `summit run` puts the display mode back with it, so an error on the way (the game
@@ -177,18 +235,20 @@ fn main() -> Result<()> {
if let Some(o) = &out { state::path_text(o)?; }
let p = profile::load(&profile)?;
let mut args = engine::plan(&eng, &src, &p, out.is_none(), out.as_deref(), max_ticks);
if out.is_none() { if let Some(w) = p.watermark { args.extend(["--watermark".to_string(), if w { "on" } else { "off" }.to_string()]); } }
// Instant replay only exists while playing on screen. Lengths come from the launcher's settings page;
// without a ui.toml the engine keeps whatever it has stored itself.
if out.is_none() && summit_core::ui::path().is_ok_and(|p| p.exists()) {
let ui = summit_core::ui::load();
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
args.extend(engine::overlay_args(&ui.overlay_key));
}
if out.is_none() && no_watermark { args.extend(["--watermark".to_string(), "off".to_string()]); }
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
let py = engine::python(&eng);
println!("{} {}", py.display(), args.join(" "));
if !dry_run {
let st = std::process::Command::new(&py).args(&args).env("SMOOVPLAY_TITLE", "Summit").status()?;
let st = std::process::Command::new(&py).args(&args).envs(engine::engine_env(&p)).env("SMOOVPLAY_TITLE", "Summit").status()?;
anyhow::ensure!(st.success(), "engine exited with {st}");
}
}
@@ -221,22 +281,38 @@ 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, title, mut cmd } => {
Cmd::Run { id, enhance, window, wait, no_watermark, detached, focus, title, mut cmd } => {
// From here on a signal to summit stops the game and the engine and puts the display mode back.
signals::install();
let custom = state::load().custom.into_iter().find(|c| c.id == id);
let st = state::load();
let custom = st.custom.iter().find(|c| c.id == id).cloned();
let console = st.consoles.iter().find(|c| c.id == id).cloned();
if cmd.is_empty() { // an entry added with `summit add` knows its own path
if let Some(c) = &custom { cmd = vec![c.path.clone()]; }
}
let title = title.or(custom.map(|c| c.title)).unwrap_or_else(|| id.clone());
let title = title.or(custom.map(|c| c.title)).or(console.as_ref().map(|c| c.title.clone())).unwrap_or_else(|| id.clone());
let mut p = profile::load(&id)?;
if focus { p.focus = true; }
// A console: what to start comes from its entry (console_command), not from after `--`.
let mut enhance = enhance;
let mut remote_play = false;
if let Some(c) = &console {
anyhow::ensure!(cmd.is_empty(), "{id} is a console: summit run starts it by itself, without a command after --");
let (argv, rp) = console_command(c, &mut p, enhance, no_watermark, &title)?;
cmd = argv;
remote_play = rp;
// A capture card's command is the engine itself (Enhance only changes its settings).
if !remote_play { enhance = false; }
}
anyhow::ensure!(!cmd.is_empty(), "give the command after --, e.g. summit run my-game -- ./game.sh");
let p = profile::load(&id)?;
// A Steam game tied to an account (or last played on one) starts on it: Steam is switched first.
if id.starts_with("steam:") && cmd.iter().any(|a| a.starts_with("steam://rungameid/")) { steam_account_for(&id, &st)?; }
// Found before the game starts, so a missing engine never leaves a game running without it.
let eng = if enhance { Some(engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: set SUMMIT_ENGINE to the engine/ folder"))?) } else { None };
let (s, d) = (display::detect_session(), display::detect_desktop());
let outs = if p.monitor.is_some() { display::outputs(s, d) } else { Ok(vec![]) };
let plan = display::plan_for(s, d, &p, outs.as_deref().unwrap_or_default());
if plan.is_empty() && p.monitor.is_some() { err!("note: no display control for {s:?}/{d:?}; launching without mode change"); }
if plan.is_empty() && p.monitor.is_some() && (p.width.is_some() || p.refresh_hz.is_some()) { err!("note: no display control for {s:?}/{d:?}; launching without mode change"); }
// The mode in use now, to put back when the game is over. A detached game without the engine runs on
// after this command returns, so there is no "after" to restore in.
let restore = if plan.is_empty() || (detached && eng.is_none()) { None } else {
@@ -252,22 +328,71 @@ fn main() -> Result<()> {
let restore_guard = OnDrop(|| if let Some(r) = &restore { run_display(r); });
let start = std::time::Instant::now();
let mut child = std::process::Command::new(&cmd[0]);
child.args(&cmd[1..]).args(&p.launch_args).envs(display::launch_env(s, &p));
child.args(&cmd[1..]).envs(display::launch_env(s, &p));
// A profile's launch arguments are for a game; chiaki-ng takes the console's address as its last one.
if console.is_none() { child.args(&p.launch_args); }
if console.is_some() {
child.env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title).env("PYTHONUNBUFFERED", "1").envs(engine::engine_env(&p));
}
// Remote Play with Enhance: chiaki-ng copies every frame into the shared memory the engine reads.
if remote_play && enhance { child.env("CHIAKI_FRAMETAP", "1"); }
// A game given by its full path is started from its own folder: many look for their data there.
if let Some(dir) = std::path::Path::new(&cmd[0]).parent().filter(|d| d.is_absolute() && d.is_dir()) { child.current_dir(dir); }
let status = if let Some(eng) = eng {
let mut placer: Option<Placer> = None;
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 mut args = engine::plan(eng, &engine::Source::Ps5, &p, true, None, None);
args.extend(engine::live_args(&live));
if summit_core::ui::path().is_ok_and(|p| p.exists()) {
let ui = summit_core::ui::load();
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
args.extend(engine::overlay_args(&ui.overlay_key));
}
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
let py = engine::python(eng);
out!("{} {}", py.display(), args.join(" "));
let grace = std::time::Duration::from_secs(8);
let mut eng_proc = std::process::Command::new(&py).args(&args).envs(engine::engine_env(&p)).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title)
.env("PYTHONUNBUFFERED", "1").stdout(std::process::Stdio::piped()).spawn()
.map_err(|e| anyhow::anyhow!("could not start the engine ({}): {e}", py.display()))?;
let ready = forward_until(eng_proc.stdout.take(), &["[chiaki] waiting for chiaki-ng", "[chiaki] stream:"]);
let waited = std::time::Instant::now();
loop {
if ready.recv_timeout(std::time::Duration::from_millis(250)).is_ok() { break; }
if let Some(st) = eng_proc.try_wait()? { anyhow::bail!("the engine stopped before the stream started ({st}); its last lines above say why"); }
if signals::requested().is_some() { let _ = engine::stop(&mut eng_proc, grace); anyhow::bail!("stopped before the stream started"); }
if waited.elapsed() > std::time::Duration::from_secs(120) { err!("note: the engine did not say it is ready after 2 minutes; starting chiaki-ng anyway"); break; }
}
out!("starting chiaki-ng with the frame tap: {}", cmd.join(" "));
let mut game = match child.spawn() {
Ok(g) => g,
Err(e) => { let _ = engine::stop(&mut eng_proc, grace); anyhow::bail!("could not start {}: {e}", cmd[0]); }
};
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace, false, &|| signals::requested().is_some())?;
match who {
engine::Ended::Stopped => out!("{}: stopped the engine and chiaki-ng", signals::requested().map_or("asked to stop", signals::name)),
engine::Ended::Game => out!("the Remote Play stream ended; the engine was stopped"),
engine::Ended::Engine => out!("the engine exited ({}); chiaki-ng was stopped", eng_proc.wait()?),
engine::Ended::EngineFailed => out!("Enhance could not run ({}; the engine's last lines above say why): Remote Play went on in chiaki-ng's own window", eng_proc.wait()?),
}
status
} 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 mut args = engine::run_enhance_plan(&eng, game.id(), window.as_deref(), &p, &live);
if summit_core::ui::path().is_ok_and(|p| p.exists()) {
let ui = summit_core::ui::load();
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
args.extend(engine::overlay_args(&ui.overlay_key));
}
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
let py = engine::python(&eng);
out!("{} {}", py.display(), args.join(" "));
let grace = std::time::Duration::from_secs(8);
let mut eng_proc = match std::process::Command::new(&py).args(&args).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title).spawn() {
let mut eng_proc = match std::process::Command::new(&py).args(&args).envs(engine::engine_env(&p)).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title).spawn() {
Ok(c) => c,
Err(e) => { let _ = engine::stop(&mut game, grace); anyhow::bail!("could not start the engine ({}): {e}", py.display()); }
};
@@ -282,10 +407,13 @@ fn main() -> Result<()> {
status
} else {
let mut game = child.spawn().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))?;
if console.is_none() { placer = start_placer(s, d, &p, false, place_target(&id, window.as_deref(), game.id()), wait); }
let (status, stopped) = engine::wait_or_stop(&mut game, std::time::Duration::from_secs(8), &|| signals::requested().is_some())?;
if stopped { out!("{}: stopped the game", signals::requested().map_or("asked to stop", signals::name)); }
status
};
// A game handed to its own launcher opens its window after the command returned: keep looking for it.
if let Some(pl) = placer { pl.finish(detached && !enhance && signals::requested().is_none()); }
drop(restore_guard);
let secs = start.elapsed().as_secs();
if detached && !enhance {
@@ -300,24 +428,80 @@ fn main() -> Result<()> {
// A stop asked for by a signal ends like the signal would have (128 + its number), for process managers.
if let Some(sig) = signals::requested() { std::process::exit(128 + sig); }
}
Cmd::Profile { cmd: ProfileCmd::Show { id } } => {
print!("{}", toml::to_string_pretty(&profile::load(&id)?)?);
Cmd::Console { cmd } => console_cmd(cmd)?,
Cmd::Profile { cmd: ProfileCmd::Show { id, own } } => {
let layer = profile::load_layer(&id)?;
if own {
print!("{}", toml::to_string_pretty(&profile::Layer { version: None, ..layer })?);
} else {
print!("{}", toml::to_string_pretty(&profile::load(&id)?)?);
let set: Vec<&str> = profile::KEYS.iter().copied().filter(|k| layer.has(k)).collect();
if id != profile::DEFAULT_ID {
println!("# set by {id} itself: {}; the rest from the defaults ({})", if set.is_empty() { "nothing".to_string() } else { set.join(", ") }, profile::file(profile::DEFAULT_ID)?.display());
}
}
}
Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, fullscreen, focus, upscaler, framegen, multiplier, target_hz, model, enhance } } => {
let mut p = profile::load(&id)?;
if monitor.is_some() { p.monitor = monitor; }
if width.is_some() { p.width = width; }
if height.is_some() { p.height = height; }
if refresh.is_some() { p.refresh_hz = refresh; }
if let Some(v) = fullscreen { p.fullscreen = v; }
if let Some(v) = focus { p.focus = v; }
if let Some(v) = upscaler { p.upscaler = v; }
if let Some(v) = framegen { p.framegen = v; }
if let Some(v) = multiplier { p.framegen_multiplier = v; }
if let Some(v) = target_hz { anyhow::ensure!([60, 90, 120].contains(&v), "--target-hz is 60, 90 or 120"); p.target_hz = Some(v); }
if model.is_some() { p.model = model; }
if let Some(v) = enhance { p.enhance = v; }
println!("saved {}", profile::save(&id, &p)?.display());
Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, window_mode, fullscreen, focus, enhance, upscaler, fsr_sharpness, vsr_quality, framegen, multiplier, target_hz, model, vfg_quality, motion, ai_engine, steady_hud, fill, vsync, watermark, args, env, unset_env } } => {
use profile as pr;
let window_mode = match (window_mode, fullscreen) {
(Some(m), _) => Some(pick("window-mode", m, pr::WINDOW_MODES, true)?),
(None, Some(f)) => Some(if f { "borderless".to_string() } else { String::new() }),
(None, None) => None,
};
if let Some(v) = fsr_sharpness { anyhow::ensure!(pr::FSR_SHARPNESS.contains(&v), "--fsr-sharpness is 0, 0.25, 0.5, 1 or 2"); }
if let Some(v) = vsr_quality { anyhow::ensure!(pr::VSR_QUALITIES.contains(&v), "--vsr-quality is 1, 2, 3 or 4"); }
if let Some(v) = target_hz { anyhow::ensure!(v == 0 || pr::TARGET_HZ.contains(&v), "--target-hz is 60, 90 or 120 (0: the engine's setting)"); }
let upscaler = upscaler.map(|v| pick("upscaler", v, pr::UPSCALERS, true)).transpose()?;
let framegen = framegen.map(|v| pick("framegen", v, pr::FRAMEGENS, true)).transpose()?;
let model = model.map(|v| pick("model", v, pr::MODELS, true)).transpose()?;
let vfg_quality = vfg_quality.map(|v| pick("vfg-quality", v, pr::VFG_QUALITIES, true)).transpose()?;
let motion = motion.map(|v| pick("motion", v, pr::MOTIONS, true)).transpose()?;
let ai_engine = ai_engine.map(|v| pick("ai-engine", v, pr::AI_ENGINES, true)).transpose()?;
let fill = fill.map(|v| pick("fill", v, pr::FILLS, true)).transpose()?;
let env: Vec<(String, String)> = env.iter().map(|e| pr::parse_env(e)).collect::<Result<_, _>>().map_err(|e| anyhow::anyhow!("--env: {e}"))?;
let l = pr::update_layer(&id, |l| {
if let Some(m) = monitor {
// a new monitor brings its own mode: the old one's resolution is not kept
if l.monitor.as_deref() != Some(m.as_str()) { l.width = None; l.height = None; l.refresh_hz = None; }
l.monitor = Some(m);
}
if width.is_some() { l.width = width; }
if height.is_some() { l.height = height; }
if refresh.is_some() { l.refresh_hz = refresh; }
if window_mode.is_some() { l.window_mode = window_mode; }
if focus.is_some() { l.focus = focus; }
if enhance.is_some() { l.enhance = enhance; }
if upscaler.is_some() { l.upscaler = upscaler; }
if fsr_sharpness.is_some() { l.fsr_sharpness = fsr_sharpness; }
if vsr_quality.is_some() { l.vsr_quality = vsr_quality; }
if framegen.is_some() { l.framegen = framegen; }
if multiplier.is_some() { l.framegen_multiplier = multiplier; }
if target_hz.is_some() { l.target_hz = target_hz; }
if model.is_some() { l.model = model; }
if vfg_quality.is_some() { l.vfg_quality = vfg_quality; }
if motion.is_some() { l.motion = motion; }
if ai_engine.is_some() { l.ai_engine = ai_engine; }
if steady_hud.is_some() { l.steady_hud = steady_hud; }
if fill.is_some() { l.fill = fill; }
if vsync.is_some() { l.vsync = vsync; }
if watermark.is_some() { l.watermark = watermark; }
if let Some(a) = args { l.launch_args = Some(pr::split_args(&a)); }
if !env.is_empty() || !unset_env.is_empty() {
let mut m = l.env.take().unwrap_or_default();
for k in &unset_env { m.remove(k); }
m.extend(env);
l.env = if m.is_empty() { None } else { Some(m) };
}
})?;
println!("saved {}", pr::file(&id)?.display());
if l.is_empty() { println!("{id} sets nothing of its own: it follows the defaults"); }
}
Cmd::Profile { cmd: ProfileCmd::Reset { id, keys } } => {
if let Some(bad) = keys.iter().find(|k| !profile::KEYS.contains(&k.as_str())) {
anyhow::bail!("no setting called {bad}: one of {}", profile::KEYS.join(", "));
}
profile::update_layer(&id, |l| if keys.is_empty() { *l = profile::Layer::default(); } else { for k in &keys { l.unset(k); } })?;
println!("{id}: {} the defaults again", if keys.is_empty() { "everything follows".to_string() } else { format!("{} follow", keys.join(", ")) });
}
Cmd::SteamAdd { id, user, force } => {
let ui = summit_core::ui::load();
@@ -364,6 +548,170 @@ fn main() -> Result<()> {
Ok(())
}
/// Switch Steam to the account `id` starts on (steam_account.rs), if that is not the one it is on.
fn steam_account_for(id: &str, st: &state::State) -> Result<()> {
use summit_core::steam_account as sa;
let Some(root) = sa::root() else { return Ok(()) };
let accounts = sa::list_in(&root);
let last = sa::last_played_by(&root, &accounts);
let Some((acc, why)) = sa::target(id, st, &accounts, &last) else { return Ok(()) };
let why = match why { sa::Why::Chosen => "chosen for this game", sa::Why::LastPlayed => "last played on" };
match sa::switch_to(&root, &accounts, acc, &|m| out!("{m}"))? {
sa::Switched::AlreadyOn => out!("steam account: {} ({why}), already signed in", acc.label()),
sa::Switched::Switched => out!("steam account: switched to {} ({why})", acc.label()),
}
Ok(())
}
/// Which windows are the game's: `--window class:NAME` (or a Steam game's `steam_app_<id>`), else the process.
fn place_target(id: &str, window: Option<&str>, pid: u32) -> summit_core::winmode::Target {
use summit_core::winmode::Target;
if let Some(c) = window.and_then(|w| w.strip_prefix("class:")) { return Target::Class(c.to_string()); }
match id.strip_prefix("steam:").and_then(|n| n.parse::<u32>().ok()) {
Some(n) => Target::Class(format!("steam_app_{n}")),
None => Target::Pid(pid),
}
}
/// Places the game's window (monitor, window mode, focus) from a thread while the game runs (winmode.rs).
struct Placer { stop: std::sync::Arc<std::sync::atomic::AtomicBool>, thread: std::thread::JoinHandle<()> }
impl Placer {
/// `wait_for_it`: the command handed the game to another launcher and returned, so keep looking until the
/// window was placed or the time is up. Otherwise the game is over: stop looking.
fn finish(self, wait_for_it: bool) {
if !wait_for_it { self.stop.store(true, std::sync::atomic::Ordering::Relaxed); }
let _ = self.thread.join();
}
}
fn start_placer(s: display::Session, d: display::Desktop, p: &profile::Profile, enhance: bool, target: summit_core::winmode::Target, wait: u32) -> Option<Placer> {
use summit_core::winmode;
let want = winmode::wanted(p, enhance)?;
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = stop.clone();
let watch = winmode::Watch { wait: std::time::Duration::from_secs(u64::from(wait.max(30)) + 30), ..Default::default() };
let thread = std::thread::spawn(move || {
let should_stop = || flag.load(std::sync::atomic::Ordering::Relaxed) || signals::requested().is_some();
match winmode::place(s, d, &target, &want, watch, &should_stop, &mut |l| out!("{l}")) {
Ok(0) if !should_stop() => err!("note: the game's window did not turn up, so its monitor, window mode and focus were not set"),
Ok(_) => {}
Err(e) => err!("note: the game's window is left as it opens ({e})"),
}
});
Some(Placer { stop, thread })
}
/// What `summit run` starts for a console, and whether it is Remote Play (chiaki-ng; the engine goes first when
/// Enhance is on). A capture card's command is the engine on the card: frame generation and the upscaler from the
/// profile with Enhance, a plain picture without.
fn console_command(c: &console::Console, p: &mut profile::Profile, enhance: bool, no_watermark: bool, title: &str) -> Result<(Vec<String>, bool)> {
match &c.link {
console::Link::Capture { device } => {
let eng = engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: a capture card is shown by Summit's engine (run install.sh, or set SUMMIT_ENGINE)"))?;
let mut shown = p.clone();
if !enhance { shown.framegen = "none".into(); shown.upscaler = "none".into(); }
let mut args = engine::plan(&eng, &engine::Source::Capture(device.clone()), &shown, true, None, None);
if summit_core::ui::path().is_ok_and(|p| p.exists()) {
let ui = summit_core::ui::load();
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
args.extend(engine::overlay_args(&ui.overlay_key));
}
if no_watermark { args.extend(["--watermark".to_string(), "off".to_string()]); }
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
let mut v = vec![engine::python(&eng).to_string_lossy().into_owned()];
v.extend(args);
out!("{title}: {} through the engine{}", c.describe(), if enhance { ", with Enhance" } else { "" });
Ok((v, false))
}
console::Link::RemotePlay { nickname, ps5, host } => {
let chiaki = console::chiaki_binary().ok_or_else(|| anyhow::anyhow!(
"chiaki-ng is not installed: Remote Play needs it (with SmoovPlay's frame tap for Enhance). Run install.sh --with-remote-play, or build packaging/chiaki-ng"))?;
if enhance && !console::has_frame_tap(&chiaki) {
anyhow::bail!("{} is a chiaki-ng without SmoovPlay's frame tap, so Enhance can't read the stream: install chiaki-ng-smoovplay (install.sh --with-remote-play), or turn Enhance off", chiaki.display());
}
let reg = console::registered().into_iter().find(|r| &r.nickname == nickname);
anyhow::ensure!(reg.is_some(), "chiaki-ng has no console named {nickname}: open chiaki-ng and link it again (PS5: Settings > System > Remote Play > Link Device)");
let ip = console::reach(nickname, *ps5, host.as_deref(), reg.and_then(|r| r.credential()), &mut |l| out!("{l}"))
.map_err(|e| anyhow::anyhow!(e))?;
// Remember where it answered, for when discovery does not reach it next time.
let (id, ip_text) = (c.id.clone(), ip.to_string());
let _ = state::update(|st| if let Some(x) = st.consoles.iter_mut().find(|x| x.id == id) {
if let console::Link::RemotePlay { host, .. } = &mut x.link { *host = Some(ip_text.clone()); }
});
// With Enhance the engine's window is the one on screen (chiaki-ng's is minimised while it runs).
Ok((console::stream_argv(&chiaki, nickname, &ip.to_string(), p.fullscreen() && !enhance), true))
}
}
}
/// Copy a child's stdout to ours line by line (it goes to the launcher's log), and say on the channel when a line
/// starts with one of `marks`.
fn forward_until(out: Option<std::process::ChildStdout>, marks: &'static [&'static str]) -> std::sync::mpsc::Receiver<()> {
let (tx, rx) = std::sync::mpsc::channel();
if let Some(o) = out {
std::thread::spawn(move || {
use std::io::BufRead;
let mut told = false;
for line in std::io::BufReader::new(o).lines() {
let Ok(line) = line else { break };
out!("{line}");
if !told && marks.iter().any(|m| line.trim_start().starts_with(m)) { let _ = tx.send(()); told = true; }
}
});
}
rx
}
fn console_cmd(cmd: ConsoleCmd) -> Result<()> {
match cmd {
ConsoleCmd::List => {
let chiaki = console::chiaki_binary();
match &chiaki {
Some(c) if console::has_frame_tap(c) => println!("chiaki-ng: {} (with SmoovPlay's frame tap: Enhance works)", c.display()),
Some(c) => println!("chiaki-ng: {} (no frame tap: Remote Play works, Enhance doesn't)", c.display()),
None => println!("chiaki-ng: not installed (install.sh --with-remote-play)"),
}
let reg = console::registered();
let found = if reg.is_empty() { vec![] } else { console::discover(std::time::Duration::from_secs(3), &[]) };
println!("\nRemote Play, consoles registered in chiaki-ng:");
if reg.is_empty() { println!(" none: open chiaki-ng and link your console"); }
for r in &reg {
let now = match found.iter().find(|f| f.name == r.nickname) {
Some(f) if f.standby => format!("in rest mode at {}", f.ip),
Some(f) => format!("on, at {}", f.ip),
None => "not answering".into(),
};
println!(" {} ({}): {now}", r.nickname, if r.ps5 { "PS5" } else { "PS4" });
}
println!("\nCapture devices:");
let devs = console::capture_devices();
if devs.is_empty() { println!(" none (plugged in? in the video group?)"); }
for d in devs { println!(" {} ({}){}", d.name, d.path, if console::looks_like_webcam(&d.name) { " [webcam]" } else { "" }); }
let st = state::load();
println!("\nIn the library:");
if st.consoles.is_empty() { println!(" none"); }
for c in &st.consoles { println!(" {} {}: {}", c.id, c.title, c.describe()); }
}
ConsoleCmd::AddRemotePlay { nickname, title } => {
let reg = console::registered().into_iter().find(|r| r.nickname == nickname)
.ok_or_else(|| anyhow::anyhow!("chiaki-ng has no console named {nickname} (summit console list shows the ones it has)"))?;
println!("added {}", state::add_console(console::Console::remote_play(&reg.nickname, reg.ps5, title.as_deref()))?);
}
ConsoleCmd::AddCapture { device, title } => {
let known = console::capture_devices();
anyhow::ensure!(device.starts_with("/dev/") || known.iter().any(|d| d.name == device),
"no capture device named {device} (summit console list shows them)");
println!("added {}", state::add_console(console::Console::capture(&device, title.as_deref()))?);
}
ConsoleCmd::Remove { id } => {
anyhow::ensure!(state::remove_console(&id)?, "no console entry {id}");
println!("removed {id}");
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
+5
View File
@@ -12,3 +12,8 @@ toml.workspace = true
dirs.workspace = true
ureq = "2"
libc = "0.2"
# Lutris keeps its game list in an SQLite file (pga.db). Bundled, so no system libsqlite3 is needed.
rusqlite = { version = "0.37", features = ["bundled"] }
# Placing a game's window on KDE: a KWin script over D-Bus that reports back (winmode.rs). Already in the build
# through the GUI's window toolkit.
zbus = "5"
+37
View File
@@ -0,0 +1,37 @@
//! Where an entry's art comes from, by source, before any art the user set in Summit (`State::artwork`, which the
//! caller checks first):
//!
//! * Steam games: art set by hand in Steam (`userdata/<user>/config/grid`), then Steam's library cache.
//! * Non-Steam games in Steam: their grid art (`<appid>p.png`, `<appid>.png`, `_hero`, `_logo`); the cover falls
//! back to the wide image, then the hero.
//! * Lutris: its cover art, then its banner.
use crate::model::Entry;
use crate::shortcuts::ArtKind;
use crate::{lutris, shortcuts, steam};
use std::path::PathBuf;
/// The cover: portrait art preferred, else wide art (the GUI centres it on a soft copy of itself).
pub fn cover(e: &Entry) -> Option<PathBuf> {
if let Some(id) = e.steam_app_id {
return steam::grid_art(id, ArtKind::Portrait).or_else(|| steam::cover(id)).or_else(|| steam::grid_art(id, ArtKind::Wide));
}
if let Some(id) = shortcuts::appid_of(&e.id) {
return [ArtKind::Portrait, ArtKind::Wide, ArtKind::Hero].into_iter().find_map(|k| steam::grid_art(id, k));
}
if let Some(slug) = lutris::slug_of(&e.id) {
return lutris::cover(slug).or_else(|| lutris::banner(slug));
}
None
}
/// Wide background art for the Big Picture backdrop. None: the caller blurs the cover instead.
pub fn hero(e: &Entry) -> Option<PathBuf> {
if let Some(id) = e.steam_app_id { return steam::grid_art(id, ArtKind::Hero).or_else(|| steam::hero(id)); }
shortcuts::appid_of(&e.id).and_then(|id| steam::grid_art(id, ArtKind::Hero))
}
/// The title logo on a transparent background.
pub fn logo(e: &Entry) -> Option<PathBuf> {
if let Some(id) = e.steam_app_id { return steam::grid_art(id, ArtKind::Logo).or_else(|| steam::logo(id)); }
shortcuts::appid_of(&e.id).and_then(|id| steam::grid_art(id, ArtKind::Logo))
}
+516
View File
@@ -0,0 +1,516 @@
//! Consoles as library entries: PlayStation Remote Play through chiaki-ng (built with SmoovPlay's frame tap, see
//! `packaging/chiaki-ng/`) and capture cards. The launcher's **Add a game** offers both next to a game on this PC.
//!
//! * Remote Play: a console registered in chiaki-ng (its `Chiaki.conf`, `[registered_hosts]`), by its nickname.
//! At Play, Summit finds it on the network (the PlayStation discovery protocol, UDP 9302 for a PS5, 987 for a
//! PS4), wakes it from rest mode with the registration's credential, and starts
//! `chiaki --exit-app-on-stream-exit stream <nickname> <ip>`. With Enhance the engine starts first, waits on the
//! frame tap, and chiaki-ng gets `CHIAKI_FRAMETAP=1`: every compressed frame the console sends then also goes to
//! the engine (`engine/framegen/chiaki_tap.py`), which shows it with frame generation and the upscaler.
//! * Capture card: a V4L2 device, by the name its driver gives (as the engine names it, `capture_linux.py`). The
//! engine is the viewer, with frame generation and the upscaler only when Enhance is on.
use serde::{Deserialize, Serialize};
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
/// What a console entry plays.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Link {
/// PlayStation Remote Play to the console chiaki-ng knows by `nickname`. `host`: the address it last answered
/// from, tried when discovery finds nothing (another subnet, broadcasts blocked).
RemotePlay { nickname: String, #[serde(default)] ps5: bool, #[serde(default, skip_serializing_if = "Option::is_none")] host: Option<String> },
/// A capture card, by its V4L2 name ("Live Gamer MINI") or a /dev/videoN path.
Capture { device: String },
}
/// A console entry, stored in `state.json` (`consoles`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Console {
pub id: String,
pub title: String,
#[serde(flatten)]
pub link: Link,
}
fn slug(s: &str) -> String {
let mut out = String::new();
for c in s.trim().chars().flat_map(char::to_lowercase) {
if c.is_alphanumeric() { out.push(c) } else if !out.ends_with('-') { out.push('-') }
}
out.trim_matches('-').to_string()
}
impl Console {
/// A Remote Play entry: id `remoteplay:<nickname>`, titled after the console ("PlayStation 5").
pub fn remote_play(nickname: &str, ps5: bool, title: Option<&str>) -> Console {
let title = title.map(str::trim).filter(|t| !t.is_empty()).map(String::from)
.unwrap_or_else(|| if ps5 { "PlayStation 5".into() } else { "PlayStation 4".into() });
Console { id: format!("remoteplay:{}", slug(nickname)), title, link: Link::RemotePlay { nickname: nickname.into(), ps5, host: None } }
}
/// A capture card entry: id `capture:<device>`, titled "Capture Card" unless named.
pub fn capture(device: &str, title: Option<&str>) -> Console {
let title = title.map(str::trim).filter(|t| !t.is_empty()).map(String::from).unwrap_or_else(|| "Capture Card".into());
Console { id: format!("capture:{}", slug(device)), title, link: Link::Capture { device: device.into() } }
}
/// One line on what it is, for the entry's reasons and `summit console list`.
pub fn describe(&self) -> String {
match &self.link {
Link::RemotePlay { nickname, ps5, .. } => format!("{} \"{nickname}\" over PlayStation Remote Play (chiaki-ng)", if *ps5 { "PS5" } else { "PS4" }),
Link::Capture { device } => format!("capture card \"{device}\""),
}
}
pub fn entry(&self) -> crate::model::Entry {
use crate::model::*;
Entry {
id: self.id.clone(), title: self.title.clone(), source: Source::Console, kind: Kind::Game, installed: true,
path: None, steam_app_id: None, playtime_minutes: 0, last_played: None, launch_uri: None,
reasons: vec![format!("added by you: {}", self.describe())],
}
}
}
// ---- chiaki-ng ----
/// The `chiaki` program: $SUMMIT_CHIAKI, then `chiaki` / `chiaki-ng` on PATH, then one built by install.sh into
/// `<prefix>/share/summit/chiaki-ng/` next to the summit binary.
pub fn chiaki_binary() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("SUMMIT_CHIAKI").map(PathBuf::from).filter(|p| p.is_file()) { return Some(p); }
let path = std::env::var_os("PATH").unwrap_or_default();
for name in ["chiaki", "chiaki-ng"] {
if let Some(p) = std::env::split_paths(&path).map(|d| d.join(name)).find(|p| p.is_file()) { return Some(p); }
}
let exe = std::env::current_exe().ok()?;
let p = exe.parent()?.join("../share/summit/chiaki-ng/chiaki");
p.is_file().then(|| p.canonicalize().unwrap_or(p))
}
/// The frame tap's shared-memory name, compiled into a chiaki-ng built with SmoovPlay's patch (frametap.c).
const TAP_MARK: &[u8] = b"chiaki-frametap";
/// True when the chiaki binary at `path` carries the frame tap (its shared-memory name is in the binary).
pub fn has_frame_tap(path: &Path) -> bool {
use std::io::Read;
let Ok(mut f) = std::fs::File::open(path) else { return false };
let mut buf = vec![0u8; 1 << 20];
let mut carry: Vec<u8> = Vec::new();
loop {
let n = match f.read(&mut buf) { Ok(0) | Err(_) => return false, Ok(n) => n };
carry.extend_from_slice(&buf[..n]);
if carry.windows(TAP_MARK.len()).any(|w| w == TAP_MARK) { return true; }
let keep = carry.len().saturating_sub(TAP_MARK.len() - 1);
carry.drain(..keep);
}
}
/// Where chiaki-ng keeps its settings and registered consoles: the native build's, then the Flatpak's.
pub fn chiaki_conf_paths() -> Vec<PathBuf> {
let mut v = vec![];
if let Some(c) = dirs::config_dir() { v.push(c.join("Chiaki/Chiaki.conf")); }
if let Some(h) = dirs::home_dir() { v.push(h.join(".var/app/io.github.streetpea.Chiaki4deck/config/Chiaki/Chiaki.conf")); }
v
}
/// A console registered (linked) in chiaki-ng.
#[derive(Debug, Clone, PartialEq)]
pub struct Registered {
pub nickname: String,
pub ps5: bool,
/// The registration key as chiaki-ng stores it (hex text): its value is the credential that wakes the console.
pub regist_key: Option<String>,
}
impl Registered {
/// The `user-credential` a WAKEUP packet carries: the registration key read as a hex number (as chiaki-ng does).
pub fn credential(&self) -> Option<u64> {
let k = self.regist_key.as_deref()?;
if k.is_empty() || k.len() > 8 { return None; }
u64::from_str_radix(k, 16).ok()
}
}
/// A QSettings INI value as bytes: `@ByteArray(...)`, a quoted string, or plain text, with Qt's escapes
/// (`\0`, `\xHH` greedy over hex digits, `\n`, `\\`, `\"`...).
pub fn qt_value(raw: &str) -> Vec<u8> {
let mut s = raw.trim();
if let Some(inner) = s.strip_prefix("@ByteArray(").and_then(|r| r.strip_suffix(')')) { s = inner; }
else if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') { s = &s[1..s.len() - 1]; }
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] != b'\\' || i + 1 == b.len() { out.push(b[i]); i += 1; continue; }
i += 1;
match b[i] {
b'x' => {
let start = i + 1;
let mut j = start;
while j < b.len() && b[j].is_ascii_hexdigit() { j += 1; }
let v = u32::from_str_radix(std::str::from_utf8(&b[start..j]).unwrap_or("0"), 16).unwrap_or(0);
if v > 0xff { out.extend(char::from_u32(v).unwrap_or('?').to_string().as_bytes()); } else { out.push(v as u8); }
i = j;
}
d @ b'0'..=b'7' => {
let mut v = (d - b'0') as u32;
let mut j = i + 1;
while j < b.len() && j < i + 3 && (b'0'..=b'7').contains(&b[j]) { v = v * 8 + (b[j] - b'0') as u32; j += 1; }
out.push(v as u8);
i = j;
}
c => {
out.push(match c { b'n' => b'\n', b'r' => b'\r', b't' => b'\t', b'a' => 7, b'b' => 8, b'f' => 12, b'v' => 11, o => o });
i += 1;
}
}
}
out
}
/// The consoles in a chiaki-ng settings file's `[registered_hosts]`, in its order.
pub fn parse_registered(conf: &str) -> Vec<Registered> {
let mut in_section = false;
let mut rows: std::collections::BTreeMap<u32, (Option<String>, Option<i64>, Option<String>)> = Default::default();
for line in conf.lines() {
let line = line.trim();
if line.starts_with('[') { in_section = line == "[registered_hosts]"; continue; }
if !in_section { continue; }
let Some((key, value)) = line.split_once('=') else { continue };
// QSettings writes the array index and the field as `1\server_nickname`
let Some((n, field)) = key.trim().split_once('\\') else { continue };
let Ok(n) = n.parse::<u32>() else { continue };
let text = || String::from_utf8_lossy(&qt_value(value)).into_owned();
let row = rows.entry(n).or_default();
match field {
"server_nickname" => row.0 = Some(text()),
"target" => row.1 = text().trim().parse().ok(),
"rp_regist_key" => {
let bytes = qt_value(value);
let end = bytes.iter().position(|b| *b == 0).unwrap_or(bytes.len());
row.2 = Some(String::from_utf8_lossy(&bytes[..end]).into_owned());
}
_ => {}
}
}
rows.into_values().filter_map(|(nick, target, key)| {
let nickname = nick.filter(|n| !n.trim().is_empty())?;
// ChiakiTarget: PS4 versions are below 1000000, PS5 ones from there up
Some(Registered { nickname, ps5: target.is_none_or(|t| t >= 1_000_000), regist_key: key })
}).collect()
}
/// The consoles chiaki-ng has registered on this machine (native and Flatpak installs), each nickname once.
pub fn registered() -> Vec<Registered> {
let mut out: Vec<Registered> = vec![];
for p in chiaki_conf_paths() {
let Ok(text) = std::fs::read_to_string(&p) else { continue };
for r in parse_registered(&text) {
if !out.iter().any(|o| o.nickname == r.nickname) { out.push(r); }
}
}
out
}
/// argv that streams from a registered console. `fullscreen` starts chiaki-ng's window in fullscreen (without
/// Enhance; with it the engine's window is the one on screen and chiaki-ng's is minimised).
pub fn stream_argv(chiaki: &Path, nickname: &str, host: &str, fullscreen: bool) -> Vec<String> {
let mut v = vec![chiaki.to_string_lossy().into_owned(), "--exit-app-on-stream-exit".into()];
if fullscreen { v.push("--fullscreen".into()); }
v.extend(["stream".into(), nickname.into(), host.into()]);
v
}
// ---- discovery and wake ----
pub const PORT_PS5: u16 = 9302;
pub const PORT_PS4: u16 = 987;
const PROTO_PS5: &str = "00030010";
const PROTO_PS4: &str = "00020020";
/// A console that answered on the network.
#[derive(Debug, Clone, PartialEq)]
pub struct Found {
pub ip: Ipv4Addr,
pub name: String,
pub ps5: bool,
/// In rest mode ("620 Server Standby"): it has to be woken before it streams.
pub standby: bool,
}
pub fn srch_packet(ps5: bool) -> String {
format!("SRCH * HTTP/1.1\ndevice-discovery-protocol-version:{}\n", if ps5 { PROTO_PS5 } else { PROTO_PS4 })
}
pub fn wakeup_packet(credential: u64, ps5: bool) -> String {
format!("WAKEUP * HTTP/1.1\nclient-type:vr\nauth-type:R\nmodel:w\napp-type:r\nuser-credential:{credential}\ndevice-discovery-protocol-version:{}\n",
if ps5 { PROTO_PS5 } else { PROTO_PS4 })
}
/// A discovery reply: `HTTP/1.1 200 Ok` (on) or `HTTP/1.1 620 Server Standby` (rest mode), then `key:value` lines.
pub fn parse_reply(text: &str, ip: Ipv4Addr) -> Option<Found> {
let mut lines = text.lines();
let status: u32 = lines.next()?.split_whitespace().nth(1)?.parse().ok()?;
let (mut name, mut kind) = (None, None);
for l in lines {
let Some((k, v)) = l.split_once(':') else { continue };
match k.trim() { "host-name" => name = Some(v.trim().to_string()), "host-type" => kind = Some(v.trim().to_string()), _ => {} }
}
Some(Found { ip, name: name?, ps5: kind.as_deref() == Some("PS5"), standby: status == 620 })
}
/// The IPv4 broadcast addresses of this machine's interfaces that are up, plus 255.255.255.255.
pub fn broadcast_addrs() -> Vec<Ipv4Addr> {
let mut v = vec![Ipv4Addr::BROADCAST];
// SAFETY: getifaddrs fills a list this function frees again; only IPv4 entries' addresses are read.
unsafe {
let mut ifa: *mut libc::ifaddrs = std::ptr::null_mut();
if libc::getifaddrs(&mut ifa) != 0 { return v; }
let mut p = ifa;
while !p.is_null() {
let i = &*p;
let flags = i.ifa_flags as libc::c_int;
let bcast = i.ifa_ifu;
if flags & libc::IFF_UP != 0 && flags & libc::IFF_BROADCAST != 0 && flags & libc::IFF_LOOPBACK == 0
&& !bcast.is_null() && (*bcast).sa_family as libc::c_int == libc::AF_INET {
let sin = &*(bcast as *const libc::sockaddr_in);
let a = Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr));
if !v.contains(&a) { v.push(a); }
}
p = i.ifa_next;
}
libc::freeifaddrs(ifa);
}
v
}
/// Ask the network which consoles are there, for `timeout`. `also` gets a direct question too (an address that
/// answered before). PS5s and PS4s both; each console once.
pub fn discover(timeout: Duration, also: &[Ipv4Addr]) -> Vec<Found> {
let Ok(sock) = UdpSocket::bind(("0.0.0.0", 0)) else { return vec![] };
let _ = sock.set_broadcast(true);
let _ = sock.set_read_timeout(Some(Duration::from_millis(100)));
let targets: Vec<Ipv4Addr> = broadcast_addrs().into_iter().chain(also.iter().copied()).collect();
let mut found: Vec<Found> = vec![];
let end = Instant::now() + timeout;
let mut next_ask = Instant::now();
let mut buf = [0u8; 2048];
while Instant::now() < end {
if Instant::now() >= next_ask {
for ip in &targets {
for (ps5, port) in [(true, PORT_PS5), (false, PORT_PS4)] {
let _ = sock.send_to(srch_packet(ps5).as_bytes(), SocketAddrV4::new(*ip, port));
}
}
next_ask = Instant::now() + Duration::from_millis(700);
}
if let Ok((n, std::net::SocketAddr::V4(from))) = sock.recv_from(&mut buf) {
if let Some(f) = parse_reply(&String::from_utf8_lossy(&buf[..n]), *from.ip()) {
if let Some(o) = found.iter_mut().find(|o| o.name == f.name) { *o = f; } else { found.push(f); }
}
}
}
found
}
/// Look for one console by nickname: returns as soon as it answers (or None after `timeout`).
pub fn find(nickname: &str, timeout: Duration, also: &[Ipv4Addr]) -> Option<Found> {
let end = Instant::now() + timeout;
while Instant::now() < end {
let left = end.saturating_duration_since(Instant::now()).min(Duration::from_millis(1500));
if let Some(f) = discover(left, also).into_iter().find(|f| f.name == nickname) { return Some(f); }
}
None
}
/// Wake a console in rest mode (it has to have "Stay connected to the internet" / "Enable turning on from network").
pub fn wake(ip: Ipv4Addr, credential: u64, ps5: bool) -> std::io::Result<()> {
let sock = UdpSocket::bind(("0.0.0.0", 0))?;
sock.send_to(wakeup_packet(credential, ps5).as_bytes(), SocketAddrV4::new(ip, if ps5 { PORT_PS5 } else { PORT_PS4 }))?;
Ok(())
}
/// The address to stream from: the console found by nickname (woken first if it is in rest mode), else `known`
/// (where it answered last time). `say` gets a line for each step, for the log and the launcher.
pub fn reach(nickname: &str, ps5: bool, known: Option<&str>, credential: Option<u64>, say: &mut dyn FnMut(String)) -> Result<Ipv4Addr, String> {
let known: Option<Ipv4Addr> = known.and_then(|k| k.parse().ok());
say(format!("looking for {nickname} on the network..."));
let also: Vec<Ipv4Addr> = known.into_iter().collect();
match find(nickname, Duration::from_secs(4), &also) {
Some(f) if !f.standby => { say(format!("{nickname} is on, at {}", f.ip)); Ok(f.ip) }
Some(f) => {
let Some(cred) = credential else {
return Err(format!("{nickname} is in rest mode and chiaki-ng has no registration key to wake it: turn it on with the controller"));
};
say(format!("{nickname} is in rest mode at {}: waking it", f.ip));
let end = Instant::now() + Duration::from_secs(60);
let mut next_wake = Instant::now();
while Instant::now() < end {
if Instant::now() >= next_wake {
wake(f.ip, cred, ps5 || f.ps5).map_err(|e| format!("could not send the wake-up to {}: {e}", f.ip))?;
next_wake = Instant::now() + Duration::from_secs(10);
}
if let Some(now) = find(nickname, Duration::from_secs(2), &[f.ip]) {
if !now.standby { say(format!("{nickname} is awake")); return Ok(now.ip); }
}
}
Err(format!("{nickname} did not wake up within a minute. In the console's settings, turn on Remote Play and, under Power Saving, \"Stay connected to the internet\" and \"Enable turning on from network\""))
}
None => match known {
Some(ip) => { say(format!("{nickname} did not answer discovery: trying {ip}, where it was last time")); Ok(ip) }
None => Err(format!("{nickname} did not answer on the network. Turn it on (or put it in rest mode) with Remote Play on (Settings > System > Remote Play), on the same network as this PC")),
},
}
}
// ---- capture cards ----
/// A video capture device: the name the engine takes (`--capture=<name>`) and its node.
#[derive(Debug, Clone, PartialEq)]
pub struct CaptureDevice { pub name: String, pub path: String }
#[repr(C)]
struct V4l2Capability { driver: [u8; 16], card: [u8; 32], bus_info: [u8; 32], version: u32, capabilities: u32, device_caps: u32, reserved: [u32; 3] }
const VIDIOC_QUERYCAP: libc::c_ulong = 0x8068_5600;
const CAP_VIDEO_CAPTURE: u32 = 0x1;
const CAP_DEVICE_CAPS: u32 = 0x8000_0000;
/// Names for the nodes, as the engine gives them: the second device of a name gets " (2)", and so on.
pub fn number_names(names: Vec<(String, String)>) -> Vec<CaptureDevice> {
let mut seen: std::collections::HashMap<String, u32> = Default::default();
names.into_iter().map(|(name, path)| {
let n = seen.entry(name.clone()).or_insert(0);
*n += 1;
CaptureDevice { name: if *n == 1 { name } else { format!("{name} ({n})") }, path }
}).collect()
}
/// The video capture devices (capture cards, webcams), in /dev/videoN order, without UVC metadata nodes. A device
/// Summit cannot open (not in the `video` group) is left out, as the engine would.
pub fn capture_devices() -> Vec<CaptureDevice> {
let num = |p: &Path| p.file_name().and_then(|n| n.to_str()).map(|n| n.trim_start_matches("video").parse::<u32>().unwrap_or(0)).unwrap_or(0);
let mut nodes: Vec<PathBuf> = std::fs::read_dir("/sys/class/video4linux").map(|rd| rd.flatten().map(|e| e.path())
.filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("video"))).collect()).unwrap_or_default();
nodes.sort_by_key(|p| num(p));
let mut named = vec![];
for node in nodes {
let Some(dev) = node.file_name().and_then(|n| n.to_str()).map(|n| format!("/dev/{n}")) else { continue };
let Ok(cpath) = std::ffi::CString::new(dev.clone()) else { continue };
// SAFETY: open/ioctl/close on a descriptor this block owns; the ioctl fills a struct of the kernel's layout.
let cap = unsafe {
let fd = libc::open(cpath.as_ptr(), libc::O_RDWR | libc::O_NONBLOCK);
if fd < 0 { continue; }
let mut cap: V4l2Capability = std::mem::zeroed();
let ok = libc::ioctl(fd, VIDIOC_QUERYCAP as _, &mut cap as *mut V4l2Capability) == 0;
libc::close(fd);
if !ok { continue; }
cap
};
let caps = if cap.capabilities & CAP_DEVICE_CAPS != 0 { cap.device_caps } else { cap.capabilities };
if caps & CAP_VIDEO_CAPTURE == 0 { continue; }
let end = cap.card.iter().position(|b| *b == 0).unwrap_or(cap.card.len());
let name = String::from_utf8_lossy(&cap.card[..end]).trim().to_string();
let _ = cap.driver; let _ = cap.bus_info; let _ = cap.version; let _ = cap.reserved;
named.push((if name.is_empty() { dev.trim_start_matches("/dev/").to_string() } else { name }, dev));
}
number_names(named)
}
/// Webcams show up as capture devices too: a name that says so is listed after the cards.
pub fn looks_like_webcam(name: &str) -> bool {
let n = name.to_lowercase();
["webcam", "camera", "facetime", "integrated", " cam"].iter().any(|w| n.contains(w))
}
#[cfg(test)]
mod tests {
use super::*;
const CONF: &str = r#"[General]
version=2
[registered_hosts]
1\ap_name=PS5
1\rp_regist_key=@ByteArray(1a2b3c4d\0\0\0\0\0\0\0\0\0\0\0\0)
1\server_mac=@ByteArray(\xe8n:z\xdb\x5)
1\server_nickname=PS5-829
1\target=1000100
2\rp_regist_key=@ByteArray(00ff00aa\0\0\0\0\0\0\0\0)
2\server_nickname=Living Room
2\target=1000
size=2
[settings]
1\server_nickname=not-a-host
"#;
#[test]
fn registered_consoles_from_chiaki_conf() {
let r = parse_registered(CONF);
assert_eq!(r.len(), 2);
assert_eq!((r[0].nickname.as_str(), r[0].ps5, r[0].regist_key.as_deref()), ("PS5-829", true, Some("1a2b3c4d")));
assert_eq!(r[0].credential(), Some(0x1a2b3c4d));
assert_eq!((r[1].nickname.as_str(), r[1].ps5), ("Living Room", false));
assert_eq!(r[1].credential(), Some(0x00ff00aa));
assert!(parse_registered("[settings]\nx=1\n").is_empty());
}
#[test]
fn qt_escapes() {
assert_eq!(qt_value(r"@ByteArray(\xe8n:z\xdb\x5)"), vec![0xe8, b'n', b':', b'z', 0xdb, 0x05]);
assert_eq!(qt_value(r#""a b\\c\"""#), b"a b\\c\"".to_vec());
assert_eq!(qt_value(r"@ByteArray(ab\0\0)"), b"ab\0\0".to_vec());
assert_eq!(qt_value("plain"), b"plain".to_vec());
}
#[test]
fn discovery_packets_and_replies() {
assert_eq!(srch_packet(true), "SRCH * HTTP/1.1\ndevice-discovery-protocol-version:00030010\n");
assert!(wakeup_packet(439041101, true).contains("user-credential:439041101\n"));
assert!(wakeup_packet(1, false).ends_with("device-discovery-protocol-version:00020020\n"));
let ip = Ipv4Addr::new(10, 0, 0, 249);
let on = parse_reply("HTTP/1.1 200 Ok\nhost-id:E86E3A7ADB05\nhost-type:PS5\nhost-name:PS5-829\nhost-request-port:997\n", ip).unwrap();
assert_eq!(on, Found { ip, name: "PS5-829".into(), ps5: true, standby: false });
let rest = parse_reply("HTTP/1.1 620 Server Standby\nhost-type:PS4\nhost-name:Den\n", ip).unwrap();
assert!(rest.standby && !rest.ps5);
assert!(parse_reply("garbage", ip).is_none());
assert!(parse_reply("HTTP/1.1 200 Ok\nhost-type:PS5\n", ip).is_none());
}
#[test]
fn stream_command() {
let v = stream_argv(Path::new("/usr/bin/chiaki"), "PS5-829", "10.0.0.249", true);
assert_eq!(v.join(" "), "/usr/bin/chiaki --exit-app-on-stream-exit --fullscreen stream PS5-829 10.0.0.249");
assert!(!stream_argv(Path::new("c"), "n", "h", false).contains(&"--fullscreen".to_string()));
}
#[test]
fn ids_titles_and_entries() {
let c = Console::remote_play("PS5-829", true, None);
assert_eq!((c.id.as_str(), c.title.as_str()), ("remoteplay:ps5-829", "PlayStation 5"));
assert_eq!(Console::remote_play("Den", false, Some(" ")).title, "PlayStation 4");
let k = Console::capture("Live Gamer MINI", Some("Switch"));
assert_eq!((k.id.as_str(), k.title.as_str()), ("capture:live-gamer-mini", "Switch"));
let e = k.entry();
assert_eq!(e.source, crate::model::Source::Console);
assert!(e.reasons[0].contains("Live Gamer MINI"));
// stored flat in state.json, and read back
let json = serde_json::to_string(&c).unwrap();
assert!(json.contains(r#""kind":"remote-play""#) && json.contains(r#""nickname":"PS5-829""#), "{json}");
assert_eq!(serde_json::from_str::<Console>(&json).unwrap(), c);
}
#[test]
fn duplicate_device_names_numbered_like_the_engine() {
let d = number_names(vec![("Cam".into(), "/dev/video0".into()), ("Card".into(), "/dev/video2".into()), ("Cam".into(), "/dev/video4".into())]);
assert_eq!(d.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["Cam", "Card", "Cam (2)"]);
assert!(looks_like_webcam("C922 Pro Stream Webcam") && !looks_like_webcam("Live Gamer MINI"));
}
#[test]
fn frame_tap_found_across_read_boundaries() {
let d = std::env::temp_dir().join(format!("summit-console-tap-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let with = d.join("with");
let mut bytes = vec![0u8; (1 << 20) - 5];
bytes.extend_from_slice(b"chiaki-frametap\0");
std::fs::write(&with, &bytes).unwrap();
let without = d.join("without");
std::fs::write(&without, b"chiaki-ng plain build").unwrap();
assert!(has_frame_tap(&with));
assert!(!has_frame_tap(&without));
assert!(!has_frame_tap(&d.join("missing")));
let _ = std::fs::remove_dir_all(d);
}
}
+6 -3
View File
@@ -69,11 +69,14 @@ pub fn plan(session: Session, desktop: Desktop, p: &Profile) -> Vec<Cmd> {
}
}
/// Env hints so the game opens fullscreen on the right output without compositor-specific tricks.
/// Environment for the game: hints so it opens fullscreen on the right output without compositor-specific tricks,
/// `SUMMIT_MONITOR` and `SUMMIT_WINDOW_MODE` for launch scripts, then the profile's own variables (which win).
pub fn launch_env(session: Session, p: &Profile) -> Vec<(String, String)> {
let mut e = vec![];
if session == Session::Wayland && p.fullscreen { e.push(("SDL_VIDEODRIVER".into(), "wayland,x11".into())); }
if session == Session::Wayland && p.fullscreen() { e.push(("SDL_VIDEODRIVER".into(), "wayland,x11".into())); }
if let Some(m) = &p.monitor { e.push(("SUMMIT_MONITOR".into(), m.clone())); }
if !p.window_mode.is_empty() { e.push(("SUMMIT_WINDOW_MODE".into(), p.window_mode.clone())); }
e.extend(p.env.iter().map(|(k, v)| (k.clone(), v.clone())));
e
}
@@ -259,7 +262,7 @@ pub fn apply(cmds: &[Cmd]) -> Vec<(Cmd, Result<(), String>)> {
#[cfg(test)]
mod tests {
use super::*;
fn prof() -> Profile { Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(60.0), fullscreen: true, ..Default::default() } }
fn prof() -> Profile { Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(60.0), window_mode: "fullscreen".into(), ..Default::default() } }
#[test] fn session_detect() {
assert_eq!(detect_session_from(Some("wayland"), false, true), Session::Wayland);
assert_eq!(detect_session_from(None, false, true), Session::X11);
+9
View File
@@ -76,6 +76,10 @@ pub fn checks(session: Session, engine: Option<&Path>, model: Option<&str>) -> V
}
Err(e) => v.push(Check::new("torch", Status::Missing, format!("could not start {}: {e}", venv.display()))),
}
// The in-game overlay, the stats and the messages are drawn with Pillow (engine/framegen/ui_draw.py)
if Command::new(&venv).args(["-c", "import PIL"]).output().is_ok_and(|o| !o.status.success()) {
v.push(Check::new("pillow", Status::Missing, format!("the engine's venv has no Pillow, which draws the in-game overlay: Enhance can't start (uv pip install --python {} Pillow, or run install.sh again)", e.join(".venv").display())));
}
}
let w = weights_path(e, model);
if w.is_file() {
@@ -103,6 +107,11 @@ pub fn checks(session: Session, engine: Option<&Path>, model: Option<&str>) -> V
Some(p) => Check::new("file dialog", Status::Ok, format!("{p}, for Change artwork")),
None => Check::new("file dialog", Status::Missing, "neither kdialog nor zenity: Change artwork can't open a file dialog"),
});
v.push(match crate::console::chiaki_binary() {
Some(c) if crate::console::has_frame_tap(&c) => Check::new("remote play", Status::Ok, format!("{} with SmoovPlay's frame tap: PlayStation Remote Play, with Enhance", c.display())),
Some(c) => Check::new("remote play", Status::Warn, format!("{} has no frame tap: Remote Play works without Enhance (install.sh --with-remote-play builds one with it)", c.display())),
None => Check::new("remote play", Status::Warn, "chiaki-ng not found: PlayStation Remote Play is off (install.sh --with-remote-play)"),
});
v
}
+52 -4
View File
@@ -73,18 +73,43 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option
}
if p.framegen == "none" { a.push("--off".into()); }
if let Some(m) = &p.model { a.push(opt("model", m)); }
if let Some(s) = scaler_arg(&p.upscaler) { a.push("--scaler".into()); a.push(s.into()); }
if p.model.as_deref() == Some("vfg") { if let Some(q) = &p.vfg_quality { a.push(opt("vfg-quality", q)); } }
match p.motion.as_deref() { Some("full") => a.push("--scale=1.0".into()), Some("half") => a.push("--scale=0.5".into()), _ => {} }
if let Some(e) = &p.ai_engine { a.push(opt("engine", e)); }
if let Some(v) = p.steady_hud { a.push(if v { "--steady-hud" } else { "--no-steady-hud" }.into()); }
if let Some(s) = scaler_arg(&p.upscaler) {
a.push("--scaler".into()); a.push(s.into());
if let (Some(v), "fsr") = (p.fsr_sharpness, s) { a.push(format!("--fsr-sharpness={v}")); }
if let (Some(q), "vsr") = (p.vsr_quality, s) { a.push(format!("--vsr-quality={q}")); }
}
if display {
a.push("--display".into());
let hz = p.target_hz.unwrap_or(60);
if [60, 90, 120].contains(&hz) { a.push("--hz".into()); a.push(hz.to_string()); }
if p.fullscreen { a.push("--fullscreen".into()); }
match p.window_mode.as_str() {
"windowed" => a.push("--no-fullscreen".into()),
_ if p.fullscreen() => a.push("--fullscreen".into()),
_ => {}
}
if let Some(m) = &p.monitor { a.push(opt("monitor", m)); }
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())); }
if let Some(t) = max_ticks { a.push("--max-ticks".into()); a.push(t.to_string()); }
a
}
/// Environment for the engine process from the profile: "fullscreen" asks for the window system's own fullscreen
/// (GLFW's, an always-on-top window exactly over the monitor), "borderless" for a borderless window over it
/// (engine/framegen/io.py FULLSCREEN_STYLE). Over a live game window the engine always uses a borderless window.
pub fn engine_env(p: &Profile) -> Vec<(String, String)> {
match p.window_mode.as_str() {
"fullscreen" => vec![("FRAMEGEN_FULLSCREEN_STYLE".into(), "monitor".into())],
"borderless" => vec![("FRAMEGEN_FULLSCREEN_STYLE".into(), "borderless".into())],
_ => vec![],
}
}
/// The input file as the engine's positional argument: a relative name starting with '-' gets a "./" so argparse
/// takes it as a file, not an option.
fn file_arg(f: &Path) -> String {
@@ -119,7 +144,8 @@ pub fn window_of_pid(pid: u32) -> Source { Source::Window(format!("pid:{pid}"))
pub fn run_enhance_plan(engine: &Path, game_pid: u32, window: Option<&str>, p: &Profile, l: &Live) -> Vec<String> {
let src = match window { Some(w) => Source::Window(w.into()), None => window_of_pid(game_pid) };
let mut a = plan(engine, &src, p, true, None, None);
a.extend(live_args(l));
// `--no-watermark` on the command line wins over the profile
a.extend(live_args(&Live { watermark: l.watermark.or(p.watermark), ..l.clone() }));
a
}
@@ -260,6 +286,9 @@ pub fn clips_dir() -> Option<PathBuf> {
/// Instant replay flags for the engine, from the launcher's clip settings.
/// The engine only accepts 15, 30, 60, 180, 300 or 600 seconds, and a save is never longer than the buffer.
/// The engine's flag for the key that opens the overlay (ui.toml `overlay_key`, from the launcher's Settings page).
pub fn overlay_args(key: &str) -> Vec<String> { vec![format!("--overlay-key={key}")] }
pub fn clip_args(replay_seconds: u32, clip_seconds: u32) -> Vec<String> {
const OK: [u32; 6] = [15, 30, 60, 180, 300, 600];
if !OK.contains(&replay_seconds) { return vec![]; }
@@ -272,7 +301,7 @@ pub fn clip_args(replay_seconds: u32, clip_seconds: u32) -> Vec<String> {
#[cfg(test)]
mod tests {
use super::*;
fn p() -> Profile { Profile { monitor: Some("HDMI-A-1".into()), fullscreen: true, upscaler: "rtx-vsr".into(), framegen: "rife".into(), target_hz: Some(120), model: Some("4.25".into()), ..Default::default() } }
fn p() -> Profile { Profile { monitor: Some("HDMI-A-1".into()), window_mode: "borderless".into(), upscaler: "rtx-vsr".into(), framegen: "rife".into(), target_hz: Some(120), model: Some("4.25".into()), ..Default::default() } }
#[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");
@@ -282,6 +311,10 @@ mod tests {
let a = plan(Path::new("/e"), &Source::File("c.mp4".into()), &pr, false, Some(Path::new("o.mp4")), Some(120));
assert_eq!(a[1..].join(" "), "c.mp4 --out=o.mp4 --max-ticks 120");
}
#[test] fn overlay_key_goes_as_one_argument() {
assert_eq!(overlay_args("Insert"), vec!["--overlay-key=Insert"]);
assert_eq!(overlay_args("Ctrl+Shift+O"), vec!["--overlay-key=Ctrl+Shift+O"]);
}
#[test] fn clip_args_follow_the_engine_choices() {
assert_eq!(clip_args(60, 30).join(" "), "--replay 60 --clip-length 30");
assert_eq!(clip_args(30, 300).join(" "), "--replay 30 --clip-length 30");
@@ -434,6 +467,21 @@ mod tests {
assert_eq!(f[1..].join(" "), "./-clip.mp4 --out=-o.mp4");
assert_eq!(plan(Path::new("/e"), &Source::File("/abs/-c.mp4".into()), &Profile::default(), false, None, None)[1], "/abs/-c.mp4");
}
#[test] fn every_profile_setting_reaches_the_engine() {
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");
// 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:?}");
assert_eq!(engine_env(&Profile { window_mode: "fullscreen".into(), ..Default::default() }), vec![("FRAMEGEN_FULLSCREEN_STYLE".to_string(), "monitor".to_string())]);
assert!(engine_env(&Profile::default()).is_empty());
// the profile's watermark, unless the command line says otherwise
let w = Profile { watermark: Some(false), ..Default::default() };
assert!(run_enhance_plan(Path::new("/e"), 1, None, &w, &Live::default()).ends_with(&["--watermark".to_string(), "off".to_string()]));
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 framegen_none_turns_interp_off() {
let pr = Profile { framegen: "none".into(), ..Default::default() };
+1 -23
View File
@@ -1,4 +1,4 @@
//! Heroic (Epic/GOG/Amazon) and Lutris discovery.
//! Heroic (Epic/GOG/Amazon) discovery. Lutris is in `lutris.rs`.
use crate::model::{Entry, Kind, Source};
use serde_json::Value;
@@ -57,28 +57,6 @@ pub fn heroic_in(root: &std::path::Path) -> Vec<Entry> {
out
}
/// Lutris keeps one YAML per game; we only need name/slug/runner so a line scan avoids a YAML dependency.
pub fn lutris() -> Vec<Entry> {
let mut out = Vec::new();
let Some(data) = dirs::data_dir() else { return out };
let dir = data.join("lutris/games");
let Ok(rd) = std::fs::read_dir(&dir) else { return out };
for f in rd.flatten() {
let p = f.path();
if p.extension().and_then(|e| e.to_str()) != Some("yml") { continue; }
let Ok(txt) = std::fs::read_to_string(&p) else { continue };
let get = |k: &str| txt.lines().find_map(|l| l.strip_prefix(&format!("{k}: "))).map(|s| s.trim().trim_matches('\'').trim_matches('"').to_string());
let (Some(slug), Some(runner)) = (get("game_slug"), get("runner")) else { continue };
let exe = get("exe");
out.push(Entry {
id: format!("lutris:{slug}"), title: slug.replace('-', " "), source: Source::Lutris, kind: Kind::Game,
installed: true, path: exe, steam_app_id: None, playtime_minutes: 0, last_played: None,
launch_uri: None, reasons: vec![format!("Lutris game config {} (runner: {runner})", p.display())],
});
}
out
}
#[cfg(test)]
mod tests {
#[test]
+65 -2
View File
@@ -1,11 +1,59 @@
//! The global "save a clip" key. The engine owns it (engine/framegen/globalkeys.py); this says, for the launcher,
//! whether this session can have one at all.
//! The engine's system-wide keys. The engine owns them (engine/framegen/globalkeys.py); this says, for the launcher,
//! whether this session can have a "save a clip" key at all, and which key opens the in-game overlay.
use crate::display::Session;
use std::process::Command;
/// The engine's save key; Ctrl+Alt+B saves a before & after.
pub const SAVE_KEY: &str = "Ctrl+Alt+R";
/// The key that opens Summit's overlay over a game (upscaling, frame generation, the performance view), unless
/// ui.toml's `overlay_key` says otherwise. Esc is never it: Esc is the game's own key and never closes Summit.
pub const OVERLAY_KEY: &str = "Insert";
/// The choices on the launcher's Settings page. ui.toml takes any key [`overlay_key`] accepts ("Ctrl+Shift+O").
pub const OVERLAY_KEYS: &[&str] = &["Insert", "Home", "End", "Pause", "F9", "F10"];
const MOD_ORDER: &[&str] = &["Ctrl", "Alt", "Shift", "Super"];
/// Keys that can open the overlay on their own: they type nothing and games rarely use them.
const ALONE: &[&str] = &["Insert", "Home", "End", "Delete", "PageUp", "PageDown", "Pause", "ScrollLock"];
/// `text` in the engine's spelling of an overlay key ("insert" -> "Insert", "shift + ctrl + o" -> "Ctrl+Shift+O"),
/// or None if it cannot be one. The same rules as engine/framegen/overlaykey.py: Insert, Home, End, Delete,
/// PageUp, PageDown, Pause, ScrollLock and F1 to F24 work on their own; a letter, digit, Space or Tab needs Ctrl,
/// Alt or Super with it (the game would lose that key otherwise); Esc, Enter, Backspace and the arrows never work.
pub fn overlay_key(text: &str) -> Option<String> {
let mut mods: Vec<&str> = vec![];
let mut key: Option<String> = None;
for part in text.split('+').map(str::trim).filter(|p| !p.is_empty()) {
let low = part.to_ascii_lowercase();
let m = match low.as_str() {
"ctrl" | "control" => Some("Ctrl"), "alt" => Some("Alt"), "shift" => Some("Shift"),
"super" | "win" | "windows" | "meta" | "logo" => Some("Super"), _ => None,
};
if let Some(m) = m {
if mods.contains(&m) { return None; }
mods.push(m);
continue;
}
if key.is_some() { return None; }
let low = match low.as_str() {
"ins" => "insert", "del" => "delete", "pgup" | "prior" => "pageup", "pgdn" | "pagedn" | "next" => "pagedown",
"break" => "pause", "scroll_lock" | "scrlk" => "scrolllock", other => other,
}.to_string();
key = Some(if let Some(k) = ALONE.iter().find(|k| k.eq_ignore_ascii_case(&low)) { k.to_string() }
else if let Some(n) = low.strip_prefix('f').and_then(|n| n.parse::<u32>().ok()).filter(|n| (1..=24).contains(n)) { format!("F{n}") }
else if low == "space" { "Space".into() }
else if low == "tab" { "Tab".into() }
else if low.len() == 1 && low.chars().all(|c| c.is_ascii_alphanumeric()) { low.to_ascii_uppercase() }
else { return None });
}
let key = key?;
let alone = ALONE.contains(&key.as_str()) || (key.starts_with('F') && key.len() > 1);
if !alone && !mods.iter().any(|m| ["Ctrl", "Alt", "Super"].contains(m)) { return None; }
let mut out: Vec<&str> = MOD_ORDER.iter().copied().filter(|m| mods.contains(m)).collect();
out.push(&key);
Some(out.join("+"))
}
/// Whether xdg-desktop-portal offers GlobalShortcuts. None: the portal could not be asked (no gdbus, no session bus).
pub fn portal_has_global_shortcuts() -> Option<bool> {
let o = Command::new("gdbus").args(["introspect", "--session", "--dest", "org.freedesktop.portal.Desktop", "--object-path", "/org/freedesktop/portal/desktop"]).output().ok()?;
@@ -28,6 +76,21 @@ pub fn status(session: Session, portal: Option<bool>) -> String {
mod tests {
use super::*;
#[test]
fn overlay_keys_are_normalised_and_game_keys_refused() {
assert_eq!(overlay_key("insert").as_deref(), Some("Insert"));
assert_eq!(overlay_key(" HOME ").as_deref(), Some("Home"));
assert_eq!(overlay_key("f10").as_deref(), Some("F10"));
assert_eq!(overlay_key("pgdn").as_deref(), Some("PageDown"));
assert_eq!(overlay_key("shift + ctrl + o").as_deref(), Some("Ctrl+Shift+O"));
assert_eq!(overlay_key("win+f1").as_deref(), Some("Super+F1"));
assert_eq!(overlay_key("Alt+Space").as_deref(), Some("Alt+Space"));
for bad in ["", "Esc", "Escape", "Enter", "Up", "Backspace", "w", "Shift+W", "1", "Space", "Tab", "Ctrl", "Ctrl+A+B", "Ctrl+Ctrl+A", "F25", "F0", "Nope"] {
assert_eq!(overlay_key(bad), None, "{bad}");
}
assert!(OVERLAY_KEYS.contains(&OVERLAY_KEY));
for k in OVERLAY_KEYS { assert_eq!(overlay_key(k).as_deref(), Some(*k)); }
}
#[test]
fn status_says_what_is_there() {
assert!(status(Session::X11, None).starts_with("Ctrl+Alt+R saves"));
assert!(status(Session::Wayland, Some(true)).contains("GlobalShortcuts portal"));
+69 -6
View File
@@ -19,10 +19,15 @@ pub enum Plan {
/// for it. Steam keeps the playtime. Without the summit binary it falls back to `steam steam://rungameid/<id>`.
/// A game that is not installed gets `steam steam://install/<id>`, which opens Steam's install dialog.
/// * Added by hand: `summit run <id> [--enhance] -- <path>`: profile applied, session tracked.
/// * Lutris: `summit run <id> --detached -- lutris lutris:rungame/<slug>` (no enhance: Lutris games have no
/// window rule Summit can know in advance).
/// * Steam, a non-Steam game added to the Steam library: `summit run <id> --detached -- steam steam://rungameid/<id64>`
/// (Steam starts it with its own settings; no enhance).
/// * Lutris: `summit run <id> --detached -- lutris lutris:rungameid/<db id>` (`lutris:rungame/<slug>` for an entry
/// with no id). No enhance: Lutris games have no window rule Summit can know in advance.
/// * Heroic: `summit run <id> --detached -- xdg-open heroic://launch?appName=..&runner=..`: Heroic starts the game
/// with its own Wine/Proton settings and keeps the playtime. No enhance yet (no window rule known in advance).
/// * Console (PlayStation Remote Play, a capture card): `summit run <id> [--enhance]`, no command: `summit run`
/// looks the console up and starts chiaki-ng (finding and waking the console) or the engine on the card, with
/// the engine first and chiaki-ng's frame tap on when Enhance is on (console.rs).
/// * Folders found on disk: not wired (add them with `summit add`).
pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
let cli = summit_cli.map(|c| c.to_string_lossy().into_owned());
@@ -49,7 +54,15 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
}
}
Some(id) => Plan::Run(vec!["steam".into(), format!("steam://install/{id}")]),
None => Plan::Unsupported("this Steam entry has no app id".into()),
// A non-Steam game in the Steam library: Steam starts it (its Proton choice, its launch options).
None => match e.launch_uri.as_deref() {
Some(uri) => {
if enhance { return Plan::Unsupported("Enhance is not wired for non-Steam games in Steam yet".into()); }
let steam = vec!["steam".to_string(), uri.to_string()];
match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], steam)), None => Plan::Run(steam) }
}
None => Plan::Unsupported("this Steam entry has no app id".into()),
},
},
Source::Custom => {
let Some(path) = e.path.as_deref() else { return Plan::Unsupported("no path stored for this entry".into()) };
@@ -62,9 +75,9 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
None => Plan::Unsupported("the summit command line tool was not found next to summit-gui".into()),
}
}
Source::Lutris => match e.id.strip_prefix("lutris:") {
Some(slug) if !slug.is_empty() => {
let lutris = vec!["lutris".to_string(), format!("lutris:rungame/{slug}")];
Source::Lutris => match e.launch_uri.clone().or_else(|| e.id.strip_prefix("lutris:").filter(|s| !s.is_empty()).map(|s| format!("lutris:rungame/{s}"))) {
Some(uri) => {
let lutris = vec!["lutris".to_string(), uri];
if enhance { return Plan::Unsupported("Enhance is not wired for Lutris games yet".into()); }
match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], lutris)), None => Plan::Run(lutris) }
}
@@ -78,10 +91,27 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
}
None => Plan::Unsupported("no Heroic app name for this entry".into()),
},
Source::Console => match cli {
Some(cli) => {
let mut v = vec![cli, "run".into(), e.id.clone()];
if enhance { v.push("--enhance".into()); }
if !e.title.is_empty() { v.push(format!("--title={}", e.title)); }
Plan::Run(v)
}
None => Plan::Unsupported("consoles start through the summit command line tool, which was not found next to summit-gui".into()),
},
Source::Heuristic => Plan::Unsupported("found on disk: add it with `summit add` and pick its executable to launch it".into()),
}
}
/// The same start, with the game's window given the keyboard once it opens (`summit run --focus`): Play in the
/// launcher, which steps aside for the game. A start that does not go through `summit run` is left as it is.
pub fn with_focus(mut argv: Vec<String>) -> Vec<String> {
let ours = argv.len() >= 3 && argv[1] == "run" && !argv.iter().take_while(|a| a.as_str() != "--").any(|a| a == "--focus");
if ours { argv.insert(3, "--focus".into()); }
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() }
@@ -96,6 +126,19 @@ mod tests {
fn cli() -> Option<&'static Path> { Some(Path::new(CLI)) }
fn argv(p: Plan) -> String { match p { Plan::Run(v) => v.join(" "), Plan::Unsupported(w) => format!("unsupported: {w}") } }
#[test]
fn focus_is_added_to_summit_run_only() {
let e = entry("steam:620", Source::Steam, true, Some(620), None);
let Plan::Run(v) = plan(&e, cli(), false) else { panic!() };
let f = with_focus(v);
assert_eq!(f.join(" "), "/usr/bin/summit run steam:620 --focus --detached --title=steam:620 -- steam steam://rungameid/620");
assert_eq!(with_focus(f.clone()), f); // once
let plain = vec!["steam".to_string(), "steam://rungameid/620".to_string()];
assert_eq!(with_focus(plain.clone()), plain);
// 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");
}
#[test]
fn steam_installed_goes_through_summit_run() {
let e = entry("steam:620", Source::Steam, true, Some(620), None);
assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam:620 --detached --title=steam:620 -- steam steam://rungameid/620");
@@ -105,6 +148,14 @@ mod tests {
assert!(!is_install(&e));
}
#[test]
fn steam_shortcut_starts_through_steam() {
let mut e = entry("steam-shortcut:3604730456", Source::Steam, true, None, None);
e.launch_uri = Some("steam://rungameid/15482199419448721408".into());
assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam-shortcut:3604730456 --detached --title=steam-shortcut:3604730456 -- steam steam://rungameid/15482199419448721408");
assert!(matches!(plan(&e, cli(), true), Plan::Unsupported(_)));
assert!(!is_install(&e));
}
#[test]
fn steam_not_installed_opens_install() {
let e = entry("steam:730", Source::Steam, false, Some(730), None);
assert_eq!(plan(&e, cli(), true), Plan::Run(vec!["steam".into(), "steam://install/730".into()]));
@@ -127,11 +178,23 @@ mod tests {
assert!(matches!(plan(&e, cli(), false), Plan::Unsupported(_)));
}
#[test]
fn consoles_go_through_summit_run_without_a_command() {
let mut e = entry("remoteplay:ps5-829", Source::Console, true, None, None);
e.title = "PlayStation 5".into();
assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run remoteplay:ps5-829 --title=PlayStation 5");
assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run remoteplay:ps5-829 --enhance --title=PlayStation 5");
assert!(matches!(plan(&e, None, false), Plan::Unsupported(_)));
assert!(!is_install(&e));
}
#[test]
fn lutris_and_unwired_sources() {
let l = entry("lutris:celeste", Source::Lutris, true, None, None);
assert_eq!(argv(plan(&l, cli(), false)), "/usr/bin/summit run lutris:celeste --detached --title=lutris:celeste -- lutris lutris:rungame/celeste");
assert_eq!(plan(&l, None, false), Plan::Run(vec!["lutris".into(), "lutris:rungame/celeste".into()]));
assert!(matches!(plan(&l, cli(), true), Plan::Unsupported(_)));
let mut l2 = entry("lutris:celeste@5", Source::Lutris, true, None, None);
l2.launch_uri = Some("lutris:rungameid/5".into());
assert_eq!(plan(&l2, None, false), Plan::Run(vec!["lutris".into(), "lutris:rungameid/5".into()]));
assert!(matches!(plan(&entry("heroic:epic:x", Source::Heroic, true, None, None), cli(), false), Plan::Unsupported(_)));
let mut h = entry("heroic:epic:quail", Source::Heroic, true, None, None);
h.launch_uri = Some("heroic://launch?appName=Quail&runner=legendary".into());
+6
View File
@@ -1,19 +1,25 @@
//! Summit core: library scanning, per-game profiles, and the detection-reason model.
pub mod artwork;
pub mod console;
pub mod display;
pub mod doctor;
pub mod engine;
pub mod hotkey;
pub mod epic;
pub mod launch;
pub mod lutris;
pub mod model;
pub mod names;
pub mod profile;
pub mod running;
pub mod scan;
pub mod sgdb;
pub mod shortcuts;
pub mod signals;
pub mod state;
pub mod steam;
pub mod steam_account;
pub mod ui;
pub mod vdf;
pub mod vdf_bin;
pub mod winmode;
+234
View File
@@ -0,0 +1,234 @@
//! Lutris discovery. Lutris keeps its game list in an SQLite file (`pga.db`: name, slug, runner, playtime, ...)
//! and one YAML per game (`games/<configpath>.yml`) that holds the executable. Current Lutris versions write no
//! `game_slug:` or `runner:` into that YAML, so the database is what says which games exist.
use crate::model::{Entry, Kind, Source};
use std::path::{Path, PathBuf};
/// Lutris data folders that exist: the native one and the Flatpak's.
pub fn roots() -> Vec<PathBuf> {
let mut out = Vec::new();
if let Some(d) = dirs::data_dir() { out.push(d.join("lutris")); }
if let Some(h) = dirs::home_dir() { out.push(h.join(".var/app/net.lutris.Lutris/data/lutris")); }
out.retain(|p| p.is_dir());
out
}
/// Every installed Lutris game on this machine.
pub fn scan() -> Vec<Entry> {
let mut out: Vec<Entry> = Vec::new();
for root in roots() {
for e in scan_root(&root) {
if !out.iter().any(|o| o.id == e.id) { out.push(e); }
}
}
out
}
/// One row of the `games` table, the columns Summit uses.
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
pub id: i64,
pub name: String,
pub slug: String,
pub runner: String,
pub directory: String,
pub configpath: String,
pub playtime_hours: f64,
pub lastplayed: i64,
}
/// The installed games in one `pga.db`, minus those in Lutris's ".hidden" category. Opened read-only, so a
/// running Lutris is not disturbed.
pub fn read_db(db: &Path) -> rusqlite::Result<Vec<Row>> {
use rusqlite::{Connection, OpenFlags};
let c = Connection::open_with_flags(db, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)?;
c.busy_timeout(std::time::Duration::from_secs(2))?;
let hidden: Vec<i64> = c
.prepare("SELECT gc.game_id FROM games_categories gc JOIN categories c ON c.id = gc.category_id WHERE c.name = '.hidden'")
.and_then(|mut s| s.query_map([], |r| r.get(0))?.collect())
.unwrap_or_default(); // older databases have no categories
let mut s = c.prepare(
"SELECT id, name, slug, runner, directory, configpath, playtime, lastplayed FROM games WHERE installed = 1 ORDER BY id",
)?;
let rows = s.query_map([], |r| {
Ok(Row {
id: r.get(0)?,
name: r.get::<_, Option<String>>(1)?.unwrap_or_default(),
slug: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
runner: r.get::<_, Option<String>>(3)?.unwrap_or_default(),
directory: r.get::<_, Option<String>>(4)?.unwrap_or_default(),
configpath: r.get::<_, Option<String>>(5)?.unwrap_or_default(),
playtime_hours: r.get::<_, Option<f64>>(6)?.unwrap_or(0.0),
lastplayed: r.get::<_, Option<i64>>(7)?.unwrap_or(0),
})
})?;
Ok(rows.filter_map(Result::ok).filter(|r| !hidden.contains(&r.id)).collect())
}
/// A field under the `game:` section of a Lutris game YAML (`exe`, `prefix`, `working_dir`). Long values are
/// folded onto indented lines by the YAML writer; those are joined back with single spaces, as YAML reads them.
/// Only plain and simply quoted scalars, which is what Lutris writes for paths.
pub fn game_field(yaml: &str, key: &str) -> Option<String> {
let mut in_game = false;
let mut lines = yaml.lines().peekable();
while let Some(line) = lines.next() {
let indent = line.len() - line.trim_start().len();
if indent == 0 { in_game = line.trim_end() == "game:"; continue; }
if !in_game { continue; }
let Some(rest) = line.trim_start().strip_prefix(key).and_then(|r| r.strip_prefix(':')) else { continue };
let mut v = rest.trim().to_string();
while let Some(next) = lines.peek() {
let ni = next.len() - next.trim_start().len();
if next.trim().is_empty() || ni <= indent { break; }
v.push(' ');
v.push_str(next.trim());
lines.next();
}
let v = if v.len() >= 2 && ((v.starts_with('\'') && v.ends_with('\'')) || (v.starts_with('"') && v.ends_with('"'))) {
v[1..v.len() - 1].replace("''", "'")
} else { v };
return (!v.is_empty()).then_some(v);
}
None
}
/// The game's executable as an absolute path: Lutris stores some relative to the Wine prefix (`drive_c/...`) or
/// to the game's folder.
pub fn exe_path(exe: &str, prefix: Option<&str>, directory: &str) -> String {
if exe.starts_with('/') { return exe.to_string(); }
let base = prefix.filter(|p| !p.is_empty()).or((!directory.is_empty()).then_some(directory));
match base { Some(b) => Path::new(b).join(exe).to_string_lossy().into_owned(), None => exe.to_string() }
}
fn scan_root(root: &Path) -> Vec<Entry> {
let db = root.join("pga.db");
let rows = match read_db(&db) {
Ok(r) => r,
Err(_) => return Vec::new(),
};
let mut out: Vec<Entry> = Vec::new();
for r in rows {
// Steam games that Lutris lists through its Steam service are already Steam entries.
if r.slug.is_empty() || r.runner == "steam" { continue; }
let yml = root.join("games").join(format!("{}.yml", r.configpath));
let txt = if r.configpath.is_empty() { String::new() } else { std::fs::read_to_string(&yml).unwrap_or_default() };
let exe = game_field(&txt, "exe").map(|e| exe_path(&e, game_field(&txt, "prefix").as_deref(), &r.directory));
let path = exe.clone().or((!r.directory.is_empty()).then(|| r.directory.clone()));
// The slug names the entry (profiles and pins are kept under it). Two installs of one game get the
// database id as well, so neither hides the other.
let mut id = format!("lutris:{}", r.slug);
if out.iter().any(|o| o.id == id) { id = format!("lutris:{}@{}", r.slug, r.id); }
let mut reasons = vec![format!("installed in Lutris ({}, game {})", db.display(), r.id)];
if !r.runner.is_empty() { reasons.push(format!("runner: {}", r.runner)); }
if !txt.is_empty() { reasons.push(format!("config {}", yml.display())); }
out.push(Entry {
id,
title: if r.name.trim().is_empty() { r.slug.replace('-', " ") } else { r.name.trim().to_string() },
source: Source::Lutris,
kind: Kind::Game,
installed: true,
path,
steam_app_id: None,
playtime_minutes: (r.playtime_hours.max(0.0) * 60.0).round() as u64,
last_played: (r.lastplayed > 0).then_some(r.lastplayed as u64),
reasons,
launch_uri: Some(format!("lutris:rungameid/{}", r.id)),
});
}
out
}
/// Lutris's cover (portrait) for a slug, from any Lutris data or cache folder.
pub fn cover(slug: &str) -> Option<PathBuf> { art(slug, "coverart") }
/// Lutris's banner (wide) for a slug.
pub fn banner(slug: &str) -> Option<PathBuf> { art(slug, "banners") }
fn art(slug: &str, kind: &str) -> Option<PathBuf> {
let mut dirs_: Vec<PathBuf> = roots().into_iter().map(|r| r.join(kind)).collect();
if let Some(c) = dirs::cache_dir() { dirs_.push(c.join("lutris").join(kind)); }
if let Some(h) = dirs::home_dir() { dirs_.push(h.join(".var/app/net.lutris.Lutris/cache/lutris").join(kind)); }
art_in(&dirs_, slug)
}
pub fn art_in(dirs_: &[PathBuf], slug: &str) -> Option<PathBuf> {
if slug.is_empty() || slug.contains('/') { return None; }
dirs_.iter().find_map(|d| ["jpg", "png", "jpeg", "webp"].iter().map(|x| d.join(format!("{slug}.{x}"))).find(|p| p.is_file()))
}
/// The slug part of a Lutris entry id (`lutris:<slug>`, or `lutris:<slug>@<db id>` for a second install).
pub fn slug_of(id: &str) -> Option<&str> {
let s = id.strip_prefix("lutris:")?;
Some(s.split_once('@').map_or(s, |(slug, _)| slug))
}
#[cfg(test)]
mod tests {
use super::*;
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("summit-lutris-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn folded_and_quoted_yaml_values() {
let y = "game:\n arch: auto\n exe: /run/media/x/SteamLibrary/steamapps/common/Call of Duty Black\n Ops II/t6zm.exe\n prefix: '/home/u/it''s'\n working_dir: ''\nsystem:\n exe: /not/this\n";
assert_eq!(game_field(y, "exe").as_deref(), Some("/run/media/x/SteamLibrary/steamapps/common/Call of Duty Black Ops II/t6zm.exe"));
assert_eq!(game_field(y, "prefix").as_deref(), Some("/home/u/it's"));
assert_eq!(game_field(y, "working_dir"), None);
assert_eq!(game_field("wine:\n exe: /x\n", "exe"), None);
assert_eq!(game_field("game:\n exe_args: a\n exe: /y\n", "exe").as_deref(), Some("/y"));
}
#[test]
fn relative_exe_joins_the_prefix_then_the_folder() {
assert_eq!(exe_path("drive_c/a.exe", Some("/p"), "/d"), "/p/drive_c/a.exe");
assert_eq!(exe_path("bin/a", None, "/d"), "/d/bin/a");
assert_eq!(exe_path("/abs/a.exe", Some("/p"), "/d"), "/abs/a.exe");
}
#[test]
fn reads_installed_games_from_a_lutris_database() {
let root = tmp("db");
std::fs::create_dir_all(root.join("games")).unwrap();
let c = rusqlite::Connection::open(root.join("pga.db")).unwrap();
c.execute_batch("
CREATE TABLE games (id INTEGER PRIMARY KEY, name TEXT, sortname TEXT, slug TEXT, installer_slug TEXT, parent_slug TEXT, platform TEXT, runner TEXT, executable TEXT, directory TEXT, updated DATETIME, lastplayed INTEGER, installed INTEGER, installed_at INTEGER, year INTEGER, configpath TEXT, has_custom_banner INTEGER, has_custom_icon INTEGER, has_custom_coverart_big INTEGER, playtime REAL, service TEXT, service_id TEXT, discord_id TEXT);
CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE games_categories (game_id INTEGER, category_id INTEGER);
INSERT INTO games (id, name, slug, runner, directory, installed, configpath, playtime, lastplayed) VALUES
(2, 'Celeste', 'celeste', 'wine', '/g/celeste', 1, 'celeste-1', 1.5, 1700000000),
(3, 'Gone', 'gone', '', '', 0, 'gone-1', 0, 0),
(4, 'Secret', 'secret', 'wine', '', 1, 'secret-1', 0, 0),
(5, 'Celeste', 'celeste', 'linux', '/g/c2', 1, '', NULL, NULL),
(6, 'Via Steam', 'portal', 'steam', '', 1, '', 0, 0);
INSERT INTO categories VALUES (1, '.hidden');
INSERT INTO games_categories VALUES (4, 1);
").unwrap();
drop(c);
std::fs::write(root.join("games/celeste-1.yml"), "game:\n exe: drive_c/Celeste/Celeste.exe\n prefix: /pfx\nwine:\n version: ge\n").unwrap();
let es = scan_root(&root);
let got: Vec<_> = es.iter().map(|e| (e.id.as_str(), e.title.as_str(), e.path.as_deref(), e.launch_uri.as_deref(), e.playtime_minutes)).collect();
assert_eq!(got, vec![
("lutris:celeste", "Celeste", Some("/pfx/drive_c/Celeste/Celeste.exe"), Some("lutris:rungameid/2"), 90),
("lutris:celeste@5", "Celeste", Some("/g/c2"), Some("lutris:rungameid/5"), 0),
]);
assert_eq!(es[0].last_played, Some(1_700_000_000));
assert_eq!(slug_of(&es[1].id), Some("celeste"));
assert_eq!(slug_of("lutris:portal-2"), Some("portal-2"));
assert!(scan_root(&tmp("empty")).is_empty());
}
#[test]
fn art_prefers_the_first_folder_and_known_types() {
let a = tmp("art-a"); let b = tmp("art-b");
std::fs::write(b.join("celeste.png"), b"x").unwrap();
std::fs::write(a.join("celeste.txt"), b"x").unwrap();
assert_eq!(art_in(&[a.clone(), b.clone()], "celeste"), Some(b.join("celeste.png")));
std::fs::write(a.join("celeste.jpg"), b"x").unwrap();
assert_eq!(art_in(&[a.clone(), b], "celeste"), Some(a.join("celeste.jpg")));
assert_eq!(art_in(&[a], "../celeste"), None);
}
}
+3 -1
View File
@@ -2,7 +2,9 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(rename_all = "lowercase")]
pub enum Source { Steam, Heroic, Lutris, Heuristic, Custom }
pub enum Source { Steam, Heroic, Lutris, Heuristic, Custom,
/// A console added by hand: PlayStation Remote Play through chiaki-ng, or a capture card (console.rs).
Console }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
+349 -26
View File
@@ -1,8 +1,39 @@
//! Per-game profiles: which monitor, what mode, which upscaler/framegen. Stored as TOML, one file per game.
//! Launch profiles: which monitor and mode, how the game's window is placed, and how Enhance (upscaling and frame
//! generation) runs. Stored as TOML, one file per game, plus `default.toml`: the launcher's defaults.
//!
//! Every file is a [`Layer`]: each setting is either set or left out. A game's effective [`Profile`] is the built-in
//! values, then the defaults layer on top, then the game's own layer on top ([`resolve`]). So a game only stores what
//! it changes, and a change to the defaults reaches every game that has not set that value itself.
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
/// The id of the launcher-wide defaults layer (`default.toml`). Also what `summit enhance` uses without `--profile`.
pub const DEFAULT_ID: &str = "default";
/// Written into every layer saved by this version. A file without it is from before layers ([`Layer::from_legacy`]).
pub const LAYER_VERSION: u32 = 2;
/// How the game's window is placed. "" leaves the game's own choice alone.
pub const WINDOW_MODES: &[&str] = &["", "windowed", "borderless", "fullscreen"];
/// The engine's upscalers ("" = the engine's saved setting). DLSS is not one: it is in the game itself.
pub const UPSCALERS: &[&str] = &["", "none", "fsr", "rtx-vsr", "bilinear"];
/// "" = the engine's default (RIFE on), "none" = off, "rife" = on.
pub const FRAMEGENS: &[&str] = &["", "none", "rife"];
/// Interpolation models the engine takes as `--model` (engine/framegen/interpolator.py MODELS, and "vfg").
pub const MODELS: &[&str] = &["4.22.lite", "4.25.lite", "4.25", "4.26", "vfg"];
pub const VFG_QUALITIES: &[&str] = &["low", "medium", "high"];
/// RIFE's flow resolution: full = `--scale 1.0`, half = `--scale 0.5`.
pub const MOTIONS: &[&str] = &["full", "half"];
pub const AI_ENGINES: &[&str] = &["auto", "trt", "torch"];
pub const FILLS: &[&str] = &["fit", "zoom", "stretch", "panorama"];
/// FSR 1 sharpening in stops below maximum (engine `--fsr-sharpness`).
pub const FSR_SHARPNESS: &[f32] = &[0.0, 0.25, 0.5, 1.0, 2.0];
pub const VSR_QUALITIES: &[u8] = &[1, 2, 3, 4];
pub const TARGET_HZ: &[u32] = &[60, 90, 120];
/// The settings a game launches with, after the layers are put together. `None` (and "") everywhere means "not
/// chosen": the monitor is not switched, the window is left alone, the engine uses its own saved setting.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct Profile {
@@ -11,62 +42,354 @@ pub struct Profile {
pub width: Option<u32>,
pub height: Option<u32>,
pub refresh_hz: Option<f32>,
pub fullscreen: bool,
/// Raise and focus the game window after launch.
/// "" (leave the game's choice) | "windowed" | "borderless" | "fullscreen". Applied to the game's window once it
/// opens (crate::winmode) and to the engine's picture with Enhance.
pub window_mode: String,
/// Raise and focus the game window once it opens.
pub focus: bool,
/// "none" | "fsr" | "nis" | "rtx-vsr" | "dlss"
/// Play from the launcher runs the engine on the game's window (`summit run --enhance`).
pub enhance: bool,
/// "" (engine's setting) | "none" | "fsr" | "rtx-vsr" | "bilinear" (older files: "nis", "dlss": stored, not used)
pub upscaler: String,
/// "none" | "rife" | "lsfg"
pub fsr_sharpness: Option<f32>,
pub vsr_quality: Option<u8>,
/// "" (engine default, on) | "none" | "rife" (older files: "lsfg": stored, not used)
pub framegen: String,
/// 1 = off, 2..4 = multiplier
/// 1 = off, 2..4 = multiplier. Stored only: the engine picks the multiplier from `target_hz`.
pub framegen_multiplier: u8,
/// Output rate for the engine: 60, 90 or 120.
pub target_hz: Option<u32>,
/// RIFE model, e.g. "4.22.lite" (default), "4.25", "4.26".
/// Interpolation model, e.g. "4.22.lite" or "vfg".
pub model: Option<String>,
pub vfg_quality: Option<String>,
/// "full" | "half": RIFE's motion detail.
pub motion: Option<String>,
/// "auto" | "trt" | "torch"
pub ai_engine: Option<String>,
pub steady_hud: Option<bool>,
/// How the picture fills a screen that is not 16:9: "fit" | "zoom" | "stretch" | "panorama".
pub fill: Option<String>,
pub vsync: Option<bool>,
/// The "summit - git.molberg.cloud/alex/summit" line in a corner of the engine's picture.
pub watermark: Option<bool>,
/// Added after the game's command.
pub launch_args: Vec<String>,
/// Play from the launcher runs the engine on the game's window (`summit run --enhance`).
pub enhance: bool,
/// Set for the game's process (e.g. MANGOHUD=1, PROTON_ENABLE_NVAPI=1). The game's own keys win over the defaults'.
pub env: BTreeMap<String, String>,
}
impl Profile {
/// The engine's picture covers the monitor (borderless or fullscreen), rather than sitting over the game's window.
pub fn fullscreen(&self) -> bool { matches!(self.window_mode.as_str(), "borderless" | "fullscreen") }
}
/// One stored file: only what it sets. For text and number settings an empty string or 0 is a real choice that
/// overrides the layer below with "not chosen" (e.g. a game that must not switch the default monitor: `monitor = ""`).
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct Layer {
#[serde(skip_serializing_if = "Option::is_none")] pub version: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] pub monitor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub width: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] pub height: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] pub refresh_hz: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")] pub window_mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub focus: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] pub enhance: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] pub upscaler: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub fsr_sharpness: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")] pub vsr_quality: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")] pub framegen: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub framegen_multiplier: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")] pub target_hz: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub vfg_quality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub motion: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub ai_engine: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub steady_hud: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] pub fill: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] pub vsync: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] pub watermark: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")] pub launch_args: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")] pub env: Option<BTreeMap<String, String>>,
/// 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>,
}
/// Every setting a layer can hold, by the name it has in the file. `summit profile unset` and the editor use these.
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",
];
impl Layer {
/// A file from before layers stored every field, so "false", "" and 0 there only meant "nothing chosen": they
/// become unset, and the game follows the defaults for them. Anything else stays the game's own choice.
pub fn from_legacy(mut self) -> Self {
fn s(v: &mut Option<String>) { if v.as_deref() == Some("") { *v = None; } }
fn b(v: &mut Option<bool>) { if *v == Some(false) { *v = None; } }
fn n<T: Default + PartialEq>(v: &mut Option<T>) { if v.as_ref() == Some(&T::default()) { *v = None; } }
if self.window_mode.is_none() && self.fullscreen == Some(true) { self.window_mode = Some("borderless".into()); }
self.fullscreen = None;
s(&mut self.monitor); n(&mut self.width); n(&mut self.height); n(&mut self.refresh_hz);
s(&mut self.window_mode); b(&mut self.focus); b(&mut self.enhance); s(&mut self.upscaler); s(&mut self.framegen);
n(&mut self.framegen_multiplier); s(&mut self.model);
if self.launch_args.as_ref().is_some_and(|a| a.is_empty()) { self.launch_args = None; }
if self.env.as_ref().is_some_and(|e| e.is_empty()) { self.env = None; }
self
}
/// Put this layer over `p`. The monitor and its mode go together: a layer that picks a monitor also decides its
/// resolution and rate (left out: the monitor's own), so a game on another monitor never gets the defaults' mode.
pub fn apply(&self, p: &mut Profile) {
let text = |v: &str| if v.is_empty() { None } else { Some(v.to_string()) };
if let Some(m) = &self.monitor {
p.monitor = text(m);
p.width = None; p.height = None; p.refresh_hz = None;
}
if let Some(v) = self.width { p.width = Some(v).filter(|v| *v > 0); }
if let Some(v) = self.height { p.height = Some(v).filter(|v| *v > 0); }
if let Some(v) = self.refresh_hz { p.refresh_hz = Some(v).filter(|v| *v > 0.0); }
if let Some(v) = &self.window_mode { p.window_mode = v.clone(); }
if let Some(v) = self.focus { p.focus = v; }
if let Some(v) = self.enhance { p.enhance = v; }
if let Some(v) = &self.upscaler { p.upscaler = v.clone(); }
if let Some(v) = self.fsr_sharpness { p.fsr_sharpness = Some(v).filter(|v| *v >= 0.0); }
if let Some(v) = self.vsr_quality { p.vsr_quality = Some(v).filter(|v| *v > 0); }
if let Some(v) = &self.framegen { p.framegen = v.clone(); }
if let Some(v) = self.framegen_multiplier { p.framegen_multiplier = v; }
if let Some(v) = self.target_hz { p.target_hz = Some(v).filter(|v| *v > 0); }
if let Some(v) = &self.model { p.model = text(v); }
if let Some(v) = &self.vfg_quality { p.vfg_quality = text(v); }
if let Some(v) = &self.motion { p.motion = text(v); }
if let Some(v) = &self.ai_engine { p.ai_engine = text(v); }
if let Some(v) = self.steady_hud { p.steady_hud = Some(v); }
if let Some(v) = &self.fill { p.fill = text(v); }
if let Some(v) = self.vsync { p.vsync = Some(v); }
if let Some(v) = self.watermark { p.watermark = Some(v); }
if let Some(v) = &self.launch_args { p.launch_args = v.clone(); }
if let Some(v) = &self.env { for (k, val) in v { p.env.insert(k.clone(), val.clone()); } }
}
/// Whether this layer sets `key` (one of [`KEYS`]).
pub fn has(&self, key: &str) -> bool {
match key {
"monitor" => self.monitor.is_some(), "width" => self.width.is_some(), "height" => self.height.is_some(),
"refresh_hz" => self.refresh_hz.is_some(), "window_mode" => self.window_mode.is_some(), "focus" => self.focus.is_some(),
"enhance" => self.enhance.is_some(), "upscaler" => self.upscaler.is_some(), "fsr_sharpness" => self.fsr_sharpness.is_some(),
"vsr_quality" => self.vsr_quality.is_some(), "framegen" => self.framegen.is_some(),
"framegen_multiplier" => self.framegen_multiplier.is_some(), "target_hz" => self.target_hz.is_some(),
"model" => self.model.is_some(), "vfg_quality" => self.vfg_quality.is_some(), "motion" => self.motion.is_some(),
"ai_engine" => self.ai_engine.is_some(), "steady_hud" => self.steady_hud.is_some(), "fill" => self.fill.is_some(),
"vsync" => self.vsync.is_some(), "watermark" => self.watermark.is_some(), "launch_args" => self.launch_args.is_some(),
"env" => self.env.is_some(),
_ => false,
}
}
/// Stop setting `key`, so the layer below decides. False for an unknown key.
pub fn unset(&mut self, key: &str) -> bool {
match key {
// the mode belongs to the monitor (see apply): unsetting the monitor hands both down
"monitor" => { self.monitor = None; self.width = None; self.height = None; self.refresh_hz = None; }
"width" => self.width = None, "height" => self.height = None, "refresh_hz" => self.refresh_hz = None,
"window_mode" => self.window_mode = None, "focus" => self.focus = None, "enhance" => self.enhance = None,
"upscaler" => self.upscaler = None, "fsr_sharpness" => self.fsr_sharpness = None, "vsr_quality" => self.vsr_quality = None,
"framegen" => self.framegen = None, "framegen_multiplier" => self.framegen_multiplier = None,
"target_hz" => self.target_hz = None, "model" => self.model = None, "vfg_quality" => self.vfg_quality = None,
"motion" => self.motion = None, "ai_engine" => self.ai_engine = None, "steady_hud" => self.steady_hud = None,
"fill" => self.fill = None, "vsync" => self.vsync = None, "watermark" => self.watermark = None,
"launch_args" => self.launch_args = None, "env" => self.env = None,
_ => return false,
}
true
}
/// Sets nothing (a game that follows the defaults everywhere).
pub fn is_empty(&self) -> bool { KEYS.iter().all(|k| !self.has(k)) }
}
/// Built-in values, then each layer in order (the defaults, then the game).
pub fn resolve(layers: &[&Layer]) -> Profile {
let mut p = Profile::default();
for l in layers { l.apply(&mut p); }
p
}
pub fn dir() -> Result<PathBuf> {
Ok(dirs::config_dir().context("no config dir")?.join("summit/profiles"))
}
fn file(id: &str) -> Result<PathBuf> {
/// The file for `id`: anything but letters, digits, '-' and '_' becomes '_'.
pub fn file(id: &str) -> Result<PathBuf> {
let safe: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
Ok(dir()?.join(format!("{safe}.toml")))
}
pub fn load(id: &str) -> Result<Profile> {
let f = file(id)?;
if !f.exists() { return Ok(Profile::default()); }
Ok(toml::from_str(&std::fs::read_to_string(&f)?)?)
/// Parse one stored layer; a file without `version` is from before layers.
pub fn parse_layer(text: &str) -> Result<Layer> {
let l: Layer = toml::from_str(text)?;
Ok(if l.version.is_none() { l.from_legacy() } else { l })
}
pub fn save(id: &str, p: &Profile) -> Result<PathBuf> {
/// The layer stored for `id`. No file: an empty layer.
pub fn load_layer(id: &str) -> Result<Layer> {
let f = file(id)?;
crate::state::write_atomic(&f, toml::to_string_pretty(p)?.as_bytes())?;
if !f.exists() { return Ok(Layer::default()); }
parse_layer(&std::fs::read_to_string(&f)?).with_context(|| format!("reading {}", f.display()))
}
pub fn save_layer(id: &str, l: &Layer) -> Result<PathBuf> {
let f = file(id)?;
let l = Layer { version: Some(LAYER_VERSION), fullscreen: None, ..l.clone() };
crate::state::write_atomic(&f, toml::to_string_pretty(&l)?.as_bytes())?;
Ok(f)
}
/// Change the layer stored for `id` and save it (read first, so a change made elsewhere meanwhile is kept).
pub fn update_layer(id: &str, f: impl FnOnce(&mut Layer)) -> Result<Layer> {
let mut l = load_layer(id)?;
f(&mut l);
save_layer(id, &l)?;
Ok(l)
}
/// The launcher's defaults as a profile of their own.
pub fn load_defaults() -> Result<Profile> { Ok(resolve(&[&load_layer(DEFAULT_ID)?])) }
/// What `id` launches with: the defaults with the game's own settings on top. A defaults file that cannot be read
/// is reported and skipped, so one broken file never stops every game.
pub fn load(id: &str) -> Result<Profile> {
let own = load_layer(id)?;
if id == DEFAULT_ID { return Ok(resolve(&[&own])); }
let defaults = load_layer(DEFAULT_ID).unwrap_or_else(|e| { eprintln!("note: the default profile is skipped: {e:#}"); Layer::default() });
Ok(resolve(&[&defaults, &own]))
}
/// `KEY=VALUE` as a pair. The key must look like an environment variable name.
pub fn parse_env(s: &str) -> Result<(String, String), String> {
let (k, v) = s.split_once('=').ok_or_else(|| format!("{s:?} is not KEY=VALUE"))?;
let k = k.trim();
let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !ok { return Err(format!("{k:?} is not a variable name (letters, digits and _)")); }
Ok((k.to_string(), v.to_string()))
}
/// Split a line of launch arguments like a shell would for plain words and quotes: `-w "My Save" --x=1`.
pub fn split_args(s: &str) -> Vec<String> {
let (mut out, mut cur, mut quote, mut any) = (vec![], String::new(), None::<char>, false);
let mut chars = s.chars();
while let Some(c) = chars.next() {
match (quote, c) {
(None, '"' | '\'') => { quote = Some(c); any = true; }
(Some(q), c) if c == q => quote = None,
(q, '\\') if q != Some('\'') => { if let Some(n) = chars.next() { cur.push(n); any = true; } }
(None, c) if c.is_whitespace() => { if any { out.push(std::mem::take(&mut cur)); any = false; } }
(_, c) => { cur.push(c); any = true; }
}
}
if any { out.push(cur); }
out
}
/// The reverse of [`split_args`], for showing and editing: words with spaces or quotes are quoted.
pub fn join_args(a: &[String]) -> String {
a.iter().map(|w| {
if !w.is_empty() && !w.chars().any(|c| c.is_whitespace() || c == '"' || c == '\'' || c == '\\') { w.clone() }
else { format!("\"{}\"", w.replace('\\', "\\\\").replace('"', "\\\"")) }
}).collect::<Vec<_>>().join(" ")
}
/// Environment variables as one line, `A=1 B="two words"`, and back ([`parse_env_line`]).
pub fn join_env(e: &BTreeMap<String, String>) -> String {
join_args(&e.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>())
}
pub fn parse_env_line(s: &str) -> Result<BTreeMap<String, String>, String> {
split_args(s).iter().map(|w| parse_env(w)).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_toml() {
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(60.0), fullscreen: true, focus: true, upscaler: "fsr".into(), framegen: "rife".into(), framegen_multiplier: 2, launch_args: vec![], target_hz: Some(90), model: None, enhance: true };
let s = toml::to_string_pretty(&p).unwrap();
assert_eq!(toml::from_str::<Profile>(&s).unwrap(), p);
fn layer_roundtrip_writes_only_what_is_set() {
let l = Layer { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), window_mode: Some("fullscreen".into()), upscaler: Some("fsr".into()), env: Some([("MANGOHUD".to_string(), "1".to_string())].into()), ..Default::default() };
let s = toml::to_string_pretty(&l).unwrap();
assert!(!s.contains("focus") && !s.contains("framegen"), "{s}");
assert_eq!(toml::from_str::<Layer>(&s).unwrap(), l);
}
}
#[cfg(test)]
mod compat {
#[test]
fn old_files_without_enhance_still_load() {
let p: super::Profile = toml::from_str("upscaler = \"fsr\"\nframegen = \"rife\"\n").unwrap();
fn games_follow_the_defaults_until_they_set_their_own() {
let d = Layer { upscaler: Some("fsr".into()), framegen: Some("rife".into()), window_mode: Some("borderless".into()), enhance: Some(true), env: Some([("A".to_string(), "1".to_string()), ("B".to_string(), "2".to_string())].into()), ..Default::default() };
let g = Layer { upscaler: Some("rtx-vsr".into()), enhance: Some(false), env: Some([("B".to_string(), "3".to_string())].into()), ..Default::default() };
let p = resolve(&[&d, &g]);
assert_eq!((p.upscaler.as_str(), p.framegen.as_str(), p.window_mode.as_str(), p.enhance), ("rtx-vsr", "rife", "borderless", false));
assert_eq!(p.env.get("A").map(String::as_str), Some("1"));
assert_eq!(p.env.get("B").map(String::as_str), Some("3"));
assert!(p.fullscreen());
}
#[test]
fn a_monitor_brings_its_own_mode() {
let d = Layer { monitor: Some("DP-1".into()), width: Some(2560), height: Some(1440), refresh_hz: Some(144.0), ..Default::default() };
let tv = Layer { monitor: Some("HDMI-A-1".into()), ..Default::default() };
let p = resolve(&[&d, &tv]);
assert_eq!((p.monitor.as_deref(), p.width, p.refresh_hz), (Some("HDMI-A-1"), None, None));
// an empty monitor in a game: never switch, even if the defaults do
let stay = Layer { monitor: Some(String::new()), ..Default::default() };
assert_eq!(resolve(&[&d, &stay]).monitor, None);
// no monitor in the game: the defaults' monitor and mode
let p = resolve(&[&d, &Layer::default()]);
assert_eq!((p.monitor.as_deref(), p.width, p.height), (Some("DP-1"), Some(2560), Some(1440)));
}
#[test]
fn empty_and_zero_override_with_not_chosen() {
let d = Layer { model: Some("4.25".into()), target_hz: Some(120), upscaler: Some("fsr".into()), ..Default::default() };
let g = Layer { model: Some(String::new()), target_hz: Some(0), upscaler: Some(String::new()), ..Default::default() };
let p = resolve(&[&d, &g]);
assert_eq!((p.model, p.target_hz, p.upscaler.as_str()), (None, None, ""));
}
#[test]
fn old_files_become_layers() {
// as the launcher wrote them before layers: every field, false/""/0 meaning nothing chosen
let old = "fullscreen = true\nfocus = false\nupscaler = \"\"\nframegen = \"rife\"\nframegen_multiplier = 0\nlaunch_args = []\nenhance = false\n";
let l = parse_layer(old).unwrap();
assert_eq!(l, Layer { window_mode: Some("borderless".into()), framegen: Some("rife".into()), ..Default::default() });
// so the defaults reach what the old file never chose
let d = Layer { upscaler: Some("fsr".into()), enhance: Some(true), ..Default::default() };
let p = resolve(&[&d, &l]);
assert_eq!((p.upscaler.as_str(), p.enhance, p.window_mode.as_str()), ("fsr", true, "borderless"));
// older still: no enhance key at all
let p = resolve(&[&parse_layer("upscaler = \"fsr\"\nframegen = \"rife\"\n").unwrap()]);
assert!(!p.enhance);
assert_eq!(p.upscaler, "fsr");
// a new file keeps an explicit false
let l = parse_layer("version = 2\nenhance = false\n").unwrap();
assert_eq!(l.enhance, Some(false));
}
#[test]
fn unset_hands_a_setting_down() {
let mut l = Layer { monitor: Some("DP-1".into()), width: Some(1920), height: Some(1080), focus: Some(true), ..Default::default() };
assert!(l.has("focus") && l.unset("focus") && !l.has("focus"));
assert!(l.unset("monitor"));
assert!(l.is_empty(), "{l:?}");
assert!(!l.unset("nonsense"));
for k in KEYS { assert!(!Layer::default().has(k)); }
}
#[test]
fn args_and_env_lines() {
assert_eq!(split_args(r#"-w "My Save" --x=1 '' a\ b"#), vec!["-w", "My Save", "--x=1", "", "a b"]);
assert!(split_args(" ").is_empty());
let a = vec!["-w".to_string(), "My Save".into(), "".into(), "x\"y".into()];
assert_eq!(split_args(&join_args(&a)), a);
let e = parse_env_line("MANGOHUD=1 DXVK_HUD=\"fps,gpuload\" EMPTY=").unwrap();
assert_eq!(e.get("DXVK_HUD").map(String::as_str), Some("fps,gpuload"));
assert_eq!(e.get("EMPTY").map(String::as_str), Some(""));
assert_eq!(parse_env_line(&join_env(&e)).unwrap(), e);
assert!(parse_env_line("NOEQUALS").is_err());
assert!(parse_env_line("1X=2").is_err());
assert!(parse_env_line("A-B=2").is_err());
}
}
+229
View File
@@ -0,0 +1,229 @@
//! Whether a game is running, for the launcher's "now playing" screen.
//!
//! A game Summit starts itself is a child process: the launcher waits for it. A game handed to another launcher
//! (Steam, Lutris, Heroic) is not: the command that starts it returns at once. Those launchers mark the game's
//! processes, though, and /proc shows the marks:
//!
//! * Steam: `SteamAppId=<id>` and `SteamGameId=<id>` in the environment (a non-Steam game: `SteamGameId` only,
//! the long id of its `steam://rungameid/` link), and an `AppId=<id>` argument on Steam's own wrapper process.
//! * Lutris: `LUTRIS_GAME_UUID` (a new one for each start, so processes that were already there are left out).
//! * Heroic: `HEROIC_APP_NAME=<app name>`. Not checked against a running Heroic game yet.
//!
//! Reading /proc and the rules ([`Tracker`]) are pure and unit tested; the launcher polls.
use crate::model::{Entry, Source};
use std::collections::HashSet;
use std::path::Path;
use std::time::{Duration, Instant};
/// How a game's processes are told from the rest.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Marker {
/// Environment entries, whole: `SteamAppId=620`.
pub env: Vec<String>,
/// Environment names, with any value: `LUTRIS_GAME_UUID`.
pub env_names: Vec<String>,
/// Command line arguments, whole: `AppId=620`.
pub args: Vec<String>,
}
/// The marks `e`'s processes carry once its own launcher has started it, or None for an entry Summit starts
/// itself (its process is the launcher's child, so nothing needs looking for).
pub fn marker(e: &Entry) -> Option<Marker> {
match e.source {
Source::Steam => {
let id = match e.steam_app_id {
Some(id) => id.to_string(),
None => e.launch_uri.as_deref()?.rsplit('/').next().filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))?.to_string(),
};
let mut m = Marker { env: vec![format!("SteamGameId={id}")], args: vec![format!("AppId={id}")], ..Default::default() };
if e.steam_app_id.is_some() { m.env.push(format!("SteamAppId={id}")); }
Some(m)
}
Source::Lutris => Some(Marker { env_names: vec!["LUTRIS_GAME_UUID".into()], ..Default::default() }),
Source::Heroic => {
let uri = e.launch_uri.as_deref()?;
let name = uri.split(['?', '&']).find_map(|kv| kv.strip_prefix("appName="))?;
Some(Marker { env: vec![format!("HEROIC_APP_NAME={}", percent_decode(name))], ..Default::default() })
}
_ => None,
}
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let (mut out, mut i) = (Vec::with_capacity(b.len()), 0);
while i < b.len() {
let hex = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
match (b[i], b.get(i + 1).copied().and_then(hex), b.get(i + 2).copied().and_then(hex)) {
(b'%', Some(h), Some(l)) => { out.push(h * 16 + l); i += 3; }
(c, _, _) => { out.push(c); i += 1; }
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn has_entry(blob: &[u8], want: &str) -> bool { blob.split(|b| *b == 0).any(|e| e == want.as_bytes()) }
fn has_name(blob: &[u8], name: &str) -> bool {
blob.split(|b| *b == 0).any(|e| e.len() > name.len() && e.starts_with(name.as_bytes()) && e[name.len()] == b'=')
}
/// The processes under `proc_dir` (normally /proc) that carry one of `m`'s marks. Processes whose environment
/// cannot be read (another user's) are skipped.
pub fn pids(proc_dir: &Path, m: &Marker) -> Vec<u32> {
let Ok(rd) = std::fs::read_dir(proc_dir) else { return vec![] };
let mut out: Vec<u32> = rd.flatten().filter_map(|d| d.file_name().to_str()?.parse::<u32>().ok()).filter(|pid| {
let dir = proc_dir.join(pid.to_string());
if !m.args.is_empty() {
if let Ok(c) = std::fs::read(dir.join("cmdline")) { if m.args.iter().any(|a| has_entry(&c, a)) { return true; } }
}
if m.env.is_empty() && m.env_names.is_empty() { return false; }
let Ok(env) = std::fs::read(dir.join("environ")) else { return false };
m.env.iter().any(|e| has_entry(&env, e)) || m.env_names.iter().any(|n| has_name(&env, n))
}).collect();
out.sort_unstable();
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
/// Not seen yet: its launcher is still starting it.
Starting,
Running,
/// It ran and its processes are gone.
Ended,
/// It never turned up in the time allowed.
NeverStarted,
}
/// Follows one start of a game through [`pids`] results.
#[derive(Debug, Clone)]
pub struct Tracker {
/// Marked processes that were there before this start (another game of the same launcher): not this game.
before: HashSet<u32>,
started: Instant,
seen: bool,
gone_since: Option<Instant>,
/// How long to wait for the first process.
pub start_timeout: Duration,
/// How long the processes must be gone before it counts as ended (a game's own launcher hands over to the
/// game, with a moment in between).
pub gone_for: Duration,
}
impl Tracker {
/// `before`: what [`pids`] gave just before the game was started.
pub fn new(before: &[u32], now: Instant) -> Self {
Self { before: before.iter().copied().collect(), started: now, seen: false, gone_since: None,
start_timeout: Duration::from_secs(120), gone_for: Duration::from_secs(2) }
}
pub fn seen(&self) -> bool { self.seen }
/// `now_pids`: what [`pids`] gives now.
pub fn step(&mut self, now_pids: &[u32], now: Instant) -> Phase {
if now_pids.iter().any(|p| !self.before.contains(p)) {
self.seen = true;
self.gone_since = None;
return Phase::Running;
}
if !self.seen {
return if now.duration_since(self.started) >= self.start_timeout { Phase::NeverStarted } else { Phase::Starting };
}
let since = *self.gone_since.get_or_insert(now);
if now.duration_since(since) >= self.gone_for { Phase::Ended } else { Phase::Running }
}
}
/// "12 min", "1 h 05 min": how long a game has been running, for the "now playing" screen.
pub fn elapsed_label(secs: u64) -> String {
let m = secs / 60;
if m < 1 { "less than a minute".into() } else if m < 60 { format!("{m} min") } else { format!("{} h {:02} min", m / 60, m % 60) }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Kind;
fn entry(source: Source, app: Option<u32>, uri: Option<&str>) -> Entry {
Entry { id: "x".into(), title: "X".into(), source, kind: Kind::Game, installed: true, path: None, steam_app_id: app,
playtime_minutes: 0, last_played: None, reasons: vec![], launch_uri: uri.map(String::from) }
}
fn fake_proc(name: &str, procs: &[(u32, &[u8], &[u8])]) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("summit-running-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
for (pid, env, cmd) in procs {
let p = d.join(pid.to_string());
std::fs::create_dir_all(&p).unwrap();
std::fs::write(p.join("environ"), env).unwrap();
std::fs::write(p.join("cmdline"), cmd).unwrap();
}
std::fs::create_dir_all(d.join("self")).unwrap(); // not a pid
d
}
#[test]
fn markers_per_launcher() {
let m = marker(&entry(Source::Steam, Some(620), None)).unwrap();
assert_eq!(m.env, vec!["SteamGameId=620", "SteamAppId=620"]);
assert_eq!(m.args, vec!["AppId=620"]);
// a non-Steam game in the Steam library: the long id of its link
let m = marker(&entry(Source::Steam, None, Some("steam://rungameid/12345678901234567890"))).unwrap();
assert_eq!(m.env, vec!["SteamGameId=12345678901234567890"]);
assert_eq!(marker(&entry(Source::Steam, None, Some("steam://rungameid/"))), None);
assert_eq!(marker(&entry(Source::Lutris, None, Some("lutris:rungameid/7"))).unwrap().env_names, vec!["LUTRIS_GAME_UUID"]);
let m = marker(&entry(Source::Heroic, None, Some("heroic://launch?appName=Quail%20Two&runner=legendary"))).unwrap();
assert_eq!(m.env, vec!["HEROIC_APP_NAME=Quail Two"]);
assert_eq!(marker(&entry(Source::Custom, None, None)), None);
assert_eq!(marker(&entry(Source::Console, None, None)), None);
}
#[test]
fn finds_marked_processes_only() {
let d = fake_proc("find", &[
(10, b"HOME=/h\0SteamAppId=620\0SteamGameId=620\0", b"/game/portal2\0-novid\0"),
(11, b"HOME=/h\0SteamAppId=6200\0", b"other\0"), // another game: not a prefix match
(12, b"HOME=/h\0", b"reaper\0SteamLaunch\0AppId=620\0--\0game\0"), // Steam's wrapper, by its argument
(13, b"HOME=/h\0LUTRIS_GAME_UUID=abc\0", b"wine\0"),
(14, b"HOME=/h\0NOT_LUTRIS_GAME_UUID=1\0LUTRIS_GAME_UUIDX=1\0", b"x\0"),
]);
let steam = marker(&entry(Source::Steam, Some(620), None)).unwrap();
assert_eq!(pids(&d, &steam), vec![10, 12]);
assert_eq!(pids(&d, &marker(&entry(Source::Lutris, None, None)).unwrap()), vec![13]);
assert_eq!(pids(&d, &Marker::default()), Vec::<u32>::new());
assert_eq!(pids(Path::new("/nonexistent-summit"), &steam), Vec::<u32>::new());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn tracker_waits_for_the_game_then_for_it_to_go() {
let t0 = Instant::now();
let s = |n: u64| t0 + Duration::from_secs(n);
let mut t = Tracker::new(&[5], t0); // 5: another Lutris game, already running
assert_eq!(t.step(&[5], s(1)), Phase::Starting);
assert_eq!(t.step(&[5, 40], s(10)), Phase::Running);
assert!(t.seen());
assert_eq!(t.step(&[5], s(20)), Phase::Running); // gone, but only just: its launcher may be handing over
assert_eq!(t.step(&[5, 41], s(21)), Phase::Running); // the game itself
assert_eq!(t.step(&[5], s(30)), Phase::Running);
assert_eq!(t.step(&[5], s(31)), Phase::Running);
assert_eq!(t.step(&[5], s(32)), Phase::Ended);
}
#[test]
fn tracker_gives_up_on_a_game_that_never_starts() {
let t0 = Instant::now();
let mut t = Tracker::new(&[], t0);
assert_eq!(t.step(&[], t0 + Duration::from_secs(119)), Phase::Starting);
assert_eq!(t.step(&[], t0 + Duration::from_secs(120)), Phase::NeverStarted);
assert!(!t.seen());
}
#[test]
fn elapsed_labels() {
assert_eq!(elapsed_label(0), "less than a minute");
assert_eq!(elapsed_label(59), "less than a minute");
assert_eq!(elapsed_label(60), "1 min");
assert_eq!(elapsed_label(59 * 60 + 59), "59 min");
assert_eq!(elapsed_label(3900), "1 h 05 min");
}
}
+29 -3
View File
@@ -86,12 +86,17 @@ pub fn walk(root: &Path, depth: usize, out: &mut Vec<Entry>) {
}
}
/// Everything: Steam, Heroic, Lutris, plus heuristic walk of `extra` folders (deduped against known paths).
/// Everything: Steam (its games and the non-Steam games added to it), Heroic, Lutris, plus heuristic walk of
/// `extra` folders (deduped against known paths).
pub fn full(extra: &[std::path::PathBuf], depth: usize) -> Vec<Entry> {
let mut all = crate::steam::scan();
all.extend(crate::epic::heroic());
all.extend(crate::epic::lutris());
all.extend(crate::state::custom_entries(&crate::state::load()));
all.extend(crate::lutris::scan());
let st = crate::state::load();
all.extend(crate::state::custom_entries(&st));
all.extend(crate::state::console_entries(&st));
let shortcuts = crate::shortcuts::scan();
all.extend(new_shortcuts(shortcuts, &all));
let known: Vec<String> = all.iter().filter_map(|e| e.path.clone()).collect();
let mut found = Vec::new();
for r in extra { walk(r, depth, &mut found); }
@@ -99,6 +104,15 @@ pub fn full(extra: &[std::path::PathBuf], depth: usize) -> Vec<Entry> {
all
}
/// Non-Steam games in Steam that are not already listed from somewhere else: a game added to Steam and to Lutris
/// (or to Summit by hand) is listed once, as the other entry, which Summit can track. Same title or same program.
fn new_shortcuts(shortcuts: Vec<Entry>, known: &[Entry]) -> Vec<Entry> {
let norm = |t: &str| t.trim().to_lowercase();
shortcuts.into_iter().filter(|s| {
!known.iter().any(|k| norm(&k.title) == norm(&s.title) || (k.path.is_some() && k.path == s.path))
}).collect()
}
/// Heuristic finds that are not already known: inside a known path, or holding one (a custom entry's run.sh).
/// Compared by path components, so a known `/games/Foo` does not hide `/games/FooBar`.
fn dedupe(found: Vec<Entry>, known: &[String]) -> Vec<Entry> {
@@ -133,6 +147,18 @@ mod tests {
assert_eq!(kept, vec!["/games/FooBar", "/games/Baz"]);
}
#[test]
fn shortcuts_already_listed_elsewhere_are_dropped() {
let e = |id: &str, t: &str, p: Option<&str>| Entry { id: id.into(), title: t.into(), source: Source::Steam, kind: Kind::Game, installed: true, path: p.map(Into::into), steam_app_id: None, playtime_minutes: 0, last_played: None, launch_uri: None, reasons: vec![] };
let known = vec![e("lutris:mw2", "MW2", Some("/g/iw4l.exe")), e("custom:voidrunner", "Voidrunner", Some("/v/run.sh")), e("steam:1", "Other", None)];
let kept: Vec<String> = new_shortcuts(vec![
e("steam-shortcut:1", "MW2 + Skate", Some("/g/iw4l.exe")),
e("steam-shortcut:2", "voidrunner ", Some("/v/steam-launch.sh")),
e("steam-shortcut:3", "New Game", Some("/n/game.exe")),
e("steam-shortcut:4", "No Path", None),
], &known).into_iter().map(|x| x.id).collect();
assert_eq!(kept, vec!["steam-shortcut:3", "steam-shortcut:4"]);
}
#[test]
fn missing_and_odd_dirs_find_nothing() {
let mut out = vec![]; walk(Path::new("/nonexistent/summit"), 3, &mut out); assert!(out.is_empty());
let d = tmp("odd"); use std::os::unix::ffi::OsStrExt;
+75
View File
@@ -126,6 +126,62 @@ fn renumber(map: &mut [(String, BVal)]) {
for (i, (k, _)) in map.iter_mut().enumerate() { *k = i.to_string(); }
}
// ---- reading: the non-Steam games in the user's Steam library, as library entries ----
/// The entry id of a non-Steam shortcut: its 32-bit app id, which also names its grid art.
pub fn entry_id(appid: u32) -> String { format!("steam-shortcut:{appid}") }
/// The app id in a `steam-shortcut:<appid>` entry id.
pub fn appid_of(entry_id: &str) -> Option<u32> { entry_id.strip_prefix("steam-shortcut:")?.parse().ok() }
/// The non-Steam games added to Steam, from every local account's `shortcuts.vdf` (the most recently used
/// account first; a game added on two accounts is listed once). Hidden ones and Summit's own shortcuts
/// (`summit steam-add`, which run `summit` itself) are left out.
pub fn scan() -> Vec<crate::model::Entry> {
let mut out: Vec<crate::model::Entry> = Vec::new();
for u in crate::steam::userdata_dirs() {
let f = u.join("config/shortcuts.vdf");
let Ok(bytes) = std::fs::read(&f) else { continue };
let Ok(root) = vdf_bin::parse(&bytes) else { continue };
for e in entries_in(&root, &f) {
if !out.iter().any(|o| o.id == e.id) { out.push(e); }
}
}
out
}
/// The shortcuts of one parsed `shortcuts.vdf` as entries. `file` is only named in the reasons.
pub fn entries_in(root: &[(String, BVal)], file: &Path) -> Vec<crate::model::Entry> {
use crate::model::{Entry, Kind, Source};
let mut out: Vec<Entry> = Vec::new();
for (_, v) in shortcuts_ref(root) {
let Some(m) = v.map() else { continue };
let s = |k: &str| find_field(m, k).and_then(|v| v.str()).unwrap_or("").to_string();
let n = |k: &str| find_field(m, k).and_then(|v| v.int32()).unwrap_or(0);
let (name, exe_raw) = (s("AppName"), s("Exe"));
if name.trim().is_empty() || n("IsHidden") != 0 { continue; }
let exe = exe_raw.trim().trim_matches('"').to_string();
if Path::new(&exe).file_name().is_some_and(|f| f == "summit") { continue; }
// Old files may lack the id; Steam derives it the same way.
let appid = match n("appid") { 0 => legacy_app_id(&exe_raw, &name), a => a as u32 };
let id = entry_id(appid);
if out.iter().any(|o| o.id == id) { continue; }
// A command rather than a file path (`flatpak run ...`, `env ...`) is taken as present.
let installed = !exe.starts_with('/') || Path::new(&exe).exists();
let last = n("LastPlayTime");
let mut reasons = vec![format!("non-Steam game in your Steam library ({})", file.display())];
if !exe.is_empty() { reasons.push(format!("Steam runs {exe}")); }
if !installed { reasons.push("that file is not there any more".into()); }
out.push(Entry {
id, title: name.trim().to_string(), source: Source::Steam, kind: Kind::Game, installed,
path: (!exe.is_empty()).then_some(exe), steam_app_id: None, playtime_minutes: 0,
last_played: (last > 0).then_some(last as u64), reasons,
launch_uri: Some(format!("steam://rungameid/{}", grid_app_id(appid))),
});
}
out
}
// ---- file I/O: backup, and refuse to write while Steam runs unless forced ----
pub fn backup_path(p: &Path) -> PathBuf {
@@ -359,6 +415,25 @@ mod tests {
assert_eq!(find_field(e, "SomeFutureField").unwrap().int32(), Some(99));
}
#[test]
fn shortcuts_become_library_entries() {
let mut root = empty_root();
let a = add_shortcut(&mut root, &NewShortcut { app_name: "Voidrunner", exe: "\"/nonexistent/summit-test/run.sh\"", launch_options: "", start_dir: "", icon: "" });
add_shortcut(&mut root, &NewShortcut { app_name: "My PS5", exe: "\"/usr/local/bin/summit\"", launch_options: "run ps5", start_dir: "", icon: "" });
add_shortcut(&mut root, &NewShortcut { app_name: "Flatpak Game", exe: "flatpak", launch_options: "run x", start_dir: "", icon: "" });
add_shortcut(&mut root, &NewShortcut { app_name: "Hidden", exe: "/bin/true", launch_options: "", start_dir: "", icon: "" });
if let Some((_, BVal::Map(m))) = ensure_shortcuts(&mut root).last_mut() {
for (k, v) in m.iter_mut() { if k == "IsHidden" { *v = BVal::Int32(1); } }
}
let es = entries_in(&root, Path::new("/x/shortcuts.vdf"));
let got: Vec<_> = es.iter().map(|e| (e.id.clone(), e.title.as_str(), e.installed)).collect();
assert_eq!(got, vec![(entry_id(a), "Voidrunner", false), (entry_id(legacy_app_id("flatpak", "Flatpak Game")), "Flatpak Game", true)]);
assert_eq!(es[0].path.as_deref(), Some("/nonexistent/summit-test/run.sh"));
assert_eq!(es[0].launch_uri, Some(format!("steam://rungameid/{}", grid_app_id(a))));
assert_eq!(appid_of(&es[0].id), Some(a));
assert_eq!(appid_of("steam:620"), None);
}
#[test]
fn full_roundtrip_through_a_file() {
let d = tmp("roundtrip");
+41 -7
View File
@@ -19,6 +19,11 @@ pub struct State {
pub pinned: Vec<String>,
pub artwork: HashMap<String, String>,
pub tracked: HashMap<String, Tracked>,
/// Consoles added from the launcher's Add a game (or `summit console add-*`): Remote Play and capture cards.
pub consoles: Vec<crate::console::Console>,
/// The Steam account (SteamID64, as text) a Steam game starts on, by entry id. A game not listed starts on the
/// account it was last played on (steam_account.rs).
pub steam_accounts: HashMap<String, String>,
}
/// A path as the text stored in `state.json`. JSON holds UTF-8 only, and a lossy copy (U+FFFD for the odd bytes)
@@ -52,6 +57,21 @@ pub fn add_custom(title: &str, path: &std::path::Path, software: bool) -> Result
Ok(id)
}
/// Add (or replace, same id) a console entry. Returns its id.
pub fn add_console(c: crate::console::Console) -> Result<String> {
let id = c.id.clone();
update(|st| { st.consoles.retain(|x| x.id != id); st.consoles.push(c); })?;
Ok(id)
}
/// Remove a console entry; false if there was none with that id. Its tracked time and pin are left (so adding it
/// again brings them back).
pub fn remove_console(id: &str) -> Result<bool> {
let mut removed = false;
update(|st| { let n = st.consoles.len(); st.consoles.retain(|x| x.id != id); removed = st.consoles.len() != n; })?;
Ok(removed)
}
/// A name for a game from the file picked to start it: its folder's name, unless that folder is a generic one
/// (`bin`, `x86_64`, `Binaries/Linux`...), then the next folder up; the file name if no folder fits.
pub fn title_guess(file: &std::path::Path) -> String {
@@ -110,6 +130,12 @@ impl State {
pub fn hero_art(&self, id: &str) -> Option<&str> { self.artwork.get(&format!("{id}#hero")).map(String::as_str) }
/// Custom logo (transparent title image), stored under "<id>#logo".
pub fn logo_art(&self, id: &str) -> Option<&str> { self.artwork.get(&format!("{id}#logo")).map(String::as_str) }
/// The Steam account chosen for an entry (SteamID64), if any.
pub fn steam_account(&self, id: &str) -> Option<u64> { self.steam_accounts.get(id).and_then(|s| s.parse().ok()) }
/// Choose the Steam account an entry starts on; None: the account it was last played on.
pub fn set_steam_account(&mut self, id: &str, steam_id: Option<u64>) {
match steam_id { Some(n) => { self.steam_accounts.insert(id.into(), n.to_string()); } None => { self.steam_accounts.remove(id); } }
}
pub fn record_session(&mut self, id: &str, seconds: u64, now: u64) {
let t = self.tracked.entry(id.into()).or_default();
t.seconds += seconds; t.sessions += 1; t.last_played = now;
@@ -127,12 +153,17 @@ pub fn custom_entries(st: &State) -> Vec<crate::model::Entry> {
}).collect()
}
/// Steam keeps its own authoritative count for Steam games, so those use Steam's number.
/// Everything else (Heroic, Lutris, software, .exe) uses Summit's tracked sessions.
/// Never summed: that would double count Steam titles launched through Summit.
pub fn console_entries(st: &State) -> Vec<crate::model::Entry> { st.consoles.iter().map(|c| c.entry()).collect() }
/// Steam keeps its own authoritative count for Steam games, and Lutris for its games (it times the game itself,
/// also when Summit starts it), so those use the launcher's number. Everything else (non-Steam games in Steam,
/// Heroic, software, .exe) uses Summit's tracked sessions.
/// Never summed: that would double count titles launched through Summit.
pub fn apply(entries: &mut [crate::model::Entry], st: &State) {
use crate::model::Source;
for e in entries.iter_mut() {
if e.source != crate::model::Source::Steam {
let launcher_counts = (e.source == Source::Steam && e.steam_app_id.is_some()) || e.source == Source::Lutris;
if !launcher_counts {
if let Some(t) = st.tracked.get(&e.id) {
e.playtime_minutes = t.seconds / 60;
if t.last_played > 0 { e.last_played = Some(t.last_played); }
@@ -181,11 +212,14 @@ mod tests {
fn steam_not_double_counted_others_tracked() {
let mut st = State::default();
st.record_session("steam:1", 6000, 5); st.record_session("lutris:x", 7200, 9);
let mut v = vec![entry("steam:1", Source::Steam, 30), entry("lutris:x", Source::Lutris, 0)];
st.record_session("steam-shortcut:7", 600, 4); st.record_session("heroic:epic:q", 1200, 3);
let mut steam = entry("steam:1", Source::Steam, 30); steam.steam_app_id = Some(1);
let mut v = vec![steam, entry("lutris:x", Source::Lutris, 45), entry("steam-shortcut:7", Source::Steam, 0), entry("heroic:epic:q", Source::Heroic, 0)];
apply(&mut v, &st);
assert_eq!(v[0].playtime_minutes, 30);
assert_eq!(v[1].playtime_minutes, 120);
assert_eq!(v[1].last_played, Some(9));
assert_eq!((v[1].playtime_minutes, v[1].last_played), (45, None));
assert_eq!((v[2].playtime_minutes, v[2].last_played), (10, Some(4)));
assert_eq!((v[3].playtime_minutes, v[3].last_played), (20, Some(3)));
}
#[test]
fn toggle_pin_and_extra_art_keys() {
+64 -15
View File
@@ -58,18 +58,37 @@ pub fn playtime(root: &Path) -> HashMap<u32, (u64, u64)> {
map
}
/// Every `userdata/<id>` folder across all detected Steam installs (one per local Steam account).
/// Every `userdata/<id>` folder across all detected Steam installs (one per local Steam account), the account used
/// most recently first (by when Steam last wrote its localconfig.vdf), so its art wins where accounts differ.
pub fn userdata_dirs() -> Vec<PathBuf> {
let mut out = Vec::new();
let mut out: Vec<(std::time::SystemTime, PathBuf)> = Vec::new();
for root in steam_roots() {
let Ok(rd) = std::fs::read_dir(root.join("userdata")) else { continue };
for e in rd.flatten() {
if e.path().is_dir() && e.file_name().to_string_lossy().chars().all(|c| c.is_ascii_digit()) {
out.push(e.path());
let name = e.file_name().to_string_lossy().into_owned();
// "0" is a placeholder folder Steam makes before anyone logs in
if e.path().is_dir() && !name.is_empty() && name != "0" && name.chars().all(|c| c.is_ascii_digit()) {
let used = std::fs::metadata(e.path().join("config/localconfig.vdf")).or_else(|_| e.metadata())
.and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
out.push((used, e.path()));
}
}
}
out
out.sort_by_key(|(used, _)| std::cmp::Reverse(*used));
out.into_iter().map(|(_, p)| p).collect()
}
/// Art set by hand in Steam ("Manage > Set custom artwork"), or installed for a non-Steam shortcut:
/// `userdata/<user>/config/grid/<id><suffix>.<ext>`. `id` is a Steam app id or a shortcut's 32-bit app id.
pub fn grid_art(id: u32, kind: crate::shortcuts::ArtKind) -> Option<PathBuf> {
let grids: Vec<PathBuf> = userdata_dirs().into_iter().map(|u| u.join("config/grid")).collect();
grid_art_in(&grids, id, kind)
}
pub fn grid_art_in(grids: &[PathBuf], id: u32, kind: crate::shortcuts::ArtKind) -> Option<PathBuf> {
grids.iter().find_map(|g| {
["png", "jpg", "jpeg", "webp"].iter().map(|x| g.join(crate::shortcuts::grid_filename(id as u64, kind, x))).find(|p| p.is_file())
})
}
fn is_tool(name: &str) -> bool {
@@ -135,27 +154,30 @@ pub fn scan() -> Vec<Entry> {
out
}
/// First of `names` that exists for `app_id` under one Steam root's library cache.
/// First of `names` that exists for `app_id` under one Steam root's library cache. The order of `names` is the
/// preference: each name is looked for at the top and in the sub-folders before the next name is tried.
/// Newer clients nest the files in a hash folder, so one level of sub-folders is checked too.
pub fn art_in(root: &Path, app_id: u32, names: &[&str]) -> Option<PathBuf> {
let d = root.join("appcache/librarycache").join(app_id.to_string());
for n in names {
if d.join(n).is_file() { return Some(d.join(n)); }
}
let mut subs: Vec<PathBuf> = std::fs::read_dir(&d).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
subs.sort();
for n in names {
for sub in &subs {
if sub.join(n).is_file() { return Some(sub.join(n)); }
}
if d.join(n).is_file() { return Some(d.join(n)); }
if let Some(p) = subs.iter().map(|s| s.join(n)).find(|p| p.is_file()) { return Some(p); }
}
None
}
fn art(app_id: u32, names: &[&str]) -> Option<PathBuf> { steam_roots().iter().find_map(|r| art_in(r, app_id, names)) }
/// Cover art from Steam's own library cache (portrait 600x900 preferred, then header). Works without network.
pub fn cover(app_id: u32) -> Option<PathBuf> { art(app_id, &["library_600x900.jpg", "header.jpg"]) }
/// Portrait capsule names: older clients cache `library_600x900.jpg`, newer ones `library_capsule.jpg`.
const PORTRAIT: [&str; 2] = ["library_600x900.jpg", "library_capsule.jpg"];
/// Wide capsule names: older clients cache `header.jpg`, newer ones `library_header.jpg`.
const WIDE: [&str; 2] = ["header.jpg", "library_header.jpg"];
/// Cover art from Steam's own library cache (the portrait capsule preferred, then the wide header). Works without
/// network.
pub fn cover(app_id: u32) -> Option<PathBuf> { art(app_id, &[PORTRAIT[0], PORTRAIT[1], WIDE[0], WIDE[1]]) }
/// Wide background art (library_hero.jpg) for the Big Picture backdrop. No fallback: callers blur the cover instead.
pub fn hero(app_id: u32) -> Option<PathBuf> { art(app_id, &["library_hero.jpg"]) }
@@ -164,7 +186,7 @@ pub fn hero(app_id: u32) -> Option<PathBuf> { art(app_id, &["library_hero.jpg"])
pub fn logo(app_id: u32) -> Option<PathBuf> { art(app_id, &["logo.png"]) }
/// Wide library capsule (header.jpg), distinct from the portrait cover.
pub fn wide(app_id: u32) -> Option<PathBuf> { art(app_id, &["header.jpg"]) }
pub fn wide(app_id: u32) -> Option<PathBuf> { art(app_id, &WIDE) }
#[cfg(test)]
mod tests {
@@ -194,5 +216,32 @@ mod tests {
assert_eq!(art_in(&r, 271590, &["library_hero.jpg"]), Some(d.join("bbb/library_hero.jpg")));
}
#[test]
fn newer_client_names_are_found() {
// what the 2025+ client writes: every file in its own hash folder, new names for the capsules
let r = root("newnames"); let d = r.join("appcache/librarycache/620980");
for (sub, n) in [("aa", "library_header.jpg"), ("bb", "library_capsule.jpg"), ("cc", "library_hero.jpg")] {
fs::create_dir_all(d.join(sub)).unwrap(); fs::write(d.join(sub).join(n), b"x").unwrap();
}
let cover = [PORTRAIT[0], PORTRAIT[1], WIDE[0], WIDE[1]];
assert_eq!(art_in(&r, 620980, &cover), Some(d.join("bb/library_capsule.jpg")));
assert_eq!(art_in(&r, 620980, &WIDE), Some(d.join("aa/library_header.jpg")));
// a top-level header does not beat a nested portrait
fs::write(d.join("header.jpg"), b"x").unwrap();
assert_eq!(art_in(&r, 620980, &cover), Some(d.join("bb/library_capsule.jpg")));
}
#[test]
fn grid_art_by_id_and_kind() {
use crate::shortcuts::ArtKind;
let a = root("grid-a"); let b = root("grid-b");
fs::write(b.join("3604730456p.png"), b"x").unwrap();
fs::write(b.join("3604730456_hero.jpg"), b"x").unwrap();
fs::write(a.join("3604730456p.jpg"), b"x").unwrap();
let g = [a.clone(), b.clone()];
assert_eq!(grid_art_in(&g, 3604730456, ArtKind::Portrait), Some(a.join("3604730456p.jpg")));
assert_eq!(grid_art_in(&g, 3604730456, ArtKind::Hero), Some(b.join("3604730456_hero.jpg")));
assert_eq!(grid_art_in(&g, 3604730456, ArtKind::Logo), None);
assert_eq!(grid_art_in(&g, 620, ArtKind::Portrait), None);
}
#[test]
fn missing_app_has_no_art() { assert_eq!(art_in(&root("none"), 1, &["library_hero.jpg"]), None); }
}
+319
View File
@@ -0,0 +1,319 @@
//! Which Steam account a game starts on, and switching Steam to it.
//!
//! Steam remembers the accounts that signed in on this PC in `config/loginusers.vdf` (login name, display name,
//! whether the password is remembered) and caches their avatars in `config/avatarcache/<SteamID64>.png`. The account
//! it signs in with when it starts is `AutoLoginUser` in `registry.vdf` (`~/.steam/registry.vdf`); while it runs,
//! the signed-in account is `ActiveProcess/ActiveUser` there.
//!
//! A game can be tied to one account (state.json `steam_accounts`). Without that, it starts on the account it was
//! last played on (the newest `LastPlayed` across the accounts' `localconfig.vdf`). A game never played here starts
//! on whatever Steam is signed in with.
//!
//! Switching: when Steam runs on another account it is asked to close (`steam -shutdown`), Summit waits for it to
//! exit, then sets `AutoLoginUser` and marks the account as the most recent one in `loginusers.vdf`, so the
//! `steam steam://rungameid/<id>` that follows starts Steam on that account and the game with it. Both files are
//! copied to `<file>.summit-backup` before they are changed.
use crate::{state, vdf};
use anyhow::{bail, Context, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
/// SteamID64 of account id 0 (individual accounts, public universe). account id = SteamID64 - this.
const ID64_BASE: u64 = 76561197960265728;
/// How long Steam gets to close before the switch gives up.
const SHUTDOWN_WAIT: Duration = Duration::from_secs(60);
#[derive(Debug, Clone, PartialEq)]
pub struct Account {
pub steam_id: u64,
/// The login name (what Steam's sign-in asks for, and what `AutoLoginUser` holds).
pub account_name: String,
/// The display name others see.
pub persona_name: String,
/// Steam keeps a sign-in token for it: switching to it needs no password.
pub remember_password: bool,
/// When it last signed in (unix seconds; 0 if Steam did not say).
pub timestamp: u64,
pub avatar: Option<PathBuf>,
}
impl Account {
/// The 32-bit account id: the `userdata/<id>` folder name and what `ActiveUser` holds.
pub fn account_id(&self) -> u32 { self.steam_id.wrapping_sub(ID64_BASE) as u32 }
/// "Display name (login)".
pub fn label(&self) -> String {
if self.persona_name.is_empty() || self.persona_name == self.account_name { self.account_name.clone() }
else { format!("{} ({})", self.persona_name, self.account_name) }
}
}
/// The Steam install that holds the account list (the first with a `config/loginusers.vdf`).
pub fn root() -> Option<PathBuf> {
crate::steam::steam_roots().into_iter().find(|r| r.join("config/loginusers.vdf").is_file())
}
/// Every account Steam remembers on this PC, the one signed in most recently first.
pub fn list() -> Vec<Account> { root().map(|r| list_in(&r)).unwrap_or_default() }
pub fn list_in(root: &Path) -> Vec<Account> {
let Ok(txt) = std::fs::read_to_string(root.join("config/loginusers.vdf")) else { return vec![] };
let mut v = parse_users(&txt);
for a in &mut v {
a.avatar = ["png", "jpg"].iter().map(|x| root.join(format!("config/avatarcache/{}.{x}", a.steam_id))).find(|p| p.is_file());
}
v
}
fn parse_users(txt: &str) -> Vec<Account> {
let Ok(v) = vdf::parse(txt) else { return vec![] };
let flag = |u: &vdf::Value, k: &str| u.get(k).and_then(|x| x.str()) == Some("1");
let mut out: Vec<(bool, Account)> = v.get("users").map(|u| u.children()).unwrap_or(&[]).iter().filter_map(|(id, u)| {
let steam_id = id.parse::<u64>().ok().filter(|&n| n > ID64_BASE)?;
let s = |k: &str| u.get(k).and_then(|x| x.str()).unwrap_or("").to_string();
let account_name = s("AccountName");
if account_name.is_empty() { return None; }
let timestamp = u.get("Timestamp").and_then(|x| x.str()).and_then(|t| t.parse().ok()).unwrap_or(0);
// older clients mark the last account with MostRecent, newer ones with AutoLogin
let recent = flag(u, "MostRecent") || flag(u, "AutoLogin");
Some((recent, Account { steam_id, account_name, persona_name: s("PersonaName"), remember_password: flag(u, "RememberPassword"), timestamp, avatar: None }))
}).collect();
out.sort_by_key(|(recent, a)| std::cmp::Reverse((a.timestamp, *recent)));
out.into_iter().map(|(_, a)| a).collect()
}
/// `registry.vdf` of the Steam install at `root`: `~/.steam/registry.vdf`, or the Flatpak sandbox's own.
pub fn registry_path(root: &Path) -> PathBuf {
let s = root.to_string_lossy();
if let Some(base) = s.strip_suffix("/.local/share/Steam") {
let p = Path::new(base).join(".steam/registry.vdf");
if p.is_file() { return p; }
}
dirs::home_dir().unwrap_or_default().join(".steam/registry.vdf")
}
/// appid -> (SteamID64, LastPlayed) of the account that played it most recently, for the accounts given.
pub fn last_played_by(root: &Path, accounts: &[Account]) -> HashMap<u32, (u64, u64)> {
let mut map: HashMap<u32, (u64, u64)> = HashMap::new();
for a in accounts {
let Ok(txt) = std::fs::read_to_string(root.join(format!("userdata/{}/config/localconfig.vdf", a.account_id()))) else { continue };
let Ok(v) = vdf::parse(&txt) else { continue };
let apps = v.path(&["UserLocalConfigStore", "Software", "Valve", "Steam", "apps"]);
for (id, app) in apps.map(|x| x.children()).unwrap_or(&[]) {
let Ok(id) = id.parse::<u32>() else { continue };
let Some(lp) = app.get("LastPlayed").and_then(|p| p.str()).and_then(|s| s.parse::<u64>().ok()).filter(|&t| t > 0) else { continue };
let e = map.entry(id).or_insert((a.steam_id, lp));
if lp > e.1 { *e = (a.steam_id, lp); }
}
}
map
}
/// Why a game starts on the account it does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Why {
/// Picked for this game (state.json).
Chosen,
/// The account the game was last played on.
LastPlayed,
}
/// The account `entry_id` (`steam:<appid>`) should start on, and why. None: start on whatever Steam is signed in
/// with (never played here, or only one account, or the chosen account is no longer on this PC).
pub fn target<'a>(entry_id: &str, st: &state::State, accounts: &'a [Account], last: &HashMap<u32, (u64, u64)>) -> Option<(&'a Account, Why)> {
if accounts.len() < 2 { return None; }
if let Some(a) = st.steam_account(entry_id).and_then(|id| accounts.iter().find(|a| a.steam_id == id)) { return Some((a, Why::Chosen)); }
let app = entry_id.strip_prefix("steam:")?.parse::<u32>().ok()?;
let (id, _) = last.get(&app)?;
accounts.iter().find(|a| a.steam_id == *id).map(|a| (a, Why::LastPlayed))
}
/// Is the Steam client running (a process named `steam`)?
pub fn running() -> bool {
let Ok(rd) = std::fs::read_dir("/proc") else { return false };
rd.flatten().any(|e| {
e.file_name().to_str().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()))
&& std::fs::read_to_string(e.path().join("comm")).is_ok_and(|c| c.trim_end() == "steam")
})
}
/// The account Steam is on: while it runs, the signed-in one (`ActiveUser`), else the one it signs in with when it
/// starts (`AutoLoginUser`).
pub fn current(root: &Path, accounts: &[Account], is_running: bool) -> Option<u64> {
let txt = std::fs::read_to_string(registry_path(root)).ok()?;
current_in(&vdf::parse(&txt).ok()?, accounts, is_running)
}
fn current_in(reg: &vdf::Value, accounts: &[Account], is_running: bool) -> Option<u64> {
let steam = reg.path(&["Registry", "HKCU", "Software", "Valve", "Steam"])?;
if is_running {
let active = steam.path(&["ActiveProcess", "ActiveUser"]).and_then(|x| x.str()).and_then(|s| s.parse::<u32>().ok()).filter(|&n| n != 0);
if let Some(n) = active { return accounts.iter().find(|a| a.account_id() == n).map(|a| a.steam_id); }
}
let name = steam.get("AutoLoginUser").and_then(|x| x.str())?;
accounts.iter().find(|a| a.account_name.eq_ignore_ascii_case(name)).map(|a| a.steam_id)
}
/// Write the files so Steam signs in as `acc` the next time it starts. Steam must not be running (it writes both
/// files when it exits, over this).
pub fn set_login(root: &Path, acc: &Account) -> Result<()> {
let users_path = root.join("config/loginusers.vdf");
let txt = std::fs::read_to_string(&users_path).with_context(|| format!("could not read {}", users_path.display()))?;
let mut users = vdf::parse(&txt).map_err(|e| anyhow::anyhow!("{}: {e}", users_path.display()))?;
mark_most_recent(&mut users, acc.steam_id, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0));
let reg_path = registry_path(root);
let mut reg = match std::fs::read_to_string(&reg_path) {
Ok(t) => vdf::parse(&t).map_err(|e| anyhow::anyhow!("{}: {e}", reg_path.display()))?,
Err(_) => vdf::Value::Obj(vec![]),
};
let steam = reg.path_mut(&["Registry", "HKCU", "Software", "Valve", "Steam"]).context("registry.vdf has an unexpected layout")?;
steam.set("AutoLoginUser", &acc.account_name);
steam.set("RememberPassword", "1");
for (p, v) in [(&users_path, &users), (&reg_path, &reg)] {
if p.is_file() { let _ = std::fs::copy(p, p.with_extension("vdf.summit-backup")); }
state::write_atomic(p, vdf::to_text(v).as_bytes()).with_context(|| format!("could not write {}", p.display()))?;
}
Ok(())
}
/// In a parsed `loginusers.vdf`: `id` becomes the most recent account (and the one to sign in automatically),
/// every other one not. Uses the flags this client writes: `MostRecent` (older) and/or `AutoLogin` (newer).
fn mark_most_recent(users: &mut vdf::Value, id: u64, now: u64) {
let Some(list) = users.get_mut("users") else { return };
let has = |k: &str, l: &vdf::Value| l.children().iter().any(|(_, u)| u.get(k).is_some());
let (most, auto) = (has("MostRecent", list), has("AutoLogin", list));
let id = id.to_string();
for (k, u) in list.children_mut() {
let me = *k == id;
let on = if me { "1" } else { "0" };
if most || !auto { u.set("MostRecent", on); }
if auto { u.set("AutoLogin", on); }
if me {
if u.get("AllowAutoLogin").is_some() { u.set("AllowAutoLogin", "1"); }
if u.get("Timestamp").is_some() { u.set("Timestamp", &now.to_string()); }
}
}
}
/// What [`switch_to`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Switched { AlreadyOn, Switched }
/// Make Steam be on `acc` for the launch that follows: nothing if it already is; else close Steam if it runs
/// (`steam -shutdown`), wait for it to exit and set the account it signs in with. `say` gets progress lines.
pub fn switch_to(root: &Path, accounts: &[Account], acc: &Account, say: &dyn Fn(String)) -> Result<Switched> {
let is_running = running();
if current(root, accounts, is_running) == Some(acc.steam_id) { return Ok(Switched::AlreadyOn); }
if is_running {
say(format!("steam account: closing Steam to switch to {}", acc.label()));
shutdown();
let t = Instant::now();
while running() {
if t.elapsed() > SHUTDOWN_WAIT { bail!("Steam did not close within {} s, so it is still on the other account; close it and try again", SHUTDOWN_WAIT.as_secs()); }
std::thread::sleep(Duration::from_millis(300));
}
// the last files are written as the process ends; give the disk a moment
std::thread::sleep(Duration::from_millis(1500));
}
set_login(root, acc)?;
say(format!("steam account: Steam will sign in as {}{}", acc.label(),
if acc.remember_password { "" } else { " (Steam has no saved sign-in for it, so it will ask for the password)" }));
Ok(Switched::Switched)
}
/// Ask the running Steam to close. Flatpak and Snap installs have no `steam` on PATH; their steam:// handler does.
fn shutdown() {
use std::process::{Command, Stdio};
let quiet = |c: &mut Command| { c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); };
let mut c = Command::new("steam");
c.arg("-shutdown"); quiet(&mut c);
if c.spawn().is_err() {
let mut c = Command::new("xdg-open");
c.arg("steam://exit"); quiet(&mut c);
let _ = c.spawn();
}
}
#[cfg(test)]
mod tests {
use super::*;
const NEW: &str = r#""users"
{
"76561198000000001"
{
"AccountName" "main_acc"
"PersonaName" "Main"
"RememberPassword" "1"
"AutoLogin" "1"
"timestamp" "200"
}
"76561198000000002"
{
"AccountName" "alt_acc"
"PersonaName" "Alt"
"RememberPassword" "0"
"AutoLogin" "0"
"timestamp" "300"
}
}
"#;
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("summit-acct-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(d.join("config")).unwrap(); d
}
#[test]
fn lists_accounts_newest_first() {
let v = parse_users(NEW);
assert_eq!(v.iter().map(|a| a.account_name.as_str()).collect::<Vec<_>>(), ["alt_acc", "main_acc"]);
assert_eq!(v[0].account_id(), 39734274);
assert!(!v[0].remember_password && v[1].remember_password);
assert_eq!(v[1].label(), "Main (main_acc)");
}
#[test]
fn marks_the_chosen_account_most_recent() {
let mut v = vdf::parse(NEW).unwrap();
mark_most_recent(&mut v, 76561198000000002, 999);
let u = |id: &str, k: &str| v.path(&["users", id, k]).and_then(|x| x.str()).map(String::from);
assert_eq!(u("76561198000000002", "AutoLogin").as_deref(), Some("1"));
assert_eq!(u("76561198000000001", "AutoLogin").as_deref(), Some("0"));
assert_eq!(u("76561198000000002", "timestamp").as_deref(), Some("999"));
assert_eq!(u("76561198000000001", "MostRecent"), None); // this client does not use MostRecent
let mut old = vdf::parse(r#""users" { "76561198000000001" { "AccountName" "a" "MostRecent" "1" } "76561198000000002" { "AccountName" "b" "MostRecent" "0" } }"#).unwrap();
mark_most_recent(&mut old, 76561198000000002, 5);
assert_eq!(old.path(&["users", "76561198000000002", "MostRecent"]).unwrap().str(), Some("1"));
assert_eq!(old.path(&["users", "76561198000000001", "MostRecent"]).unwrap().str(), Some("0"));
}
#[test]
fn picks_chosen_then_last_played() {
let r = dir("target");
std::fs::write(r.join("config/loginusers.vdf"), NEW).unwrap();
let acc = list_in(&r);
for (a, lp) in [(&acc[0], 50), (&acc[1], 40)] {
let d = r.join(format!("userdata/{}/config", a.account_id()));
std::fs::create_dir_all(&d).unwrap();
std::fs::write(d.join("localconfig.vdf"), format!(r#""UserLocalConfigStore" {{ "Software" {{ "Valve" {{ "Steam" {{ "apps" {{ "730" {{ "LastPlayed" "{lp}" }} "620" {{ "LastPlayed" "{}" }} }} }} }} }} }}"#, 100 - lp)).unwrap();
}
let last = last_played_by(&r, &acc);
let mut st = state::State::default();
assert_eq!(target("steam:730", &st, &acc, &last).map(|(a, w)| (a.account_name.as_str(), w)), Some(("alt_acc", Why::LastPlayed)));
assert_eq!(target("steam:620", &st, &acc, &last).map(|(a, _)| a.account_name.as_str()), Some("main_acc"));
assert_eq!(target("steam:1", &st, &acc, &last), None);
st.set_steam_account("steam:730", Some(76561198000000001));
assert_eq!(target("steam:730", &st, &acc, &last).map(|(a, w)| (a.account_name.as_str(), w)), Some(("main_acc", Why::Chosen)));
// a chosen account that is gone falls back to the last one played
st.set_steam_account("steam:730", Some(76561198000000009));
assert_eq!(target("steam:730", &st, &acc, &last).map(|(_, w)| w), Some(Why::LastPlayed));
assert_eq!(target("steam:730", &st, &acc[..1], &last), None);
}
#[test]
fn current_reads_active_then_autologin() {
let acc = parse_users(NEW);
let reg = |body: &str| vdf::parse(&format!(r#""Registry" {{ "HKCU" {{ "Software" {{ "Valve" {{ "Steam" {{ {body} }} }} }} }} }}"#)).unwrap();
let both = reg(r#""AutoLoginUser" "MAIN_ACC" "ActiveProcess" { "ActiveUser" "39734274" }"#);
assert_eq!(current_in(&both, &acc, true), Some(76561198000000002));
assert_eq!(current_in(&both, &acc, false), Some(76561198000000001));
// signed out (ActiveUser 0) while running: the account it will sign in with
assert_eq!(current_in(&reg(r#""AutoLoginUser" "main_acc" "ActiveProcess" { "ActiveUser" "0" }"#), &acc, true), Some(76561198000000001));
assert_eq!(current_in(&reg(r#""AutoLoginUser" "someone_else""#), &acc, false), None);
}
}
+30 -3
View File
@@ -27,6 +27,9 @@ pub struct UiSettings {
pub replay_seconds: u32,
/// Instant replay: how many seconds a save writes. Never more than `replay_seconds`.
pub clip_seconds: u32,
/// The key that opens and closes Summit's overlay while playing: "Insert", "Home", "F10", "Ctrl+Shift+O"...
/// (hotkey::overlay_key says what works). Esc is never it, and never closes Summit.
pub overlay_key: String,
/// Steam shortcuts `summit steam-add`/`steam-remove` know about. Defaults to the two
/// built-ins ("My PS5", "Capture Card"); edit or add to this list to change what they do.
#[serde(default = "default_shortcuts")]
@@ -55,7 +58,8 @@ impl Default for UiSettings {
fn default() -> Self {
Self {
layout: "bigpicture".into(), theme: "midnight".into(), anim_speed: 1.0, anim_style: "smooth".into(),
ui_scale: 1.0, replay_seconds: 60, clip_seconds: 30, shortcuts: default_shortcuts(),
ui_scale: 1.0, replay_seconds: 60, clip_seconds: 30, overlay_key: crate::hotkey::OVERLAY_KEY.into(),
shortcuts: default_shortcuts(),
}
}
}
@@ -73,10 +77,17 @@ impl UiSettings {
self.ui_scale = if self.ui_scale.is_finite() { self.ui_scale.clamp(0.8, 1.5) } else { d.ui_scale };
self.replay_seconds = nearest_u32(self.replay_seconds, CLIP_LENGTHS);
self.clip_seconds = nearest_u32(self.clip_seconds, CLIP_LENGTHS).min(self.replay_seconds);
self.overlay_key = crate::hotkey::overlay_key(&self.overlay_key).unwrap_or(d.overlay_key);
self
}
pub fn layout_index(&self) -> usize { LAYOUTS.iter().position(|l| *l == self.layout).unwrap_or(0) }
pub fn anim_style_index(&self) -> usize { ANIM_STYLES.iter().position(|l| *l == self.anim_style).unwrap_or(0) }
/// The Settings page's choices for the overlay key: the usual ones, then this one if it is another (set by hand).
pub fn overlay_key_choices(&self) -> Vec<String> {
let mut v: Vec<String> = crate::hotkey::OVERLAY_KEYS.iter().map(|k| k.to_string()).collect();
if !v.contains(&self.overlay_key) { v.push(self.overlay_key.clone()); }
v
}
}
pub fn path() -> Result<PathBuf> { Ok(dirs::config_dir().context("no config dir")?.join("summit/ui.toml")) }
@@ -115,7 +126,7 @@ mod tests {
#[test]
fn roundtrip_through_file() {
let p = tmp("roundtrip");
let s = UiSettings { layout: "list".into(), theme: "violet".into(), anim_speed: 0.0, anim_style: "snappy".into(), ui_scale: 1.25, replay_seconds: 600, clip_seconds: 180, shortcuts: default_shortcuts() };
let s = UiSettings { layout: "list".into(), theme: "violet".into(), anim_speed: 0.0, anim_style: "snappy".into(), ui_scale: 1.25, replay_seconds: 600, clip_seconds: 180, overlay_key: "Home".into(), shortcuts: default_shortcuts() };
save_to(&p, &s).unwrap();
assert_eq!(load_from(&p), s);
assert_eq!(std::fs::read_dir(p.parent().unwrap()).unwrap().count(), 1, "no temporary file left");
@@ -137,7 +148,8 @@ mod tests {
}
#[test]
fn bad_values_are_clamped() {
let s = UiSettings { layout: "hologram".into(), theme: " ".into(), anim_speed: 9.0, anim_style: "wobbly".into(), ui_scale: 0.1, replay_seconds: 100, clip_seconds: 9999, shortcuts: vec![] }.sanitized();
let s = UiSettings { layout: "hologram".into(), theme: " ".into(), anim_speed: 9.0, anim_style: "wobbly".into(), ui_scale: 0.1, replay_seconds: 100, clip_seconds: 9999, overlay_key: "Esc".into(), shortcuts: vec![] }.sanitized();
assert_eq!(s.overlay_key, "Insert");
assert_eq!(s.layout, "bigpicture");
assert_eq!(s.theme, "midnight");
assert_eq!(s.anim_speed, 2.0);
@@ -148,6 +160,21 @@ mod tests {
assert_eq!(UiSettings { anim_speed: f32::NAN, ..Default::default() }.sanitized().anim_speed, 1.0);
}
#[test]
fn overlay_key_defaults_to_insert_and_refuses_the_games_keys() {
assert_eq!(UiSettings::default().overlay_key, "Insert");
let s = UiSettings { overlay_key: "home".into(), ..Default::default() }.sanitized();
assert_eq!(s.overlay_key, "Home");
assert_eq!(s.overlay_key_choices().len(), crate::hotkey::OVERLAY_KEYS.len());
for bad in ["Escape", "w", ""] {
assert_eq!(UiSettings { overlay_key: bad.into(), ..Default::default() }.sanitized().overlay_key, "Insert", "{bad}");
}
let own = UiSettings { overlay_key: "ctrl+shift+o".into(), ..Default::default() }.sanitized();
assert_eq!(own.overlay_key_choices().last().map(String::as_str), Some("Ctrl+Shift+O"));
let p = tmp("overlaykey");
save_to(&p, &own).unwrap();
assert_eq!(load_from(&p).overlay_key, "Ctrl+Shift+O");
}
#[test]
fn clip_never_longer_than_replay() {
let s = UiSettings { replay_seconds: 30, clip_seconds: 300, ..Default::default() }.sanitized();
assert_eq!((s.replay_seconds, s.clip_seconds), (30, 30));
+84
View File
@@ -24,6 +24,73 @@ impl Value {
pub fn path(&self, keys: &[&str]) -> Option<&Value> {
keys.iter().try_fold(self, |v, k| v.get(k))
}
/// Case-insensitive child lookup, for changing it.
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
match self {
Value::Obj(kv) => kv.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v),
_ => None,
}
}
pub fn children_mut(&mut self) -> &mut [(String, Value)] {
match self { Value::Obj(kv) => kv, _ => &mut [] }
}
/// Set `key` to a string: replaced where it is (keeping the file's order and spelling of the key), else added
/// at the end. Does nothing on a string value.
pub fn set(&mut self, key: &str, val: &str) {
if let Some(v) = self.get_mut(key) { *v = Value::Str(val.into()); return; }
if let Value::Obj(kv) = self { kv.push((key.into(), Value::Str(val.into()))); }
}
/// Walk a path of keys, making the objects that are missing. None if a key on the way holds a string.
pub fn path_mut(&mut self, keys: &[&str]) -> Option<&mut Value> {
let mut v = self;
for k in keys {
if v.get(k).is_none() {
let Value::Obj(kv) = v else { return None };
kv.push((k.to_string(), Value::Obj(vec![])));
}
v = v.get_mut(k)?;
if !matches!(v, Value::Obj(_)) { return None; }
}
Some(v)
}
}
fn quote(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
c => out.push(c),
}
}
out.push('"');
}
fn write_obj(kv: &[(String, Value)], depth: usize, out: &mut String) {
for (k, v) in kv {
out.extend(std::iter::repeat_n('\t', depth));
quote(k, out);
match v {
Value::Str(s) => { out.push_str("\t\t"); quote(s, out); out.push('\n'); }
Value::Obj(c) => {
out.push('\n');
out.extend(std::iter::repeat_n('\t', depth)); out.push_str("{\n");
write_obj(c, depth + 1, out);
out.extend(std::iter::repeat_n('\t', depth)); out.push_str("}\n");
}
}
}
}
/// The text form of a parsed file, laid out the way Steam writes it (tabs, one key per line), so [`parse`] reads
/// back the same value.
pub fn to_text(v: &Value) -> String {
let mut out = String::new();
write_obj(v.children(), 0, &mut out);
out
}
#[derive(Debug, PartialEq)]
@@ -115,6 +182,23 @@ mod tests {
assert_eq!(v.path(&["AppState", "UserConfig", "language"]).unwrap().str(), Some("english"));
}
#[test]
fn writes_what_it_reads() {
let src = "\"Registry\"\n{\n\t\"HKCU\"\n\t{\n\t\t\"Path\"\t\t\"/a\\\\sourcemods\"\n\t\t\"Q\"\t\t\"say \\\"hi\\\"\"\n\t}\n}\n";
let v = parse(src).unwrap();
assert_eq!(v.path(&["Registry", "HKCU", "Path"]).unwrap().str(), Some("/a\\sourcemods"));
assert_eq!(to_text(&v), src);
assert_eq!(parse(&to_text(&v)).unwrap(), v);
}
#[test]
fn set_and_path_mut() {
let mut v = parse("\"R\" { \"HKCU\" { \"autologinuser\" \"a\" } }").unwrap();
v.path_mut(&["R", "HKCU"]).unwrap().set("AutoLoginUser", "b");
v.path_mut(&["R", "HKCU", "Software", "Valve"]).unwrap().set("X", "1");
assert_eq!(v.path(&["R", "HKCU", "autologinuser"]).unwrap().str(), Some("b"));
assert_eq!(v.path(&["R", "HKCU", "Software", "Valve", "X"]).unwrap().str(), Some("1"));
assert!(v.path_mut(&["R", "HKCU", "autologinuser", "deeper"]).is_none());
}
#[test]
fn rejects_unbalanced() { assert!(parse("\"a\" {").is_err()); }
#[test]
fn deep_nesting_is_an_error_not_a_stack_overflow() {
+14 -7
View File
@@ -2,8 +2,8 @@
//!
//! Layout: one key-type byte, a nul-terminated key name, then a value whose shape depends on
//! the type byte. Type 0x00 is a nested map (itself a sequence of key/value pairs, closed by a
//! 0x08 byte); the file as a whole is one unclosed map at the top level (EOF ends it instead of
//! a 0x08). Types we don't otherwise interpret (float32, pointer, color, (u)int64, wstring) are
//! 0x08 byte); the file as a whole is one map at the top level, which Steam closes with a final
//! 0x08 too (a file that just ends there is read as well). Types we don't otherwise interpret (float32, pointer, color, (u)int64, wstring) are
//! kept as raw bytes so a round trip never drops a field Steam wrote that we don't understand.
use std::fmt;
@@ -99,8 +99,9 @@ fn parse_map(b: &[u8], i: &mut usize, bounded: bool, depth: usize) -> Result<Vec
}
let tag = b[*i]; *i += 1;
if tag == T_END {
if bounded { return Ok(kv); }
return Err("unexpected end-of-map marker at the top level".into());
// the top level's own closer must be the last byte
if bounded || *i == b.len() { return Ok(kv); }
return Err("data after the end of the top-level map".into());
}
let key = read_cstr(b, i)?;
let val = match tag {
@@ -139,15 +140,16 @@ fn write_map(out: &mut Vec<u8>, kv: &[(String, BVal)], bounded: bool) {
if bounded { out.push(T_END); }
}
/// Parses a whole `shortcuts.vdf`-style file: one unclosed map at the top level.
/// Parses a whole `shortcuts.vdf`-style file: one map at the top level, closed by a final 0x08 or by the end.
pub fn parse(bytes: &[u8]) -> Result<Vec<(String, BVal)>, String> {
let mut i = 0;
parse_map(bytes, &mut i, false, 0)
}
/// Writes a whole file the way Steam does, top-level closer included.
pub fn write(kv: &[(String, BVal)]) -> Vec<u8> {
let mut out = Vec::new();
write_map(&mut out, kv, false);
write_map(&mut out, kv, true);
out
}
@@ -199,6 +201,7 @@ mod tests {
bytes.push(T_STR); bytes.extend_from_slice(b"AppName\0"); bytes.extend_from_slice(b"My PS5\0");
bytes.push(T_END); // close entry "0"
bytes.push(T_END); // close "shortcuts"
bytes.push(T_END); // close the file's top-level map, as Steam does
let v = parse(&bytes).unwrap();
assert_eq!(v.len(), 1);
let shortcuts = &v[0].1;
@@ -206,6 +209,10 @@ mod tests {
assert_eq!(shortcuts.get("0").unwrap().get("appid").unwrap().int32(), Some(42));
// and it comes back out byte-identical
assert_eq!(write(&v), bytes);
// a file that ends without the top-level closer reads the same; anything after the closer is an error
assert_eq!(parse(&bytes[..bytes.len() - 1]).unwrap(), v);
let mut extra = bytes.clone(); extra.push(T_STR);
assert!(parse(&extra).unwrap_err().contains("after the end"));
}
#[test]
@@ -221,7 +228,7 @@ mod tests {
bytes.push(T_MAP); bytes.extend_from_slice(b"0\0");
bytes.push(T_STR); bytes.extend_from_slice(b"AppName\0"); bytes.extend_from_slice(b"Caf\xe9\0"); // Latin-1
bytes.push(T_STR); bytes.extend_from_slice(b"Exe\0"); bytes.extend_from_slice(b"/g/caf\xe9.sh\0");
bytes.push(T_END); bytes.push(T_END);
bytes.push(T_END); bytes.push(T_END); bytes.push(T_END);
let v = parse(&bytes).unwrap();
assert_eq!(write(&v), bytes, "byte-identical, not U+FFFD");
assert_eq!(v[0].1.get("0").unwrap().get("AppName").unwrap().str(), None); // not text we can use, but kept
+340
View File
@@ -0,0 +1,340 @@
//! Puts a game's window where its profile says once the window opens: on the profile's monitor, windowed,
//! borderless (no frame, covering the monitor) or fullscreen, and focused.
//!
//! * KDE Plasma (Wayland and X11): a small KWin script run over D-Bus (org.kde.kwin.Scripting), the same way the
//! engine lists windows (engine/framegen/kwin.py). The script calls back on our D-Bus connection with the windows
//! it changed, so Summit knows when the game's window was found.
//! * Other X11 desktops: `wmctrl` (and `xprop` for borderless). Moving to another monitor is not done there.
//! * Other Wayland desktops: nothing (a Wayland program cannot place another program's window).
//!
//! Planning (the script, the wmctrl commands, parsing) is pure and unit tested; [`place`] does the work.
use crate::display::{Desktop, Session};
use crate::profile::Profile;
use std::time::{Duration, Instant};
/// Which windows are the game's.
#[derive(Debug, Clone, PartialEq)]
pub enum Target {
/// The process Summit started and everything it started (a launch script's game, Wine's processes).
Pid(u32),
/// A window class, e.g. `steam_app_620` (Steam gives Proton games that one).
Class(String),
}
/// What to do to the game's window. Built from a profile by [`wanted`].
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Want {
/// "" (leave it) | "windowed" | "borderless" | "fullscreen"
pub mode: String,
pub monitor: Option<String>,
pub focus: bool,
}
/// What `p` asks of the game's window, or None when it asks nothing. With Enhance the engine's picture is what
/// is windowed or covers the monitor (the engine gets the window mode), so the game's window is not resized: it is
/// only moved to the monitor and focused.
pub fn wanted(p: &Profile, enhance: bool) -> Option<Want> {
let w = Want { mode: if enhance { String::new() } else { p.window_mode.clone() }, monitor: p.monitor.clone(), focus: p.focus };
if w.mode.is_empty() && w.monitor.is_none() && !w.focus { None } else { Some(w) }
}
/// How windows can be placed in this session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend { KWin, Wmctrl }
pub fn backend(session: Session, desktop: Desktop, have: impl Fn(&str) -> bool) -> Result<Backend, String> {
match (session, desktop) {
(Session::Unknown, _) => Err("no desktop session".into()),
(_, Desktop::Kde) => Ok(Backend::KWin),
(Session::X11, _) if have("wmctrl") => Ok(Backend::Wmctrl),
(Session::X11, _) => Err("wmctrl is not installed (it places windows on X11)".into()),
(Session::Wayland, d) => Err(format!("{d:?} Wayland has no way for Summit to place another program's window (KDE Plasma has)")),
}
}
fn js(s: &str) -> String { serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into()) }
/// The KWin script for one look at the windows. `pids` are the game's processes now (Target::Pid), `done` KWin's ids
/// of windows already placed (left alone, so a window the player moved is not moved back). It reports what it
/// changed to `reply_to` (our D-Bus connection's name) as JSON: `[{"id":..,"pid":..,"cls":..,"caption":..,"output":..}]`.
pub fn kwin_script(target: &Target, pids: &[u32], want: &Want, done: &[String], reply_to: &str) -> String {
let (cls, pids) = match target { Target::Class(c) => (c.to_lowercase(), vec![]), Target::Pid(_) => (String::new(), pids.to_vec()) };
let pids = pids.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(",");
let done = done.iter().map(|d| js(d)).collect::<Vec<_>>().join(",");
format!(r#"const PIDS = [{pids}], CLS = {cls}, MODE = {mode}, MON = {mon}, FOCUS = {focus}, DONE = [{done}];
const out = [];
for (const w of workspace.windowList()) {{
if (!w.normalWindow) continue;
const mine = CLS !== "" ? String(w.resourceClass).toLowerCase() === CLS : PIDS.indexOf(w.pid) >= 0;
const id = String(w.internalId);
if (!mine || DONE.indexOf(id) >= 0) continue;
try {{
let screen = w.output;
if (MON !== "") {{
for (const s of workspace.screens) {{ if (s.name === MON) screen = s; }}
if (screen && screen !== w.output) workspace.sendClientToScreen(w, screen);
}}
if (MODE === "fullscreen") {{ w.fullScreen = true; }}
else if (MODE === "borderless") {{ w.fullScreen = false; w.noBorder = true; if (screen) {{ const g = screen.geometry; w.frameGeometry = (typeof Qt !== "undefined" && Qt.rect) ? Qt.rect(g.x, g.y, g.width, g.height) : {{x: g.x, y: g.y, width: g.width, height: g.height}}; }} }}
else if (MODE === "windowed") {{ w.fullScreen = false; w.noBorder = false; }}
if (FOCUS) workspace.activeWindow = w;
out.push({{id: id, pid: w.pid, cls: String(w.resourceClass), caption: String(w.caption), output: screen ? String(screen.name) : ""}});
}} catch (e) {{ out.push({{id: id, error: String(e)}}); }}
}}
callDBus({reply}, "/summit/winmode", "org.summit.WinMode", "placed", JSON.stringify(out));
"#, cls = js(&cls), mode = js(&want.mode), mon = js(want.monitor.as_deref().unwrap_or("")), focus = want.focus, reply = js(reply_to))
}
/// A window the KWin script changed.
#[derive(Debug, Clone, PartialEq)]
pub struct Placed { pub id: String, pub pid: u32, pub class: String, pub caption: String, pub output: String,
/// What KWin said went wrong for this window (it is then not tried again).
pub error: Option<String> }
pub fn parse_placed(text: &str) -> Vec<Placed> {
let Ok(serde_json::Value::Array(a)) = serde_json::from_str::<serde_json::Value>(text) else { return vec![] };
a.iter().filter_map(|d| Some(Placed {
id: d.get("id")?.as_str()?.to_string(),
pid: d.get("pid").and_then(|p| p.as_u64()).unwrap_or(0) as u32,
class: d.get("cls").and_then(|c| c.as_str()).unwrap_or_default().to_string(),
caption: d.get("caption").and_then(|c| c.as_str()).unwrap_or_default().to_string(),
output: d.get("output").and_then(|c| c.as_str()).unwrap_or_default().to_string(),
error: d.get("error").and_then(|c| c.as_str()).map(str::to_string),
})).collect()
}
/// One line of `wmctrl -lpx`: window id, pid, class ("instance.Class"), title.
#[derive(Debug, Clone, PartialEq)]
pub struct XWin { pub xid: String, pub pid: u32, pub class: String, pub title: String }
/// `wmctrl -lpx`: `0x03a00007 0 4242 steam_app_620.steam_app_620 host Portal 2`.
pub fn parse_wmctrl(text: &str) -> Vec<XWin> {
text.lines().filter_map(|l| {
let mut it = l.split_whitespace();
let xid = it.next()?.to_string();
let _desk = it.next()?;
let pid = it.next()?.parse().ok()?;
let class = it.next()?.to_string();
let _host = it.next();
Some(XWin { xid, pid, class, title: it.collect::<Vec<_>>().join(" ") })
}).collect()
}
/// Whether an X window is the game's: its class (either half of "instance.Class") or one of its processes.
pub fn x_matches(w: &XWin, target: &Target, pids: &[u32]) -> bool {
match target {
Target::Class(c) => w.class.split('.').any(|p| p.eq_ignore_ascii_case(c)),
Target::Pid(_) => pids.contains(&w.pid),
}
}
/// Commands that put X window `xid` into `want`'s mode with wmctrl (and xprop: borderless takes the frame off with
/// _MOTIF_WM_HINTS and maximizes the window). The monitor is not changed this way.
pub fn wmctrl_cmds(xid: &str, want: &Want) -> Vec<Vec<String>> {
let c = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<String>>();
let mut v = vec![];
match want.mode.as_str() {
"fullscreen" => v.push(c(&["wmctrl", "-i", "-r", xid, "-b", "add,fullscreen"])),
"borderless" => {
v.push(c(&["wmctrl", "-i", "-r", xid, "-b", "remove,fullscreen"]));
v.push(c(&["xprop", "-id", xid, "-f", "_MOTIF_WM_HINTS", "32c", "-set", "_MOTIF_WM_HINTS", "2, 0, 0, 0, 0"]));
v.push(c(&["wmctrl", "-i", "-r", xid, "-b", "add,maximized_vert,maximized_horz"]));
}
"windowed" => v.push(c(&["wmctrl", "-i", "-r", xid, "-b", "remove,fullscreen"])),
_ => {}
}
if want.focus { v.push(c(&["wmctrl", "-i", "-a", xid])); }
v
}
/// The game's processes now: the one Summit started and all it started.
fn family(target: &Target) -> Vec<u32> {
match target {
Target::Pid(p) => { let mut v = vec![*p]; v.extend(crate::engine::descendants_in(std::path::Path::new("/proc"), *p)); v }
Target::Class(_) => vec![],
}
}
/// How long to keep looking.
#[derive(Debug, Clone, Copy)]
pub struct Watch {
/// Give up if no window turns up in this time.
pub wait: Duration,
/// After the first window, keep looking this long for more (a launcher or splash window opens first in many games).
pub settle: Duration,
pub poll: Duration,
}
impl Default for Watch { fn default() -> Self { Self { wait: Duration::from_secs(90), settle: Duration::from_secs(15), poll: Duration::from_millis(700) } } }
/// Look for the game's windows and place each as it opens, until `watch` runs out or `stop` says so (the game
/// ended). Calls `log` with a line per window placed. Returns how many were placed, or why nothing could be done.
pub fn place(session: Session, desktop: Desktop, target: &Target, want: &Want, watch: Watch, stop: &dyn Fn() -> bool, log: &mut dyn FnMut(String)) -> Result<usize, String> {
let have = |t: &str| std::process::Command::new("sh").args(["-c", &format!("command -v {t}")]).stdout(std::process::Stdio::null()).status().is_ok_and(|s| s.success());
match backend(session, desktop, have)? {
Backend::KWin => kwin::place(target, want, watch, stop, log),
Backend::Wmctrl => place_wmctrl(target, want, watch, stop, log),
}
}
fn watch_loop(watch: Watch, stop: &dyn Fn() -> bool, mut round: impl FnMut() -> Result<usize, String>) -> Result<usize, String> {
let start = Instant::now();
let mut first: Option<Instant> = None;
let mut n = 0;
loop {
n += round()?;
if n > 0 && first.is_none() { first = Some(Instant::now()); }
let over = match first { Some(t) => t.elapsed() >= watch.settle, None => start.elapsed() >= watch.wait };
if over || stop() { return Ok(n); }
std::thread::sleep(watch.poll);
}
}
fn place_wmctrl(target: &Target, want: &Want, watch: Watch, stop: &dyn Fn() -> bool, log: &mut dyn FnMut(String)) -> Result<usize, String> {
let mut done: Vec<String> = vec![];
watch_loop(watch, stop, || {
let out = std::process::Command::new("wmctrl").arg("-lpx").output().map_err(|e| format!("wmctrl: {e}"))?;
let pids = family(target);
let mut n = 0;
for w in parse_wmctrl(&String::from_utf8_lossy(&out.stdout)) {
if done.contains(&w.xid) || !x_matches(&w, target, &pids) { continue; }
for c in wmctrl_cmds(&w.xid, want) { let _ = std::process::Command::new(&c[0]).args(&c[1..]).status(); }
log(format!("window: placed \"{}\" ({}){}", w.title, w.class, if want.mode.is_empty() { String::new() } else { format!(", {}", want.mode) }));
done.push(w.xid);
n += 1;
}
Ok(n)
})
}
mod kwin {
use super::*;
use std::sync::{mpsc, Mutex};
use zbus::blocking::Connection;
struct Reporter { tx: Mutex<mpsc::Sender<String>> }
#[zbus::interface(name = "org.summit.WinMode")]
impl Reporter {
// the script calls "placed"; zbus would name it "Placed"
#[zbus(name = "placed")]
fn placed(&self, json: String) { if let Ok(tx) = self.tx.lock() { let _ = tx.send(json); } }
}
fn scripting(c: &Connection, method: &str, body: &(impl serde::Serialize + zbus::zvariant::DynamicType)) -> zbus::Result<zbus::message::Message> {
c.call_method(Some("org.kde.KWin"), "/Scripting", Some("org.kde.kwin.Scripting"), method, body)
}
/// Run the script once and wait for its report.
fn once(c: &Connection, rx: &mpsc::Receiver<String>, script: &str, n: u32) -> Result<Vec<Placed>, String> {
let name = format!("summit-winmode-{}-{n}", std::process::id());
let path = std::env::temp_dir().join(format!("{name}.js"));
std::fs::write(&path, script).map_err(|e| format!("writing {}: {e}", path.display()))?;
let r = (|| {
let id: i32 = scripting(c, "loadScript", &(path.to_string_lossy().as_ref(), name.as_str()))
.and_then(|m| m.body().deserialize()).map_err(|e| format!("KWin would not load the script: {e}"))?;
if id < 0 { return Err("KWin would not load the script".to_string()); }
while rx.try_recv().is_ok() {}
c.call_method(Some("org.kde.KWin"), format!("/Scripting/Script{id}").as_str(), Some("org.kde.kwin.Script"), "run", &())
.map_err(|e| format!("KWin would not run the script: {e}"))?;
rx.recv_timeout(Duration::from_secs(3)).map(|j| parse_placed(&j)).map_err(|_| "KWin's script did not answer".to_string())
})();
let _ = scripting(c, "unloadScript", &(name.as_str(),));
// KWin unloads later and hands the same id to the next script: running that id before the old script is
// gone runs nothing. So wait until it says the script is gone.
let t = Instant::now();
while t.elapsed() < Duration::from_secs(2) {
let loaded: bool = scripting(c, "isScriptLoaded", &(name.as_str(),)).and_then(|m| m.body().deserialize()).unwrap_or(false);
if !loaded { break; }
std::thread::sleep(Duration::from_millis(20));
}
let _ = std::fs::remove_file(&path);
r
}
pub fn place(target: &Target, want: &Want, watch: Watch, stop: &dyn Fn() -> bool, log: &mut dyn FnMut(String)) -> Result<usize, String> {
let (tx, rx) = mpsc::channel();
let c = Connection::session().map_err(|e| format!("no D-Bus session: {e}"))?;
c.object_server().at("/summit/winmode", Reporter { tx: Mutex::new(tx) }).map_err(|e| format!("D-Bus: {e}"))?;
let me = c.unique_name().map(|n| n.to_string()).ok_or("no D-Bus name")?;
let mut done: Vec<String> = vec![];
let mut n = 0u32;
watch_loop(watch, stop, || {
n += 1;
let placed = once(&c, &rx, &kwin_script(target, &family(target), want, &done, &me), n)?;
for p in &placed {
if let Some(e) = &p.error { log(format!("window: KWin could not place it: {e}")); done.push(p.id.clone()); continue; }
log(format!("window: placed \"{}\" ({}) on {}{}{}", p.caption, p.class, if p.output.is_empty() { "its monitor" } else { &p.output },
if want.mode.is_empty() { String::new() } else { format!(", {}", want.mode) }, if want.focus { ", focused" } else { "" }));
done.push(p.id.clone());
}
Ok(placed.iter().filter(|p| p.error.is_none()).count())
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wanted_follows_the_profile_and_enhance() {
assert_eq!(wanted(&Profile::default(), false), None);
let p = Profile { window_mode: "borderless".into(), monitor: Some("DP-1".into()), ..Default::default() };
assert_eq!(wanted(&p, false), Some(Want { mode: "borderless".into(), monitor: Some("DP-1".into()), focus: false }));
// with Enhance the engine's picture takes the mode; the game is only moved
assert_eq!(wanted(&p, true).unwrap().mode, "");
assert_eq!(wanted(&Profile { window_mode: "fullscreen".into(), ..Default::default() }, true), None);
assert!(wanted(&Profile { focus: true, ..Default::default() }, true).unwrap().focus);
}
#[test]
fn backends_per_session() {
assert_eq!(backend(Session::Wayland, Desktop::Kde, |_| false), Ok(Backend::KWin));
assert_eq!(backend(Session::X11, Desktop::Kde, |_| false), Ok(Backend::KWin));
assert_eq!(backend(Session::X11, Desktop::Other, |t| t == "wmctrl"), Ok(Backend::Wmctrl));
assert!(backend(Session::X11, Desktop::Gnome, |_| false).is_err());
assert!(backend(Session::Wayland, Desktop::Gnome, |_| true).is_err());
assert!(backend(Session::Unknown, Desktop::Kde, |_| true).is_err());
}
#[test]
fn kwin_script_carries_the_choices_as_json() {
let w = Want { mode: "fullscreen".into(), monitor: Some("HDMI-A-1".into()), focus: true };
let s = kwin_script(&Target::Pid(10), &[10, 11], &w, &["{abc}".into()], ":1.42");
assert!(s.starts_with("const PIDS = [10,11], CLS = \"\", MODE = \"fullscreen\", MON = \"HDMI-A-1\", FOCUS = true, DONE = [\"{abc}\"];"), "{s}");
assert!(s.contains("callDBus(\":1.42\", \"/summit/winmode\""));
let s = kwin_script(&Target::Class("Steam_App_620".into()), &[1], &Want::default(), &[], ":1.1");
assert!(s.starts_with("const PIDS = [], CLS = \"steam_app_620\", MODE = \"\", MON = \"\", FOCUS = false, DONE = [];"), "{s}");
// a quote in a monitor name cannot end the string
let s = kwin_script(&Target::Pid(1), &[1], &Want { monitor: Some("a\"); evil(\"".into()), ..Default::default() }, &[], ":1.1");
assert!(s.contains(r#"MON = "a\"); evil(\"""#), "{s}");
}
#[test]
fn kwin_reports_parse() {
let p = parse_placed(r#"[{"id":"{1}","pid":4242,"cls":"steam_app_620","caption":"Portal 2","output":"DP-1"},{"pid":1}]"#);
assert_eq!(p, vec![Placed { id: "{1}".into(), pid: 4242, class: "steam_app_620".into(), caption: "Portal 2".into(), output: "DP-1".into(), error: None }]);
assert!(parse_placed("not json").is_empty());
}
#[test]
fn wmctrl_lines_and_commands() {
let w = parse_wmctrl("0x03a00007 0 4242 steam_app_620.steam_app_620 box Portal 2\n0x01 -1 0 desktop_window.Nautilus box Desktop\nbad\n");
assert_eq!(w.len(), 2);
assert_eq!((w[0].xid.as_str(), w[0].pid, w[0].title.as_str()), ("0x03a00007", 4242, "Portal 2"));
assert!(x_matches(&w[0], &Target::Class("steam_app_620".into()), &[]));
assert!(x_matches(&w[0], &Target::Pid(1), &[1, 4242]));
assert!(!x_matches(&w[1], &Target::Pid(1), &[1, 4242]));
let cmds = |m: &str, f: bool| wmctrl_cmds("0x5", &Want { mode: m.into(), monitor: None, focus: f }).iter().map(|c| c.join(" ")).collect::<Vec<_>>();
assert_eq!(cmds("fullscreen", true), vec!["wmctrl -i -r 0x5 -b add,fullscreen", "wmctrl -i -a 0x5"]);
assert_eq!(cmds("borderless", false).len(), 3);
assert_eq!(cmds("windowed", false), vec!["wmctrl -i -r 0x5 -b remove,fullscreen"]);
assert!(cmds("", false).is_empty());
}
#[test]
fn the_watch_stops_after_settling_or_giving_up() {
let w = Watch { wait: Duration::from_millis(200), settle: Duration::from_millis(100), poll: Duration::from_millis(20) };
let t = Instant::now();
assert_eq!(watch_loop(w, &|| false, || Ok(0)).unwrap(), 0);
assert!(t.elapsed() >= Duration::from_millis(200));
let mut k = 0;
assert_eq!(watch_loop(w, &|| false, || { k += 1; Ok(if k == 2 { 1 } else { 0 }) }).unwrap(), 1);
assert_eq!(watch_loop(w, &|| true, || Ok(0)).unwrap(), 0);
assert!(watch_loop(w, &|| false, || Err("x".into())).is_err());
}
}
+3 -1
View File
@@ -11,7 +11,9 @@ path = "src/main.rs"
[dependencies]
summit-core = { path = "../summit-core" }
# 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"] }
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
# listened to while it does (pad.rs reads every press, whatever window is in front).
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
[build-dependencies]
+138
View File
@@ -0,0 +1,138 @@
//! The Steam account a Steam game is played on: the card on its page and the picker (ui/accounts.slint).
//! Choosing and switching are in summit_core::steam_account; `summit run` does the switch when the game starts.
use crate::{data, rgb, App, Lib, SteamAccount};
use slint::{ComponentHandle, Image, ModelRc, VecModel};
use std::collections::HashMap;
use std::path::PathBuf;
use summit_core::{model::{Entry, Source}, state, steam_account as sa};
/// The accounts Steam remembers and which one played each game last, read once and kept until the library reloads
/// or a game ends (the localconfig.vdf files are large).
pub struct Accounts {
pub root: PathBuf,
pub list: Vec<sa::Account>,
pub last: HashMap<u32, (u64, u64)>,
avatars: HashMap<u64, Image>,
}
impl Accounts {
pub fn load() -> Option<Accounts> {
let root = sa::root()?;
let list = sa::list_in(&root);
let last = sa::last_played_by(&root, &list);
let avatars = list.iter().filter_map(|a| Some((a.steam_id, Image::load_from_path(a.avatar.as_ref()?).ok()?))).collect();
Some(Accounts { root, list, last, avatars })
}
fn row(&self, a: &sa::Account, note: String, selected: bool) -> SteamAccount {
let (c1, c2) = data::colors(&a.account_name);
let avatar = self.avatars.get(&a.steam_id).cloned();
let shown = if a.persona_name.is_empty() { &a.account_name } else { &a.persona_name };
SteamAccount {
persona: shown.as_str().into(), login: a.account_name.as_str().into(),
has_avatar: avatar.is_some(), avatar: avatar.unwrap_or_default(),
initial: shown.chars().next().map(|c| c.to_uppercase().collect::<String>()).unwrap_or_else(|| "?".into()).into(),
note: note.into(),
warn: if a.remember_password { "".into() } else { "Steam has no saved sign-in for it: it will ask for the password".into() },
selected, c1: rgb(c1), c2: rgb(c2),
}
}
}
/// Only Steam games (not non-Steam shortcuts: those belong to one account's library) on a PC with 2+ accounts.
fn applies(e: &Entry) -> bool { e.source == Source::Steam && e.steam_app_id.is_some() }
impl App {
/// The cached account list, read now if there is none.
pub fn accounts(&self) -> Option<std::cell::Ref<'_, Accounts>> {
if self.steam_accounts.borrow().is_none() { *self.steam_accounts.borrow_mut() = Accounts::load(); }
std::cell::Ref::filter_map(self.steam_accounts.borrow(), |a| a.as_ref()).ok()
}
/// Forget the cached accounts (a game ended, the library reloaded): the next look reads Steam's files again.
pub fn forget_accounts(&self) { *self.steam_accounts.borrow_mut() = None; }
/// For a game's page: (has a card, the account, why). Login "" means whichever account Steam is on.
pub fn account_card(&self, e: &Entry, st: &state::State) -> (bool, SteamAccount, String) {
let none = SteamAccount::default();
if !applies(e) { return (false, none, String::new()); }
let Some(acc) = self.accounts() else { return (false, none, String::new()) };
if acc.list.len() < 2 { return (false, none, String::new()); }
let current = sa::current(&acc.root, &acc.list, sa::running());
match sa::target(&e.id, st, &acc.list, &acc.last) {
Some((a, why)) => {
let mut note = match why {
sa::Why::Chosen => "Chosen for this game".to_string(),
sa::Why::LastPlayed => "Automatic: the account it was last played on".to_string(),
};
if current == Some(a.steam_id) { note.push_str(" · Steam is on it now"); }
else { note.push_str(" · Play switches Steam to it"); }
let row = acc.row(a, String::new(), false);
if !row.warn.is_empty() { note = format!("{note} · {}", row.warn); }
(true, row, note)
}
None => (true, none, "Automatic: not played on any of your accounts here yet, so it starts on the account Steam is on".into()),
}
}
/// Play's toast for a Steam game that needs Steam on another account first.
pub fn switch_note(&self, e: &Entry) -> Option<String> {
if !applies(e) || self.cli().is_none() { return None; }
let acc = self.accounts()?;
let (a, _) = sa::target(&e.id, &self.state.borrow(), &acc.list, &acc.last)?;
let current = sa::current(&acc.root, &acc.list, sa::running());
(current != Some(a.steam_id)).then(|| format!("Switching Steam to {}", a.label()))
}
pub fn open_accounts(&self, idx: i32) {
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
if !applies(&e) { return; }
self.forget_accounts(); // fresh: an account may have signed in since
let Some(acc) = self.accounts() else { return self.toast("No Steam sign-in list found (config/loginusers.vdf)") };
let st = self.state.borrow();
let chosen = st.steam_account(&e.id).filter(|id| acc.list.iter().any(|a| a.steam_id == *id));
let current = sa::current(&acc.root, &acc.list, sa::running());
let last = e.steam_app_id.and_then(|app| acc.last.get(&app)).map(|(id, _)| *id);
let rows: Vec<SteamAccount> = acc.list.iter().map(|a| {
let mut notes = vec![];
if current == Some(a.steam_id) { notes.push(if sa::running() { "Signed in now".to_string() } else { "Steam signs in as it".to_string() }); }
if last == Some(a.steam_id) { notes.push(format!("{} was last played here", e.title)); }
acc.row(a, notes.join(" · "), chosen == Some(a.steam_id))
}).collect();
let auto = match last.and_then(|id| acc.list.iter().find(|a| a.steam_id == id)) {
Some(a) => format!("Last played on {}", a.label()),
None => "Not played on these accounts yet: starts on the account Steam is on".into(),
};
let row = chosen.and_then(|id| acc.list.iter().position(|a| a.steam_id == id)).map_or(0, |i| i + 1);
drop(st);
drop(acc);
let lib = self.ui.global::<Lib>();
lib.set_accounts(ModelRc::new(VecModel::from(rows)));
lib.set_accounts_title(e.title.as_str().into());
lib.set_accounts_auto(auto.into());
lib.set_accounts_auto_selected(chosen.is_none());
lib.set_accounts_row(row as i32);
lib.set_accounts_open(true);
}
/// Row 0: automatic (the account it was last played on); row i: the i-th account.
pub fn pick_account(&self, row: i32) {
let idx = self.ui.global::<Lib>().get_detail().idx;
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
let picked = if row <= 0 { None } else {
match self.accounts().and_then(|a| a.list.get(row as usize - 1).cloned()) { Some(a) => Some(a), None => return }
};
let id = picked.as_ref().map(|a| a.steam_id);
match state::update(|st| st.set_steam_account(&e.id, id)) {
Ok(st) => {
*self.state.borrow_mut() = st;
self.ui.global::<Lib>().set_accounts_open(false);
self.toast(match &picked {
Some(a) => format!("{} now starts on {}", e.title, a.label()),
None => format!("{} starts on the account it was last played on", e.title),
});
self.open_detail(idx);
}
Err(err) => self.toast(format!("Could not save: {err}")),
}
}
}
+19 -4
View File
@@ -20,6 +20,12 @@ pub enum Done {
Backdrop { idx: usize, seq: u64, img: Rgb, logo: Option<Rgba> },
}
/// Decodes by what the file holds, not its name: Steam grid art from SteamGridDB is often WebP (animated, too:
/// the first frame is used) saved as `.png`.
fn open(path: &Path) -> image::ImageResult<DynamicImage> {
image::ImageReader::open(path)?.with_guessed_format()?.decode()
}
fn to_rgb(img: &RgbImage) -> Rgb { Rgb::clone_from_slice(img.as_raw(), img.width(), img.height()) }
fn to_rgba(img: &RgbaImage) -> Rgba { Rgba::clone_from_slice(img.as_raw(), img.width(), img.height()) }
@@ -32,7 +38,7 @@ fn soft(img: &DynamicImage, w: u32, h: u32, sigma: f32) -> RgbImage {
/// 2:3 thumbnail. Portrait art is cropped to fill; wide art (Steam's header.jpg) is centred on a soft copy of itself.
pub fn cover(path: &Path) -> Option<Rgb> {
let img = image::open(path).ok()?;
let img = open(path).ok()?;
let (w, h) = (img.width(), img.height());
if w == 0 || h == 0 { return None; }
let out = if (w as f32 / h as f32) < 1.05 {
@@ -58,11 +64,11 @@ fn gradient(c1: [u8; 3], c2: [u8; 3]) -> RgbImage {
/// Backdrop for the hero: the game's wide hero art if there is one, else a blurred cover, else its two colours.
pub fn backdrop(hero: Option<&Path>, cover: Option<&Path>, c1: [u8; 3], c2: [u8; 3]) -> Rgb {
if let Some(img) = hero.and_then(|p| image::open(p).ok()) {
if let Some(img) = hero.and_then(|p| open(p).ok()) {
let img = if img.width() > 1600 { img.resize(1600, 1600, FilterType::Triangle) } else { img };
return to_rgb(&img.to_rgb8());
}
if let Some(img) = cover.and_then(|p| image::open(p).ok()) {
if let Some(img) = cover.and_then(|p| open(p).ok()) {
// the middle band of the cover, where the subject usually is
let (w, h) = (img.width(), img.height());
let band = (w as f32 / 2.6).min(h as f32) as u32;
@@ -74,7 +80,7 @@ pub fn backdrop(hero: Option<&Path>, cover: Option<&Path>, c1: [u8; 3], c2: [u8;
/// Logo with its transparent margins trimmed, so it lines up with the text under it.
pub fn logo(path: &Path) -> Option<Rgba> {
let img = image::open(path).ok()?.to_rgba8();
let img = open(path).ok()?.to_rgba8();
let (mut x0, mut y0, mut x1, mut y1) = (img.width(), img.height(), 0u32, 0u32);
for (x, y, p) in img.enumerate_pixels() {
if p.0[3] > 16 { x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x); y1 = y1.max(y); }
@@ -162,6 +168,15 @@ mod tests {
assert!(g.as_slice()[0].r > 200 && g.as_slice().last().unwrap().b > 200);
}
#[test]
fn art_is_read_by_content_not_by_name() {
// a JPEG saved as .png, the way grid art often is
let p = tmp("really-a-jpeg.png");
let mut buf = std::io::Cursor::new(Vec::new());
RgbImage::from_pixel(60, 90, image::Rgb([200, 10, 10])).write_to(&mut buf, image::ImageFormat::Jpeg).unwrap();
std::fs::write(&p, buf.into_inner()).unwrap();
assert!(cover(&p).is_some());
}
#[test]
fn logo_is_trimmed_to_its_pixels() {
let p = tmp("logo.png");
let mut img = RgbaImage::new(100, 40);
+391 -121
View File
@@ -1,7 +1,7 @@
//! What the views show, computed from the scanned entries. No UI types here, so it is unit tested.
use summit_core::model::{Entry, Kind, Source};
use summit_core::display::Output;
use summit_core::profile::Profile;
use summit_core::profile::{Layer, Profile};
pub const SHELF_MAX: usize = 24;
@@ -27,7 +27,7 @@ pub fn ago(last: Option<u64>, now: u64) -> String {
}
pub fn source_label(s: Source) -> &'static str {
match s { Source::Steam => "Steam", Source::Heroic => "Heroic", Source::Lutris => "Lutris", Source::Heuristic => "Found on disk", Source::Custom => "Added by you" }
match s { Source::Steam => "Steam", Source::Heroic => "Heroic", Source::Lutris => "Lutris", Source::Heuristic => "Found on disk", Source::Custom => "Added by you", Source::Console => "Console" }
}
pub fn kind_label(k: Kind) -> &'static str { match k { Kind::Game => "Game", Kind::Software => "Software", Kind::Tool => "Tool" } }
@@ -82,7 +82,7 @@ pub enum Row { Header { label: String, count: usize }, Item(usize) }
/// Unfiltered view: everything that is on this machine, grouped by source and kind, each group under a header.
pub fn unfiltered(entries: &[Entry]) -> Vec<Row> {
let mut out = vec![];
for src in [Source::Steam, Source::Heroic, Source::Lutris, Source::Custom, Source::Heuristic] {
for src in [Source::Steam, Source::Heroic, Source::Lutris, Source::Console, Source::Custom, Source::Heuristic] {
for (kind, label) in [(Kind::Game, "GAMES"), (Kind::Software, "SOFTWARE"), (Kind::Tool, "TOOLS")] {
let mut items: Vec<usize> = (0..entries.len()).filter(|i| entries[*i].source == src && entries[*i].kind == kind && entries[*i].installed).collect();
if items.is_empty() { continue; }
@@ -97,17 +97,29 @@ pub fn unfiltered(entries: &[Entry]) -> Vec<Row> {
pub struct ProfileSummary { pub monitor: String, pub mode: String, pub upscaler: String, pub framegen: String, pub window: String, pub set: bool }
pub fn upscaler_label(u: &str) -> String {
match u { "" | "none" => "None".into(), "fsr" => "FSR".into(), "nis" => "NIS".into(), "rtx-vsr" | "vsr" => "RTX Video Super Resolution".into(), "dlss" => "DLSS".into(), o => o.to_string() }
match u { "" => "Engine setting".into(), "none" => "None".into(), "fsr" => "FSR".into(), "nis" => "NIS".into(), "rtx-vsr" | "vsr" => "RTX Video Super Resolution".into(), "bilinear" => "Bilinear".into(), "dlss" => "DLSS".into(), o => o.to_string() }
}
pub fn profile_summary(p: &Profile) -> ProfileSummary {
pub fn window_mode_label(m: &str) -> &'static str {
match m { "windowed" => "Windowed", "borderless" => "Borderless window", "fullscreen" => "Fullscreen", _ => "As the game opens it" }
}
/// The game's page: what it launches with (`p`, the defaults with its own settings on top). `own` is how many
/// settings the game sets itself.
pub fn profile_summary(p: &Profile, own: usize) -> ProfileSummary {
let res = match (p.width, p.height) { (Some(w), Some(h)) => Some(format!("{w} × {h}")), _ => None };
let hz = p.refresh_hz.map(|r| if r.fract() == 0.0 { format!("{r:.0} Hz") } else { format!("{r:.2} Hz") });
let mode = match (res, hz) { (Some(r), Some(h)) => format!("{r} at {h}"), (Some(r), None) => r, (None, Some(h)) => h, (None, None) => "Default".into() };
let framegen = match p.framegen.as_str() {
"" | "none" => "None".to_string(),
"none" => "None".to_string(),
f => {
let name = if f == "rife" { "RIFE".to_string() } else if f == "lsfg" { "lsfg-vk".to_string() } else { f.to_string() };
let name = match (f, p.model.as_deref()) {
(_, Some("vfg")) => "NVIDIA VFG".to_string(),
("" | "rife", Some(m)) => format!("RIFE {m}"),
("" | "rife", None) => "RIFE".to_string(),
("lsfg", _) => "lsfg-vk".to_string(),
(f, _) => f.to_string(),
};
match (p.framegen_multiplier, p.target_hz) {
(m, Some(hz)) if m > 1 => format!("{name} ×{m}, {hz} Hz out"),
(m, None) if m > 1 => format!("{name} ×{m}"),
@@ -116,30 +128,49 @@ pub fn profile_summary(p: &Profile) -> ProfileSummary {
}
}
};
let window = match (p.fullscreen, p.focus) { (true, true) => "Fullscreen, focused", (true, false) => "Fullscreen", (false, true) => "Focused", _ => "Default" };
let window = match (p.window_mode.as_str(), p.focus) { ("", false) => "Default".to_string(), ("", true) => "Focused".to_string(), (m, f) => format!("{}{}", window_mode_label(m), if f { ", focused" } else { "" }) };
ProfileSummary {
monitor: p.monitor.clone().unwrap_or_else(|| "Default".into()), mode, upscaler: upscaler_label(&p.upscaler), framegen, window: window.into(),
set: *p != Profile::default(),
monitor: p.monitor.clone().unwrap_or_else(|| "Default".into()), mode, upscaler: upscaler_label(&p.upscaler), framegen, window,
set: own > 0,
}
}
// ---- the profile editor ----
/// One row of the profile editor: a value picked from `options`.
#[derive(Debug, Clone, PartialEq)]
pub struct EditRow { pub label: &'static str, pub hint: String, pub options: Vec<String>, pub value: usize }
// One editor for both the launcher's defaults and a game. Each row is one setting of a profile layer
// (summit_core::profile::Layer). On a game every row starts with "Default · <what the defaults say>": that leaves
// the setting out of the game's file, so the game follows the defaults. Values are encoded as text for the row:
// None = not set in this layer, Some("") = set to "not chosen" (e.g. never switch monitors).
pub const UPSCALERS: [&str; 3] = ["none", "fsr", "rtx-vsr"];
pub const TARGET_HZ: [u32; 3] = [60, 90, 120];
#[cfg(test)]
pub const EDIT_ROWS: usize = 8;
/// What a row is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowKind { Choice, Text, Header }
#[derive(Debug, Clone, PartialEq)]
pub struct EditRow {
/// The setting (profile::KEYS, or "resolution" for width and height together); "" for a header.
pub key: &'static str,
pub kind: RowKind,
pub label: String,
pub hint: String,
pub options: Vec<String>,
pub value: usize,
/// Text rows: this layer's text, and what is used when it is left empty.
pub text: String,
pub placeholder: String,
/// The game sets this itself (always false on the defaults).
pub own: bool,
}
/// One choice: how it is stored (None: not set here) and its label.
type Choice = (Option<String>, String);
fn rate_label(r: f32) -> String { if (r - r.round()).abs() < 0.005 { format!("{r:.0} Hz") } else { format!("{r:.2} Hz") } }
fn same_rate(a: f32, b: f32) -> bool { (a - b).abs() < 0.01 }
/// The monitors to choose from: connected outputs, plus the profile's own if it is not connected now.
pub fn monitor_names(p: &Profile, outs: &[Output]) -> Vec<String> {
/// The monitors to choose from: connected outputs, plus `extra` (a profile's own) if it is not connected now.
pub fn monitor_names(extra: Option<&str>, outs: &[Output]) -> Vec<String> {
let mut v: Vec<String> = outs.iter().filter(|o| o.connected).map(|o| o.name.clone()).collect();
if let Some(m) = &p.monitor { if !v.contains(m) { v.push(m.clone()); } }
if let Some(m) = extra.filter(|m| !m.is_empty()) { if !v.iter().any(|x| x == m) { v.push(m.to_string()); } }
v
}
fn sizes(p: &Profile, outs: &[Output]) -> Vec<(u32, u32)> {
@@ -158,67 +189,237 @@ fn rates(p: &Profile, outs: &[Output]) -> Vec<f32> {
v
}
/// Editor rows for `p`. `outs` is what the display module listed; `list_err` why there is no list.
pub fn edit_rows(p: &Profile, outs: &[Output], list_err: Option<&str>, tool: &str) -> Vec<EditRow> {
let onoff = |b: bool| (vec!["Off".to_string(), "On".to_string()], b as usize);
let mons = monitor_names(p, outs);
let mut mon_opts = vec!["Default".to_string()];
mon_opts.extend(mons.iter().map(|m| if outs.iter().any(|o| &o.name == m && o.connected) { m.clone() } else { format!("{m} (not connected)") }));
let mon_val = p.monitor.as_ref().and_then(|m| mons.iter().position(|x| x == m)).map_or(0, |i| i + 1);
let sz = sizes(p, outs);
let mut sz_opts = vec!["Default".to_string()];
sz_opts.extend(sz.iter().map(|(w, h)| format!("{w} × {h}")));
let sz_val = match (p.width, p.height) { (Some(w), Some(h)) => sz.iter().position(|x| *x == (w, h)).map_or(0, |i| i + 1), _ => 0 };
let rt = rates(p, outs);
let mut rt_opts = vec!["Default".to_string()];
rt_opts.extend(rt.iter().map(|r| rate_label(*r)));
let rt_val = p.refresh_hz.and_then(|r| rt.iter().position(|x| same_rate(*x, r))).map_or(0, |i| i + 1);
let (fs, fs_v) = onoff(p.fullscreen);
let (fo, fo_v) = onoff(p.focus);
let up_v = UPSCALERS.iter().position(|u| *u == p.upscaler || (*u == "rtx-vsr" && p.upscaler == "vsr")).unwrap_or(0);
let hz_v = TARGET_HZ.iter().position(|h| Some(*h) == p.target_hz).unwrap_or(0);
let mon_hint = match list_err {
Some(e) => format!("Monitors could not be listed: {e}."),
None => format!("Listed with {tool}. Switched with {tool} when Summit starts the game, and put back when it ends."),
};
vec![
EditRow { label: "Monitor", hint: mon_hint, options: mon_opts, value: mon_val },
EditRow { label: "Resolution", hint: if p.monitor.is_none() { "Pick a monitor first.".into() } else { "The monitor's mode while the game runs.".into() }, options: sz_opts, value: sz_val },
EditRow { label: "Refresh rate", hint: if p.width.is_none() { "Pick a resolution first.".into() } else { "Rates this mode offers.".into() }, options: rt_opts, value: rt_val },
EditRow { label: "Fullscreen", hint: "With Enhance: the engine's picture covers the whole monitor (where the upscaler has work to do). The game's own window mode is not changed.".into(), options: fs, value: fs_v },
EditRow { label: "Focus", hint: "Stored only: raising the game window after launch is not built yet.".into(), options: fo, value: fo_v },
EditRow { label: "Upscaler", hint: "Used by Enhance. FSR was run on the test machine; RTX VSR is wired but untested.".into(), options: vec!["None".into(), "FSR".into(), "RTX VSR".into()], value: up_v },
EditRow { label: "Frame generation", hint: "Used by Enhance: RIFE needs an NVIDIA GPU and the engine's Python environment.".into(), options: vec!["None".into(), "RIFE".into()], value: (p.framegen == "rife") as usize },
EditRow { label: "Target rate", hint: "The engine's output rate. 60 Hz was tested; 90 and 120 Hz are wired, not tested.".into(), options: TARGET_HZ.iter().map(|h| format!("{h} Hz")).collect(), value: hz_v },
]
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> {
match key {
"monitor" => l.monitor.clone(),
"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() }),
"model" => l.model.clone(), "vfg_quality" => l.vfg_quality.clone(), "motion" => l.motion.clone(),
"ai_engine" => l.ai_engine.clone(), "fill" => l.fill.clone(),
_ => None,
}
}
/// `p` with editor row `row` set to option `value` (as indexed in `edit_rows`).
pub fn edit_apply(p: &Profile, outs: &[Output], row: usize, value: usize) -> Profile {
let mut p = p.clone();
match row {
0 => {
let mons = monitor_names(&p, outs);
let new = if value == 0 { None } else { mons.get(value - 1).cloned() };
if new != p.monitor { p.monitor = new; p.width = None; p.height = None; p.refresh_hz = None; }
/// Store an encoded row value into a layer (None: leave it to the layer below).
pub fn enc_set(l: &mut Layer, key: &str, v: Option<&str>) {
let b = |v: Option<&str>| v.map(|s| s == "on");
let s = |v: Option<&str>| v.map(str::to_string);
match key {
"monitor" => {
if enc_get(l, "monitor").as_deref() != v { l.width = None; l.height = None; l.refresh_hz = None; }
l.monitor = s(v);
}
1 => {
let sz = sizes(&p, outs);
let new = if value == 0 { None } else { sz.get(value - 1).copied() };
if new != p.width.zip(p.height) {
p.width = new.map(|x| x.0); p.height = new.map(|x| x.1);
if let Some(r) = p.refresh_hz { p.refresh_hz = None; if rates(&p, outs).iter().any(|x| same_rate(*x, r)) { p.refresh_hz = Some(r); } }
}
"resolution" => {
let wh = v.map(|t| t.split_once('x').and_then(|(w, h)| Some((w.parse::<u32>().ok()?, h.parse::<u32>().ok()?))).unwrap_or((0, 0)));
if wh.map(|x| (Some(x.0), Some(x.1))) != Some((l.width, l.height)) { l.refresh_hz = None; }
l.width = wh.map(|x| x.0); l.height = wh.map(|x| x.1);
}
2 => { p.refresh_hz = if value == 0 { None } else { rates(&p, outs).get(value - 1).copied() }; }
3 => p.fullscreen = value == 1,
4 => p.focus = value == 1,
5 => p.upscaler = UPSCALERS[value.min(2)].into(),
6 => p.framegen = if value == 1 { "rife".into() } else { "none".into() },
7 => p.target_hz = Some(TARGET_HZ[value.min(2)]),
"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)),
"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),
_ => {}
}
p
}
/// Everything the editor needs to build its rows.
pub struct EditCtx<'a> {
/// The layer being edited.
pub own: &'a Layer,
/// What it sits on: the built-in values for the defaults, the defaults for a game.
pub base: &'a Profile,
/// Editing the launcher's defaults (no "Default · ..." choices).
pub defaults: bool,
pub outs: &'a [Output],
pub list_err: Option<&'a str>,
/// The tool that lists and switches monitors here (xrandr, kscreen-doctor, wlr-randr).
pub tool: &'a str,
/// How the game's window is placed here (KWin, wmctrl), or why it cannot be.
pub placer: Result<&'a str, &'a str>,
}
fn label_of(choices: &[Choice], v: &Option<String>) -> String {
choices.iter().find(|c| &c.0 == v).map(|c| c.1.clone()).unwrap_or_else(|| v.clone().unwrap_or_default())
}
/// Choices of a row on the defaults (the first is "not set") and its base value, encoded.
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" => {
let mut v = vec![unset("Don't switch")];
let mons = monitor_names(own.monitor.as_deref().or(base.monitor.as_deref()), outs);
v.extend(mons.iter().map(|m| c(m, &if outs.iter().any(|o| &o.name == m && o.connected) { m.clone() } else { format!("{m} (not connected)") })));
(v, opt(base.monitor.clone()))
}
"resolution" => {
let mut v = vec![unset("The monitor's own")];
v.extend(sizes(eff, outs).iter().map(|(w, h)| c(&format!("{w}x{h}"), &format!("{w} × {h}"))));
(v, opt(base.width.zip(base.height).map(|(w, h)| format!("{w}x{h}"))))
}
"refresh_hz" => {
let mut v = vec![unset("The mode's own")];
v.extend(rates(eff, outs).iter().map(|r| c(&format!("{r}"), &rate_label(*r))));
(v, opt(base.refresh_hz.map(|r| format!("{r}"))))
}
"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", "None"), 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))),
"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),
}
}
/// What the layer being edited gives: its base with the layer on top.
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> {
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
}
/// Text rows: launch arguments and environment variables, as one line each.
fn text_of(l: &Layer, key: &str) -> Option<String> {
match key {
"launch_args" => l.launch_args.as_ref().map(|a| summit_core::profile::join_args(a)),
"env" => l.env.as_ref().map(summit_core::profile::join_env),
_ => None,
}
}
/// 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.
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)" }),
};
let place_note = match cx.placer { Ok(t) => format!("Done through {t} once the window opens."), Err(e) => format!("Not on this desktop: {e}.") };
let spec: Vec<(&str, &'static str, String)> = vec![
("#", "DISPLAY", String::new()),
("monitor", "Monitor", mon_hint),
("resolution", "Resolution", if eff.monitor.is_none() { "Pick a monitor first.".into() } else { "The monitor's mode while the game runs.".into() }),
("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()),
("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()),
("target_hz", "Output rate", "The engine's output rate. 60 Hz was tested; 90 and 120 Hz are wired, not tested.".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()),
("#", "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()),
];
for (key, label, hint) in spec {
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" | "target_hz" | "steady_hud" => eff.framegen == "none",
"motion" | "ai_engine" => !rife,
_ => false,
};
if skip && !cx.own.has(key) { continue; }
let own = !cx.defaults && match key { "resolution" => cx.own.width.is_some() || cx.own.height.is_some(), k => cx.own.has(k) };
if matches!(key, "launch_args" | "env") {
let base_text = match key { "launch_args" => summit_core::profile::join_args(&cx.base.launch_args), _ => summit_core::profile::join_env(&cx.base.env) };
let placeholder = if cx.defaults || base_text.is_empty() { "None".to_string() } else { format!("Default: {base_text}") };
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 });
continue;
}
let (ch, base_v) = choices(key, &eff, cx.base, cx.outs, cx.own);
let base_label = label_of(&ch, &base_v.filter(|v| !v.is_empty()));
let mut ch = layer_choices(key, ch, cx.defaults, &base_label);
let cur = enc_get(cx.own, key);
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 => { 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 });
}
rows
}
/// The layer with choice row `key` set to option `value` (as listed by `edit_rows` for the same layer).
pub fn edit_apply(cx: &EditCtx, key: &str, value: usize) -> Layer {
let mut l = cx.own.clone();
let (ch, _) = choices(key, &effective(cx), cx.base, cx.outs, cx.own);
let ch = layer_choices(key, ch, cx.defaults, "");
let Some((enc, _)) = ch.get(value) else { return l };
enc_set(&mut l, key, enc.as_deref());
l
}
/// The layer with text row `key` set to `text`. Empty: not set here. Bad environment text is an error.
pub fn edit_text(own: &Layer, key: &str, text: &str) -> Result<Layer, String> {
let mut l = own.clone();
let t = text.trim();
match key {
"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)?) },
_ => {}
}
Ok(l)
}
/// The error `summit run` ended with, from its output: the last "Error: ..." line, else the last line.
@@ -343,64 +544,133 @@ mod tests {
}
#[test]
fn profile_summary_says_default_when_unset() {
let s = profile_summary(&Profile::default());
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("Default", "Default", "None", "None", "Default", false));
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(59.94), fullscreen: true, focus: true, upscaler: "fsr".into(), framegen: "rife".into(), framegen_multiplier: 2, target_hz: Some(120), ..Default::default() };
let s = profile_summary(&p);
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("HDMI-A-1", "3840 × 2160 at 59.94 Hz", "FSR", "RIFE ×2, 120 Hz out", "Fullscreen, focused", true));
let s = profile_summary(&Profile::default(), 0);
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("Default", "Default", "Engine setting", "RIFE", "Default", false));
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(59.94), window_mode: "borderless".into(), focus: true, upscaler: "fsr".into(), framegen: "rife".into(), framegen_multiplier: 2, target_hz: Some(120), ..Default::default() };
let s = profile_summary(&p, 3);
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("HDMI-A-1", "3840 × 2160 at 59.94 Hz", "FSR", "RIFE ×2, 120 Hz out", "Borderless window, focused", true));
assert_eq!(profile_summary(&Profile { framegen: "none".into(), ..Default::default() }, 0).framegen, "None");
}
#[test]
fn colours_are_stable_per_title() { assert_eq!(colors("Portal 2"), colors("Portal 2")); }
fn outs() -> Vec<Output> {
summit_core::display::parse_xrandr("Screen 0: minimum 320 x 200\nVirtual-1 connected primary 1920x1080+0+0 (normal)\n 1920x1080 60.00*+ 50.00\n 1280x720 60.00 59.94\nHDMI-1 disconnected (normal)\n")
}
fn cx<'a>(own: &'a Layer, base: &'a Profile, defaults: bool, o: &'a [Output]) -> EditCtx<'a> {
EditCtx { own, base, defaults, outs: o, list_err: None, tool: "xrandr", placer: Ok("KWin") }
}
fn row<'a>(rows: &'a [EditRow], key: &str) -> &'a EditRow { rows.iter().find(|r| r.key == key).unwrap_or_else(|| panic!("no row {key}")) }
fn set(own: &Layer, base: &Profile, defaults: bool, o: &[Output], key: &str, label: &str) -> Layer {
let rows = edit_rows(&cx(own, base, defaults, o));
let r = row(&rows, key);
let i = r.options.iter().position(|x| x == label).unwrap_or_else(|| panic!("{key}: no {label:?} in {:?}", r.options));
edit_apply(&cx(own, base, defaults, o), key, i)
}
#[test]
fn editor_lists_real_outputs_and_their_modes() {
fn defaults_editor_lists_real_outputs_and_their_modes() {
let o = outs();
let r = edit_rows(&Profile::default(), &o, None, "xrandr");
assert_eq!(r.len(), EDIT_ROWS);
assert_eq!(r[0].options, vec!["Default", "Virtual-1"]); // disconnected outputs are left out
assert_eq!((r[0].value, r[1].options.len(), r[2].options.len()), (0, 1, 1));
let p = edit_apply(&Profile::default(), &o, 0, 1);
assert_eq!(p.monitor.as_deref(), Some("Virtual-1"));
let r = edit_rows(&p, &o, None, "xrandr");
assert_eq!(r[1].options, vec!["Default", "1920 × 1080", "1280 × 720"]);
let p = edit_apply(&p, &o, 1, 2);
assert_eq!((p.width, p.height), (Some(1280), Some(720)));
let r = edit_rows(&p, &o, None, "xrandr");
assert_eq!(r[2].options, vec!["Default", "60 Hz", "59.94 Hz"]);
let p = edit_apply(&p, &o, 2, 2);
assert_eq!(p.refresh_hz, Some(59.94));
// a size without that rate drops the rate; switching monitor drops the whole mode
let q = edit_apply(&p, &o, 1, 1);
let base = Profile::default();
let l = Layer::default();
let rows = edit_rows(&cx(&l, &base, true, &o));
assert_eq!(row(&rows, "monitor").options, vec!["Don't switch", "Virtual-1"]); // disconnected outputs are left out
assert!(rows.iter().any(|r| r.kind == RowKind::Header));
let l = set(&l, &base, true, &o, "monitor", "Virtual-1");
assert_eq!(l.monitor.as_deref(), Some("Virtual-1"));
assert_eq!(row(&edit_rows(&cx(&l, &base, true, &o)), "resolution").options, vec!["The monitor's own", "1920 × 1080", "1280 × 720"]);
let l = set(&l, &base, true, &o, "resolution", "1280 × 720");
assert_eq!((l.width, l.height), (Some(1280), Some(720)));
assert_eq!(row(&edit_rows(&cx(&l, &base, true, &o)), "refresh_hz").options, vec!["The mode's own", "60 Hz", "59.94 Hz"]);
let l = set(&l, &base, true, &o, "refresh_hz", "59.94 Hz");
assert_eq!(l.refresh_hz, Some(59.94));
assert_eq!(row(&edit_rows(&cx(&l, &base, true, &o)), "refresh_hz").value, 2);
// another size drops the rate; another monitor drops the whole mode
let q = set(&l, &base, true, &o, "resolution", "1920 × 1080");
assert_eq!((q.width, q.refresh_hz), (Some(1920), None));
let q = edit_apply(&p, &o, 0, 0);
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);
}
#[test]
fn editor_keeps_a_monitor_that_is_not_connected() {
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(120.0), ..Default::default() };
let r = edit_rows(&p, &outs(), None, "xrandr");
assert_eq!(r[0].options[r[0].value], "HDMI-A-1 (not connected)");
assert_eq!(r[1].options[r[1].value], "3840 × 2160");
assert_eq!(r[2].options[r[2].value], "120 Hz");
let r = edit_rows(&p, &[], Some("GNOME Wayland has no stable tool"), "");
assert!(r[0].hint.contains("could not be listed"));
}
#[test]
fn editor_switches_and_engine_settings() {
fn a_game_follows_the_defaults_or_overrides_them() {
let o = outs();
let p = Profile::default();
let p = edit_apply(&p, &o, 3, 1);
let p = edit_apply(&p, &o, 4, 1);
let p = edit_apply(&p, &o, 5, 1);
let p = edit_apply(&p, &o, 6, 1);
let p = edit_apply(&p, &o, 7, 2);
assert!(p.fullscreen && p.focus);
assert_eq!((p.upscaler.as_str(), p.framegen.as_str(), p.target_hz), ("fsr", "rife", Some(120)));
let r = edit_rows(&p, &o, None, "xrandr");
assert_eq!((r[3].value, r[4].value, r[5].value, r[6].value, r[7].value), (1, 1, 1, 1, 2));
let p = edit_apply(&p, &o, 6, 0);
assert_eq!(p.framegen, "none");
let d = Layer { upscaler: Some("fsr".into()), window_mode: Some("borderless".into()), monitor: Some("Virtual-1".into()), enhance: Some(true), ..Default::default() };
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");
// overriding with "not chosen" is a real value in the game's file
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 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"));
// back to Default: left out of the file again
assert!(set(&g3, &base, false, &o, "upscaler", "Default · AMD FSR 1").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() {
let o = outs();
let base = Profile::default();
let g = set(&Layer::default(), &base, false, &o, "monitor", "Virtual-1");
let rows = edit_rows(&cx(&g, &base, false, &o));
assert_eq!(row(&rows, "resolution").options, vec!["Default · The monitor's own", "The monitor's own", "1920 × 1080", "1280 × 720"]);
let g = set(&g, &base, false, &o, "resolution", "1280 × 720");
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]);
let rows = edit_rows(&cx(&Layer::default(), &base, false, &[]));
let env = row(&rows, "env");
assert_eq!((env.kind, env.text.as_str(), env.placeholder.as_str()), (RowKind::Text, "", "Default: MANGOHUD=1"));
let g = edit_text(&Layer::default(), "env", "DXVK_HUD=fps A=\"b c\"").unwrap();
assert_eq!(g.env.as_ref().unwrap().get("A").map(String::as_str), Some("b c"));
assert!(edit_text(&Layer::default(), "env", "nope").is_err());
let g = edit_text(&g, "launch_args", " -windowed -dx11 ").unwrap();
assert_eq!(g.launch_args, Some(vec!["-windowed".to_string(), "-dx11".to_string()]));
assert_eq!(edit_text(&g, "launch_args", " ").unwrap().launch_args, None);
assert_eq!(row(&edit_rows(&cx(&g, &base, false, &[])), "launch_args").text, "-windowed -dx11");
}
#[test]
fn a_monitor_that_is_not_connected_is_kept() {
let l = Layer { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(120.0), ..Default::default() };
let base = Profile::default();
let rows = edit_rows(&cx(&l, &base, true, &outs()));
let m = row(&rows, "monitor");
assert_eq!(m.options[m.value], "HDMI-A-1 (not connected)");
let r = row(&rows, "resolution");
assert_eq!(r.options[r.value], "3840 × 2160");
let r = row(&rows, "refresh_hz");
assert_eq!(r.options[r.value], "120 Hz");
let e = EditCtx { list_err: Some("GNOME Wayland has no stable tool"), ..cx(&l, &base, true, &[]) };
assert!(row(&edit_rows(&e), "monitor").hint.contains("could not be listed"));
}
}
+637 -53
View File
@@ -1,4 +1,5 @@
//! Summit launcher window. The UI is in ui/*.slint; this file feeds it data and carries out its actions.
mod accounts;
mod art;
mod data;
mod pad;
@@ -9,7 +10,8 @@ use std::cell::{Cell, RefCell};
use std::collections::{HashSet, VecDeque};
use std::path::PathBuf;
use std::rc::Rc;
use summit_core::{display, hotkey, launch, model::{Entry, Kind, Source}, profile, scan, state, steam, ui as prefs};
use std::time::{Duration, Instant};
use summit_core::{artwork, console, display, hotkey, launch, model::{Entry, Kind, Source}, profile, running, scan, state, ui as prefs, winmode};
slint::include_modules!();
@@ -34,39 +36,112 @@ pub struct App {
backdrop_seq: Cell<u64>,
backdrop_for: Cell<i64>,
settings: RefCell<prefs::UiSettings>,
default_profile: RefCell<profile::Profile>,
theme_keys: Vec<String>,
pub headless: bool,
base_scale: Cell<f32>,
fullscreen: Cell<bool>,
save_timer: slint::Timer,
/// The profile editor's game id and the outputs listed when it opened (or why there is no list).
editing: RefCell<Option<(usize, Outputs)>>,
/// What the profile editor is editing, if it is open.
editing: RefCell<Option<Editing>>,
/// 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.
gen: Cell<u64>,
/// What each row and button of the Add dialog's list does, in order (rows, then buttons).
add_actions: RefCell<Vec<AddAction>>,
/// The consoles that answered the last network search (None: still looking), and which search that was.
remote_found: RefCell<Option<Vec<console::Found>>>,
discover_seq: Cell<u64>,
/// chiaki-ng's path and whether it has the frame tap (reading the binary once, not on every page).
chiaki_tap: RefCell<Option<(PathBuf, bool)>>,
/// The Steam accounts on this PC, read when first needed (accounts.rs).
steam_accounts: RefCell<Option<accounts::Accounts>>,
/// The game started from here that is still running: the launcher shows only the "now playing" screen.
playing: RefCell<Option<Playing>>,
/// Counts the starts, so a game that ends after the launcher was taken back does not end the next one.
play_seq: Cell<u64>,
play_timer: slint::Timer,
}
/// A game started with Play, from the moment it is started until it is gone (ui/playing.slint).
struct Playing {
seq: u64,
/// The game's row, for its cover.
idx: usize,
title: String,
started: Instant,
/// 0 starting, 1 running, 2 stopping (Lib.play-phase)
phase: i32,
/// What the screen says while it starts: "Opening through Steam, with Enhance".
how: String,
/// `summit run`'s process while it runs. For a game Summit starts itself it lasts as long as the game.
child: Option<u32>,
/// How long `summit run` ran, once it has ended.
child_ran: Option<Duration>,
/// A game its own launcher starts (Steam, Lutris, Heroic): how its processes are found, and what was seen.
tracker: Option<(running::Marker, running::Tracker)>,
track: running::Phase,
scanned: Option<Instant>,
/// The launcher's window lost the keyboard after the start: the game's window has it.
lost_focus: bool,
status: String,
}
/// A row or button in the Add dialog.
#[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> {
self.state.borrow().artwork.get(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| e.steam_app_id.and_then(steam::cover))
self.state.borrow().artwork.get(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| artwork::cover(e))
}
fn hero_path(&self, e: &Entry) -> Option<PathBuf> {
self.state.borrow().hero_art(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| e.steam_app_id.and_then(steam::hero))
self.state.borrow().hero_art(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| artwork::hero(e))
}
fn logo_path(&self, e: &Entry) -> Option<PathBuf> {
self.state.borrow().logo_art(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| e.steam_app_id.and_then(steam::logo))
self.state.borrow().logo_art(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| artwork::logo(e))
}
fn cli(&self) -> Option<PathBuf> {
std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join("summit"))).filter(|p| p.is_file())
}
fn console_of(&self, id: &str) -> Option<console::Console> {
self.state.borrow().consoles.iter().find(|c| c.id == id).cloned()
}
/// chiaki-ng and whether it carries SmoovPlay's frame tap. The answer is kept while the path stays the same.
fn chiaki(&self) -> Option<(PathBuf, bool)> {
let path = console::chiaki_binary()?;
if let Some((p, tap)) = self.chiaki_tap.borrow().as_ref() { if *p == path { return Some((path, *tap)); } }
let tap = console::has_frame_tap(&path);
*self.chiaki_tap.borrow_mut() = Some((path.clone(), tap));
Some((path, tap))
}
fn row(&self, e: &Entry, keep: Option<&Game>) -> Game {
let (c1, c2) = data::colors(&e.title);
let con = if e.source == Source::Console { self.console_of(&e.id) } else { None };
let (c1, c2) = match con.as_ref().map(|c| &c.link) {
Some(console::Link::RemotePlay { .. }) => ([0x2b, 0x5c, 0xe0], [0x0a, 0x17, 0x45]),
Some(console::Link::Capture { .. }) => ([0x1f, 0x8a, 0x9c], [0x0a, 0x24, 0x33]),
None => data::colors(&e.title),
};
let (glyph, source) = match con.as_ref().map(|c| &c.link) {
Some(console::Link::RemotePlay { .. }) => (1, "PS Remote Play"),
Some(console::Link::Capture { .. }) => (2, "Capture card"),
None => (0, data::source_label(e.source)),
};
let action = match launch::plan(e, self.cli().as_deref(), false) {
launch::Plan::Run(_) if launch::is_install(e) => "INSTALL",
launch::Plan::Run(_) => "PLAY",
@@ -77,7 +152,7 @@ impl App {
id: e.id.as_str().into(), title: e.title.as_str().into(),
hours: data::hours_long(e.playtime_minutes).into(), hours_short: data::hours_short(e.playtime_minutes).into(),
last: data::ago(e.last_played, now()).into(),
source: data::source_label(e.source).into(), kind: data::kind_label(e.kind).into(),
source: source.into(), kind: data::kind_label(e.kind).into(), glyph,
installed: e.installed, pinned: self.state.borrow().is_pinned(&e.id),
cover: keep.map(|g| g.cover.clone()).unwrap_or_default(), has_cover: keep.is_some_and(|g| g.has_cover),
c1: rgb(c1), c2: rgb(c2), reasons: short(&e.reasons.join(" · ")).into(), action: action.into(),
@@ -141,6 +216,11 @@ impl App {
let Some(img) = img else { return };
let Some(mut g) = self.games.row_data(idx) else { return };
g.cover = Image::from_rgb8(img); g.has_cover = true;
if self.playing.borrow().as_ref().is_some_and(|p| p.idx == idx) { // the "now playing" screen's cover
let lib = self.ui.global::<Lib>();
lib.set_play_art(g.cover.clone());
lib.set_play_has_art(true);
}
self.games.set_row_data(idx, g);
let dropped: Vec<usize> = {
let (mut loaded, keep) = (self.loaded.borrow_mut(), self.keep.borrow());
@@ -184,7 +264,11 @@ 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 p = data::profile_summary(&profile::load(&e.id).unwrap_or_default());
let own = profile::load_layer(&e.id).unwrap_or_default();
let own_n = profile::KEYS.iter().filter(|k| own.has(k)).count();
let p = data::profile_summary(&profile::load(&e.id).unwrap_or_default(), own_n);
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();
let (sessions, note) = if e.source == Source::Steam {
("–".to_string(), "Steam does not report sessions")
@@ -194,6 +278,7 @@ impl App {
let (label, can, play_note) = match launch::plan(&e, self.cli().as_deref(), false) {
launch::Plan::Run(_) if launch::is_install(&e) => ("INSTALL", true, "Opens Steam's install dialog for this game.".to_string()),
launch::Plan::Run(_) if e.source == Source::Steam => ("PLAY", true, "Starts through summit run and the Steam client: the display profile is applied, Steam keeps the playtime. Not tested with a real Steam yet.".to_string()),
launch::Plan::Run(_) if console_play.is_some() => { let (can, note) = console_play.clone().unwrap_or_default(); ("PLAY", can, note) }
launch::Plan::Run(_) if e.source == Source::Lutris => ("PLAY", true, "Starts through summit run and Lutris. Not tested yet.".to_string()),
launch::Plan::Run(_) => ("PLAY", true, "Summit starts it, applies the launch profile and tracks the session.".to_string()),
launch::Plan::Unsupported(_) if e.source == Source::Heuristic => ("ADD", true, "Found on disk. ADD asks for the file that starts it and a name, then the game can be played from Summit.".to_string()),
@@ -202,12 +287,19 @@ impl App {
let (can_enhance, enhance_note) = self.enhance_available(&e);
let reasons: Vec<SharedString> = e.reasons.iter().map(|r| short(r).into()).collect();
let prof = profile::load(&e.id).unwrap_or_default();
let (has_account, account, account_note) = self.account_card(&e, &st);
self.ui.global::<Lib>().set_detail(Detail {
idx, sessions: sessions.into(), sessions_note: note.into(), reasons: ModelRc::new(VecModel::from(reasons)),
path: short(&e.path.clone().unwrap_or_default()).into(),
path: short(&con.as_ref().map(|c| match &c.link {
console::Link::RemotePlay { nickname, host: Some(h), .. } => format!("chiaki-ng · {nickname} · last seen at {h}"),
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() },
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(),
});
drop(st);
self.want_cover(idx as usize);
@@ -215,9 +307,47 @@ impl App {
self.focus_game(idx);
}
/// Whether Play can start a console here, and the line its page shows about Play.
fn console_play(&self, c: &console::Console) -> (bool, String) {
match &c.link {
console::Link::RemotePlay { nickname, .. } => {
if self.chiaki().is_none() {
return (false, "Remote Play needs chiaki-ng: run install.sh --with-remote-play (it builds chiaki-ng with SmoovPlay's frame tap).".into());
}
if !console::registered().iter().any(|r| &r.nickname == nickname) {
return (false, format!("chiaki-ng has no console named {nickname} any more: link it again in chiaki-ng."));
}
(true, format!("Finds {nickname} on your network (waking it from rest mode) and streams it with chiaki-ng. Your controller connects to this PC; chiaki-ng sends it on."))
}
console::Link::Capture { device } => {
if summit_core::engine::find_engine().is_none() {
return (false, "The card's picture is shown by Summit's engine, which was not found: run install.sh.".into());
}
if !device.starts_with("/dev/") && !console::capture_devices().iter().any(|d| &d.name == device) {
return (false, format!("{device} is not plugged in (or Summit can't open it: is your user in the video group?)."));
}
(true, format!("Shows {device} on screen through Summit's engine, with the card's sound. Press q in the picture to stop."))
}
}
}
/// Whether Enhance can run for `e` here, and the line the game's page shows about it.
fn enhance_available(&self, e: &Entry) -> (bool, String) {
let session = display::detect_session();
if e.source == Source::Console && session != display::Session::Unknown {
match self.console_of(&e.id).map(|c| c.link) {
Some(console::Link::RemotePlay { .. }) => {
if summit_core::engine::find_engine().is_none() { return (false, "Enhance needs Summit's engine, which was not found: run install.sh.".into()); }
return match self.chiaki() {
None => (false, "Enhance needs chiaki-ng with SmoovPlay's frame tap: run install.sh --with-remote-play.".into()),
Some((p, false)) => (false, format!("This chiaki-ng ({}) has no frame tap, so the engine can't read the stream: install.sh --with-remote-play builds one that has it.", tilde(&p))),
Some(_) => (true, "Enhance: the engine starts first and takes every frame chiaki-ng receives through SmoovPlay's frame tap, then shows it with frame generation and the upscaler from this profile (chiaki-ng's own window is minimised meanwhile). Set chiaki-ng's stream to 60 fps.".into()),
};
}
Some(console::Link::Capture { .. }) => return (true, "Enhance: frame generation and the upscaler from this profile on the card's picture. Off, the picture is shown as it comes.".into()),
None => {}
}
}
match launch::plan(e, self.cli().as_deref(), true) {
_ if launch::is_install(e) => (false, "Enhance needs the game installed.".to_string()),
launch::Plan::Unsupported(why) => (false, format!("Enhance is not available: {why}.")),
@@ -237,7 +367,14 @@ impl App {
launch::Plan::Run(argv) => 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.
let switching = if launch::is_install(&e) { None } else { self.switch_note(&e) };
// Play steps aside for the game, so the game's window gets the keyboard once it opens.
let argv = if launch::is_install(&e) { argv } else { launch::with_focus(argv) };
if self.headless { return self.toast(format!("Headless render, nothing started. Would run: {}", argv.join(" "))); }
// A game its own launcher starts is followed by its processes: the ones there now are not it.
let mark = if launch::is_install(&e) { None } else { running::marker(&e) };
let before = mark.as_ref().map(|m| running::pids(std::path::Path::new("/proc"), m));
use std::process::{Command, Stdio};
// What `summit run` prints (display steps, the engine's command, how it ended) goes to a log, for when it fails.
let log = dirs_log().and_then(|p| std::fs::File::create(&p).ok().map(|f| (p, f)));
@@ -257,17 +394,32 @@ impl App {
};
match started {
Ok(mut child) => {
let what = if launch::is_install(&e) { format!("Asked Steam to install {}", e.title) } else if e.source == Source::Steam { format!("Starting {} through Steam", e.title) } else { format!("Starting {}", e.title) };
self.toast(if enhance { format!("{what}, with Enhance") } else { what });
let con = if e.source == Source::Console { self.console_of(&e.id) } else { None };
let install = launch::is_install(&e);
let how = if let Some(console::Link::RemotePlay { nickname, .. }) = con.as_ref().map(|c| &c.link) { format!("Connecting to {nickname}") }
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 };
// 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;
self.play_seq.set(seq);
if install { self.toast(how); } else {
let tracker = mark.zip(before).map(|(m, b)| (m, running::Tracker::new(&b, Instant::now())));
self.begin_playing(Playing { seq, idx: idx.max(0) as usize, title: e.title.clone(), started: Instant::now(), phase: 0, status: how.clone(), how, child: Some(child.id()),
child_ran: None, tracker, track: running::Phase::Starting, scanned: None, lost_focus: false });
}
// When it exits, pick up the session `summit run` recorded.
// If it failed (summit run exits 1 on an error, such as a missing engine), say why: the log's last line.
let (title, log_path) = (e.title.clone(), log.as_ref().map(|(p, _)| p.clone()));
let (title, log_path, t0) = (e.title.clone(), log.as_ref().map(|(p, _)| p.clone()), Instant::now());
std::thread::spawn(move || {
let failed = child.wait().map(|st| st.code() == Some(1)).unwrap_or(false);
let ran = t0.elapsed();
let why = if failed { log_path.as_deref().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| data::last_error(&t)) } else { None };
let _ = slint::invoke_from_event_loop(move || with_app(|a| {
a.refresh_tracked();
if failed { a.toast(format!("{title} did not start: {}", why.unwrap_or_else(|| "see ~/.cache/summit/last-run.log".into()))); }
let error = failed.then(|| format!("{title} did not start: {}", why.unwrap_or_else(|| "see ~/.cache/summit/last-run.log".into())));
a.child_exited(seq, error, ran);
}));
});
}
@@ -275,6 +427,121 @@ impl App {
}
}
// ---- now playing ----
/// Whether the launcher's window has the keyboard. A controller is only listened to while it does: pad.rs
/// reads every press, whatever window is in front. True when it cannot be told (a headless render).
pub fn window_focused(&self) -> bool {
use slint::winit_030::WinitWindowAccessor;
self.ui.window().with_winit_window(|w| w.has_focus()).unwrap_or(true)
}
pub fn is_playing(&self) -> bool { self.playing.borrow().is_some() }
/// Put the "now playing" screen up (its loading phase first).
fn begin_playing(&self, p: Playing) {
let lib = self.ui.global::<Lib>();
self.want_cover(p.idx); // (if it is not loaded yet, apply() puts it on the screen when it is)
let art = self.games.row_data(p.idx).filter(|g| g.has_cover);
lib.set_play_has_art(art.is_some());
lib.set_play_art(art.map(|g| g.cover).unwrap_or_default());
lib.set_play_title(p.title.as_str().into());
lib.set_play_status(p.status.as_str().into());
lib.set_play_phase(p.phase);
// Summit can end a game whose process it holds. One that Steam, Lutris or Heroic started is theirs.
lib.set_play_can_stop(p.tracker.is_none() && p.child.is_some());
lib.set_playing(true);
self.ui.set_toast_shown(false);
*self.playing.borrow_mut() = Some(p);
if !self.headless {
self.play_timer.start(slint::TimerMode::Repeated, Duration::from_millis(400), || with_app(|a| a.play_tick()));
}
}
/// Twice a second while a game runs: where it has got to (starting, running, gone), and the screen's text.
fn play_tick(&self) {
let now = Instant::now();
let focused = self.window_focused();
let mut end: Option<Option<String>> = None;
{
let mut guard = self.playing.borrow_mut();
let Some(p) = guard.as_mut() else { self.play_timer.stop(); return };
let up = now.duration_since(p.started);
if !focused && up >= Duration::from_secs(1) { p.lost_focus = true; }
if let Some((marker, tracker)) = p.tracker.as_mut() {
if p.scanned.is_none_or(|t| now.duration_since(t) >= Duration::from_secs(1)) {
p.scanned = Some(now);
p.track = tracker.step(&running::pids(std::path::Path::new("/proc"), marker), now);
}
// The game's processes came and went: it is over, whatever `summit run` is still doing (looking
// for the game's window to place, or closing the engine). `summit run` itself returns at once for
// these, unless it follows the game (Enhance, whose engine lasts as long as the game's window):
// then its end is the game's, if the game's processes were never seen.
let followed = p.child_ran.is_some_and(|ran| ran >= Duration::from_secs(20));
match (p.track, p.child_ran) {
(running::Phase::Ended, _) => end = Some(None),
(running::Phase::Starting, Some(_)) if followed => end = Some(None),
(running::Phase::NeverStarted, Some(_)) => end = Some(Some(format!("Summit did not see {} start, so the launcher is back. If it is running, it keeps running.", p.title))),
_ => {}
}
}
if p.phase == 0 {
let there = match &p.tracker { Some(_) => p.track == running::Phase::Running, None => p.lost_focus || up >= Duration::from_secs(8) };
if there { p.phase = 1; self.ui.global::<Lib>().set_play_phase(1); }
}
let status = match p.phase { 0 => p.how.clone(), 2 => "Closing it".into(), _ => format!("Playing for {}", running::elapsed_label(up.as_secs())) };
if status != p.status { self.ui.global::<Lib>().set_play_status(status.as_str().into()); p.status = status; }
}
if let Some(note) = end { self.end_playing(note, true); }
}
/// `summit run` ended. For a game Summit started itself that is the game ending; one handed to Steam, Lutris
/// or Heroic is followed by its processes (play_tick). `error`: it failed, and why.
fn child_exited(&self, seq: u64, error: Option<String>, ran: Duration) {
let ours = self.playing.borrow().as_ref().is_some_and(|p| p.seq == seq);
if !ours { // the launcher was taken back before it ended (or it was an install)
self.refresh_tracked();
if self.ui.get_detail_open() { self.open_detail(self.ui.global::<Lib>().get_detail().idx); }
if let Some(e) = error { self.toast(e); }
return;
}
let over = {
let mut guard = self.playing.borrow_mut();
let p = guard.as_mut().expect("checked above");
p.child = None;
p.child_ran = Some(ran);
error.is_some() || p.tracker.is_none()
};
if over { self.end_playing(error, true); } else { self.ui.global::<Lib>().set_play_can_stop(false); }
}
/// The launcher again. `front`: the game is gone, so bring the launcher's window to the front too (after a
/// game from Steam, Steam's own window can turn up on top). `note`: something to say, as a toast.
fn end_playing(&self, note: Option<String>, front: bool) {
if self.playing.borrow_mut().take().is_none() { return; }
self.play_timer.stop();
self.ui.global::<Lib>().set_playing(false);
self.refresh_tracked();
// the game's page, if that is where Play was pressed: its sessions and hours, with this one in
if self.ui.get_detail_open() { self.open_detail(self.ui.global::<Lib>().get_detail().idx); }
if let Some(n) = note { self.toast(n); }
if front && !self.headless && !self.window_focused() { raise_window(); }
}
/// Back to the launcher (Esc, the button, a held B): the game keeps running.
pub fn play_back(&self) { self.end_playing(None, false); }
/// Stop the game: `summit run` gets SIGTERM, and stops the game (and the engine) and puts the display back.
fn play_stop(&self) {
let mut guard = self.playing.borrow_mut();
let Some(p) = guard.as_mut() else { return };
let Some(pid) = p.child.filter(|pid| *pid > 1 && p.tracker.is_none()) else { return }; // (0: a preview render)
let _ = std::process::Command::new("kill").args(["-TERM", &pid.to_string()]).status();
p.phase = 2;
let lib = self.ui.global::<Lib>();
lib.set_play_phase(2);
lib.set_play_can_stop(false);
}
/// Settings > Clips folder: open it in the file manager (made first, so there is something to open).
fn open_clips(&self) {
let Some(dir) = summit_core::engine::clips_dir() else { return self.toast("No Videos folder found") };
@@ -331,8 +598,187 @@ impl App {
});
}
// ---- the Add dialog: a game on this PC, a capture card, PlayStation Remote Play ----
fn item(label: impl Into<SharedString>, detail: impl Into<SharedString>, status: impl Into<SharedString>, state: i32, glyph: i32, enabled: bool) -> AddItem {
AddItem { label: label.into(), detail: detail.into(), status: status.into(), state, glyph, enabled }
}
/// "+ Add a game or console": the three kinds, each with what Summit sees of it right now.
fn open_add(&self) {
let lib = self.ui.global::<Lib>();
let picker = ["kdialog", "zenity"].into_iter().find(|n| summit_core::doctor::on_path(n));
let cards: Vec<_> = console::capture_devices().into_iter().filter(|d| !console::looks_like_webcam(&d.name)).collect();
let reg = console::registered();
let chiaki = self.chiaki();
let choices = vec![
Self::item("A game on this PC", "Pick the file that starts it: a Linux game, an AppImage, a script. Summit tracks its time and can Enhance its window.",
picker.map_or("No file dialog: install zenity".to_string(), |p| format!("Opens {p}")), if picker.is_some() { 1 } else { 3 }, 0, true),
Self::item("A capture card", "A Switch, Xbox, PlayStation or anything with HDMI out, through a capture card on this PC.",
match cards.as_slice() { [] => "No card plugged in".to_string(), [one] => format!("{} found", one.name), many => format!("{} cards found", many.len()) },
if cards.is_empty() { 2 } else { 1 }, 2, true),
Self::item("PlayStation Remote Play", "Stream your PS5 or PS4 to this PC with chiaki-ng, built with SmoovPlay's frame tap so Enhance can add frame generation.",
match (&chiaki, reg.len()) {
(None, _) => "chiaki-ng not installed".to_string(),
(_, 0) => "No console linked yet".to_string(),
(_, 1) => format!("{} linked", reg[0].nickname),
(_, n) => format!("{n} consoles linked"),
},
match (&chiaki, reg.len()) { (None, _) => 3, (_, 0) => 2, _ => 1 }, 1, true),
];
lib.set_add_choices(ModelRc::new(VecModel::from(choices)));
lib.set_add_step(0);
lib.set_add_row(0);
lib.set_add_open(true);
}
fn add_choose(&self, i: i32) {
let lib = self.ui.global::<Lib>();
match i {
0 => { lib.set_add_open(false); self.add_game(-1); }
1 => { lib.set_add_step(1); lib.set_add_row(0); self.fill_capture(); }
_ => {
lib.set_add_step(2); lib.set_add_row(0);
*self.remote_found.borrow_mut() = None;
self.fill_remote();
self.search_consoles();
}
}
}
fn set_add_list(&self, items: Vec<AddItem>, buttons: &[&str], actions: Vec<AddAction>, note: String, empty: &str) {
let lib = self.ui.global::<Lib>();
let n = (items.len() + buttons.len()) as i32;
lib.set_add_items(ModelRc::new(VecModel::from(items)));
lib.set_add_buttons(ModelRc::new(VecModel::from(buttons.iter().map(|b| SharedString::from(*b)).collect::<Vec<_>>())));
lib.set_add_note(note.into());
lib.set_add_empty(empty.into());
*self.add_actions.borrow_mut() = actions;
if lib.get_add_row() >= n { lib.set_add_row((n - 1).max(0)); }
}
/// The console entry already in the library for this link, if any.
fn added(&self, same: impl Fn(&console::Link) -> bool) -> Option<console::Console> {
self.state.borrow().consoles.iter().find(|c| same(&c.link)).cloned()
}
fn fill_capture(&self) {
let mut devs = console::capture_devices();
devs.sort_by_key(|d| console::looks_like_webcam(&d.name)); // cards first, stable otherwise
let (mut items, mut actions) = (vec![], vec![]);
for d in devs {
let cam = console::looks_like_webcam(&d.name);
let have = self.added(|l| matches!(l, console::Link::Capture { device } if *device == d.name));
let detail = format!("{}{}", d.path, if cam { " · looks like a webcam, not a capture card" } else { "" });
items.push(match &have {
Some(c) => Self::item(d.name.as_str(), format!("{detail} · in your library as {}", c.title), "Added", 1, if cam { 3 } else { 2 }, true),
None => Self::item(d.name.as_str(), detail, if cam { "Webcam" } else { "Plugged in" }, if cam { 0 } else { 1 }, if cam { 3 } else { 2 }, true),
});
actions.push(match have { Some(c) => AddAction::Open(c.id), None => AddAction::Capture(d) });
}
actions.push(AddAction::Refresh);
let note = if summit_core::engine::find_engine().is_none() {
"Summit's engine was not found: it shows the card's picture, so run install.sh first.".to_string()
} else { String::new() };
self.set_add_list(items, &["Refresh"], actions, note,
"No capture device found. Plug the card in (your user needs to be in the video group to open it), then press Refresh.");
}
fn fill_remote(&self) {
let found = self.remote_found.borrow().clone();
let (mut items, mut actions) = (vec![], vec![]);
for r in console::registered() {
let kind = if r.ps5 { "PS5" } else { "PS4" };
let have = self.added(|l| matches!(l, console::Link::RemotePlay { nickname, .. } if *nickname == r.nickname));
let seen = found.as_ref().map(|f| f.iter().find(|f| f.name == r.nickname).cloned());
let (status, state, where_) = match &seen {
None if self.headless => ("Not checked".to_string(), 0, String::new()),
None => ("Looking...".to_string(), 0, String::new()),
Some(None) => ("Not answering".to_string(), 2, String::new()),
Some(Some(f)) if f.standby => ("Rest mode: Play wakes it".to_string(), 1, format!(" · at {}", f.ip)),
Some(Some(f)) => ("On".to_string(), 1, format!(" · at {}", f.ip)),
};
let detail = format!("{kind} linked in chiaki-ng{where_}");
items.push(match &have {
Some(c) => Self::item(r.nickname.as_str(), format!("{detail} · in your library as {}", c.title), "Added", 1, 1, true),
None => Self::item(r.nickname.as_str(), detail, status, state, 1, true),
});
actions.push(match have { Some(c) => AddAction::Open(c.id), None => AddAction::Remote(r) });
}
actions.extend([AddAction::Refresh, AddAction::LinkInChiaki]);
let note = match self.chiaki() {
None => "chiaki-ng is not installed: Remote Play needs it. install.sh --with-remote-play builds it with SmoovPlay's frame tap.".to_string(),
Some((p, false)) => format!("{} has no frame tap: Remote Play works, Enhance doesn't. install.sh --with-remote-play builds one that has it.", tilde(&p)),
Some((p, true)) => format!("{} has SmoovPlay's frame tap: Enhance works. Set its stream to 60 fps (H.265, 1080p) in chiaki-ng's settings.", tilde(&p)),
};
self.set_add_list(items, &["Refresh", "Link a console in chiaki-ng"], actions, note,
"chiaki-ng has no console linked yet. Press Link a console in chiaki-ng, sign in and enter the code from the console (PS5: Settings > System > Remote Play > Link Device), then Refresh.");
}
/// Ask the network which consoles are on (3 s, off the UI thread); the rows say what answered.
fn search_consoles(&self) {
if self.headless { return; }
let seq = self.discover_seq.get() + 1;
self.discover_seq.set(seq);
std::thread::spawn(move || {
let found = console::discover(std::time::Duration::from_secs(3), &[]);
let _ = slint::invoke_from_event_loop(move || with_app(|a| {
if a.discover_seq.get() != seq { return; }
*a.remote_found.borrow_mut() = Some(found);
let lib = a.ui.global::<Lib>();
if lib.get_add_open() && lib.get_add_step() == 2 { a.fill_remote(); }
}));
});
}
fn add_pick(&self, i: i32) {
let Some(action) = usize::try_from(i).ok().and_then(|i| self.add_actions.borrow().get(i).cloned()) else { return };
let lib = self.ui.global::<Lib>();
match action {
AddAction::Refresh if lib.get_add_step() == 1 => { self.fill_capture(); self.toast("Looked for capture devices again"); }
AddAction::Refresh => { *self.remote_found.borrow_mut() = None; self.fill_remote(); self.search_consoles(); }
AddAction::LinkInChiaki => {
let Some((chiaki, _)) = self.chiaki() else { return self.toast("chiaki-ng is not installed: run install.sh --with-remote-play") };
if self.headless { return self.toast(format!("Headless render, would open {}", tilde(&chiaki))); }
match std::process::Command::new(&chiaki).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn() {
Ok(mut c) => {
std::thread::spawn(move || { let _ = c.wait(); });
self.toast("chiaki-ng is open: link your console there, then press Refresh");
}
Err(err) => self.toast(format!("Could not start chiaki-ng: {err}")),
}
}
AddAction::Open(id) => {
lib.set_add_open(false);
if let Some(idx) = self.entries.borrow().iter().position(|e| e.id == id) { self.open_detail(idx as i32); }
}
AddAction::Capture(d) => {
let taken = self.state.borrow().consoles.iter().any(|c| c.title == "Capture Card");
self.finish_console(console::Console::capture(&d.name, if taken { Some(d.name.as_str()) } else { None }));
}
AddAction::Remote(r) => {
let plain = console::Console::remote_play(&r.nickname, r.ps5, None);
let taken = self.state.borrow().consoles.iter().any(|c| c.title == plain.title);
let c = if taken { console::Console::remote_play(&r.nickname, r.ps5, Some(&format!("{} ({})", plain.title, r.nickname))) } else { plain };
self.finish_console(c);
}
}
}
fn finish_console(&self, c: console::Console) {
let (title, what) = (c.title.clone(), c.describe());
let id = match state::add_console(c) {
Ok(id) => id,
Err(err) => return self.toast(format!("Could not add {title}: {err}")),
};
self.ui.global::<Lib>().set_add_open(false);
self.reload();
if let Some(i) = self.entries.borrow().iter().position(|e| e.id == id) { self.open_detail(i as i32); }
self.toast(format!("Added {title}: {what}"));
}
/// Scan everything again (after adding a game): new list, shelves, counts; covers load again as cards ask.
fn reload(&self) {
self.forget_accounts();
let mut entries = scan::full(&self.folders, 4);
let st = state::load();
state::apply(&mut entries, &st);
@@ -391,56 +837,133 @@ impl App {
}
// ---- launch profile ----
/// Enhance on or off for this game. Matching the defaults again leaves it out of the game's file.
fn toggle_enhance(&self, idx: i32) {
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
let mut p = profile::load(&e.id).unwrap_or_default();
p.enhance = !p.enhance;
// An empty frame generation setting means the engine's default (RIFE): say it in the profile, so the page shows it.
if p.enhance && p.framegen.is_empty() { p.framegen = "rife".into(); }
match profile::save(&e.id, &p) {
Ok(_) => { self.toast(if p.enhance { format!("Enhance on for {}", e.title) } else { format!("Enhance off for {}", e.title) }); self.open_detail(idx); }
let on = !profile::load(&e.id).map(|p| p.enhance).unwrap_or(false);
let default_on = profile::load_defaults().map(|p| p.enhance).unwrap_or(false);
match profile::update_layer(&e.id, |l| l.enhance = if on == default_on { None } else { Some(on) }) {
Ok(_) => { self.toast(if on { format!("Enhance on for {}", e.title) } else { format!("Enhance off for {}", e.title) }); self.open_detail(idx); }
Err(err) => self.toast(format!("Could not save the profile: {err}")),
}
}
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());
let outs = display::outputs(s, d);
*self.editing.borrow_mut() = Some((idx as usize, outs));
*self.editing.borrow_mut() = Some(Editing { game, outs: display::outputs(s, d), keys: vec![] });
let lib = self.ui.global::<Lib>();
lib.set_editor_row(0);
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);
}
fn fill_editor(&self) {
/// The id of the profile being edited.
fn editing_id(&self) -> Option<String> {
let ed = self.editing.borrow();
let Some((idx, outs)) = ed.as_ref() else { return };
let id = self.entries.borrow()[*idx].id.clone();
let p = profile::load(&id).unwrap_or_default();
let tool = match (display::detect_session(), display::detect_desktop()) {
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 (list, err) = match outs { Ok(o) => (o.as_slice(), None), Err(e) => (&[][..], Some(e.as_str())) };
let rows: Vec<PRow> = data::edit_rows(&p, list, err, tool).into_iter().map(|r| PRow {
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 cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: err, tool, placer };
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::dir().map(|d| tilde(&d.join(format!("{}.toml", id.replace(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_', "_"))))).unwrap_or_default().into());
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((idx, outs)) = self.editing.borrow().as_ref().map(|(i, o)| (*i, o.clone().unwrap_or_default())) else { return };
let id = self.entries.borrow()[idx].id.clone();
let old = profile::load(&id).unwrap_or_default();
let new = data::edit_apply(&old, &outs, row.max(0) as usize, value.max(0) as usize);
if new == old { return; }
if let Err(err) = profile::save(&id, &new) { return self.toast(format!("Could not save the profile: {err}")); }
self.fill_editor();
self.open_detail(idx as 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("") };
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) {
@@ -450,6 +973,7 @@ impl App {
}
fn refresh_tracked(&self) {
self.forget_accounts(); // a game ended: which account played it last may have changed
*self.state.borrow_mut() = state::load();
state::apply(&mut self.entries.borrow_mut(), &self.state.borrow());
let n = self.entries.borrow().len();
@@ -485,11 +1009,13 @@ impl App {
p.set_replay(prefs::CLIP_LENGTHS.iter().position(|c| *c == s.replay_seconds).unwrap_or(2) as i32);
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());
let d = self.default_profile.borrow();
p.set_upscaler(match d.upscaler.as_str() { "fsr" => 1, "rtx-vsr" | "vsr" => 2, _ => 0 });
p.set_framegen(if d.framegen == "rife" { 1 } else { 0 });
drop(s);
self.load_defaults_into_ui();
}
fn settings_from_ui(&self) -> prefs::UiSettings {
@@ -503,6 +1029,8 @@ impl App {
ui_scale: prefs::UI_SCALES[pick(p.get_scale(), prefs::UI_SCALES.len())],
replay_seconds: prefs::CLIP_LENGTHS[pick(p.get_replay(), 6)],
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()
}
@@ -519,12 +1047,14 @@ impl App {
}
if scale_changed { self.apply_scale(); }
let p = self.ui.global::<Prefs>();
let (up, fg) = (["none", "fsr", "rtx-vsr"][p.get_upscaler().clamp(0, 2) as usize], ["none", "rife"][p.get_framegen().clamp(0, 1) as usize]);
let mut d = self.default_profile.borrow_mut();
let same = |a: &str, b: &str| a == b || (a.is_empty() && b == "none");
if !same(&d.upscaler, up) || !same(&d.framegen, fg) {
d.upscaler = up.into(); d.framegen = fg.into();
if let Err(err) = profile::save("default", &d) { self.toast(format!("Could not save the default profile: {err}")); }
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}")),
}
}
}
@@ -549,6 +1079,17 @@ impl App {
}
}
/// Bring the launcher's own window to the front and give it the keyboard, through the desktop (KWin, or wmctrl
/// on X11: a Wayland program cannot do that for itself). On a thread: it talks to the desktop. Where the desktop
/// offers no way, the window stays where the game left it, usually right behind it.
fn raise_window() {
std::thread::spawn(|| {
let want = winmode::Want { focus: true, ..Default::default() };
let watch = winmode::Watch { wait: Duration::from_secs(2), settle: Duration::ZERO, poll: Duration::from_millis(300) };
let _ = winmode::place(display::detect_session(), display::detect_desktop(), &winmode::Target::Pid(std::process::id()), &want, watch, &|| false, &mut |_| {});
});
}
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)
}
@@ -589,9 +1130,12 @@ pub fn build(headless: bool) -> Rc<App> {
ui, entries: RefCell::new(entries), state: RefCell::new(st), games: Rc::new(VecModel::default()), loader,
requested: Default::default(), loaded: Default::default(), keep: Default::default(),
backdrop_seq: Cell::new(0), backdrop_for: Cell::new(-1),
settings: RefCell::new(prefs::load()), default_profile: RefCell::new(profile::load("default").unwrap_or_default()),
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),
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(),
playing: Default::default(), play_seq: Cell::new(0), play_timer: slint::Timer::default(),
});
APP.with(|a| *a.borrow_mut() = Some(app.clone()));
@@ -620,8 +1164,18 @@ pub fn build(headless: bool) -> Rc<App> {
lib.on_change_art(|i| with_app(|a| a.change_art(i)));
lib.on_add_game(|i| with_app(|a| a.add_game(i)));
lib.on_open_clips(|| with_app(|a| a.open_clips()));
lib.on_open_add(|| with_app(|a| a.open_add()));
lib.on_add_choose(|i| with_app(|a| a.add_choose(i)));
lib.on_add_pick(|i| with_app(|a| a.add_pick(i)));
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_play_back(|| with_app(|a| a.play_back()));
lib.on_play_stop(|| with_app(|a| a.play_stop()));
let session = display::detect_session();
let portal = if session == display::Session::Wayland && !headless { hotkey::portal_has_global_shortcuts() } else { None };
lib.set_hotkey_status(hotkey::status(session, portal).into());
@@ -636,7 +1190,7 @@ pub fn build(headless: bool) -> Rc<App> {
app.rebuild_shelves();
app.requery();
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, 9)); }
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, 11)); }
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)));
@@ -645,12 +1199,30 @@ pub fn build(headless: bool) -> Rc<App> {
if env("SUMMIT_EDITOR").is_some() { app.open_profile(i as i32); }
}
}
// 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));
if let Some(e) = app.entries.borrow().get(idx).cloned() {
let how = "Opening through Steam, with Enhance".to_string();
let status = if phase == 1 { "Playing for 12 min".to_string() } else if phase == 2 { "Closing it".into() } else { how.clone() };
app.begin_playing(Playing { seq: 0, idx, title: e.title, started: Instant::now(), phase: phase.clamp(0, 2), how, status, child: Some(0), child_ran: None,
tracker: None, track: running::Phase::Starting, scanned: None, lost_focus: false });
}
}
// SUMMIT_ADD=0|1|2: the Add dialog, on its first page (0) or on the capture card (1) or Remote Play (2) list.
if let Some(step) = env("SUMMIT_ADD").and_then(|v| v.parse::<i32>().ok()) {
app.open_add();
if step > 0 { app.add_choose(step.min(2)); }
}
app
}
fn main() {
if let Ok(dir) = std::env::var("SUMMIT_SHOT") { return shot::run(&dir); }
let app = build(false);
// Matches summit.desktop, so the taskbar and the app switcher show Summit's icon (Wayland uses this, not the
// window icon). Has to happen before the window is shown.
let _ = slint::set_xdg_app_id("summit");
if std::env::args().any(|a| a == "--fullscreen") { app.toggle_fullscreen(); }
app.ui.show().expect("could not show the window");
// The backend sets the system's scale factor when it creates the window, so ours goes on top once that has happened.
@@ -668,11 +1240,23 @@ fn main() {
}
// Controllers: polled on the UI thread, pressed as keys.
// Without a pad this only looks for one every two seconds, so an idle launcher stays idle.
// SUMMIT_PAD_ALWAYS=1: act on a pad whatever window has the keyboard (for a desktop that never reports focus).
let pad_always = std::env::var("SUMMIT_PAD_ALWAYS").is_ok_and(|v| v == "1");
let pad_timer = Rc::new(slint::Timer::default());
let mut pads = pad::Pads::new();
let timer = pad_timer.clone();
pad_timer.start(slint::TimerMode::Repeated, std::time::Duration::from_secs(2), move || {
for k in pads.poll(std::time::Instant::now()) { with_app(|a| shot::press(a.ui.window(), k)); }
// A pad is read whatever window has the keyboard, so its presses only count while the launcher's does,
// and never while a game started from here runs (then the launcher shows "now playing" and waits).
// The one thing a pad does there: B held down, with the launcher in front, takes the launcher back.
let now = std::time::Instant::now();
let keys = pads.poll(now);
let held_b = pads.held_for(1, now);
with_app(|a| match pad::listen(a.is_playing(), pad_always || a.window_focused()) {
pad::Listen::Keys => for k in &keys { shot::press(a.ui.window(), k); },
pad::Listen::BackOnly => if held_b.is_some_and(|d| d >= pad::HOLD_BACK) { a.play_back(); },
pad::Listen::Nothing => {}
});
let want = std::time::Duration::from_millis(if pads.connected() { 16 } else { 2000 });
if timer.interval() != want { timer.set_interval(want); }
});
+62 -4
View File
@@ -2,6 +2,10 @@
//! 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.
//!
//! 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
//! runs ([`listen`]): otherwise playing a game with a pad would steer the launcher behind it.
//!
//! The button and axis numbers are the ones the Linux xpad and hid-playstation drivers report.
//! NOT tested on real hardware yet: the event decoding and the mapping are unit tested, the devices are not.
use std::io::Read;
@@ -29,6 +33,26 @@ pub fn decode(b: &[u8; 8]) -> Option<Event> {
}
}
/// How long B has to be held to take the launcher back while a game runs.
pub const HOLD_BACK: Duration = Duration::from_millis(900);
/// What a pad may do right now. The kernel hands its presses to every program that reads the device, whatever
/// window is in front, so a pad used in a game would steer the launcher behind it too.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Listen {
/// The launcher's window has the keyboard and no game started from it runs: the pad steers it.
Keys,
/// A game started from the launcher runs, but the launcher's window is the one in front (the player came
/// back to it): holding B takes the launcher back, nothing else does anything.
BackOnly,
/// Another window has the keyboard (the game's, most likely): the pad is that program's.
Nothing,
}
pub fn listen(playing: bool, window_focused: bool) -> Listen {
match (window_focused, playing) { (false, _) => Listen::Nothing, (true, true) => Listen::BackOnly, (true, false) => Listen::Keys }
}
/// 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 }
@@ -84,12 +108,14 @@ pub struct Pads {
dirs: [Direction; 8],
repeat: Repeater,
last_scan: Option<Instant>,
/// Buttons held down now, and since when: (pad, button).
down: Vec<((usize, u8), Instant)>,
}
impl Pads {
pub fn new() -> Self {
let (tx, rx) = channel();
Pads { tx, rx, open: [false; 8], dirs: Default::default(), repeat: Repeater::default(), last_scan: None }
Pads { tx, rx, open: [false; 8], dirs: Default::default(), repeat: Repeater::default(), last_scan: None, down: vec![] }
}
fn scan(&mut self) {
for id in 0..8 {
@@ -104,14 +130,24 @@ impl Pads {
}
}
pub fn connected(&self) -> bool { self.open.iter().any(|o| *o) }
/// How long button `number` has been held down, on whichever pad has held it longest.
pub fn held_for(&self, number: u8, now: Instant) -> Option<Duration> {
self.down.iter().filter(|((_, n), _)| *n == number).map(|(_, t)| now.duration_since(*t)).max()
}
fn note_button(&mut self, id: usize, number: u8, pressed: bool, now: Instant) {
self.down.retain(|(k, _)| *k != (id, number));
if pressed { self.down.push(((id, number), now)); }
}
pub fn poll(&mut self, now: Instant) -> Vec<&'static str> {
if self.last_scan.is_none_or(|t| now.duration_since(t) > Duration::from_secs(2)) { self.last_scan = Some(now); self.scan(); }
let mut keys = vec![];
while let Ok((id, ev)) = self.rx.try_recv() {
match ev {
None => { self.open[id] = false; self.dirs[id] = Direction::default(); }
Some(Event::Button { number, pressed: true }) => keys.extend(button_key(number)),
Some(Event::Button { .. }) => {}
None => { self.open[id] = false; self.dirs[id] = Direction::default(); self.down.retain(|((p, _), _)| *p != id); }
Some(Event::Button { number, pressed }) => {
self.note_button(id, number, pressed, now);
if pressed { keys.extend(button_key(number)); }
}
Some(Event::Axis { number, value }) => self.dirs[id].update(number, value),
}
}
@@ -151,6 +187,28 @@ mod tests {
d.update(6, 0); d.update(7, 32767); assert_eq!(d.key(), Some("Down"));
}
#[test]
fn a_pad_is_heard_only_by_the_window_in_front_and_not_during_a_game() {
assert_eq!(listen(false, true), Listen::Keys);
assert_eq!(listen(false, false), Listen::Nothing); // another program has the keyboard: its pad
assert_eq!(listen(true, false), Listen::Nothing); // in the game
assert_eq!(listen(true, true), Listen::BackOnly); // came back to the launcher while the game runs
}
#[test]
fn held_buttons_are_timed_per_pad() {
let mut p = Pads::new();
let t = Instant::now();
assert_eq!(p.held_for(1, t), None);
p.note_button(0, 1, true, t);
p.note_button(2, 1, true, t + Duration::from_millis(400));
p.note_button(0, 0, true, t + Duration::from_millis(500));
assert_eq!(p.held_for(1, t + Duration::from_millis(1000)), Some(Duration::from_millis(1000)));
p.note_button(0, 1, false, t + Duration::from_millis(1100));
assert_eq!(p.held_for(1, t + Duration::from_millis(1200)), Some(Duration::from_millis(800))); // the other pad's
p.note_button(2, 1, false, t + Duration::from_millis(1300));
assert_eq!(p.held_for(1, t + Duration::from_millis(1400)), None);
assert_eq!(p.held_for(0, t + Duration::from_millis(1400)), Some(Duration::from_millis(900)));
}
#[test]
fn held_direction_repeats_after_a_pause() {
let mut r = Repeater::default();
let t = Instant::now();
+1 -1
View File
@@ -20,7 +20,7 @@ fn key_text(name: &str) -> slint::SharedString {
"up" => Key::UpArrow, "down" => Key::DownArrow, "left" => Key::LeftArrow, "right" => Key::RightArrow,
"enter" | "return" => Key::Return, "esc" | "escape" => Key::Escape, "tab" => Key::Tab, "backtab" => Key::Backtab,
"pagedown" => Key::PageDown, "pageup" => Key::PageUp, "home" => Key::Home, "end" => Key::End, "f11" => Key::F11,
"backspace" => Key::Backspace,
"backspace" => Key::Backspace, "delete" => Key::Delete,
"space" => return " ".into(),
_ => return name.into(),
};
+81
View File
@@ -0,0 +1,81 @@
// The Steam account picker, over a Steam game's page: which account Play signs Steam in with before it starts the
// game. Automatic (the first row) is the account the game was last played on. Up/Down picks, Enter chooses.
import { Theme } from "theme.slint";
import { Lib, SteamAccount, Avatar, Icon, Icons, Btn, Tag, FocusRing } from "widgets.slint";
component AccountRow inherits Rectangle {
in property <SteamAccount> a;
in property <bool> focused;
in property <bool> auto; // the Automatic row
in property <string> auto-text;
callback clicked;
height: 84px; border-radius: Theme.r-md;
background: root.focused ? Theme.p.raised : ta.has-hover ? Theme.p.raised.with-alpha(0.6) : Theme.p.surface.with-alpha(0.7);
border-width: root.a.selected ? 2px : Theme.p.border-w; border-color: root.a.selected ? Theme.p.accent : Theme.p.border;
animate background { duration: Theme.ms(140); }
ta := TouchArea { mouse-cursor: pointer; clicked => { root.clicked(); } }
Avatar { x: 18px; y: (parent.height - self.height) / 2; size: 52px; a: root.a; icon: root.auto ? Icons.refresh : ""; }
Text { x: 88px; y: 16px; width: parent.width - 88px - 200px; overflow: elide;
text: root.auto ? "Automatic" : root.a.persona; color: Theme.p.text; font-size: Theme.t-md; font-weight: 800; }
Text { x: 88px; y: 40px; width: parent.width - 88px - 200px; overflow: elide;
text: root.auto ? root.auto-text : root.a.login; color: Theme.p.dim; font-size: Theme.t-sm; font-weight: root.auto ? 500 : 700; }
if root.a.note != "" || root.a.warn != "": Text { x: 88px; y: 60px; width: parent.width - 88px - 200px; overflow: elide;
text: root.a.warn != "" ? (root.a.note != "" ? root.a.note + " · " : "") + root.a.warn : root.a.note;
color: root.a.warn != "" ? #e0a43a : Theme.p.faint; font-size: Theme.t-xs; }
if root.a.selected: Tag { x: parent.width - self.width - 20px; y: (parent.height - self.height) / 2; text: "In use for this game"; tint: Theme.p.accent; dot: true; }
FocusRing { on: root.focused; radius: Theme.r-md; }
}
export component AccountPicker inherits Rectangle {
property <length> step: 94px; // row height + gap
property <int> n: Lib.accounts.length + 1;
function reveal() {
let y = Lib.accounts-row * root.step;
if (y + list.content-y < 0px) { list.content-y = -y; }
else if (y + 84px + list.content-y > list.height) { list.content-y = list.height - y - 84px; }
}
public function key(e: KeyEvent) -> bool {
if (e.text == Key.Escape || e.text == Key.Backspace) { Lib.accounts-open = false; }
else if (e.text == Key.DownArrow) { Lib.accounts-row = Math.min(root.n - 1, Lib.accounts-row + 1); root.reveal(); }
else if (e.text == Key.UpArrow) { Lib.accounts-row = Math.max(0, Lib.accounts-row - 1); root.reveal(); }
else if (e.text == Key.Return || e.text == " ") { Lib.pick-account(Lib.accounts-row); }
else if (e.text == Key.LeftArrow || e.text == Key.RightArrow) { }
else { return false; }
return true;
}
changed visible => { if (self.visible) { list.content-y = 0; root.reveal(); } }
background: Theme.p.bg.with-alpha(0.82);
TouchArea { clicked => { Lib.accounts-open = false; } }
panel := Rectangle {
property <length> w: Math.min(root.width - 48px, 760px);
property <length> h: Math.min(root.height - 32px, 150px + root.n * root.step);
x: (root.width - self.w) / 2; width: self.w; y: (root.height - self.h) / 2; height: self.h;
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.user; }
Text { x: 56px; y: 20px; width: parent.width - 180px; text: "Steam account · " + Lib.accounts-title; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; overflow: elide; }
Text { x: 56px; y: 50px; width: parent.width - 180px; color: Theme.p.dim; font-size: Theme.t-xs; wrap: word-wrap;
text: "Play switches Steam to this account first: Steam closes, then starts again signed in as it, and starts the game."; }
Btn { x: parent.width - self.width - 20px; y: 18px; h: 40px; text: "Close"; clicked => { Lib.accounts-open = false; } }
list := Flickable {
x: 20px; y: 96px; width: parent.width - 40px; height: parent.height - 96px - 40px;
content-width: self.width; content-height: root.n * root.step;
animate content-y { duration: Theme.ms(180); easing: ease-out; }
AccountRow {
x: 0; y: 0; width: parent.width; auto: true; focused: Lib.accounts-row == 0;
a: { persona: "", login: "", has-avatar: false, initial: "", note: "", warn: "", selected: Lib.accounts-auto-selected, c1: Theme.p.surface, c2: Theme.p.raised };
auto-text: Lib.accounts-auto;
clicked => { Lib.accounts-row = 0; Lib.pick-account(0); }
}
for a[i] in Lib.accounts: AccountRow {
x: 0; y: (i + 1) * root.step; width: parent.width; a: a; focused: Lib.accounts-row == i + 1;
clicked => { Lib.accounts-row = i + 1; Lib.pick-account(i + 1); }
}
}
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: account · Enter: use it for this game · Esc: close"; }
}
}
+165
View File
@@ -0,0 +1,165 @@
// "Add to your library": a game on this PC, a capture card, or PlayStation Remote Play (chiaki-ng). Over the
// current view, driven like the rest of the launcher: arrows move, Enter picks, Esc goes back.
import { Theme } from "theme.slint";
import { Lib, AddItem, Icon, Icons, Btn, FocusRing } from "widgets.slint";
// The icon of a choice or a row: 0 a game on this PC, 1 PlayStation Remote Play, 2 a capture card, 3 a webcam.
component Glyph inherits Rectangle {
in property <int> glyph;
in property <length> size: 28px;
in property <bool> lit;
width: root.size * 2; height: self.width; border-radius: self.width / 2;
background: root.lit ? @linear-gradient(140deg, Theme.p.accent 0%, Theme.p.accent2 100%) : Theme.p.raised;
border-width: root.lit ? 0px : Theme.p.border-w; border-color: Theme.p.border;
animate background { duration: Theme.ms(160); }
Icon {
x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; size: root.size; weight: 1.8px;
color: root.lit ? Theme.p.on-accent : Theme.p.text;
commands: root.glyph == 1 ? Icons.gamepad : root.glyph == 2 ? Icons.capture : root.glyph == 3 ? Icons.camera : Icons.folder;
}
}
// The state of a row or a choice: a dot and a word or two ("On", "Rest mode", "Not installed").
component Status inherits Rectangle {
in property <string> text;
in property <int> state; // 0 neutral, 1 good, 2 needs attention, 3 unavailable
property <color> tint: root.state == 1 ? Theme.p.ok : root.state == 2 ? #e0a43a : root.state == 3 ? Theme.p.faint : Theme.p.dim;
height: 26px; width: l.preferred-width + 34px; border-radius: 13px;
background: Theme.p.raised.with-alpha(0.9); border-width: Theme.p.border-w; border-color: Theme.p.border;
Rectangle { x: 11px; y: 9px; width: 8px; height: 8px; border-radius: 4px; background: root.tint; }
l := Text { x: 25px; height: parent.height; text: root.text; color: root.state == 3 ? Theme.p.faint : Theme.p.text; font-size: Theme.t-xs; font-weight: 700; vertical-alignment: center; }
}
component Choice inherits Rectangle {
in property <AddItem> it;
in property <bool> focused;
callback clicked;
property <bool> hot: ta.has-hover;
border-radius: Theme.r-lg;
background: root.focused ? Theme.p.raised : root.hot ? Theme.p.surface : Theme.p.surface.with-alpha(0.7);
border-width: Theme.p.border-w; border-color: Theme.p.border;
drop-shadow-blur: root.focused ? 28px : 0px; drop-shadow-color: Theme.p.glow.with-alpha(0.45);
animate background { duration: Theme.ms(140); } animate drop-shadow-blur { duration: Theme.ms(160); }
Glyph { x: 24px; y: 26px; glyph: root.it.glyph; size: 26px; lit: root.focused; }
Text { x: 24px; y: 104px; width: parent.width - 48px; text: root.it.label; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; wrap: word-wrap; }
Text { x: 24px; y: 134px; width: parent.width - 48px; height: parent.height - 134px - 56px; text: root.it.detail; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; overflow: elide; }
Status { x: 22px; y: parent.height - self.height - 20px; text: root.it.status; state: root.it.state; }
FocusRing { on: root.focused; radius: Theme.r-lg; }
ta := TouchArea { mouse-cursor: pointer; clicked => { root.clicked(); } }
}
component ItemRow inherits Rectangle {
in property <AddItem> it;
in property <bool> focused;
callback clicked;
height: 72px; border-radius: Theme.r-md;
background: root.focused ? Theme.p.raised : ta.has-hover && root.it.enabled ? Theme.p.surface : Theme.p.surface.with-alpha(0.6);
border-width: Theme.p.border-w; border-color: Theme.p.border;
opacity: root.it.enabled ? 1 : 0.7;
animate background { duration: Theme.ms(120); }
Glyph { x: 16px; y: (parent.height - self.height) / 2; glyph: root.it.glyph; size: 18px; lit: root.focused && root.it.enabled; }
Text { x: 74px; y: 15px; width: parent.width - 74px - st.width - 32px; text: root.it.label; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; overflow: elide; }
Text { x: 74px; y: 39px; width: parent.width - 74px - st.width - 32px; text: root.it.detail; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
st := Status { x: parent.width - self.width - 18px; y: (parent.height - self.height) / 2; text: root.it.status; state: root.it.state; }
FocusRing { on: root.focused; radius: Theme.r-md; }
ta := TouchArea { enabled: root.it.enabled; mouse-cursor: pointer; clicked => { root.clicked(); } }
}
export component AddDialog inherits Rectangle {
property <int> n: Lib.add-items.length;
property <int> total: root.n + Lib.add-buttons.length;
property <[string]> titles: ["Add to your library", "Capture card", "PlayStation Remote Play"];
property <[string]> subtitles: [
"A game installed on this PC, or a console: its picture through a capture card, or streamed from your PlayStation.",
"Pick the card your console is plugged into. Summit shows its picture full screen; with Enhance, with frame generation and the upscaler.",
"Pick a console linked in chiaki-ng. Play finds it on your network, wakes it from rest mode and streams it; with Enhance, through Summit's engine."];
public function key(e: KeyEvent) -> bool {
if (e.text == Key.Escape || e.text == Key.Backspace) { root.back(); return true; }
if (Lib.add-step == 0) {
if (e.text == Key.RightArrow || e.text == Key.DownArrow) { Lib.add-row = Math.min(2, Lib.add-row + 1); }
else if (e.text == Key.LeftArrow || e.text == Key.UpArrow) { Lib.add-row = Math.max(0, Lib.add-row - 1); }
else if (e.text == Key.Return || e.text == " ") { Lib.add-choose(Lib.add-row); }
else if (e.text == "1" || e.text == "2" || e.text == "3") { Lib.add-choose(e.text == "1" ? 0 : e.text == "2" ? 1 : 2); }
else { return false; }
return true;
}
if (root.total == 0) { return e.text == Key.Return; }
if (e.text == Key.DownArrow || (e.text == Key.RightArrow && Lib.add-row >= root.n)) { Lib.add-row = Math.min(root.total - 1, Lib.add-row + 1); }
else if (e.text == Key.UpArrow || (e.text == Key.LeftArrow && Lib.add-row > root.n)) { Lib.add-row = Math.max(0, Lib.add-row - 1); }
else if (e.text == Key.Return || e.text == " ") {
if (Lib.add-row >= root.n || Lib.add-items[Lib.add-row].enabled) { Lib.add-pick(Lib.add-row); }
}
else { return false; }
return true;
}
function back() {
if (Lib.add-step == 0) { Lib.add-open = false; }
else { Lib.add-row = Lib.add-step; Lib.add-step = 0; }
}
background: Theme.p.bg.with-alpha(0.84);
TouchArea { clicked => { Lib.add-open = false; } }
panel := Rectangle {
property <length> w: Math.min(root.width - 48px, 1040px);
property <length> list-h: root.n * 72px + Math.max(0, root.n - 1) * 10px;
property <length> body-h: Lib.add-step == 0 ? 290px : Math.max(72px, self.list-h) + (Lib.add-buttons.length > 0 ? 70px : 0px) + (Lib.add-note != "" ? 54px : 0px);
x: (root.width - self.w) / 2; width: self.w;
height: Math.min(root.height - 32px, 150px + self.body-h + 48px);
y: Math.max(16px, (root.height - self.height) / 2);
border-radius: Theme.r-lg; background: Theme.p.bg2; border-width: Theme.p.border-w; border-color: Theme.p.border;
drop-shadow-blur: 48px; drop-shadow-color: #000000a0;
clip: true;
TouchArea { } // clicks on the panel stay on it
if Lib.add-step > 0: Btn { x: 24px; y: 22px; h: 40px; text: "Back"; icon: Icons.back; clicked => { root.back(); } }
Icon { x: Lib.add-step > 0 ? 136px : 28px; y: 30px; size: 22px; color: Theme.p.accent; commands: Lib.add-step == 1 ? Icons.capture : Lib.add-step == 2 ? Icons.gamepad : Icons.plus; }
Text { x: Lib.add-step > 0 ? 168px : 62px; y: 25px; text: root.titles[Lib.add-step]; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; }
Text { x: 28px; y: 80px; width: parent.width - 56px; text: root.subtitles[Lib.add-step]; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
Btn { x: parent.width - self.width - 22px; y: 22px; h: 40px; text: ""; icon: Icons.close; clicked => { Lib.add-open = false; } }
// step 0: the three kinds
if Lib.add-step == 0: HorizontalLayout {
x: 24px; y: 140px; width: parent.width - 48px; height: 290px; spacing: 18px;
for c[i] in Lib.add-choices: Choice {
it: c; focused: Lib.add-row == i;
clicked => { Lib.add-row = i; Lib.add-choose(i); }
}
}
// steps 1 and 2: what was found, then the actions
if Lib.add-step > 0: Flickable {
// 6px around the rows, so the focus ring drawn outside a row is not cut off
x: 18px; y: 134px; width: parent.width - 36px; height: Math.min(panel.list-h + 12px, parent.height - 134px - 48px - (Lib.add-buttons.length > 0 ? 70px : 0px) - (Lib.add-note != "" ? 54px : 0px));
content-height: panel.list-h + 12px;
VerticalLayout { padding: 6px; spacing: 10px; alignment: start;
for it[i] in Lib.add-items: ItemRow {
it: it; focused: Lib.add-row == i;
clicked => { Lib.add-row = i; Lib.add-pick(i); }
}
}
}
if Lib.add-step > 0 && root.n == 0: Text {
x: 28px; y: 140px; width: parent.width - 56px; height: 72px; vertical-alignment: center;
text: Lib.add-empty; color: Theme.p.dim; font-size: Theme.t-md; wrap: word-wrap;
}
if Lib.add-step > 0 && Lib.add-note != "": Rectangle {
x: 24px; y: parent.height - 48px - (Lib.add-buttons.length > 0 ? 70px : 0px) - 44px; width: parent.width - 48px; height: 44px; border-radius: Theme.r-md;
background: Theme.p.surface.with-alpha(0.7); border-width: Theme.p.border-w; border-color: Theme.p.border;
Icon { x: 14px; y: 12px; size: 20px; color: Theme.p.accent; commands: Icons.info; }
Text { x: 46px; width: parent.width - 60px; height: parent.height; text: Lib.add-note; color: Theme.p.text; font-size: Theme.t-xs; vertical-alignment: center; wrap: word-wrap; overflow: elide; }
}
if Lib.add-step > 0 && Lib.add-buttons.length > 0: HorizontalLayout {
x: 24px; y: parent.height - 48px - 56px; height: 48px; spacing: 12px; alignment: start;
for b[j] in Lib.add-buttons: Btn {
h: 48px; text: b; icon: j == 0 ? Icons.refresh : Icons.link;
focused: Lib.add-row == root.n + j;
clicked => { Lib.add-row = root.n + j; Lib.add-pick(root.n + j); }
}
}
Text {
x: 20px; y: parent.height - 32px; width: parent.width - 40px; horizontal-alignment: center; color: Theme.p.faint; font-size: Theme.t-xs;
text: Lib.add-step == 0 ? "Left / Right: choose · Enter: next · Esc: close" : "Up / Down: choose · Enter: add · Esc: back";
}
}
}
+33 -4
View File
@@ -1,11 +1,14 @@
// 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, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint";
import { Lib, Prefs, Game, URow, Detail, PRow, AddItem, SteamAccount, 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";
export { Lib, Prefs, Game, URow, Detail, PRow, Palette }
import { PlayingView } from "playing.slint";
import { Splash } from "splash.slint";
export { Lib, Prefs, Game, URow, Detail, PRow, AddItem, SteamAccount, Palette }
component NavTab inherits Rectangle {
in property <string> label;
@@ -47,6 +50,7 @@ component Backdrop inherits Rectangle {
export component MainWindow inherits Window {
title: "Summit";
icon: @image-url("../../../packaging/icons/summit-256.png");
preferred-width: 1600px; preferred-height: 900px; min-width: 880px; min-height: 560px;
background: Theme.p.bg;
default-font-size: Theme.t-md;
@@ -87,6 +91,7 @@ export component MainWindow inherits Window {
public function close-detail() {
root.detail-open = false;
Lib.editor-open = false;
Lib.accounts-open = false;
if (root.view == 0) { Lib.focus-game(home.hero-idx); }
}
@@ -103,10 +108,15 @@ export component MainWindow inherits Window {
fs := FocusScope {
key-pressed(e) => {
if (e.text == Key.F11) { Lib.toggle-fullscreen(); return accept; }
// 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); }
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; }
@@ -153,6 +163,7 @@ export component MainWindow inherits Window {
opacity: root.view == 3 && !root.detail-open ? 1 : 0; visible: self.opacity > 0.01;
animate opacity { duration: Theme.ms(240); } animate y { duration: Theme.ms(320); easing: Theme.ease; }
exit-up => { root.zone = 0; }
refocus => { fs.focus(); }
}
}
@@ -185,6 +196,14 @@ export component MainWindow inherits Window {
y: root.detail-open ? 0px : 20px; height: root.height - root.hint-h;
animate opacity { duration: Theme.ms(260); } animate y { duration: Theme.ms(340); easing: Theme.ease; }
close => { root.close-detail(); }
refocus => { fs.focus(); }
}
// ---- add a game or a console ----
add := AddDialog {
height: root.height - root.hint-h;
opacity: Lib.add-open ? 1 : 0; visible: self.opacity > 0.01;
animate opacity { duration: Theme.ms(200); }
}
// ---- key hints (big picture) ----
@@ -194,8 +213,8 @@ export component MainWindow inherits Window {
HorizontalLayout {
x: Theme.pad; width: parent.width - 2 * Theme.pad; alignment: end; spacing: 24px;
VerticalLayout { alignment: center; KeyCap { key: "Arrows"; label: "Navigate"; } }
VerticalLayout { alignment: center; KeyCap { key: "Enter"; label: root.detail-open ? "Activate" : "Select"; } }
if !root.detail-open: VerticalLayout { alignment: center; KeyCap { key: "Tab"; label: "Next section"; } }
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.detail-open || root.view != 0: VerticalLayout { alignment: center; KeyCap { key: "Esc"; label: root.detail-open ? "Back" : "Home"; } }
@@ -204,6 +223,16 @@ export component MainWindow inherits Window {
}
}
// ---- a game started from here is running: over everything, and all there is to press ----
playing := PlayingView {
width: root.width; height: root.height;
visible: Lib.playing;
changed visible => { self.btn = 0; }
}
Toast { max-w: root.width - 48px; x: (parent.width - self.width) / 2; y: parent.height - root.hint-h - 72px; text: root.toast; shown: root.toast-shown; }
Timer { interval: 4s; running: root.toast-shown; triggered => { root.toast-shown = false; } }
// ---- the intro as the window opens, over everything ----
Splash { width: root.width; height: root.height; }
}
+39 -65
View File
@@ -1,6 +1,8 @@
// 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 } from "widgets.slint";
import { Lib, Game, Detail, PRow, Icon, Icons, Btn, Tag, CoverArt, FocusRing, Avatar } from "widgets.slint";
import { ProfileEditor } from "editor.slint";
import { AccountPicker } from "accounts.slint";
component Stat inherits Rectangle {
in property <string> label;
@@ -34,64 +36,11 @@ component Field inherits Rectangle {
}
// The launch profile editor, over the game's page. Up/Down picks a row, Left/Right changes it; every change is saved.
component Picker inherits Rectangle {
in property <PRow> r;
in property <bool> focused;
callback set(int);
height: 64px; 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;
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 - 360px; text: root.r.hint; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
Rectangle { x: parent.width - 330px; y: 12px; width: 312px; 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.options[root.r.value]; horizontal-alignment: center; vertical-alignment: center; color: root.r.value == 0 && root.r.options[0] == "Default" ? 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); } } }
}
FocusRing { on: root.focused; radius: Theme.r-md; }
}
component ProfileEditor inherits Rectangle {
in property <string> title;
callback close();
public function key(e: KeyEvent) -> bool {
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
else if (e.text == Key.DownArrow) { Lib.editor-row = Math.min(Lib.prof-rows.length - 1, Lib.editor-row + 1); }
else if (e.text == Key.UpArrow) { Lib.editor-row = Math.max(0, Lib.editor-row - 1); }
else if (e.text == Key.RightArrow || e.text == Key.Return || e.text == " ") {
if (Lib.prof-rows[Lib.editor-row].value < Lib.prof-rows[Lib.editor-row].options.length - 1) { Lib.prof-set(Lib.editor-row, Lib.prof-rows[Lib.editor-row].value + 1); }
else if (e.text != Key.RightArrow) { Lib.prof-set(Lib.editor-row, 0); }
}
else if (e.text == Key.LeftArrow) { if (Lib.prof-rows[Lib.editor-row].value > 0) { Lib.prof-set(Lib.editor-row, Lib.prof-rows[Lib.editor-row].value - 1); } }
else { return false; }
return true;
}
background: Theme.p.bg.with-alpha(0.82);
TouchArea { clicked => { root.close(); } }
panel := Rectangle {
property <length> w: Math.min(root.width - 48px, 980px);
x: (root.width - self.w) / 2; width: self.w; y: Math.max(16px, (root.height - self.height) / 2); height: Math.min(root.height - 32px, 64px * Lib.prof-rows.length + 10px * (Lib.prof-rows.length - 1) + 150px);
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: 22px; text: "Launch profile · " + root.title; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; }
Text { x: 56px; y: 52px; width: parent.width - 200px; text: "Saved to " + Lib.prof-file + " as you change it."; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
Btn { x: parent.width - self.width - 20px; y: 18px; h: 40px; text: "Done"; clicked => { root.close(); } }
VerticalLayout { x: 20px; y: 88px; width: parent.width - 40px; spacing: 10px; alignment: start;
for r[i] in Lib.prof-rows: Picker { r: r; focused: Lib.editor-row == i; set(v) => { Lib.editor-row = i; Lib.prof-set(i, v); } }
}
Text { x: 20px; y: parent.height - 30px; width: parent.width - 40px; text: "Up / Down: setting · Left / Right: change · Esc: done"; color: Theme.p.faint; font-size: Theme.t-xs; horizontal-alignment: center; }
}
}
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
in-out property <int> btn: 0; // 0 play, 1 enhance, 2 pin, 3 profile, 4 artwork, 5 Steam account
callback close();
callback refocus(); // give the keyboard back to the window (the editor's text rows)
property <Detail> d: Lib.detail;
property <Game> g: Lib.games[root.d.idx];
property <length> pad: Theme.pad + 8px;
@@ -101,12 +50,13 @@ export component DetailView inherits Rectangle {
property <bool> wide: root.rw >= 720px;
property <bool> compact: root.rw < 660px;
property <length> reasons-h: 56px + root.d.reasons.length * 26px + 44px;
property <length> profile-h: 56px + 5 * 28px + 62px;
property <length> profile-h: 56px + 5 * 28px + 92px;
public function key(e: KeyEvent) -> bool {
if (Lib.editor-open) { return editor.key(e); }
if (Lib.editor-open && !Lib.editor-defaults) { return editor.key(e); }
if (Lib.accounts-open) { return picker.key(e); }
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
else if (e.text == Key.RightArrow) { root.btn = Math.min(4, root.btn + 1); }
else if (e.text == Key.RightArrow) { root.btn = Math.min(root.d.has-account ? 5 : 4, 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); }
@@ -116,6 +66,7 @@ export component DetailView inherits Rectangle {
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 (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; }
@@ -158,9 +109,26 @@ export component DetailView inherits Rectangle {
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); } }
}
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);
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); } }
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;
Text { text: root.d.account.login == "" ? "Whichever account Steam is on" : root.d.account.persona; color: Theme.p.text; font-size: Theme.t-md; font-weight: 800; vertical-alignment: center; overflow: elide; }
if root.d.account.login != "": Text { text: root.d.account.login; color: Theme.p.dim; font-size: Theme.t-sm; font-weight: 600; vertical-alignment: center; overflow: elide; }
}
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; }
}
Text {
text: 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 ? "Monitor, resolution, refresh rate, fullscreen, focus, upscaler, frame generation and target rate for this game."
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."
: 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;
@@ -182,7 +150,9 @@ export component DetailView inherits Rectangle {
Field { label: "Frame generation"; value: root.d.framegen; unset: root.d.framegen == "None"; }
Field { label: "Window"; value: root.d.window; unset: root.d.window == "Default"; }
Rectangle { height: 8px; }
Text { text: "Monitor and mode are switched when Summit starts the game and put back when it ends" + (root.g.source == "Steam" ? " (Steam games: put back only with Enhance, when the window closes)" : "") + ". Upscaler and frame generation are used when Enhance is on. Focus is stored only."; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
Text { text: root.d.profile-note; color: root.d.profile-set ? Theme.p.accent : Theme.p.dim; font-size: Theme.t-xs; font-weight: 700; wrap: word-wrap; }
Rectangle { height: 4px; }
Text { text: "Monitor and mode are switched when Summit starts the game and put back when it ends" + (root.g.source == "Steam" ? " (Steam games: put back only with Enhance, when the window closes)" : "") + ". Window mode and focus are applied to the game's window once it opens (KDE Plasma, or X11 with wmctrl). Upscaler and frame generation are used when Enhance is on."; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
}
}
Panel {
@@ -201,9 +171,13 @@ export component DetailView inherits Rectangle {
}
}
picker := AccountPicker {
visible: Lib.accounts-open; opacity: self.visible ? 1 : 0;
}
editor := ProfileEditor {
title: root.g.title;
visible: Lib.editor-open; opacity: Lib.editor-open ? 1 : 0;
close => { Lib.editor-open = false; }
visible: Lib.editor-open && !Lib.editor-defaults; opacity: self.visible ? 1 : 0;
close => { Lib.editor-open = false; Lib.editor-typing = false; }
refocus => { root.refocus(); }
}
}
+135
View File
@@ -0,0 +1,135 @@
// 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.
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; }
}
}
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;
}
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);
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(); }
}
}
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"; }
}
}
+16 -6
View File
@@ -12,11 +12,13 @@ component Shelf inherits Rectangle {
property <length> gap: Theme.big ? 20px : 16px;
property <length> step: root.card-w + root.gap;
property <int> nvis: Math.max(1, Math.floor((root.width - 2 * Theme.pad + root.gap) / root.step));
property <int> first: 0;
// how far the row is scrolled; the keyboard snaps it to whole covers, the wheel moves it freely
property <length> off: 0px;
property <length> max-off: Math.max(0px, (root.items.length - root.nvis) * root.step);
function follow() {
if (root.cur < root.first) { root.first = root.cur; }
else if (root.cur > root.first + root.nvis - 1) { root.first = root.cur - root.nvis + 1; }
if (root.first > Math.max(0, root.items.length - root.nvis)) { root.first = Math.max(0, root.items.length - root.nvis); }
if (root.cur * root.step < root.off) { root.off = root.cur * root.step; }
else if (root.cur > Math.floor(root.off / root.step + 0.001) + root.nvis - 1) { root.off = (root.cur - root.nvis + 1) * root.step; }
root.off = Math.clamp(root.off, 0px, root.max-off);
}
changed cur => { root.follow(); }
changed nvis => { root.follow(); }
@@ -25,9 +27,17 @@ component Shelf inherits Rectangle {
animate color { duration: Theme.ms(160); } }
Text { x: Theme.pad + 12px + tw.preferred-width; y: 4px; text: root.items.length; color: Theme.p.faint; font-size: Theme.t-sm; font-weight: 600; }
tw := Text { visible: false; text: root.title; font-size: Theme.t-sm; font-weight: 800; letter-spacing: 1.6px; }
// the wheel (or a sideways swipe) scrolls the covers instead of changing rows
TouchArea {
scroll-event(e) => {
if (root.max-off <= 0px) { return reject; }
root.off = Math.clamp(root.off - (e.delta-x != 0px ? e.delta-x : e.delta-y), 0px, root.max-off);
return accept;
}
}
Rectangle {
y: 40px; height: root.card-w * 1.5;
x: Theme.pad - root.first * root.step; width: root.items.length * root.step;
x: Theme.pad - root.off; width: root.items.length * root.step;
animate x { duration: Theme.ms(280); easing: Theme.ease; }
for idx[i] in root.items: CoverCard {
x: i * root.step; y: 0; width: root.card-w;
@@ -122,7 +132,7 @@ export component HomeView inherits Rectangle {
HorizontalLayout { alignment: center; LogoMark { size: 88px; } }
Text { text: "No games yet"; color: Theme.p.text; font-size: Theme.t-2xl; font-weight: 800; horizontal-alignment: center; }
Text { text: "Summit looks in Steam, Heroic and Lutris. Nothing was found on this machine."; color: Theme.p.dim; font-size: Theme.t-md; horizontal-alignment: center; }
Text { text: "Add anything by hand: Library > + Add a game (or summit add \"My Game\" ~/Games/mygame/run.sh)"; color: Theme.p.faint; font-size: Theme.t-sm; horizontal-alignment: center; }
Text { text: "Add anything by hand: Library > + Add a game or console (or summit add \"My Game\" ~/Games/mygame/run.sh)"; color: Theme.p.faint; font-size: Theme.t-sm; horizontal-alignment: center; }
}
}
+3 -3
View File
@@ -92,7 +92,7 @@ export component LibraryView inherits Rectangle {
function activate(t: int) {
if (t <= 2) { Lib.filter = t; Lib.query(); }
else if (t == 3) { Lib.sort = Math.mod(Lib.sort + 1, 3); Lib.query(); }
else if (t == 4) { Lib.add-game(-1); }
else if (t == 4) { Lib.open-add(); }
else { search.grab(); }
}
changed n => { if (root.sel > Math.max(0, root.n - 1)) { root.sel = 0; } if (root.n == 0) { root.zone = 0; } }
@@ -148,12 +148,12 @@ export component LibraryView inherits Rectangle {
Rectangle { width: 16px; Rectangle { x: 8px; y: 7px; width: 1px; height: 20px; background: Theme.p.border; } }
Chip { text: "Sort: " + root.sorts[Lib.sort]; focused: root.active && root.zone == 0 && root.tool == 3; clicked => { root.activate(3); } }
Rectangle { width: 16px; Rectangle { x: 8px; y: 7px; width: 1px; height: 20px; background: Theme.p.border; } }
Chip { text: "+ Add a game"; focused: root.active && root.zone == 0 && root.tool == 4; clicked => { root.activate(4); } }
Chip { text: "+ Add a game or console"; focused: root.active && root.zone == 0 && root.tool == 4; clicked => { root.activate(4); } }
}
if root.n == 0: EmptyState { y: root.head-h; height: root.height - root.head-h;
title: Lib.total-games == 0 ? "No games yet" : "Nothing matches";
hint: Lib.total-games == 0 ? "Summit found no games on this machine. Add one with + Add a game above (it asks for the file that starts it)." : "Try another filter, or clear the search."; }
hint: Lib.total-games == 0 ? "Summit found no games on this machine. Add one with + Add a game or console above: a game on this PC, a capture card or PlayStation Remote Play." : "Try another filter, or clear the search."; }
// ---- cover grid: one ListView row per grid row, so only the rows on screen exist ----
grid-view := ListView {
+86
View File
@@ -0,0 +1,86 @@
// While a game started from the launcher runs: first a loading screen, then a small "now playing" card.
// Nothing else of the launcher is on screen or takes input then, so a controller in the game cannot press things
// here. It goes away by itself when the game closes (Rust: App::end_playing).
import { Theme } from "theme.slint";
import { Lib, Icon, Icons, Btn, KeyCap, LogoMark } from "widgets.slint";
// Three dots that pulse one after the other.
component Dots inherits Rectangle {
in property <bool> running;
width: 56px; height: 12px;
property <float> t: root.running && Theme.motion ? Math.mod(animation-tick() / 1.2s, 1.0) : 0.3;
for i in 3: Rectangle {
x: i * 22px; y: 0; width: 12px; height: 12px; border-radius: 6px;
background: Theme.p.accent;
opacity: 0.25 + 0.75 * Math.max(0, 1 - Math.abs(Math.mod(root.t * 3 - i + 3, 3) - 0.5) * 1.6);
}
}
export component PlayingView inherits Rectangle {
in property <int> phase: Lib.play-phase; // 0 starting, 1 running, 2 stopping
in-out property <int> btn: 0; // 0 back to the launcher, 1 stop
background: Theme.p.bg;
// keys come here while it is up; everything else is swallowed by the window (app.slint)
public function key(e: KeyEvent) -> bool {
if (e.text == Key.Escape) { Lib.play-back(); return true; }
if (e.text == Key.LeftArrow || e.text == Key.UpArrow) { root.btn = 0; return true; }
if ((e.text == Key.RightArrow || e.text == Key.DownArrow) && Lib.play-can-stop) { root.btn = 1; return true; }
if (e.text == Key.Return || e.text == " ") {
if (root.btn == 1 && Lib.play-can-stop) { Lib.play-stop(); } else { Lib.play-back(); }
return true;
}
return false;
}
// the game's art, far back and dark
Image { source: Lib.play-art; width: parent.width; height: parent.height; image-fit: cover; opacity: Lib.play-has-art ? 0.16 : 0; }
Rectangle { background: @linear-gradient(180deg, Theme.p.bg.with-alpha(0.55) 0%, Theme.p.bg 100%); }
TouchArea { } // clicks stop here
LogoMark { x: Theme.pad; y: Theme.pad - 8px; size: 26px; opacity: 0.8; }
// the card: the cover (when there is one), then what is going on
property <length> cover-w: Lib.play-has-art ? 168px : 0px;
property <length> gap: Lib.play-has-art ? 36px : 0px;
property <length> card-w: Math.min(root.width - 2 * Theme.pad, 880px);
property <length> card-x: (root.width - root.card-w) / 2;
property <length> card-y: (root.height - 252px) / 2 - 12px;
if Lib.play-has-art: Rectangle {
x: root.card-x; y: root.card-y; width: root.cover-w; height: 252px; border-radius: Theme.r-md; clip: true;
border-width: Theme.p.border-w; border-color: Theme.p.border;
Image { source: Lib.play-art; width: parent.width; height: parent.height; image-fit: cover; }
}
VerticalLayout {
x: root.card-x + root.cover-w + root.gap; y: root.card-y; width: root.card-w - root.cover-w - root.gap; height: 252px;
alignment: center; spacing: 14px;
Text {
text: root.phase == 0 ? "STARTING" : root.phase == 2 ? "STOPPING" : "NOW PLAYING";
color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px;
}
Text { text: Lib.play-title; color: Theme.p.text; font-size: Theme.t-xl + 8px; font-weight: 800; overflow: elide; }
HorizontalLayout {
alignment: start; spacing: 14px; height: 24px;
if root.phase != 1: VerticalLayout { alignment: center; Dots { running: true; } }
if root.phase == 1: VerticalLayout { alignment: center; Rectangle { width: 10px; height: 10px; border-radius: 5px; background: Theme.p.ok; } }
Text { text: Lib.play-status; color: Theme.p.dim; font-size: Theme.t-md; vertical-alignment: center; overflow: elide; }
}
Text {
text: root.phase == 0 ? "Summit steps aside while the game opens."
: "Summit is paused while you play, controller included. It comes back when the game closes.";
color: Theme.p.faint; font-size: Theme.t-sm; wrap: word-wrap;
}
Rectangle { height: 6px; }
HorizontalLayout {
alignment: start; spacing: 12px;
Btn { text: "Back to the launcher"; icon: Icons.back; focused: root.btn == 0 || !Lib.play-can-stop; clicked => { root.btn = 0; Lib.play-back(); } }
if Lib.play-can-stop: Btn { text: "Stop the game"; icon: Icons.close; focused: root.btn == 1; clicked => { root.btn = 1; Lib.play-stop(); } }
}
}
HorizontalLayout {
x: Theme.pad; y: parent.height - 48px; width: parent.width - 2 * Theme.pad; height: 22px; alignment: end; spacing: 24px;
KeyCap { key: "Esc"; label: "Back to the launcher"; }
KeyCap { key: "Hold B"; label: "Back, when this window is in front"; }
}
}
+33 -12
View File
@@ -1,6 +1,7 @@
// Settings: layout, theme, UI scale, motion, clip lengths and the default enhance profile.
// 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;
@@ -45,10 +46,11 @@ 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 : 1112px;
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 : 1328px;
}
pure function rh(i: int) -> length { return i == 1 ? 160px : 72px; }
function reveal() {
@@ -66,13 +68,17 @@ export component SettingsView inherits Rectangle {
else if (root.srow == 5) { Prefs.replay = Math.clamp(Prefs.replay + d, 0, 5); Prefs.clip = Math.min(Prefs.clip, Prefs.replay); }
else if (root.srow == 6) { Prefs.clip = Math.clamp(Prefs.clip + d, 0, Prefs.replay); }
else if (root.srow == 7) { return; }
else if (root.srow == 8) { Prefs.upscaler = Math.clamp(Prefs.upscaler + d, 0, 2); }
else { Prefs.framegen = Math.clamp(Prefs.framegen + d, 0, 1); }
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();
}
public function key(e: KeyEvent) -> bool {
if (e.text == Key.DownArrow) { root.srow = Math.min(9, root.srow + 1); }
if (Lib.editor-open && Lib.editor-defaults) { return editor.key(e); }
if (e.text == Key.DownArrow) { root.srow = Math.min(11, 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); }
@@ -82,7 +88,7 @@ export component SettingsView inherits Rectangle {
}
flick := Flickable {
width: root.width; height: root.height; content-width: root.width; content-height: 1260px;
width: root.width; height: root.height; content-width: root.width; content-height: 1476px;
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; }
@@ -125,13 +131,28 @@ export component SettingsView inherits Rectangle {
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: "ENHANCE DEFAULTS"; icon: Icons.monitor; }
Row { x: root.cx; y: root.ry(8); width: root.cw; label: "Default upscaler"; hint: "Stored in the \"default\" profile for summit enhance. Each game has its own on its page (Profile)."; focused: root.active && root.srow == 8; hit => { root.srow = 8; }
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 100px + 8px; options: ["None", "FSR", "RTX VSR"]; value <=> Prefs.upscaler; changed => { root.srow = 8; root.save(); } }
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(); } }
}
Row { x: root.cx; y: root.ry(9); width: root.cw; label: "Default frame generation"; hint: "RIFE needs an NVIDIA GPU and the engine's Python environment."; focused: root.active && root.srow == 9; hit => { root.srow = 9; }
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 2 * 100px + 8px; options: ["None", "RIFE"]; value <=> Prefs.framegen; changed => { root.srow = 9; 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(); } }
}
Text { x: root.cx; y: 1204px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
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(); } }
}
Text { x: root.cx; y: 1420px; 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; }
refocus => { root.refocus(); }
}
}
+60
View File
@@ -0,0 +1,60 @@
// The intro over the launcher as it opens: Summit's icon rises in over a warm glow, the name and a short bar
// follow, then the whole thing lifts and fades into the app. About a second, it takes no keys or clicks (the app
// underneath is already live), and it is skipped when motion is off (speed 0, or the headless renders).
import { Theme } from "theme.slint";
export component Splash inherits Rectangle {
// go flips one frame after the window opens: every animation hangs off it, with its own delay.
property <bool> go: false;
property <bool> done: false;
property <duration> leave: Theme.ms(760);
visible: Theme.motion && !root.done;
background: Theme.p.bg;
opacity: root.go ? 0 : 1;
animate opacity { delay: root.leave; duration: Theme.ms(320); easing: ease-in-out; }
Timer { interval: 50ms; running: Theme.motion && !root.go; triggered => { root.go = true; } }
Timer { interval: root.leave + Theme.ms(360); running: Theme.motion && root.go && !root.done; triggered => { root.done = true; } }
// the glow behind the icon, the same amber as the icon's
Rectangle {
width: 560px; height: 560px; x: (root.width - self.width) / 2; y: (root.height - self.height) / 2 - 36px;
background: @radial-gradient(circle, #ffb02e.with-alpha(0.20) 0%, #ff7a3d.with-alpha(0.08) 40%, #ff7a3d.with-alpha(0) 70%);
opacity: root.go ? 1 : 0;
transform-scale: root.go ? 1.0 : 0.55;
animate opacity { duration: Theme.ms(520); easing: ease-out-quart; }
animate transform-scale { duration: Theme.ms(900); easing: ease-out-quart; }
}
// icon, name and bar, lifted a little as the splash leaves
stack := Rectangle {
width: 240px; height: 200px; x: (root.width - self.width) / 2; y: (root.height - self.height) / 2 - 20px;
transform-scale: root.go ? 1.06 : 1.0;
animate transform-scale { delay: root.leave; duration: Theme.ms(340); easing: ease-in-quad; }
Image {
source: @image-url("../../../packaging/icons/summit-256.png");
width: 112px; height: 112px; x: (parent.width - self.width) / 2;
y: root.go ? 0px : 18px;
opacity: root.go ? 1 : 0;
transform-scale: root.go ? 1.0 : 0.82;
animate y { duration: Theme.ms(460); easing: ease-out-quart; }
animate opacity { duration: Theme.ms(300); easing: ease-out-quad; }
animate transform-scale { duration: Theme.ms(520); easing: ease-out-back; }
}
Text {
width: parent.width; horizontal-alignment: center;
y: root.go ? 136px : 148px;
text: "SUMMIT"; color: Theme.p.text; font-size: 26px; font-weight: 800; letter-spacing: 6px;
opacity: root.go ? 1 : 0;
animate y { delay: Theme.ms(130); duration: Theme.ms(420); easing: ease-out-quart; }
animate opacity { delay: Theme.ms(130); duration: Theme.ms(320); easing: ease-out-quad; }
}
Rectangle {
y: 184px; height: 3px; border-radius: 1.5px;
width: root.go ? 72px : 0px; x: (parent.width - self.width) / 2;
background: @linear-gradient(90deg, #ffb02e 0%, #ff7a3d 100%);
animate width { delay: Theme.ms(220); duration: Theme.ms(480); easing: ease-out-quart; }
}
}
}
+103 -4
View File
@@ -17,10 +17,36 @@ export struct Game {
c2: color,
reasons: string, // detection reasons on one line
action: string, // "PLAY", "INSTALL", "ADD" (found on disk), or "" when Summit cannot start it yet
glyph: int, // drawn on art-less covers: 0 none, 1 PlayStation Remote Play, 2 capture card
}
// One choice, row or found device in the Add dialog (add.slint).
export struct AddItem {
label: string,
detail: string,
status: string, // "On", "Rest mode", "Already added"...
state: int, // 0 neutral, 1 good, 2 needs attention, 3 unavailable
glyph: int, // 0 a game on this PC, 1 PlayStation Remote Play, 2 a capture card, 3 a webcam
enabled: bool,
}
export struct URow { header: bool, label: string, count: int, idx: int }
// A Steam account remembered on this PC (Steam's sign-in list), for a game's page and the account picker.
// persona "" with login "": no account (the picker's Automatic row, or a game that starts on whatever Steam is on).
export struct SteamAccount {
persona: string, // display name
login: string, // account (sign-in) name
avatar: image,
has-avatar: bool,
initial: string, // shown when there is no avatar
note: string, // "Signed in now", "Played Counter-Strike 2 here last"...
warn: string, // "Steam will ask for the password"
selected: bool, // the game's choice in the picker
c1: color, // the round fallback behind the initial, when there is no avatar
c2: color,
}
// Filled by Rust when a game's page opens.
export struct Detail {
idx: int,
@@ -34,16 +60,21 @@ export struct Detail {
framegen: string,
window: string,
profile-set: bool,
profile-note: string, // how much of the profile is the game's own
play-label: string,
play-note: string,
can-play: bool,
enhance: bool, // Play also runs the engine (frame generation + upscaler) on the game's window
can-enhance: bool,
enhance-note: string,
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
}
// One row of the profile editor: a value picked from options.
export struct PRow { label: string, hint: string, options: [string], value: int }
// 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).
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 {
@@ -52,8 +83,11 @@ export global Prefs {
in-out property <int> replay: 2; // index into 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-out property <int> upscaler: 0; // none, fsr, rtx-vsr
in-out property <int> framegen: 0; // none, rife
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
}
@@ -84,16 +118,54 @@ export global Lib {
// profile editor
in property <[PRow]> prof-rows;
in property <string> prof-file;
in property <string> prof-title;
in property <string> prof-note;
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 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
in property <string> clips-dir; // where saved clips go
callback open-clips(); // pick a cover image with the desktop's file dialog
in property <string> hotkey-status; // the global save-clip key, for the settings page
// the Add dialog (add.slint): what to add, then what was found
in-out property <bool> add-open;
in-out property <int> add-step; // 0 what to add, 1 capture card, 2 PlayStation Remote Play
in-out property <int> add-row; // focused choice, row, or button (rows first, then add-buttons)
in property <[AddItem]> add-choices;
in property <[AddItem]> add-items;
in property <[string]> add-buttons;
in property <string> add-note; // under the list: what is missing, what Enhance needs
in property <string> add-empty; // instead of the list when nothing was found
callback open-add();
callback add-choose(int); // 0 a game on this PC (file dialog), 1 capture card, 2 Remote Play
callback add-pick(int); // a row, or add-buttons[i - add-items.length]
// the Steam account picker, over a Steam game's page: row 0 automatic, then accounts[i - 1]
in property <[SteamAccount]> accounts;
in property <string> accounts-title;
in property <string> accounts-auto; // under Automatic: who that is for this game
in property <bool> accounts-auto-selected; // the game has no account of its own
in-out property <bool> accounts-open;
in-out property <int> accounts-row;
callback open-accounts(int); // the game's index
callback pick-account(int); // the row
// while a game started from here runs (playing.slint): the launcher shows only that and takes no other input
in property <bool> playing;
in property <int> play-phase; // 0 starting, 1 running, 2 stopping
in property <string> play-title;
in property <string> play-status; // "Opening through Steam, with Enhance", "Playing for 12 min"
in property <image> play-art;
in property <bool> play-has-art;
in property <bool> play-can-stop; // Summit holds the game's process, so it can end it
callback play-back(); // show the launcher again; the game keeps running
callback play-stop();
}
// 24x24 line icons, drawn as paths so they follow the theme and scale cleanly.
@@ -131,6 +203,13 @@ export global Icons {
out property <string> sliders: "M4 7 H13 M17 7 H20 M4 17 H7 M11 17 H20 M15 4.5 V9.5 M9 14.5 V19.5";
out property <string> info: "M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18z M12 11 V16.5 M12 7.6 H12.01";
out property <string> sparkle: "M12 3 L13.8 10.2 L21 12 L13.8 13.8 L12 21 L10.2 13.8 L3 12 L10.2 10.2 Z";
out property <string> gamepad: "M7 7.5 H17 A4.5 4.5 0 0 1 21.3 13.2 L20.4 17 A2.3 2.3 0 0 1 16.4 18 L14.6 15.5 H9.4 L7.6 18 A2.3 2.3 0 0 1 3.6 17 L2.7 13.2 A4.5 4.5 0 0 1 7 7.5 Z M7.5 10.2 V13.6 M5.8 11.9 H9.2 M15.6 10.8 H15.61 M17.6 12.8 H17.61";
out property <string> capture: "M3 5 H21 V16 H3 Z M8 20 H16 M12 16 V20 M10 8.3 L14.6 10.5 L10 12.7 Z";
out property <string> camera: "M12 3.5a6.5 6.5 0 1 0 0 13a6.5 6.5 0 0 0 0-13z M12 7.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 0 0 0-5z M8 20.5 H16 M12 16.5 V20.5";
out property <string> folder: "M3 6.5 A1.5 1.5 0 0 1 4.5 5 H9.5 L11.5 7.5 H19.5 A1.5 1.5 0 0 1 21 9 V17.5 A1.5 1.5 0 0 1 19.5 19 H4.5 A1.5 1.5 0 0 1 3 17.5 Z";
out property <string> refresh: "M19.5 12 A7.5 7.5 0 1 1 17.3 6.7 M19.5 4 V8.5 H15";
out property <string> link: "M10 14 L14 10 M8.8 11.2 L6.6 13.4 A3.2 3.2 0 0 0 11.1 17.9 L13.3 15.7 M11.2 8.8 L13.4 6.6 A3.2 3.2 0 0 1 17.9 11.1 L15.7 13.3";
out property <string> user: "M12 4a4 4 0 1 0 0 8a4 4 0 0 0 0-8z M4.5 20.5 A7.5 7.5 0 0 1 19.5 20.5";
out property <string> film: "M3 6 H15 V18 H3 Z M15 10.5 L21 7 V17 L15 13.5";
}
@@ -316,6 +395,10 @@ export component CoverArt inherits Rectangle {
text: root.g.title; color: white; font-size: root.title-size; font-weight: 800; wrap: word-wrap; overflow: elide;
vertical-alignment: top;
}
if root.g.glyph > 0 && root.width > 60px: Icon {
x: root.width * 0.1 - root.width * 0.02; y: root.height * 0.52; size: root.width * 0.42; weight: 1.6px; color: #ffffffc8;
commands: root.g.glyph == 1 ? Icons.gamepad : Icons.capture;
}
if root.width > 110px: Text {
x: root.width * 0.1; y: root.height - 30px; text: root.g.source; color: #ffffffb0; font-size: 10px; font-weight: 700; letter-spacing: 1.2px;
}
@@ -388,3 +471,19 @@ export component Toast inherits Rectangle {
Icon { x: 18px; y: 14px; size: 20px; color: Theme.p.accent; commands: Icons.info; }
t := Text { x: 48px; width: parent.width - 66px; height: parent.height; text: root.text; color: Theme.p.text; font-size: Theme.t-sm; font-weight: 600; vertical-alignment: center; overflow: elide; }
}
// A round Steam avatar; the first letter of the name on a gradient when Steam has no picture cached.
export component Avatar inherits Rectangle {
in property <SteamAccount> a;
in property <length> size: 48px;
in property <string> icon; // drawn instead of a letter (the Automatic row)
width: root.size; height: root.size; border-radius: root.size / 2; clip: true;
background: root.a.has-avatar ? Theme.p.surface : @linear-gradient(135deg, root.a.c1 0%, root.a.c2 100%);
if root.a.has-avatar: Image { width: parent.width; height: parent.height; source: root.a.avatar; image-fit: cover; }
if !root.a.has-avatar && root.icon != "": Icon { x: (parent.width - self.size) / 2; y: (parent.height - self.size) / 2; size: root.size * 0.5; color: Theme.p.accent; commands: root.icon; }
if !root.a.has-avatar && root.icon == "": Text {
width: parent.width; height: parent.height; horizontal-alignment: center; vertical-alignment: center;
text: root.a.initial;
color: #ffffff; font-size: root.size * 0.42; font-weight: 800; overflow: clip;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 577 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 600 B

After

Width:  |  Height:  |  Size: 690 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 919 B

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

+137 -42
View File
@@ -1,4 +1,5 @@
"""System-wide keys on Linux: the save-a-clip key works while the game, not the engine, has the keyboard.
"""System-wide keys on Linux: the save-a-clip key and the overlay's key work while the game, not the engine, has the
keyboard.
X11 XGrabKey on the root window, through libX11 with ctypes (no extra package). A key another program
already grabbed is reported as taken.
@@ -11,6 +12,11 @@
else reported as unavailable (`GlobalKeys.status`), and the engine window's own keys (R) still work.
Same interface as replay.Hotkeys (Windows): GlobalKeys({"ctrl+alt+r": fn}).start() / .stop().
The overlay (framegen/menu.py) over a game uses X11Keys directly, on X11 and through XWayland: its key may be a key
on its own (Insert), which only an X grab takes without asking, and while the overlay is open X11Keys.set_modal takes
the whole keyboard, so the arrows, Enter and Esc move about in the overlay instead of reaching the game. The game
gets its keys back the moment the overlay closes.
"""
from __future__ import annotations
@@ -29,23 +35,35 @@ MODS = {"shift": SHIFT, "ctrl": CONTROL, "control": CONTROL, "alt": MOD1, "super
IGNORED = (0, LOCK, MOD2, LOCK | MOD2)
KEYPRESS = 2
REPEAT_S = 0.4 # holding the keys down repeats KeyPress: one save per press
MODAL_S = 2.0 # X11Keys.set_modal: the keyboard goes back to the game if the overlay hasn't asked again for this long
def parse(combo: str) -> tuple[int, str]:
""""ctrl+alt+r" -> (X11 modifier mask, key name for XStringToKeysym). ValueError if it has no key or no
modifier (a key on its own would be taken from the game)."""
# Key names as written (lower case) -> X keysym names, where they differ from the lower-case name itself
KEYSYMS = {"insert": "Insert", "ins": "Insert", "home": "Home", "end": "End", "delete": "Delete", "del": "Delete",
"pageup": "Prior", "prior": "Prior", "pagedown": "Next", "next": "Next", "pause": "Pause",
"scrolllock": "Scroll_Lock", "scroll_lock": "Scroll_Lock", "tab": "Tab", "space": "space",
"esc": "Escape", "escape": "Escape", "enter": "Return", "return": "Return", "backspace": "BackSpace",
"up": "Up", "down": "Down", "left": "Left", "right": "Right"}
KEYSYMS |= {f"f{n}": f"F{n}" for n in range(1, 25)}
# The overlay's keys (X keysym names), taken one by one while it's open when the whole keyboard can't be
NAV_KEYS = ("Up", "Down", "Left", "Right", "Return", "KP_Enter", "Escape", "BackSpace", "Tab", "Prior", "Next")
def parse(combo: str, bare: bool = False) -> tuple[int, str]:
""""ctrl+alt+r" -> (X11 modifier mask, key name for XStringToKeysym). ValueError if it has no key, or no
modifier (a key on its own would be taken from the game) unless `bare` allows that (the overlay's key)."""
parts = [p.strip().lower() for p in combo.split("+") if p.strip()]
mods, key = 0, None
for p in parts:
if p in MODS:
mods |= MODS[p]
elif key is None:
key = p
key = KEYSYMS.get(p, p)
else:
raise ValueError(f"{combo!r}: more than one key")
if key is None:
raise ValueError(f"{combo!r}: no key")
if not mods & (CONTROL | MOD1 | MOD4):
if not bare and not mods & (CONTROL | MOD1 | MOD4):
raise ValueError(f"{combo!r}: needs Ctrl, Alt or Super")
return mods, key
@@ -90,22 +108,47 @@ BAD_ACCESS = 10
class X11Keys:
"""XGrabKey on the root window of its own X connection, read on a thread of its own."""
"""XGrabKey on the root window of its own X connection, read on a thread of its own.
def __init__(self, keys: dict, display: str | None = None) -> None:
self.keys, self.name = keys, display or os.environ.get("DISPLAY", ":0")
bare: a key on its own may be grabbed too (the overlay's key: Insert, Home). set_modal(True, fn): from then
until set_modal(False) every key goes here instead of to the game, and fn(name, shift) gets each press that
isn't one of `keys` (name: the X keysym name in lower case: "up", "return", "escape", "tab"). `modal` says how
that went: "keyboard" (the whole keyboard), "keys" (another program holds the keyboard, so only NAV_KEYS were
taken) or "" (off). The overlay asks again every time round its loop while it's open; if it stops asking for
MODAL_S (the video loop stalled), the keyboard goes back to the game by itself."""
def __init__(self, keys: dict, display: str | None = None, bare: bool = False) -> None:
self.keys, self.name, self.bare = keys, display or os.environ.get("DISPLAY", ":0"), bare
self.got: list[str] = [] # combos grabbed
self.taken: list[str] = [] # combos another program has
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._ready = threading.Event()
self.error: str | None = None
self.modal = ""
self._modal_want, self._modal_fn, self._modal_asked = False, None, 0.0
self._wake = os.pipe() # set_modal and stop wake the thread through it
def start(self) -> None:
self._thread = threading.Thread(target=self._run, name="globalkeys-x11", daemon=True)
self._thread.start()
self._ready.wait(5)
def set_modal(self, on: bool, fn=None) -> None:
"""Takes the keyboard for the overlay, or gives it back (any thread; done on the key thread, at once).
While it's on, call it again at least every MODAL_S."""
self._modal_fn = fn if on else self._modal_fn
self._modal_asked = time.monotonic()
if on != self._modal_want or on != bool(self.modal):
self._modal_want = on
self._poke()
def _poke(self) -> None:
try:
os.write(self._wake[1], b"x")
except OSError:
pass
def _run(self) -> None:
try:
x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
@@ -117,9 +160,14 @@ class X11Keys:
x.XDefaultRootWindow.restype, x.XDefaultRootWindow.argtypes = c_ulong, [c_void_p]
x.XStringToKeysym.restype, x.XStringToKeysym.argtypes = c_ulong, [c_char_p]
x.XKeysymToKeycode.restype, x.XKeysymToKeycode.argtypes = ctypes.c_ubyte, [c_void_p, c_ulong]
x.XKeysymToString.restype, x.XKeysymToString.argtypes = c_char_p, [c_ulong]
x.XLookupKeysym.restype, x.XLookupKeysym.argtypes = c_ulong, [POINTER(_XKeyEvent), c_int]
x.XGrabKey.argtypes = [c_void_p, c_int, c_uint, c_ulong, c_int, c_int, c_int]
x.XUngrabKey.argtypes = [c_void_p, c_int, c_uint, c_ulong]
x.XGrabKeyboard.restype, x.XGrabKeyboard.argtypes = c_int, [c_void_p, c_ulong, c_int, c_int, c_int, c_ulong]
x.XUngrabKeyboard.argtypes = [c_void_p, c_ulong]
x.XSync.argtypes = [c_void_p, c_int]
x.XFlush.argtypes = [c_void_p]
x.XPending.argtypes = [c_void_p]
x.XNextEvent.argtypes = [c_void_p, POINTER(_XEvent)]
x.XConnectionNumber.argtypes = [c_void_p]
@@ -131,56 +179,102 @@ class X11Keys:
self._ready.set()
return
root = x.XDefaultRootWindow(d)
x.XSetErrorHandler(_ERROR_HANDLER)
fns: dict[tuple[int, int], tuple[str, object]] = {}
try:
for combo, fn in self.keys.items():
mods, key = parse(combo)
sym = x.XStringToKeysym(key.encode())
code = x.XKeysymToKeycode(d, sym) if sym else 0
if not code:
print(f"[keys] {combo}: no key {key!r} on this keyboard")
continue
x.XSetErrorHandler(_ERROR_HANDLER)
_x_errors.clear()
for combo, fn in self.keys.items():
try:
mods, key = parse(combo, self.bare)
except ValueError as e:
print(f"[keys] {e}")
continue
sym = x.XStringToKeysym(key.encode())
code = x.XKeysymToKeycode(d, sym) if sym else 0
if not code:
print(f"[keys] {combo}: no key {key!r} on this keyboard")
continue
_x_errors.clear()
for extra in IGNORED:
x.XGrabKey(d, code, mods | extra, root, 1, 1, 1) # owner_events, GrabModeAsync x2
x.XSync(d, 0)
if BAD_ACCESS in _x_errors:
for extra in IGNORED:
x.XGrabKey(d, code, mods | extra, root, 1, 1, 1) # owner_events, GrabModeAsync x2
x.XSync(d, 0)
if BAD_ACCESS in _x_errors:
for extra in IGNORED:
x.XUngrabKey(d, code, mods | extra, root)
self.taken.append(combo)
print(f"[keys] {combo} is taken by another program; use the engine window's own key")
continue
fns[(code, mods)] = (combo, fn)
self.got.append(combo)
except ValueError as e:
print(f"[keys] {e}")
x.XUngrabKey(d, code, mods | extra, root)
self.taken.append(combo)
print(f"[keys] {combo} is taken by another program")
continue
fns[(code, mods)] = (combo, fn)
self.got.append(combo)
self._ready.set()
nav: list[int] = [] # modal "keys": the keycodes taken one by one
def modal(on: bool) -> None:
if on and not self.modal:
# owner_events off, both async, CurrentTime: every key comes here until it's let go of
if x.XGrabKeyboard(d, root, 0, 1, 1, 0) == 0:
self.modal = "keyboard"
else: # a game or another program holds the keyboard: the overlay's own keys, one by one
for name in NAV_KEYS:
code = x.XKeysymToKeycode(d, x.XStringToKeysym(name.encode()))
if code and not any(code == c for c, _ in fns):
for extra in IGNORED:
x.XGrabKey(d, code, extra, root, 1, 1, 1)
x.XGrabKey(d, code, extra | SHIFT, root, 1, 1, 1)
nav.append(code)
self.modal = "keys"
elif not on and self.modal:
if self.modal == "keyboard":
x.XUngrabKeyboard(d, 0)
for code in nav:
for extra in IGNORED:
x.XUngrabKey(d, code, extra, root)
x.XUngrabKey(d, code, extra | SHIFT, root)
nav.clear()
self.modal = ""
x.XSync(d, 0)
fd = x.XConnectionNumber(d)
ev, last = _XEvent(), {}
try:
while not self._stop.is_set():
if self._modal_want and time.monotonic() - self._modal_asked > MODAL_S:
self._modal_want = False # nobody is looking after the overlay: the game gets its keys back
print("[keys] the overlay stopped answering: the keyboard is the game's again")
if self._modal_want != bool(self.modal):
modal(self._modal_want)
elif self.modal == "keys" and x.XGrabKeyboard(d, root, 0, 1, 1, 0) == 0:
for code in nav: # whoever held the keyboard let go: all of it now, as usual
for extra in IGNORED:
x.XUngrabKey(d, code, extra, root)
x.XUngrabKey(d, code, extra | SHIFT, root)
nav.clear()
self.modal = "keyboard"
if not x.XPending(d):
select.select([fd], [], [], 0.25)
ready = select.select([fd, self._wake[0]], [], [], 0.25)[0]
if self._wake[0] in ready:
os.read(self._wake[0], 64)
continue
x.XNextEvent(d, byref(ev))
if ev.type != KEYPRESS:
continue
k = (ev.xkey.keycode, ev.xkey.state & (SHIFT | CONTROL | MOD1 | MOD4))
hit = fns.get(k)
if hit is None:
continue
now = time.monotonic()
if now - last.get(k, 0) < REPEAT_S:
last[k] = now
continue
last[k] = now
combo, fn = hit
try:
fn()
if hit is None:
if self.modal and self._modal_fn is not None:
name = x.XKeysymToString(x.XLookupKeysym(byref(ev.xkey), 0))
if name:
self._modal_fn(name.decode().lower(), bool(ev.xkey.state & SHIFT))
continue
now = time.monotonic()
if now - last.get(k, 0) < REPEAT_S:
last[k] = now
continue
last[k] = now
hit[1]()
except Exception as e: # noqa: BLE001 - a failing save must not end the key thread
print(f"[keys] {combo}: {e}")
print(f"[keys] {hit[0] if hit else 'overlay'}: {e}")
finally:
modal(False)
for code, mods in fns:
for extra in IGNORED:
x.XUngrabKey(d, code, mods | extra, root)
@@ -189,6 +283,7 @@ class X11Keys:
def stop(self) -> None:
self._stop.set()
self._poke()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=2)
+19 -14
View File
@@ -2,15 +2,16 @@
never takes the keyboard: the app keeps it, as some apps stop drawing without it. So the video window's keys come
through Windows' system-wide shortcuts (RegisterHotKey) instead, Ctrl+Alt with the usual key by default:
Ctrl+Alt+M menu Ctrl+Alt+F fullscreen Ctrl+Alt+Esc quit
Insert overlay Ctrl+Alt+F fullscreen Ctrl+Alt+Esc quit
Ctrl+Alt+S stats Ctrl+Alt+I smooth on/off
A shortcut another program already has goes to the next one in its list (Ctrl+Alt+Space for the menu), and the video
and the launcher say which keys SmoovPlay got. People can pick their own on the launcher's Play page, which passes
them as `run.py --window-keys "menu=Ctrl+Alt+K;quit=Ctrl+Alt+End"`.
The overlay's key is the one key that may be a key on its own (Insert, or `run.py --overlay-key`: see
framegen/overlaykey.py). A shortcut another program already has goes to the next one in its list (Ctrl+Alt+M, then
Ctrl+Alt+Space, for the overlay), and the video and the launcher say which keys SmoovPlay got. People can pick their
own on the launcher's Play page, which passes them as `run.py --window-keys "menu=Ctrl+Alt+K;quit=Ctrl+Alt+End"`.
While the menu is open, its own keys (arrows, Enter, Esc, Backspace) are taken too, without Ctrl+Alt, and given back
when it closes. Windows treats AltGr as Ctrl+Alt, so while SmoovPlay plays in this mode, AltGr with these keys types
While the overlay is open, its own keys (arrows, Enter, Tab, Esc, Backspace) are taken too, without Ctrl+Alt, and
given back when it closes. Esc on its own is never taken otherwise: it's the app's. Windows treats AltGr as Ctrl+Alt, so while SmoovPlay plays in this mode, AltGr with these keys types
nothing (AltGr+M is µ on a German keyboard), which is why only five keys are taken.
"""
from __future__ import annotations
@@ -35,13 +36,14 @@ _ALIASES = {"escape": "Esc", "return": "Enter", "pgup": "PageUp", "pgdn": "PageD
# action: (what it does, in words; the video window's own key it stands for; its shortcuts, first free one wins)
ACTIONS = {
"menu": ("Menu", "M", ("Ctrl+Alt+M", "Ctrl+Alt+Space")),
"menu": ("Overlay", "M", ("Insert", "Ctrl+Alt+M", "Ctrl+Alt+Space")),
"quit": ("Quit", "Q", ("Ctrl+Alt+Esc", "Ctrl+Alt+End")),
"fullscreen": ("Fullscreen", "F", ("Ctrl+Alt+F",)),
"stats": ("Stats overlay", "S", ("Ctrl+Alt+S",)),
"smooth": ("Smooth on/off", "I", ("Ctrl+Alt+I",)),
}
NAV = ("Up", "Down", "Left", "Right", "Enter", "Esc", "Backspace") # the menu's keys, plain, while it's open
NAV = ("Up", "Down", "Left", "Right", "Enter", "Esc", "Backspace", "Tab") # the overlay's keys, plain, while it's open
BARE = ("menu",) # actions whose shortcut may be a key on its own (framegen/overlaykey.py says which keys)
# Windows' own, or keys people need to get out of things: never taken
RESERVED = {"Ctrl+Alt+Delete", "Ctrl+Shift+Esc", "Alt+Tab", "Alt+Esc", "Alt+F4", "Ctrl+Alt+Tab", "Win+L", "Win+D",
@@ -56,9 +58,10 @@ class Combo:
name: str # as shown: "Ctrl+Alt+M"
def parse(text: str) -> Combo:
def parse(text: str, bare: bool = False) -> Combo:
"""A shortcut from its name ("Ctrl+Alt+M", "ctrl + alt + escape"), or ValueError saying what's wrong with it. It
needs Ctrl, Alt or Win: a key on its own, or with Shift only, would be taken from the app."""
needs Ctrl, Alt or Win: a key on its own, or with Shift only, would be taken from the app. bare: the overlay's
key, which may be one of the keys framegen/overlaykey.py allows on their own (Insert, Home, the F keys...)."""
parts = [p.strip() for p in text.replace(" ", "").split("+") if p.strip()]
if not parts:
raise ValueError("no keys")
@@ -79,7 +82,9 @@ def parse(text: str) -> Combo:
if key is None:
raise ValueError("Ctrl, Alt, Shift or Win needs a key with it")
if not mods & (MODS["ctrl"] | MODS["alt"] | MODS["win"]):
raise ValueError("it needs Ctrl, Alt or Win, or the app would lose that key")
from .overlaykey import ALONE
if not (bare and key in ALONE):
raise ValueError("it needs Ctrl, Alt or Win, or the app would lose that key")
names = [m for m in MOD_ORDER if mods & MODS[m.lower()]]
name = "+".join(names + [key])
if name in RESERVED:
@@ -99,7 +104,7 @@ def parse_arg(text: str | None) -> dict[str, str]:
if action not in ACTIONS:
raise ValueError(f"no action {action!r} (there are {', '.join(ACTIONS)})")
try:
out[action] = parse(combo).name
out[action] = parse(combo, action in BARE).name
except ValueError as e:
raise ValueError(f"{action}: {combo.strip()!r}: {e}") from None
names = list(out.values())
@@ -124,7 +129,7 @@ def describe(got: dict[str, str | None], sep: str = "\n") -> str:
"""The keys, menu first, one a line by default ("Ctrl+Alt+M: menu", "Ctrl+Alt+F: fullscreen"...), in plain
ASCII: the video window's font has nothing else."""
order = ("menu", "fullscreen", "quit", "stats", "smooth")
return sep.join(f"{got[a]}: {ACTIONS[a][0].lower()}" for a in order if got.get(a))
return sep.join(f"{got[a]}: {ACTIONS[a][0].lower()}" for a in order if got.get(a)) # "Insert: overlay"
class Hotkeys:
@@ -139,7 +144,7 @@ class Hotkeys:
for i, (action, combos) in enumerate(choices(picked).items(), start=1):
self.got[action] = None
for name in combos:
c = parse(name)
c = parse(name, action in BARE)
if self.u32.RegisterHotKey(None, i, c.mods | NOREPEAT, c.vk):
self.got[action], self._ids[i] = name, action
break
+181
View File
@@ -0,0 +1,181 @@
"""The performance overlay and the messages over the picture, as images (framegen/ui_draw.py draws them, the GL window
blits them): stats in three styles (settings "overlay_style": Minimal, Detailed, Graphs) and toast().
Each takes the pipeline's io.MiniText (its parts, health, second line, details and graph data), `ui` (1.0 at 1080p,
times the settings' size) and `opacity` (how solid the background is; text and graph lines stay solid), and returns
an RGBA image with rounded corners.
"""
from __future__ import annotations
import numpy as np
from . import ui_draw as U
PART = {"main": U.TEXT, "dim": U.DIM, "warn": U.TIGHT} # io.MiniText part kinds
def _px(ui: float):
return lambda v: max(1, int(round(v * ui)))
def _parts_width(parts, f_main, f_rest, gap: int) -> int:
return sum(U.text_w(t, f_main if k == "main" else f_rest) for t, k in parts) + gap * max(0, len(parts) - 1)
def _draw_parts(c: U.Canvas, x: int, y: int, parts, f_main, f_rest, gap: int) -> int:
for text, kind in parts:
x += c.text(x, y, text, f_main if kind == "main" else f_rest, PART.get(kind, U.DIM)) + gap
return x - gap
def stats(t, ui: float = 1.0, opacity: float = 1.0, details=()) -> np.ndarray:
"""Minimal: a pill with a dot (green keeping up, yellow tight, red falling behind) and a few numbers. A second
line (the test line, while a test runs) goes under them. Detailed: the same with `details`, (name, value) rows,
under it."""
px = _px(ui)
f_main, f_rest = U.font(px(15), "semibold"), U.font(px(14))
f_small, f_name = U.font(px(12)), U.font(px(12))
pad, gap, r = px(13), px(11), px(5)
line_w = 2 * r + px(9) + _parts_width(t.parts, f_main, f_rest, gap)
second = U.wrap(t.second, f_small, px(520)) if t.second else []
details = [(n, v) for n, v in details if v]
name_w = max((U.text_w(n, f_name) for n, _ in details), default=0)
detail_w = max((name_w + px(16) + U.text_w(v, f_small) for _, v in details), default=0)
w = 2 * pad + max([line_w, detail_w] + [U.text_w(s, f_small) for s in second])
row, small_row = px(32), px(19)
extra = len(second) * small_row + len(details) * small_row
h = row + (extra + px(8) + (px(8) if details and second else 0) if extra else 0)
c = U.Canvas(w, h, U.BG, row // 2 if not extra else px(12), border=U.BORDER)
cy = row // 2
c.circle(pad + r, cy, r, U.HEALTH.get(t.health, U.FAINT))
_draw_parts(c, pad + 2 * r + px(9), cy, t.parts, f_main, f_rest, gap)
y = row - px(2)
if details:
c.line(pad, y, w - pad, y, U.BORDER, 1)
y += px(3)
for name, value in details:
y += small_row
c.text(pad, y - small_row // 2 + px(2), name, f_name, U.FAINT)
c.text(pad + name_w + px(16), y - small_row // 2 + px(2), value, f_small, U.DIM)
y += px(8) if details and second else 0
for s in second:
y += small_row
c.text(pad, y - small_row // 2, s, f_small, U.TIGHT)
return c.rgba(opacity)
def _plot(w: int, h: int, series, vmax: float, colour, target: float | None = None) -> np.ndarray:
"""A bar graph as an RGB image: one column per sample, newest on the right, coloured by `colour(values)` (an
array of RGB rows), with a line at `target` (the budget)."""
img = np.empty((h, w, 3), np.uint8)
img[:] = U.SURFACE
v = np.asarray(list(series)[-w:], np.float32)
if v.size:
bars = np.clip(np.round(np.minimum(v, vmax) / vmax * (h - 1)), 1, h).astype(np.int32)
fill = np.arange(h)[::-1, None] < bars[None, :] # row 0 is the top
img[:, w - v.size:][fill] = np.broadcast_to(colour(v)[None, :, :], (h, v.size, 3))[fill]
if target is not None and 0 < target < vmax:
img[h - 1 - int(round(target / vmax * (h - 1)))] = U.DIM
return img
def _levels(v: np.ndarray, good: float, tight: float) -> np.ndarray:
"""Green up to `good`, yellow up to `tight`, red above, as RGB rows."""
out = np.empty((v.size, 3), np.uint8)
out[:] = U.BAD
out[v <= tight] = U.TIGHT
out[v <= good] = U.GOOD
return out
def graphs(t, frametimes, ui: float = 1.0, opacity: float = 1.0, gpu=None) -> np.ndarray:
"""Graphs, like MangoHud's: the frame rate in big numbers, then a graph each for the time between frames on screen
(what you see), the pipeline's time per tick against its budget, Summit's delay, and the graphics card's load.
t.graph, from the pipeline: hz, tick_ms (the budget), busy, delay (lists, newest last), show (the rows the
settings leave on). frametimes: milliseconds between the window's last presents. gpu: framegen.gpustats.GpuStats."""
from PIL import Image
px = _px(ui)
g = t.graph
f_big, f_main, f_rest = U.font(px(26), "bold"), U.font(px(15), "semibold"), U.font(px(13))
f_name, f_num = U.font(px(12), "semibold"), U.font(px(12))
pad, gw, gh, gap = px(14), px(300), px(44), px(10)
target = 1000.0 / max(1, g.get("hz", 60))
tick = g.get("tick_ms", 1000 / 60)
ft = list(frametimes)[-gw:]
rows = [("frametime", "Frametime", ft, max(3 * target, float(np.percentile(ft, 99)) * 1.15 if ft else 3 * target),
target, lambda v: _levels(v, 1.35 * target, 2.2 * target)),
("pipeline", "Pipeline", g.get("busy", [])[-gw:], 2 * tick, tick, lambda v: _levels(v, 0.75 * tick, tick)),
("delay", "Delay", g.get("delay", [])[-gw:], 120.0, None, lambda v: _levels(v, 45.0, 80.0))]
show = g.get("show")
if show is not None: # the rows the settings turn off
rows = [r for r in rows if r[0] in show]
gpu = gpu if "gpu" in show else None
gpu_d = gpu.latest if gpu is not None else None
second = U.wrap(t.second, f_num, gw) if t.second else []
head, label_h, gpu_h = px(40), px(20), px(24)
w = 2 * pad + gw
h = (px(8) + head + len(rows) * (label_h + gh + gap) + (label_h + gpu_h + px(18) + gap if gpu_d else 0)
+ len(second) * px(18) + px(6))
c = U.Canvas(w, h, U.BG, px(14), border=U.BORDER)
y = px(8) + head // 2
c.circle(pad + px(5), y, px(5), U.HEALTH.get(t.health, U.FAINT))
x = pad + px(18)
for text, kind in t.parts: # the frame rate big, the rest beside it
if kind == "main" and text.endswith(" fps"):
x += c.text(x, y, text[:-4], f_big, U.TEXT) + px(5)
x += c.text(x, y + px(4), "fps", f_main, U.DIM) + px(14)
else:
x += c.text(x, y + px(4), text, f_rest, PART.get(kind, U.DIM)) + px(12)
y = px(8) + head
def plot(series, vmax, colour, tgt, height) -> None:
nonlocal y
c.img.paste(Image.fromarray(_plot(gw, height, series, max(vmax, 1.0), colour, tgt)), (pad, y))
y += height + gap
for _key, name, series, vmax, tgt, colour in rows:
series = list(series)
if series:
last, avg = series[-1], sum(series) / len(series)
if name == "Frametime":
p99 = sorted(series)[min(len(series) - 1, int(0.99 * len(series)))]
text = f"{last:.1f} ms avg {avg:.1f} 1% low {1000.0 / max(p99, 0.1):.0f} fps"
elif name == "Pipeline":
text = f"{last:.1f} ms avg {avg:.1f} budget {tick:.1f}"
else:
text = f"{last:.0f} ms avg {avg:.0f} max {max(series):.0f}"
else:
text = "-"
c.text(pad, y + label_h // 2 - px(1), name, f_name, U.TEXT)
c.text(w - pad, y + label_h // 2 - px(1), text, f_num, U.DIM, "rm")
y += label_h
plot(series, vmax, colour, tgt, gh)
if gpu_d:
c.text(pad, y + label_h // 2 - px(1), "Graphics card", f_name, U.TEXT)
c.text(w - pad, y + label_h // 2 - px(1), f"{gpu_d['util']:.0f}% {gpu_d['power']:.0f} W {gpu_d['temp']:.0f} C",
f_num, U.DIM, "rm")
y += label_h
plot(list(gpu.util), 100.0, lambda v: _levels(v, 80.0, 95.0), None, gpu_h)
c.text(pad, y - gap + px(11), f"{gpu_d['clock']:.0f} MHz memory {gpu_d['mem'] / 1024:.1f} of "
f"{gpu_d['mem_total'] / 1024:.0f} GB", f_num, U.FAINT)
y += px(18)
for s in second:
c.text(pad, y + px(8), s, f_num, U.TIGHT)
y += px(18)
return c.rgba(opacity, (U.SURFACE,))
def toast(text: str, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray:
"""A short message (one line, or a few split by newlines) on a rounded card with Summit's mark."""
px = _px(ui)
f = U.font(px(15), "medium")
lines = text.split("\n")
pad, mark, line_h = px(16), px(20), px(24)
w = pad + mark + px(12) + max(U.text_w(s, f) for s in lines) + pad + px(2)
h = len(lines) * line_h + px(22)
c = U.Canvas(w, h, U.BG, px(14), border=U.BORDER)
c.logo(pad, px(11) + (line_h - mark) // 2, mark)
for k, s in enumerate(lines):
c.text(pad + mark + px(12), px(11) + k * line_h + line_h // 2, s, f, U.TEXT if k == 0 else U.DIM)
return c.rgba(opacity)
+243 -239
View File
@@ -427,6 +427,27 @@ class _Panel:
else:
GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, w, h, GL.GL_BGR, kind, img)
def update_rgba(self, rgba: np.ndarray) -> None:
"""An RGBA picture with its own alpha (framegen/ui_draw.py: rounded corners, a see-through background),
blended over the frame. Over an HDR10 picture it's copied without its alpha instead (square and solid)."""
if self.hdr:
self.update(np.ascontiguousarray(rgba[..., 2::-1]))
return
GL = self.GL
h, w = rgba.shape[:2]
if not self.blend: # the texture's format changes: make it again
self.blend, self.w, self.h = True, 0, 0
rgba = np.ascontiguousarray(rgba)
GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
if (w, h) != (self.w, self.h):
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, rgba)
self.w, self.h = w, h
else:
GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, rgba)
_PROG: dict = {} # per GL module: the program and vertex array that draw a see-through panel
def _draw_blended(self, x: int, top: int, target: int) -> None:
@@ -480,170 +501,28 @@ void main() {
class MiniText(str):
"""The minimal stats overlay (Stats overlay style: Minimal), from the pipeline: a str (the plain line, and a
second one while a test runs) for sinks that just print text, plus what GLWindowSink draws from it:
"""The stats overlay's numbers, from the pipeline: a str (the plain line, and a second one while a test runs)
for sinks that just print text, plus what GLWindowSink draws from it (framegen/hud.py):
parts, [(text, kind)] with kind "main", "dim" or "warn"; health, how well the PC keeps up ("good", "tight",
"behind", "off" with frame generation off, "" not known yet); second, the test line or ""."""
"behind", "off" with frame generation off, "" not known yet); second, the test line or ""; details, (name, value)
rows for the Detailed style, else None; graph, the Graphs style's data, else None."""
parts: tuple = ()
health: str = ""
second: str = ""
graph: dict | None = None # the Graphs overlay's data (pipeline: hz, tick_ms, busy, delay), else None
details: tuple | None = None
@classmethod
def make(cls, parts, health: str = "", second: str = "", graph: dict | None = None) -> "MiniText":
t = cls(" ".join(x for x, _ in parts) + (f"\n{second}" if second else ""))
def make(cls, parts, health: str = "", second: str = "", graph: dict | None = None, details=None,
plain: str | None = None) -> "MiniText":
"""plain: the text for sinks that only print (default: the parts in a line, then `second`)."""
t = cls(plain if plain is not None else " ".join(x for x, _ in parts) + (f"\n{second}" if second else ""))
t.parts, t.health, t.second, t.graph = tuple(parts), health, second, graph
t.details = tuple(details) if details is not None else None
return t
# BGR: the minimal overlay's dot (how well the PC keeps up) and its text
HEALTH_COLORS = {"good": (110, 200, 80), "tight": (40, 180, 250), "behind": (70, 70, 235), "off": (150, 150, 150),
"": (110, 110, 110)}
MINI_TEXT = {"main": (245, 245, 245), "dim": (185, 185, 185), "warn": (40, 180, 250)}
def _mini(t: MiniText, ui: float) -> np.ndarray:
"""The minimal overlay: a small dark box with a dot (green keeping up, amber tight, red falling behind) and a few
numbers, plus the test line under them while a test runs."""
font, fs, th = cv2.FONT_HERSHEY_SIMPLEX, 0.52 * ui, 1 if ui < 1.6 else 2
small = 0.42 * ui
pad, gap, r = int(9 * ui), int(12 * ui), max(3, int(5 * ui))
th_main = cv2.getTextSize("90", font, fs, th)[0][1]
widths = [cv2.getTextSize(x, font, fs, th)[0][0] for x, _ in t.parts]
line_w = 2 * r + gap + sum(widths) + gap * max(0, len(widths) - 1)
second_w, second_h = (cv2.getTextSize(t.second, font, small, 1)[0] if t.second else (0, 0))
w = 2 * pad + max(line_w, second_w)
h = 2 * pad + th_main + (second_h + int(8 * ui) if t.second else 0)
img = np.full((h, w, 3), (30, 27, 25), np.uint8)
base = pad + th_main
cv2.circle(img, (pad + r, base - th_main // 2), r, HEALTH_COLORS.get(t.health, HEALTH_COLORS[""]), -1, cv2.LINE_AA)
x = pad + 2 * r + gap
for (text, kind), tw in zip(t.parts, widths):
cv2.putText(img, text, (x, base), font, fs, MINI_TEXT.get(kind, MINI_TEXT["dim"]), th, cv2.LINE_AA)
x += tw + gap
if t.second:
cv2.putText(img, t.second, (pad, base + int(8 * ui) + second_h), font, small, MINI_TEXT["dim"], 1, cv2.LINE_AA)
return img
GRAPH_BG, GRAPH_PLOT = (30, 27, 25), (44, 40, 37)
GRAPH_GOOD, GRAPH_TIGHT, GRAPH_BAD = (110, 200, 80), (40, 180, 250), (70, 70, 235)
def _plot(img, x: int, y: int, w: int, h: int, series, vmax: float, target: float | None, ui: float, colour) -> None:
"""A MangoHud-style bar graph: one vertical line per sample, newest on the right, coloured by `colour(v)`, with a
thin line at `target` (the budget). The box is x, y (top-left), w by h."""
cv2.rectangle(img, (x, y), (x + w - 1, y + h - 1), GRAPH_PLOT, -1)
vals = list(series)[-w:]
x0 = x + w - len(vals)
for i, v in enumerate(vals):
bar = max(1, int(round(min(v, vmax) / vmax * (h - 1))))
cv2.line(img, (x0 + i, y + h - 1), (x0 + i, y + h - bar), colour(v), 1)
if target is not None and 0 < target < vmax:
ty = y + h - 1 - int(round(target / vmax * (h - 1)))
cv2.line(img, (x, ty), (x + w - 1, ty), (150, 150, 150), 1, cv2.LINE_AA)
def _graphs(t: MiniText, frametimes, ui: float, gpu=None) -> np.ndarray:
"""The Graphs overlay (Stats overlay style: Graphs), like MangoHud's: the frame rate in big numbers, then a graph each
for the time between frames on screen (what you see), the pipeline's time per tick against its budget, SmoovPlay's
delay, and the graphics card's load. t.graph, from the pipeline: hz, tick_ms (the budget), busy, delay (lists, newest
last). frametimes: milliseconds between the window's last presents, newest last. gpu: framegen.gpustats.GpuStats."""
g = t.graph
font = cv2.FONT_HERSHEY_SIMPLEX
fs, small, big = 0.46 * ui, 0.40 * ui, 0.95 * ui
th = 1 if ui < 1.6 else 2
pad, gw, gh, gap = int(10 * ui), int(300 * ui), int(46 * ui), int(8 * ui)
ft = list(frametimes)[-gw:]
target = 1000.0 / max(1, g.get("hz", 60))
colour_ft = lambda v: GRAPH_GOOD if v <= 1.35 * target else GRAPH_TIGHT if v <= 2.2 * target else GRAPH_BAD # noqa: E731
tick = g.get("tick_ms", 1000 / 60)
colour_busy = lambda v: GRAPH_GOOD if v < 0.75 * tick else GRAPH_TIGHT if v < tick else GRAPH_BAD # noqa: E731
colour_delay = lambda v: GRAPH_GOOD if v < 45 else GRAPH_TIGHT if v < 80 else GRAPH_BAD # noqa: E731
def label(img, text, y, colour=MINI_TEXT["dim"], x=None, scale=small):
cv2.putText(img, text, (pad if x is None else x, y), font, scale, colour, 1, cv2.LINE_AA)
rows = [("frametime", ft, max(3 * target, float(np.percentile(ft, 99)) * 1.15 if ft else 3 * target), target,
colour_ft), ("pipeline", g.get("busy", [])[-gw:], 2 * tick, tick, colour_busy),
("delay", g.get("delay", [])[-gw:], 120.0, None, colour_delay)]
show = g.get("show")
if show is not None: # the rows the settings turn off
rows = [r for r in rows if r[0] in show]
if show is not None and "gpu" not in show:
gpu = None
th_big = cv2.getTextSize("120", font, big, th + 1)[0][1]
th_lbl = cv2.getTextSize("Ag", font, small, 1)[0][1]
gpu_d = gpu.latest if gpu is not None else None
w = 2 * pad + gw
h = 2 * pad + th_big + gap + len(rows) * (th_lbl + int(4 * ui) + gh + gap)
if gpu_d:
h += th_lbl + int(4 * ui) + int(26 * ui) + gap + th_lbl
h += (th_lbl + gap) if t.second else 0
img = np.full((h, w, 3), GRAPH_BG, np.uint8)
y = pad + th_big
cv2.circle(img, (pad + int(5 * ui), y - th_big // 2), max(3, int(5 * ui)), HEALTH_COLORS.get(t.health, HEALTH_COLORS[""]), -1,
cv2.LINE_AA)
x = pad + int(18 * ui)
for text, kind in t.parts:
sc = big if text.endswith(" fps") and kind == "main" else fs
cv2.putText(img, text, (x, y), font, sc, MINI_TEXT.get(kind, MINI_TEXT["dim"]), th if sc == big else 1, cv2.LINE_AA)
x += cv2.getTextSize(text, font, sc, th if sc == big else 1)[0][0] + int(12 * ui)
y += gap
for name, series, vmax, tgt, colour in rows:
series = list(series)
y += th_lbl
if series:
last = series[-1]
srt = sorted(series)
p99 = srt[min(len(srt) - 1, int(0.99 * len(srt)))]
if name == "frametime":
text = f"{last:5.1f} ms avg {sum(series) / len(series):4.1f} 1% low {1000.0 / max(p99, 0.1):.0f} fps"
elif name == "pipeline":
text = f"{last:5.1f} ms avg {sum(series) / len(series):4.1f} budget {tick:.1f}"
else:
text = f"{last:5.0f} ms avg {sum(series) / len(series):4.0f} max {max(series):.0f}"
else:
text = "-"
label(img, name, y, MINI_TEXT["main"])
label(img, text, y, MINI_TEXT["dim"], x=pad + int(80 * ui))
y += int(4 * ui)
_plot(img, pad, y, gw, gh, series, max(vmax, 1.0), tgt, ui, colour)
y += gh + gap
if gpu_d:
y += th_lbl
label(img, "gpu", y, MINI_TEXT["main"])
label(img, f"{gpu_d['util']:3.0f}% {gpu_d['power']:3.0f} W {gpu_d['temp']:.0f} C "
f"{gpu_d['clock']:.0f} MHz vram {gpu_d['mem'] / 1024:.1f}/{gpu_d['mem_total'] / 1024:.0f} GB",
y, MINI_TEXT["dim"], x=pad + int(40 * ui))
y += int(4 * ui)
_plot(img, pad, y, gw, int(26 * ui), list(gpu.util), 100.0, None, ui,
lambda v: GRAPH_GOOD if v < 80 else GRAPH_TIGHT if v < 95 else GRAPH_BAD)
y += int(26 * ui) + gap
if t.second:
y += th_lbl
label(img, t.second, y, MINI_TEXT["dim"])
return img
def _pill(text: str, ui: float, color=(238, 238, 238)) -> np.ndarray:
"""A short message (one line, or a few split by newlines) on a dark rounded-off box."""
fs, th = 0.7 * ui, 1 if ui < 1.4 else 2
lines = text.split("\n")
sizes = [cv2.getTextSize(t, cv2.FONT_HERSHEY_SIMPLEX, fs, th)[0] for t in lines]
tw, tht = max(w for w, _ in sizes), max(h for _, h in sizes)
padx, pady, gap = int(18 * ui), int(14 * ui), int(12 * ui)
img = np.full((len(lines) * (tht + gap) - gap + 2 * pady + int(6 * ui), tw + 2 * padx, 3), (34, 30, 28),
np.uint8)
img[:, : max(2, int(5 * ui))] = (40, 170, 255)
for k, t in enumerate(lines):
cv2.putText(img, t, (padx, pady + tht + k * (tht + gap)), cv2.FONT_HERSHEY_SIMPLEX, fs, color, th,
cv2.LINE_AA)
return img
class GLWindowSink:
"""OpenGL window (GLFW): texture upload + draw, ~1-2 ms per 1080p frame, with an in-video settings menu.
@@ -653,10 +532,12 @@ class GLWindowSink:
with AMD FSR 1 (~0.1 ms GPU at 1440p), "vsr" with NVIDIA RTX Video Super Resolution (needs NVIDIA's package
or the RTX Video SDK, see framegen/rtxvsr.py, and frames on the GPU), "bilinear" with a plain filtered blit. A
look (framegen/looks.py, drawn by framegen/looks_gl.py) goes on after that, at the window's size.
Keys: m/Tab = settings menu (arrows + Enter in it, Esc back a page), i = interpolation on/off for this session, s = stats
overlay (off, minimal, detailed), f = fullscreen, u = next upscaler, k = look on/off, j = next look (Shift+J:
the one before), l = delay test (PS5 Remote Play), r = save the instant replay, b = save a before & after video
of it (framegen/replay.py), q/Esc = quit.
Keys: Insert (the overlay's key: run.py --overlay-key, from the launcher's Settings page), m, Tab or a right-click =
the overlay (framegen/menu.py: arrows, Enter and Tab in it, Esc closes it), i = interpolation on/off for this
session, s = stats overlay (off, minimal, detailed, graphs), f = fullscreen, u = next upscaler, k = look on/off,
j = next look (Shift+J: the one before), l = delay test (PS5 Remote Play), r = save the instant replay, b = save a
before & after video of it (framegen/replay.py), Ctrl+Q = quit. Esc never quits (it's a game's own key): Quit
is a row in the overlay.
restart_reasons(): labels of pending restart-only changes (the menu then offers "Restart now", which makes
write() return "restart"). choices: {key: allowed values} for options the program can't use right now;
@@ -674,23 +555,26 @@ class GLWindowSink:
overlay_of (window capture, framegen/window.py): () -> (the app's picture area, its monitor) in screen pixels, or
None while it's minimised. The window then sits over the app's picture (fullscreen: over its monitor), clicks
and keys go through to the app, it never takes the focus, and it's left out of the capture. Settings change on
the launcher's Settings page, since the keys go to the app.
and keys go through to the app, it never takes the focus, and it's left out of the capture. The overlay's key is
then taken system-wide (Linux: framegen/globalkeys.py X11Keys, on X11 and through XWayland; Windows:
framegen/hotkeys.py), and only while the overlay is open are the keyboard and the mouse Summit's: the game has
every key but that one the rest of the time.
"""
NAMES = {"fsr": "FSR 1", "vsr": "RTX VSR", "bilinear": "bilinear"}
# Shown when the window opens, and again when the mouse moves over it.
KEYS_HINT = "Right-click or M: menu F: fullscreen Esc: quit"
# Shown when the window opens, and again when the mouse moves over it (set in __init__, with the overlay's key).
KEYS_HINT = "Insert: Summit's overlay F: fullscreen Ctrl+Q: quit"
fill, panorama = "fit", None # Fill the screen (set from the settings in __init__)
def __init__(self, w: int, h: int, settings=None, restart_reasons=None, choices: dict | None = None,
unavailable: dict | None = None, overlay_of=None, hdr: bool = False, hdr_peak: float = 1000.0,
window_keys: dict | None = None, clean_source: bool = False) -> None:
window_keys: dict | None = None, clean_source: bool = False, overlay_key: str | None = None) -> None:
import glfw
from OpenGL import GL
from .menu import Menu
from .overlaykey import glfw_key, pick
from .settings import Settings
self.settings = st = settings if settings is not None else Settings()
@@ -808,7 +692,7 @@ class GLWindowSink:
self.mode = self.modes[0]
details = {"fsr": f" (sharpness {sharpness:g})", "vsr": f" (quality {vsr_quality})", "bilinear": ""}
print(f"[display] upscaling with {self._name(self.mode)}{details[self.mode]}; u cycles "
+ " / ".join(self._name(m) for m in self.modes) + "; m opens the settings menu")
+ " / ".join(self._name(m) for m in self.modes))
self.timer = GpuTimer(GL) # GPU time of the scale/draw step, reported on close
# Looks: which one is on (the settings, or the launcher's Looks page while it edits one) and its drawing.
@@ -829,15 +713,28 @@ class GLWindowSink:
self.choices, self.unavailable = dict(choices or {}), dict(unavailable or {})
self.note_presentation()
self.menu = Menu(st, allowed=self.allowed, disabled=self.disabled, restart_reasons=restart_reasons)
self.overlay_key, note = pick(overlay_key) # the key that opens the overlay (framegen/overlaykey.py)
if note:
print(f"[display] {note}")
self._toggle = glfw_key(self.overlay_key, glfw)
self.KEYS_HINT = f"{self.overlay_key.name}: Summit's overlay F: fullscreen Ctrl+Q: quit"
over_game = overlay_of is not None
self.menu = Menu(st, allowed=self.allowed, disabled=self.disabled, restart_reasons=restart_reasons,
title=os.environ.get("SUMMIT_GAME", ""), toggle_key=self.overlay_key.name,
quit_label="Stop Summit" if over_game else "Quit",
quit_help=("Takes Summit's picture off the game. A game added to Summit by hand closes with "
"it; a Steam game keeps running, as it looks without Summit." if over_game else
"Closes the video window and stops playing."), window_keys=not over_game)
self.menu_panel, self.toast_panel = _Panel(GL, self.hdr10), _Panel(GL, self.hdr10)
self.mini_panel, self._mini_state = _Panel(GL, self.hdr10), None
self.wm_panel, self._wm_state = _Panel(GL, self.hdr10), None # the Summit watermark
self._frametimes, self._last_write, self._graph_drawn, self._gpu = collections.deque(maxlen=480), 0.0, 0.0, None
self._menu_top = None # (GL y of the menu's top, the picture's (y0, height) it was placed in) while it's open
self._menu_top = None # (GL y of the menu's top, the picture's (y0, height) it was placed in, on the left?) while open
self._menu_at = None # (x, GL y of the top) the menu was last drawn at, for the mouse
self._cursor = (0.0, 0.0) # the mouse, in window coordinates
self._menu_state = self._toast_state = None
self._status_at = 0.0 # when the overlay's header last got new numbers
self.xkeys, self._keyq, self._modal = None, queue.SimpleQueue(), False # over a game on Linux (_start_x11_keys)
self._toast_text, self._toast_until = self.KEYS_HINT, time.perf_counter() + 8.0
self._waited = -1 # wait(): the whole second the "no picture" note last said (-1: no wait going on)
self._unwatch = st.watch(self._apply)
@@ -847,6 +744,7 @@ class GLWindowSink:
self._make_overlay()
self._start_hotkeys(window_keys)
else:
print(f"[display] {self.overlay_key.name} opens Summit's overlay; Ctrl+Q quits (Esc doesn't)")
if st.fullscreen:
self._set_fullscreen(True)
self.take_focus()
@@ -971,33 +869,28 @@ class GLWindowSink:
return cx - mx, cy - (fh - top)
def _on_click(self, win, button, action, mods) -> None:
"""Mouse: right-click on the video opens the menu. In the menu, left-click is the next choice (or opens a
section, or Close/Back), right-click the one before, a click outside closes it."""
"""Mouse: right-click on the video opens the overlay. In it, a click picks a tab, a choice or an arrow (a
right-click on a row: the choice before), and a click outside closes it. Over a game (window capture) clicks
belong to the game: they come here only while the overlay is open (_sync_modal)."""
glfw = self.glfw
if action != glfw.PRESS or self.overlay_of is not None:
if action != glfw.PRESS or (self.overlay_of is not None and not self.menu.open):
return
right = button == glfw.MOUSE_BUTTON_RIGHT
if not self.menu.open:
if right:
self.menu.open = True
self._toast_until = 0.0
self._do("menu")
return
p = self._menu_xy()
inside = p is not None and 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h
if not inside:
self.menu.open = False
return
r = self.menu.click(*p, right=right)
if r == "close":
self.menu.open = False
elif r == "restart":
self.menu.open = False
self.cmd = "restart"
self._menu_result(self.menu.click(*p, right=right))
def _on_scroll(self, win, dx, dy) -> None:
"""The wheel moves the highlight in the menu (the keys' Up and Down)."""
"""The wheel moves the highlight in the overlay."""
if self.menu.open and dy:
self.menu.key("up" if dy > 0 else "down")
self.menu.scroll(dy)
def _name(self, mode: str) -> str:
if mode == "vsr":
@@ -1027,8 +920,8 @@ class GLWindowSink:
# ---- presentation ----------------------------------------------------------
def _set_icon(self, glfw) -> None:
"""SmoovPlay's logo in the title bar and on the taskbar instead of Python's: the plain SP at 16-32 px, the
full logo at 48 and 64 (framegen/assets, from docs/brand). A missing icon never stops a session."""
"""Summit's icon in the title bar and on the taskbar instead of Python's (framegen/assets, rendered from
packaging/icons/summit.svg by packaging/icons/render.sh). A missing icon never stops a session."""
try:
from pathlib import Path
images = []
@@ -1261,14 +1154,17 @@ class GLWindowSink:
x.XFlush(dpy)
def _start_hotkeys(self, picked: dict | None) -> None:
"""Window capture: the overlay never has the keys, so its own come through system-wide shortcuts
(framegen/hotkeys.py), registered for this thread, the one that draws (_events takes their messages). Says
which it got, over the picture and to the launcher ("[window-keys] ...")."""
if sys.platform != "win32": # no system-wide shortcuts off Windows yet: the keys all go to the game
self.KEYS_HINT = "Summit is enhancing this game. Close the game to stop."
self.toast(self.KEYS_HINT, 6.0)
"""Window capture: the picture over the game never has the keys, so the overlay's key is taken system-wide.
Linux: _start_x11_keys. Windows: shortcuts (framegen/hotkeys.py) registered for this thread, the one that
draws (_events takes their messages). Says what it got, over the picture and in the log."""
if sys.platform != "win32":
self._start_x11_keys()
return
from .hotkeys import Hotkeys, describe
from .overlaykey import windows
picked = dict(picked or {})
if windows(self.overlay_key):
picked.setdefault("menu", windows(self.overlay_key))
try:
self.hotkeys = Hotkeys(picked)
except Exception as e: # noqa: BLE001 - no shortcuts: the launcher's Stop and Settings page still work
@@ -1278,25 +1174,90 @@ class GLWindowSink:
print(self.hotkeys.report(), flush=True)
for name in self.hotkeys.taken:
print(f"[display] {name} is taken by another program")
if self.hotkeys.got.get("menu"):
self.menu.toggle_key = self.hotkeys.got["menu"]
self.KEYS_HINT = ("SmoovPlay's keys here (other keys go to the app):\n" + keys if keys
else "Keys go to the app: use Stop and Settings on SmoovPlay's Play page")
self.toast(self.KEYS_HINT, 12.0)
# the video window's key each menu key stands for
_HOTKEY_GLFW = {"Up": "UP", "Down": "DOWN", "Left": "LEFT", "Right": "RIGHT", "Enter": "ENTER", "Esc": "ESCAPE",
"Backspace": "BACKSPACE"}
def _start_x11_keys(self) -> None:
"""Window capture on Linux: the overlay's key (Insert, or the launcher's choice) as an X key grab, on X11 and
through XWayland (framegen/globalkeys.py X11Keys), so it works while the game has the keyboard. Nothing else
is taken from the game: its other keys, Esc included, never reach Summit. Presses arrive on the key thread
and are handed to the video loop (_events)."""
name = self.overlay_key.name
why = "" if X11 else "this session has no X11 or XWayland to take a key through"
if not why:
from .globalkeys import X11Keys
from .overlaykey import x11
keys = X11Keys({x11(self.overlay_key): lambda: self._keyq.put(("toggle", False))}, bare=True)
try:
keys.start()
why = keys.error or ("" if keys.got else f"{name} is taken by another program")
except Exception as e: # noqa: BLE001 - no key: the launcher's Stop still works
why = str(e)[:120]
if why:
keys.stop()
else:
self.xkeys = keys
if why:
print(f"[display] no key for the overlay ({why}): pick another overlay key in Summit's settings, or close "
"the game to stop")
self.KEYS_HINT = f"Summit is enhancing this game\nNo overlay here: {why}"
else:
print(f"[display] {name} opens Summit's overlay; every other key stays the game's", flush=True)
self.KEYS_HINT = f"Summit is enhancing this game\n{name} opens the overlay"
self.toast(self.KEYS_HINT, 8.0)
# an X key (its keysym name, lower case) -> what it does in the open overlay (framegen/menu.py Menu.key)
_X_NAV = {"up": "up", "down": "down", "left": "left", "right": "right", "return": "enter", "kp_enter": "enter",
"escape": "back", "backspace": "back", "tab": "next_tab", "next": "next_tab", "prior": "prev_tab"}
def _sync_modal(self) -> None:
"""Window capture on Linux: while the overlay is open the keyboard and the mouse are Summit's (the game would
otherwise act on the arrows and Enter, and clicks would go through the overlay to it); the moment it closes
they're the game's again. Called every time round the video loop: X11Keys gives the keyboard back by itself
if these calls stop coming while the overlay is open (a stall), so the game is never left without its keys."""
if self.xkeys is None:
return
on = self.menu.open
self.xkeys.set_modal(on, lambda name, shift: self._keyq.put((name, shift)))
if on != self._modal:
self._modal = on
try: # clicks: to the overlay while it's open, through to the game otherwise
self.glfw.set_window_attrib(self.win, self.glfw.MOUSE_PASSTHROUGH,
self.glfw.FALSE if on else self.glfw.TRUE)
except Exception as e: # noqa: BLE001 - the keys still work
print(f"[display] the mouse stays the game's while the overlay is open ({str(e)[:100]})")
# a Windows shortcut's key (framegen/hotkeys.py NAV) -> what it does in the open overlay
_HOTKEY_NAV = {"Up": "up", "Down": "down", "Left": "left", "Right": "right", "Enter": "enter", "Esc": "back",
"Backspace": "back", "Tab": "next_tab"}
def _events(self) -> None:
"""glfw.poll_events, after the shortcuts' messages (window capture): they come to the thread, not a window,
and GLFW would drop them. Each works as its key does in the video window's own (M, F, Q...); the menu's keys
are taken only while it's open."""
"""glfw.poll_events, after the system-wide keys' presses (window capture). Windows: the shortcuts' messages
come to the thread, not a window, and GLFW would drop them. Linux: the key thread's queue. The overlay's own
keys are taken only while it's open."""
if self.hotkeys is not None:
from .hotkeys import ACTIONS
self.hotkeys.set_nav(self.menu.open)
for what in self.hotkeys.poll():
key = self._HOTKEY_GLFW[what[4:]] if what.startswith("nav:") else ACTIONS[what][1]
self._on_key(self.win, getattr(self.glfw, "KEY_" + key), 0, self.glfw.PRESS, 0)
if not what.startswith("nav:"):
self._do(what)
elif self.menu.open:
self._menu_result(self.menu.key(self._HOTKEY_NAV[what[4:]]))
self.hotkeys.set_nav(self.menu.open)
if self.xkeys is not None:
while True:
try:
what, shift = self._keyq.get_nowait()
except queue.Empty:
break
if what == "toggle":
self._do("menu")
elif self.menu.open and what in self._X_NAV:
nav = self._X_NAV[what]
self._menu_result(self.menu.key("prev_tab" if nav == "next_tab" and shift else nav))
self._sync_modal()
self.glfw.poll_events()
def _hint_on_hover(self, r) -> None:
@@ -1404,32 +1365,31 @@ class GLWindowSink:
self._toast_text, self._toast_until = text, time.perf_counter() + seconds
_NAV = {"UP": "up", "DOWN": "down", "LEFT": "left", "RIGHT": "right", "ENTER": "enter", "KP_ENTER": "enter",
"BACKSPACE": "back", "ESCAPE": "back"} # Esc: back a page, and on the main page it closes the menu
"BACKSPACE": "back", "ESCAPE": "back", "PAGE_DOWN": "next_tab", "PAGE_UP": "prev_tab"}
def _on_key(self, win, key, scancode, action, mods) -> None:
glfw, st = self.glfw, self.settings
nav = {getattr(glfw, "KEY_" + k): v for k, v in self._NAV.items()}
if action == glfw.REPEAT and not (self.menu.open and key in nav):
return
if action not in (glfw.PRESS, glfw.REPEAT):
return
self._keyed = True # the player has pressed a key here
if self.menu.open and key in nav:
r = self.menu.key(nav[key])
if r == "close":
self.menu.open = False
elif r == "restart":
self.menu.open = False
self.cmd = "restart"
return
if key in (glfw.KEY_M, glfw.KEY_TAB):
def _menu_result(self, r: str | None) -> None:
"""What a key or a click in the overlay asked for (Menu.key, Menu.click)."""
if r == "close":
self.menu.open = False
elif r in ("restart", "quit"):
self.menu.open = False
self.cmd = r
elif r == "save_replay":
self.cmd = r
def _do(self, action: str) -> None:
"""What the keys do, by name: the window's own (_on_key) and the system-wide ones over a game (_events)."""
st = self.settings
if action == "menu":
self.menu.open = not self.menu.open
self._toast_until = 0.0
elif key in (glfw.KEY_Q, glfw.KEY_ESCAPE):
elif action == "quit":
self.cmd = "quit"
elif key == glfw.KEY_I:
elif action == "fullscreen":
st.set("fullscreen", not st.fullscreen)
elif action == "smooth":
st.override("interp", not st.interp) # a quick A/B, not saved
elif key == glfw.KEY_S: # Off, Minimal, Detailed, Off...
elif action == "stats": # Off, Minimal, Detailed, Graphs, Off...
if not st.overlay:
st.set("overlay_style", "minimal")
st.set("overlay", True)
@@ -1439,6 +1399,40 @@ class GLWindowSink:
st.set("overlay_style", "graphs")
else:
st.set("overlay", False)
def _on_key(self, win, key, scancode, action, mods) -> None:
"""The video window's own keys (it has the keyboard: Remote Play, a capture card, a file). Over a game the
keys are the game's and none come here."""
glfw, st = self.glfw, self.settings
nav = {getattr(glfw, "KEY_" + k): v for k, v in self._NAV.items()}
in_menu = self.menu.open and (key in nav or key == glfw.KEY_TAB)
if action == glfw.REPEAT and not in_menu:
return
if action not in (glfw.PRESS, glfw.REPEAT):
return
self._keyed = True # the player has pressed a key here
held = mods & (glfw.MOD_CONTROL | glfw.MOD_ALT | glfw.MOD_SHIFT | glfw.MOD_SUPER)
if (key, held) == self._toggle:
if action == glfw.PRESS:
self._do("menu")
return
if in_menu:
name = ("prev_tab" if mods & glfw.MOD_SHIFT else "next_tab") if key == glfw.KEY_TAB else nav[key]
self._menu_result(self.menu.key(name))
return
if key in (glfw.KEY_M, glfw.KEY_TAB):
self._do("menu")
elif key == glfw.KEY_ESCAPE: # never quits: say what does
self.toast(self.KEYS_HINT, 4.0)
elif key == glfw.KEY_Q:
if mods & glfw.MOD_CONTROL:
self._do("quit")
else:
self.toast("Ctrl+Q quits (or Quit in the overlay)", 3.0)
elif key == glfw.KEY_I:
self._do("smooth")
elif key == glfw.KEY_S:
self._do("stats")
elif key == glfw.KEY_U:
st.step("scaler", 1, self.allowed)
elif key == glfw.KEY_Z:
@@ -1448,7 +1442,7 @@ class GLWindowSink:
elif key == glfw.KEY_J:
self.looks.next(-1 if mods & glfw.MOD_SHIFT else 1)
elif key == glfw.KEY_F:
st.set("fullscreen", not st.fullscreen)
self._do("fullscreen")
elif key == glfw.KEY_L:
self.cmd = "delay_test" # the pipeline runs it (PS5 Remote Play only)
elif mods & glfw.MOD_CONTROL and glfw.KEY_1 <= key <= glfw.KEY_6:
@@ -1480,35 +1474,35 @@ class GLWindowSink:
return (0, 0, fw, fh) if self._panorama_on(fw, fh) else visible(dw, dh, x0, y0, fw, fh)
def _draw_ui(self, x0: int, y0: int, dw: int, dh: int) -> None:
"""Menu and messages, on top of everything else. Images are redrawn only when they change."""
"""The overlay and messages, on top of everything else. Images are redrawn only when they change."""
ui = max(0.5, dh / 1080) * self.settings.ui_scale
op = self.settings.ui_opacity
if not self.menu.open:
self._menu_top = self._menu_at = None
if self.menu.open:
else:
state = (self.menu.state(), round(ui, 3), op)
if state != self._menu_state:
from .menu import BG, ROW_SEL
self.menu_panel.update(self.menu.render(ui), [BG, ROW_SEL], op)
self.menu_panel.update_rgba(self.menu.render(ui, op))
self._menu_state = state
p = self.menu_panel
# Centred when it opens, then its top stays put (a row appearing, such as Restart now, grows it
# downwards), so the rows never move under the highlight. Inside the picture whatever happens.
# Centred top to bottom when it opens, on the side away from the stats' corner (so they stay in view
# next to it, live, while settings change), and it stays put until it closes. Inside the picture
# whatever happens.
where = (y0, dh)
if self._menu_top is None or self._menu_top[1] != where:
self._menu_top = (y0 + (dh + p.h) // 2, where)
self._menu_top = (y0 + (dh + p.h) // 2, where, self.settings.overlay_corner.endswith("right"))
top = min(y0 + dh, max(self._menu_top[0], y0 + p.h))
mx = x0 + int(32 * ui)
mx = x0 + int(32 * ui) if self._menu_top[2] else max(x0, x0 + dw - p.w - int(32 * ui))
self._menu_at = (mx, top) # where the mouse finds it (see _menu_xy)
self.menu_panel.blit(mx, top, self._target())
elif time.perf_counter() < self._toast_until:
if time.perf_counter() < self._toast_until: # a message: top middle, clear of the stats' corner
state = (self._toast_text, round(ui, 3), op)
if state != self._toast_state:
self.toast_panel.update(_pill(self._toast_text, ui), [(34, 30, 28)], op)
from .hud import toast
self.toast_panel.update_rgba(toast(self._toast_text, ui, op))
self._toast_state = state
p = self.toast_panel
m = int(16 * ui)
p.blit(x0 + dw - p.w - m, y0 + dh - m, self._target())
p.blit(x0 + max(0, (dw - p.w) // 2), y0 + dh - int(16 * ui), self._target())
def busy(self, fn, text: str):
"""Run fn() on a worker thread while the window stays responsive, showing the last frame and `text`.
@@ -1556,7 +1550,8 @@ class GLWindowSink:
n = int(w.since)
if n >= 2 and (n != self._waited or self.menu.open) and self.overlay_of is None:
self._waited = n
self.toast(f"No picture from {w.what} for {n} s. Esc quits" + (f"\n{w.why}" if w.why else ""), 1.5)
self.toast(f"No picture from {w.what} for {n} s" + (f"\n{w.why}" if w.why else "")
+ f"\n{self.overlay_key.name}: Summit's overlay Ctrl+Q: quit", 1.5)
fw, fh, s, dw, dh, x0, y0 = self._layout()
GL = self.GL
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self._target())
@@ -1646,10 +1641,13 @@ class GLWindowSink:
self.panorama.draw(screen, fw, fh, panorama_t(fw, fh, self.w, self.h))
label += " + panorama"
self.timer.end(q, f"{label} {dw}x{dh}")
if isinstance(text, MiniText) and self.menu.open and now - self._status_at >= 1.0 and text.parts:
self._status_at = now # the overlay's header: the same numbers, once a second
self.menu.status = (text.health, text.parts[0][0], " \u00b7 ".join(x for x, _ in text.parts[1:]))
if self.overlay and isinstance(text, MiniText) and getattr(text, "graph", None):
self._draw_graphs(text, ux, uy, uw, uh)
elif self.overlay and isinstance(text, MiniText):
self._draw_mini(text, ux, uy, uw, uh)
self._draw_stats(text, f"{label}, {dw}x{dh}", ux, uy, uw, uh)
elif self.overlay and text:
first, nl, rest = text.partition("\n") # the upscaler goes on the first line; a second is the test line
self._blit_text(f"{first} {label}{nl}{rest}", ux, uy + uh, s)
@@ -1737,17 +1735,21 @@ class GLWindowSink:
def _stats_ui(self, dh: int) -> float:
return max(0.5, dh / 1080) * self.settings.overlay_scale
def _draw_mini(self, text: MiniText, x0: int, y0: int, dw: int, dh: int) -> None:
"""The minimal overlay in a corner, at the screen's own size (drawn again only when it changes)."""
def _draw_stats(self, text: MiniText, picture: str, x0: int, y0: int, dw: int, dh: int) -> None:
"""The Minimal or Detailed stats in a corner, at the screen's own size (drawn again only when they change).
picture: the upscaler and the size it draws at, a row of Detailed."""
from .hud import stats
ui = self._stats_ui(dh)
state = (str(text), text.parts, text.health, round(ui, 3), self.settings.overlay_opacity)
details = (*text.details, ("Picture", picture)) if text.details is not None else ()
state = (text.parts, text.health, text.second, details, round(ui, 3), self.settings.overlay_opacity)
if state != self._mini_state:
self.mini_panel.update(_mini(text, ui), [(30, 27, 25)], self.settings.overlay_opacity)
self.mini_panel.update_rgba(stats(text, ui, self.settings.overlay_opacity, details))
self._mini_state = state
self._blit_corner(self.mini_panel, x0, y0, dw, dh, ui)
def _draw_graphs(self, text: MiniText, x0: int, y0: int, dw: int, dh: int) -> None:
"""The Graphs overlay in a corner (drawn about 30 times a second: the graphs scroll)."""
from .hud import graphs
if self._gpu is None and self.settings.graph_gpu:
from .gpustats import GpuStats
self._gpu = GpuStats()
@@ -1755,8 +1757,7 @@ class GLWindowSink:
now = time.perf_counter()
key = ("graphs", round(ui, 3), self.settings.overlay_opacity)
if now - self._graph_drawn >= 1 / 30 or self._mini_state != key:
self.mini_panel.update(_graphs(text, self._frametimes, ui, self._gpu), [GRAPH_BG, GRAPH_PLOT],
self.settings.overlay_opacity)
self.mini_panel.update_rgba(graphs(text, self._frametimes, ui, self.settings.overlay_opacity, self._gpu))
self._graph_drawn, self._mini_state = now, key
self._blit_corner(self.mini_panel, x0, y0, dw, dh, ui)
@@ -1766,7 +1767,7 @@ class GLWindowSink:
from . import watermark as wm
ui = max(0.5, dh / 1080)
if self._wm_state != round(ui, 3):
self.wm_panel.update(wm.render(ui), [wm.BG], wm.OPACITY)
self.wm_panel.update_rgba(wm.render_rgba(ui))
self._wm_state = round(ui, 3)
p = self.wm_panel
x, top = wm.place(wm.corner(self.settings.overlay_corner, bool(self.overlay)), p.w, p.h, x0, y0, dw, dh,
@@ -1856,6 +1857,9 @@ class GLWindowSink:
if self.hotkeys is not None:
self.hotkeys.close()
self.hotkeys = None
if self.xkeys is not None: # (the keyboard, if the overlay was open, goes back to the game)
self.xkeys.stop()
self.xkeys = None
self.GL.glFinish()
self.timer._collect()
private = self.vsr is not None and self.vsr.private # NVIDIA's package: its timings stay off the log
@@ -1899,7 +1903,7 @@ class GLWindowSink:
class WindowSink:
"""OpenCV window (fallback; its GDI paint costs 5-12 ms/frame, too slow for 60 Hz on Windows).
Keys: i = toggle interpolation, s = stats overlay, f = fullscreen, r/b = save the instant replay (plain or
before & after), q/Esc = quit."""
before & after), q = quit (Esc doesn't: it's a game's own key)."""
NAME = "SmoovPlay"
@@ -1917,7 +1921,7 @@ class WindowSink:
frame = _draw_text(frame, text)
cv2.imshow(self.NAME, frame)
k = cv2.waitKey(1) & 0xFF
if k in (ord("q"), 27):
if k == ord("q"):
return "quit"
if k == ord("f"):
self.full = not self.full
+490 -237
View File
@@ -1,61 +1,103 @@
"""In-video settings menu: keyboard-driven, drawn as an image that the GL window blits over the video.
"""Summit's in-game overlay: the settings panel that opens over the picture (Insert by default; the launcher's
Settings page picks the key). Drawn as an image the GL window blits over the game (framegen/ui_draw.py draws it).
Rows come from settings.SPECS, so a new setting shows up here without changes to this file. The main page has the
quick picks (Spec.quick choices that apply live: the launcher's big choices) and a row for each section (Spec.group,
as on the launcher's Settings page); Enter or Right opens a section's page, Esc or Backspace goes back. Drawing
happens only when something on the menu changes (the window caches the image), so an open menu costs nothing per
frame.
Rows come from settings.SPECS, so a new setting shows up here without changes to this file. Tabs along the top: Home
(the big choices that apply live, the performance overlay, and Restart / Save a clip / Quit), then one for each section
(Spec.group, as on the launcher's Settings page). Keys: Up and Down pick a row (Up from the first row goes to the
tabs, where Left and Right change tab), Left and Right change the value, Enter is the next value (or does the row's
action), Tab and Shift+Tab change tab, Esc or Backspace closes the overlay. Esc never closes the game or Summit's
picture: Quit is a row on Home, and asks twice. The mouse works too: click a tab, a choice or an arrow, right-click a
row for the choice before, wheel to move.
Drawing happens only when something on the overlay changes (the window caches the image), so an open overlay costs
nothing per frame.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Callable
import cv2
import numpy as np
from . import ui_draw as U
from .settings import SPECS, Settings, Spec
FONT = cv2.FONT_HERSHEY_SIMPLEX
TITLE_FONT = cv2.FONT_HERSHEY_DUPLEX
# BGR
BG = (34, 30, 28)
ROW_SEL = (70, 58, 48)
ACCENT = (40, 170, 255)
TEXT = (238, 238, 238)
MUTED = (150, 150, 150)
IMPACT = (200, 200, 200)
DIM = (95, 95, 95)
RULE = (70, 66, 62)
VISIBLE = 8 # rows shown at once; longer tabs scroll
HOME = "Home"
TAB_NAMES = {"Instant replay": "Clips", "PS5 Remote Play": "Remote Play"} # shorter, for the tab strip
# A row: ("setting", Spec), ("section", its name) or ("restart", None)
Row = tuple[str, object]
PERF = "perf" # Home's "Performance overlay": the settings "overlay" and "overlay_style" as one row
PERF_CHOICES = ("off", "minimal", "detailed", "graphs")
PERF_NAMES = {"off": "Off", "minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs"}
PERF_HELP = ("Live numbers in a corner of the picture. Minimal: frames on screen, the game's own frame rate, the delay, "
"and a dot for how well your PC keeps up. Detailed adds the AI's time per frame and the upscaler. Graphs "
"draws frametime, the pipeline's time, delay and the graphics card's load over time. Its corner, size and "
"opacity are on the Display tab.")
ACTION_HELP = {
"restart": "Restarts Summit's pipeline with the new settings. The game keeps running; it takes a few seconds.",
"clip": "Saves what you just played to your Videos folder. Ctrl+Alt+R does the same without opening this.",
}
QUIT_HELP = "Closes Summit's picture. A game started from Summit's launcher is closed with it."
@dataclass(frozen=True)
class Row:
kind: str # "setting" | "perf" | "action"
key: str # the setting's key, "perf", or the action: "restart", "clip", "quit"
label: str
spec: Spec | None = None
class Menu:
"""allowed(key, value): whether a choice can be picked now (e.g. RTX VSR when the SDK isn't installed).
disabled(key): a reason to grey out a whole row, or None. restart_reasons(): labels of settings changed
since start that need a restart. Changes go through Settings, whose watchers apply them.
disabled(key): a reason to grey out a whole row, or None. restart_reasons(): labels of settings changed since
start that need a restart. Changes go through Settings, whose watchers apply them.
page: the section shown, or None for the main page. It stays when the menu closes, so the player comes back to
where they were."""
title: the game's name, for the header. toggle_key: the key that opens and closes the overlay, as shown.
quit_label / quit_help: what the Quit row says (it differs over a game and in the video window).
window_keys: the video window has the keyboard, so its one-letter keys work (F, S, U...) and the help may name
them; over a game they're the game's, and the help leaves them out.
status: (health, main, rest), the live line in the header ("good", "118 fps", "game 60 - 21 ms"), set by the window.
tab, and each tab's highlighted row, stay when the overlay closes, so the player comes back to where they were."""
def __init__(self, settings: Settings, specs: tuple[Spec, ...] = SPECS,
allowed: Callable[[str, object], bool] | None = None,
disabled: Callable[[str], str | None] | None = None,
restart_reasons: Callable[[], list[str]] | None = None) -> None:
restart_reasons: Callable[[], list[str]] | None = None, title: str = "",
toggle_key: str = "Insert", quit_label: str = "Quit", quit_help: str = QUIT_HELP,
window_keys: bool = True) -> None:
self.settings, self.specs = settings, specs
self.allowed = allowed or (lambda k, v: True)
self.disabled = disabled or (lambda k: None)
self.restart_reasons = restart_reasons or (lambda: [])
self.open = False
self.page: str | None = None
self.title, self.toggle_key = title, toggle_key
self.quit_label, self.quit_help, self.window_keys = quit_label, quit_help, window_keys
self._open = False
self.tab: str | None = None # the section shown; None: Home
self.focus = "rows" # "rows" or "tabs": where the arrow keys are
self.index = 0
self.armed = False # Quit was picked once: once more quits
self.status: tuple[str, str, str] = ("", "", "")
self._sel: str | None = None # the highlighted row's key, and the index it was at (see _follow)
self._at = 0
self._left: dict[str, str] = {} # each section's highlighted row when the player last left it
self._size_key, self._size = None, (0, 0) # render(): the longest page and the tallest help, for these rows
self._hit: dict = {} # render()'s layout in the image's pixels, for the mouse: head_h, row_h, n, w, buttons
self._left: dict[str | None, str] = {} # each tab's highlighted row when the player last left it
self._scroll = 0
self._hover: tuple | None = None # ("tab", i), ("close",): what the mouse is over, besides rows
self._hit: dict = {} # render()'s layout in the image's pixels, for the mouse
self._drawn: tuple = (None, None) # render()'s last picture and what it showed (see there)
@property
def open(self) -> bool:
return self._open
@open.setter
def open(self, on: bool) -> None:
if on != self._open: # (what the mouse was over, and a half-asked Quit, don't outlive a visit)
self._open, self._hover, self.armed = on, None, False
# ---- what there is ---------------------------------------------------------
def sections(self) -> list[str]:
"""The sections that have a setting that applies right now, in SPECS order."""
values = self.settings.values()
@@ -65,269 +107,480 @@ class Menu:
out.append(s.group)
return out
def page_rows(self, page: str | None) -> list[Row]:
"""A page's rows: the settings that apply right now (VFG quality only while NVIDIA VFG is picked, and so on),
on the main page the quick picks and the sections, and Restart now when something needs it."""
def tabs(self) -> list[str | None]:
return [None] + self.sections()
def tab_rows(self, tab: str | None) -> list[Row]:
"""A tab's rows: the settings that apply right now (VFG quality only while NVIDIA VFG is picked, and so on).
Home: the big choices that apply live, the performance overlay, and the actions. Restart now is on every tab
while something needs it."""
values = self.settings.values()
if page is None:
rows: list[Row] = [("setting", s) for s in self.specs
if (s.quick and s.live or not s.group) and s.applies_to(values)]
rows += [("section", g) for g in self.sections()]
if tab is None:
rows = [Row("setting", s.key, s.label, s) for s in self.specs
if (s.quick and s.live or not s.group) and s.applies_to(values)]
if "overlay" in values and "overlay_style" in values:
rows.append(Row(PERF, PERF, "Performance overlay"))
else:
rows = [("setting", s) for s in self.specs if s.group == page and s.applies_to(values)]
rows = [Row("setting", s.key, s.label, s) for s in self.specs if s.group == tab and s.applies_to(values)]
if self.restart_reasons():
rows.append(("restart", None))
rows.append(Row("action", "restart", "Restart now"))
if tab is None:
if values.get("replay"):
rows.append(Row("action", "clip", "Save a clip"))
rows.append(Row("action", "quit", self.quit_label))
return rows
def rows(self) -> list[Row]:
"""The rows of the page shown (the main page, if its section has gone: nothing in it applies any more)."""
if self.page is not None and self.page not in self.sections():
self.page = None
return self.page_rows(self.page)
"""The rows of the tab shown (Home, if its section has gone: nothing in it applies any more)."""
if self.tab is not None and self.tab not in self.sections():
self.tab = None
return self.tab_rows(self.tab)
@staticmethod
def _row_key(row: Row) -> str:
kind, item = row
return item.key if kind == "setting" else f"section:{item}" if kind == "section" else kind
# ---- a row's value ---------------------------------------------------------
def choices(self, row: Row) -> tuple:
return PERF_CHOICES if row.kind == PERF else row.spec.choices if row.kind == "setting" else ()
def value(self, row: Row):
if row.kind == PERF:
return self.settings.overlay_style if self.settings.overlay else "off"
return getattr(self.settings, row.key) if row.kind == "setting" else None
def name(self, row: Row, value) -> str:
return PERF_NAMES[value] if row.kind == PERF else row.spec.name(value)
def can(self, row: Row, value) -> bool:
return row.kind == PERF or self.allowed(row.key, value)
def off(self, row: Row) -> str | None:
"""Why the row can't be changed, or None."""
return self.disabled(row.key) if row.kind == "setting" else None
def set_value(self, row: Row, value) -> None:
if row.kind == "action" or self.off(row) or value not in self.choices(row) or not self.can(row, value):
return
if row.kind == PERF:
if value == "off":
self.settings.set("overlay", False)
else:
self.settings.set("overlay_style", value)
self.settings.set("overlay", True)
else:
self.settings.set(row.key, value)
def step(self, row: Row, delta: int) -> None:
"""The next (or previous) choice that can be picked, going round."""
choices = self.choices(row)
if not choices or self.off(row):
return
i = choices.index(self.value(row))
for _ in range(len(choices)):
i = (i + delta) % len(choices)
if self.can(row, choices[i]):
self.set_value(row, choices[i])
return
# ---- moving about ----------------------------------------------------------
def _follow(self, rows: list[Row]) -> None:
"""Keeps the highlight on the same row when rows appear or go (a model or upscaler change)."""
keys = [self._row_key(r) for r in rows]
keys = [r.key for r in rows]
if self.index == self._at and self._sel in keys: # (index set from outside: that row, as given)
self.index = keys.index(self._sel)
self.index = min(self.index, len(rows) - 1)
self.index = max(0, min(self.index, len(rows) - 1))
self._sel, self._at = keys[self.index], self.index
self._scroll = max(0, min(self._scroll, len(rows) - VISIBLE))
if self.index < self._scroll:
self._scroll = self.index
elif self.index >= self._scroll + VISIBLE:
self._scroll = self.index - VISIBLE + 1
def _show(self, page: str | None) -> None:
"""Opens a section's page (on the row it was left on), or goes back to the main page (on that section)."""
if self.page is not None:
self._left[self.page] = self._sel
want = f"section:{self.page}" if page is None else self._left.get(page)
self.page = page
keys = [self._row_key(r) for r in self.rows()]
self.index = keys.index(want) if want in keys else 0
self._sel, self._at = keys[self.index], self.index
def _select(self, i: int, rows: list[Row] | None = None) -> None:
rows = self.rows() if rows is None else rows
self.index = max(0, min(i, len(rows) - 1))
self._sel, self._at = rows[self.index].key, self.index
self._follow(rows)
def show(self, tab: str | None) -> None:
"""Goes to a tab, on the row it was left on."""
if tab == self.tab:
return
self._left[self.tab] = self._sel
self.tab, self.armed, self._scroll = tab, False, 0
rows = self.rows()
keys = [r.key for r in rows]
want = self._left.get(self.tab)
self._select(keys.index(want) if want in keys else 0, rows)
def _turn(self, delta: int) -> None:
tabs = self.tabs()
self.show(tabs[(tabs.index(self.tab) + delta) % len(tabs)])
def _act(self, row: Row) -> str | None:
if row.key == "restart":
return "restart"
if row.key == "clip":
return "save_replay"
if self.armed:
self.armed = False
return "quit"
self.armed = True
return None
def key(self, name: str) -> str | None:
"""name: up / down / left / right / enter / back. Returns "close", "restart" or None."""
"""name: up / down / left / right / enter / back / next_tab / prev_tab. Returns "close", "restart", "quit",
"save_replay" or None."""
rows = self.rows()
self._follow(rows)
row = rows[self.index]
if not (name == "enter" and self.focus == "rows" and row.key == "quit"):
self.armed = False
if name == "back":
if self.page is None:
return "close"
self._show(None)
return "close"
if name in ("next_tab", "prev_tab"):
self._turn(1 if name == "next_tab" else -1)
return None
if name in ("up", "down"):
self.index = (self.index + (-1 if name == "up" else 1)) % len(rows)
self._sel, self._at = self._row_key(rows[self.index]), self.index
if self.focus == "tabs":
if name in ("left", "right"):
self._turn(-1 if name == "left" else 1)
elif name in ("down", "enter"):
self.focus = "rows"
return None
kind, item = rows[self.index]
if kind == "restart":
return "restart" if name == "enter" else None
if kind == "section":
if name in ("enter", "right"):
self._show(item)
return None
if self.disabled(item.key):
return None
if name in ("left", "right", "enter"):
self.settings.step(item.key, -1 if name == "left" else 1, self.allowed)
if name == "up":
if self.index == 0:
self.focus = "tabs"
else:
self._select(self.index - 1, rows)
elif name == "down":
self._select(self.index + 1, rows)
elif row.kind == "action":
if name == "enter":
return self._act(row)
elif name in ("left", "right", "enter"):
self.step(row, -1 if name == "left" else 1)
return None
# ---- mouse (x, y: pixels in the image render() made, from its top-left corner)
@staticmethod
def _in(box, x: float, y: float) -> bool:
return box[0] <= x < box[2] and box[1] <= y < box[3]
def _row_at(self, x: float, y: float) -> int | None:
h = self._hit
if not h or not (0 <= x < h["w"]) or y < h["head_h"]:
if not h or not self._in(h["rows"], x, y):
return None
i = int((y - h["head_h"]) // h["row_h"])
i = self._scroll + int((y - h["rows"][1]) // h["row_h"])
return i if 0 <= i < len(self.rows()) else None
def hover(self, x: float, y: float) -> None:
"""Moving the mouse over a row highlights it."""
"""Moving the mouse over a row highlights it; over a tab or Close, lights that up."""
self._hover = None
for i, box in enumerate(self._hit.get("tabs", ())):
if self._in(box, x, y):
self._hover = ("tab", i)
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
self._hover = ("close",)
i = self._row_at(x, y)
if i is not None and i != self.index:
rows = self.rows()
self.index, self._sel, self._at = i, self._row_key(rows[i]), i
if i is not None and (i != self.index or self.focus != "rows"):
self.focus, self.armed = "rows", False
self._select(i)
def scroll(self, dy: float) -> None:
"""The wheel moves the highlight (and the list with it)."""
if dy:
self.focus, self.armed = "rows", False
self._select(self.index + (-1 if dy > 0 else 1))
def click(self, x: float, y: float, right: bool = False) -> str | None:
"""A click: the Close and Back buttons, a section (opens it), Restart now, or a setting (left: the next
choice, right: the one before). A right click in the header goes back a page. Returns \"close\", \"restart\" or None."""
for name, (x0, y0, x1, y1) in self._hit.get("buttons", {}).items():
if x0 <= x <= x1 and y0 <= y <= y1:
if name == "close":
return "close"
self._show(None)
"""A click: Close, a tab, an action row, or a setting: on one of its choices picks that one, on an arrow
steps, anywhere else on the row is the next choice (right-click: the one before). Returns as key()."""
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
return "close"
tabs = self.tabs()
for i, box in enumerate(self._hit.get("tabs", ())):
if self._in(box, x, y) and i < len(tabs):
self.show(tabs[i])
self.focus = "rows"
return None
i = self._row_at(x, y)
if i is None:
if right and self.page is not None:
self._show(None)
self.armed = False
return None
rows = self.rows()
self.index, self._sel, self._at = i, self._row_key(rows[i]), i
kind, item = rows[i]
if kind == "restart":
return None if right else "restart"
if kind == "section":
if not right:
self._show(item)
return None
if not self.disabled(item.key):
self.settings.step(item.key, -1 if right else 1, self.allowed)
self.focus = "rows"
self._select(i, rows)
row = rows[i]
if row.kind == "action":
if right:
self.armed = False
return None
if row.key != "quit":
self.armed = False
return self._act(row)
self.armed = False
for box, what, arg in self._hit.get("controls", {}).get(i, ()):
if self._in(box, x, y):
if what == "set":
self.set_value(row, arg)
else:
self.step(row, arg)
return None
self.step(row, -1 if right else 1)
return None
def _shown(self) -> tuple:
"""What the drawing depends on, but for the header's live numbers."""
return (self.tab, self.focus, self.index, self._scroll, self.armed, self._hover, self.title, self.toggle_key,
tuple(self.settings.values().items()), tuple(self.restart_reasons()),
tuple(self.disabled(s.key) for s in self.specs))
def state(self) -> tuple:
"""Everything the drawing depends on (the window redraws only when this changes)."""
return (self.page, self.index, tuple(self.settings.values().items()), tuple(self.restart_reasons()),
tuple(self.disabled(s.key) for s in self.specs))
return (self.status, self._shown())
def _section_help(self, section: str) -> str:
labels = [s.label for kind, s in self.page_rows(section) if kind == "setting"]
return "In here: " + (", ".join(labels[:-1]) + " and " + labels[-1] if len(labels) > 1 else labels[0]) + "."
# ---- drawing ---------------------------------------------------------------
def _help(self, row: Row) -> tuple[str, list[tuple[str, str]]]:
"""A row's help, and its rough effect on the picture and on speed as (name, text) pairs."""
if row.kind == "action":
return (self.quit_help if row.key == "quit" else ACTION_HELP[row.key]), []
if row.kind == PERF:
return PERF_HELP, []
why = self.off(row)
if why:
return why, []
text = row.spec.help
if not self.window_keys: # "Key: U." and the like: over a game those keys are the game's
text = re.sub(r"\s*Key: [^.]*\.", "", text)
return text, [(name, row.spec.impact[k]) for k, name in (("picture", "PICTURE"), ("speed", "SPEED"))
if row.spec.impact.get(k)]
def render(self, ui: float = 1.0) -> np.ndarray:
"""The menu as a BGR image; ui scales it (1.0 suits a 1080p-tall window)."""
def render(self, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray:
"""The overlay as an RGBA image: clear outside its rounded corners, and its background lets `1 - opacity` of
the game through (text and controls stay solid). ui scales it (1.0 suits a 1080p-tall picture)."""
def px(v: float) -> int:
return max(1, int(round(v * ui)))
w, pad, row_h, head_h = px(780), px(26), px(46), px(78)
fs, small = 0.66 * ui, 0.5 * ui
th = 1 if ui < 1.4 else 2
rows = self.rows()
self._follow(rows)
tabs = self.tabs()
W, pad = px(880), px(28)
head_h, tabs_h, row_h, help_h, foot_h = px(70), px(40), px(46), px(178), px(46)
y_tabs = head_h + px(12)
y_rows = y_tabs + tabs_h + px(12)
y_help = y_rows + VISIBLE * row_h + px(12)
y_foot = y_help + help_h + px(4)
H = y_foot + foot_h + px(4)
x0, x1 = pad - px(10), W - pad + px(10) # rows, cards and tabs reach a little past the text's margins
# Only the header's numbers change while nothing is touched (once a second): then just the header is drawn
# again, over the picture kept from last time.
key = (round(ui, 3), self._shown())
if key == self._drawn[0]:
c = self._drawn[1]
c.d.rectangle((pad - px(2), px(8), W - pad + px(4), head_h - px(4)), fill=U.BG)
self._hit["close"] = self._header(c, px, W, pad, head_h)
return c.rgba(opacity, (U.SURFACE,))
c = U.Canvas(W, H, U.BG, px(18), border=U.BORDER)
f_label, f_value = U.font(px(16), "medium"), U.font(px(15), "medium")
f_small, f_tag, f_help = U.font(px(13)), U.font(px(10), "bold"), U.font(px(14))
close = self._header(c, px, W, pad, head_h)
c.line(1, head_h, W - 2, head_h, U.BORDER, 1)
def foot(kind: str, item) -> tuple[list[str], list[str]]:
"""A row's help under the list, and under that its rough effect on the picture and on speed."""
impact: list[str] = []
if kind == "restart":
text = "Restarts the pipeline with the new settings. The stream keeps running; takes a few seconds."
elif kind == "section":
text = self._section_help(item)
# -- tabs
f_tab = U.font(px(15), "semibold")
tab_boxes, x = [], x0
for i, tab in enumerate(tabs):
name = HOME if tab is None else TAB_NAMES.get(tab, tab)
tw = U.text_w(name, f_tab)
box = (x, y_tabs, x + tw + 2 * px(15), y_tabs + tabs_h)
active, hover = tab == self.tab, self._hover == ("tab", i)
if active and self.focus == "tabs":
c.rrect(*box, px(10), fill=U.ACCENT)
col = U.ON_ACCENT
elif active:
c.rrect(*box, px(10), fill=U.RAISED, outline=U.BORDER)
col = U.TEXT
else:
text = self.disabled(item.key) or item.help
if not self.disabled(item.key):
for k, name in (("picture", "Picture"), ("speed", "Speed")):
if item.impact.get(k):
impact += _wrap(f"{name}: {item.impact[k]}", w - 2 * pad, small, th)[:2]
return _wrap(text, w - 2 * pad, small, th)[:4], impact
col = U.TEXT if hover else U.DIM
c.text(x + px(15), y_tabs + tabs_h // 2, name, f_tab, col)
if active and self.focus != "tabs":
c.rrect(x + px(15), box[3] - px(6), box[2] - px(15), box[3] - px(3), px(2), fill=U.ACCENT)
tab_boxes.append(box)
x = box[2] + px(4)
def foot_size(lines: tuple[list[str], list[str]]) -> int:
return (len(lines[0]) + len(lines[1])) * px(26) + (px(8) if lines[1] else 0)
help_lines, impact_lines = foot(*rows[self.index])
# The list is as long as the longest page and the help area as tall as the longest help, whatever page and row
# are shown, so the menu keeps its size and the rows stay where they are while the player goes through it.
pages = {p: self.page_rows(p) for p in [None] + self.sections()}
key = (round(ui, 3), tuple((p, tuple((self._row_key(r), self.disabled(r[1].key) if r[0] == "setting" else None)
for r in rs)) for p, rs in pages.items()))
if self._size_key != key:
self._size_key = key
self._size = (max(len(rs) for rs in pages.values()),
max(foot_size(foot(*r)) for rs in pages.values() for r in rs))
n, foot_body = self._size
foot_h = px(18) + foot_body + px(46)
if head_h + n * row_h + foot_h > px(1040): # many rows: closer together, so it fits the window
row_h = max(px(30), (px(1040) - head_h - foot_h) // n)
h = head_h + n * row_h + foot_h
img = np.full((h, w, 3), BG, np.uint8)
buttons: dict[str, tuple[int, int, int, int]] = {}
def button(name: str, label: str, right: int) -> int:
"""A clickable box in the header, ending at `right`; returns where it starts."""
tw, tht = cv2.getTextSize(label, FONT, small, th)[0]
x1, x0, y0, y1 = right, right - tw - 2 * px(12), px(20), px(60)
cv2.rectangle(img, (x0, y0), (x1, y1), ROW_SEL, -1)
cv2.rectangle(img, (x0, y0), (x1, y1), ACCENT, 1)
cv2.putText(img, label, (x0 + px(12), (y0 + y1 + tht) // 2), FONT, small, TEXT, th, cv2.LINE_AA)
buttons[name] = (x0, y0, x1, y1)
return x0
title_scale = 1.05 * ui
if self.page is None:
cv2.putText(img, "Settings", (pad, px(50)), TITLE_FONT, title_scale, TEXT, th + 1, cv2.LINE_AA)
button("close", "Close", w - pad)
else: # Settings > Smoothness
x = pad
for part, color in (("Settings > ", MUTED), (self.page, TEXT)):
cv2.putText(img, part, (x, px(50)), TITLE_FONT, title_scale, color, th + 1, cv2.LINE_AA)
x += cv2.getTextSize(part, TITLE_FONT, title_scale, th + 1)[0][0]
button("back", "< Back", button("close", "Close", w - pad) - px(10))
cv2.line(img, (pad, head_h - px(10)), (w - pad, head_h - px(10)), RULE, max(1, px(1.5)))
for i, (kind, item) in enumerate(rows):
y0 = head_h + i * row_h
base = y0 + int(row_h * 0.66)
# -- rows
controls: dict[int, list] = {}
for i in range(self._scroll, min(len(rows), self._scroll + VISIBLE)):
row, ry = rows[i], y_rows + (i - self._scroll) * row_h
mid = ry + row_h // 2
selected = i == self.index
lit = selected and self.focus == "rows"
if selected:
cv2.rectangle(img, (0, y0), (w, y0 + row_h - px(2)), ROW_SEL, -1)
cv2.rectangle(img, (0, y0), (px(6), y0 + row_h - px(2)), ACCENT, -1)
if kind == "restart":
reasons = ", ".join(self.restart_reasons())
cv2.putText(img, f"Restart now (applies: {reasons})", (pad, base), FONT, fs, ACCENT, th,
cv2.LINE_AA)
c.rrect(x0, ry + px(2), x1, ry + row_h - px(2), px(10), fill=U.RAISED if lit else U.SURFACE)
if lit:
c.rrect(x0, ry + px(12), x0 + px(4), ry + row_h - px(12), px(2), fill=U.ACCENT)
xr = x1 - px(14)
if row.kind == "action":
danger = row.key == "quit"
again = "Press Enter again to " + self.quit_label[:1].lower() + self.quit_label[1:]
label = again if danger and self.armed else row.label
colour = U.BAD if danger else U.ACCENT
c.text(pad + px(8), mid, label, f_label, colour)
if row.key == "restart":
note = "Applies: " + ", ".join(self.restart_reasons())
c.text(xr, mid, U.fit(note, f_small, px(430)), f_small, U.DIM, "rm")
elif row.key == "clip":
c.text(xr, mid, "the last " + _span(min(self.settings.replay_clip, self.settings.replay)),
f_small, U.DIM, "rm")
continue
if kind == "section":
if i and rows[i - 1][0] == "setting": # the quick picks above, the sections below
cv2.line(img, (pad, y0), (w - pad, y0), RULE, max(1, px(1.5)))
cv2.putText(img, item, (pad, base), FONT, fs, TEXT, th, cv2.LINE_AA)
_text_right(img, ">", w - pad, base, fs, ACCENT if selected else MUTED, th)
why = self.off(row)
x = pad + px(8) + c.text(pad + px(8), mid, row.label, f_label, U.FAINT if why else U.TEXT) + px(12)
spec = row.spec
for tag, on in (("EXPERIMENTAL", spec is not None and spec.experimental),
("RESTART", spec is not None and not spec.live)):
if on: # built without the hardware to test it; applies after Restart now
tw = U.text_w(tag, f_tag) + px(0.8) * (len(tag) - 1)
c.rrect(x, mid - px(9), x + tw + px(14), mid + px(9), px(9), fill=U.SURFACE, outline=U.BORDER)
c.spaced(x + px(7), mid, tag, f_tag, U.FAINT if why else U.DIM, px(0.8))
x += tw + px(20)
if why:
c.text(xr, mid, "Not available", f_value, U.FAINT, "rm")
continue
spec = item
off = self.disabled(spec.key) is not None
color = DIM if off else TEXT
cv2.putText(img, spec.label, (pad, base), FONT, fs, color, th, cv2.LINE_AA)
tag_x = pad + cv2.getTextSize(spec.label, FONT, fs, th)[0][0] + px(12)
if spec.experimental: # built without the hardware to test it (as the launcher's EXPERIMENTAL badge)
cv2.putText(img, "experimental", (tag_x, base), FONT, small * 0.9, DIM if off else ACCENT, th,
cv2.LINE_AA)
tag_x += cv2.getTextSize("experimental", FONT, small * 0.9, th)[0][0] + px(10)
if not spec.live:
cv2.putText(img, "restart", (tag_x, base), FONT, small * 0.9, DIM if off else MUTED,
th, cv2.LINE_AA)
value = "not available" if off else spec.name(getattr(self.settings, spec.key))
right = w - pad
if selected and not off:
_text_right(img, ">", right, base, fs, ACCENT, th)
right -= px(30)
vw = _text_right(img, value, right, base, fs, TEXT, th)
_text_right(img, "<", right - vw - px(14), base, fs, ACCENT, th)
else:
_text_right(img, value, right - (px(30) if not off else 0), base, fs, MUTED if not off else DIM, th)
controls[i] = self._control(c, row, xr, mid, lit, px, f_value)
y = head_h + n * row_h
cv2.line(img, (pad, y + px(4)), (w - pad, y + px(4)), RULE, max(1, px(1.5)))
y += px(18)
for line in help_lines:
y += px(26)
cv2.putText(img, line, (pad, y), FONT, small, MUTED, th, cv2.LINE_AA)
y += px(8) if impact_lines else 0
for line in impact_lines:
y += px(26)
cv2.putText(img, line, (pad, y), FONT, small, IMPACT, th, cv2.LINE_AA)
cv2.putText(img, KEYS[self.page is not None], (pad, h - px(16)), FONT, small * 0.9, DIM, th, cv2.LINE_AA)
self._hit = {"w": w, "head_h": head_h, "row_h": row_h, "buttons": buttons}
return img
n = len(rows)
if n > VISIBLE: # a scrollbar, at the right edge
top, span = y_rows + px(4), VISIBLE * row_h - px(8)
bx = W - px(9)
c.rrect(bx, top, bx + px(3), top + span, px(2), fill=U.SURFACE)
th = max(px(24), span * VISIBLE // n)
ty = top + (span - th) * self._scroll // (n - VISIBLE)
c.rrect(bx, ty, bx + px(3), ty + th, px(2), fill=U.FAINT)
# -- what the highlighted row does
row = rows[self.index]
c.rrect(x0, y_help, x1, y_help + help_h, px(12), fill=U.SURFACE, outline=U.BORDER)
hx, hy, hw = x0 + px(18), y_help + px(26), x1 - x0 - 2 * px(18)
c.text(hx, hy, row.label, U.font(px(15), "semibold"), U.TEXT)
text, impact = self._help(row)
hy += px(12)
room = 6 # lines: the help, then each effect, which gets a second line if there's room for it
lines = U.wrap(text, f_help, hw, room - len(impact))
for line in lines:
hy += px(21)
c.text(hx, hy, line, f_help, U.DIM)
room -= len(lines)
hy += px(4) if impact else 0
for k, (name, what) in enumerate(impact):
mine = U.wrap(what, f_help, hw - px(64), max(1, room - (len(impact) - 1 - k)))
room -= len(mine)
for j, line in enumerate(mine):
hy += px(21)
if j == 0:
c.spaced(hx, hy, name, f_tag, U.ACCENT, px(0.8))
c.text(hx + px(64), hy, line, f_help, U.TEXT)
# -- the keys
fy = y_foot + foot_h // 2
f_key, f_hint = U.font(px(11), "semibold"), U.font(px(12))
def cap(x: int, label: str | None, arrows: str = "", right: bool = False) -> int:
"""A key's cap ending (right) or starting at x; returns its other edge."""
w = (U.text_w(label, f_key) if label else px(26)) + px(14)
a = x - w if right else x
c.rrect(a, fy - px(11), a + w, fy + px(11), px(6), fill=U.RAISED, outline=U.BORDER)
if label:
c.text(a + w // 2, fy, label, f_key, U.TEXT, "mm")
for k, direction in enumerate(arrows):
c.chevron(a + w // 2 + (px(6) if k else -px(6)), fy, px(8),
{"u": "up", "d": "down", "l": "left", "r": "right"}[direction], U.TEXT)
return a if right else a + w
x = x0 + px(4)
for label, arrows, what in ((None, "ud", "Select"), (None, "lr", "Change"), ("Tab", "", "Section"),
("Esc", "", "Close")):
x = cap(x, label, arrows) + px(8)
x += c.text(x, fy, what, f_hint, U.DIM) + px(18)
x = x1 - px(4)
x -= c.text(x, fy, "Show / hide", f_hint, U.DIM, "rm") + px(8)
cap(x, self.toggle_key, right=True)
self._hit = {"w": W, "h": H, "rows": (x0, y_rows, x1, y_rows + VISIBLE * row_h), "row_h": row_h,
"tabs": tab_boxes, "close": close, "controls": controls}
self._drawn = (key, c)
return c.rgba(opacity, (U.SURFACE,))
def _header(self, c: U.Canvas, px, W: int, pad: int, head_h: int) -> tuple[int, int, int, int]:
"""The mark, the game's name, the live numbers and Close. Returns Close's box."""
f_label = U.font(px(16), "medium")
cy = head_h // 2 + px(2)
c.logo(pad, cy - px(14), px(28))
x = pad + px(38)
x += c.spaced(x, cy, "SUMMIT", U.font(px(15), "bold"), U.TEXT, px(2.6)) + px(14)
close = (W - pad - px(26), cy - px(14), W - pad + px(2), cy + px(14))
right = close[0] - px(14)
health, main, rest = self.status
if main:
f_main, f_rest = U.font(px(15), "semibold"), U.font(px(14))
chip_w = px(12) + px(20) + U.text_w(main, f_main) + (px(10) + U.text_w(rest, f_rest) if rest else 0) + px(14)
c.rrect(right - chip_w, cy - px(15), right, cy + px(15), px(15), fill=U.SURFACE, outline=U.BORDER)
cx = right - chip_w + px(16)
c.circle(cx, cy, px(5), U.HEALTH.get(health, U.FAINT))
cx += px(14)
cx += c.text(cx, cy, main, f_main, U.TEXT) + px(10)
c.text(cx, cy, rest, f_rest, U.DIM)
right -= chip_w + px(14)
if self.title and right - x > px(60):
c.line(x, cy - px(9), x, cy + px(9), U.BORDER, max(1, px(1.5)))
c.text(x + px(14), cy, U.fit(self.title, f_label, right - x - px(14)), f_label, U.DIM)
if self._hover == ("close",):
c.rrect(*close, px(8), fill=U.RAISED)
col = U.TEXT if self._hover == ("close",) else U.FAINT
mx, a, t = (close[0] + close[2]) // 2, px(5.5), max(2, px(2))
c.line(mx - a, cy - a, mx + a, cy + a, col, t)
c.line(mx - a, cy + a, mx + a, cy - a, col, t)
return close
def _control(self, c: U.Canvas, row: Row, xr: int, mid: int, lit: bool, px, f) -> list:
"""Draws a row's value, ending at xr: a switch for on/off, the choices side by side when they're few and
short, else the value between two arrows. Returns what a click does where: [(box, "set" | "step", arg)]."""
choices, value = self.choices(row), self.value(row)
hits: list = []
if set(choices) == {True, False}:
w, h = px(42), px(24)
on = bool(value)
box = (xr - w, mid - h // 2, xr, mid - h // 2 + h)
c.rrect(*box, h // 2, fill=U.ACCENT if on else U.HILITE)
r = h // 2 - px(3)
c.circle(xr - h // 2 if on else xr - w + h // 2, mid, r, (255, 255, 255) if on else U.DIM)
c.text(xr - w - px(12), mid, self.name(row, value), f, U.TEXT if on else U.DIM, "rm")
return [((xr - w - px(60), mid - h, xr, mid + h), "step", 1)]
names = [self.name(row, v) for v in choices]
widths = [U.text_w(n, f) + 2 * px(13) for n in names]
if len(choices) <= 4 and sum(widths) <= px(440):
h = px(30)
x = xr - sum(widths)
c.rrect(x - px(3), mid - h // 2 - px(3), xr + px(3), mid + h // 2 + px(3), px(10), fill=U.BG, outline=U.BORDER)
for v, n, w in zip(choices, names, widths):
ok = self.can(row, v)
if v == value:
c.rrect(x, mid - h // 2, x + w, mid + h // 2, px(7), fill=U.ACCENT if lit else U.HILITE)
col = U.ON_ACCENT if lit else U.TEXT
else:
col = U.DIM if ok else U.OFF
c.text(x + w // 2, mid, n, f, col, "mm")
if ok:
hits.append(((x, mid - h, x + w, mid + h), "set", v))
x += w
return hits
col = U.ACCENT if lit else U.FAINT
c.chevron(xr - px(6), mid, px(11), "right", col)
tw = c.text(xr - px(24), mid, self.name(row, value), f, U.TEXT if lit else U.DIM, "rm")
left = xr - px(24) - tw - px(18)
c.chevron(left, mid, px(11), "left", col)
return [((left - px(14), mid - px(18), left + px(14), mid + px(18)), "step", -1),
((xr - px(20), mid - px(18), xr + px(8), mid + px(18)), "step", 1)]
# The keys, at the bottom: on the main page, and on a section's page
KEYS = ("Click: next Right-click: previous Wheel: select Enter: open M: close Q: quit",
"Click: next Right-click: previous Wheel: select Esc: back M: close Q: quit")
def _text_right(img: np.ndarray, text: str, right: int, base: int, scale: float, color, th: int) -> int:
tw = cv2.getTextSize(text, FONT, scale, th)[0][0]
cv2.putText(img, text, (right - tw, base), FONT, scale, color, th, cv2.LINE_AA)
return tw
def _wrap(text: str, width: int, scale: float, th: int) -> list[str]:
lines, line = [], ""
for word in text.split():
trial = f"{line} {word}".strip()
if line and cv2.getTextSize(trial, FONT, scale, th)[0][0] > width:
lines.append(line)
line = word
else:
line = trial
return lines + ([line] if line else [])
def _span(seconds: int) -> str:
"""15 -> "15 seconds", 180 -> "3 minutes"."""
if seconds < 60:
return f"{seconds} seconds"
return "minute" if seconds == 60 else f"{seconds // 60} minutes"
+109
View File
@@ -0,0 +1,109 @@
"""The key that opens and closes Summit's overlay (framegen/menu.py): Insert unless the launcher's Settings page
(ui.toml `overlay_key`) or `run.py --overlay-key` says otherwise.
Insert Home F10 Ctrl+Shift+O Alt+F1
A key on its own is fine when it types nothing and games rarely use it (Insert, Home, End, Delete, Page Up/Down,
Pause, Scroll Lock, the F keys); a letter, digit, Space or Tab needs Ctrl, Alt or Super with it, or the game would
lose that key. Esc, Enter, Backspace and the arrows are never the overlay's key: they move about inside it, and Esc
belongs to the game.
parse() gives the key in one spelling; x11(), glfw_key() and windows() turn it into what each way of listening wants
(framegen/globalkeys.py over a game on Linux, the video window's own keys, framegen/hotkeys.py on Windows).
"""
from __future__ import annotations
from dataclasses import dataclass
DEFAULT = "Insert"
MODS = ("Ctrl", "Alt", "Shift", "Super") # in the order they're shown
_MOD_ALIASES = {"ctrl": "Ctrl", "control": "Ctrl", "alt": "Alt", "shift": "Shift", "super": "Super", "win": "Super",
"windows": "Super", "meta": "Super", "logo": "Super"}
# Keys that can be the overlay's key on their own: name -> (X keysym name, GLFW key name)
ALONE = {"Insert": ("Insert", "INSERT"), "Home": ("Home", "HOME"), "End": ("End", "END"),
"Delete": ("Delete", "DELETE"), "PageUp": ("Prior", "PAGE_UP"), "PageDown": ("Next", "PAGE_DOWN"),
"Pause": ("Pause", "PAUSE"), "ScrollLock": ("Scroll_Lock", "SCROLL_LOCK")}
ALONE |= {f"F{n}": (f"F{n}", f"F{n}") for n in range(1, 25)}
# Keys that need Ctrl, Alt or Super with them
WITH_MOD = {"Space": ("space", "SPACE"), "Tab": ("Tab", "TAB")}
WITH_MOD |= {chr(c): (chr(c).lower(), chr(c)) for c in range(ord("A"), ord("Z") + 1)}
WITH_MOD |= {str(d): (str(d), str(d)) for d in range(10)}
_KEY_ALIASES = {"ins": "Insert", "del": "Delete", "pgup": "PageUp", "pgdn": "PageDown", "pagedn": "PageDown",
"prior": "PageUp", "next": "PageDown", "break": "Pause", "scroll_lock": "ScrollLock",
"scrlk": "ScrollLock"}
NEVER = {"esc": "Esc", "escape": "Esc", "enter": "Enter", "return": "Enter", "backspace": "Backspace", "up": "Up",
"down": "Down", "left": "Left", "right": "Right"}
@dataclass(frozen=True)
class Key:
mods: tuple[str, ...] # of MODS, in that order
key: str # a name in ALONE or WITH_MOD
name: str # as shown and saved: "Insert", "Ctrl+Shift+O"
def parse(text: str) -> Key:
"""The key from its name, in any case and with or without spaces ("insert", "ctrl + shift + o"). ValueError,
saying what's wrong, for one that can't be the overlay's key."""
parts = [p.strip() for p in (text or "").split("+") if p.strip()]
if not parts:
raise ValueError("no key")
mods: list[str] = []
key = None
for p in parts:
low = p.lower()
if low in _MOD_ALIASES:
if _MOD_ALIASES[low] in mods:
raise ValueError(f"{_MOD_ALIASES[low]} twice")
mods.append(_MOD_ALIASES[low])
continue
if key is not None:
raise ValueError("more than one key besides Ctrl, Alt, Shift and Super")
if low in NEVER:
raise ValueError(f"{NEVER[low]} moves about inside the overlay (and Esc is the game's): pick another key")
low = _KEY_ALIASES.get(low, p).lower()
key = next((k for k in (*ALONE, *WITH_MOD) if k.lower() == low), None)
if key is None:
raise ValueError(f"unknown key {p!r}")
if key is None:
raise ValueError("Ctrl, Alt, Shift or Super needs a key with it")
if key in WITH_MOD and not {"Ctrl", "Alt", "Super"} & set(mods):
raise ValueError(f"{key} needs Ctrl, Alt or Super with it, or the game would lose that key")
mods_ = tuple(m for m in MODS if m in mods)
return Key(mods_, key, "+".join((*mods_, key)))
def pick(text: str | None) -> tuple[Key, str]:
"""The key to use for `text` (None or "": the default), and a note when `text` couldn't be used ("" if it
could): the default is used then, so the overlay always has a key."""
if not (text or "").strip():
return parse(DEFAULT), ""
try:
return parse(text), ""
except ValueError as e:
return parse(DEFAULT), f"the overlay key {text!r} can't be used ({e}); using {DEFAULT}"
def x11(k: Key) -> str:
"""As framegen/globalkeys.py takes it: "ctrl+shift+o", "Insert" (the key as its X keysym name)."""
sym = (ALONE.get(k.key) or WITH_MOD[k.key])[0]
return "+".join((*(m.lower() for m in k.mods), sym))
def glfw_key(k: Key, glfw) -> tuple[int, int]:
"""(GLFW's key, its modifier bits) for the video window's own key callback."""
name = (ALONE.get(k.key) or WITH_MOD[k.key])[1]
bits = {"Ctrl": glfw.MOD_CONTROL, "Alt": glfw.MOD_ALT, "Shift": glfw.MOD_SHIFT, "Super": glfw.MOD_SUPER}
mods = 0
for m in k.mods:
mods |= bits[m]
return getattr(glfw, "KEY_" + name), mods
def windows(k: Key) -> str | None:
"""As framegen/hotkeys.py writes it ("Ctrl+Alt+M", "Insert"), or None for a key it has no name for."""
from .hotkeys import KEYS
if k.key not in KEYS:
return None
return "+".join((*("Win" if m == "Super" else m for m in k.mods), k.key))
+15 -7
View File
@@ -444,13 +444,21 @@ class Pipeline:
text = f"{label} INTERP ON {rates or f'{hz} Hz'} interp {np.mean(proc) if proc else 0.0:5.1f} ms"
if hz > 60 and shown + skipped:
text += f" extra frames {100 * shown / (shown + skipped):3.0f}%"
if delay_test is not None: # the delay test, while it runs, is the second line
text += "\n" + delay_test.status()
elif note: # the game isn't at the rate that's needed: that's the second line
text += "\n" + note
elif testing:
text += "\n" + test_line()
return text
second = (delay_test.status() if delay_test is not None # the delay test, while it runs
else note or (test_line() if testing else "")) # the game isn't at the rate that's needed
if second:
text += "\n" + second
if settings is None:
return text
# Stats overlay style Detailed: the Minimal numbers, with these rows under them (the window adds the
# upscaler's). `text` stays what sinks that only print get.
details = [("Model", label), ("Frame generation", "On" if enabled else "Off")]
if enabled:
details.append(("AI frame", f"{np.mean(proc) if proc else 0.0:.1f} ms"))
if hz > 60 and shown + skipped:
details.append(("Extra frames shown", f"{100 * shown / (shown + skipped):.0f}%"))
m = mini_text(g, s, proc, shown, skipped, testing)
return MiniText.make(m.parts, m.health, second, details=details, plain=text)
def mini_text(g, s, proc, shown: int, skipped: int, testing: bool, graphs: bool = False) -> MiniText:
"""Stats overlay style Minimal: frames on screen, the game's rate (amber while it's off the rate that's
+1 -1
View File
@@ -4,7 +4,7 @@ The launcher writes one command per line to our stdin:
set <key> <json value> change a setting and save it, as if it were picked in the video window's menu
restart apply restart-only settings now (the menu's "Restart now")
quit stop, as Esc in the video window does (clips being saved are finished first)
quit stop, as Quit in the overlay does (clips being saved are finished first)
state print the current state again
look-show <look JSON> show this look (the Looks page is editing it), whatever the Look settings say
look-hide back to the Look settings' look
+1 -1
View File
@@ -236,7 +236,7 @@ GUIDES = {
"window": "Open the app you stream with (PS Remote Play, the Xbox app, Moonlight, or a browser) and start the "
"game, pick its window, then press Play. Keep the app's window on screen: SmoovPlay shows the smooth "
"picture on top of it, and the app keeps the controller and the keyboard. SmoovPlay's own keys use Ctrl+Alt "
"(Ctrl+Alt+M menu, Ctrl+Alt+F fullscreen, Ctrl+Alt+Esc quit), and can be changed on the Play page.",
"(Insert overlay, Ctrl+Alt+F fullscreen, Ctrl+Alt+Esc quit), and can be changed on the Play page.",
"tap": "For app developers: an app built to send its frames straight to SmoovPlay (docs/frame-tap.md in "
"SmoovPlay's repo). For the Xbox app, PS Remote Play, Moonlight or a browser, pick App window instead. "
"Press Play, then start the app: its smooth video opens in its own window, and the app keeps the "
+236
View File
@@ -0,0 +1,236 @@
"""Drawing for everything Summit puts over the picture: the overlay (framegen/menu.py), the performance stats and
messages (framegen/hud.py) and the watermark. Real fonts and anti-aliased rounded shapes with Pillow, handed to the
window as numpy images (it uploads them as textures and blends them over the game).
Colours are RGB and match the launcher's default theme (crates/summit-gui/ui/theme.slint, "Midnight"). Sizes are in
pixels of the image; callers scale them with the picture (`ui`, 1.0 at 1080p).
"""
from __future__ import annotations
import functools
import os
import subprocess
import sys
import numpy as np
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError as e: # pragma: no cover - a missing package, said plainly
raise RuntimeError("Summit's overlay needs the Pillow package: pip install Pillow (or run install.sh again, "
"which adds it to the engine's environment)") from e
BG = (13, 16, 23)
SURFACE = (22, 27, 37)
RAISED = (33, 40, 55)
HILITE = (52, 61, 82) # the picked choice of a row that isn't the selected one
BORDER = (44, 52, 69)
TEXT = (238, 241, 247)
DIM = (160, 169, 187)
FAINT = (104, 113, 132)
OFF = (72, 80, 98) # a choice that can't be picked
ACCENT = (255, 176, 46)
ACCENT2 = (255, 122, 61)
ON_ACCENT = (28, 19, 0)
GOOD = (74, 222, 128)
TIGHT = (250, 204, 21)
BAD = (248, 113, 113)
# how well the PC keeps up (io.MiniText.health)
HEALTH = {"good": GOOD, "tight": TIGHT, "behind": BAD, "off": FAINT, "": FAINT}
WEIGHTS = ("regular", "medium", "semibold", "bold")
SS = 4 # shapes are drawn this many times bigger, then shrunk: that's their anti-aliasing
# Looked for when fontconfig isn't there to ask (or finds nothing)
_FALLBACK_FONTS = {
"regular": ("/usr/share/fonts/noto/NotoSans-Regular.ttf", "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf", "/usr/share/fonts/liberation/LiberationSans-Regular.ttf"),
"bold": ("/usr/share/fonts/noto/NotoSans-Bold.ttf", "/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf",
"/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf", "/usr/share/fonts/liberation/LiberationSans-Bold.ttf"),
}
_WINDOWS_FONTS = {"regular": "segoeui.ttf", "medium": "seguisb.ttf", "semibold": "seguisb.ttf", "bold": "segoeuib.ttf"}
@functools.lru_cache(maxsize=None)
def font_file(weight: str = "regular") -> str | None:
"""The file of the system's sans-serif font in this weight (SUMMIT_UI_FONT names another family), or None when
none is found: Pillow's own font is used then."""
family = os.environ.get("SUMMIT_UI_FONT", "").strip()
if sys.platform == "win32":
path = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", _WINDOWS_FONTS[weight])
return path if os.path.isfile(path) else None
try:
out = subprocess.run(["fc-match", "-f", "%{file}", f"{family or 'sans-serif'}:{weight}"], capture_output=True,
text=True, timeout=3).stdout.strip()
if out and os.path.isfile(out) and out.lower().endswith((".ttf", ".otf", ".ttc")):
return out
except (OSError, subprocess.SubprocessError):
pass
heavy = "bold" if weight in ("semibold", "bold") else "regular"
return next((p for p in _FALLBACK_FONTS[heavy] if os.path.isfile(p)), None)
@functools.lru_cache(maxsize=256)
def font(size: int, weight: str = "regular"):
size = max(6, int(size))
path = font_file(weight)
if path:
try:
return ImageFont.truetype(path, size)
except OSError:
pass
return ImageFont.load_default(size)
def text_w(s: str, f) -> int:
return int(round(f.getlength(s))) if s else 0
def wrap(s: str, f, width: int, max_lines: int = 0) -> list[str]:
"""s as lines no wider than `width`; with max_lines, what doesn't fit ends in an ellipsis."""
lines, line = [], ""
for word in s.split():
trial = f"{line} {word}".strip()
if line and f.getlength(trial) > width:
lines.append(line)
line = word
else:
line = trial
if line:
lines.append(line)
if max_lines and len(lines) > max_lines:
lines = lines[:max_lines]
lines[-1] = fit(lines[-1] + " ...", f, width, force=True)
return lines
def fit(s: str, f, width: int, force: bool = False) -> str:
"""s, cut short with an ellipsis if it's wider than `width` (force: it already stands for cut text)."""
if f.getlength(s) <= width and not force:
return s
s = s.removesuffix(" ...").rstrip()
while s and f.getlength(s + "...") > width:
s = s[:-1].rstrip()
return s + "..."
@functools.lru_cache(maxsize=512)
def _rr_mask(w: int, h: int, r: int):
"""An anti-aliased rounded rectangle, as a mask."""
big = Image.new("L", (w * SS, h * SS), 0)
ImageDraw.Draw(big).rounded_rectangle((0, 0, w * SS - 1, h * SS - 1), max(0, min(r, w // 2, h // 2)) * SS, fill=255)
return big.reduce(SS)
class Canvas:
"""An opaque picture to draw a panel on. rgba() hands it over with rounded corners and a see-through
background."""
def __init__(self, w: int, h: int, bg=BG, radius: int = 0, border=None) -> None:
self.w, self.h, self.bg, self.radius = int(w), int(h), bg, int(radius)
self.img = Image.new("RGB", (self.w, self.h), bg)
self.d = ImageDraw.Draw(self.img)
if border is not None:
self.rrect(0, 0, self.w, self.h, self.radius, fill=bg, outline=border)
def rrect(self, x0: int, y0: int, x1: int, y1: int, r: int, fill=None, outline=None, width: int = 1) -> None:
"""A rounded rectangle from (x0, y0) up to, not including, (x1, y1)."""
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
w, h = x1 - x0, y1 - y0
if w <= 0 or h <= 0:
return
if outline is not None:
self.img.paste(outline, (x0, y0), _rr_mask(w, h, int(r)))
if fill is None:
fill = self.bg
x0, y0, w, h, r = x0 + width, y0 + width, w - 2 * width, h - 2 * width, r - width
if w <= 0 or h <= 0:
return
if fill is not None:
self.img.paste(fill, (x0, y0), _rr_mask(w, h, max(0, int(r))))
def circle(self, cx: int, cy: int, r: int, fill) -> None:
self.rrect(cx - r, cy - r, cx + r, cy + r, r, fill=fill)
def poly(self, points, fill) -> None:
"""An anti-aliased filled polygon; points are (x, y) pairs, fractions allowed."""
xs, ys = [p[0] for p in points], [p[1] for p in points]
x0, y0 = int(np.floor(min(xs))), int(np.floor(min(ys)))
w, h = int(np.ceil(max(xs))) - x0 + 1, int(np.ceil(max(ys))) - y0 + 1
big = Image.new("L", (w * SS, h * SS), 0)
ImageDraw.Draw(big).polygon([((x - x0) * SS, (y - y0) * SS) for x, y in points], fill=255)
self.img.paste(fill, (x0, y0), big.reduce(SS))
def chevron(self, cx: int, cy: int, size: int, direction: str, fill, weight: float = 0.3) -> None:
"""A small arrowhead (< > ^ v) centred on (cx, cy), `size` tall (or wide, for up and down)."""
a, t = size / 2, max(1.0, size * weight)
left = [(cx + a / 2, cy - a), (cx + a / 2 - t, cy - a), (cx - a / 2 - t / 2, cy), (cx + a / 2 - t, cy + a),
(cx + a / 2, cy + a), (cx - a / 2 + t / 2, cy)]
if direction == "right":
pts = [(2 * cx - x, y) for x, y in left]
elif direction == "up":
pts = [(cx + (y - cy), cy + (x - cx)) for x, y in left]
elif direction == "down":
pts = [(cx + (y - cy), cy - (x - cx)) for x, y in left]
else:
pts = left
self.poly(pts, fill)
def line(self, x0: int, y0: int, x1: int, y1: int, fill, width: int = 1) -> None:
self.d.line((x0, y0, x1, y1), fill=fill, width=width)
def text(self, x: int, y: int, s: str, f, fill=TEXT, anchor: str = "lm") -> int:
"""Draws s; anchor as Pillow's (left/middle/right + top/middle/baseline/bottom). Returns its width."""
if not s:
return 0
self.d.text((x, y), s, font=f, fill=fill, anchor=anchor)
return text_w(s, f)
def spaced(self, x: int, y: int, s: str, f, fill=TEXT, gap: float = 0.0) -> int:
"""s with extra room between its letters (a wordmark), left-middle at (x, y). Returns its width."""
x0 = x
for ch in s:
self.d.text((x, y), ch, font=f, fill=fill, anchor="lm")
x += f.getlength(ch) + gap
return int(round(x - gap - x0))
def logo(self, x: int, y: int, size: int) -> None:
"""Summit's peak mark (the launcher's LogoMark), size x size with its top-left at (x, y)."""
s = size / 24.0
at = lambda pts: [(x + px * s, y + py * s) for px, py in pts] # noqa: E731
self.poly(at([(9, 21), (16.5, 8.5), (23.5, 21)]), (150, 96, 44))
self.poly(at([(0.5, 21), (9.5, 3.5), (18.5, 21)]), ACCENT)
self.poly(at([(9.5, 3.5), (12.6, 9.6), (10.6, 8.6), (9.3, 10.6), (8, 8.8), (6.5, 9.4)]), (255, 250, 240))
def rgb(self) -> np.ndarray:
return np.asarray(self.img)
def rgba(self, opacity: float = 1.0, backgrounds=()) -> np.ndarray:
"""The picture as RGBA: outside the rounded corners it's clear, the background (and the other colours in
`backgrounds`, such as a card's) lets `1 - opacity` of the game through, and text and controls stay solid,
with the anti-aliased edges in between."""
rgb = np.asarray(self.img)
out = np.empty((self.h, self.w, 4), np.uint8)
out[..., :3] = rgb
if opacity >= 0.999:
alpha = np.full((self.h, self.w), 255, np.uint8)
else: # how far each pixel is from the nearest background colour, through small tables (fast)
steps = np.arange(256)
dist = None
for colour in (self.bg, *backgrounds):
d = None
for ch in range(3):
one = np.abs(steps - colour[ch]).astype(np.uint8)[rgb[..., ch]]
d = one if d is None else np.maximum(d, one)
dist = d if dist is None else np.minimum(dist, d)
alpha = ((opacity + (1.0 - opacity) * np.clip(steps / 60.0, 0.0, 1.0)) * 255.0).astype(np.uint8)[dist]
r = min(self.radius, self.w // 2, self.h // 2)
if r > 0: # the mask is solid but for its corners
mask = np.asarray(_rr_mask(self.w, self.h, self.radius))
for ys in (slice(0, r), slice(self.h - r, self.h)):
for xs in (slice(0, r), slice(self.w - r, self.w)):
alpha[ys, xs] = (alpha[ys, xs].astype(np.uint16) * mask[ys, xs] // 255).astype(np.uint8)
out[..., 3] = alpha
return out
+18 -8
View File
@@ -1,10 +1,11 @@
"""The Summit watermark: one small line of text in a corner of the video window (settings "watermark", on by default).
Pure drawing with OpenCV, so it is tested without a window."""
Pure drawing (framegen/ui_draw.py), so it is tested without a window."""
from __future__ import annotations
import cv2
import numpy as np
from . import ui_draw as U
TEXT = "summit - git.molberg.cloud/alex/summit"
BG = (24, 22, 20) # the box behind the text (BGR); drawn see-through by the window
FG = (235, 235, 235)
@@ -18,14 +19,23 @@ def corner(stats_corner: str, stats_on: bool = True) -> str:
return "bottom-right" if stats_on and stats_corner == "bottom-left" else "bottom-left"
def _canvas(ui: float, text: str) -> U.Canvas:
f = U.font(max(9, round(12 * max(ui, 0.6))))
padx, pady = max(4, int(8 * ui)), max(3, int(5 * ui))
asc, desc = f.getmetrics()
c = U.Canvas(U.text_w(text, f) + 2 * padx, asc + desc + 2 * pady, BG[::-1], radius=max(3, int(6 * ui)))
c.text(padx, pady + asc, text, f, FG[::-1], "ls")
return c
def render(ui: float = 1.0, text: str = TEXT) -> np.ndarray:
"""The watermark as a small BGR image; ui scales it with the picture (1.0 at 1080p)."""
fs = 0.42 * max(ui, 0.6)
(tw, th), base = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, fs, 1)
padx, pady = max(4, int(8 * ui)), max(3, int(5 * ui))
img = np.full((th + base + 2 * pady, tw + 2 * padx, 3), BG, np.uint8)
cv2.putText(img, text, (padx, pady + th), cv2.FONT_HERSHEY_SIMPLEX, fs, FG, 1, cv2.LINE_AA)
return img
return np.ascontiguousarray(_canvas(ui, text).rgb()[..., ::-1])
def render_rgba(ui: float = 1.0, text: str = TEXT) -> np.ndarray:
"""The same as RGBA, for the window: rounded corners, and the box lets the game show through."""
return _canvas(ui, text).rgba(OPACITY)
def place(corner_: str, pw: int, ph: int, x0: int, y0: int, dw: int, dh: int, margin: int) -> tuple[int, int]:
+2
View File
@@ -3,6 +3,8 @@
torch>=2.6
numpy
opencv-python
# The overlay, the stats and the messages over the picture: fonts and rounded shapes (framegen/ui_draw.py)
Pillow
glfw
PyOpenGL
av
+7 -3
View File
@@ -247,6 +247,10 @@ def main() -> int:
help="--source window: SmoovPlay's shortcuts while the app has the keys, as "
'"menu=Ctrl+Alt+K;quit=Ctrl+Alt+End" (actions: menu, quit, fullscreen, stats, smooth; the '
'others keep their defaults, framegen/hotkeys.py)')
ap.add_argument("--overlay-key", metavar="KEY", default=None,
help="the key that opens and closes Summit's overlay over the picture (default Insert; e.g. Home, "
"F10, Ctrl+Shift+O: framegen/overlaykey.py). Over a game it's the only key taken from the "
"game; Esc is never taken, and never quits")
ap.add_argument("--capture", metavar="NAME|N|FILE",
help="a capture card by name or number (from --list-devices), or a video file standing in for "
"one (played in real time through the capture path, to test it without a card)")
@@ -622,7 +626,7 @@ def main() -> int:
window = (WindowSink(src.w, src.h) if a.display_cv else
GLWindowSink(src.w, src.h, settings, restart_reasons, choices, unavailable,
overlay_of=src.where if kind == "window" else None, hdr=hdr10[0],
window_keys=window_keys if kind == "window" else None,
window_keys=window_keys if kind == "window" else None, overlay_key=a.overlay_key,
hdr_peak=min(hdr_peak or 1e9, 1000.0),
clean_source=kind == "capture" and bool(getattr(src, "raw", False))) if a.display else None)
if hdr10[0] and not getattr(window, "hdr10", False): # the window couldn't present HDR10: shown in SDR
@@ -642,8 +646,8 @@ def main() -> int:
src.set_hdr(hdr_out, hdr_peak if hdr10[0] else None, why=hdr_why)
sink = MultiSink(window, FileSink(a.out, src.w, src.h) if a.out else None)
if window is not None and sys.platform != "win32":
# `summit run --enhance` (or anything else) stops the engine with SIGTERM: leave as Esc does, so the window
# closes, clips finish saving and the summary is printed.
# `summit run --enhance` (or anything else) stops the engine with SIGTERM: leave as Quit in the overlay does,
# so the window closes, clips finish saving and the summary is printed.
import signal
signal.signal(signal.SIGTERM, lambda *_: setattr(window, "cmd", "quit"))
settings.watch(model_rows) # before Remote's own watcher, so what it publishes is already up to date
+53 -1
View File
@@ -17,13 +17,21 @@ from framegen import globalkeys as gk
def test_parse_and_portal_trigger():
assert gk.parse("ctrl+alt+r") == (gk.CONTROL | gk.MOD1, "r")
assert gk.parse(" Ctrl + Shift + F9 ") == (gk.CONTROL | gk.SHIFT, "f9")
assert gk.parse(" Ctrl + Shift + F9 ") == (gk.CONTROL | gk.SHIFT, "F9") # (as X names the key)
assert gk.portal_trigger("ctrl+alt+r") == "CTRL+ALT+r"
for bad in ("r", "shift+r", "ctrl+alt", "ctrl+r+t"):
with pytest.raises(ValueError):
gk.parse(bad)
def test_a_key_on_its_own_only_for_the_overlay():
assert gk.parse("Insert", bare=True) == (0, "Insert")
assert gk.parse("home", bare=True) == (0, "Home")
assert gk.parse("ctrl+pageup") == (gk.CONTROL, "Prior")
with pytest.raises(ValueError):
gk.parse("Insert")
def test_backend_follows_the_session():
assert gk.backend({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"})[0] == "x11"
assert gk.backend({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"})[0] == "portal"
@@ -112,3 +120,47 @@ def test_x11_grab_fires_on_the_key_only(xserver):
other.stop()
finally:
k.stop()
def test_the_overlays_key_and_the_keyboard_while_it_is_open(xserver, monkeypatch):
"""Insert on its own toggles; the arrows, Enter and Esc come here only while the overlay is open, and the
keyboard goes back by itself if the overlay stops asking for it."""
monkeypatch.setattr(gk, "MODAL_S", 0.8)
toggles, nav = [], []
k = gk.X11Keys({"Insert": lambda: toggles.append(1)}, display=xserver, bare=True)
k.start()
try:
assert k.error is None and k.got == ["Insert"], (k.error, k.got, k.taken)
_press(xserver, ["Insert"])
for key in ("Escape", "Up", "Return"): # closed: these are the game's
_press(xserver, [key])
time.sleep(0.5)
assert toggles == [1] and nav == [] and k.modal == ""
k.set_modal(True, lambda name, shift: nav.append((name, shift)))
time.sleep(0.3)
assert k.modal == "keyboard"
for key in ("Up", "Return", "Escape"):
_press(xserver, [key])
_press(xserver, ["Shift_L", "Tab"])
time.sleep(0.3)
k.set_modal(True, None) # still open
assert [n for n in nav if n[0] != "shift_l"] == [("up", False), ("return", False), ("escape", False), ("tab", True)]
_press(xserver, ["Insert"]) # the overlay's key still toggles while it's open
time.sleep(0.3)
assert toggles == [1, 1]
k.set_modal(False)
time.sleep(0.3)
seen = len(nav)
_press(xserver, ["Escape"])
time.sleep(0.3)
assert k.modal == "" and len(nav) == seen # closed again: Esc is the game's
k.set_modal(True, lambda name, shift: nav.append((name, shift)))
time.sleep(0.3)
assert k.modal == "keyboard"
time.sleep(1.2) # the video loop stalled: nobody asks again
assert k.modal == ""
finally:
k.stop()
+261
View File
@@ -0,0 +1,261 @@
"""Summit's overlay (framegen/menu.py), its key (framegen/overlaykey.py) and the stats and messages
(framegen/hud.py): the rules that keep it out of the game's way, checked without a window."""
import pathlib
import sys
import pytest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from framegen import hud, overlaykey as ok
from framegen.io import MiniText
from framegen.menu import PERF, VISIBLE, Menu
from framegen.settings import Settings
def menu(**kw) -> Menu:
m = Menu(Settings(), **kw)
m.open = True
return m
# ---- the key ----------------------------------------------------------------------------------------------------
def test_insert_is_the_default_and_home_works():
assert ok.DEFAULT == "Insert"
assert ok.pick(None)[0].name == "Insert" and ok.pick("")[0].name == "Insert"
assert ok.parse("home").name == "Home" and ok.parse(" f10 ").name == "F10"
assert ok.parse("shift + ctrl + o").name == "Ctrl+Shift+O"
assert ok.x11(ok.parse("Insert")) == "Insert" and ok.x11(ok.parse("PageUp")) == "Prior"
assert ok.x11(ok.parse("Ctrl+Shift+O")) == "ctrl+shift+o"
@pytest.mark.parametrize("bad", ["Esc", "escape", "Enter", "Up", "Backspace", "w", "Shift+W", "1", "Space", "Tab",
"Ctrl", "Ctrl+A+B", "Nope", "Ctrl+Ctrl+A"])
def test_keys_a_game_needs_are_refused(bad):
with pytest.raises(ValueError):
ok.parse(bad)
key, note = ok.pick(bad) # the overlay still gets a key, and the log says why it isn't the one asked for
assert key.name == "Insert" and bad in note
def test_the_key_in_each_listeners_terms():
class Glfw:
MOD_CONTROL, MOD_ALT, MOD_SHIFT, MOD_SUPER = 2, 4, 1, 8
KEY_INSERT, KEY_O, KEY_PAGE_DOWN = 260, 79, 267
assert ok.glfw_key(ok.parse("Insert"), Glfw) == (260, 0)
assert ok.glfw_key(ok.parse("Ctrl+Shift+O"), Glfw) == (79, 3)
assert ok.glfw_key(ok.parse("pgdn"), Glfw) == (267, 0)
assert ok.windows(ok.parse("Insert")) == "Insert" and ok.windows(ok.parse("Super+F1")) == "Win+F1"
assert ok.windows(ok.parse("ScrollLock")) is None # (hotkeys.py has no name for it)
def test_windows_shortcuts_take_a_bare_key_for_the_overlay_only():
from framegen import hotkeys as hk
assert hk.parse("Insert", bare=True).name == "Insert"
with pytest.raises(ValueError):
hk.parse("Insert")
with pytest.raises(ValueError):
hk.parse("M", bare=True) # a letter still needs Ctrl, Alt or Win
assert hk.parse_arg("menu=Home;quit=Ctrl+Alt+End") == {"menu": "Home", "quit": "Ctrl+Alt+End"}
with pytest.raises(ValueError):
hk.parse_arg("quit=End")
assert hk.choices()["menu"][0] == "Insert"
# ---- Esc and Quit -----------------------------------------------------------------------------------------------
def test_esc_closes_the_overlay_and_nothing_else():
m = menu()
for start in ("rows", "tabs"):
m.focus = start
assert m.key("back") == "close"
m.show("Display")
assert m.key("back") == "close" # from any tab: one press, never "quit"
def test_quit_is_a_row_and_asks_twice():
m = menu(quit_label="Stop Summit")
rows = m.rows()
assert rows[-1].key == "quit" and rows[-1].label == "Stop Summit"
m.index = len(rows) - 1
assert m.key("enter") is None and m.armed
assert m.key("up") is None and not m.armed # moving away takes it back
m.key("down")
assert m.key("enter") is None and m.key("enter") == "quit"
assert all(r.key != "quit" for tab in m.sections() for r in m.tab_rows(tab)) # only on Home
# ---- moving about -----------------------------------------------------------------------------------------------
def test_home_has_the_big_choices_and_the_performance_overlay():
m = menu()
keys = [r.key for r in m.rows()]
assert keys[:3] == ["interp", "hz", "scaler"] and PERF in keys and "clip" not in keys
m.settings.override("replay", 60)
assert "clip" in [r.key for r in m.rows()]
m.index = [r.key for r in m.rows()].index("clip")
assert m.key("enter") == "save_replay"
def test_arrows_tabs_and_values():
m = menu()
assert m.tabs()[0] is None and "Smoothness" in m.tabs() and "Picture" in m.tabs()
assert m.key("right") is None and m.settings.interp is False # Left and Right change the value
m.key("left")
assert m.settings.interp is True
m.key("down")
m.key("enter")
assert m.settings.hz == 90
m.key("up")
assert m.focus == "rows" and m.index == 0
m.key("up") # from the first row: the tabs
assert m.focus == "tabs"
m.key("right")
assert m.tab == m.tabs()[1] and m.settings.interp is True # (nothing changed on the way)
m.key("left")
m.key("left")
assert m.tab == m.tabs()[-1] # round the end
m.key("down")
assert m.focus == "rows"
m.key("next_tab")
assert m.tab is None
m.key("prev_tab")
assert m.tab == m.tabs()[-1]
def test_each_tab_keeps_its_row_and_long_tabs_scroll():
m = menu()
m.show("Display")
n = len(m.rows())
assert n > VISIBLE
for _ in range(n + 3):
m.key("down")
assert m.index == n - 1 and m._scroll == n - VISIBLE # stops at the end, scrolled to it
left = m.rows()[m.index].key
m.show("Picture")
assert m.index == 0
m.show("Display")
assert m.rows()[m.index].key == left
def test_performance_overlay_row_sets_both_settings():
m = menu()
row = next(r for r in m.rows() if r.kind == PERF)
assert m.value(row) == "minimal"
m.set_value(row, "graphs")
assert m.settings.overlay is True and m.settings.overlay_style == "graphs"
m.set_value(row, "off")
assert m.settings.overlay is False and m.value(row) == "off"
m.step(row, 1)
assert m.settings.overlay is True and m.settings.overlay_style == "minimal"
def test_rows_that_cant_be_used_stay_put():
m = Menu(Settings(), allowed=lambda k, v: not (k == "scaler" and v == "vsr"),
disabled=lambda k: "Not here." if k == "hz" else None)
rows = m.rows()
hz, scaler = (next(r for r in rows if r.key == k) for k in ("hz", "scaler"))
m.step(hz, 1)
assert m.settings.hz == 60 # a greyed-out row
m.step(scaler, 1)
assert m.settings.scaler == "bilinear" # skips the choice that can't be picked
m.set_value(scaler, "vsr")
assert m.settings.scaler == "bilinear"
assert m._help(hz) == ("Not here.", [])
def test_over_a_game_the_help_names_no_one_letter_keys():
row = lambda m: next(r for r in m.tab_rows("Picture") if r.key == "scaler") # noqa: E731
video, game = Menu(Settings()), Menu(Settings(), window_keys=False)
assert "Key: U." in video._help(row(video))[0]
text = game._help(row(game))[0]
assert "Key:" not in text and text.endswith("display.")
def test_closing_forgets_a_half_asked_quit():
m = menu()
m.index = len(m.rows()) - 1
m.key("enter")
m._hover = ("tab", 2)
assert m.armed
m.open = False
m.open = True
assert not m.armed and m._hover is None
def test_restart_row_appears_when_something_needs_it():
pending = []
m = Menu(Settings(), restart_reasons=lambda: pending)
assert "restart" not in [r.key for r in m.rows()]
pending.append("Interpolation model")
keys = [r.key for r in m.rows()]
assert "restart" in keys
m.index = keys.index("restart")
assert m.key("enter") == "restart"
# ---- drawing and the mouse --------------------------------------------------------------------------------------
def test_render_is_a_rounded_see_through_panel():
m = menu(title="Voidrunner")
m.status = ("good", "118 fps", "game 60")
img = m.render(1.0, 0.8)
h, w = img.shape[:2]
assert img.shape[2] == 4 and w == 880 and 600 < h < 900
assert img[0, 0, 3] == 0 and img[-1, -1, 3] == 0 # outside the rounded corners
assert img[h // 2, 3, 3] > 0 and img[..., 3].max() == 255 # the panel, and solid text on it
assert 190 < img[h - 30, w // 2, 3] < 255 # its background lets some of the game through
assert m.render(0.5, 1.0).shape[1] == 440
assert m.render(1.0, 1.0)[h - 30, w // 2, 3] == 255
def test_only_the_header_changes_with_the_numbers():
m = menu()
m.status = ("good", "118 fps", "game 60")
a = m.render(1.0)
m.status = ("tight", "97 fps", "game 60")
b = m.render(1.0)
changed = (a != b).any(axis=2)
assert changed.any() and not changed[80:].any() # below the header: the same picture
def test_clicks_pick_tabs_choices_and_close():
m = menu()
m.render(1.0)
hit = m._hit
box = hit["tabs"][m.tabs().index("Picture")]
assert m.click(box[0] + 5, box[1] + 5) is None and m.tab == "Picture"
m.show(None)
m.render(1.0)
hz_row = [r.key for r in m.rows()].index("hz")
sets = {arg: b for b, what, arg in m._hit["controls"][hz_row] if what == "set"}
assert set(sets) == {60, 90, 120}
b = sets[120]
m.click((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
assert m.settings.hz == 120 and m.index == hz_row
row_y = m._hit["rows"][1] + m._hit["row_h"] * 0.5 # the first row, away from its switch: next, then back
m.click(m._hit["rows"][0] + 20, row_y)
assert m.settings.interp is False
m.click(m._hit["rows"][0] + 20, row_y, right=True)
assert m.settings.interp is True
c = m._hit["close"]
assert m.click(c[0] + 2, c[1] + 2) == "close"
m.hover(box[0] + 5, box[1] + 5)
assert m._hover == ("tab", m.tabs().index("Picture"))
m.scroll(-1)
assert m.index == 1
def test_stats_toast_and_graphs_draw():
parts = [("118 fps", "main"), ("game 60", "dim"), ("delay 21 ms", "dim")]
small = hud.stats(MiniText.make(parts, "good"), 1.0, 0.8)
assert small.shape[2] == 4 and small.shape[0] < 40 and small[0, 0, 3] == 0
t = MiniText.make(parts, "good", details=[("Model", "RIFE"), ("AI frame", "5.1 ms")], plain="RIFE INTERP ON")
assert str(t) == "RIFE INTERP ON" and t.details == (("Model", "RIFE"), ("AI frame", "5.1 ms"))
detailed = hud.stats(t, 1.0, 0.8, t.details)
assert detailed.shape[0] > small.shape[0]
assert hud.stats(MiniText.make(parts, "good"), 2.0).shape[1] > small.shape[1] * 1.8
g = MiniText.make(parts, "tight", graph={"hz": 120, "tick_ms": 16.7, "busy": [9.0, 12.0, 20.0], "delay": [30.0, 90.0],
"show": ["frametime", "delay"]})
two = hud.graphs(g, [8.3, 8.4, 30.0], 1.0, 0.8)
g.graph["show"] = None
assert hud.graphs(g, [8.3, 8.4, 30.0], 1.0, 0.8).shape[0] > two.shape[0] # a row more
assert hud.graphs(MiniText.make(parts, graph={"hz": 60}), [], 1.0).shape[2] == 4 # nothing measured yet
one, three = hud.toast("Saved"), hud.toast("Saved\nto a file\nsomewhere")
assert three.shape[0] > one.shape[0] and one[0, 0, 3] == 0
+92 -3
View File
@@ -16,6 +16,10 @@
# --yes, -y don't ask before sudo steps
# --force rebuild and reinstall even when the installed version is the newest
# --dry-run print what would happen, change nothing
# --with-remote-play
# also build chiaki-ng with SmoovPlay's frame tap, for PlayStation Remote Play in Summit (with
# Enhance). Arch: makepkg (packaging/chiaki-ng/PKGBUILD, about 10 minutes); other distros: prints
# how to build it with packaging/chiaki-ng/build_linux.sh
# --uninstall remove what this installer installed
# --help, -h show this message
#
@@ -36,12 +40,14 @@ SHARE_DIR="$PREFIX/share/summit"
BIN_DIR="$PREFIX/bin"
SRC_DIR="${SUMMIT_SRC_DIR:-$HOME/.cache/summit/src}"
APPS_DIR="$PREFIX/share/applications"
ICON_DIR="$PREFIX/share/icons/hicolor/64x64/apps"
ICON_BASE="$PREFIX/share/icons/hicolor"
ICON_SIZES="16 24 32 48 64 128 256 512"
ASSUME_YES=0
FORCE=0
DRY_RUN=0
UNINSTALL=0
REMOTE_PLAY=0
log() { printf '%s\n' "$*"; }
step() { printf '\n==> %s\n' "$*"; }
@@ -104,6 +110,7 @@ for arg in "$@"; do
--yes|-y) ASSUME_YES=1 ;;
--force) FORCE=1 ;;
--dry-run) DRY_RUN=1 ;;
--with-remote-play) REMOTE_PLAY=1 ;;
--uninstall) UNINSTALL=1 ;;
--help|-h) usage; exit 0 ;;
*) die "unknown flag: $arg (see --help)" ;;
@@ -416,7 +423,14 @@ install_desktop_entry() {
# The app menu entry, pointing at the installed binary by its full path (a custom SUMMIT_PREFIX is often not
# on the menu's PATH).
pkg="$1"
run_prefix install -Dm644 "$pkg/icons/summit.png" "$ICON_DIR/summit.png"
for n in $ICON_SIZES; do
run_prefix install -Dm644 "$pkg/icons/summit-$n.png" "$ICON_BASE/${n}x$n/apps/summit.png"
done
run_prefix install -Dm644 "$pkg/icons/summit.svg" "$ICON_BASE/scalable/apps/summit.svg"
# Only refresh a cache that is already there: a new one would hide icons installed later without a refresh.
if [ -f "$ICON_BASE/icon-theme.cache" ] && command -v gtk-update-icon-cache >/dev/null 2>&1; then
run_prefix gtk-update-icon-cache -q -t -f "$ICON_BASE" || true
fi
desktop_tmp="$(mktemp)"
sed "s|^Exec=summit-gui|Exec=$BIN_DIR/summit-gui|" "$pkg/summit.desktop" > "$desktop_tmp"
run_prefix install -Dm644 "$desktop_tmp" "$APPS_DIR/summit.desktop"
@@ -424,6 +438,22 @@ install_desktop_entry() {
if command -v update-desktop-database >/dev/null 2>&1; then
run_prefix update-desktop-database "$APPS_DIR" || true
fi
refresh_desktop_caches
}
# A desktop that is already running keeps the icon it loaded before (Plasma holds it in memory until it is told),
# so an updated icon would only show after logging out. Tell it now. As the user, on their session bus; a no-op
# where there is no session (ssh, a console) or no KDE.
refresh_desktop_caches() {
[ "$DRY_RUN" -eq 0 ] || return 0
[ "$(id -u)" -ne 0 ] || return 0
run_prefix touch "$ICON_BASE" || true
for k in kbuildsycoca6 kbuildsycoca5; do
if command -v "$k" >/dev/null 2>&1; then "$k" >/dev/null 2>&1 || true; break; fi
done
if [ -n "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-send >/dev/null 2>&1; then
dbus-send --session --type=signal /KIconLoader org.kde.KIconLoader.iconChanged int32:0 >/dev/null 2>&1 || true
fi
}
fetch_default_model() {
@@ -472,6 +502,55 @@ setup_engine_venv() {
fetch_default_model "$engine_dir"
}
# chiaki-ng with the frame tap on PATH: its binary carries the tap's shared-memory name.
chiaki_with_tap() {
c="$(command -v chiaki 2>/dev/null || command -v chiaki-ng 2>/dev/null || true)"
[ -n "$c" ] && grep -q 'chiaki-frametap' "$c" 2>/dev/null
}
install_remote_play() {
step "PlayStation Remote Play: chiaki-ng with SmoovPlay's frame tap"
if chiaki_with_tap; then
log " already installed: $(command -v chiaki 2>/dev/null || command -v chiaki-ng)"
return
fi
pkgsrc="$SRC_DIR/packaging/chiaki-ng"
if [ ! -f "$pkgsrc/PKGBUILD" ]; then
log " warning: $pkgsrc is missing (an older checkout?): skipping"
return
fi
case "$DISTRO_FAMILY" in
arch)
if [ "$(id -u)" -eq 0 ]; then
log " warning: makepkg does not run as root: run install.sh --with-remote-play as your own user"
return
fi
# Built in a copy, so makepkg's src/ and pkg/ stay out of the checkout. makepkg -s installs chiaki-ng's build
# dependencies with pacman (it asks for sudo itself); the package replaces a plain chiaki-ng, keeping its consoles.
build="$HOME/.cache/summit/chiaki-ng"
run mkdir -p "$build"
run cp "$pkgsrc/PKGBUILD" "$pkgsrc/apply_patch.py" "$pkgsrc/frametap.c" "$pkgsrc/frametap.h" \
"$pkgsrc/frametap_session.cpp" "$pkgsrc/frametap_session.h" "$build/"
if [ "$ASSUME_YES" -eq 0 ] && [ "$DRY_RUN" -eq 0 ]; then
ask ' build and install chiaki-ng-smoovplay now (about 10 minutes, asks for sudo)?' || { log " skipped"; return; }
fi
if [ "$DRY_RUN" -eq 1 ]; then
log " $ (cd $build && makepkg -si --needed)"
elif [ "$ASSUME_YES" -eq 1 ]; then
( cd "$build" && run makepkg -si --noconfirm --needed ) || log " warning: the chiaki-ng build failed: Remote Play is off (see the output above)"
else
( cd "$build" && run makepkg -si --needed ) || log " warning: the chiaki-ng build failed: Remote Play is off (see the output above)"
fi
;;
*)
log " no package for $DISTRO_FAMILY yet. Build it by hand, with chiaki-ng's build dependencies installed:"
log " git clone --branch v1.10.1 https://github.com/streetpea/chiaki-ng.git ~/src/chiaki-ng"
log " bash $pkgsrc/build_linux.sh ~/src/chiaki-ng ~/src/chiaki-ng-build"
log " install -Dm755 ~/src/chiaki-ng-build/gui/chiaki $SHARE_DIR/chiaki-ng/chiaki"
;;
esac
}
do_install() {
step "Plan"
log " distro family : $DISTRO_FAMILY (ID=$DISTRO_ID)"
@@ -480,6 +559,9 @@ do_install() {
detect_existing
log " will install : summit, summit-gui into $BIN_DIR"
log " engine : $SHARE_DIR/engine with its own venv"
if [ "$REMOTE_PLAY" -eq 1 ]; then
log " remote play : chiaki-ng with SmoovPlay's frame tap"
fi
if [ "$DRY_RUN" -eq 1 ]; then
log " (--dry-run: no changes will be made)"
fi
@@ -499,6 +581,9 @@ do_install() {
fi
setup_engine_venv
if [ "$REMOTE_PLAY" -eq 1 ]; then
install_remote_play
fi
step "Done"
log " summit -> $BIN_DIR/summit"
@@ -507,12 +592,16 @@ do_install() {
log " app menu -> $APPS_DIR/summit.desktop"
check_runtime_tools
log ""
if [ "$REMOTE_PLAY" -eq 0 ] && ! chiaki_with_tap; then
log " PlayStation Remote Play: run this again with --with-remote-play (builds chiaki-ng with SmoovPlay's frame tap)."
fi
log " Next: 'summit doctor' checks what Enhance needs; 'summit-gui' (or Summit in the app menu) starts the launcher."
}
do_uninstall() {
step "Uninstalling Summit"
run_prefix rm -f "$BIN_DIR/summit" "$BIN_DIR/summit-gui" "$APPS_DIR/summit.desktop" "$ICON_DIR/summit.png"
run_prefix rm -f "$BIN_DIR/summit" "$BIN_DIR/summit-gui" "$APPS_DIR/summit.desktop" "$ICON_BASE/scalable/apps/summit.svg"
for n in $ICON_SIZES; do run_prefix rm -f "$ICON_BASE/${n}x$n/apps/summit.png"; done
run_prefix rm -rf "$SHARE_DIR"
log "Left in place: $SRC_DIR (build cache), ~/.config/summit, ~/.local/share/summit (your data)"
}
+4 -1
View File
@@ -36,6 +36,9 @@ package() {
find "$pkgdir/usr/share/summit/engine" -name '__pycache__' -exec rm -rf {} +
install -Dm644 packaging/summit.desktop "$pkgdir/usr/share/applications/summit.desktop"
install -Dm644 packaging/icons/summit.png "$pkgdir/usr/share/icons/hicolor/64x64/apps/summit.png"
for n in 16 24 32 48 64 128 256 512; do
install -Dm644 "packaging/icons/summit-$n.png" "$pkgdir/usr/share/icons/hicolor/${n}x$n/apps/summit.png"
done
install -Dm644 packaging/icons/summit.svg "$pkgdir/usr/share/icons/hicolor/scalable/apps/summit.svg"
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
}
+4
View File
@@ -0,0 +1,4 @@
src/
pkg/
chiaki-ng/
*.pkg.tar.*
+46
View File
@@ -0,0 +1,46 @@
# chiaki-ng with SmoovPlay's frame tap, for Arch Linux: PlayStation Remote Play in Summit, with Enhance.
# Copied from SmoovPlay's chiaki_tap/ (https://github.com/smoovplay/smoovplay, MIT), unchanged but for these lines.
#
# cd packaging/chiaki-ng && makepkg -si (install.sh --with-remote-play does this)
#
# Builds chiaki-ng v1.10.1 (the version apply_patch.py's edits are written against) with the tap compiled in. With
# CHIAKI_FRAMETAP unset it behaves exactly like chiaki-ng; Summit (and SmoovPlay) start it with CHIAKI_FRAMETAP=1. It replaces
# the chiaki-ng package (provides/conflicts), so the controller mapping and registered consoles carry over.
#
# chiaki-ng is AGPL-3.0; the tap files are MIT (SmoovPlay). The result is a build of chiaki-ng, under its licence.
pkgname=chiaki-ng-smoovplay
_tag=v1.10.1
pkgver=1.10.1
pkgrel=1
pkgdesc="chiaki-ng (PS5 Remote Play) with SmoovPlay's frame tap, for SmoovPlay's frame generation"
arch=('x86_64')
url="https://github.com/smoovplay/smoovplay"
license=('AGPL-3.0-only' 'MIT')
depends=('qt6-base' 'qt6-declarative' 'qt6-svg' 'qt6-wayland' 'qt6-webengine' 'qt6-positioning' 'ffmpeg'
'sdl2-compat' 'opus' 'openssl' 'json-c' 'miniupnpc' 'libevent' 'hidapi' 'libplacebo' 'speexdsp' 'fftw'
'lcms2' 'libdovi' 'shaderc' 'spirv-cross' 'protobuf' 'systemd-libs' 'libevdev' 'curl')
makedepends=('cmake' 'ninja' 'git' 'python' 'python-protobuf' 'python-setuptools' 'qt6-shadertools'
'vulkan-headers' 'fast_float')
provides=('chiaki-ng')
conflicts=('chiaki-ng' 'chiaki-ng-bin' 'chiaki-ng-git')
source=("chiaki-ng::git+https://github.com/streetpea/chiaki-ng.git#tag=${_tag}"
'apply_patch.py' 'frametap.c' 'frametap.h' 'frametap_session.cpp' 'frametap_session.h')
sha256sums=('SKIP' 'SKIP' 'SKIP' 'SKIP' 'SKIP' 'SKIP') # the tap files come from this folder; the tag pins chiaki-ng
prepare() {
cd chiaki-ng
git submodule update --init --recursive --depth 1
python "${srcdir}/apply_patch.py" .
}
build() {
cmake -S chiaki-ng -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr \
-DCHIAKI_ENABLE_CLI=OFF -DCHIAKI_ENABLE_TESTS=OFF -DCHIAKI_USE_SYSTEM_CURL=ON # the bundled curl fails on OpenSSL 3.6+
cmake --build build --target chiaki
}
package() {
DESTDIR="${pkgdir}" cmake --install build --component Unspecified 2>/dev/null || DESTDIR="${pkgdir}" cmake --install build
install -Dm644 chiaki-ng/COPYING "${pkgdir}/usr/share/licenses/${pkgname}/COPYING"
}
+33
View File
@@ -0,0 +1,33 @@
# chiaki-ng with SmoovPlay's frame tap
Summit's PlayStation Remote Play runs through [chiaki-ng](https://github.com/streetpea/chiaki-ng) (AGPL-3.0), with
the small **frame tap** from [SmoovPlay](https://github.com/smoovplay/smoovplay) (`chiaki_tap/`, MIT) built in. The
tap copies every compressed video frame the console sends into shared memory (`/dev/shm/chiaki-frametap`, plus a
sound ring), where Summit's engine (`engine/framegen/chiaki_tap.py`) decodes it and adds frame generation and the
upscaler. chiaki-ng keeps doing everything else: linking the console, the controller, the sound, recovering from
network loss. Without `CHIAKI_FRAMETAP=1` the build behaves exactly like chiaki-ng.
The files here are SmoovPlay's, copied unchanged (SmoovPlay commit 7eba484, 2026-11-19), except for the comment at
the top of the PKGBUILD.
| | |
|---|---|
| `PKGBUILD` | Arch: `makepkg -si` builds chiaki-ng v1.10.1 with the tap as `chiaki-ng-smoovplay` (provides and replaces `chiaki-ng`, so linked consoles carry over). `install.sh --with-remote-play` runs it. |
| `build_linux.sh` | other distros: `bash build_linux.sh <chiaki-ng v1.10.1 checkout> <build folder>`, with chiaki-ng's build dependencies installed (the PKGBUILD's lists, by their Arch names). Then point Summit at it: `SUMMIT_CHIAKI=<build folder>/gui/chiaki`, or copy it to `<prefix>/share/summit/chiaki-ng/chiaki`. |
| `apply_patch.py` | adds the tap to a chiaki-ng checkout (both of the above call it) |
| `frametap.c/.h`, `frametap_session.cpp/.h` | the tap |
## How Summit uses it
* **Library > + Add a game or console > PlayStation Remote Play** lists the consoles linked in chiaki-ng
(`~/.config/Chiaki/Chiaki.conf`) and whether each one answers on the network. Link a new one there with
**Link a console in chiaki-ng** (PS5: Settings > System > Remote Play > Link Device).
* **Play** finds the console by its nickname (the PlayStation discovery protocol: UDP 9302 for a PS5, 987 for a
PS4), wakes it from rest mode, and runs `chiaki --exit-app-on-stream-exit stream <nickname> <ip>`.
* **With Enhance** the engine starts first (`run.py --chiaki`). When it says it is waiting on the tap, Summit starts
chiaki-ng with `CHIAKI_FRAMETAP=1`. The engine has to see the stream start, because the codec header comes only
once. While it runs, the engine minimises chiaki-ng's window. When either one exits, Summit stops the other.
* `summit doctor` says whether chiaki-ng is there and whether it has the tap. `summit console list` shows the linked
consoles and the capture devices.
Set chiaki-ng's stream to 60 fps (the engine expects the console's 60 Hz output, repeats included), H.265, 1080p.
+120
View File
@@ -0,0 +1,120 @@
"""Add the frame tap to a chiaki-ng source checkout (tested against v1.10.1).
python chiaki_tap/apply_patch.py <chiaki-ng source folder>
Copies the tap into gui/ (frametap.c/.h: the shared memory; frametap_session.cpp/.h: what it does inside chiaki-ng's
StreamSession) and makes one-line edits to chiaki-ng's own files: six calls in gui/src/streamsession.cpp, one
friend line in gui/include/streamsession.h (the tap reaches the session's sound output and controller state), the
new files in gui/CMakeLists.txt, and one check in gui/src/qmlmainwindow.cpp (CHIAKI_FRAMETAP_RENDERER=opengl: OpenGL
for that session, which SmoovPlay asks for on AMD and Intel graphics, where chiaki-ng's Vulkan has crashed). Each
edit is an exact-text replacement that must match once, so a chiaki-ng change that moves the code fails loudly here
instead of building something subtly wrong; with one-line edits, a new chiaki-ng is quick to fix up. Running it twice is a no-op. A source patched by an older version (with the tap's
code inside streamsession.cpp) has to be restored first:
git checkout -- gui/src/streamsession.cpp gui/CMakeLists.txt
With the tap built in, chiaki-ng behaves exactly as before unless CHIAKI_FRAMETAP=1 is set. With it set, besides
copying frames out, it presses buttons when SmoovPlay's delay test asks, holds the sound back by SmoovPlay's
picture delay when SmoovPlay asks (both through the shared memory; see frametap.h), and copies the game's sound as
it arrives into a second ring, for SmoovPlay's instant replay.
"""
import shutil
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
MARK = "FrameTapSession::" # this version's edits are in
OLD_MARK = "frametap" # an older version's are (its code was inside streamsession.cpp)
FILES = {"frametap.h": "include", "frametap_session.h": "include", "frametap.c": "src", "frametap_session.cpp": "src"}
EDITS = [
("#include <streamsession.h>\n",
"#include <streamsession.h>\n#include <frametap_session.h>\n"),
# Stream start: the tap sets its own video callback (copy out, then chiaki-ng's decoder), or chiaki-ng's as before.
("\t\tchiaki_session_set_video_sample_cb(&session, chiaki_ffmpeg_decoder_video_sample_cb, ffmpeg_decoder);\n",
"\t\tif(!FrameTapSession::Begin(this, &session, chiaki_connect_info.video_profile))\n"
"\t\t\tchiaki_session_set_video_sample_cb(&session, chiaki_ffmpeg_decoder_video_sample_cb, ffmpeg_decoder);\n"),
("\tchiaki_session_fini(&session);\n\tchiaki_opus_decoder_fini(&opus_decoder);\n",
"\tchiaki_session_fini(&session);\n\tFrameTapSession::End();\n\tchiaki_opus_decoder_fini(&opus_decoder);\n"),
# Sound: SmoovPlay can ask for it to be held back to meet its picture.
("\taudio_out_sample_size = sizeof(int16_t) * channels;\n",
"\taudio_out_sample_size = sizeof(int16_t) * channels;\n\tFrameTapSession::AudioFormat(rate, audio_out_sample_size);\n"),
("queue_audio:\n\tQueueAudioOutData(buf);\n",
"queue_audio:\n\tFrameTapSession::QueueAudio(this, buf);\n"),
# Instant replay: the game's sound as it arrives, before chiaki-ng's volume (so a quiet chiaki-ng still records).
("void StreamSession::PushAudioFrame(int16_t *og_buf, size_t samples_count)\n{\n",
"void StreamSession::PushAudioFrame(int16_t *og_buf, size_t samples_count)\n{\n"
"\tFrameTapSession::PushAudio(this, og_buf, samples_count);\n"),
]
HEADER_EDIT = ("\tfriend class StreamSessionPrivate;\n",
"\tfriend class StreamSessionPrivate;\n\tfriend class FrameTapSession;\n")
# SmoovPlay draws the stream itself, and asks for OpenGL on cards where chiaki-ng's Vulkan has crashed: this session
# only (chiaki-ng's own test switch below it shows a dialog; the saved setting, shared with a standalone chiaki-ng,
# stays as it is).
RENDERER_EDIT = (
' if (render_backend == RenderBackend::Vulkan) {\n'
' if (qEnvironmentVariableIsSet("CHIAKI_FORCE_VULKAN_FALLBACK")) {\n',
' if (render_backend == RenderBackend::Vulkan) {\n'
' if (qEnvironmentVariable("CHIAKI_FRAMETAP_RENDERER") == QLatin1String("opengl")) {\n'
' // SmoovPlay, which draws the stream itself, asks for OpenGL on cards where Vulkan has crashed: this '
'session only, no dialog\n'
' fallbackToOpenGL(QStringLiteral("SmoovPlay asked for OpenGL (CHIAKI_FRAMETAP_RENDERER)"));\n'
' pending_renderer_fallback_reason.clear();\n'
' goto renderer_backend_ready;\n'
' }\n'
' if (qEnvironmentVariableIsSet("CHIAKI_FORCE_VULKAN_FALLBACK")) {\n')
CMAKE_EDIT = ("\tsrc/streamsession.cpp\n",
"\tsrc/streamsession.cpp\n\tinclude/frametap.h\n\tsrc/frametap.c\n"
"\tinclude/frametap_session.h\n\tsrc/frametap_session.cpp\n")
def replace_once(text: str, old: str, new: str, where: str) -> str:
n = text.count(old)
if n != 1:
sys.exit(f"{where}: expected the anchor exactly once, found {n}:\n{old}")
return text.replace(old, new)
def patch_file(path: Path, edits: list[tuple[str, str]], done_marker: str) -> None:
with open(path, encoding="utf-8", newline="") as f:
text = f.read()
if done_marker in text:
print(f"{path.name}: already patched")
return
if path.name in ("streamsession.cpp", "CMakeLists.txt") and OLD_MARK in text:
sys.exit(f"{path.name} has an older frame tap: restore it first "
"(git checkout -- gui/src/streamsession.cpp gui/CMakeLists.txt)")
crlf = "\r\n" in text
text = text.replace("\r\n", "\n")
for old, new in edits:
text = replace_once(text, old, new, path.name)
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(text.replace("\n", "\r\n") if crlf else text)
print(f"{path.name}: patched")
def main() -> int:
root = Path(sys.argv[1])
gui = root / "gui"
session = (gui / "src" / "streamsession.cpp").read_text(encoding="utf-8")
if OLD_MARK in session and MARK not in session: # before copying anything in
sys.exit("streamsession.cpp has an older frame tap: restore it first "
"(git checkout -- gui/src/streamsession.cpp gui/CMakeLists.txt)")
for name, folder in FILES.items():
shutil.copy(HERE / name, gui / folder / name)
patch_file(gui / "src" / "streamsession.cpp", EDITS, MARK)
patch_file(gui / "include" / "streamsession.h", [HEADER_EDIT], "friend class FrameTapSession;")
patch_file(gui / "CMakeLists.txt", [CMAKE_EDIT], "src/frametap_session.cpp")
patch_file(gui / "src" / "qmlmainwindow.cpp", [RENDERER_EDIT], "CHIAKI_FRAMETAP_RENDERER")
return 0
if __name__ == "__main__":
sys.exit(main())
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
# Build chiaki-ng with the frame tap on Linux, without packaging it (on Arch, prefer `makepkg -si` with the PKGBUILD
# in this folder):
#
# bash chiaki_tap/build_linux.sh <chiaki-ng source, at v1.10.1> <build folder>
#
# Needs chiaki-ng's build dependencies (see the PKGBUILD's depends and makedepends for Arch's names). The result is
# <build folder>/gui/chiaki; start it with the tap on:
#
# CHIAKI_FRAMETAP=1 <build folder>/gui/chiaki
set -euo pipefail
SRC="${1:?usage: build_linux.sh <chiaki-ng source> <build folder>}"
OUT="${2:?usage: build_linux.sh <chiaki-ng source> <build folder>}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "=== submodules"
git -C "$SRC" submodule update --init --recursive --depth 1
echo "=== frame tap patch"
python3 "$HERE/apply_patch.py" "$SRC"
echo "=== configure + build chiaki-ng"
cmake -S "$SRC" -B "$OUT" -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCHIAKI_ENABLE_CLI=OFF -DCHIAKI_ENABLE_TESTS=OFF -DCHIAKI_USE_SYSTEM_CURL=ON # the bundled curl fails on OpenSSL 3.6+
cmake --build "$OUT" --target chiaki
echo
echo "done: CHIAKI_FRAMETAP=1 $OUT/gui/chiaki"
+387
View File
@@ -0,0 +1,387 @@
// See frametap.h.
#include "frametap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TOTAL_SIZE ((size_t)FRAMETAP_HEADER_SIZE + (size_t)FRAMETAP_SLOT_COUNT * FRAMETAP_SLOT_SIZE)
#define AUDIO_TOTAL_SIZE ((size_t)FRAMETAP_AUDIO_HEADER + (size_t)FRAMETAP_AUDIO_SLOT_COUNT * FRAMETAP_AUDIO_SLOT_SIZE)
#if defined(_WIN32) || defined(__linux__)
// ---- what differs between Windows and Linux: the shared memory, the clock, atomics and waking the reader ----------
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
static HANDLE g_map = NULL;
static HANDLE g_event = NULL;
static HANDLE g_amap = NULL;
#define XCHG32(p, v) InterlockedExchange((volatile LONG *)(p), (LONG)(v))
#define XCHG64(p, v) InterlockedExchange64((volatile LONG64 *)(p), (LONG64)(v))
#define INC32(p) InterlockedIncrement((volatile LONG *)(p))
#define CAS32(p, want, to) (InterlockedCompareExchange((volatile LONG *)(p), (LONG)(to), (LONG)(want)) == (LONG)(want))
#define BARRIER() MemoryBarrier()
static uint64_t now_ticks(void)
{
LARGE_INTEGER v;
QueryPerformanceCounter(&v);
return (uint64_t)v.QuadPart;
}
static uint64_t tick_freq(void)
{
LARGE_INTEGER f;
QueryPerformanceFrequency(&f);
return (uint64_t)f.QuadPart;
}
static void *map_shared(const char *name, size_t size, HANDLE *map)
{
// Either side may create the mapping first; CreateFileMapping opens the existing one if it's there.
*map = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
(DWORD)((uint64_t)size >> 32), (DWORD)(size & 0xffffffffu), name);
if(!*map)
return NULL;
void *base = MapViewOfFile(*map, FILE_MAP_ALL_ACCESS, 0, 0, size);
if(!base)
{
CloseHandle(*map);
*map = NULL;
}
return base;
}
#else // Linux: POSIX shared memory (/dev/shm), CLOCK_MONOTONIC, GCC atomics and a futex
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#define XCHG32(p, v) __atomic_exchange_n((volatile uint32_t *)(p), (uint32_t)(v), __ATOMIC_SEQ_CST)
#define XCHG64(p, v) __atomic_exchange_n((volatile uint64_t *)(p), (uint64_t)(v), __ATOMIC_SEQ_CST)
#define INC32(p) __atomic_add_fetch((volatile uint32_t *)(p), 1u, __ATOMIC_SEQ_CST)
static inline bool cas32(volatile uint32_t *p, uint32_t want, uint32_t to)
{
return __atomic_compare_exchange_n(p, &want, to, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
}
#define CAS32(p, want, to) cas32((volatile uint32_t *)(p), (uint32_t)(want), (uint32_t)(to))
#define BARRIER() __atomic_thread_fence(__ATOMIC_SEQ_CST)
static uint64_t now_ticks(void) // nanoseconds of CLOCK_MONOTONIC, the clock Python's time.perf_counter reads here
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec;
}
static uint64_t tick_freq(void) { return 1000000000u; }
// The Windows name as a POSIX one, as framegen/oslayer.py's shm_name does: "Local\" or "Global\" dropped, other
// slashes made dashes, with the leading "/" shm_open wants. "Local\chiaki-frametap" is /dev/shm/chiaki-frametap.
static bool posix_name(const char *name, char *out, size_t cap)
{
if(!strncmp(name, "Local\\", 6))
name += 6;
else if(!strncmp(name, "Global\\", 7))
name += 7;
size_t n = strlen(name);
if(!n || n + 2 > cap || !strcmp(name, ".") || !strcmp(name, ".."))
return false;
out[0] = '/';
for(size_t i = 0; i < n; i++)
out[i + 1] = (name[i] == '\\' || name[i] == '/') ? '-' : name[i];
out[n + 1] = '\0';
return true;
}
static void *map_shared(const char *name, size_t size, int *unused)
{
(void)unused;
char pname[256];
if(!posix_name(name, pname, sizeof(pname)))
return NULL;
int fd = shm_open(pname, O_RDWR | O_CREAT, 0600); // this user only; either side may create it first
if(fd < 0)
return NULL;
struct stat st;
if(fstat(fd, &st) != 0 || ((size_t)st.st_size < size && ftruncate(fd, (off_t)size) != 0))
{
close(fd);
return NULL;
}
void *base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
return base == MAP_FAILED ? NULL : base;
}
static int g_map = 0, g_amap = 0; // unused on Linux (map_shared's handle)
#endif
static uint8_t *g_base = NULL;
static uint8_t *g_abase = NULL; // the sound ring; NULL if it couldn't be made (the frames still flow)
static uint32_t g_arate = 48000, g_achannels = 2;
static int g_enabled = -1;
#define H32(off) ((volatile uint32_t *)(g_base + (off)))
#define H64(off) ((volatile uint64_t *)(g_base + (off)))
#define A32(off) ((volatile uint32_t *)(g_abase + (off)))
#define A64(off) ((volatile uint64_t *)(g_abase + (off)))
// Wakes the reader after a frame, or at the stream's end: Windows' named event, or on Linux a bump of the header's
// `wake` word (FRAMETAP_WAKE_OFFSET) and a futex wake on it.
static void signal_reader(void)
{
#ifdef _WIN32
if(g_event)
SetEvent(g_event);
#else
INC32(H32(FRAMETAP_WAKE_OFFSET));
syscall(SYS_futex, (uint32_t *)H32(FRAMETAP_WAKE_OFFSET), FUTEX_WAKE, 0x7fffffff, NULL, NULL, 0);
#endif
}
#ifdef _WIN32
#define FEATURE_PLATFORM 0u
#else
#define FEATURE_PLATFORM FRAMETAP_FEATURE_WAKE
#endif
// ---- the same everywhere ---------------------------------------------------------------------------------------
bool frametap_enabled(void)
{
if(g_enabled < 0)
{
const char *v = getenv("CHIAKI_FRAMETAP");
g_enabled = (v && v[0] == '1') ? 1 : 0;
}
return g_enabled == 1;
}
static bool open_shared(void)
{
if(g_base)
return true;
const char *name = getenv("CHIAKI_FRAMETAP_NAME");
if(!name || !name[0] || strlen(name) > 200)
name = FRAMETAP_NAME;
g_base = (uint8_t *)map_shared(name, TOTAL_SIZE, &g_map);
if(!g_base)
return false;
#ifdef _WIN32
char event_name[256];
snprintf(event_name, sizeof(event_name), "%s-frame", name);
g_event = CreateEventA(NULL, FALSE, FALSE, event_name); // auto-reset, one reader
#endif
char audio_name[256];
snprintf(audio_name, sizeof(audio_name), "%s" FRAMETAP_AUDIO_SUFFIX, name);
g_abase = (uint8_t *)map_shared(audio_name, AUDIO_TOTAL_SIZE, &g_amap);
return true;
}
static void audio_header(uint64_t qpc_freq)
{
if(!g_abase)
return;
XCHG32(A32(0), 0);
*A32(4) = 1;
*A32(8) = FRAMETAP_AUDIO_SLOT_COUNT;
*A32(12) = FRAMETAP_AUDIO_SLOT_SIZE;
*A32(16) = g_arate;
*A32(20) = g_achannels;
*A64(32) = qpc_freq;
XCHG64(A64(24), 0);
XCHG32(A32(0), FRAMETAP_AUDIO_MAGIC);
}
bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t max_fps)
{
if(!frametap_enabled() || !open_shared())
return false;
XCHG32(H32(0), 0); // header is being rewritten
uint64_t freq = tick_freq();
*H32(4) = FRAMETAP_VERSION;
*H32(8) = FRAMETAP_SLOT_COUNT;
*H32(12) = FRAMETAP_SLOT_SIZE;
*H32(16) = codec;
*H32(20) = width;
*H32(24) = height;
*H32(28) = max_fps;
*H64(48) = freq;
*H32(40) = 0;
*H32(64) = FRAMETAP_FEATURE_PRESS | FRAMETAP_FEATURE_AUDIO_DELAY | (g_abase ? FRAMETAP_FEATURE_AUDIO_TAP : 0u)
| FRAMETAP_FEATURE_WINDOW | FEATURE_PLATFORM;
*H32(68) = 0;
*H32(FRAMETAP_WINDOW_OFFSET) = 0;
audio_header(freq);
// The reader treats a new session as a new stream: it resets its decoder and waits for a keyframe.
XCHG64(H64(32), 0);
INC32(H32(44));
XCHG32(H32(0), FRAMETAP_MAGIC); // last: header is complete
return true;
}
void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool recovered)
{
if(!g_base || *H32(0) != FRAMETAP_MAGIC)
return;
uint64_t now = now_ticks();
uint64_t seq = *H64(32);
uint8_t *slot = g_base + FRAMETAP_HEADER_SIZE + (size_t)(seq % FRAMETAP_SLOT_COUNT) * FRAMETAP_SLOT_SIZE;
size_t cap = FRAMETAP_SLOT_SIZE - FRAMETAP_SLOT_HEADER;
uint32_t flags = 0;
if(size > cap)
{
size = cap;
flags |= 1;
}
// Mark the slot as being rewritten first, so a reader copying it sees the sequence change and retries.
*(volatile uint64_t *)(slot + 0) = UINT64_MAX;
BARRIER();
*(volatile uint64_t *)(slot + 8) = now;
*(volatile uint32_t *)(slot + 16) = (uint32_t)size;
*(volatile int32_t *)(slot + 20) = frames_lost;
*(volatile uint32_t *)(slot + 24) = recovered ? 1u : 0u;
*(volatile uint32_t *)(slot + 28) = flags;
memcpy(slot + FRAMETAP_SLOT_HEADER, buf, size);
BARRIER();
*(volatile uint64_t *)(slot + 0) = seq;
XCHG64(H64(32), seq + 1);
signal_reader();
}
bool frametap_take_idr_request(void)
{
if(!g_base)
return false;
return CAS32(H32(40), 1, 0);
}
uint32_t frametap_take_press_request(uint32_t *hold_ms)
{
if(!g_base)
return 0;
uint32_t buttons = (uint32_t)XCHG32(H32(68), 0);
if(buttons && hold_ms)
{
uint32_t h = *H32(72);
*hold_ms = h < 20 ? 20 : h > 2000 ? 2000 : h;
}
return buttons;
}
uint32_t frametap_take_window_request(void)
{
if(!g_base)
return 0;
return (uint32_t)XCHG32(H32(FRAMETAP_WINDOW_OFFSET), 0);
}
void frametap_press_sent(void)
{
if(!g_base)
return;
XCHG64(H64(80), now_ticks());
INC32(H32(76));
}
uint32_t frametap_audio_delay_ms(void)
{
if(!g_base || *H32(0) != FRAMETAP_MAGIC)
return 0;
uint32_t ms = *H32(88);
uint64_t freq = *H64(48);
if(!ms || !freq)
return 0;
if((int64_t)(now_ticks() - *H64(56)) > (int64_t)(2 * freq)) // SmoovPlay stopped
return 0;
return ms > 500 ? 500 : ms;
}
void frametap_audio_format(uint32_t rate, uint32_t channels)
{
if(!rate || !channels || channels > 8)
return;
g_arate = rate;
g_achannels = channels;
if(g_abase && *A32(0) == FRAMETAP_AUDIO_MAGIC)
{
*A32(16) = rate;
*A32(20) = channels;
}
}
void frametap_push_audio(const uint8_t *buf, size_t size)
{
if(!g_abase || *A32(0) != FRAMETAP_AUDIO_MAGIC || !buf || !size)
return;
uint64_t now = now_ticks();
uint64_t freq = *A64(32);
size_t frame_bytes = 2u * g_achannels;
size_t cap = (FRAMETAP_AUDIO_SLOT_SIZE - FRAMETAP_AUDIO_SLOT_HEADER) / frame_bytes * frame_bytes;
size_t done = 0;
while(done < size)
{
size_t n = size - done < cap ? size - done : cap;
// A chunk too big for one slot goes in several; each slot's time is when its first sample arrived.
uint64_t q = now;
if(done && freq)
q += (uint64_t)((double)(done / frame_bytes) * (double)freq / (double)g_arate);
uint64_t seq = *A64(24);
uint8_t *slot = g_abase + FRAMETAP_AUDIO_HEADER + (size_t)(seq % FRAMETAP_AUDIO_SLOT_COUNT) * FRAMETAP_AUDIO_SLOT_SIZE;
*(volatile uint64_t *)(slot + 0) = UINT64_MAX;
BARRIER();
*(volatile uint64_t *)(slot + 8) = q;
*(volatile uint32_t *)(slot + 16) = (uint32_t)n;
*(volatile uint32_t *)(slot + 20) = g_arate;
*(volatile uint32_t *)(slot + 24) = g_achannels;
memcpy(slot + FRAMETAP_AUDIO_SLOT_HEADER, buf + done, n);
BARRIER();
*(volatile uint64_t *)(slot + 0) = seq;
XCHG64(A64(24), seq + 1);
done += n;
}
}
void frametap_end(void)
{
if(!g_base)
return;
// Keep the mapping open (the reader may still hold it); just mark the stream as stopped.
XCHG32(H32(0), 0);
if(g_abase)
XCHG32(A32(0), 0);
signal_reader();
}
#else // neither Windows nor Linux: compiled in, does nothing
bool frametap_enabled(void) { return false; }
bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t max_fps)
{
(void)codec; (void)width; (void)height; (void)max_fps;
return false;
}
void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool recovered)
{
(void)buf; (void)size; (void)frames_lost; (void)recovered;
}
bool frametap_take_idr_request(void) { return false; }
uint32_t frametap_take_window_request(void) { return 0; }
uint32_t frametap_take_press_request(uint32_t *hold_ms) { (void)hold_ms; return 0; }
uint32_t frametap_audio_delay_ms(void) { return 0; }
void frametap_audio_format(uint32_t rate, uint32_t channels) { (void)rate; (void)channels; }
void frametap_push_audio(const uint8_t *buf, size_t size) { (void)buf; (void)size; }
void frametap_press_sent(void) {}
void frametap_end(void) {}
#endif
+112
View File
@@ -0,0 +1,112 @@
// Frame tap for chiaki-ng: copies every compressed video frame the PS5 sends into a shared-memory
// ring, so another process (SmoovPlay's ChiakiSource) can decode and interpolate it. A second, smaller ring
// carries the game's sound as it arrives (16-bit PCM, before chiaki-ng's own volume), for SmoovPlay's instant replay.
//
// Enabled only when the environment variable CHIAKI_FRAMETAP=1 is set; otherwise every call is a no-op.
// CHIAKI_FRAMETAP_NAME, if set, replaces the shared memory's name (tests run beside a real stream that way).
// Windows: a named file mapping + named event. Linux: POSIX shared memory (shm_open: "Local\\chiaki-frametap" is
// /dev/shm/chiaki-frametap) and a futex on the header's `wake` word; timestamps are CLOCK_MONOTONIC nanoseconds
// (qpc_freq 1e9). A no-op elsewhere.
//
// Layout (all little-endian, must match framegen/chiaki_tap.py):
// header, 4096 bytes:
// 0 u32 magic 'CFTP' 4 u32 version 8 u32 slot_count 12 u32 slot_size
// 16 u32 codec (0 H.264, 1 H.265, 2 H.265 HDR) 20 u32 width 24 u32 height
// 28 u32 max_fps 32 u64 write_seq (frames written so far; bumped after the slot is complete)
// 40 u32 idr_request (reader sets 1, writer clears it and asks the PS5 for a keyframe)
// 44 u32 session (bumped at every stream start) 48 u64 qpc_freq
// 56 u64 reader_heartbeat_qpc (reader writes it; informational)
// 64 u32 features (writer; bit 0: it presses buttons when asked, for SmoovPlay's delay test)
// 68 u32 press_buttons (reader sets a ChiakiControllerButton mask; writer clears it and presses them)
// 72 u32 press_hold_ms (reader, before press_buttons) 76 u32 press_count (writer: presses sent so far)
// 80 u64 press_qpc (writer: when the latest press went to the PS5; written before press_count goes up)
// 88 u32 audio_delay_ms (reader: hold chiaki-ng's sound back this long, to meet SmoovPlay's picture; ignored
// once the reader's heartbeat is over 2 s old, so sound comes back on time if SmoovPlay stops)
// 96 u32 wake (Linux writer: bumped after each frame and at the end, then FUTEX_WAKE on it; feature bit 4)
// 100 u32 window_request (reader: 1 minimise chiaki-ng's windows, 2 show them again; the writer clears it and
// does it, feature bit 5). On Wayland one program can't minimise another's window, so chiaki-ng does its own.
// features bit 1: it honours audio_delay_ms; bit 2: it writes the sound ring below; bit 4: it wakes the reader
// through `wake` (Linux; bit 3, variable frame timing, is for other writers: docs/frame-tap.md).
// slot i at 4096 + i * slot_size:
// 0 u64 seq 8 u64 qpc_arrival 16 u32 size 20 i32 frames_lost 24 u32 recovered
// 28 u32 flags (bit 0: frame was larger than the slot and got truncated) 64 data[size]
//
// Sound ring: its own mapping, named like the frames' with "-audio" added, so a reader or writer that predates it
// is unaffected. Same scheme as the frames: a slot's seq is set to all ones while it's rewritten.
// header, 64 bytes:
// 0 u32 magic 'CFTA' (0 while no stream) 4 u32 version 8 u32 slot_count 12 u32 slot_size
// 16 u32 rate (Hz) 20 u32 channels 24 u64 write_seq (chunks written so far) 32 u64 qpc_freq
// slot i at 64 + i * slot_size:
// 0 u64 seq 8 u64 qpc_arrival (of the chunk's first sample) 16 u32 size (bytes) 20 u32 rate
// 24 u32 channels 32 data[size]: interleaved signed 16-bit samples
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define FRAMETAP_NAME "Local\\chiaki-frametap"
#define FRAMETAP_EVENT_NAME "Local\\chiaki-frametap-frame"
#define FRAMETAP_MAGIC 0x50544643u /* 'CFTP' */
#define FRAMETAP_VERSION 1u
#define FRAMETAP_HEADER_SIZE 4096u
#define FRAMETAP_SLOT_HEADER 64u
#define FRAMETAP_SLOT_COUNT 32u
#define FRAMETAP_SLOT_SIZE (2u * 1024u * 1024u)
#define FRAMETAP_FEATURE_PRESS 1u
#define FRAMETAP_FEATURE_AUDIO_DELAY 2u
#define FRAMETAP_FEATURE_AUDIO_TAP 4u
#define FRAMETAP_FEATURE_WAKE 16u
#define FRAMETAP_FEATURE_WINDOW 32u
#define FRAMETAP_WAKE_OFFSET 96u
#define FRAMETAP_WINDOW_OFFSET 100u
#define FRAMETAP_WINDOW_MINIMIZE 1u
#define FRAMETAP_WINDOW_RESTORE 2u
#define FRAMETAP_AUDIO_SUFFIX "-audio"
#define FRAMETAP_AUDIO_MAGIC 0x41544643u /* 'CFTA' */
#define FRAMETAP_AUDIO_HEADER 64u
#define FRAMETAP_AUDIO_SLOT_HEADER 32u
#define FRAMETAP_AUDIO_SLOT_COUNT 512u
#define FRAMETAP_AUDIO_SLOT_SIZE 8192u
// True if CHIAKI_FRAMETAP=1 is set in the environment.
bool frametap_enabled(void);
// Call when a stream session starts. Creates the shared memory on first use. Returns false if disabled or on error.
bool frametap_begin(uint32_t codec, uint32_t width, uint32_t height, uint32_t max_fps);
// Call for every compressed video frame, before handing it to the decoder. Never blocks.
void frametap_push(const uint8_t *buf, size_t size, int32_t frames_lost, bool recovered);
// Returns true once per reader request for a keyframe (the caller then asks the PS5 for one).
bool frametap_take_idr_request(void);
// The buttons the reader asked to press (a ChiakiControllerButton mask), once per request, or 0; *hold_ms says how
// long to hold them. The caller presses them, sends the controller state, then calls frametap_press_sent().
uint32_t frametap_take_press_request(uint32_t *hold_ms);
// Call right after a press went to the PS5: the reader times the PS5's response from here.
void frametap_press_sent(void);
// What the reader asked chiaki-ng's windows to do, once per request: FRAMETAP_WINDOW_MINIMIZE, _RESTORE or 0.
uint32_t frametap_take_window_request(void);
// How long to hold the sound back (0-500 ms), as the reader asked; 0 if it hasn't, or has stopped.
uint32_t frametap_audio_delay_ms(void);
// The sound's format, when chiaki-ng sets up its sound output (sample rate, channels of 16-bit samples).
void frametap_audio_format(uint32_t rate, uint32_t channels);
// Call for every chunk of decoded sound as it arrives (interleaved signed 16-bit). Never blocks.
void frametap_push_audio(const uint8_t *buf, size_t size);
// Call when the stream session ends.
void frametap_end(void);
#ifdef __cplusplus
}
#endif
+129
View File
@@ -0,0 +1,129 @@
// See frametap_session.h. The frame tap's work inside chiaki-ng's StreamSession: copying frames and sound out,
// SmoovPlay's keyframe requests, the delay test's button presses and the sound delay. It reaches the session's
// private parts as a friend (one line in streamsession.h).
#include <frametap_session.h>
#include <frametap.h>
#include <streamsession.h>
#include <QGuiApplication>
#include <QMetaObject>
#include <QTimer>
#include <QWindow>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
bool FrameTapSession::Begin(StreamSession *session, ChiakiSession *chiaki_session, const ChiakiConnectVideoProfile &profile)
{
if(!frametap_begin((uint32_t)profile.codec, profile.width, profile.height, profile.max_fps))
return false;
CHIAKI_LOGI(session->GetChiakiLog(), "Frame tap on: copying every video frame to shared memory " FRAMETAP_NAME);
chiaki_session_set_video_sample_cb(chiaki_session, VideoSample, session);
#ifdef _WIN32
// SmoovPlay's video window opens as the stream starts, while chiaki-ng (where the player just pressed connect)
// is in front, and Windows only lets a window come to the front if the program in front allows it.
AllowSetForegroundWindow(ASFW_ANY);
#endif
return true;
}
void FrameTapSession::End()
{
frametap_end();
}
bool FrameTapSession::VideoSample(uint8_t *buf, size_t buf_size, int32_t frames_lost, bool frame_recovered, void *user)
{
auto session = reinterpret_cast<StreamSession *>(user);
// Copy first (never blocks), then decode as usual. A reader that joined mid-stream or fell behind asks for a
// keyframe; RequestIDR runs on the GUI thread, like chiaki-ng's own calls to it.
frametap_push(buf, buf_size, frames_lost, frame_recovered);
if(frametap_take_idr_request())
QMetaObject::invokeMethod(session, [session]() { session->RequestIDR(); }, Qt::QueuedConnection);
uint32_t hold_ms = 0;
if(uint32_t buttons = frametap_take_press_request(&hold_ms))
QMetaObject::invokeMethod(session, [session, buttons, hold_ms]() { Press(session, buttons, hold_ms); }, Qt::QueuedConnection);
if(uint32_t what = frametap_take_window_request())
QMetaObject::invokeMethod(session, [what]() { Windows(what); }, Qt::QueuedConnection);
return chiaki_ffmpeg_decoder_video_sample_cb(buf, buf_size, frames_lost, frame_recovered, session->ffmpeg_decoder);
}
// SmoovPlay's delay test: press the buttons, send the state at once, note the time, let go after hold_ms.
void FrameTapSession::Press(StreamSession *session, uint32_t buttons, uint32_t hold_ms)
{
session->keyboard_state.buttons |= buttons;
session->SendFeedbackState();
frametap_press_sent();
QTimer::singleShot((int)hold_ms, session, [session, buttons]() {
session->keyboard_state.buttons &= ~buttons;
session->SendFeedbackState();
});
}
// SmoovPlay's video window is in front: chiaki-ng's own (which would draw the unsmoothed stream, taking GPU time)
// goes down, and comes back when SmoovPlay is done. On Windows SmoovPlay can do this itself; on Wayland a program can
// only minimise its own windows, so SmoovPlay asks here. chiaki-ng keeps streaming and reading the controller.
void FrameTapSession::Windows(uint32_t what)
{
for(QWindow *w : QGuiApplication::topLevelWindows())
{
if(!w->isVisible() && what == FRAMETAP_WINDOW_MINIMIZE)
continue;
if(what == FRAMETAP_WINDOW_MINIMIZE)
w->showMinimized();
else if(what == FRAMETAP_WINDOW_RESTORE && w->windowState() & Qt::WindowMinimized)
w->showNormal();
}
}
// Sound held back by SmoovPlay's picture delay (frametap_audio_delay_ms): a first-in first-out buffer of exactly
// that much sound. Each frame in sends one frame's worth out, so the device is fed as steadily as before; while the
// delay grows that's silence, and when it shrinks the oldest sound is skipped.
static QByteArray &TapAudioFifo() { static QByteArray fifo; return fifo; }
static size_t &TapAudioBytesPerMs() { static size_t n = 192; return n; } // 48 kHz stereo 16-bit
static size_t &TapAudioSampleSize() { static size_t n = 4; return n; }
void FrameTapSession::AudioFormat(unsigned int rate, size_t sample_size)
{
TapAudioFifo().clear();
TapAudioSampleSize() = sample_size ? sample_size : 4;
TapAudioBytesPerMs() = (size_t)rate * TapAudioSampleSize() / 1000;
frametap_audio_format(rate, (uint32_t)(TapAudioSampleSize() / sizeof(int16_t)));
}
void FrameTapSession::QueueAudio(StreamSession *session, const QByteArray &buf)
{
QByteArray &fifo = TapAudioFifo();
size_t ss = TapAudioSampleSize();
size_t want = (size_t)frametap_audio_delay_ms() * TapAudioBytesPerMs() / ss * ss;
if(!want && fifo.isEmpty())
{
session->QueueAudioOutData(buf);
return;
}
fifo.append(buf);
size_t n = (size_t)buf.size();
if((size_t)fifo.size() > want + 2 * n) // the delay shrank: skip the oldest sound
fifo.remove(0, (int)((size_t)fifo.size() - want - n));
if((size_t)fifo.size() >= want + n)
{
session->QueueAudioOutData(fifo.left((int)n));
fifo.remove(0, (int)n);
}
else // the delay is growing: silence while the buffer fills
session->QueueAudioOutData(QByteArray((int)n, 0));
}
void FrameTapSession::PushAudio(StreamSession *session, const int16_t *buf, size_t samples_count)
{
if(session->audio_out_sample_size)
frametap_push_audio((const uint8_t *)buf, samples_count * session->audio_out_sample_size);
}
+36
View File
@@ -0,0 +1,36 @@
// SmoovPlay's frame tap, as chiaki-ng's StreamSession uses it. Everything the tap does inside chiaki-ng lives in
// frametap_session.cpp; chiaki-ng's own files only get one-line calls to these (apply_patch.py) and one friend line
// in streamsession.h, so a new chiaki-ng version is quick to patch.
//
// With CHIAKI_FRAMETAP unset, Begin() returns false and chiaki-ng runs exactly as without the tap.
#pragma once
#include <chiaki/session.h>
#include <QByteArray>
#include <stddef.h>
#include <stdint.h>
class StreamSession;
class FrameTapSession
{
public:
// At stream start, in place of setting chiaki-ng's video callback. True if the tap is on and has set its own
// callback (which copies each frame out, then hands it to chiaki-ng's decoder); false: set chiaki-ng's own.
static bool Begin(StreamSession *session, ChiakiSession *chiaki_session, const ChiakiConnectVideoProfile &profile);
// After chiaki_session_fini.
static void End();
// When chiaki-ng sets up its sound output.
static void AudioFormat(unsigned int rate, size_t sample_size);
// In place of QueueAudioOutData: holds the sound back by SmoovPlay's picture delay when SmoovPlay asks.
static void QueueAudio(StreamSession *session, const QByteArray &buf);
// At the top of PushAudioFrame: the game's sound as it arrives, for SmoovPlay's instant replay.
static void PushAudio(StreamSession *session, const int16_t *buf, size_t samples_count);
private:
static bool VideoSample(uint8_t *buf, size_t buf_size, int32_t frames_lost, bool frame_recovered, void *user);
static void Press(StreamSession *session, uint32_t buttons, uint32_t hold_ms);
static void Windows(uint32_t what);
};
+4 -1
View File
@@ -34,7 +34,10 @@ cp -r engine/. "$STAGE/usr/share/summit/engine/"
find "$STAGE/usr/share/summit/engine" -name '__pycache__' -exec rm -rf {} + 2>/dev/null || true
install -Dm644 packaging/summit.desktop "$STAGE/usr/share/applications/summit.desktop"
install -Dm644 packaging/icons/summit.png "$STAGE/usr/share/icons/hicolor/64x64/apps/summit.png"
for n in 16 24 32 48 64 128 256 512; do
install -Dm644 "packaging/icons/summit-$n.png" "$STAGE/usr/share/icons/hicolor/${n}x$n/apps/summit.png"
done
install -Dm644 packaging/icons/summit.svg "$STAGE/usr/share/icons/hicolor/scalable/apps/summit.svg"
install -Dm644 LICENSE "$STAGE/usr/share/doc/summit/LICENSE"
mkdir -p "$OUT_DIR"
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Renders the app icon PNGs from summit.svg (needs rsvg-convert, from librsvg). Run from anywhere; the PNGs are
# committed, so a build does not need this.
set -eu
here="$(cd "$(dirname "$0")" && pwd)"
root="$here/../.."
for n in 16 24 32 48 64 128 256 512; do
rsvg-convert -w "$n" -h "$n" "$here/summit.svg" -o "$here/summit-$n.png"
done
cp "$here/summit-256.png" "$here/summit.png"
# the engine's window icon (engine/framegen/io.py _set_icon)
for n in 16 24 32 48 64; do cp "$here/summit-$n.png" "$root/engine/framegen/assets/icon_$n.png"; done
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 690 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 23 KiB

+46
View File
@@ -0,0 +1,46 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<!-- Summit app icon: the launcher's peak mark (ui/widgets.slint LogoMark) on a night sky tile.
Rendered to PNGs by packaging/icons/render.sh. -->
<defs>
<linearGradient id="tile" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#1d2330"/>
<stop offset="1" stop-color="#0a0c11"/>
</linearGradient>
<radialGradient id="sun" cx="0.5" cy="0.5" r="0.5">
<stop offset="0" stop-color="#ffb02e" stop-opacity="0.55"/>
<stop offset="0.55" stop-color="#ff7a3d" stop-opacity="0.16"/>
<stop offset="1" stop-color="#ff7a3d" stop-opacity="0"/>
</radialGradient>
<linearGradient id="front" x1="0.25" y1="0" x2="0.75" y2="1">
<stop offset="0" stop-color="#ffc65c"/>
<stop offset="0.45" stop-color="#ffb02e"/>
<stop offset="1" stop-color="#ff6a2b"/>
</linearGradient>
<linearGradient id="back" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#b9743a"/>
<stop offset="1" stop-color="#6b3a22"/>
</linearGradient>
<linearGradient id="shade" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#000" stop-opacity="0"/>
<stop offset="1" stop-color="#7a1f00" stop-opacity="0.28"/>
</linearGradient>
<clipPath id="clip"><rect x="16" y="16" width="480" height="480" rx="108"/></clipPath>
</defs>
<rect x="16" y="16" width="480" height="480" rx="108" fill="url(#tile)"/>
<g clip-path="url(#clip)">
<circle cx="300" cy="190" r="210" fill="url(#sun)"/>
<!-- back peak -->
<path d="M196 412 L330 186 L470 412 Z" fill="url(#back)"/>
<!-- front peak -->
<path d="M42 412 L208 96 L374 412 Z" fill="url(#front)"/>
<!-- right face in shadow -->
<path d="M208 96 L374 412 L262 412 Z" fill="url(#shade)"/>
<!-- snow cap -->
<path d="M208 96 L262 198 L232 182 L210 214 L188 186 L160 198 Z" fill="#ffffff" fill-opacity="0.94"/>
<!-- ground line -->
<rect x="16" y="412" width="480" height="84" fill="#0a0c11"/>
<rect x="42" y="412" width="428" height="10" rx="5" fill="#ffb02e" fill-opacity="0.9"/>
</g>
<rect x="17" y="17" width="478" height="478" rx="107" fill="none" stroke="#ffffff" stroke-opacity="0.07" stroke-width="2"/>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

+1
View File
@@ -7,3 +7,4 @@ Icon=summit
Terminal=false
Categories=Game;
StartupNotify=true
StartupWMClass=summit