Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b3c42aa6d | ||
|
|
2eec6b324d | ||
|
|
023f8b3ecc | ||
|
|
d44502447b | ||
|
|
072a071e3c | ||
|
|
7dc52a4a2e | ||
|
|
7a147ec4c6 | ||
|
|
97e762642c | ||
|
|
41986c910f | ||
|
|
2a068e4daf | ||
|
|
b282334af3 |
No files matched your search
@@ -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"
|
||||
|
||||
@@ -58,6 +58,8 @@ curl -fsSL https://git.molberg.cloud/alex/summit/raw/branch/main/install.sh | sh
|
||||
|
||||
The installer detects your distro (Arch/CachyOS/Manjaro, Debian/Ubuntu/neon/Mint, Fedora, openSUSE), your GPU vendor and your session type, prints exactly what it is about to do, and asks before any `sudo` step (`--yes` skips that, `--dry-run` only prints, `--uninstall` removes what it installed). It builds Summit from source with `cargo` (no release packages are published yet) and sets up the engine's Python environment with `uv` (Python 3.12; CUDA 12.8 torch if it finds an NVIDIA GPU). It also installs the tools Summit calls (`ffmpeg`, `xrandr`, `xdg-open`, `zenity`; a failure there only warns), downloads the default RIFE model, and adds **Summit** to the app menu. Then run `summit doctor` to see whether Enhance can work on this machine, and `summit-gui` (or Summit in the app menu).
|
||||
|
||||
**Updating**: run the same command again. It finds the existing install and its version, rebuilds only if the source changed (`--force` always), replaces the engine's files but keeps its Python environment and models (adding what new requirements need), and leaves your library, profiles and clips alone. On Arch it installs only missing packages and never runs `pacman -Sy` on its own (a partial upgrade). Checked on the owner's Arch desktop into a scratch prefix: a fresh install, a run with nothing new (1 s, nothing rebuilt), and two updates to new commits.
|
||||
|
||||
What was really run: see [Status](#status) (a real install into a scratch prefix on one Ubuntu machine; dry-runs for the other distros).
|
||||
|
||||
## Why
|
||||
@@ -78,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
|
||||
|
||||
@@ -124,6 +132,10 @@ A game's page has Play, an **Enhance** toggle and **Profile**. With Enhance on,
|
||||
|  |  |
|
||||
| Profile editor: monitor, resolution and refresh from xrandr | After Play: RIFE + FSR on the game's 720p window, full screen |
|
||||
|
||||
### 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
|
||||
@@ -134,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
|
||||
@@ -159,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.
|
||||
@@ -190,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
|
||||
|
||||
@@ -204,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 |
|
||||
|
||||
@@ -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>,
|
||||
@@ -52,6 +55,10 @@ enum Cmd {
|
||||
/// Check this machine: session, monitors, and whether the engine, torch with CUDA, the model, ffmpeg, xrandr
|
||||
/// and a file dialog are there (with an id: the display commands that game's profile would run)
|
||||
Doctor { id: Option<String> },
|
||||
/// NVIDIA VFG frame generation and RTX VSR: NVIDIA's runtime (about 540 MB, from NVIDIA), per user
|
||||
Nvidia { #[command(subcommand)] cmd: NvidiaCmd },
|
||||
/// The windows open now, and the rule Enhance would save for each (`summit profile set <id> --window <rule>`)
|
||||
Windows,
|
||||
/// Look up names for Steam games you own but have not installed (cached)
|
||||
Names { #[arg(long, default_value_t = 60)] limit: usize },
|
||||
/// Run the frame-gen/upscale engine on a source, using a profile's settings
|
||||
@@ -70,6 +77,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 +95,101 @@ 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 },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum NvidiaCmd {
|
||||
/// Installed? Can this graphics card run it? Which licences it comes under
|
||||
Status,
|
||||
/// Download it from NVIDIA's package index (pinned version and hash). You must accept NVIDIA's licences first
|
||||
Install {
|
||||
/// You have read and accept the licences `summit nvidia status` lists
|
||||
#[arg(long)] accept_nvidia_licence: bool,
|
||||
},
|
||||
/// Delete it again
|
||||
Remove,
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
/// Frame multiplier: frames shown for each real one of a 30 fps game, 2 to 10 (2 = 60 fps, 4 = 120 fps)
|
||||
#[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>,
|
||||
/// Which window Enhance takes: class:NAME, part of its title, dir:FOLDER ("|" between alternatives; see
|
||||
/// `summit windows`). "" goes back to automatic
|
||||
#[arg(long, allow_hyphen_values = true)] window: Option<String>,
|
||||
/// The game's frame rate for frame generation: auto, 30 or 60 (60: the multiplier works from 60)
|
||||
#[arg(long)] game_fps: Option<String>,
|
||||
/// Output resolution: the upscaler makes the picture at this size, e.g. 2560x1440 ("screen": the screen's)
|
||||
#[arg(long)] output_res: Option<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 +260,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}");
|
||||
}
|
||||
}
|
||||
@@ -199,6 +284,41 @@ fn main() -> Result<()> {
|
||||
let text = state::path_text(&image.canonicalize()?)?;
|
||||
state::update(|st| { st.artwork.insert(id.clone(), text); })?; println!("artwork set for {id}");
|
||||
}
|
||||
Cmd::Nvidia { cmd } => {
|
||||
let eng = engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: run install.sh"))?;
|
||||
let dir = engine::vfx_dir().map(|d| d.display().to_string()).unwrap_or_default();
|
||||
match cmd {
|
||||
NvidiaCmd::Status => {
|
||||
let st = engine::vfx_status(&eng).map_err(|e| anyhow::anyhow!(e))?;
|
||||
println!("NVIDIA VFG + RTX VSR: {}", if st.installed { format!("installed ({}) in {dir}", st.version) } else { format!("not installed (about {} MB, into {dir})", st.size_mb) });
|
||||
println!("graphics card: {}{}", if st.gpu.is_empty() { "no NVIDIA card found" } else { &st.gpu }, if st.unsupported.is_empty() { String::new() } else { format!(" - {}", st.unsupported) });
|
||||
if !st.installed {
|
||||
println!("It comes under NVIDIA's licences:");
|
||||
for l in &st.licences { println!(" {}: {}", l.name, l.url); }
|
||||
println!("If you accept them: summit nvidia install --accept-nvidia-licence");
|
||||
}
|
||||
}
|
||||
NvidiaCmd::Install { accept_nvidia_licence } => {
|
||||
if !accept_nvidia_licence {
|
||||
let st = engine::vfx_status(&eng).map_err(|e| anyhow::anyhow!(e))?;
|
||||
let list: Vec<String> = st.licences.iter().map(|l| format!(" {}: {}", l.name, l.url)).collect();
|
||||
anyhow::bail!("NVIDIA's runtime comes under these licences; read them, and if you accept them run this again with --accept-nvidia-licence:\n{}", list.join("\n"));
|
||||
}
|
||||
let st = engine::vfx_command(&eng, false).ok_or_else(|| anyhow::anyhow!("no data folder"))?.status()?;
|
||||
anyhow::ensure!(st.success(), "the download did not finish ({st})");
|
||||
}
|
||||
NvidiaCmd::Remove => {
|
||||
let st = engine::vfx_command(&eng, true).ok_or_else(|| anyhow::anyhow!("no data folder"))?.status()?;
|
||||
anyhow::ensure!(st.success(), "it could not be removed ({st})");
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::Windows => {
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
let ws = summit_core::winmode::list_windows(s, d).map_err(|e| anyhow::anyhow!("can't list windows here: {e}"))?;
|
||||
for w in &ws { println!("{:<8} {:<40} {}", w.pid, summit_core::winmode::rule_for(w), w.title); }
|
||||
if ws.is_empty() { println!("no windows found"); }
|
||||
}
|
||||
Cmd::Doctor { id } => {
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
println!("session: {s:?}\ndesktop: {d:?}");
|
||||
@@ -221,22 +341,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,26 +388,85 @@ 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_cmd = std::process::Command::new(&py);
|
||||
eng_cmd.args(&args).envs(engine::engine_env(&p)).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title);
|
||||
// The launcher writes the window the player picks here while the engine waits (a rule from an
|
||||
// earlier run must not count, so it starts empty).
|
||||
let pick_file = engine::window_file(&id);
|
||||
if let Some(f) = &pick_file {
|
||||
if f.parent().is_some_and(|d| std::fs::create_dir_all(d).is_ok()) && std::fs::write(f, "").is_ok() { eng_cmd.env("SUMMIT_WINDOW_FILE", f); }
|
||||
}
|
||||
let mut eng_proc = match eng_cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => { let _ = engine::stop(&mut game, grace); anyhow::bail!("could not start the engine ({}): {e}", py.display()); }
|
||||
};
|
||||
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace, detached, &|| signals::requested().is_some())?;
|
||||
let supervised = engine::supervise(&mut game, &mut eng_proc, grace, detached, &|| signals::requested().is_some());
|
||||
if let Some(f) = &pick_file { let _ = std::fs::remove_file(f); }
|
||||
let (who, status) = supervised?;
|
||||
match who {
|
||||
engine::Ended::Stopped => out!("{}: stopped the engine and the game", signals::requested().map_or("asked to stop", signals::name)),
|
||||
engine::Ended::Game if detached => out!("the game's window closed; the engine ended ({})", eng_proc.wait()?),
|
||||
@@ -282,10 +477,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 +498,91 @@ 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, window, game_fps, output_res } } => {
|
||||
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); --multiplier takes 2 to 10"); }
|
||||
if let Some(v) = &game_fps { anyhow::ensure!(pr::GAME_FPS.contains(&v.as_str()), "--game-fps is auto, 30 or 60"); }
|
||||
let output_res = match output_res.as_deref() {
|
||||
None => None,
|
||||
Some("screen") | Some("") => Some(String::new()),
|
||||
Some(r) => Some(pr::parse_res(r).map(|(w, h)| format!("{w}x{h}")).ok_or_else(|| anyhow::anyhow!("--output-res is a size like 2560x1440, or screen"))?),
|
||||
};
|
||||
if let Some(v) = multiplier { anyhow::ensure!(pr::MULTIPLIER_RANGE.contains(&v), "--multiplier is a whole number from 2 to 10 (2x = 60 fps, 4x = 120 fps)"); }
|
||||
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 let Some(w) = window { l.window = Some(w.trim().to_string()).filter(|w| !w.is_empty()); }
|
||||
if game_fps.is_some() { l.game_fps = game_fps; }
|
||||
if let Some(r) = output_res { l.output_res = Some(r).filter(|r| !r.is_empty()); }
|
||||
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; }
|
||||
// one or the other: the multiplier replaces an older output rate in the same profile
|
||||
if multiplier.is_some() { l.framegen_multiplier = multiplier; l.target_hz = None; }
|
||||
if target_hz.is_some() { l.target_hz = target_hz; if multiplier.is_none() { l.framegen_multiplier = None; } }
|
||||
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 +629,176 @@ 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, from `--window` (alternatives split by "|", launch::window_query): a Steam game's
|
||||
/// `class:steam_app_<id>`, else `dir:<folder>` (the processes running from the game's folder), else the first
|
||||
/// `class:NAME`; with no `--window`, a Steam game's class or the process Summit started.
|
||||
fn place_target(id: &str, window: Option<&str>, pid: u32) -> summit_core::winmode::Target {
|
||||
use summit_core::winmode::Target;
|
||||
let alts: Vec<&str> = window.map(|w| w.split('|').map(str::trim).collect()).unwrap_or_default();
|
||||
let find = |pre: &str| alts.iter().find_map(|a| a.strip_prefix(pre).filter(|v| !v.is_empty()));
|
||||
if let Some(c) = find("class:steam_app_") { return Target::Class(format!("steam_app_{c}")); }
|
||||
if let Some(d) = find("dir:") { return Target::Dir(d.to_string()); }
|
||||
if let Some(c) = find("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 ® {
|
||||
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(®.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]
|
||||
|
||||
@@ -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"
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ pub fn scaler_arg(upscaler: &str) -> Option<&'static str> {
|
||||
"fsr" => Some("fsr"),
|
||||
"rtx-vsr" | "vsr" => Some("vsr"),
|
||||
"bilinear" => Some("bilinear"),
|
||||
// no upscaling: the picture at its own size (the profile editor's "None")
|
||||
"none" | "off" => Some("off"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -73,18 +75,96 @@ 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()); }
|
||||
// the frame multiplier N: the engine shows N frames for each real one of a 30 fps game, 30 x N fps
|
||||
let hz = 30 * u32::from(p.multiplier().unwrap_or(2));
|
||||
a.push("--hz".into()); a.push(hz.to_string());
|
||||
if let Some(g) = p.game_fps.as_deref().filter(|g| crate::profile::GAME_FPS.contains(g)) { a.push(opt("game-fps", g)); }
|
||||
if let Some((w, h)) = p.output_res.as_deref().and_then(crate::profile::parse_res) { a.push(format!("--output-res={w}x{h}")); }
|
||||
match p.window_mode.as_str() {
|
||||
"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)> {
|
||||
let mut v: 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![],
|
||||
};
|
||||
// where NVIDIA VFG and RTX VSR live once downloaded (`summit nvidia install`, Settings)
|
||||
if std::env::var_os("FRAMEGEN_VFX_PATH").is_none() {
|
||||
if let Some(d) = vfx_dir() { v.push(("FRAMEGEN_VFX_PATH".into(), d.to_string_lossy().into_owned())); }
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// NVIDIA's runtime for VFG frame generation and RTX VSR (the `nvidia-vfx` package, ~540 MB): downloaded from
|
||||
/// NVIDIA's own package index by the engine (framegen/vfg_setup.py) once the user accepts NVIDIA's licences. Per
|
||||
/// user, so it needs no sudo and an update of Summit keeps it. $FRAMEGEN_VFX_PATH wins.
|
||||
pub fn vfx_dir() -> Option<PathBuf> {
|
||||
if let Some(d) = std::env::var_os("FRAMEGEN_VFX_PATH").filter(|d| !d.is_empty()) { return Some(d.into()); }
|
||||
Some(dirs::data_dir()?.join("summit").join("nvidia-vfx"))
|
||||
}
|
||||
|
||||
/// What `framegen.vfg_setup --status --json` says: installed or not, and whether this graphics card can run it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct VfxStatus {
|
||||
pub installed: bool,
|
||||
pub version: String,
|
||||
pub gpu: String,
|
||||
/// Why this PC can't run it ("" if it can).
|
||||
pub unsupported: String,
|
||||
pub size_mb: u32,
|
||||
pub licences: Vec<Licence>,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Licence { pub name: String, pub url: String }
|
||||
|
||||
/// The engine's word on NVIDIA VFG / RTX VSR here (a second or so: it asks nvidia-smi).
|
||||
pub fn vfx_status(engine: &Path) -> Result<VfxStatus, String> {
|
||||
let dir = vfx_dir().ok_or("no data folder")?;
|
||||
let out = std::process::Command::new(python(engine)).current_dir(engine).args(["-m", "framegen.vfg_setup", "--status", "--json"])
|
||||
.env("FRAMEGEN_VFX_PATH", &dir).output().map_err(|e| format!("could not run the engine: {e}"))?;
|
||||
serde_json::from_slice(&out.stdout).map_err(|e| format!("the engine's answer was not understood ({e}): {}", String::from_utf8_lossy(&out.stderr).trim()))
|
||||
}
|
||||
|
||||
/// The command that downloads and installs NVIDIA's runtime into [`vfx_dir`]. Only to be run once the user has
|
||||
/// accepted NVIDIA's licences ([`VfxStatus::licences`]): the flag says they did. `remove`: delete it again.
|
||||
pub fn vfx_command(engine: &Path, remove: bool) -> Option<std::process::Command> {
|
||||
let dir = vfx_dir()?;
|
||||
let mut c = std::process::Command::new(python(engine));
|
||||
c.current_dir(engine).env("FRAMEGEN_VFX_PATH", &dir).env("PYTHONUNBUFFERED", "1").args(["-m", "framegen.vfg_setup"]);
|
||||
if remove { c.arg("--remove"); } else {
|
||||
if let Some(parent) = dir.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
c.args(["--install", "--accept-nvidia-licence"]);
|
||||
}
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// 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 +199,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
|
||||
}
|
||||
|
||||
@@ -207,6 +288,33 @@ pub fn descendants_in(proc_dir: &Path, pid: u32) -> Vec<u32> {
|
||||
family
|
||||
}
|
||||
|
||||
/// Whether `path` is `folder` or inside it, compared as the engine does (framegen/window_x11.py `under`): "/"
|
||||
/// separators, case ignored, and Wine's `Z:\\games\\x.exe` read as `/games/x.exe`.
|
||||
pub fn under(path: &str, folder: &str) -> bool {
|
||||
fn norm(p: &str) -> String {
|
||||
let p = p.trim().trim_matches('"').replace('\\', "/");
|
||||
let p = if p.len() > 2 && p.as_bytes()[1] == b':' && p[..1].eq_ignore_ascii_case("z") { p[2..].to_string() } else { p };
|
||||
p.trim_end_matches('/').to_lowercase()
|
||||
}
|
||||
let (p, f) = (norm(path), norm(folder));
|
||||
!f.is_empty() && (p == f || p.starts_with(&format!("{f}/")))
|
||||
}
|
||||
|
||||
/// The processes that belong to the game in `folder`: running from it (working directory or program) or started
|
||||
/// with a file in it on the command line (a Wine game's .exe). How a game Steam, Lutris or Heroic started is found.
|
||||
pub fn procs_in_dir(proc_dir: &Path, folder: &str) -> Vec<u32> {
|
||||
let mut out = vec![];
|
||||
for e in std::fs::read_dir(proc_dir).into_iter().flatten().flatten() {
|
||||
let Some(n) = e.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let link = |l: &str| std::fs::read_link(e.path().join(l)).ok().is_some_and(|t| under(&t.to_string_lossy(), folder));
|
||||
let cmd = || std::fs::read(e.path().join("cmdline")).ok().is_some_and(|c| {
|
||||
c.split(|b| *b == 0).any(|a| !a.is_empty() && under(&String::from_utf8_lossy(a), folder))
|
||||
});
|
||||
if link("cwd") || link("exe") || cmd() { out.push(n); }
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Still running (not gone, not a zombie waiting for its parent).
|
||||
fn alive(proc_dir: &Path, pid: u32) -> bool {
|
||||
match std::fs::read(proc_dir.join(pid.to_string()).join("stat")) {
|
||||
@@ -251,6 +359,15 @@ pub fn stop(child: &mut std::process::Child, grace: std::time::Duration) -> std:
|
||||
child.wait().map(|_| ())
|
||||
}
|
||||
|
||||
/// The file through which the launcher hands a waiting engine the window the player picked for game `id`
|
||||
/// (SUMMIT_WINDOW_FILE, framegen/window_x11.py LiveQuery): in the runtime folder, one per game, so the launcher can
|
||||
/// find it from the game's id alone. None without a runtime folder (then picking still saves the game's rule).
|
||||
pub fn window_file(id: &str) -> Option<PathBuf> {
|
||||
let dir = dirs::runtime_dir()?.join("summit");
|
||||
let safe: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
|
||||
Some(dir.join(format!("window-{safe}")))
|
||||
}
|
||||
|
||||
/// Where the engine saves clips: $SMOOVPLAY_REPLAY_DIR if set, else Summit in the Videos folder (XDG_VIDEOS_DIR),
|
||||
/// with a folder per game inside (see engine/framegen/replay.py videos_folder()).
|
||||
pub fn clips_dir() -> Option<PathBuf> {
|
||||
@@ -260,8 +377,13 @@ 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];
|
||||
// off: the engine records nothing (no encoder, no buffer), whatever its own settings say
|
||||
if replay_seconds == 0 { return vec!["--replay".into(), "0".into()]; }
|
||||
if !OK.contains(&replay_seconds) { return vec![]; }
|
||||
let mut a = vec!["--replay".to_string(), replay_seconds.to_string()];
|
||||
let clip = clip_seconds.min(replay_seconds);
|
||||
@@ -272,15 +394,20 @@ 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");
|
||||
}
|
||||
#[test] fn file_to_out_plan() {
|
||||
// upscaler "none" (the editor's Off): the engine shows the picture at its own size
|
||||
let pr = Profile { framegen: "rife".into(), upscaler: "none".into(), ..Default::default() };
|
||||
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");
|
||||
assert_eq!(a[1..].join(" "), "c.mp4 --scaler off --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");
|
||||
@@ -434,9 +561,62 @@ 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() })[0], ("FRAMEGEN_FULLSCREEN_STYLE".to_string(), "monitor".to_string()));
|
||||
assert!(engine_env(&Profile::default()).iter().all(|(k, _)| k == "FRAMEGEN_VFX_PATH"));
|
||||
// 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() };
|
||||
assert!(plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None).contains(&"--off".to_string()));
|
||||
}
|
||||
#[test]
|
||||
fn under_reads_wine_paths_and_keeps_folder_boundaries() {
|
||||
assert!(under("/games/VR/bin/vr", "/games/VR"));
|
||||
assert!(under("Z:\\games\\VR\\VR.exe", "/games/vr/"));
|
||||
assert!(under("/games/VR", "/games/VR"));
|
||||
assert!(!under("/games/VR2/vr", "/games/VR"));
|
||||
assert!(!under("C:\\windows\\explorer.exe", "/games/VR"));
|
||||
assert!(!under("/games/VR", ""));
|
||||
}
|
||||
#[test]
|
||||
fn procs_in_dir_reads_cwd_exe_and_cmdline() {
|
||||
let root = std::env::temp_dir().join(format!("summit-procs-in-dir-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let proc = |pid: u32, cwd: &str, exe: &str, cmd: &[&str]| {
|
||||
let d = root.join(pid.to_string());
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::os::unix::fs::symlink(cwd, d.join("cwd")).unwrap();
|
||||
std::os::unix::fs::symlink(exe, d.join("exe")).unwrap();
|
||||
std::fs::write(d.join("cmdline"), cmd.join("\0") + "\0").unwrap();
|
||||
};
|
||||
proc(1, "/games/VR", "/usr/bin/vr", &["vr"]);
|
||||
proc(2, "/home/me", "/games/VR/vr", &["vr"]);
|
||||
proc(3, "/home/me", "/proton/wine64", &["Z:\\games\\VR\\VR.exe"]);
|
||||
proc(4, "/home/me", "/usr/bin/steam", &["steam", "steam://rungameid/1"]);
|
||||
let mut got = procs_in_dir(&root, "/games/VR");
|
||||
got.sort();
|
||||
assert_eq!(got, vec![1, 2, 3]);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
#[test]
|
||||
fn game_frame_rate_and_output_resolution_reach_the_engine() {
|
||||
let p = Profile { framegen: "rife".into(), game_fps: Some("60".into()), output_res: Some("2560 x 1440".into()), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("pid:1".into()), &p, true, None, None).join(" ");
|
||||
assert!(a.contains("--hz 60 --game-fps=60 --output-res=2560x1440"), "{a}");
|
||||
let p = Profile { game_fps: Some("120".into()), output_res: Some("huge".into()), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("pid:1".into()), &p, true, None, None).join(" ");
|
||||
assert!(!a.contains("--game-fps") && !a.contains("--output-res"), "{a}"); // nothing the engine would refuse
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -19,13 +19,23 @@ 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 {
|
||||
pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { plan_with(e, summit_cli, enhance, None) }
|
||||
|
||||
/// [`plan`], with the game's own window rule (its profile's `window`, picked in the launcher or typed in the profile
|
||||
/// editor), which then wins over the one Summit works out.
|
||||
pub fn plan_with(e: &Entry, summit_cli: Option<&Path>, enhance: bool, window: Option<&str>) -> Plan {
|
||||
let cli = summit_cli.map(|c| c.to_string_lossy().into_owned());
|
||||
let rule = enhance_rule(e, window);
|
||||
let via_run = |cli: &str, extra: &[String], cmd: Vec<String>| {
|
||||
let mut v = vec![cli.to_string(), "run".into(), e.id.clone()];
|
||||
v.extend(extra.iter().cloned());
|
||||
@@ -41,7 +51,7 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
|
||||
match cli {
|
||||
Some(cli) => {
|
||||
let mut extra = vec!["--detached".to_string()];
|
||||
if enhance { extra.extend(["--enhance".into(), "--window".into(), format!("class:steam_app_{id}"), "--wait".into(), "120".into()]); }
|
||||
if enhance { extra.extend(enhance_args(rule.clone())); }
|
||||
Plan::Run(via_run(&cli, &extra, steam))
|
||||
}
|
||||
None if enhance => Plan::Unsupported("Enhance needs the summit command line tool next to summit-gui".into()),
|
||||
@@ -49,39 +59,126 @@ 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) => {
|
||||
let steam = vec!["steam".to_string(), uri.to_string()];
|
||||
detached(cli, steam, &via_run, enhance.then_some(rule))
|
||||
}
|
||||
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()) };
|
||||
if !Path::new(path).is_file() { return Plan::Unsupported(format!("{path} is not a file Summit can run")); }
|
||||
match cli {
|
||||
Some(cli) => {
|
||||
let extra: Vec<String> = if enhance { vec!["--enhance".into()] } else { vec![] };
|
||||
let mut extra: Vec<String> = if enhance { vec!["--enhance".into()] } else { vec![] };
|
||||
// Summit holds this game's process, so the engine takes that one's window unless a rule says otherwise
|
||||
if let (true, Some(w)) = (enhance, window.map(str::trim).filter(|w| !w.is_empty())) { extra.extend(["--window".into(), w.to_string()]); }
|
||||
Plan::Run(via_run(&cli, &extra, vec![path.into()]))
|
||||
}
|
||||
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}")];
|
||||
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) }
|
||||
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];
|
||||
detached(cli, lutris, &via_run, enhance.then_some(rule))
|
||||
}
|
||||
_ => Plan::Unsupported("no Lutris slug for this entry".into()),
|
||||
},
|
||||
Source::Heroic => match e.launch_uri.as_deref() {
|
||||
Some(uri) => {
|
||||
if enhance { return Plan::Unsupported("Enhance is not wired for Heroic games yet".into()); }
|
||||
let open = vec!["xdg-open".to_string(), uri.to_string()];
|
||||
match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], open)), None => Plan::Run(open) }
|
||||
detached(cli, open, &via_run, enhance.then_some(rule))
|
||||
}
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A game handed to another launcher (Steam for a non-Steam game, Lutris, Heroic): `summit run <id> --detached
|
||||
/// [--enhance --window <rule>] -- <cmd>`. With Enhance the engine finds the game's window by [`window_query`].
|
||||
fn detached(cli: Option<String>, cmd: Vec<String>, via_run: &dyn Fn(&str, &[String], Vec<String>) -> Vec<String>, enhance: Option<String>) -> Plan {
|
||||
let mut extra = vec!["--detached".to_string()];
|
||||
if let Some(rule) = enhance {
|
||||
let Some(cli) = cli else { return Plan::Unsupported("Enhance needs the summit command line tool next to summit-gui".into()) };
|
||||
extra.extend(enhance_args(rule));
|
||||
return Plan::Run(via_run(&cli, &extra, cmd));
|
||||
}
|
||||
match cli { Some(cli) => Plan::Run(via_run(&cli, &extra, cmd)), None => Plan::Run(cmd) }
|
||||
}
|
||||
|
||||
/// The engine waits this long for the game's window: time for a slow start, and for the player to pick the window
|
||||
/// in the launcher when Summit's own rule finds nothing.
|
||||
pub const WINDOW_WAIT_S: u32 = 300;
|
||||
|
||||
fn enhance_args(window: String) -> [String; 5] {
|
||||
["--enhance".into(), "--window".into(), window, "--wait".into(), WINDOW_WAIT_S.to_string()]
|
||||
}
|
||||
|
||||
/// The window rule Enhance starts with: the game's own (`window`), else Summit's guess ([`window_query`]), else
|
||||
/// [`ASK`]: the engine waits for the player to pick the window in the launcher.
|
||||
pub fn enhance_rule(e: &Entry, window: Option<&str>) -> String {
|
||||
window.map(str::trim).filter(|w| !w.is_empty()).map(String::from).or_else(|| window_query(e)).unwrap_or_else(|| ASK.into())
|
||||
}
|
||||
|
||||
/// The engine's `--window` for "no rule yet: wait for one picked in the launcher" (framegen/window_x11.py LiveQuery).
|
||||
pub const ASK: &str = "ask:";
|
||||
|
||||
/// Which window is the game's, for a game another program starts (so Summit never sees its process), in the
|
||||
/// engine's `--window` form, alternatives split by "|":
|
||||
/// * Steam: `class:steam_app_<id>` (Proton games), then `dir:<install folder>` (native games);
|
||||
/// * an executable (a non-Steam game in Steam, Lutris): `class:<file name>` (Wine names the window after its .exe),
|
||||
/// then `dir:<its folder>`;
|
||||
/// * a folder (Heroic): `dir:<folder>`.
|
||||
///
|
||||
/// `dir:` takes a window whose process runs from that folder or was started with a file in it: Steam, Lutris and
|
||||
/// Heroic all start a game from its own folder. None when the entry has no usable path (a command such as
|
||||
/// `flatpak run ...`, or a folder too broad to tell the game by, like the home folder).
|
||||
pub fn window_query(e: &Entry) -> Option<String> {
|
||||
let mut alts: Vec<String> = vec![];
|
||||
if let Some(id) = e.steam_app_id { alts.push(format!("class:steam_app_{id}")); }
|
||||
if let Some(path) = e.path.as_deref().map(str::trim).filter(|p| p.starts_with('/') && !p.contains('|')) {
|
||||
let p = Path::new(path);
|
||||
// Steam (with an app id) and Heroic store the install folder; a non-Steam game in Steam and Lutris the program
|
||||
let is_folder = e.steam_app_id.is_some() || e.source == Source::Heroic || p.is_dir();
|
||||
let folder = if is_folder { Some(p) } else {
|
||||
if let Some(f) = p.file_name().map(|f| f.to_string_lossy().to_lowercase()) { alts.push(format!("class:{f}")); }
|
||||
p.parent()
|
||||
};
|
||||
if let Some(folder) = folder.filter(|f| specific(f)) { alts.push(format!("dir:{}", folder.display())); }
|
||||
}
|
||||
(alts.iter().any(|a| a.starts_with("dir:") || a.starts_with("class:steam_app_"))).then(|| alts.join("|"))
|
||||
}
|
||||
|
||||
/// A folder narrow enough that "runs from here" means this game: not /, /usr/bin, the home folder or above it.
|
||||
fn specific(folder: &Path) -> bool {
|
||||
let depth = folder.components().count(); // "/" counts as one
|
||||
let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
|
||||
let wide = ["/usr", "/usr/bin", "/usr/local", "/usr/local/bin", "/bin", "/opt", "/tmp", "/mnt", "/media", "/run/media"];
|
||||
depth >= 3 && !wide.iter().any(|w| folder == Path::new(w)) && !home.is_some_and(|h| h.starts_with(folder))
|
||||
}
|
||||
|
||||
/// 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,15 +193,37 @@ 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");
|
||||
assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam:620 --detached --enhance --window class:steam_app_620 --wait 120 --title=steam:620 -- steam steam://rungameid/620");
|
||||
assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam:620 --detached --enhance --window class:steam_app_620 --wait 300 --title=steam:620 -- steam steam://rungameid/620");
|
||||
assert_eq!(plan(&e, None, false), Plan::Run(vec!["steam".into(), "steam://rungameid/620".into()]));
|
||||
assert!(matches!(plan(&e, None, true), Plan::Unsupported(_)));
|
||||
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");
|
||||
// nothing to tell its window by: the engine waits for the player to pick it in the launcher
|
||||
assert!(argv(plan(&e, cli(), true)).contains("--enhance --window ask: --wait 300"));
|
||||
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,17 +246,79 @@ 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(_)));
|
||||
assert!(argv(plan(&l, cli(), true)).contains("--window ask:"));
|
||||
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());
|
||||
assert_eq!(argv(plan(&h, cli(), false)), "/usr/bin/summit run heroic:epic:quail --detached --title=heroic:epic:quail -- xdg-open heroic://launch?appName=Quail&runner=legendary");
|
||||
assert_eq!(plan(&h, None, false), Plan::Run(vec!["xdg-open".into(), "heroic://launch?appName=Quail&runner=legendary".into()]));
|
||||
assert!(matches!(plan(&h, cli(), true), Plan::Unsupported(_)));
|
||||
assert!(argv(plan(&h, cli(), true)).contains("--window ask:"));
|
||||
assert!(matches!(plan(&h, None, true), Plan::Unsupported(_)));
|
||||
assert!(matches!(plan(&entry("scan:/g", Source::Heuristic, true, None, Some("/g")), cli(), false), Plan::Unsupported(_)));
|
||||
}
|
||||
#[test]
|
||||
fn games_other_launchers_start_can_be_enhanced_by_their_folder() {
|
||||
// a non-Steam game in Steam: Wine names the window after the .exe, or a program running from its folder
|
||||
let mut e = entry("steam-shortcut:1", Source::Steam, true, None, Some("/games/ULTRAKILL/ULTRAKILL.exe"));
|
||||
e.launch_uri = Some("steam://rungameid/99".into());
|
||||
assert_eq!(window_query(&e).as_deref(), Some("class:ultrakill.exe|dir:/games/ULTRAKILL"));
|
||||
assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam-shortcut:1 --detached --enhance --window class:ultrakill.exe|dir:/games/ULTRAKILL --wait 300 --title=steam-shortcut:1 -- steam steam://rungameid/99");
|
||||
assert!(matches!(plan(&e, None, true), Plan::Unsupported(_)));
|
||||
// a Steam game: Proton's class first, its install folder for native games
|
||||
let s = entry("steam:620", Source::Steam, true, Some(620), Some("/games/steamapps/common/Portal 2"));
|
||||
assert_eq!(window_query(&s).as_deref(), Some("class:steam_app_620|dir:/games/steamapps/common/Portal 2"));
|
||||
// Lutris (an exe) and Heroic (a folder)
|
||||
let mut l = entry("lutris:celeste", Source::Lutris, true, None, Some("/games/celeste/Celeste"));
|
||||
l.launch_uri = Some("lutris:rungameid/5".into());
|
||||
assert!(argv(plan(&l, cli(), true)).contains("--enhance --window class:celeste|dir:/games/celeste --wait 300"));
|
||||
let dir = std::env::temp_dir().join("summit-launch-test-heroic");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut h = entry("heroic:epic:quail", Source::Heroic, true, None, Some(&dir.to_string_lossy()));
|
||||
h.launch_uri = Some("heroic://launch?appName=Quail&runner=legendary".into());
|
||||
assert_eq!(window_query(&h), Some(format!("dir:{}", dir.display())));
|
||||
assert!(matches!(plan(&h, cli(), true), Plan::Run(_)));
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
#[test]
|
||||
fn a_folder_too_broad_or_a_command_gives_no_window_rule() {
|
||||
let mk = |p: &str| entry("steam-shortcut:2", Source::Steam, true, None, Some(p));
|
||||
assert_eq!(window_query(&mk("flatpak run org.x.Game")), None); // a command, not a path
|
||||
assert_eq!(window_query(&mk("/usr/bin/game")), None); // /usr/bin runs everything
|
||||
assert_eq!(window_query(&mk("/game")), None); // the root
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
let exe = std::path::Path::new(&home).join("game.sh");
|
||||
assert_eq!(window_query(&mk(&exe.to_string_lossy())), None); // the home folder
|
||||
}
|
||||
let mut e = mk("/usr/bin/game");
|
||||
e.launch_uri = Some("steam://rungameid/99".into());
|
||||
assert!(argv(plan(&e, cli(), true)).contains("--window ask:"));
|
||||
}
|
||||
#[test]
|
||||
fn the_games_own_window_rule_wins() {
|
||||
let mut e = entry("steam-shortcut:1", Source::Steam, true, None, Some("/games/VR/run.sh"));
|
||||
e.launch_uri = Some("steam://rungameid/99".into());
|
||||
assert!(argv(plan_with(&e, cli(), true, Some(" class:voidrunner "))).contains("--window class:voidrunner --wait 300"));
|
||||
assert!(argv(plan_with(&e, cli(), true, Some(""))).contains("--window class:run.sh|dir:/games/VR")); // empty: automatic
|
||||
assert!(!argv(plan_with(&e, cli(), false, Some("class:voidrunner"))).contains("--window")); // no Enhance
|
||||
// a game Summit starts itself: its process is known, a rule only when one is saved
|
||||
let c = entry("custom:x", Source::Custom, true, None, Some("/bin/sh"));
|
||||
assert_eq!(argv(plan_with(&c, cli(), true, Some("title words"))), "/usr/bin/summit run custom:x --enhance --window title words --title=custom:x -- /bin/sh");
|
||||
assert_eq!(argv(plan_with(&c, cli(), true, None)), "/usr/bin/summit run custom:x --enhance --title=custom:x -- /bin/sh");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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")]
|
||||
|
||||
@@ -1,8 +1,53 @@
|
||||
//! 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];
|
||||
/// Frame generation's multiplier: frames shown for each real frame of a 30 fps game (the engine's output is 30 x N
|
||||
/// fps). These are the editor's choices; any whole number in MULTIPLIER_RANGE works (a custom one).
|
||||
pub const MULTIPLIERS: &[u8] = &[2, 3, 4, 5, 6, 8];
|
||||
pub const MULTIPLIER_RANGE: std::ops::RangeInclusive<u8> = 2..=10;
|
||||
pub const GAME_FPS: &[&str] = &["auto", "30", "60"];
|
||||
/// Output resolution presets (any WxH from 320x240 to 7680x4320 works: [`parse_res`]).
|
||||
pub const OUTPUT_SIZES: &[&str] = &["1280x720", "1600x900", "1920x1080", "2560x1440", "3200x1800", "3840x2160"];
|
||||
|
||||
/// "2560x1440" (or "2560 x 1440", "2560X1440") as a size the engine takes.
|
||||
pub fn parse_res(s: &str) -> Option<(u32, u32)> {
|
||||
let (w, h) = s.trim().split_once(['x', 'X', '×'])?;
|
||||
let (w, h) = (w.trim().parse::<u32>().ok()?, h.trim().parse::<u32>().ok()?);
|
||||
((320..=7680).contains(&w) && (240..=4320).contains(&h)).then_some((w, h))
|
||||
}
|
||||
|
||||
/// 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 +56,393 @@ 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"
|
||||
pub upscaler: String,
|
||||
/// "none" | "rife" | "lsfg"
|
||||
pub framegen: String,
|
||||
/// 1 = off, 2..4 = multiplier
|
||||
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".
|
||||
pub model: Option<String>,
|
||||
pub launch_args: Vec<String>,
|
||||
/// 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,
|
||||
pub fsr_sharpness: Option<f32>,
|
||||
pub vsr_quality: Option<u8>,
|
||||
/// "" (engine default, on) | "none" | "rife" (older files: "lsfg": stored, not used)
|
||||
pub framegen: String,
|
||||
/// Frame multiplier, 2..=10 (0: not set; see [`Profile::multiplier`]). The engine shows 30 x N fps.
|
||||
pub framegen_multiplier: u8,
|
||||
/// Older files: the output rate (60, 90 or 120), which is the multiplier x 30. A layer sets one or the other.
|
||||
pub target_hz: Option<u32>,
|
||||
/// 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>,
|
||||
/// 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>,
|
||||
/// The game's frame rate for frame generation: "auto" | "30" | "60" (None: the engine's own setting).
|
||||
pub game_fps: Option<String>,
|
||||
/// The size the upscaler makes the picture, "2560x1440" (None: the screen's own).
|
||||
pub output_res: Option<String>,
|
||||
/// Which window Enhance takes, in the engine's `--window` form (`class:NAME`, part of the title, `dir:FOLDER`,
|
||||
/// alternatives split by "|"). None: Summit works it out (launch::window_query), and asks when it can't.
|
||||
pub window: Option<String>,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
/// The frame multiplier in use: the profile's, else its old output rate / 30, else None (the engine's own).
|
||||
pub fn multiplier(&self) -> Option<u8> {
|
||||
if MULTIPLIER_RANGE.contains(&self.framegen_multiplier) { return Some(self.framegen_multiplier); }
|
||||
self.target_hz.map(|hz| (hz / 30).clamp(*MULTIPLIER_RANGE.start() as u32, *MULTIPLIER_RANGE.end() as u32) as u8)
|
||||
}
|
||||
|
||||
/// 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>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub window: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub game_fps: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")] pub output_res: Option<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", "window", "game_fps", "output_res",
|
||||
];
|
||||
|
||||
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(); }
|
||||
// the multiplier and the older output rate say the same thing: what a later layer sets wins
|
||||
if let Some(v) = self.target_hz { p.target_hz = Some(v).filter(|v| *v > 0); p.framegen_multiplier = 0; }
|
||||
// A layer with both is an older file, where the multiplier was stored only and the rate was what counted
|
||||
// (this Summit writes one or the other).
|
||||
if let (Some(v), None) = (self.framegen_multiplier, self.target_hz) { p.framegen_multiplier = v; if MULTIPLIER_RANGE.contains(&v) { p.target_hz = None; } }
|
||||
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()); } }
|
||||
if let Some(v) = &self.window { p.window = Some(v.trim().to_string()).filter(|v| !v.is_empty()); }
|
||||
if let Some(v) = &self.game_fps { p.game_fps = text(v); }
|
||||
if let Some(v) = &self.output_res { p.output_res = text(v).filter(|r| r != "screen"); }
|
||||
}
|
||||
|
||||
/// 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(), "window" => self.window.is_some(),
|
||||
"game_fps" => self.game_fps.is_some(), "output_res" => self.output_res.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, "window" => self.window = None,
|
||||
"game_fps" => self.game_fps = None, "output_res" => self.output_res = 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());
|
||||
}
|
||||
#[test]
|
||||
fn the_multiplier_and_the_older_output_rate() {
|
||||
let defaults = Layer { target_hz: Some(120), ..Default::default() }; // files from before: 120 Hz is 4x
|
||||
assert_eq!(resolve(&[&defaults]).multiplier(), Some(4));
|
||||
let game = Layer { framegen_multiplier: Some(6), ..Default::default() };
|
||||
let p = resolve(&[&defaults, &game]); // the game's own wins
|
||||
assert_eq!((p.multiplier(), p.target_hz), (Some(6), None));
|
||||
let custom = Layer { framegen_multiplier: Some(7), ..Default::default() };
|
||||
assert_eq!(resolve(&[&custom]).multiplier(), Some(7));
|
||||
assert_eq!(resolve(&[&custom, &Layer { target_hz: Some(90), ..Default::default() }]).multiplier(), Some(3));
|
||||
assert_eq!(resolve(&[]).multiplier(), None);
|
||||
// an older file with both: its rate is what it ran at
|
||||
let old = Layer { framegen_multiplier: Some(2), target_hz: Some(120), ..Default::default() };
|
||||
assert_eq!(resolve(&[&old]).multiplier(), Some(4));
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -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(®_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), (®_path, ®)] {
|
||||
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(®(r#""AutoLoginUser" "main_acc" "ActiveProcess" { "ActiveUser" "0" }"#), &acc, true), Some(76561198000000001));
|
||||
assert_eq!(current_in(®(r#""AutoLoginUser" "someone_else""#), &acc, false), None);
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,12 @@ pub struct UiSettings {
|
||||
/// Multiplier on top of the system scale factor.
|
||||
pub ui_scale: f32,
|
||||
/// Instant replay: how many seconds the engine keeps.
|
||||
pub replay_seconds: u32,
|
||||
pub replay_seconds: u32, // 0: off
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,12 +75,21 @@ impl UiSettings {
|
||||
if self.theme.trim().is_empty() { self.theme = d.theme; }
|
||||
self.anim_speed = if self.anim_speed.is_finite() { self.anim_speed.clamp(0.0, 2.0) } else { d.anim_speed };
|
||||
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);
|
||||
// 0: instant replay off (nothing recorded, so it costs nothing); the clip length is kept for when it's on
|
||||
if self.replay_seconds != 0 { self.replay_seconds = nearest_u32(self.replay_seconds, CLIP_LENGTHS); }
|
||||
self.clip_seconds = nearest_u32(self.clip_seconds, CLIP_LENGTHS);
|
||||
if self.replay_seconds != 0 { self.clip_seconds = self.clip_seconds.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 +128,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 +150,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 +162,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));
|
||||
@@ -158,4 +187,11 @@ mod tests {
|
||||
assert_eq!((s.layout_index(), s.anim_style_index()), (2, 2));
|
||||
assert_eq!((clip_label(15).as_str(), clip_label(60).as_str(), clip_label(600).as_str()), ("15 s", "1 min", "10 min"));
|
||||
}
|
||||
#[test]
|
||||
fn instant_replay_can_be_off() {
|
||||
let s = UiSettings { replay_seconds: 0, clip_seconds: 60, ..Default::default() }.sanitized();
|
||||
assert_eq!((s.replay_seconds, s.clip_seconds), (0, 60)); // off, and the clip length kept for later
|
||||
assert_eq!(crate::engine::clip_args(0, 60), vec!["--replay".to_string(), "0".to_string()]);
|
||||
assert_eq!(crate::engine::clip_args(30, 60), vec!["--replay", "30", "--clip-length", "30"]);
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,401 @@
|
||||
//! 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),
|
||||
/// The processes running from the game's folder (a game Steam, Lutris or Heroic started: engine::procs_in_dir).
|
||||
Dir(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(_) | Target::Dir(_) => (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(_) | Target::Dir(_) => 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::Dir(d) => crate::engine::procs_in_dir(std::path::Path::new("/proc"), d),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
/// An open window, for the launcher's "pick the game's window" list.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct OpenWindow { pub pid: u32, pub class: String, pub title: String }
|
||||
|
||||
/// The KWin script that reports every normal window (pid, class, caption) without changing any.
|
||||
pub fn kwin_list_script(reply_to: &str) -> String {
|
||||
format!(r#"const out = [];
|
||||
for (const w of workspace.windowList()) {{
|
||||
if (!w.normalWindow) continue;
|
||||
out.push({{id: String(w.internalId), pid: w.pid, cls: String(w.resourceClass), caption: String(w.caption), output: w.output ? String(w.output.name) : ""}});
|
||||
}}
|
||||
callDBus({reply}, "/summit/winmode", "org.summit.WinMode", "placed", JSON.stringify(out));
|
||||
"#, reply = js(reply_to))
|
||||
}
|
||||
|
||||
/// The windows open now (KWin's on KDE, wmctrl's on other X11 desktops), or why they can't be listed.
|
||||
pub fn list_windows(session: Session, desktop: Desktop) -> Result<Vec<OpenWindow>, 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::list(),
|
||||
Backend::Wmctrl => {
|
||||
let out = std::process::Command::new("wmctrl").arg("-lpx").output().map_err(|e| format!("wmctrl: {e}"))?;
|
||||
Ok(parse_wmctrl(&String::from_utf8_lossy(&out.stdout)).into_iter()
|
||||
// wmctrl gives "instance.Class": the engine compares WM_CLASS's class half
|
||||
.map(|w| OpenWindow { pid: w.pid, class: w.class.rsplit('.').next().unwrap_or_default().to_string(), title: w.title }).collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Classes that many programs share (Wine's own, Java, Electron...), so they don't tell a game's window apart.
|
||||
const GENERIC_CLASSES: &[&str] = &["", "wine", "explorer.exe", "steam", "java", "python", "python3", "electron", "sdl_app", "xterm", "unknown"];
|
||||
|
||||
/// The rule that finds this window again next time, in the engine's `--window` form: its class when that names the
|
||||
/// program (Wine gives a game the class of its .exe, a native game its own), else its title.
|
||||
pub fn rule_for(w: &OpenWindow) -> String {
|
||||
let class = w.class.trim().to_lowercase();
|
||||
if !GENERIC_CLASSES.contains(&class.as_str()) && !class.contains('|') { return format!("class:{class}"); }
|
||||
w.title.trim().replace('|', " ")
|
||||
}
|
||||
|
||||
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 list() -> Result<Vec<OpenWindow>, 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 seen = once(&c, &rx, &kwin_list_script(&me), 0)?;
|
||||
Ok(seen.into_iter().map(|p| OpenWindow { pid: p.pid, class: p.class, title: p.caption }).collect())
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
#[test]
|
||||
fn a_picked_window_is_found_again_by_its_class_or_title() {
|
||||
let w = |class: &str, title: &str| OpenWindow { pid: 1, class: class.into(), title: title.into() };
|
||||
assert_eq!(rule_for(&w("ULTRAKILL.exe", "ULTRAKILL")), "class:ultrakill.exe");
|
||||
assert_eq!(rule_for(&w("voidrunner", "Voidrunner -- arena")), "class:voidrunner");
|
||||
assert_eq!(rule_for(&w("wine", "My Game")), "My Game"); // Wine's own class: by title
|
||||
assert_eq!(rule_for(&w("", " A | B ")), "A B"); // "|" splits rules
|
||||
assert!(kwin_list_script(":1.5").contains("\":1.5\""));
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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,49 +97,78 @@ 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" => "Off (no upscaling)".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() };
|
||||
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}"),
|
||||
(_, Some(hz)) => format!("{name}, {hz} Hz out"),
|
||||
_ => name,
|
||||
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.multiplier() {
|
||||
Some(m) => format!("{name} {m}×"),
|
||||
None => name,
|
||||
}
|
||||
}
|
||||
};
|
||||
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 +187,375 @@ 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() }),
|
||||
// the multiplier, or an older file's output rate read as one (120 Hz is 4x); "" a game's "engine setting"
|
||||
"framegen_multiplier" => match (l.framegen_multiplier, l.target_hz) {
|
||||
(Some(m), _) if summit_core::profile::MULTIPLIER_RANGE.contains(&m) => Some(m.to_string()),
|
||||
(_, Some(0)) | (Some(_), None) => Some(String::new()),
|
||||
(_, Some(hz)) => Some((hz / 30).to_string()),
|
||||
(None, None) => None,
|
||||
},
|
||||
"model" => l.model.clone(), "vfg_quality" => l.vfg_quality.clone(), "motion" => l.motion.clone(),
|
||||
"ai_engine" => l.ai_engine.clone(), "fill" => l.fill.clone(),
|
||||
"game_fps" => l.game_fps.clone(),
|
||||
"output_res" => l.output_res.as_deref().map(|r| summit_core::profile::parse_res(r).map(|(w, h)| format!("{w}x{h}")).unwrap_or_default()),
|
||||
_ => 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)),
|
||||
"framegen_multiplier" => match v.map(str::parse::<u8>) {
|
||||
None => { l.framegen_multiplier = None; l.target_hz = None; }
|
||||
Some(Ok(m)) => { l.framegen_multiplier = Some(m); l.target_hz = None; }
|
||||
Some(Err(_)) => { l.framegen_multiplier = None; l.target_hz = Some(0); } // "": the engine's own
|
||||
},
|
||||
"model" => l.model = s(v), "vfg_quality" => l.vfg_quality = s(v), "motion" => l.motion = s(v),
|
||||
"ai_engine" => l.ai_engine = s(v), "fill" => l.fill = s(v),
|
||||
"game_fps" => l.game_fps = s(v),
|
||||
"output_res" => l.output_res = s(v),
|
||||
_ => {}
|
||||
}
|
||||
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>,
|
||||
/// The window rule Summit works out for this game (launch::window_query), shown while the game has none of its own.
|
||||
pub auto_window: Option<&'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", "Off (no upscaling)"), c("fsr", "AMD FSR 1"), c("rtx-vsr", "NVIDIA RTX VSR"), c("bilinear", "Bilinear")], opt(Some(if base.upscaler == "vsr" { "rtx-vsr".into() } else { base.upscaler.clone() }))),
|
||||
"fsr_sharpness" => (vec![unset("Engine setting"), c("0", "Max"), c("0.25", "High"), c("0.5", "Medium"), c("1", "Low"), c("2", "Minimal")], opt(base.fsr_sharpness.map(|v| format!("{v}")))),
|
||||
"vsr_quality" => (vec![unset("Engine setting"), c("1", "Low"), c("2", "Medium"), c("3", "High"), c("4", "Ultra")], opt(enc_num(base.vsr_quality))),
|
||||
"framegen" => (vec![unset("Engine setting (on)"), c("none", "Off"), c("rife", "On")], opt(Some(base.framegen.clone()))),
|
||||
"model" => (vec![unset("Engine setting"), c("4.22.lite", "RIFE 4.22 lite"), c("4.25.lite", "RIFE 4.25 lite"), c("4.25", "RIFE 4.25"), c("4.26", "RIFE 4.26"), c("vfg", "NVIDIA VFG")], opt(base.model.clone())),
|
||||
"vfg_quality" => (vec![unset("Engine setting"), c("low", "Low"), c("medium", "Medium"), c("high", "High")], opt(base.vfg_quality.clone())),
|
||||
"motion" => (vec![unset("Auto"), c("full", "Full"), c("half", "Half")], opt(base.motion.clone())),
|
||||
"ai_engine" => (vec![unset("Engine setting"), c("auto", "Auto"), c("trt", "TensorRT"), c("torch", "PyTorch")], opt(base.ai_engine.clone())),
|
||||
"target_hz" => (vec![unset("Engine setting"), c("60", "60 Hz"), c("90", "90 Hz"), c("120", "120 Hz")], opt(enc_num(base.target_hz))),
|
||||
"game_fps" => (vec![unset("Engine setting (Auto)"), c("auto", "Auto"), c("30", "30 fps"), c("60", "60 fps")], opt(base.game_fps.clone())),
|
||||
"output_res" => {
|
||||
let mut v = vec![unset("Same as the screen")];
|
||||
v.extend(summit_core::profile::OUTPUT_SIZES.iter().map(|r| c(r, &res_label(r))));
|
||||
(v, opt(base.output_res.clone()))
|
||||
}
|
||||
"framegen_multiplier" => {
|
||||
let mut v = vec![unset("Engine setting (2×)")];
|
||||
v.extend(summit_core::profile::MULTIPLIERS.iter().map(|m| c(&m.to_string(), &multiplier_label(*m))));
|
||||
(v, opt(base.multiplier().map(|m| m.to_string())))
|
||||
}
|
||||
"steady_hud" => (bool3("Engine setting"), Some(base.steady_hud.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
"fill" => (vec![unset("Engine setting"), c("fit", "Fit (bars)"), c("zoom", "Zoom (crop)"), c("stretch", "Stretch"), c("panorama", "Panorama")], opt(base.fill.clone())),
|
||||
"vsync" => (bool3("Engine setting"), Some(base.vsync.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
"watermark" => (bool3("Engine setting (on)"), Some(base.watermark.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
_ => (vec![], None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// "4× (120 fps)": a frame multiplier and the rate it makes of a 30 fps game.
|
||||
pub fn multiplier_label(m: u8) -> String { format!("{m}×") }
|
||||
|
||||
/// "1440p" for the presets, "2560 × 1080" for any other size.
|
||||
pub fn res_label(r: &str) -> String {
|
||||
match summit_core::profile::parse_res(r) {
|
||||
Some((3840, 2160)) => "4K (3840 × 2160)".into(),
|
||||
Some((w, h)) if summit_core::profile::OUTPUT_SIZES.contains(&format!("{w}x{h}").as_str()) => format!("{h}p ({w} × {h})"),
|
||||
Some((w, h)) => format!("{w} × {h}"),
|
||||
None => r.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer's output resolution when it isn't one of the editor's choices (typed in Custom output resolution).
|
||||
fn custom_res(l: &Layer) -> Option<String> {
|
||||
let (w, h) = summit_core::profile::parse_res(l.output_res.as_deref()?)?;
|
||||
let r = format!("{w}x{h}");
|
||||
(!summit_core::profile::OUTPUT_SIZES.contains(&r.as_str())).then_some(r)
|
||||
}
|
||||
|
||||
/// The layer's multiplier when it isn't one of the editor's choices (typed in Custom multiplier).
|
||||
fn custom_multiplier(l: &Layer) -> Option<u8> {
|
||||
l.framegen_multiplier.filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m) && !summit_core::profile::MULTIPLIERS.contains(m))
|
||||
}
|
||||
|
||||
/// Text rows: launch arguments and environment variables, as one line each.
|
||||
fn text_of(l: &Layer, key: &str) -> Option<String> {
|
||||
match key {
|
||||
"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),
|
||||
"window" => l.window.clone(),
|
||||
_ => 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()),
|
||||
("output_res", "Output resolution", "The size the upscaler makes the picture, then fitted to the screen: smaller is lighter, bigger than the screen sharpens (supersampling).".into()),
|
||||
("output_res_custom", "Custom output resolution", "Any size, e.g. 2560x1080 (from 320x240 to 7680x4320). Enter to type it, Enter to save; empty goes back to the choice above.".into()),
|
||||
("fill", "Fill the screen", "On a screen that is not 16:9: bars, crop, stretch, or panorama.".into()),
|
||||
("#", "ENHANCE: FRAME GENERATION", String::new()),
|
||||
("framegen", "Frame generation", "AI in-between frames. Needs an NVIDIA GPU and the engine's Python environment.".into()),
|
||||
("model", "Model", "RIFE 4.22 lite is the one the engine is tuned and tested with. NVIDIA VFG is a separate download (RTX 40/50).".into()),
|
||||
("vfg_quality", "VFG quality", "How much work NVIDIA VFG puts into each frame.".into()),
|
||||
("motion", "Motion detail", "How finely RIFE tracks movement. Half is about 40% faster and a little softer.".into()),
|
||||
("ai_engine", "AI engine", "TensorRT is about 12% faster at full motion detail; its first start takes a minute or two.".into()),
|
||||
("steady_hud", "Steady HUD", "Keeps still parts of the picture (map, health bar) exactly as the game drew them.".into()),
|
||||
("framegen_multiplier", "Frame multiplier", "Frames shown for each one the game draws: 2× makes 30 fps 60 and 60 fps 120. Needs a display that fast; more needs a faster card.".into()),
|
||||
("multiplier_custom", "Custom multiplier", "Any whole number from 2 to 10. Enter to type it, Enter to save; empty goes back to the choice above.".into()),
|
||||
("game_fps", "Game frame rate", "Auto works it out as the game plays. 60 fps: the multiplier works from 60 (2× is 120 fps). 30 fps: every other frame is new.".into()),
|
||||
("#", "ENGINE WINDOW", String::new()),
|
||||
("vsync", "VSync", "Sync the engine's picture to the display (G-Sync/FreeSync).".into()),
|
||||
("watermark", "Watermark", "The \"summit - git.molberg.cloud/alex/summit\" line in a corner of the picture.".into()),
|
||||
("#", "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()),
|
||||
("#", "GAME WINDOW", String::new()),
|
||||
("window", "Game window", "Enhance's window: class:NAME, part of its title, or dir:FOLDER. Empty: automatic, and Summit asks when that finds nothing".into()),
|
||||
];
|
||||
for (key, label, hint) in spec {
|
||||
// a window belongs to one game: not a default
|
||||
if cx.defaults && (key == "window" || label == "GAME WINDOW") { continue; }
|
||||
if key == "#" { rows.push(header(label)); continue; }
|
||||
let skip = match key {
|
||||
"fsr_sharpness" => !matches!(up, "" | "fsr"),
|
||||
"vsr_quality" => !matches!(up, "rtx-vsr" | "vsr"),
|
||||
"vfg_quality" => eff.model.as_deref() != Some("vfg") || eff.framegen == "none",
|
||||
"model" | "framegen_multiplier" | "multiplier_custom" | "game_fps" | "steady_hud" => eff.framegen == "none",
|
||||
"motion" | "ai_engine" => !rife,
|
||||
_ => false,
|
||||
};
|
||||
if skip && !cx.own.has(key) && key != "multiplier_custom" { continue; }
|
||||
if skip && key == "multiplier_custom" { continue; }
|
||||
if key == "output_res_custom" {
|
||||
let text = custom_res(cx.own).unwrap_or_default();
|
||||
let placeholder = match eff.output_res.as_deref() { Some(r) => format!("Now {}", res_label(r)), None => "e.g. 2560x1080".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text, placeholder, own: !cx.defaults && custom_res(cx.own).is_some() });
|
||||
continue;
|
||||
}
|
||||
let own = !cx.defaults && match key {
|
||||
"resolution" => cx.own.width.is_some() || cx.own.height.is_some(),
|
||||
"framegen_multiplier" => cx.own.framegen_multiplier.is_some() || cx.own.target_hz.is_some(),
|
||||
"multiplier_custom" => custom_multiplier(cx.own).is_some(),
|
||||
k => cx.own.has(k),
|
||||
};
|
||||
if key == "multiplier_custom" {
|
||||
let text = custom_multiplier(cx.own).map(|m| m.to_string()).unwrap_or_default();
|
||||
let placeholder = match eff.multiplier() { Some(m) => format!("Now {}", multiplier_label(m)), None => "e.g. 7".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text, placeholder, own });
|
||||
continue;
|
||||
}
|
||||
if key == "window" {
|
||||
let placeholder = match cx.auto_window { Some(q) => format!("Automatic: {q}"), None => "Automatic: asks you to pick it".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text: text_of(cx.own, key).unwrap_or_default(), placeholder, own });
|
||||
continue;
|
||||
}
|
||||
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 => {
|
||||
// a value the list doesn't have: a custom multiplier, or something a newer Summit (or the CLI) wrote
|
||||
let l = match (key, cur.as_deref().and_then(|c| c.parse::<u8>().ok())) {
|
||||
("framegen_multiplier", Some(m)) => format!("{} (custom)", multiplier_label(m)),
|
||||
("output_res", _) if cur.as_deref().is_some_and(|c| !c.is_empty()) => format!("{} (custom)", res_label(cur.as_deref().unwrap_or_default())),
|
||||
_ => cur.clone().unwrap_or_default(),
|
||||
};
|
||||
ch.push((cur, l)); ch.len() - 1
|
||||
}
|
||||
};
|
||||
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)?) },
|
||||
"window" => l.window = if t.is_empty() { None } else { Some(t.to_string()) },
|
||||
"output_res_custom" => {
|
||||
if t.is_empty() {
|
||||
if custom_res(&l).is_some() { l.output_res = None; } // back to the choice above
|
||||
} else {
|
||||
let (w, h) = summit_core::profile::parse_res(t).ok_or_else(|| "A size like 2560x1440, from 320x240 to 7680x4320".to_string())?;
|
||||
l.output_res = Some(format!("{w}x{h}"));
|
||||
}
|
||||
}
|
||||
"multiplier_custom" => {
|
||||
if t.is_empty() {
|
||||
if custom_multiplier(&l).is_some() { l.framegen_multiplier = None; } // back to the choice above
|
||||
} else {
|
||||
let m = t.trim_end_matches(['x', 'X', '×']).trim().parse::<u8>().ok().filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m))
|
||||
.ok_or_else(|| "The multiplier is a whole number from 2 to 10".to_string())?;
|
||||
l.framegen_multiplier = Some(m);
|
||||
l.target_hz = None;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
/// Where Enhance has got to in finding the game's window, from `summit run`'s log (the engine's lines).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum WindowWait {
|
||||
/// Nothing said yet (the engine is starting).
|
||||
NotYet,
|
||||
/// Looking. `asking`: it has no rule at all and waits for one picked in the launcher.
|
||||
Waiting { asking: bool },
|
||||
/// Enhancing this window.
|
||||
Found(String),
|
||||
/// It gave up: nothing matched in time.
|
||||
GaveUp,
|
||||
}
|
||||
|
||||
pub fn window_wait(log: &str) -> WindowWait {
|
||||
let mut w = WindowWait::NotYet;
|
||||
for l in log.lines() {
|
||||
if let Some(rest) = l.split("[run] source: ").nth(1) { w = WindowWait::Found(rest.trim().trim_end_matches(" window").trim().to_string()); }
|
||||
else if l.contains("[window] waiting for the game's window to be picked") { w = WindowWait::Waiting { asking: true }; }
|
||||
else if l.contains("[window] waiting for") { w = WindowWait::Waiting { asking: false }; }
|
||||
else if l.contains("[window] now looking for") { w = WindowWait::Waiting { asking: false }; }
|
||||
else if l.contains("no window matches") && !matches!(w, WindowWait::Found(_)) { w = WindowWait::GaveUp; }
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// The error `summit run` ended with, from its output: the last "Error: ..." line, else the last line.
|
||||
@@ -343,64 +680,193 @@ 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(), 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 4×", "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"), auto_window: None }
|
||||
}
|
||||
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"));
|
||||
}
|
||||
#[test]
|
||||
fn window_wait_follows_the_engine() {
|
||||
assert_eq!(window_wait(""), WindowWait::NotYet);
|
||||
let ask = "x\n[window] waiting for the game's window to be picked in Summit (up to 300 s)\n";
|
||||
assert_eq!(window_wait(ask), WindowWait::Waiting { asking: true });
|
||||
let picked = format!("{ask}[window] now looking for 'class:voidrunner' (picked in Summit)\n");
|
||||
assert_eq!(window_wait(&picked), WindowWait::Waiting { asking: false });
|
||||
let found = format!("{picked}[window] Voidrunner (xid 0x1, pid 2): 1280x720\n[run] source: Voidrunner window\n");
|
||||
assert_eq!(window_wait(&found), WindowWait::Found("Voidrunner".into()));
|
||||
assert_eq!(window_wait("[window] waiting for a window matching 'class:a' (up to 300 s)\n"), WindowWait::Waiting { asking: false });
|
||||
assert_eq!(window_wait("[window] waiting for a window matching 'class:a'\nError: no window matches 'class:a' after 300 s\n"), WindowWait::GaveUp);
|
||||
}
|
||||
#[test]
|
||||
fn frame_multiplier_rows() {
|
||||
let base = Profile { framegen: "rife".into(), target_hz: Some(120), ..Default::default() }; // the defaults: 4x
|
||||
let g = Layer::default();
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
let r = row(&rows, "framegen_multiplier");
|
||||
assert_eq!(r.options[r.value], "Default · 4×");
|
||||
assert!(r.options.contains(&"8×".to_string()));
|
||||
// picking 6x: the game's own, and no older output rate left beside it
|
||||
let six = r.options.iter().position(|o| o.starts_with("6×")).unwrap();
|
||||
let g = edit_apply(&cx(&g, &base, false, &[]), "framegen_multiplier", six);
|
||||
assert_eq!((g.framegen_multiplier, g.target_hz), (Some(6), None));
|
||||
// a custom 7x: typed, shown as custom in the choice row, cleared again with an empty line
|
||||
let g = edit_text(&g, "multiplier_custom", " 7x ").unwrap();
|
||||
assert_eq!(g.framegen_multiplier, Some(7));
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
assert_eq!(row(&rows, "multiplier_custom").text, "7");
|
||||
let r = row(&rows, "framegen_multiplier");
|
||||
assert_eq!(r.options[r.value], "7× (custom)");
|
||||
assert!(edit_text(&g, "multiplier_custom", "11").is_err() && edit_text(&g, "multiplier_custom", "1.5").is_err());
|
||||
assert_eq!(edit_text(&g, "multiplier_custom", "").unwrap().framegen_multiplier, None);
|
||||
// frame generation off: neither row
|
||||
let off = Profile { framegen: "none".into(), ..Default::default() };
|
||||
let rows = edit_rows(&cx(&Layer::default(), &off, false, &[]));
|
||||
assert!(!rows.iter().any(|r| r.key == "framegen_multiplier" || r.key == "multiplier_custom"));
|
||||
}
|
||||
#[test]
|
||||
fn game_frame_rate_and_output_resolution_rows() {
|
||||
let base = Profile { framegen: "rife".into(), ..Default::default() };
|
||||
let g = Layer::default();
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
let fps = row(&rows, "game_fps");
|
||||
let sixty = fps.options.iter().position(|o| o == "60 fps").unwrap();
|
||||
assert_eq!(edit_apply(&cx(&g, &base, false, &[]), "game_fps", sixty).game_fps.as_deref(), Some("60"));
|
||||
let r = row(&rows, "output_res");
|
||||
assert!(r.options.contains(&"1440p (2560 × 1440)".to_string()) && r.options.contains(&"4K (3840 × 2160)".to_string()));
|
||||
let k = r.options.iter().position(|o| o.starts_with("1440p")).unwrap();
|
||||
assert_eq!(edit_apply(&cx(&g, &base, false, &[]), "output_res", k).output_res.as_deref(), Some("2560x1440"));
|
||||
// any size, typed: shown as custom in the choice row
|
||||
let g = edit_text(&g, "output_res_custom", " 2560 x 1080 ").unwrap();
|
||||
assert_eq!(g.output_res.as_deref(), Some("2560x1080"));
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
assert_eq!(row(&rows, "output_res_custom").text, "2560x1080");
|
||||
let r = row(&rows, "output_res");
|
||||
assert_eq!(r.options[r.value], "2560 × 1080 (custom)");
|
||||
assert!(edit_text(&g, "output_res_custom", "99x99").is_err() && edit_text(&g, "output_res_custom", "big").is_err());
|
||||
assert_eq!(edit_text(&g, "output_res_custom", "").unwrap().output_res, None);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
|
||||
@@ -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"; }
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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, PickRow, 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, PickRow, 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; }
|
||||
}
|
||||
@@ -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(); }
|
||||
}
|
||||
}
|
||||
@@ -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"; }
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// 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, FocusRing } 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 pick the game's window, 2 stop
|
||||
background: Theme.p.bg;
|
||||
|
||||
function shown(b: int) -> bool { return b == 0 || (b == 1 && Lib.play-enhance) || (b == 2 && Lib.play-can-stop); }
|
||||
function step(d: int) {
|
||||
if (root.shown(root.btn + d)) { root.btn += d; } else if (root.shown(root.btn + 2 * d)) { root.btn += 2 * d; }
|
||||
}
|
||||
|
||||
// keys come here while it is up; everything else is swallowed by the window (app.slint)
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (Lib.pick-open) {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { Lib.pick-close(); return true; }
|
||||
if (e.text == Key.UpArrow) { Lib.pick-sel = Math.max(0, Lib.pick-sel - 1); return true; }
|
||||
if (e.text == Key.DownArrow) { Lib.pick-sel = Math.min(Lib.pick-rows.length - 1, Lib.pick-sel + 1); return true; }
|
||||
if ((e.text == Key.Return || e.text == " ") && Lib.pick-rows.length > 0) { Lib.pick-choose(Lib.pick-sel); return true; }
|
||||
return true;
|
||||
}
|
||||
if (e.text == Key.Escape) { Lib.play-back(); return true; }
|
||||
if (e.text == Key.LeftArrow || e.text == Key.UpArrow) { root.step(-1); return true; }
|
||||
if (e.text == Key.RightArrow || e.text == Key.DownArrow) { root.step(1); return true; }
|
||||
if (e.text == "w" || e.text == "W") { if (Lib.play-enhance) { Lib.pick-show(); } return true; }
|
||||
if (e.text == Key.Return || e.text == " ") {
|
||||
if (root.btn == 2 && Lib.play-can-stop) { Lib.play-stop(); }
|
||||
else if (root.btn == 1 && Lib.play-enhance) { Lib.pick-show(); }
|
||||
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; }
|
||||
}
|
||||
if Lib.play-enhance && Lib.play-window-note != "": HorizontalLayout {
|
||||
alignment: start; spacing: 10px; height: 20px;
|
||||
VerticalLayout { alignment: center; Icon { size: 16px; color: Lib.play-window-wanted ? Theme.p.accent : Theme.p.ok; commands: Icons.sparkle; } }
|
||||
Text { text: Lib.play-window-note; color: Lib.play-window-wanted ? Theme.p.text : Theme.p.dim; font-size: Theme.t-sm; 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 || !root.shown(root.btn); clicked => { root.btn = 0; Lib.play-back(); } }
|
||||
if Lib.play-enhance: Btn { text: "Pick the game's window"; icon: Icons.monitor; primary: Lib.play-window-wanted; focused: root.btn == 1; clicked => { root.btn = 1; Lib.pick-show(); } }
|
||||
if Lib.play-can-stop: Btn { text: "Stop the game"; icon: Icons.close; focused: root.btn == 2; clicked => { root.btn = 2; Lib.play-stop(); } }
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalLayout {
|
||||
x: Theme.pad; y: parent.height - 48px; width: parent.width - 2 * Theme.pad; height: 22px; alignment: end; spacing: 24px;
|
||||
if Lib.play-enhance: KeyCap { key: "W"; label: "Pick the game's window"; }
|
||||
KeyCap { key: "Esc"; label: "Back to the launcher"; }
|
||||
KeyCap { key: "Hold B"; label: "Back, when this window is in front"; }
|
||||
}
|
||||
|
||||
// ---- pick the game's window: over the card, keys and clicks stay here ----
|
||||
if Lib.pick-open: ov := Rectangle {
|
||||
background: Theme.p.bg.with-alpha(0.86);
|
||||
TouchArea { clicked => { Lib.pick-close(); } }
|
||||
property <length> w: Math.min(root.width - 2 * Theme.pad, 760px);
|
||||
property <length> row-h: 58px;
|
||||
property <length> list-h: Math.min(root.height - 300px, Math.max(1, Lib.pick-rows.length) * self.row-h);
|
||||
Rectangle {
|
||||
x: (parent.width - parent.w) / 2; y: (parent.height - self.height) / 2; width: parent.w; height: col.preferred-height;
|
||||
background: Theme.p.surface; border-radius: Theme.r-md; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
TouchArea { } // clicks inside don't close it
|
||||
col := VerticalLayout {
|
||||
padding: 24px; spacing: 12px;
|
||||
Text { text: "PICK THE GAME'S WINDOW"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px; }
|
||||
Text { text: "Enhance runs on the window you pick, and Summit remembers it for " + Lib.play-title + " (Profile, Game window, changes it any time)."; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if Lib.pick-note != "": Text { text: Lib.pick-note; color: Theme.p.faint; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
Flickable {
|
||||
height: ov.list-h; content-height: Lib.pick-rows.length * ov.row-h;
|
||||
content-y: Math.min(0px, Math.max(self.height - self.content-height, -(Lib.pick-sel * ov.row-h) + self.height / 2 - ov.row-h / 2));
|
||||
for r[i] in Lib.pick-rows: Rectangle {
|
||||
y: i * ov.row-h; height: ov.row-h - 6px;
|
||||
border-radius: Theme.r-md;
|
||||
background: i == Lib.pick-sel ? Theme.p.raised : rta.has-hover ? Theme.p.raised.with-alpha(0.6) : transparent;
|
||||
HorizontalLayout {
|
||||
padding-left: 14px; padding-right: 14px; spacing: 12px;
|
||||
VerticalLayout { alignment: center;
|
||||
Text { text: r.title; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; overflow: elide; }
|
||||
Text { text: r.detail; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
}
|
||||
if r.fresh: VerticalLayout { alignment: center;
|
||||
Rectangle { width: fl.preferred-width + 16px; height: 22px; border-radius: 11px; background: Theme.p.accent.with-alpha(0.18);
|
||||
fl := Text { text: "opened since Play"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 700; horizontal-alignment: center; vertical-alignment: center; } }
|
||||
}
|
||||
}
|
||||
FocusRing { on: i == Lib.pick-sel; radius: Theme.r-md; }
|
||||
rta := TouchArea { mouse-cursor: pointer; clicked => { Lib.pick-sel = i; Lib.pick-choose(i); } }
|
||||
}
|
||||
}
|
||||
HorizontalLayout { alignment: end; spacing: 24px;
|
||||
KeyCap { key: "Enter"; label: "Use this window"; }
|
||||
KeyCap { key: "Esc"; label: "Cancel"; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 : i == 11 ? 1328px : 1464px;
|
||||
}
|
||||
pure function rh(i: int) -> length { return i == 1 ? 160px : 72px; }
|
||||
function reveal() {
|
||||
@@ -63,16 +65,28 @@ export component SettingsView inherits Rectangle {
|
||||
else if (root.srow == 2) { Prefs.scale = Math.clamp(Prefs.scale + d, 0, Prefs.scales.length - 1); }
|
||||
else if (root.srow == 3) { Theme.speed = Math.clamp(Math.round((Theme.speed + d * 0.25) * 4) / 4, 0, 2); }
|
||||
else if (root.srow == 4) { Theme.style = Math.clamp(Theme.style + d, 0, 2); }
|
||||
else if (root.srow == 5) { Prefs.replay = Math.clamp(Prefs.replay + d, 0, 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 == 5) { Prefs.replay = Math.clamp(Prefs.replay + d, 0, 6); Prefs.clip = Math.max(0, Math.min(Prefs.clip, Prefs.replay - 1)); }
|
||||
else if (root.srow == 6) { if (Prefs.replay == 0) { return; } Prefs.clip = Math.clamp(Prefs.clip + d, 0, Prefs.replay - 1); }
|
||||
else if (root.srow == 7) { return; }
|
||||
else if (root.srow == 8) { Prefs.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 (Lib.nvidia-open) {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { Lib.nvidia-open = false; }
|
||||
else if (e.text == Key.LeftArrow) { Lib.nvidia-btn = Math.max(0, Lib.nvidia-btn - 1); }
|
||||
else if (e.text == Key.RightArrow) { Lib.nvidia-btn = Math.min(2, Lib.nvidia-btn + 1); }
|
||||
else if (e.text == Key.Return || e.text == " ") { Lib.nvidia-act(Lib.nvidia-btn); }
|
||||
return true;
|
||||
}
|
||||
if ((e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) && root.srow == 12) { Lib.nvidia-btn = Lib.nvidia-installed ? 2 : 0; Lib.nvidia-open = true; return true; }
|
||||
if (e.text == Key.DownArrow) { root.srow = Math.min(12, root.srow + 1); }
|
||||
else if ((e.text == Key.Return || e.text == " ") && root.srow == 7) { Lib.open-clips(); }
|
||||
else if ((e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) && root.srow == 11) { Lib.open-defaults(); }
|
||||
else if (e.text == Key.UpArrow) { if (root.srow == 0) { root.exit-up(); } else { root.srow -= 1; } }
|
||||
else if (e.text == Key.RightArrow) { root.adjust(1); }
|
||||
else if (e.text == Key.LeftArrow) { root.adjust(-1); }
|
||||
@@ -82,7 +96,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: 1612px;
|
||||
animate content-y { duration: Theme.ms(220); easing: ease-out; }
|
||||
Text { x: root.cx; y: 20px; text: "Settings"; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; }
|
||||
Text { x: root.cx; y: 58px; width: root.cw; text: "Saved to " + Prefs.file + " as you change them."; color: Theme.p.dim; font-size: Theme.t-sm; overflow: elide; }
|
||||
@@ -114,24 +128,77 @@ export component SettingsView inherits Rectangle {
|
||||
}
|
||||
|
||||
Section { x: root.cx; y: 688px; width: root.cw; title: "CLIPS"; icon: Icons.film; }
|
||||
Row { x: root.cx; y: root.ry(5); width: root.cw; label: "Keep the last"; hint: "Instant replay buffer, passed to the engine as --replay."; focused: root.active && root.srow == 5; hit => { root.srow = 5; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.clip-lengths; value <=> Prefs.replay; changed => { root.srow = 5; Prefs.clip = Math.min(Prefs.clip, Prefs.replay); root.save(); } }
|
||||
Row { x: root.cx; y: root.ry(5); width: root.cw; label: "Keep the last";
|
||||
hint: Prefs.replay == 0 ? "Off: nothing is recorded, so it costs no performance." : "Instant replay buffer (--replay). Off records nothing.";
|
||||
focused: root.active && root.srow == 5; hit => { root.srow = 5; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 7 * 72px + 8px; options: Prefs.replay-options; value <=> Prefs.replay; changed => { root.srow = 5; Prefs.clip = Math.max(0, Math.min(Prefs.clip, Prefs.replay - 1)); root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(6); width: root.cw; label: "A save writes"; hint: "Passed as --clip-length. " + Lib.hotkey-status; focused: root.active && root.srow == 6; hit => { root.srow = 6; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.clip-lengths; limit: Prefs.replay; value <=> Prefs.clip; changed => { root.srow = 6; root.save(); } }
|
||||
Row { x: root.cx; y: root.ry(6); width: root.cw; label: "A save writes"; hint: Prefs.replay == 0 ? "Instant replay is off, so there is nothing to save." : "Passed as --clip-length. " + Lib.hotkey-status; focused: root.active && root.srow == 6; hit => { root.srow = 6; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.clip-lengths; limit: Prefs.replay - 1; value <=> Prefs.clip; changed => { root.srow = 6; root.save(); } }
|
||||
}
|
||||
|
||||
Row { x: root.cx; y: root.ry(7); width: root.cw; label: "Clips folder"; hint: Lib.clips-dir + "/<game>/ (Enter opens it)"; focused: root.active && root.srow == 7; hit => { root.srow = 7; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 160px; text: "Open"; icon: Icons.film; focused: root.active && root.srow == 7; clicked => { root.srow = 7; Lib.open-clips(); } }
|
||||
}
|
||||
|
||||
Section { x: root.cx; y: 984px; width: root.cw; title: "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(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(10); width: root.cw; label: "Default frame generation"; hint: "RIFE needs an NVIDIA GPU and the engine's Python environment. Auto: the engine's own setting (on)."; focused: root.active && root.srow == 10; hit => { root.srow = 10; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 96px + 8px; options: ["Auto", "Off", "RIFE"]; value <=> Prefs.framegen; changed => { root.srow = 10; root.save(); } }
|
||||
}
|
||||
Row { x: root.cx; y: root.ry(11); width: root.cw; label: "Every default setting"; hint: Prefs.defaults-note; focused: root.active && root.srow == 11; hit => { root.srow = 11; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 160px; text: "Edit"; icon: Icons.sliders; focused: root.active && root.srow == 11; clicked => { root.srow = 11; Lib.open-defaults(); } }
|
||||
}
|
||||
Section { x: root.cx; y: 1416px; width: root.cw; title: "NVIDIA"; icon: Icons.download; }
|
||||
Row { x: root.cx; y: root.ry(12); width: root.cw; label: "NVIDIA VFG and RTX VSR"; hint: Lib.nvidia-status; focused: root.active && root.srow == 12; hit => { root.srow = 12; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 200px; enabled: !Lib.nvidia-busy && (Lib.nvidia-ok || Lib.nvidia-installed);
|
||||
text: Lib.nvidia-busy ? "Working..." : Lib.nvidia-installed ? "Manage" : "Set up"; icon: Icons.download; focused: root.active && root.srow == 12;
|
||||
clicked => { root.srow = 12; Lib.nvidia-btn = Lib.nvidia-installed ? 2 : 0; Lib.nvidia-open = true; } }
|
||||
}
|
||||
Text { x: root.cx; y: 1556px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
}
|
||||
|
||||
editor := ProfileEditor {
|
||||
width: root.width; height: root.height;
|
||||
visible: Lib.editor-open && Lib.editor-defaults; opacity: self.visible ? 1 : 0;
|
||||
close => { Lib.editor-open = false; Lib.editor-typing = false; }
|
||||
refocus => { root.refocus(); }
|
||||
}
|
||||
|
||||
// ---- NVIDIA's licences, then the download: nothing is fetched until the player accepts ----
|
||||
if Lib.nvidia-open: Rectangle {
|
||||
background: Theme.p.bg.with-alpha(0.88);
|
||||
TouchArea { clicked => { Lib.nvidia-open = false; } }
|
||||
Rectangle {
|
||||
width: Math.min(root.width - 2 * Theme.pad, 820px); height: col.preferred-height;
|
||||
x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2;
|
||||
background: Theme.p.surface; border-radius: Theme.r-md; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
TouchArea { }
|
||||
col := VerticalLayout {
|
||||
padding: 28px; spacing: 14px;
|
||||
Text { text: "NVIDIA VFG AND RTX VSR"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px; }
|
||||
Text { text: Lib.nvidia-installed ? "Installed. NVIDIA VFG (frame generation) and RTX VSR (upscaling) can be picked in a game's profile and in the in-game overlay."
|
||||
: "NVIDIA VFG (AI frame generation) and RTX VSR (AI upscaling) run on NVIDIA's own runtime, which Summit can't ship. Summit downloads it for you from NVIDIA's package index (about 540 MB, an exact version checked by its hash) into your home folder."; color: Theme.p.text; font-size: Theme.t-md; wrap: word-wrap; }
|
||||
if !Lib.nvidia-installed: Text { text: "It comes under these NVIDIA licences. Read them; downloading means you accept them:"; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if !Lib.nvidia-installed: VerticalLayout { spacing: 6px;
|
||||
for l in Lib.nvidia-licences: Text { text: "• " + l; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
}
|
||||
Text { text: Lib.nvidia-status; color: Theme.p.faint; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
HorizontalLayout { alignment: end; spacing: 12px; padding-top: 8px;
|
||||
if !Lib.nvidia-installed: Btn { text: "Read the licences"; icon: Icons.link; focused: Lib.nvidia-btn == 0; clicked => { Lib.nvidia-btn = 0; Lib.nvidia-act(0); } }
|
||||
Btn { text: Lib.nvidia-installed ? "Remove it" : "I accept, download"; icon: Lib.nvidia-installed ? Icons.close : Icons.download; primary: !Lib.nvidia-installed;
|
||||
// never accepted unseen: downloading needs the licences on screen
|
||||
enabled: !Lib.nvidia-busy && (Lib.nvidia-installed || (Lib.nvidia-ok && Lib.nvidia-licences.length > 0)); focused: Lib.nvidia-btn == 1; clicked => { Lib.nvidia-btn = 1; Lib.nvidia-act(1); } }
|
||||
Btn { text: "Cancel"; focused: Lib.nvidia-btn == 2; clicked => { Lib.nvidia-btn = 2; Lib.nvidia-act(2); } }
|
||||
}
|
||||
}
|
||||
}
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,26 +60,38 @@ 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).
|
||||
// A window in the "pick the game's window" list: what it shows, and whether it opened after Play was pressed.
|
||||
export struct PickRow { title: string, detail: string, fresh: bool }
|
||||
|
||||
export struct PRow { label: string, hint: string, options: [string], value: int, kind: int, text: string, placeholder: string, own: bool }
|
||||
|
||||
// Preferences edited on the settings page (layout, theme and motion live in Theme). Rust saves them to ui.toml.
|
||||
export global Prefs {
|
||||
in-out property <int> scale: 2; // index into scales
|
||||
in property <[string]> scales: ["80%", "90%", "100%", "110%", "125%", "150%"];
|
||||
in-out property <int> replay: 2; // index into clip-lengths
|
||||
in-out property <int> replay: 3; // index into replay-options: 0 off, then clip-lengths
|
||||
in-out property <int> clip: 1;
|
||||
in property <[string]> clip-lengths: ["15 s", "30 s", "1 min", "3 min", "5 min", "10 min"];
|
||||
in-out property <int> upscaler: 0; // none, fsr, rtx-vsr
|
||||
in-out property <int> framegen: 0; // none, rife
|
||||
in property <[string]> replay-options: ["Off", "15 s", "30 s", "1 min", "3 min", "5 min", "10 min"];
|
||||
in-out property <int> overlay-key: 0; // index into overlay-keys: the key that opens the in-game overlay
|
||||
in property <[string]> overlay-keys: ["Insert", "Home", "End", "Pause", "F9", "F10"];
|
||||
in-out property <int> upscaler: 0; // auto (engine setting), none, fsr, rtx-vsr
|
||||
in-out property <int> framegen: 0; // auto (engine setting), none, rife
|
||||
in property <string> defaults-note; // the default launch profile in one line
|
||||
in property <string> file; // where the settings are stored, for display
|
||||
}
|
||||
|
||||
@@ -84,16 +122,74 @@ 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();
|
||||
// Enhance and the game's window (now playing): what the engine is doing, and picking the window by hand
|
||||
in property <bool> play-enhance; // Enhance is on for this run
|
||||
in property <string> play-window-note; // "Enhancing ULTRAKILL", "Waiting for the game's window..."
|
||||
in property <bool> play-window-wanted; // the engine is still looking: picking it helps now
|
||||
in property <bool> pick-open;
|
||||
in property <[PickRow]> pick-rows;
|
||||
in property <string> pick-note; // "Listing windows...", or why they can't be listed
|
||||
in-out property <int> pick-sel;
|
||||
// NVIDIA VFG and RTX VSR: NVIDIA's runtime (Settings); downloaded only once the player accepts NVIDIA's licences
|
||||
in property <string> nvidia-status; // "Installed", "Not installed: about 540 MB from NVIDIA", "Downloading..."
|
||||
in property <bool> nvidia-installed;
|
||||
in property <bool> nvidia-busy;
|
||||
in property <bool> nvidia-ok: true; // this PC can run it (an RTX 40/50 card)
|
||||
in property <[string]> nvidia-licences;
|
||||
in-out property <bool> nvidia-open;
|
||||
in-out property <int> nvidia-btn; // dialog: 0 read the licences, 1 accept and download (or remove), 2 cancel
|
||||
callback nvidia-act(int);
|
||||
callback pick-show();
|
||||
callback pick-choose(int);
|
||||
callback pick-close();
|
||||
}
|
||||
|
||||
// 24x24 line icons, drawn as paths so they follow the theme and scale cleanly.
|
||||
@@ -131,6 +227,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";
|
||||
}
|
||||
|
||||
@@ -254,6 +357,7 @@ export component Segmented inherits Rectangle {
|
||||
Rectangle {
|
||||
x: 4px + root.value * root.cell; y: 4px; width: root.cell; height: parent.height - 8px; border-radius: self.height / 2;
|
||||
background: @linear-gradient(100deg, Theme.p.accent 0%, Theme.p.accent2 100%);
|
||||
opacity: root.value > root.limit ? 0.3 : 1; // the whole row off (instant replay off): its pick dimmed too
|
||||
animate x { duration: Theme.ms(220); easing: Theme.ease; }
|
||||
}
|
||||
for o[i] in root.options: Rectangle {
|
||||
@@ -316,6 +420,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 +496,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;
|
||||
}
|
||||
}
|
||||
@@ -42,3 +42,23 @@ Full report with every check: [docs/WAYLAND_REPORT.md](../WAYLAND_REPORT.md) (fi
|
||||
- One focus change in one native run is not understood.
|
||||
|
||||
**Left on the desktop**: `~/summit-test` (8.9 GB). KDE's permission for X11 input injection (the owner granted it). The desktop file, the shortcut component and the ScreenCast permission that the tests created were removed. Nothing was pushed.
|
||||
|
||||
## Follow-up: install and update (asked by the owner)
|
||||
|
||||
- `install.sh` now updates an existing install:
|
||||
- it records the installed commit in `share/summit/installed-version` and rebuilds only when that changed (`--force` rebuilds anyway);
|
||||
- an update replaces the engine's files but keeps its venv and models, and reuses the venv (uv 0.13 refuses `uv venv` on an existing one, so a second run used to fail).
|
||||
- Other fixes:
|
||||
- prompts are read from `/dev/tty`, so `curl | sh` no longer reads the script as the answer;
|
||||
- Arch installs only missing packages, without `pacman -Sy`;
|
||||
- sudo is used only when the prefix isn't writable;
|
||||
- `umask 022`;
|
||||
- from ssh or a console, the session type comes from `loginctl`.
|
||||
- Checked on the owner's desktop:
|
||||
- into a scratch prefix: a fresh install (101 s), a run with nothing new (1 s), two updates to new commits (an added and a removed engine file);
|
||||
- the `curl | sh` prompt answered `n` on a real terminal.
|
||||
- Then installed for real with the README's `curl ... | sh` into `/usr/local`, with his sudo password given through a one-off askpass that was deleted afterwards:
|
||||
- **the first run went wrong because of my umask 077**: root-only folders, so the venv went into the source cache. Fixed in the installer; the folders were made readable again (only Summit's own were affected) and the misplaced venv removed;
|
||||
- the second run updated `41986c9 -> 97e7626` and put the venv in the right place;
|
||||
- `summit doctor` is all ok and the portal accepts the app id.
|
||||
- Pushed to `main` and `ap/wayland-capture` on git.molberg.cloud (asked by the owner).
|
||||
|
After Width: | Height: | Size: 577 KiB |
|
Before Width: | Height: | Size: 600 B After Width: | Height: | Size: 690 B |
|
Before Width: | Height: | Size: 919 B After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 3.7 KiB |
@@ -293,6 +293,8 @@ UNEVEN_OFF = (35, 58) # ...and outside which it switches off again
|
||||
UNEVEN_DWELL = 60 # ticks (a second) the rate has to stay there first, so a 30 fps game's 60 fps menu doesn't
|
||||
# flip it on and off
|
||||
UNEVEN_MAX_DELAY = 2.0 # ticks
|
||||
FULL_ON, FULL_OFF = 57, 52 # new frames in the last second at which a game counts as a 60 fps one (FrameTimeline.full),
|
||||
# and below which it stops counting (after UNEVEN_DWELL ticks, as for uneven)
|
||||
|
||||
# Dip smoothing (DipWatch, FrameTimeline.at_arrival): a 30 fps game that misses its slot shows a frame
|
||||
# for 3 ticks (50 ms) or, waiting for the next 30 fps slot, 4 (67 ms; Gotham Knights' hitches on PS5 Remote Play).
|
||||
@@ -401,6 +403,8 @@ class FrameTimeline:
|
||||
self._dwell = 0
|
||||
self._hz, self._j = 0, 0 # slots(): the output rate, and the next output frame's number
|
||||
self.at_arrival = False # Dip smoothing: frames timed as they arrived (set_at_arrival)
|
||||
self.full = False # a game at about 60 fps: frame generation works from 60 (the pipeline times it here)
|
||||
self._full_dwell = 0
|
||||
|
||||
def set_at_arrival(self, on: bool) -> None:
|
||||
if on == self.at_arrival:
|
||||
@@ -466,6 +470,17 @@ class FrameTimeline:
|
||||
self.uneven, self._dwell = want_on, 0
|
||||
if want_on:
|
||||
self.delay = self._want_delay()
|
||||
want_full = self.full
|
||||
if fps is not None:
|
||||
if fps >= FULL_ON:
|
||||
want_full = True
|
||||
elif fps <= FULL_OFF:
|
||||
want_full = False
|
||||
self._full_dwell = self._full_dwell + 1 if want_full != self.full else 0
|
||||
if self._full_dwell >= UNEVEN_DWELL:
|
||||
self.full, self._full_dwell = want_full, 0
|
||||
if want_full:
|
||||
self.delay = max(self.delay, self._want_delay())
|
||||
return added
|
||||
|
||||
def slots(self, hz: int) -> list[float]:
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -120,14 +120,18 @@ class Ps5SimSource:
|
||||
"""
|
||||
|
||||
def __init__(self, path: str, realtime: bool = False, hitch: float = 0.0, noise: float = 0.0,
|
||||
max_ticks: int | None = None, seed: int = 0) -> None:
|
||||
max_ticks: int | None = None, seed: int = 0, game60: bool = False) -> None:
|
||||
from .sources import source_info
|
||||
self.dec = _Decoder(path)
|
||||
self.w, self.h = self.dec.w, self.dec.h
|
||||
self.info = source_info("sim", live=realtime)
|
||||
self.realtime, self.hitch, self.max_ticks = realtime, hitch, max_ticks
|
||||
self.step = 2 if self.dec.fps > 45 else 1 # 60 fps source: drop odd frames; 30 fps: use all
|
||||
if self.step == 1:
|
||||
self.game60 = game60 # --sim60: a 60 fps file played as a 60 fps game, a new frame every tick
|
||||
if game60:
|
||||
self.step = 1
|
||||
print(f"[sim] {self.dec.fps:.2f} fps source played as a 60 fps game (no ground truth)")
|
||||
elif self.step == 1:
|
||||
print(f"[sim] {self.dec.fps:.2f} fps source: using every frame as a game frame (no ground truth)")
|
||||
self.rng = random.Random(seed)
|
||||
self.history: OrderedDict[int, np.ndarray] = OrderedDict()
|
||||
@@ -149,7 +153,7 @@ class Ps5SimSource:
|
||||
self.history.popitem(last=False)
|
||||
if i % self.step:
|
||||
continue # odd frames of a 60 fps source: the game "never rendered" these
|
||||
repeats = 3 if self.rng.random() < self.hitch else 2
|
||||
repeats = 1 if self.game60 else 3 if self.rng.random() < self.hitch else 2
|
||||
for r in range(repeats):
|
||||
if self.max_ticks is not None and tick >= self.max_ticks:
|
||||
return
|
||||
@@ -427,6 +431,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 +505,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 +536,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 +559,36 @@ 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"}
|
||||
NAMES = {"fsr": "FSR 1", "vsr": "RTX VSR", "bilinear": "bilinear", "off": "no upscaling"}
|
||||
|
||||
# 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:
|
||||
if overlay_of is not None and X11 and WAYLAND:
|
||||
# pyGLFW carries two builds of GLFW and loads its Wayland-only one in a Wayland session, which can't
|
||||
# open the XWayland window the overlay needs ("glfw init failed"): load the X11 one. Read on the first
|
||||
# `import glfw`, which is this one.
|
||||
os.environ.setdefault("PYGLFW_LIBRARY_VARIANT", "x11")
|
||||
# ...and PyOpenGL has to look functions up through GLX too: in a Wayland session it picks EGL, which
|
||||
# gives an X11 window's context no newer functions (glTexStorage2D: RTX VSR crashed the engine).
|
||||
# Read on PyOpenGL's first import, which is just below.
|
||||
if "OpenGL" not in sys.modules:
|
||||
os.environ.setdefault("PYOPENGL_PLATFORM", "glx")
|
||||
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()
|
||||
@@ -802,13 +700,13 @@ class GLWindowSink:
|
||||
self.vsr_why = why
|
||||
if why is not None and scaler == "vsr":
|
||||
print(f"[display] RTX VSR unavailable ({why})")
|
||||
self.modes = [m for m, ok in (("fsr", self.fsr), ("vsr", self._vsr_args), ("bilinear", True)) if ok]
|
||||
self.modes = [m for m, ok in (("fsr", self.fsr), ("vsr", self._vsr_args), ("bilinear", True), ("off", True)) if ok]
|
||||
self.mode = scaler if scaler in self.modes else self.modes[0]
|
||||
if self.mode == "vsr" and not self._vsr_ready():
|
||||
self.mode = self.modes[0]
|
||||
details = {"fsr": f" (sharpness {sharpness:g})", "vsr": f" (quality {vsr_quality})", "bilinear": ""}
|
||||
details = {"fsr": f" (sharpness {sharpness:g})", "vsr": f" (quality {vsr_quality})", "bilinear": "", "off": ""}
|
||||
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 +727,33 @@ 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._menu_off = (0, 0) # where the player dragged the overlay to, from where it opens (framebuffer px; kept
|
||||
# for the session, so it opens where it was left)
|
||||
self._menu_move: tuple | None = None # dragging it by its title: (cursor x, y, offset x, y) at the press
|
||||
self._cursors: dict = {} # the mouse pointers made so far (arrow, hand, move)
|
||||
self._cursor_shape = "arrow"
|
||||
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 +763,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()
|
||||
@@ -945,18 +862,53 @@ class GLWindowSink:
|
||||
self.settle_hook = None
|
||||
|
||||
def _on_mouse(self, win, x, y) -> None:
|
||||
"""Moving the mouse over the video shows the keys for a moment (not over the menu or another message)."""
|
||||
"""Moving the mouse over the video shows the keys for a moment (not over the menu or another message). Over
|
||||
the overlay: it highlights what's under it, and drags whatever was pressed (the overlay by its title, a
|
||||
slider, the scrollbar)."""
|
||||
self._cursor = (x, y)
|
||||
if self.menu.open:
|
||||
if self._menu_move is not None:
|
||||
cx, cy, ox, oy = self._menu_move
|
||||
fx, fy = self._fb_scale()
|
||||
self._menu_off = (ox + round((x - cx) * fx), oy + round((y - cy) * fy))
|
||||
self._set_cursor("move")
|
||||
return
|
||||
p = self._menu_xy()
|
||||
if p is not None:
|
||||
self.menu.hover(*p)
|
||||
inside = 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h
|
||||
self._set_cursor(self.menu.cursor(*p) if inside else "arrow")
|
||||
return
|
||||
now = time.perf_counter()
|
||||
if now >= self._hint_next and not self.menu.open and now >= self._toast_until:
|
||||
self._hint_next = now + 20.0
|
||||
self.toast(self.KEYS_HINT, 3.0 if self.hotkeys is None else 6.0)
|
||||
|
||||
def _fb_scale(self) -> tuple[float, float]:
|
||||
"""Framebuffer pixels per window coordinate (2 on a HiDPI screen)."""
|
||||
glfw = self.glfw
|
||||
ww, wh = glfw.get_window_size(self.win)
|
||||
fw, fh = glfw.get_framebuffer_size(self.win)
|
||||
return (fw / ww if ww else 1.0), (fh / wh if wh else 1.0)
|
||||
|
||||
def _set_cursor(self, shape: str) -> None:
|
||||
"""The mouse pointer over the overlay: an arrow, a hand over things to click, the move cross on its title."""
|
||||
if shape == self._cursor_shape:
|
||||
return
|
||||
glfw = self.glfw
|
||||
self._cursor_shape = shape
|
||||
std = {"hand": getattr(glfw, "POINTING_HAND_CURSOR", getattr(glfw, "HAND_CURSOR", None)),
|
||||
"move": getattr(glfw, "RESIZE_ALL_CURSOR", getattr(glfw, "HAND_CURSOR", None))}.get(shape)
|
||||
try:
|
||||
if std is None:
|
||||
glfw.set_cursor(self.win, None)
|
||||
return
|
||||
if shape not in self._cursors:
|
||||
self._cursors[shape] = glfw.create_standard_cursor(std)
|
||||
glfw.set_cursor(self.win, self._cursors[shape])
|
||||
except Exception: # noqa: BLE001 - a plain arrow then
|
||||
pass
|
||||
|
||||
def _menu_xy(self) -> tuple[float, float] | None:
|
||||
"""The mouse as a pixel of the menu's image (from its top-left), or None while the menu isn't on screen."""
|
||||
if self._menu_at is None or not self.menu.open:
|
||||
@@ -971,33 +923,40 @@ 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.RELEASE: # the end of a drag (the overlay by its title, a slider, the scrollbar)
|
||||
self._menu_move = None
|
||||
self.menu.release()
|
||||
return
|
||||
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"
|
||||
if not right:
|
||||
grabbed = self.menu.grab(*p)
|
||||
if grabbed == "move":
|
||||
self._menu_move = (*self._cursor, *self._menu_off)
|
||||
self._set_cursor("move")
|
||||
return
|
||||
if grabbed == "drag":
|
||||
return
|
||||
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 scrolls the overlay's page (or its open list); the highlight stays where it is."""
|
||||
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 +986,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 +1220,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 +1240,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 +1431,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 +1465,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 +1508,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:
|
||||
@@ -1472,6 +1532,38 @@ class GLWindowSink:
|
||||
dw, dh, x0, y0 = layout(self.fill, fw, fh, self.w, self.h) # (Fill the screen: always the same 16:9 picture)
|
||||
return fw, fh, s, dw, dh, x0, y0
|
||||
|
||||
def _output_size(self, dw: int, dh: int) -> tuple[int, int] | None:
|
||||
"""Output resolution: the size to make the picture at (its shape kept, within the size asked for), or None
|
||||
when that's the screen's own (the upscaler then draws straight to the screen)."""
|
||||
from .settings import parse_res
|
||||
want = parse_res(getattr(self.settings, "output_res", "screen"))
|
||||
if want is None or dw <= 0 or dh <= 0:
|
||||
return None
|
||||
k = min(want[0] / dw, want[1] / dh)
|
||||
ow, oh = max(2, round(dw * k)) & ~1, max(2, round(dh * k)) & ~1
|
||||
return None if abs(ow - dw) <= 2 and abs(oh - dh) <= 2 else (ow, oh)
|
||||
|
||||
def _out_target(self, w: int, h: int) -> int:
|
||||
"""The framebuffer the picture is drawn into at the output resolution (made again when the size changes)."""
|
||||
GL = self.GL
|
||||
have = getattr(self, "_out", None)
|
||||
if have is not None and have[2:] == (w, h):
|
||||
return have[1]
|
||||
if have is not None:
|
||||
GL.glDeleteFramebuffers(1, [have[1]])
|
||||
GL.glDeleteTextures([have[0]])
|
||||
tex = GL.glGenTextures(1)
|
||||
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
|
||||
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None)
|
||||
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
|
||||
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
|
||||
fbo = GL.glGenFramebuffers(1)
|
||||
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo)
|
||||
GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0)
|
||||
self._out = (tex, fbo, w, h)
|
||||
print(f"[display] output resolution {w}x{h}", flush=True)
|
||||
return fbo
|
||||
|
||||
def _panorama_on(self, fw: int, fh: int) -> bool:
|
||||
return self.fill == "panorama" and self.overlay_of is None and wider(fw, fh, self.w, self.h)
|
||||
|
||||
@@ -1480,35 +1572,41 @@ 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:
|
||||
self._menu_top = self._menu_at = self._menu_move = None
|
||||
self._set_cursor("arrow")
|
||||
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)
|
||||
top = min(y0 + dh, max(self._menu_top[0], y0 + p.h))
|
||||
mx = x0 + int(32 * ui)
|
||||
self._menu_top = (y0 + (dh + p.h) // 2, where, self.settings.overlay_corner.endswith("right"))
|
||||
ox, oy = self._menu_off # where the player dragged it (framebuffer px, y down)
|
||||
base_x = x0 + int(32 * ui) if self._menu_top[2] else max(x0, x0 + dw - p.w - int(32 * ui))
|
||||
# inside the picture whatever happens: a drag past its edge stops there (and is kept as stopped, so
|
||||
# dragging back moves it at once)
|
||||
top = min(y0 + dh, max(self._menu_top[0] - oy, y0 + p.h))
|
||||
mx = max(x0, min(base_x + ox, x0 + dw - p.w))
|
||||
self._menu_off = (mx - base_x, self._menu_top[0] - top)
|
||||
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 +1654,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())
|
||||
@@ -1609,8 +1708,23 @@ class GLWindowSink:
|
||||
self.panorama = Panorama(GL)
|
||||
target, x0, y0 = self.panorama.target(dw, dh), 0, 0
|
||||
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
|
||||
upscale = dw > self.w or dh > self.h
|
||||
# Output resolution: the upscaler makes the picture at that size, in a texture of its own, which is then
|
||||
# stretched (or shrunk: supersampling) onto the screen where the picture goes
|
||||
out_to = None
|
||||
out_size = None if pano else self._output_size(dw, dh)
|
||||
if out_size is not None:
|
||||
out_to = (target, x0, y0, dw, dh)
|
||||
target = self._out_target(*out_size)
|
||||
x0, y0, dw, dh = 0, 0, *out_size
|
||||
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
|
||||
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
|
||||
mode = self.mode
|
||||
if mode == "off" and (dw > self.w or dh > self.h):
|
||||
# Upscaling off: the picture at its own size (never enlarged), in the middle of where it would go
|
||||
k = min(1.0, dw / self.w, dh / self.h)
|
||||
ow, oh = round(self.w * k), round(self.h * k)
|
||||
x0, y0, dw, dh = x0 + (dw - ow) // 2, y0 + (dh - oh) // 2, ow, oh
|
||||
upscale = dw > self.w or dh > self.h
|
||||
if mode == "vsr" and not on_gpu: # a CPU frame: VSR needs it on the GPU
|
||||
mode = "fsr" if self.fsr is not None else "bilinear"
|
||||
ss = SUPERSAMPLE if (mode == "vsr" and not upscale) else 1.0
|
||||
@@ -1625,8 +1739,8 @@ class GLWindowSink:
|
||||
src, fbo = self.look_gl.input_target(dw, dh)
|
||||
self.fsr.draw(self.tex, self.w, self.h, fbo, 0, 0, dw, dh)
|
||||
flip_in = True # (FSR draws upright)
|
||||
elif upscale and mode == "vsr":
|
||||
src, flip_in = self._vsr_render(round(dw * ss), round(dh * ss))[0], False
|
||||
elif upscale and mode == "vsr" and self._vsr_safely(lambda: self._vsr_render(round(dw * ss), round(dh * ss))):
|
||||
src, flip_in = self.vsr_out[0], False
|
||||
else:
|
||||
src, flip_in = self.tex, False # the look's first pass resizes it
|
||||
self.look_gl.draw(plan, src, flip_in, target, x0, y0, dw, dh, True, self._frame_no)
|
||||
@@ -1635,21 +1749,32 @@ class GLWindowSink:
|
||||
elif upscale and mode == "fsr":
|
||||
self.fsr.draw(self.tex, self.w, self.h, target, x0, y0, dw, dh)
|
||||
GL.glViewport(0, 0, fw, fh)
|
||||
elif upscale and mode == "vsr":
|
||||
self._vsr_draw(x0, y0, dw, dh, ss)
|
||||
elif upscale and mode == "vsr" and self._vsr_safely(lambda: self._vsr_draw(x0, y0, dw, dh, ss)):
|
||||
pass
|
||||
else:
|
||||
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, self.fbo)
|
||||
# Image row 0 is the top; GL row 0 is the bottom, so blit with destination Y flipped.
|
||||
GL.glBlitFramebuffer(0, 0, self.w, self.h, x0, y0 + dh, x0 + dw, y0, GL.GL_COLOR_BUFFER_BIT,
|
||||
GL.GL_LINEAR)
|
||||
if out_to is not None:
|
||||
to, tx, ty, tw, th = out_to
|
||||
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, target)
|
||||
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, to)
|
||||
GL.glBlitFramebuffer(0, 0, dw, dh, tx, ty, tx + tw, ty + th, GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR)
|
||||
GL.glViewport(0, 0, fw, fh)
|
||||
label += f" at {dw}x{dh} -> {tw}x{th}"
|
||||
dw, dh = tw, th
|
||||
if pano:
|
||||
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)
|
||||
@@ -1668,6 +1793,25 @@ class GLWindowSink:
|
||||
cmd, self.cmd = self.cmd, None
|
||||
return cmd
|
||||
|
||||
def _vsr_safely(self, draw) -> bool:
|
||||
"""Runs a VSR draw. If it fails, RTX VSR is off for the rest of the session (out of the upscaler list, FSR 1
|
||||
in its place, a message saying why) and this frame is drawn without it: the game goes on either way."""
|
||||
try:
|
||||
draw()
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 - an optional upscaler never ends the session
|
||||
why = f"{type(e).__name__}: {str(e)[:160]}"
|
||||
print(f"[display] RTX VSR failed, switching to FSR 1 for this session ({why})", flush=True)
|
||||
try:
|
||||
self._vsr_target_free()
|
||||
except Exception: # noqa: BLE001 - tidying up after a failure
|
||||
pass
|
||||
self.vsr_out, self.vsr, self._vsr_args, self.vsr_why = None, None, None, f"it failed here ({why})"
|
||||
self.modes = [m for m in self.modes if m != "vsr"]
|
||||
self.mode = "fsr" if "fsr" in self.modes else self.modes[0]
|
||||
self.toast("RTX VSR stopped working, so Summit switched to FSR 1. The log says why.", 6.0)
|
||||
return False
|
||||
|
||||
def _vsr_draw(self, x0: int, y0: int, dw: int, dh: int, ss: float = 1.0) -> None:
|
||||
"""RTX VSR from the staged RGBA frame straight into a window-sized GL texture, then a 1:1 blit."""
|
||||
GL = self.GL
|
||||
@@ -1737,17 +1881,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 +1903,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 +1913,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 +2003,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 +2049,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 +2067,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
|
||||
|
||||
@@ -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))
|
||||
@@ -29,6 +29,16 @@ HUD_OFF_LEVELS = 12
|
||||
VISIBLE_LEVELS = HUD_OFF_LEVELS
|
||||
|
||||
|
||||
|
||||
def cadence_steps(hz: int) -> tuple[list[float], list[float]]:
|
||||
"""Where between two real frames of a 30 fps game the generated frames go at output rate `hz` (N = hz / 30 frames
|
||||
per real one, the frame multiplier): the first list on the real frame's own 60 Hz tick (the last of them ends
|
||||
that tick), the second on the next tick, before the real frame itself. 60: [1/2] and []; 90: [1/3, 2/3] and [];
|
||||
120: [1/4, 1/2] and [3/4]; 180: [1/6, 2/6, 3/6] and [4/6, 5/6]."""
|
||||
n = max(2, hz // 30)
|
||||
h = (n + 1) // 2
|
||||
return [j / n for j in range(1, h + 1)], [j / n for j in range(h + 1, n)]
|
||||
|
||||
def pct(share: float) -> str:
|
||||
"""0.062 -> "6.2%", 0.12 -> "12%": a share as people read it."""
|
||||
v = 100 * share
|
||||
@@ -126,10 +136,8 @@ def rate_advice(game_fps: float | None, test: bool, even: bool = False) -> str:
|
||||
if g <= 38:
|
||||
return f"Simulate is for 60 fps games. This one is at {g} fps already: turn Simulate off (menu: M)"
|
||||
return f"Simulate needs a steady 60 fps game. This one is at about {g}, so quality isn't measured"
|
||||
if g <= 38 or (even and g <= 56):
|
||||
if g <= 38 or (even and g <= 56) or g >= 55: # (a 60 fps game: frame generation works from 60)
|
||||
return ""
|
||||
if g >= 55:
|
||||
return f"Game at {g} fps: no gaps to fill. Frame generation is for 30 fps modes (Quality/Fidelity)"
|
||||
return f"Game at about {g} fps, not 30: few gaps to fill. Its 30 fps mode (Quality/Fidelity) is smoother"
|
||||
|
||||
|
||||
@@ -228,7 +236,7 @@ class Stats:
|
||||
f"{sum(b > TICK * 1000 for b in self.busy_ms)}")
|
||||
if self.quarter_shown or self.quarter_skipped:
|
||||
due = self.quarter_shown + self.quarter_skipped
|
||||
lines.append(f"extra in-between frames (90/120 Hz) shown {self.quarter_shown} of {due} "
|
||||
lines.append(f"extra in-between frames (above 60 fps) shown {self.quarter_shown} of {due} "
|
||||
f"({100 * self.quarter_shown / due:.0f}%); the rest fell back to 60 Hz because it was behind")
|
||||
if self.dedup:
|
||||
lines.append(f"dedup vs truth: {dict(self.dedup)}")
|
||||
@@ -273,7 +281,7 @@ class Stats:
|
||||
"was still busy with earlier ones")
|
||||
due = self.quarter_shown + self.quarter_skipped
|
||||
if due:
|
||||
lines.append(f"Extra frames for 90/120 fps: {100 * self.quarter_shown / due:.0f}% shown; the rest fell "
|
||||
lines.append(f"Extra frames above 60 fps: {100 * self.quarter_shown / due:.0f}% shown; the rest fell "
|
||||
"back to 60 fps because the PC was behind")
|
||||
if delay:
|
||||
lines.append(f"Delay: a real frame reached the screen {np.median(delay):.0f} ms after it arrived (median)")
|
||||
@@ -365,6 +373,7 @@ class Pipeline:
|
||||
When the pipeline is running behind, a tick skips the extra frame(s) and shows what 60 Hz would (the 1/2
|
||||
frame, or B), so it never builds a backlog.
|
||||
"""
|
||||
game60 = False # a 60 fps game (Game frame rate 60, or Auto finding one): the multiplier works from 60
|
||||
if settings is not None:
|
||||
enabled, hz = settings.interp, settings.hz if sink is not None else 60
|
||||
it, sched, st = self.interp, CadenceScheduler(), Stats(private=bool(getattr(self.interp, "private", False)))
|
||||
@@ -419,8 +428,8 @@ class Pipeline:
|
||||
at 1/3 and 2/3, where a 60 fps game has no real frame to compare against."""
|
||||
text = "TEST: 60 fps game played as 30 fps"
|
||||
q = list(zip(st.off_interp[-30:], st.off_repeat[-30:]))
|
||||
if enabled and hz == 90:
|
||||
text += " quality: measured at 60 and 120 fps"
|
||||
if enabled and cadence_steps(hz)[0][-1] != 0.5: # odd multipliers have no frame at 1/2 to score
|
||||
text += " quality: measured at even multipliers (2x, 4x...)"
|
||||
elif enabled and q:
|
||||
text += (f" quality: {pct(np.mean([x for x, _ in q]))} visibly off from the real frames"
|
||||
f" (no AI {pct(np.mean([y for _, y in q]))})")
|
||||
@@ -444,13 +453,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
|
||||
@@ -495,7 +512,8 @@ class Pipeline:
|
||||
st.stale += 1
|
||||
continue
|
||||
if settings is not None: # changed in the menu (or by a hotkey) since the last tick?
|
||||
want_hz = settings.hz if sink is not None else 60
|
||||
# The multiplier N is settings.hz / 30: N frames for each real one, so a 60 fps game shows 60 x N
|
||||
want_hz = min(600, settings.hz * (2 if game60 else 1)) if sink is not None else 60
|
||||
if want_hz != hz:
|
||||
hz, gap, quarter_due, ov_next = want_hz, 0.95 / want_hz, False, 0.0
|
||||
st.hz_used.add(hz)
|
||||
@@ -623,7 +641,7 @@ class Pipeline:
|
||||
if not extra_ok:
|
||||
st.quarter_skipped += 1
|
||||
return False
|
||||
early_cmd = present(self._generated(it.interpolate(slot, t), gpu_out), ov_text)
|
||||
early_cmd = present(self._generated(it.interpolate(slot, t), gpu_out), ov_text) or early_cmd
|
||||
st.quarter_shown += 1
|
||||
return True
|
||||
|
||||
@@ -638,8 +656,19 @@ class Pipeline:
|
||||
timeline.set_at_arrival(dipping)
|
||||
added = timeline.tick(is_new, is_cut, tick.frame, tick.t_arrival)
|
||||
was_timed = timed
|
||||
timed = dipping or (timeline.uneven and sink is not None and gt_fn is None
|
||||
and (settings is None or getattr(settings, "even_out", True)))
|
||||
# A 60 fps game: on the timeline too (each frame timed as it came, a frame of delay), which draws
|
||||
# in-between frames at any output rate; the 60 Hz beat alone would only show its own frames.
|
||||
was_60 = game60
|
||||
game_fps = getattr(settings, "game_fps", "auto") if settings is not None else "auto"
|
||||
game60 = (sink is not None and gt_fn is None
|
||||
and (game_fps == "60" or (game_fps == "auto" and timeline.full)))
|
||||
if game60 != was_60:
|
||||
print(f"[pipeline] {'60 fps game: frame generation works from 60' if game60 else 'game no longer at 60 fps'}")
|
||||
if game60 and hasattr(sink, "toast") and "60" not in toasted:
|
||||
toasted.add("60")
|
||||
sink.toast("Game at 60 fps: the frame multiplier works from 60 (2x is 120 fps)", 6.0)
|
||||
timed = dipping or (sink is not None and gt_fn is None and (
|
||||
game60 or (timeline.uneven and (settings is None or getattr(settings, "even_out", True)))))
|
||||
if timed != was_timed:
|
||||
if timed and dipping:
|
||||
unshown = None
|
||||
@@ -648,6 +677,8 @@ class Pipeline:
|
||||
toasted.add("dips")
|
||||
sink.toast("Game dipping below 30 fps: Summit is spacing its frames by when they "
|
||||
"arrived (Dip smoothing)", 6.0)
|
||||
elif timed and game60:
|
||||
unshown = None # (said above)
|
||||
elif timed:
|
||||
unshown = None
|
||||
print(f"[pipeline] game at about {timeline.fps()} fps: evening out its frames")
|
||||
@@ -692,12 +723,20 @@ class Pipeline:
|
||||
else:
|
||||
out, reached = frame, pl.reached
|
||||
action = Action.INTERP if pl.b is not None else Action.CURRENT
|
||||
elif hz == 120 and action is Action.INTERP:
|
||||
show_early(0.25)
|
||||
elif hz == 120 and quarter_due and action is Action.CURRENT and not is_new:
|
||||
show_early(0.75)
|
||||
elif hz == 90 and action is Action.INTERP and show_early(1 / 3):
|
||||
mid_t = 2 / 3
|
||||
elif hz > 60 and action is Action.INTERP:
|
||||
# N frames for each real one (N = hz / 30): its own tick shows 1/N .. h/N, the next tick the
|
||||
# rest and then the real frame (cadence_steps). Behind: the rest of them are left out, and the
|
||||
# tick ends on the 60 fps frame (1/2).
|
||||
first = cadence_steps(hz)[0]
|
||||
for t in first[:-1]:
|
||||
if not show_early(t):
|
||||
break
|
||||
else:
|
||||
mid_t = first[-1]
|
||||
elif hz > 60 and quarter_due and action is Action.CURRENT and not is_new:
|
||||
for t in cadence_steps(hz)[1]:
|
||||
if not show_early(t):
|
||||
break
|
||||
quarter_due = action is Action.INTERP
|
||||
if timed:
|
||||
pass # shown above
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -88,8 +88,8 @@ def vfx_reason() -> str | None:
|
||||
return ("it comes with NVIDIA VFG's download from NVIDIA, which SmoovPlay offers on RTX 40 and 50 series "
|
||||
"cards. AMD FSR 1 works on any card")
|
||||
if not installed():
|
||||
return ("it comes with NVIDIA VFG's download from NVIDIA: set up NVIDIA VFG on SmoovPlay's Settings page "
|
||||
"(Interpolation model). AMD FSR 1 works on any card")
|
||||
return ("it comes with NVIDIA's VFG download: Summit's Settings, NVIDIA VFG and RTX VSR, downloads it "
|
||||
"(or `summit nvidia install`). AMD FSR 1 works on any card")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ offers "Restart now" when any are pending.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
@@ -30,7 +32,9 @@ class Spec:
|
||||
live: bool = True # applies immediately; False = on the next restart
|
||||
help: str = ""
|
||||
saved: bool = True # False: this session only, never written to the settings file (e.g. test modes)
|
||||
group: str = "" # section on the launcher's Settings page; SPECS lists each section's rows together
|
||||
group: str = "" # section on the launcher's Settings page and tab of the in-game overlay; SPECS lists each
|
||||
# section's rows together
|
||||
sub: str = "" # a heading inside its section (the overlay draws one where it changes)
|
||||
quick: bool = False # one of the few big choices at the top of the launcher's Settings page
|
||||
applies: tuple = () # (key, values): only used, and only shown, while setting `key` is one of `values`
|
||||
later: str = "" # a note at the end of the launcher's dropdown, about choices that aren't offered yet
|
||||
@@ -45,8 +49,18 @@ class Spec:
|
||||
elsewhere: dict = field(default_factory=dict) # source kind -> why it isn't used there ("": any other source)
|
||||
|
||||
def name(self, value: Any) -> str:
|
||||
if self.key == "hz" and value not in self.names and valid_hz(value): # a custom multiplier
|
||||
return f"{value // 30}x"
|
||||
if self.key == "output_res" and value not in self.names and parse_res(value): # a custom size
|
||||
w, h = parse_res(value)
|
||||
return f"{w} x {h}"
|
||||
return self.names.get(value, str(value))
|
||||
|
||||
def accepts(self, value: Any) -> bool:
|
||||
"""One of the choices, or (Frame multiplier) any multiple of 30 fps that valid_hz takes."""
|
||||
return (value in self.choices or (self.key == "hz" and valid_hz(value))
|
||||
or (self.key == "output_res" and parse_res(value) is not None))
|
||||
|
||||
def applies_to(self, values: dict) -> bool:
|
||||
"""Whether this setting is used with these values (e.g. VFG quality only while NVIDIA VFG is picked)."""
|
||||
return not self.applies or values.get(self.applies[0]) in self.applies[1]
|
||||
@@ -58,6 +72,28 @@ class Spec:
|
||||
return self.elsewhere.get(source) or self.elsewhere.get("") or "Not used with this source."
|
||||
|
||||
|
||||
OUTPUT_SIZES = ("screen", "1280x720", "1600x900", "1920x1080", "2560x1440", "3200x1800", "3840x2160")
|
||||
OUTPUT_NAMES = {"screen": "Same as the screen", "1280x720": "720p", "1600x900": "900p", "1920x1080": "1080p",
|
||||
"2560x1440": "1440p", "3200x1800": "1800p", "3840x2160": "4K"}
|
||||
|
||||
|
||||
def parse_res(value) -> tuple[int, int] | None:
|
||||
""" "2560x1440" -> (2560, 1440); None for "screen" or anything that isn't a sensible size."""
|
||||
m = re.fullmatch(r"\s*(\d{3,5})\s*[xX×]\s*(\d{3,5})\s*", value) if isinstance(value, str) else None
|
||||
if not m:
|
||||
return None
|
||||
w, h = int(m.group(1)), int(m.group(2))
|
||||
return (w, h) if 320 <= w <= 7680 and 240 <= h <= 4320 else None
|
||||
|
||||
|
||||
HZ_MIN, HZ_MAX = 60, 300 # Frame multiplier 2x .. 10x (of a 30 fps game)
|
||||
|
||||
|
||||
def valid_hz(value: Any) -> bool:
|
||||
"""An output rate the pipeline can show: a whole multiplier (2x to 10x) of a 30 fps game."""
|
||||
return isinstance(value, int) and not isinstance(value, bool) and HZ_MIN <= value <= HZ_MAX and value % 30 == 0
|
||||
|
||||
|
||||
ON_OFF = {True: "On", False: "Off"}
|
||||
OPACITY = (1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3) # menu and stats opacity choices
|
||||
PCT = {v: f"{round(v * 100)}%" for v in OPACITY}
|
||||
@@ -74,19 +110,28 @@ SPECS: tuple[Spec, ...] = (
|
||||
hints={False: "No new frames: the stream exactly as the game sends it, with the least delay."},
|
||||
impact={"picture": "Smoother motion. Small, fast details can wobble a little.",
|
||||
"speed": "Adds delay: about 20 ms at 60 fps, about 40 ms at 90 or 120 fps."},
|
||||
help="Draws new frames between the ones the game sends, so a 30 fps game moves like 60, 90 or 120 fps. "
|
||||
help="Draws new frames between the ones the game sends: a 30 fps game moves like 60 fps or more, a 60 fps "
|
||||
"game like 120 or more (Frame multiplier). "
|
||||
"Off shows the stream exactly as it arrives. In the video window, I turns it off and on for this "
|
||||
"session only, to compare."),
|
||||
Spec("hz", "Output frame rate", (60, 90, 120), 60, {60: "60 fps", 90: "90 fps", 120: "120 fps"},
|
||||
# Frame generation's multiplier: N frames shown for each real frame of a 30 fps game, so N x 30 fps out (the value
|
||||
# is that rate). Any multiple of 30 from 60 to 300 works (HZ_MIN..HZ_MAX: `--hz`, a game's Summit profile); the
|
||||
# menu steps through these.
|
||||
Spec("hz", "Frame multiplier", (60, 90, 120, 150, 180, 240), 60,
|
||||
{hz: f"{hz // 30}x" for hz in (60, 90, 120, 150, 180, 240)},
|
||||
group="Smoothness", quick=True,
|
||||
hints={60: "One new frame for each real one. Any supported graphics card, any display. Adds about 20\u00a0ms of delay.",
|
||||
90: "Two new frames for each real one. Needs a 90\u00a0Hz or faster display. Adds about 40\u00a0ms of "
|
||||
"delay.",
|
||||
120: "Three for each real one. Needs a 120\u00a0Hz display and a fast card. Adds about 40\u00a0ms of "
|
||||
"delay."},
|
||||
help="How many frames you see each second. Higher is smoother, but needs a faster graphics card and a "
|
||||
"display that runs at least that fast (G-Sync or FreeSync helps). Auto-detect, on SmoovPlay's "
|
||||
"Settings page, picks the most this PC keeps up with."),
|
||||
"delay.",
|
||||
150: "Four for each real one. Needs a 144\u00a0Hz or faster display and a fast card.",
|
||||
180: "Five for each real one. Needs a 180\u00a0Hz or faster display and a very fast card.",
|
||||
240: "Seven for each real one. Needs a 240\u00a0Hz display and a very fast card."},
|
||||
help="How many frames you see for each one the game draws: 2x makes a 30 fps game 60 fps and a 60 fps game "
|
||||
"120 fps; 4x makes them 120 and 240. "
|
||||
"Higher is smoother, but needs a faster graphics card and a display that runs at least that fast "
|
||||
"(G-Sync or FreeSync helps). When the card can't keep up, the extra frames are left out for a moment."),
|
||||
# framegen/cadence.py FrameTimeline. Tried on simulated 40-55 fps games (tests/test_timeline.py), not a real one yet.
|
||||
Spec("even_out", "Even out 40-60 fps", (True, False), True, ON_OFF, group="Smoothness",
|
||||
applies=("interp", (True,)),
|
||||
@@ -98,14 +143,17 @@ SPECS: tuple[Spec, ...] = (
|
||||
"speed": "About one frame (17 ms) more delay than showing their frames as they come."}),
|
||||
# framegen/cadence.py RhythmLock. Auto reads the game's frame rate from the stream (sizes, the picture), which a
|
||||
# still or dark scene can fool (Gotham Knights, locked at 30, read as 38-47 fps on PS5 Remote Play).
|
||||
Spec("game_fps", "Game frame rate", ("auto", "30"), "auto", {"auto": "Auto", "30": "30 fps"}, group="Smoothness",
|
||||
Spec("game_fps", "Game frame rate", ("auto", "30", "60"), "auto", {"auto": "Auto", "30": "30 fps", "60": "60 fps"},
|
||||
group="Frame generation", sub="Basics", quick=True,
|
||||
applies=("interp", (True,)),
|
||||
hints={"auto": "SmoovPlay works out the game's frame rate as it plays. The default.",
|
||||
"30": "For a game locked at 30\u00a0fps. Every other frame is taken as new, so nothing can misread it."},
|
||||
help="Auto works out the game's frame rate from the stream as it plays. A still or dark scene can fool it "
|
||||
"into reading a 30 fps game as 40 or more, which makes motion uneven. If you know the game is locked "
|
||||
"at 30 fps (most console quality modes), pick 30 fps: every other frame is taken as new, so motion "
|
||||
"stays even. Menus that run at 60 fps look a little less smooth with it.",
|
||||
hints={"auto": "Summit works out the game's frame rate as it plays. The default.",
|
||||
"30": "For a game locked at 30\u00a0fps. Every other frame is taken as new, so nothing can misread it.",
|
||||
"60": "For a game locked at 60\u00a0fps: the multiplier works from 60, so 2x is 120\u00a0fps."},
|
||||
help="Auto works out the game's frame rate from the stream as it plays (a game at about 60 fps is taken as one "
|
||||
"after a second there). A still or dark scene can fool it into reading a 30 fps game as 40 or more, "
|
||||
"which makes motion uneven. If you know the game is locked at 30 fps (most console quality modes), pick "
|
||||
"30 fps: every other frame is taken as new. A game locked at 60 fps: pick 60 fps, and the multiplier "
|
||||
"works from 60 (2x is 120 fps, 3x 180), with very little extra delay.",
|
||||
impact={"picture": "Even motion in a game locked at 30 fps, whatever the scene.",
|
||||
"speed": "None. At most one frame (17 ms) later for a moment after the game stutters."}),
|
||||
# framegen/cadence.py DipWatch + FrameTimeline.at_arrival. Tried on simulated 30 fps games that hold frames for 3 or
|
||||
@@ -170,13 +218,14 @@ SPECS: tuple[Spec, ...] = (
|
||||
"1440p capture at 90, a quarter for a 4K capture, and Full otherwise. Only used with RIFE.",
|
||||
impact={"picture": "Half is a little softer on small, fast details.",
|
||||
"speed": "Half takes about 40% less time per AI frame."}),
|
||||
Spec("scaler", "Upscaler", ("fsr", "vsr", "bilinear"), "fsr",
|
||||
{"fsr": "AMD FSR 1", "vsr": "NVIDIA RTX VSR", "bilinear": "Bilinear"}, group="Picture", quick=True,
|
||||
Spec("scaler", "Upscaler", ("off", "fsr", "vsr", "bilinear"), "fsr",
|
||||
{"off": "Off", "fsr": "AMD FSR 1", "vsr": "NVIDIA RTX VSR", "bilinear": "Bilinear"}, group="Picture", quick=True,
|
||||
later="Support for other upscalers may come in a later version.",
|
||||
hints={"fsr": "Sharp and almost free: about 0.1\u00a0ms a frame. Recommended.",
|
||||
"vsr": "NVIDIA's AI upscaler, Experimental. It comes with NVIDIA VFG's download (RTX 40 and 50 "
|
||||
"series); without it, FSR\u00a01 is used. Heavier.",
|
||||
"bilinear": "Plain resizing, the softest. For comparison."},
|
||||
"bilinear": "Plain resizing, the softest. For comparison.",
|
||||
"off": "No upscaling: the picture at its own size, in the middle of the screen. Never enlarged."},
|
||||
help="Enlarges the picture from the game (usually 1080p) to fill your window or screen, so it only "
|
||||
"matters when that's bigger than 1080p, like a 1440p or 4K display. Key: U.",
|
||||
impact={"picture": "Only matters on a display bigger than the stream, like 1440p or 4K.",
|
||||
@@ -199,6 +248,19 @@ SPECS: tuple[Spec, ...] = (
|
||||
"speed": "Each step up asks more of the GPU."}),
|
||||
# framegen/hdr.py. Off by default, and then nothing changes: an HDR stream comes out washed out, and SmoovPlay says
|
||||
# so. "hdr10" needs the DXGI presentation (NVIDIA) and Windows' HDR; without them run.py uses "sdr" for the session.
|
||||
# framegen/io.py: the picture is upscaled to this size, then fitted to the window or screen (Fill the screen)
|
||||
Spec("output_res", "Output resolution", OUTPUT_SIZES, "screen", OUTPUT_NAMES, group="Upscaling", sub="Output", quick=True,
|
||||
hints={"screen": "The upscaler works straight to the screen's (or window's) size. The default.",
|
||||
"1920x1080": "Upscaled to 1080p, then shown on the screen. Lighter on a 1440p or 4K screen.",
|
||||
"2560x1440": "Upscaled to 1440p, then shown on the screen.",
|
||||
"3840x2160": "Upscaled to 4K, then shown on the screen: on a smaller screen this sharpens (supersampling)."},
|
||||
help="The size the upscaler makes the picture, whatever the screen's size. Same as the screen: it upscales "
|
||||
"straight to it. A smaller size is lighter for the graphics card (RTX VSR especially) and is then "
|
||||
"stretched to the screen; a bigger one is supersampling, shrunk to the screen afterwards, which looks "
|
||||
"sharper. The picture keeps its shape either way. Any size can be given on the command line "
|
||||
"(--output-res 2560x1080) or in Summit's game profile.",
|
||||
impact={"picture": "Smaller: softer. Bigger than the screen: sharper (supersampling).",
|
||||
"speed": "The upscaler's cost grows with the size: RTX VSR at 4K costs about 4x what it does at 1080p."}),
|
||||
Spec("hdr", "HDR", ("off", "sdr", "hdr10"), "off",
|
||||
{"off": "Off", "sdr": "On, shown in SDR", "hdr10": "On, HDR output"}, live=False,
|
||||
group="Picture", experimental=True,
|
||||
@@ -379,6 +441,39 @@ SPECS: tuple[Spec, ...] = (
|
||||
"60 and 120 fps each AI frame is also scored against the real frame it replaced. This session "
|
||||
"only."),
|
||||
)
|
||||
# Where each setting goes: (tab, heading, keys in order). The in-game overlay draws a tab for each, with the
|
||||
# headings inside; the launcher's Settings page uses the tabs as its sections. A setting not listed keeps its own.
|
||||
LAYOUT: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||||
("Frame generation", "Basics", ("interp", "hz", "game_fps")),
|
||||
("Frame generation", "AI model", ("model", "vfg_quality", "motion", "engine")),
|
||||
("Frame generation", "Smoothing", ("even_out", "even_dips", "steady_hud")),
|
||||
("Upscaling", "Upscaler", ("scaler", "fsr_sharpness", "vsr_quality")),
|
||||
("Upscaling", "Output", ("output_res", "fill")),
|
||||
("Display", "Window", ("fullscreen", "vsync", "present")),
|
||||
("Display", "Colour and look", ("hdr", "look_on", "look")),
|
||||
("Overlay", "Stats", ("overlay", "overlay_style", "overlay_corner", "overlay_scale", "overlay_opacity")),
|
||||
("Overlay", "Graphs", ("graph_frametime", "graph_pipeline", "graph_delay", "graph_gpu")),
|
||||
("Overlay", "This menu", ("ui_scale", "ui_opacity")),
|
||||
("Overlay", "Branding", ("watermark",)),
|
||||
("Clips", "Instant replay", ("replay", "replay_clip")),
|
||||
("Clips", "Saved clips", ("replay_save", "replay_layout", "look_clips")),
|
||||
("Sources", "Capture card", ("capture_size",)),
|
||||
("Sources", "PS5 Remote Play", ("minimize_chiaki", "audio_sync")),
|
||||
("Sources", "Testing", ("simulate_30",)),
|
||||
)
|
||||
|
||||
|
||||
def _laid_out(specs: tuple[Spec, ...]) -> tuple[Spec, ...]:
|
||||
from dataclasses import replace
|
||||
by = {s.key: s for s in specs}
|
||||
out: list[Spec] = []
|
||||
for group, sub, keys in LAYOUT:
|
||||
out.extend(replace(by[k], group=group, sub=sub) for k in keys if k in by)
|
||||
placed = {s.key for s in out}
|
||||
return tuple(out) + tuple(s for s in specs if s.key not in placed)
|
||||
|
||||
|
||||
SPECS = _laid_out(SPECS)
|
||||
BY_KEY = {s.key: s for s in SPECS}
|
||||
|
||||
|
||||
@@ -392,7 +487,7 @@ class Settings:
|
||||
self._v = {s.key: s.default for s in SPECS}
|
||||
self._saved = dict(self._v) # what the file holds (or would)
|
||||
for k, v in (values or {}).items():
|
||||
if k in BY_KEY and BY_KEY[k].saved and v in BY_KEY[k].choices:
|
||||
if k in BY_KEY and BY_KEY[k].saved and BY_KEY[k].accepts(v):
|
||||
self._v[k] = self._saved[k] = v
|
||||
|
||||
@classmethod
|
||||
@@ -425,7 +520,7 @@ class Settings:
|
||||
self._put(key, value, save=True)
|
||||
|
||||
def _put(self, key: str, value: Any, save: bool) -> None:
|
||||
if value not in BY_KEY[key].choices:
|
||||
if not BY_KEY[key].accepts(value):
|
||||
raise ValueError(f"{key}: {value!r} is not one of {BY_KEY[key].choices}")
|
||||
changed = self._v[key] != value
|
||||
self._v[key] = value
|
||||
@@ -439,7 +534,12 @@ class Settings:
|
||||
def step(self, key: str, delta: int, allowed=None) -> Any:
|
||||
"""Move to the next/previous choice (wrapping), skipping values `allowed(key, value)` rejects."""
|
||||
choices = BY_KEY[key].choices
|
||||
i = choices.index(self._v[key])
|
||||
cur = self._v[key]
|
||||
if cur in choices:
|
||||
i = choices.index(cur)
|
||||
else: # a custom value (Frame multiplier): step from where it falls among the choices
|
||||
below = [j for j, c in enumerate(choices) if c < cur]
|
||||
i = (below[-1] + (1 if delta < 0 else 0)) if below else (len(choices) if delta < 0 else -1)
|
||||
for _ in range(len(choices)):
|
||||
i = (i + delta) % len(choices)
|
||||
if allowed is None or allowed(key, choices[i]):
|
||||
|
||||
@@ -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 "
|
||||
|
||||
@@ -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
|
||||
@@ -20,7 +20,8 @@ import torch
|
||||
from .vfg_setup import MIN_COMPUTE, add_to_path, installed
|
||||
|
||||
QUALITY = {"low": 0, "medium": 1, "high": 2}
|
||||
NOT_SET_UP = "NVIDIA VFG isn't set up on this PC. SmoovPlay's Settings page downloads it from NVIDIA."
|
||||
NOT_SET_UP = ("NVIDIA VFG isn't set up on this PC. Summit's Settings (NVIDIA VFG and RTX VSR) downloads it from "
|
||||
"NVIDIA, or `summit nvidia install`.")
|
||||
|
||||
|
||||
def import_vfx():
|
||||
|
||||
@@ -111,6 +111,19 @@ def status(folder: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def has_pip() -> bool:
|
||||
return importlib.util.find_spec("pip") is not None
|
||||
|
||||
|
||||
def find_uv() -> str | None:
|
||||
"""uv, which made Summit's venv (install.sh): on PATH, or where its installer puts it."""
|
||||
home = Path.home()
|
||||
for c in (shutil.which("uv"), home / ".local/bin/uv", home / ".cargo/bin/uv"):
|
||||
if c and Path(c).is_file() and os.access(c, os.X_OK):
|
||||
return str(c)
|
||||
return None
|
||||
|
||||
|
||||
def install(folder: str, proxy: str = "") -> int:
|
||||
"""Download and install the pinned package into `folder` (replacing an earlier install of ours). pip's output
|
||||
goes to stdout as it comes (--progress-bar raw: "Progress <bytes> of <total>" lines for the launcher)."""
|
||||
@@ -135,16 +148,22 @@ def install(folder: str, proxy: str = "") -> int:
|
||||
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
|
||||
req = Path(tmp) / "vfg-requirements.txt"
|
||||
req.write_text(f"{PACKAGE}=={VERSION} --hash=sha256:{WHEEL_SHA256}\n", encoding="utf-8")
|
||||
cmd = [sys.executable, "-m", "pip", "install", "--target", str(staging), "--only-binary", ":all:",
|
||||
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache-dir", "--progress-bar", "raw",
|
||||
"--disable-pip-version-check", "--no-warn-script-location", "-r", str(req)]
|
||||
uv = None if has_pip() else find_uv()
|
||||
if uv: # a venv made by uv has no pip: uv installs the same pinned file, hash checked the same way
|
||||
cmd = [uv, "pip", "install", "--python", sys.executable, "--target", str(staging), "--only-binary", ":all:",
|
||||
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache", "-r", str(req)]
|
||||
else:
|
||||
cmd = [sys.executable, "-m", "pip", "install", "--target", str(staging), "--only-binary", ":all:",
|
||||
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache-dir", "--progress-bar", "raw",
|
||||
"--disable-pip-version-check", "--no-warn-script-location", "-r", str(req)]
|
||||
if proxy:
|
||||
cmd += ["--proxy", proxy]
|
||||
cmd += ["--proxy", proxy] if not uv else []
|
||||
env = dict(os.environ, **({"HTTPS_PROXY": proxy, "HTTP_PROXY": proxy} if proxy and uv else {}))
|
||||
print(f"[vfg] downloading {PACKAGE} {VERSION} from {INDEX} (about {SIZE_MB} MB)", flush=True)
|
||||
rc = subprocess.run(cmd).returncode
|
||||
rc = subprocess.run(cmd, env=env).returncode
|
||||
if rc != 0:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
print(f"[vfg] pip failed (exit code {rc})")
|
||||
print(f"[vfg] {'uv' if uv else 'pip'} failed (exit code {rc})")
|
||||
return rc
|
||||
# Check it loads, in another process: a loaded DLL would keep the folder from being renamed or removed.
|
||||
check = subprocess.run([sys.executable, "-c", f"import sys; sys.path.append({str(staging)!r}); import nvvfx"],
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -315,7 +315,7 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.enviro
|
||||
Wayland one KWin knows (the portal), waiting up to wait_s for either. Without KWin, a window that isn't an
|
||||
XWayland one can't be looked for: after the wait the portal's dialog lets the user pick it."""
|
||||
from . import kwin
|
||||
from .window_x11 import X, X11WindowSource, find_windows, session_problem
|
||||
from .window_x11 import LiveQuery, X, X11WindowSource, find_windows, session_problem, waiting_line
|
||||
x = X() if session_problem(env) is None else None
|
||||
kw = None
|
||||
if kwin.available(env):
|
||||
@@ -324,7 +324,11 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.enviro
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[window] can't ask KWin for its windows ({str(e)[:120]})")
|
||||
deadline, said = time.monotonic() + wait_s, False
|
||||
live = LiveQuery(query, env)
|
||||
while True:
|
||||
before, query = live.now, live.get()
|
||||
if query != before:
|
||||
deadline = time.monotonic() + max(wait_s, 60.0) # a rule picked late still gets its time
|
||||
if x is not None:
|
||||
target = pick(query, find_windows(x))
|
||||
if target is not None:
|
||||
@@ -358,7 +362,7 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.enviro
|
||||
raise RuntimeError(f"no window matches {query!r}" + (f" after {wait_s:.0f} s" if wait_s else ""))
|
||||
if not said:
|
||||
said = True
|
||||
print(f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)", flush=True)
|
||||
print(waiting_line(query, wait_s), flush=True)
|
||||
sleep(0.5)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
|
||||
How it works:
|
||||
- The window is picked by part of its title, "class:NAME" (its WM_CLASS), "pid:N" (the process that owns it, or one it
|
||||
started), or "xid:N" (its X window id; "hwnd:N" means the same). Windows come from the window manager's list
|
||||
started), "dir:FOLDER" (a process running from the game's folder: games started through Steam, Lutris or Heroic), or
|
||||
"xid:N" (its X window id; "hwnd:N" means the same). Windows come from the window manager's list
|
||||
(_NET_CLIENT_LIST), read with Xlib through ctypes: no extra package.
|
||||
- The window is redirected off screen with the Composite extension (XCompositeRedirectWindow, automatic: the X server
|
||||
still paints it as before), so its own picture can be read even while another window covers it. That is what lets
|
||||
@@ -91,13 +92,53 @@ def pid_family(pid: int, proc: str = "/proc") -> set[int]:
|
||||
return family
|
||||
|
||||
|
||||
def pick(query: str, windows: list[XWindow], family=pid_family) -> XWindow | None:
|
||||
"""The window `query` names: "xid:N" (or "hwnd:N"), "pid:N", "class:NAME" (or "exe:NAME"), or part of a title.
|
||||
Of several matches, the biggest. Several queries split by "|" are tried in turn."""
|
||||
def _norm_path(p: str) -> str:
|
||||
"""A path to compare by: "/" separators, lower case, no trailing "/". Wine's "Z:\\games\\x.exe" (drive Z: is the
|
||||
Linux root) becomes "/games/x.exe"."""
|
||||
p = p.strip().strip('"').replace("\\", "/")
|
||||
if len(p) > 2 and p[1] == ":" and p[0].lower() == "z":
|
||||
p = p[2:]
|
||||
return p.rstrip("/").lower()
|
||||
|
||||
|
||||
def under(path: str, folder: str) -> bool:
|
||||
"""Whether `path` is `folder` or inside it (Wine paths count, case is ignored: Wine's paths don't keep it)."""
|
||||
p, f = _norm_path(path), _norm_path(folder)
|
||||
return bool(f) and (p == f or p.startswith(f + "/"))
|
||||
|
||||
|
||||
def pid_in_dir(pid: int, folder: str, proc: str = "/proc") -> bool:
|
||||
"""Whether process `pid` belongs to the game in `folder`: it runs from there (its working directory or its
|
||||
program is in it) or was started with a file in it (a Wine game's command line names its .exe, often as
|
||||
"Z:\\..."). Steam, Lutris and Heroic all start a game in its own folder, so this finds a game they started
|
||||
without knowing its window class or process in advance."""
|
||||
if pid <= 0:
|
||||
return False
|
||||
base = os.path.join(proc, str(pid))
|
||||
for link in ("cwd", "exe"):
|
||||
try:
|
||||
if under(os.readlink(os.path.join(base, link)), folder):
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
with open(os.path.join(base, "cmdline"), "rb") as f:
|
||||
args = f.read().decode(errors="replace").split("\0")
|
||||
except OSError:
|
||||
return False
|
||||
return any(a and under(a, folder) for a in args)
|
||||
|
||||
|
||||
def pick(query: str, windows: list[XWindow], family=pid_family, in_dir=pid_in_dir) -> XWindow | None:
|
||||
"""The window `query` names: "xid:N" (or "hwnd:N"), "pid:N", "class:NAME" (or "exe:NAME"), "dir:FOLDER" (a
|
||||
process running from that folder, see pid_in_dir), or part of a title. Of several matches, the biggest. Several
|
||||
queries split by "|" are tried in turn."""
|
||||
if "|" in query:
|
||||
return next((w for q in query.split("|") if q.strip() and (w := pick(q, windows, family))), None)
|
||||
return next((w for q in query.split("|") if q.strip() and (w := pick(q, windows, family, in_dir))), None)
|
||||
q = query.strip()
|
||||
low = q.lower()
|
||||
if not q or low.startswith("ask:"): # "ask:": no rule yet, the window is picked in Summit (live_query)
|
||||
return None
|
||||
try:
|
||||
if low.startswith(("xid:", "hwnd:")):
|
||||
xid = int(q.split(":", 1)[1], 0)
|
||||
@@ -105,6 +146,9 @@ def pick(query: str, windows: list[XWindow], family=pid_family) -> XWindow | Non
|
||||
if low.startswith("pid:"):
|
||||
pids = family(int(q[4:]))
|
||||
matches = [w for w in windows if w.pid in pids]
|
||||
elif low.startswith("dir:"):
|
||||
folder = q[4:].strip()
|
||||
matches = [w for w in windows if folder and in_dir(w.pid, folder)]
|
||||
elif low.startswith(("class:", "exe:")):
|
||||
name = low.split(":", 1)[1].strip()
|
||||
matches = [w for w in windows if w.cls == name]
|
||||
@@ -470,6 +514,36 @@ class X11WindowSource:
|
||||
f"{self.restarts} time(s) for a resize")
|
||||
|
||||
|
||||
class LiveQuery:
|
||||
"""The --window rule while the engine waits for the game's window, which the player can change from Summit's
|
||||
launcher: `summit run` names a file in SUMMIT_WINDOW_FILE, and the launcher writes the rule of the window picked
|
||||
there into it (and saves it in the game's profile). Read on every look; a new rule restarts the wait."""
|
||||
|
||||
def __init__(self, query: str, env=os.environ) -> None:
|
||||
self.base, self.path, self.now = query, env.get("SUMMIT_WINDOW_FILE") or "", query
|
||||
|
||||
def get(self) -> str:
|
||||
"""The rule now; when it changed, says so (the launcher reads that line)."""
|
||||
q = self.base
|
||||
if self.path:
|
||||
try:
|
||||
with open(self.path, encoding="utf-8") as f:
|
||||
q = f.read().strip() or self.base
|
||||
except OSError:
|
||||
pass
|
||||
if q != self.now:
|
||||
self.now = q
|
||||
print(f"[window] now looking for {q!r} (picked in Summit)", flush=True)
|
||||
return q
|
||||
|
||||
|
||||
def waiting_line(query: str, wait_s: float) -> str:
|
||||
"""What the engine says while it waits; Summit's launcher looks for "[window] waiting for"."""
|
||||
if not query.strip() or query.strip().lower().startswith("ask:"):
|
||||
return f"[window] waiting for the game's window to be picked in Summit (up to {wait_s:.0f} s)"
|
||||
return f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)"
|
||||
|
||||
|
||||
def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowSource:
|
||||
"""--window QUERY: the window, waiting up to wait_s for it to open (a game that was just started), or a clear
|
||||
error naming what was looked for."""
|
||||
@@ -479,7 +553,11 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowS
|
||||
x = X()
|
||||
deadline = time.monotonic() + wait_s
|
||||
said = False
|
||||
live = LiveQuery(query)
|
||||
while True:
|
||||
before, query = live.now, live.get()
|
||||
if query != before:
|
||||
deadline = time.monotonic() + max(wait_s, 60.0) # a rule picked late still gets its time
|
||||
target = pick(query, find_windows(x))
|
||||
if target is not None:
|
||||
if wait_s: # a game's window often opens small (a splash) and grows: give it a moment to settle
|
||||
@@ -492,7 +570,7 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowS
|
||||
+ " (python -m framegen.window_x11 --list shows what's found)")
|
||||
if not said:
|
||||
said = True
|
||||
print(f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)", flush=True)
|
||||
print(waiting_line(query, wait_s), flush=True)
|
||||
sleep(0.25)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -63,7 +63,7 @@ from framegen.interpolator import MODELS, RifeInterpolator
|
||||
from framegen.io import (TICK, CaptureSource, FileSink, FileSource, GLWindowSink, MultiSink, Ps5SimSource,
|
||||
WindowSink)
|
||||
from framegen.pipeline import Pipeline
|
||||
from framegen.settings import BY_KEY, DEFAULT_PATH, SPECS, Settings
|
||||
from framegen.settings import BY_KEY, DEFAULT_PATH, SPECS, Settings, parse_res, valid_hz
|
||||
from framegen.sources import TestMode, make_detector
|
||||
from framegen.vfg import vfg_unavailable
|
||||
|
||||
@@ -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)")
|
||||
@@ -288,6 +292,7 @@ def main() -> int:
|
||||
ap.add_argument("--realtime", action="store_true", help="pace file input at 60 Hz like a capture card")
|
||||
ap.add_argument("--max-ticks", type=int)
|
||||
ap.add_argument("--hitch", type=float, default=0.0, help="[sim] probability a game frame is held 3 ticks")
|
||||
ap.add_argument("--sim60", action="store_true", help="[sim] play a 60 fps file as a 60 fps game (testing)")
|
||||
ap.add_argument("--noise", type=float, default=0.0, help="[sim] gaussian noise sigma added per tick")
|
||||
ap.add_argument("--model", default=None, choices=list(MODELS) + ["vfg"],
|
||||
help="RIFE version, or vfg for NVIDIA VFG (default: the saved setting, 4.22.lite). The other "
|
||||
@@ -329,17 +334,24 @@ def main() -> int:
|
||||
"delay in a window, G-Sync in a window). Default: the saved setting")
|
||||
ap.add_argument("--steady-hud", action=argparse.BooleanOptionalAction, default=None,
|
||||
help="keep unchanged parts of the picture (HUD, map) as the game drew them. Default: the saved setting")
|
||||
ap.add_argument("--scaler", default=None, choices=["fsr", "vsr", "bilinear"],
|
||||
help="how the window upscales when it is bigger than the frame (cycle live with 'u'); "
|
||||
ap.add_argument("--scaler", default=None, choices=["off", "fsr", "vsr", "bilinear"],
|
||||
help="how the window upscales when it is bigger than the frame (cycle live with 'u'); off = "
|
||||
"no upscaling, the picture at its own size; "
|
||||
"vsr = NVIDIA RTX Video Super Resolution, needs the RTX Video SDK (framegen/rtxvsr.py)")
|
||||
ap.add_argument("--vsr-quality", type=int, default=None, choices=[1, 2, 3, 4],
|
||||
help="RTX VSR quality: 1 low ... 4 ultra (more GPU time per frame)")
|
||||
ap.add_argument("--fsr-sharpness", type=float, default=None, choices=BY_KEY["fsr_sharpness"].choices,
|
||||
help="FSR 1 sharpening, in stops below maximum: 0 = sharpest, 1 = half, 2 = quarter")
|
||||
ap.add_argument("--hz", type=int, default=None, choices=[60, 90, 120],
|
||||
help="output rate for a 30 fps game: 120 = 3 generated frames per real one (half-res flow by "
|
||||
"default), 90 = 2 (needs a VRR/G-Sync screen or a 90 Hz mode to look even). Needs --display; "
|
||||
"falls back to 60 Hz output whenever it can't keep up")
|
||||
ap.add_argument("--hz", type=int, default=None, metavar="FPS",
|
||||
help="output rate, the frame multiplier for a 30 fps game: 60 (2x), 90 (3x), 120 (4x) ... 300 "
|
||||
"(10x), any multiple of 30. Above 60 needs --display; the extra frames are left out for a "
|
||||
"moment whenever it can't keep up")
|
||||
ap.add_argument("--game-fps", default=None, choices=["auto", "30", "60"],
|
||||
help="the game's frame rate: auto (worked out as it plays), 30 or 60 (then the frame multiplier "
|
||||
"works from 60: 2x is 120 fps)")
|
||||
ap.add_argument("--output-res", default=None, metavar="WxH",
|
||||
help="output resolution: the upscaler makes the picture at this size (e.g. 2560x1440), then it is "
|
||||
"fitted to the window or screen; 'screen' (the default) upscales straight to the screen")
|
||||
ap.add_argument("--display-cv", action="store_true", help="use the (slow) OpenCV window instead of OpenGL")
|
||||
ap.add_argument("--out", help="write output video")
|
||||
ap.add_argument("--score", action="store_true", help="[sim] PSNR of interpolated frames vs real dropped frames")
|
||||
@@ -351,6 +363,10 @@ def main() -> int:
|
||||
help="when test mode (a simulated 30 fps game) or --score was used, write a plain-language report "
|
||||
"of performance and quality here: every 10 s while playing, and at the end")
|
||||
a = ap.parse_args()
|
||||
if a.output_res is not None and a.output_res != "screen" and parse_res(a.output_res) is None:
|
||||
ap.error(f"--output-res {a.output_res}: a size like 2560x1440 (320x240 to 7680x4320), or 'screen'")
|
||||
if a.hz is not None and not valid_hz(a.hz):
|
||||
ap.error(f"--hz {a.hz}: a multiple of 30 from 60 to 300 (the frame multiplier 2x to 10x)")
|
||||
if a.monitor:
|
||||
import framegen.io as _io
|
||||
_io.MONITOR = a.monitor
|
||||
@@ -432,13 +448,13 @@ def main() -> int:
|
||||
return 1
|
||||
elif kind == "file" and a.video:
|
||||
src = (FileSource(a.video, a.realtime, a.max_ticks, test=test) if a.raw else
|
||||
Ps5SimSource(a.video, a.realtime, a.hitch, a.noise, a.max_ticks))
|
||||
Ps5SimSource(a.video, a.realtime, a.hitch, a.noise, a.max_ticks, game60=a.sim60))
|
||||
else:
|
||||
ap.error("give a video file, --capture N or --chiaki")
|
||||
print(f"[run] source: {src.info.name}")
|
||||
|
||||
settings = Settings() if a.settings.lower() == "none" else Settings.load(Path(a.settings))
|
||||
for key, value in (("hz", a.hz), ("scaler", a.scaler), ("vsr_quality", a.vsr_quality),
|
||||
for key, value in (("hz", a.hz), ("game_fps", a.game_fps), ("output_res", a.output_res), ("scaler", a.scaler), ("vsr_quality", a.vsr_quality),
|
||||
("fsr_sharpness", a.fsr_sharpness), ("engine", "trt" if a.trt else a.engine),
|
||||
("interp", False if a.off else None), ("vsync", a.vsync), ("fullscreen", a.fullscreen),
|
||||
("minimize_chiaki", a.minimize_chiaki), ("simulate_30", True if a.test_mode else None),
|
||||
@@ -463,7 +479,7 @@ def main() -> int:
|
||||
settings.watch(lambda key: test.set_on(settings.simulate_30) if key == "simulate_30" else None)
|
||||
if settings.hz > 60 and (a.out or not a.display):
|
||||
if a.hz is not None:
|
||||
ap.error("--hz 90/120 needs --display, and doesn't write --out yet")
|
||||
ap.error("--hz above 60 needs --display, and doesn't write --out yet")
|
||||
print(f"[run] output {settings.hz} Hz needs --display without --out; 60 Hz this run")
|
||||
settings.override("hz", 60)
|
||||
|
||||
@@ -514,7 +530,7 @@ def main() -> int:
|
||||
# quarter (full 52 ms, half 36, quarter 30: its motion worked out at 960x540, as half's is at 1080p).
|
||||
scale = {"full": 1.0, "half": 0.5}.get(settings.motion) or (
|
||||
0.25 if src.h > 1440 else
|
||||
0.5 if settings.hz == 120 or (src.h > 1080 and settings.hz >= 90) else 1.0)
|
||||
0.5 if settings.hz >= 120 or (src.h > 1080 and settings.hz >= 90) else 1.0)
|
||||
engine = auto_engine(scale) if settings.engine == "auto" else settings.engine
|
||||
if dml_mode:
|
||||
engine = "dml"
|
||||
@@ -622,7 +638,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 +658,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
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Frame multiplier: N generated-frame positions per real frame of a 30 fps game (pipeline.cadence_steps), and the
|
||||
settings that take any multiple of 30 fps from 60 to 300 (2x to 10x)."""
|
||||
import pathlib
|
||||
import sys
|
||||
from fractions import Fraction
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from framegen.settings import BY_KEY, Settings, valid_hz
|
||||
|
||||
pipeline = pytest.importorskip("framegen.pipeline")
|
||||
|
||||
|
||||
def test_the_old_rates_keep_their_cadence():
|
||||
assert pipeline.cadence_steps(60) == ([0.5], [])
|
||||
assert pipeline.cadence_steps(90) == ([1 / 3, 2 / 3], [])
|
||||
assert pipeline.cadence_steps(120) == ([0.25, 0.5], [0.75])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n", range(2, 11))
|
||||
def test_every_multiplier_shows_n_evenly_spaced_frames_per_real_one(n):
|
||||
first, second = pipeline.cadence_steps(30 * n)
|
||||
shown = first + second + [1.0] # the real frame closes the pair
|
||||
assert [Fraction(t).limit_denominator(100) for t in shown] == [Fraction(j, n) for j in range(1, n + 1)]
|
||||
# the real frame's tick carries half of them (one more for an odd N): the next tick never has more to show
|
||||
assert len(first) - (len(second) + 1) in (0, 1)
|
||||
|
||||
|
||||
def test_settings_take_any_multiple_of_30_from_2x_to_10x():
|
||||
assert all(valid_hz(h) for h in (60, 90, 210, 300))
|
||||
assert not any(valid_hz(h) for h in (30, 100, 330, True, "120", 120.0))
|
||||
s = Settings()
|
||||
s.override("hz", 210) # 7x, not a menu choice
|
||||
assert s.hz == 210 and BY_KEY["hz"].name(210) == "7x"
|
||||
with pytest.raises(ValueError):
|
||||
s.override("hz", 100)
|
||||
assert s.step("hz", 1) == 240 and s.step("hz", -1) == 180 # from a custom value, to the menu's neighbours
|
||||
assert BY_KEY["hz"].name(120) == "4x"
|
||||
|
||||
|
||||
def test_a_steady_60_fps_game_is_found_and_left_again():
|
||||
from framegen.cadence import UNEVEN_DWELL, FrameTimeline
|
||||
t = FrameTimeline()
|
||||
for _ in range(60 + UNEVEN_DWELL + 1): # a second to count, then a second there
|
||||
t.tick(True)
|
||||
assert t.full and t.delay <= 1.1 # at most about a frame of delay (steady frames need next to none)
|
||||
for k in range(60 + UNEVEN_DWELL + 1): # 30 fps: new every other tick
|
||||
t.tick(k % 2 == 0)
|
||||
assert not t.full
|
||||
|
||||
|
||||
def test_a_short_60_fps_burst_isnt_a_60_fps_game():
|
||||
from framegen.cadence import FrameTimeline
|
||||
t = FrameTimeline()
|
||||
for n in range(240): # a 30 fps game with a 60 fps menu for half a second
|
||||
t.tick(n % 2 == 0 or 100 <= n < 130)
|
||||
assert not t.full
|
||||
@@ -0,0 +1,413 @@
|
||||
"""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[:5] == ["interp", "hz", "game_fps", "scaler", "output_res"] 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 "Frame generation" in m.tabs() and "Upscaling" 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("Frame generation")
|
||||
n = len(m.rows())
|
||||
assert n > VISIBLE
|
||||
assert m.rows()[0].kind == "header" and m.index == 1 # a tab opens on its first setting, under its heading
|
||||
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
|
||||
assert all(m.rows()[i].kind != "header" for i in [m.index])
|
||||
left = m.rows()[m.index].key
|
||||
m.show("Upscaling")
|
||||
assert m.index == 1
|
||||
m.show("Frame generation")
|
||||
assert m.rows()[m.index].key == left
|
||||
|
||||
|
||||
def test_headings_are_skipped_by_the_keys_and_the_mouse():
|
||||
m = menu()
|
||||
m.show("Frame generation")
|
||||
rows = m.rows()
|
||||
seen = []
|
||||
for _ in range(len(rows)):
|
||||
seen.append(m.index)
|
||||
m.key("down")
|
||||
assert all(rows[i].kind != "header" for i in seen)
|
||||
while m.focus == "rows":
|
||||
m.key("up")
|
||||
assert m.focus == "tabs" # Up from the first setting (past its heading) goes to the tabs
|
||||
m.focus = "rows"
|
||||
m.render(1.0)
|
||||
h = next(i for i, r in enumerate(m.rows()) if r.kind == "header" and i >= m._scroll)
|
||||
y = m._hit["rows"][1] + (h - m._scroll + 0.5) * m._hit["row_h"]
|
||||
before = m.index
|
||||
m.hover(200, y)
|
||||
assert m.index == before and m.click(200, y) is None and m.index == before
|
||||
|
||||
|
||||
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("Upscaling") 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 == 1100 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] == 550
|
||||
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("Upscaling")]
|
||||
assert m.click(box[0] + 5, box[1] + 5) is None and m.tab == "Upscaling"
|
||||
m.show(None)
|
||||
m.render(1.0)
|
||||
hz_row = [r.key for r in m.rows()].index("hz")
|
||||
# Frame multiplier is a slider: a click picks the nearest step
|
||||
box, what, track = m._hit["controls"][hz_row][0]
|
||||
assert what == "slider" and m.kind_of(m.rows()[hz_row]) == "slider"
|
||||
mid = (box[1] + box[3]) / 2
|
||||
m.click(track[1], mid)
|
||||
assert m.settings.hz == 240 and m.index == hz_row
|
||||
m.click(track[0] + (track[1] - track[0]) * 2 / 5, mid) # 3rd of 6 steps: 4x
|
||||
assert m.settings.hz == 120
|
||||
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"
|
||||
tab_box = m._hit["tabs"][m.tabs().index("Upscaling")]
|
||||
m.hover(tab_box[0] + 5, tab_box[1] + 5)
|
||||
assert m._hover == ("tab", m.tabs().index("Upscaling"))
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ---- a window for the mouse ---------------------------------------------------------------------------------------
|
||||
def long_tab(m: Menu) -> str:
|
||||
"""A tab with more rows than fit, so it scrolls (Overlay, with the graph settings showing)."""
|
||||
m.settings.override("overlay_style", "graphs")
|
||||
for tab in sorted(m.sections(), key=lambda t: -len(m.tab_rows(t))):
|
||||
if len(m.tab_rows(tab)) > VISIBLE + 2:
|
||||
return tab
|
||||
pytest.skip("no tab is long enough to scroll")
|
||||
|
||||
|
||||
def test_the_wheel_scrolls_the_page_not_the_highlight():
|
||||
m = menu()
|
||||
m.show(long_tab(m))
|
||||
m.render(1.0)
|
||||
m._select(0, reveal=False) # (row 0 is a heading: the first setting under it)
|
||||
first = m.index
|
||||
m.scroll(-1)
|
||||
assert m._scroll == 1 and m.index == first # the page moved; the highlighted row is the same one
|
||||
m.scroll(-0.4)
|
||||
m.scroll(-0.4)
|
||||
assert m._scroll == 1 # a touchpad's small steps wait until they make a row...
|
||||
m.scroll(-0.4)
|
||||
assert m._scroll == 2
|
||||
m.scroll(+50)
|
||||
assert m._scroll == 0 # ...and the page stops at its ends
|
||||
m.key("down")
|
||||
assert m.index == first + 1
|
||||
|
||||
|
||||
def test_the_scrollbar_drags_and_the_title_bar_moves_the_window():
|
||||
m = menu()
|
||||
m.show(long_tab(m))
|
||||
m.render(1.0)
|
||||
sb, thumb = m._hit["scrollbar"], m._hit["thumb"]
|
||||
x = (sb[0] + sb[2]) / 2
|
||||
assert m.grab(x, (thumb[1] + thumb[3]) / 2) == "drag"
|
||||
m.drag(x, sb[3] + 500)
|
||||
assert m._scroll == len(m.rows()) - VISIBLE
|
||||
m.release()
|
||||
assert m._drag is None
|
||||
title = m._hit["title"]
|
||||
assert m.grab(title[0] + 200, title[1] + 10) == "move" and m.cursor(title[0] + 200, title[1] + 10) == "move"
|
||||
c = m._hit["close"]
|
||||
assert m.grab(c[0] + 2, c[1] + 2) is None and m.click(c[0] + 2, c[1] + 2) == "close"
|
||||
|
||||
|
||||
def test_sliders_drag_and_long_lists_drop_down():
|
||||
m = menu()
|
||||
m.render(1.0)
|
||||
rows = m.rows()
|
||||
hz_row = [r.key for r in rows].index("hz")
|
||||
box, _, track = m._hit["controls"][hz_row][0]
|
||||
mid = (box[1] + box[3]) / 2
|
||||
assert m.grab(track[0], mid) == "drag" and m.settings.hz == 60
|
||||
m.drag(track[1], mid)
|
||||
assert m.settings.hz == 240
|
||||
m.release()
|
||||
# a setting with a long list of choices: a drop-down
|
||||
lists = [(t, r) for t in m.tabs() for r in m.tab_rows(t) if m.kind_of(r) == "list"]
|
||||
assert lists, "some setting should have a drop-down list"
|
||||
tab, row = lists[0]
|
||||
m.show(tab)
|
||||
m.render(1.0)
|
||||
i = [r.key for r in m.rows()].index(row.key)
|
||||
m._scroll = max(0, i - VISIBLE + 1) if i >= VISIBLE else 0
|
||||
m.render(1.0)
|
||||
b = next(b for b, what, _ in m._hit["controls"][i] if what == "list")
|
||||
m.click(b[0] + 5, (b[1] + b[3]) / 2)
|
||||
assert m._drop == row.key
|
||||
m.render(1.0)
|
||||
items = m._hit["drop_items"]
|
||||
target = next((it for it in items if it[2] and it[1] != m.value(row)), None)
|
||||
assert target is not None
|
||||
m.scroll(-1) # the wheel scrolls the list while it's open, not the page
|
||||
m.render(1.0)
|
||||
items = m._hit["drop_items"]
|
||||
target = next(it for it in items if it[2] and it[1] != m.value(row))
|
||||
m.click(target[0][0] + 5, target[0][1] + 5)
|
||||
assert m.value(row) == target[1] and m._drop is None
|
||||
# keys work in an open list too, and Esc closes the list before the overlay
|
||||
m.key("enter")
|
||||
assert m._drop == row.key
|
||||
assert m.key("back") is None and m._drop is None
|
||||
assert m.key("back") == "close"
|
||||
|
||||
|
||||
def test_slider_keys_go_the_way_the_slider_does():
|
||||
m = menu()
|
||||
m.show("Overlay")
|
||||
rows = m.rows()
|
||||
op = next(r for r in rows if r.key == "ui_opacity") # stored 100% .. 30%, drawn 30% .. 100%
|
||||
assert m.kind_of(op) == "slider" and m.ordered(op) == sorted(m.choices(op))
|
||||
m.settings.set("ui_opacity", 0.5)
|
||||
m.step(op, 1)
|
||||
assert m.settings.ui_opacity == 0.6 # Right: more
|
||||
m.settings.set("ui_opacity", 1.0)
|
||||
m.step(op, 1)
|
||||
assert m.settings.ui_opacity == 1.0 # and it stops at the end
|
||||
|
||||
|
||||
def test_the_mouse_anywhere_on_a_tab_without_a_scrollbar_or_list():
|
||||
m = menu() # Home: short, so no scrollbar; no list open
|
||||
m.render(1.0)
|
||||
assert m._hit["scrollbar"] is None and m._hit["drop"] is None
|
||||
for x in range(0, m._hit["w"], 37):
|
||||
for y in range(0, m._hit["h"], 29):
|
||||
m.cursor(x, y)
|
||||
m.hover(x, y)
|
||||
m.grab(x, y)
|
||||
m.release()
|
||||
|
||||
|
||||
def test_a_failing_rtx_vsr_falls_back_to_fsr_instead_of_ending_the_session():
|
||||
import types
|
||||
from framegen.io import GLWindowSink
|
||||
said = []
|
||||
w = types.SimpleNamespace(vsr_out=None, vsr=object(), _vsr_args=(1, 1, False), vsr_why=None,
|
||||
modes=["fsr", "vsr", "bilinear", "off"], mode="vsr",
|
||||
_vsr_target_free=lambda: None, toast=lambda t, s=2.0: said.append(t))
|
||||
def boom():
|
||||
raise RuntimeError("no glTexStorage2D")
|
||||
assert GLWindowSink._vsr_safely(w, boom) is False
|
||||
assert w.mode == "fsr" and "vsr" not in w.modes and w.vsr is None and "no glTexStorage2D" in w.vsr_why
|
||||
assert said and "FSR" in said[0]
|
||||
assert GLWindowSink._vsr_safely(w, lambda: None) is True
|
||||
@@ -223,3 +223,69 @@ def test_real_x_server_lists_windows():
|
||||
assert w.title and w.w >= wx.MIN_SIZE[0]
|
||||
finally:
|
||||
x.close()
|
||||
|
||||
|
||||
def test_pick_by_dir_finds_a_game_a_launcher_started():
|
||||
# Steam/Lutris/Heroic start the game; Summit only knows its folder. 500 runs from it, 77 (Konsole) does not.
|
||||
in_dir = lambda pid, folder: pid == 500 and folder == "/games/Voidrunner"
|
||||
assert wx.pick("dir:/games/Voidrunner", WINS, in_dir=in_dir).xid == 10
|
||||
assert wx.pick("dir:/elsewhere", WINS, in_dir=in_dir) is None
|
||||
assert wx.pick("class:voidrunner.exe|dir:/games/Voidrunner", WINS, in_dir=in_dir).xid == 10
|
||||
assert wx.pick("dir:", WINS, in_dir=lambda p, f: True) is None
|
||||
|
||||
|
||||
def test_under_reads_wine_paths_and_keeps_folder_boundaries():
|
||||
assert wx.under("/games/Voidrunner/bin/vr", "/games/Voidrunner")
|
||||
assert wx.under("Z:\\games\\Voidrunner\\VR.exe", "/games/voidrunner/")
|
||||
assert wx.under("/games/Voidrunner", "/games/Voidrunner")
|
||||
assert not wx.under("/games/Voidrunner2/vr", "/games/Voidrunner")
|
||||
assert not wx.under("C:\\windows\\explorer.exe", "/games/Voidrunner")
|
||||
|
||||
|
||||
def test_pid_in_dir_reads_cwd_exe_and_cmdline(tmp_path):
|
||||
def proc(pid, cwd, exe, cmd):
|
||||
d = tmp_path / str(pid)
|
||||
d.mkdir()
|
||||
os.symlink(cwd, d / "cwd")
|
||||
os.symlink(exe, d / "exe")
|
||||
(d / "cmdline").write_bytes("\0".join(cmd).encode() + b"\0")
|
||||
proc(1, "/games/VR", "/usr/bin/vr", ["vr"]) # runs from the folder
|
||||
proc(2, "/home/me", "/games/VR/vr", ["vr"]) # its program is in it
|
||||
proc(3, "/home/me", "/proton/wine64", ["Z:\\games\\VR\\VR.exe"]) # Wine, the .exe on its command line
|
||||
proc(4, "/home/me", "/usr/bin/steam", ["steam", "steam://rungameid/1"]) # not the game
|
||||
got = [p for p in (1, 2, 3, 4, 5, 0) if wx.pid_in_dir(p, "/games/VR", proc=str(tmp_path))]
|
||||
assert got == [1, 2, 3]
|
||||
|
||||
|
||||
def test_ask_matches_nothing_until_a_rule_is_picked():
|
||||
assert wx.pick("ask:", WINS) is None
|
||||
assert wx.pick("", WINS) is None
|
||||
assert "picked in Summit" in wx.waiting_line("ask:", 300)
|
||||
assert "matching 'class:x'" in wx.waiting_line("class:x", 60)
|
||||
|
||||
|
||||
def test_live_query_follows_the_file_summit_writes(tmp_path, capsys):
|
||||
f = tmp_path / "window-rule"
|
||||
live = wx.LiveQuery("ask:", env={"SUMMIT_WINDOW_FILE": str(f)})
|
||||
assert live.get() == "ask:" # no file yet
|
||||
f.write_text("class:voidrunner\n")
|
||||
assert live.get() == "class:voidrunner" # picked in the launcher
|
||||
assert "now looking for 'class:voidrunner'" in capsys.readouterr().out
|
||||
f.write_text("")
|
||||
assert live.get() == "ask:" # emptied: back to what it was started with
|
||||
assert wx.LiveQuery("class:a", env={}).get() == "class:a"
|
||||
|
||||
|
||||
def test_open_window_takes_a_rule_picked_while_it_waits(tmp_path, monkeypatch):
|
||||
f = tmp_path / "window-rule"
|
||||
monkeypatch.setenv("SUMMIT_WINDOW_FILE", str(f))
|
||||
monkeypatch.setattr(wx, "session_problem", lambda env=None: None)
|
||||
monkeypatch.setattr(wx, "X", lambda *a: object())
|
||||
monkeypatch.setattr(wx, "find_windows", lambda x=None: WINS)
|
||||
monkeypatch.setattr(wx, "X11WindowSource", lambda target, x: target)
|
||||
looks = []
|
||||
def sleep(_s):
|
||||
looks.append(1)
|
||||
if len(looks) == 3:
|
||||
f.write_text("class:konsole") # the player picks it in Summit
|
||||
assert wx.open_window("ask:", wait_s=30, sleep=sleep).xid == 12
|
||||
@@ -9,30 +9,45 @@
|
||||
# Python virtualenv (uv, Python 3.12, CUDA 12.8 torch only if an NVIDIA GPU
|
||||
# is present).
|
||||
#
|
||||
# Run it again to update: it finds the existing install, says which version it has and which it gets, rebuilds
|
||||
# only when the source changed, keeps the engine's venv (adding what new requirements need) and your data.
|
||||
#
|
||||
# Flags:
|
||||
# --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
|
||||
#
|
||||
# Environment:
|
||||
# SUMMIT_PREFIX where to install (default /usr/local)
|
||||
# SUMMIT_SRC_DIR build this checkout as it is (no clone, no git pull)
|
||||
# SUMMIT_REPO clone and update from this git URL instead (testing)
|
||||
|
||||
set -eu
|
||||
# Files and folders it makes under the prefix must be readable by everyone, whatever umask the caller has (with
|
||||
# 077, sudo made /usr/local/share/summit root-only and the engine's venv went to the wrong place).
|
||||
umask 022
|
||||
|
||||
REPO_API="https://git.molberg.cloud/api/v1/repos/alex/summit"
|
||||
REPO_GIT="https://git.molberg.cloud/alex/summit.git"
|
||||
REPO_GIT="${SUMMIT_REPO:-https://git.molberg.cloud/alex/summit.git}"
|
||||
PREFIX="${SUMMIT_PREFIX:-/usr/local}"
|
||||
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' "$*"; }
|
||||
@@ -46,6 +61,19 @@ run() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Questions are read from the terminal: under `curl ... | sh` the script itself is on stdin.
|
||||
ask() {
|
||||
printf '%s [y/N] ' "$1"
|
||||
if [ -r /dev/tty ] && reply="$(head -n 1 < /dev/tty 2>/dev/null)"; then :; else
|
||||
printf '\n'
|
||||
die "no terminal to ask on: run again with --yes"
|
||||
fi
|
||||
case "$reply" in
|
||||
y|Y|yes|YES) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
run_sudo() {
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
run "$@"
|
||||
@@ -53,18 +81,23 @@ run_sudo() {
|
||||
fi
|
||||
if [ "$ASSUME_YES" -eq 0 ] && [ "$DRY_RUN" -eq 0 ]; then
|
||||
printf ' needs sudo: %s\n' "$*"
|
||||
printf ' proceed? [y/N] '
|
||||
read -r reply
|
||||
case "$reply" in
|
||||
y|Y|yes|YES) ;;
|
||||
*) die "aborted before: $*" ;;
|
||||
esac
|
||||
ask ' proceed?' || die "aborted before: $*"
|
||||
fi
|
||||
run sudo "$@"
|
||||
}
|
||||
|
||||
# Files into the prefix: sudo only when it isn't writable (/usr/local is not; ~/.local is).
|
||||
prefix_writable() { [ -w "$PREFIX" ] || { [ ! -e "$PREFIX" ] && [ -w "$(dirname "$PREFIX")" ]; }; }
|
||||
run_prefix() {
|
||||
if prefix_writable; then
|
||||
run "$@"
|
||||
else
|
||||
run_sudo "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
usage() {
|
||||
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
|
||||
sed -n '2,/^set -eu/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'
|
||||
}
|
||||
|
||||
# Tools Summit calls at run time. A missing one only disables a feature, so a failure here warns instead of
|
||||
@@ -75,7 +108,9 @@ RUNTIME_TOOLS="ffmpeg xrandr xdg-open zenity"
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--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)" ;;
|
||||
@@ -142,14 +177,23 @@ detect_gpu() {
|
||||
SESSION_TYPE=unknown # wayland, x11
|
||||
|
||||
detect_session() {
|
||||
if [ -n "${XDG_SESSION_TYPE:-}" ]; then
|
||||
SESSION_TYPE="$XDG_SESSION_TYPE"
|
||||
elif [ -n "${WAYLAND_DISPLAY:-}" ]; then
|
||||
SESSION_TYPE="${XDG_SESSION_TYPE:-}"
|
||||
case "$SESSION_TYPE" in
|
||||
wayland|x11) return ;;
|
||||
esac
|
||||
if [ -n "${WAYLAND_DISPLAY:-}" ]; then
|
||||
SESSION_TYPE=wayland
|
||||
elif [ -n "${DISPLAY:-}" ]; then
|
||||
SESSION_TYPE=x11
|
||||
else
|
||||
# From a text console or ssh (XDG_SESSION_TYPE=tty): the type of this user's graphical session, if any.
|
||||
SESSION_TYPE=unknown
|
||||
if command -v loginctl >/dev/null 2>&1; then
|
||||
for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk -v u="$(id -un)" '$3 == u {print $1}'); do
|
||||
t="$(loginctl show-session "$s" -p Type --value 2>/dev/null || true)"
|
||||
case "$t" in wayland|x11) SESSION_TYPE="$t"; break ;; esac
|
||||
done
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -161,7 +205,15 @@ install_dependencies() {
|
||||
step "Installing build and runtime dependencies for $DISTRO_FAMILY"
|
||||
case "$DISTRO_FAMILY" in
|
||||
arch)
|
||||
run_sudo pacman -Sy --needed --noconfirm base-devel git curl pkgconf fontconfig
|
||||
# Only what is missing (pacman -T needs no root), and no `pacman -Sy` without -u: on Arch that is a partial
|
||||
# upgrade. If a package isn't in the local sync database, pacman says so: run `sudo pacman -Syu` first.
|
||||
build_missing="$(pacman -T base-devel git curl pkgconf fontconfig 2>/dev/null || true)"
|
||||
if [ -n "$build_missing" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
run_sudo pacman -S --needed --noconfirm $build_missing
|
||||
else
|
||||
log " build tools: all there"
|
||||
fi
|
||||
runtime="ffmpeg xorg-xrandr xdg-utils zenity"
|
||||
;;
|
||||
debian)
|
||||
@@ -198,7 +250,14 @@ install_dependencies() {
|
||||
step "Installing the tools Summit runs (a failure here only disables a feature)"
|
||||
# shellcheck disable=SC2086
|
||||
case "$DISTRO_FAMILY" in
|
||||
arch) run_sudo pacman -S --needed --noconfirm $runtime || log " warning: could not install: $runtime" ;;
|
||||
arch)
|
||||
runtime="$(pacman -T $runtime 2>/dev/null || true)"
|
||||
if [ -n "$runtime" ]; then
|
||||
run_sudo pacman -S --needed --noconfirm $runtime || log " warning: could not install: $runtime"
|
||||
else
|
||||
log " all there"
|
||||
fi
|
||||
;;
|
||||
debian) run_sudo apt-get install -y $runtime || log " warning: could not install: $runtime" ;;
|
||||
fedora) run_sudo dnf install -y $runtime || log " warning: could not install: $runtime" ;;
|
||||
opensuse) run_sudo zypper install -y $runtime || log " warning: could not install: $runtime" ;;
|
||||
@@ -287,6 +346,30 @@ install_native_package() {
|
||||
esac
|
||||
}
|
||||
|
||||
# What is installed already: the commit it was built from (written by this script since the Wayland update; older
|
||||
# installs only have the binaries), or nothing.
|
||||
VERSION_FILE="$SHARE_DIR/installed-version"
|
||||
installed_version() {
|
||||
if [ -f "$VERSION_FILE" ]; then
|
||||
head -n 1 "$VERSION_FILE"
|
||||
elif [ -x "$BIN_DIR/summit" ]; then
|
||||
printf 'unknown (installed before versions were recorded)\n'
|
||||
fi
|
||||
}
|
||||
|
||||
detect_existing() {
|
||||
INSTALLED="$(installed_version)"
|
||||
if [ -n "$INSTALLED" ]; then
|
||||
log " existing : Summit in $BIN_DIR, version $INSTALLED: this run updates it"
|
||||
else
|
||||
log " existing : none in $BIN_DIR"
|
||||
fi
|
||||
other="$(command -v summit 2>/dev/null || true)"
|
||||
if [ -n "$other" ] && [ "$other" != "$BIN_DIR/summit" ]; then
|
||||
log " note : another summit is on PATH at $other (a different SUMMIT_PREFIX?); it is left alone"
|
||||
fi
|
||||
}
|
||||
|
||||
build_from_source() {
|
||||
step "No usable release package found, building from source"
|
||||
ensure_rust
|
||||
@@ -301,30 +384,75 @@ build_from_source() {
|
||||
run mkdir -p "$(dirname "$SRC_DIR")"
|
||||
run git clone "$REPO_GIT" "$SRC_DIR"
|
||||
fi
|
||||
NEW_VERSION="local checkout"
|
||||
if git -C "$SRC_DIR" rev-parse --git-dir >/dev/null 2>&1; then
|
||||
NEW_VERSION="$(git -C "$SRC_DIR" log -1 --format='%h (%cs)' 2>/dev/null || echo unknown)"
|
||||
if [ -n "$(git -C "$SRC_DIR" status --porcelain 2>/dev/null)" ]; then NEW_VERSION="$NEW_VERSION + local changes"; fi
|
||||
fi
|
||||
if [ "$DRY_RUN" -eq 0 ] && [ "$FORCE" -eq 0 ] && [ "$INSTALLED" = "$NEW_VERSION" ] && [ "${NEW_VERSION#*local}" = "$NEW_VERSION" ] \
|
||||
&& [ -x "$BIN_DIR/summit" ] && [ -x "$BIN_DIR/summit-gui" ] && [ -f "$SHARE_DIR/engine/run.py" ]; then
|
||||
log " Summit $INSTALLED is already the newest: nothing to rebuild (--force rebuilds anyway)"
|
||||
install_desktop_entry "$SRC_DIR/packaging"
|
||||
return
|
||||
fi
|
||||
if [ -n "$INSTALLED" ]; then
|
||||
log " updating $INSTALLED -> $NEW_VERSION"
|
||||
fi
|
||||
run cargo build --release --manifest-path "$SRC_DIR/Cargo.toml" -p summit -p summit-gui
|
||||
run_sudo install -Dm755 "$SRC_DIR/target/release/summit" "$BIN_DIR/summit"
|
||||
run_sudo install -Dm755 "$SRC_DIR/target/release/summit-gui" "$BIN_DIR/summit-gui"
|
||||
run_sudo mkdir -p "$SHARE_DIR/engine"
|
||||
run_sudo cp -r "$SRC_DIR/engine/." "$SHARE_DIR/engine/"
|
||||
run_prefix install -Dm755 "$SRC_DIR/target/release/summit" "$BIN_DIR/summit"
|
||||
run_prefix install -Dm755 "$SRC_DIR/target/release/summit-gui" "$BIN_DIR/summit-gui"
|
||||
run_prefix mkdir -p "$SHARE_DIR/engine"
|
||||
# An update replaces the engine's files (so ones removed upstream go too) but keeps its venv and models.
|
||||
if [ -f "$SHARE_DIR/engine/run.py" ]; then
|
||||
run_prefix find "$SHARE_DIR/engine" -mindepth 1 -maxdepth 1 ! -name .venv ! -name models -exec rm -rf {} +
|
||||
fi
|
||||
run_prefix cp -r "$SRC_DIR/engine/." "$SHARE_DIR/engine/"
|
||||
install_desktop_entry "$SRC_DIR/packaging"
|
||||
# The engine's venv is made in there next, without sudo (uv and the Python it downloads live in the user's home),
|
||||
# so the folder has to belong to the user who runs Summit.
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
if [ "$(id -u)" -ne 0 ] && ! prefix_writable; then
|
||||
run_sudo chown -R "$(id -u):$(id -g)" "$SHARE_DIR/engine"
|
||||
fi
|
||||
version_tmp="$(mktemp)"
|
||||
printf '%s\n' "$NEW_VERSION" > "$version_tmp"
|
||||
run_prefix install -Dm644 "$version_tmp" "$VERSION_FILE"
|
||||
rm -f "$version_tmp"
|
||||
}
|
||||
|
||||
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_sudo 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_sudo install -Dm644 "$desktop_tmp" "$APPS_DIR/summit.desktop"
|
||||
run_prefix install -Dm644 "$desktop_tmp" "$APPS_DIR/summit.desktop"
|
||||
rm -f "$desktop_tmp"
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
run_sudo update-desktop-database "$APPS_DIR" || true
|
||||
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
|
||||
}
|
||||
|
||||
@@ -357,7 +485,11 @@ setup_engine_venv() {
|
||||
log " engine sources not found, skipping venv setup"
|
||||
return
|
||||
fi
|
||||
run uv venv --python 3.12 "$engine_dir/.venv"
|
||||
if "$engine_dir/.venv/bin/python" -c 'import sys; sys.exit(sys.version_info[:2] != (3, 12))' 2>/dev/null; then
|
||||
log " keeping the existing venv ($engine_dir/.venv); installing what is new or missing in it"
|
||||
else
|
||||
run uv venv --clear --python 3.12 "$engine_dir/.venv"
|
||||
fi
|
||||
if [ "$GPU_VENDOR" = "nvidia" ]; then
|
||||
# torch first: requirements.txt only says torch>=2.6, and PyPI's default wheel is built for a newer CUDA than
|
||||
# many installed drivers support (seen: torch 2.15+cu132 on a driver that stops at CUDA 13.0).
|
||||
@@ -370,24 +502,73 @@ 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)"
|
||||
log " GPU vendor : $GPU_VENDOR"
|
||||
log " session type : $SESSION_TYPE"
|
||||
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
|
||||
|
||||
if [ "$ASSUME_YES" -eq 0 ] && [ "$DRY_RUN" -eq 0 ]; then
|
||||
printf '\nProceed? [y/N] '
|
||||
read -r reply
|
||||
case "$reply" in
|
||||
y|Y|yes|YES) ;;
|
||||
*) die "aborted" ;;
|
||||
esac
|
||||
printf '\n'
|
||||
ask 'Proceed?' || die "aborted"
|
||||
fi
|
||||
|
||||
install_dependencies
|
||||
@@ -400,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"
|
||||
@@ -408,13 +592,17 @@ 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_sudo rm -f "$BIN_DIR/summit" "$BIN_DIR/summit-gui" "$APPS_DIR/summit.desktop" "$ICON_DIR/summit.png"
|
||||
run_sudo rm -rf "$SHARE_DIR"
|
||||
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)"
|
||||
}
|
||||
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
src/
|
||||
pkg/
|
||||
chiaki-ng/
|
||||
*.pkg.tar.*
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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())
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 690 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 23 KiB |
@@ -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 |
@@ -7,3 +7,4 @@ Icon=summit
|
||||
Terminal=false
|
||||
Categories=Game;
|
||||
StartupNotify=true
|
||||
StartupWMClass=summit
|
||||