Merge ap/wayland-capture

This commit is contained in:
alex committed 2026-11-24 17:09:06 +00:00
commit 65b1856276
25 files changed
+1167 -54

No files matched your search

+18 -11
View File
@@ -48,7 +48,7 @@
<p align="center"><sub><b>These are real window captures</b> of <code>summit-gui</code> running fullscreen on the project's KDE neon X11 test machine (software OpenGL, 1920x1080), taken with <code>import -window</code> after keyboard input, from the release-candidate run (<a href="docs/RC_REPORT.md">docs/RC_REPORT.md</a>). <b>The library is a demo</b>: invented game titles with generated cover art and made-up playtime, written to disk as a Steam library so the real scanner reads it (<code>docs/demo/make_demo_home.py</code>). <b>Voidrunner</b> is real (the author's own game, added by hand with its own artwork). Stills show no animation.</sub></p>
> [!NOTE]
> **Pre-alpha.** The launcher, the command-line core and live enhance on an X11 desktop were run end to end on one test machine (one GPU, one game). Wayland capture, real Steam/Heroic launches, a controller, 90/120 Hz and most packaging paths are **not tested**. The table below says which is which.
> **Pre-alpha.** The launcher, the command-line core and live enhance were run end to end on an X11 test machine and on one KDE Plasma Wayland desktop (one game each: an XWayland one; native Wayland capture only with a test window). Other Wayland desktops, real Steam/Heroic launches, a controller, 90/120 Hz and most packaging paths are **not tested**. The table below says which is which.
## Install
@@ -66,7 +66,7 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
## Status
- **Working**: run end to end for real on the test machine during the release-candidate run (2026-11-24; KDE neon X11, RTX 3090 shared with another job, software OpenGL for the display).
- **Working**: run end to end for real on the test machine during the release-candidate run (2026-11-24; KDE neon X11, RTX 3090 shared with another job, software OpenGL for the display), or, where the row says Wayland, on the owner's desktop (2026-11-24; Arch, KDE Plasma 6.8 Wayland, RTX 5080; [docs/WAYLAND_REPORT.md](docs/WAYLAND_REPORT.md)).
- **Tested**: checked in part (unit tests, sample files, dry runs, a build) but not run for real end to end.
- **Experimental**: written, not tested, or known to fall short. Do not rely on it.
- **Planned**: not built.
@@ -76,19 +76,19 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
| Launcher window (`summit-gui`): Home, Library (grid and list), Unfiltered, a page per game, Settings | **Working** | Run fullscreen on the KDE X11 desktop; every screenshot above is that window. Software OpenGL there: **not checked on a GPU-rendered desktop or a TV**. |
| Keyboard navigation (arrows, Enter, Esc, Tab between sections) | **Working** | Driven with synthetic X key events on the desktop: Tab walked Home, Library, Unfiltered, Settings; arrows moved focus; Enter opened a game's page, toggled Enhance and pressed Play. `/`, `P` and `F11` were not pressed in this run (they were in the earlier headless and Xvfb checks). |
| 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** | 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. |
| Live enhance (`--enhance`): RIFE frame generation + FSR upscaling on a running game's window | **Working on 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. |
| 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. |
| Instant replay clips: global save key (Ctrl+Alt+R), clip lengths from Settings | **Working on 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. Wayland global key (xdg-desktop-portal): written, not tested. |
| 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. |
| 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. |
| `summit doctor` readiness list | **Tested** | New since the RC run: 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. Run on the build machine (no venv there, so the torch line was not exercised for real); unit tests. |
| `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** | Earlier on the test machine: `summit run` switched the output from its custom mode to 1280x800 @ 74.99 Hz and back when the game exited. Not repeated in this run (the profile used had the default mode). KDE Wayland and wlroots command plans: unit tests only. GNOME Wayland: skipped with a message. |
| 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). |
| `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. |
@@ -96,14 +96,14 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
| 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. |
| Wayland (window capture for Enhance, global keys) | **Experimental** | Enhance refuses to start on Wayland; the portal path for the save key is untested. |
| 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** | |
## Clips
The engine keeps a rolling buffer of what you played (hardware encoded where possible), like the PS5's Share button. Pick how far back to keep (15 s to 10 min) and what a save writes (15 s, 30 s, 1 m, 3 m, 5 m or 10 m) in Settings. **Ctrl+Alt+R saves a clip from any window on X11**, so you never have to leave the game; in the engine's own window **R** saves the default length and **Ctrl+1 to Ctrl+6** a chosen one. A clip is never longer than the buffer holds. Clips land in `~/Videos/Summit/<game>/` (a folder per game, named after the library entry) as plain MP4 files; **Settings > Clips folder** opens it. The folder per game is new since the RC run (unit tested; the RC clip went to the old `~/Videos/SmoovPlay/`).
The engine keeps a rolling buffer of what you played (hardware encoded where possible), like the PS5's Share button. Pick how far back to keep (15 s to 10 min) and what a save writes (15 s, 30 s, 1 m, 3 m, 5 m or 10 m) in Settings. **Ctrl+Alt+R saves a clip from any window** (on X11 with a key grab, on KDE Wayland through the GlobalShortcuts portal), so you never have to leave the game; in the engine's own window **R** saves the default length and **Ctrl+1 to Ctrl+6** a chosen one. A clip is never longer than the buffer holds. Clips land in `~/Videos/Summit/<game>/` (a folder per game, named after the library entry) as plain MP4 files; **Settings > Clips folder** opens it. The folder per game is new since the RC run (unit tested; the RC clip went to the old `~/Videos/SmoovPlay/`).
![The engine's toast after Ctrl+Alt+R: Saved the last 30 s](docs/media/rc/clip-saved-30s.png)
@@ -150,7 +150,7 @@ summit profile set default --framegen rife --upscaler fsr
summit enhance clip.mp4 --out smooth.mp4 # file in, 60 fps file out
summit enhance ps5 # PS5 Remote Play, live window (untested)
summit enhance capture:0 --profile my-console # capture card, live window (untested)
summit enhance window:Voidrunner # a running game's window, live (X11)
summit enhance window:Voidrunner # a running game's window, live (X11, Wayland)
```
The engine needs an NVIDIA GPU and its own Python environment (`engine/`, torch with CUDA). `install.sh` sets that up with `uv` (see the install row in the table for what was run).
@@ -166,6 +166,13 @@ summit enhance window:Voidrunner # or: enhance a game that is alr
`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.
| | |
|---|---|
| ![Voidrunner through XWayland on KDE Plasma Wayland, enhanced over the whole 1080p monitor, with the toast Saved the last 15 s](docs/media/wayland/enhanced-xwayland.png) | ![A native Wayland test window captured through the ScreenCast portal, the engine's picture over its monitor](docs/media/wayland/native-standin.png) |
| KDE Wayland: Voidrunner (XWayland) started from the launcher, Ctrl+Alt+R through the portal | KDE Wayland: a native Wayland test window through the portal; each green block is a key the window got with the picture on top |
How it works (X11): the engine redirects the game's window off screen with the Composite extension and reads it 60 times a second through `ffmpeg`'s x11grab, leaving out grabs where nothing changed, so frames come at the game's own rate. Its output is a borderless window on top of the game that never takes focus and lets clicks through: over the game's window, or over the whole monitor with `fullscreen = true` (that is where the upscaler has something to do). Stats and the watermark `summit - git.molberg.cloud/alex/summit` are drawn in that window; `--no-watermark` hides the watermark.
| | |
@@ -183,7 +190,7 @@ 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: X11 sessions only (on Wayland it stops with a message). 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 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.
## The launcher
+1
View File
@@ -277,6 +277,7 @@ fn main() -> Result<()> {
engine::Ended::Game if detached => out!("the game's window closed; the engine ended ({})", eng_proc.wait()?),
engine::Ended::Game => out!("the game exited; the engine was stopped"),
engine::Ended::Engine => out!("the engine exited ({}); the game was stopped", eng_proc.wait()?),
engine::Ended::EngineFailed => out!("Enhance could not run ({}; the engine's last lines above say why): the game went on without it", eng_proc.wait()?),
}
status
} else {
+74 -17
View File
@@ -39,17 +39,18 @@ fn c(a: &[&str]) -> Cmd { a.iter().map(|s| s.to_string()).collect() }
/// instead of pretending.
pub fn plan(session: Session, desktop: Desktop, p: &Profile) -> Vec<Cmd> {
let Some(mon) = p.monitor.as_deref() else { return vec![] };
let mode = match (p.width, p.height) { (Some(w), Some(h)) => Some((w, h)), _ => None };
// 0 means not set (`summit profile set --width 0`): never a mode to ask a monitor for
let mode = match (p.width, p.height) { (Some(w), Some(h)) if w > 0 && h > 0 => Some((w, h)), _ => None };
let p = &Profile { refresh_hz: p.refresh_hz.filter(|r| *r > 0.0), width: mode.map(|m| m.0), height: mode.map(|m| m.1), ..p.clone() };
match (session, desktop) {
(Session::Wayland, Desktop::Kde) => {
let mut arg = format!("output.{mon}.enable");
let mut v = vec![c(&["kscreen-doctor", &arg])];
// One call: kscreen-doctor applies all of its arguments as one configuration.
let mut v = vec!["kscreen-doctor".to_string(), format!("output.{mon}.enable")];
if let Some((w, h)) = mode {
let m = match p.refresh_hz { Some(r) => format!("{w}x{h}@{}", r.round() as u32), None => format!("{w}x{h}") };
arg = format!("output.{mon}.mode.{m}");
v.push(c(&["kscreen-doctor", &arg]));
v.push(format!("output.{mon}.mode.{m}"));
}
v
vec![v]
}
(Session::Wayland, Desktop::Wlroots) => match mode {
Some((w, h)) => {
@@ -90,8 +91,9 @@ pub struct Output {
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Mode {
pub width: u32, pub height: u32, pub rates: Vec<f32>,
/// (rate, mode name) for xrandr modes whose name is not just "WxH" (custom modes like "1920x1080_120.00"):
/// xrandr picks a mode by its name, so these need it.
/// (rate, what the tool picks this mode by) when "WxH" is not enough. xrandr: the names of custom modes
/// ("1920x1080_120.00"). kscreen-doctor: the mode id, as its names ("1920x1080@120") can be shared by two
/// modes (119.88 and 119.98 Hz on one real monitor).
pub named: Vec<(f32, String)>,
}
@@ -154,6 +156,7 @@ pub fn parse_kscreen_json(text: &str) -> Vec<Output> {
let r = m["refreshRate"].as_f64().map(|r| (r * 100.0).round() as f32 / 100.0);
push_mode(&mut x.modes, w, h, r);
let id = match &m["id"] { serde_json::Value::String(s) => s.clone(), n => n.to_string() };
if let (Some(r), Some(mm)) = (r, x.modes.iter_mut().find(|mm| mm.width == w && mm.height == h)) { mm.named.push((r, id.clone())); }
if enabled && id == cur_id { x.current = Some((w, h, r.unwrap_or(0.0))); }
}
sort_modes(&mut x.modes);
@@ -203,22 +206,43 @@ pub fn outputs(session: Session, desktop: Desktop) -> Result<Vec<Output>, String
/// None when the profile changes no mode, or the monitor's current mode is unknown.
pub fn restore_profile(outs: &[Output], p: &Profile) -> Option<Profile> {
let mon = p.monitor.as_deref()?;
let p = &Profile { width: p.width.filter(|w| *w > 0), height: p.height.filter(|h| *h > 0), refresh_hz: p.refresh_hz.filter(|r| *r > 0.0), ..p.clone() };
if p.width.is_none() && p.refresh_hz.is_none() { return None; }
let (w, h, r) = outs.iter().find(|o| o.name == mon)?.current?;
if p.width == Some(w) && p.height == Some(h) && p.refresh_hz.is_none_or(|x| (x - r).abs() < 0.01) { return None; }
Some(Profile { monitor: Some(mon.into()), width: Some(w), height: Some(h), refresh_hz: if r > 0.0 { Some(r) } else { None }, ..Default::default() })
}
/// `plan()`, with the outputs this machine has: on X11 a custom mode is asked for by its name, as xrandr needs.
/// `plan()`, with the outputs this machine has: on X11 a custom mode is asked for by its name, as xrandr needs; on KDE
/// Wayland the mode by its id (the closest rate within 0.5 Hz; the highest rate when the profile names none) and no
/// `enable` for an output that is already on.
pub fn plan_for(session: Session, desktop: Desktop, p: &Profile, outs: &[Output]) -> Vec<Cmd> {
let mut cmds = plan(session, desktop, p);
if session != Session::X11 { return cmds; }
let (Some(mon), Some(w), Some(h), Some(r)) = (p.monitor.as_deref(), p.width, p.height, p.refresh_hz) else { return cmds };
let name = outs.iter().find(|o| o.name == mon)
.and_then(|o| o.modes.iter().find(|m| m.width == w && m.height == h))
.and_then(|m| m.named.iter().find(|(x, _)| (x - r).abs() < 0.01)).map(|(_, n)| n.clone());
if let (Some(name), Some(cmd)) = (name, cmds.first_mut()) {
if let Some(i) = cmd.iter().position(|a| a == "--mode") { cmd[i + 1] = name; }
let Some(mon) = p.monitor.as_deref() else { return cmds };
let out = outs.iter().find(|o| o.name == mon);
let mode = |w: u32, h: u32| out.and_then(|o| o.modes.iter().find(|m| m.width == w && m.height == h));
match (session, desktop) {
(Session::X11, _) => {
let (Some(w), Some(h), Some(r)) = (p.width, p.height, p.refresh_hz) else { return cmds };
let name = mode(w, h).and_then(|m| m.named.iter().find(|(x, _)| (x - r).abs() < 0.01)).map(|(_, n)| n.clone());
if let (Some(name), Some(cmd)) = (name, cmds.first_mut()) {
if let Some(i) = cmd.iter().position(|a| a == "--mode") { cmd[i + 1] = name; }
}
}
(Session::Wayland, Desktop::Kde) => {
let Some(cmd) = cmds.first_mut() else { return cmds };
if let (Some(w), Some(h)) = (p.width, p.height) {
let id = mode(w, h).and_then(|m| match p.refresh_hz {
Some(r) => m.named.iter().filter(|(x, _)| (x - r).abs() < 0.5)
.min_by(|a, b| (a.0 - r).abs().total_cmp(&(b.0 - r).abs())).map(|(_, id)| id.clone()),
None => m.named.iter().max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, id)| id.clone()),
});
if let (Some(id), Some(last)) = (id, cmd.last_mut()) { *last = format!("output.{mon}.mode.{id}"); }
}
if out.is_some_and(|o| o.current.is_some()) { cmd.retain(|a| a != &format!("output.{mon}.enable")); }
if cmd.len() == 1 { cmds.clear(); }
}
_ => {}
}
cmds
}
@@ -243,12 +267,20 @@ mod tests {
}
#[test] fn kde_wayland_plan() {
let p = plan(Session::Wayland, detect_desktop_from("KDE"), &prof());
assert_eq!(p[1], vec!["kscreen-doctor", "output.HDMI-A-1.mode.3840x2160@60"]);
assert_eq!(p, vec![vec!["kscreen-doctor", "output.HDMI-A-1.enable", "output.HDMI-A-1.mode.3840x2160@60"]]);
}
#[test] fn x11_plan() {
let p = plan(Session::X11, Desktop::Other, &prof());
assert_eq!(p[0].join(" "), "xrandr --output HDMI-A-1 --mode 3840x2160 --rate 60");
}
#[test] fn zero_size_is_not_a_mode() {
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(0), height: Some(0), refresh_hz: Some(60.0), ..Default::default() };
assert_eq!(plan(Session::Wayland, Desktop::Kde, &p), vec![vec!["kscreen-doctor", "output.HDMI-A-1.enable"]]);
assert_eq!(plan(Session::X11, Desktop::Other, &p)[0].join(" "), "xrandr --output HDMI-A-1 --rate 60");
let o = parse_kscreen_json(KSCREEN_REAL);
assert!(plan_for(Session::Wayland, Desktop::Kde, &p, &o).is_empty(), "the output is on and no mode is asked for");
assert_eq!(restore_profile(&o, &Profile { refresh_hz: None, ..p }), None);
}
#[test] fn gnome_wayland_honestly_empty() { assert!(plan(Session::Wayland, Desktop::Gnome, &prof()).is_empty()); }
const XRANDR: &str = "Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
Virtual-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 0mm x 0mm
@@ -303,4 +335,29 @@ HDMI-1 disconnected (normal left inverted right x axis y axis)
assert_eq!(restore_profile(&o, &same), None); // nothing changes, nothing to undo
assert_eq!(restore_profile(&o, &Profile { monitor: Some("Virtual-1".into()), ..Default::default() }), None);
}
// From the owner's desktop (Plasma 6.8.2, `kscreen-doctor -j`, trimmed): two modes share the name "1920x1080@120".
const KSCREEN_REAL: &str = r#"{"outputs":[{"name":"HDMI-A-1","connected":true,"enabled":true,"currentModeId":"49","modes":[
{"id":"46","name":"1920x1080@144","refreshRate":143.9810028076172,"size":{"height":1080,"width":1920}},
{"id":"48","name":"1920x1080@120","refreshRate":119.87899780273438,"size":{"height":1080,"width":1920}},
{"id":"49","name":"1920x1080@120","refreshRate":119.98200225830078,"size":{"height":1080,"width":1920}},
{"id":"58","name":"1280x720@60","refreshRate":60,"size":{"height":720,"width":1280}}]},
{"name":"DP-3","connected":true,"enabled":false,"currentModeId":"","modes":[
{"id":"5","name":"1920x1080@60","refreshRate":60,"size":{"height":1080,"width":1920}}]}]}"#;
#[test] fn kde_plan_uses_mode_ids_and_restores_the_exact_mode() {
let o = parse_kscreen_json(KSCREEN_REAL);
assert_eq!(o[0].current, Some((1920, 1080, 119.98)));
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(1280), height: Some(720), refresh_hz: Some(60.0), ..Default::default() };
// the output is on: no `enable`, one call, the mode by id
assert_eq!(plan_for(Session::Wayland, Desktop::Kde, &p, &o), vec![vec!["kscreen-doctor", "output.HDMI-A-1.mode.58"]]);
// back to 119.98 Hz, not the 119.88 Hz mode that has the same name
let back = restore_profile(&o, &p).unwrap();
assert_eq!(plan_for(Session::Wayland, Desktop::Kde, &back, &o), vec![vec!["kscreen-doctor", "output.HDMI-A-1.mode.49"]]);
let fast = Profile { width: Some(1920), height: Some(1080), refresh_hz: None, ..p.clone() };
assert_eq!(plan_for(Session::Wayland, Desktop::Kde, &fast, &o), vec![vec!["kscreen-doctor", "output.HDMI-A-1.mode.46"]]);
// only a monitor, already on: nothing to run
assert!(plan_for(Session::Wayland, Desktop::Kde, &Profile { monitor: Some("HDMI-A-1".into()), ..Default::default() }, &o).is_empty());
// an output that is off is turned on in the same call
let off = Profile { monitor: Some("DP-3".into()), width: Some(1920), height: Some(1080), refresh_hz: Some(60.0), ..Default::default() };
assert_eq!(plan_for(Session::Wayland, Desktop::Kde, &off, &o), vec![vec!["kscreen-doctor", "output.DP-3.enable", "output.DP-3.mode.5"]]);
}
}
+154 -3
View File
@@ -52,7 +52,7 @@ pub fn checks(session: Session, engine: Option<&Path>, model: Option<&str>) -> V
let mut v = vec![];
match session {
Session::X11 => v.push(Check::new("session", Status::Ok, "X11: Enhance, the save-clip key and display profiles work here")),
Session::Wayland => v.push(Check::new("session", Status::Warn, "Wayland: Enhance can't capture a window here (needs an X11 session); the launcher works")),
Session::Wayland => v.push(Check::new("session", Status::Ok, "Wayland: Enhance reads XWayland games directly and native Wayland ones through the ScreenCast portal (see the lines below)")),
Session::Unknown => v.push(Check::new("session", Status::Warn, "no display found (DISPLAY and WAYLAND_DISPLAY are unset)")),
}
match engine {
@@ -90,7 +90,10 @@ pub fn checks(session: Session, engine: Option<&Path>, model: Option<&str>) -> V
let tool = |name: &'static str, ok: bool, what: &str, fix: &str| {
Check::new(name, if ok { Status::Ok } else { Status::Missing }, if ok { what.to_string() } else { format!("not on PATH: {fix}") })
};
v.push(tool("ffmpeg", on_path("ffmpeg"), "reads the game window for Enhance", "Enhance can't capture a window"));
v.push(tool("ffmpeg", on_path("ffmpeg"), "reads the game window for Enhance (X11 and XWayland games), saves clips", "Enhance can't capture an X11 window"));
if session == Session::Wayland {
v.extend(wayland_checks(&WaylandProbe::read(engine)));
}
if session != Session::Wayland {
v.push(tool("xrandr", on_path("xrandr"), "sets and restores the monitor mode", "display profiles (resolution, refresh) do nothing"));
}
@@ -103,6 +106,125 @@ pub fn checks(session: Session, engine: Option<&Path>, model: Option<&str>) -> V
v
}
/// What `summit doctor` looks at on a Wayland session (read from the machine by `read()`, judged by `wayland_checks`).
#[derive(Debug, Clone, Default)]
pub struct WaylandProbe {
pub desktop: Option<crate::display::Desktop>,
/// DISPLAY is set: XWayland runs, so XWayland games are read directly and the engine's picture can go on top.
pub xwayland: bool,
/// `gdbus introspect` of the desktop portal, None if it didn't answer.
pub portal: Option<String>,
/// $XDG_RUNTIME_DIR/pipewire-0 exists.
pub pipewire: bool,
/// gst-launch-1.0 is there and `gst-inspect-1.0 pipewiresrc` finds GStreamer's PipeWire plugin.
pub gst_pipewire: bool,
/// org.kde.KWin is on the session bus (its window list tells which window is the game, and where).
pub kwin: bool,
/// summit.desktop is in an applications folder the portal reads: it needs it to give Summit an app id.
pub desktop_file: bool,
/// The engine's venv can import jeepney (D-Bus for the portals and KWin). None: no venv to ask.
pub jeepney: Option<bool>,
/// The monitor tool of this desktop is on PATH (kscreen-doctor, wlr-randr), None when there is none to have.
pub monitor_tool: Option<(&'static str, bool)>,
/// "<GPU name>, <driver>" from nvidia-smi.
pub gpu: Option<String>,
}
fn sh(argv: &[&str]) -> Option<String> {
let o = Command::new(argv[0]).args(&argv[1..]).stderr(std::process::Stdio::null()).output().ok()?;
o.status.success().then(|| String::from_utf8_lossy(&o.stdout).into_owned())
}
/// The value of `readonly u NAME = 7;` in `gdbus introspect` output.
pub fn introspect_u32(text: &str, name: &str) -> Option<u32> {
let key = format!(" {name} = ");
text.lines().find_map(|l| l.split_once(&key).and_then(|(_, v)| v.trim().trim_end_matches(';').parse().ok()))
}
impl WaylandProbe {
pub fn read(engine: Option<&Path>) -> Self {
let desktop = crate::display::detect_desktop();
let data_dirs: Vec<PathBuf> = dirs::data_dir().into_iter()
.chain(std::env::var("XDG_DATA_DIRS").unwrap_or_else(|_| "/usr/local/share:/usr/share".into()).split(':').filter(|d| !d.is_empty()).map(PathBuf::from))
.collect();
let runtime = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from);
WaylandProbe {
desktop: Some(desktop),
xwayland: std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()),
portal: sh(&["gdbus", "introspect", "--session", "--dest", "org.freedesktop.portal.Desktop", "--object-path", "/org/freedesktop/portal/desktop"]),
pipewire: runtime.is_some_and(|r| r.join("pipewire-0").exists()),
gst_pipewire: on_path("gst-launch-1.0") && sh(&["gst-inspect-1.0", "pipewiresrc"]).is_some(),
kwin: sh(&["gdbus", "call", "--session", "--dest", "org.freedesktop.DBus", "--object-path", "/org/freedesktop/DBus",
"--method", "org.freedesktop.DBus.NameHasOwner", "org.kde.KWin"]).is_some_and(|o| o.contains("true")),
desktop_file: data_dirs.iter().any(|d| d.join("applications/summit.desktop").is_file()),
jeepney: engine.map(|e| e.join(".venv/bin/python")).filter(|p| p.is_file())
.map(|py| Command::new(py).args(["-c", "import jeepney"]).output().is_ok_and(|o| o.status.success())),
monitor_tool: match desktop {
crate::display::Desktop::Kde => Some(("kscreen-doctor", on_path("kscreen-doctor"))),
crate::display::Desktop::Wlroots => Some(("wlr-randr", on_path("wlr-randr"))),
_ => None,
},
gpu: sh(&["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"]).map(|s| s.lines().next().unwrap_or("").trim().to_string()),
}
}
}
/// The Wayland lines of `summit doctor`: each says what it is for and what is off without it.
pub fn wayland_checks(p: &WaylandProbe) -> Vec<Check> {
use crate::display::Desktop;
let mut v = vec![];
v.push(if p.xwayland {
Check::new("xwayland", Status::Ok, "XWayland games (Proton, Wine, most older games) are read directly; the engine's picture goes on top through XWayland")
} else {
Check::new("xwayland", Status::Missing, "no XWayland (DISPLAY unset): XWayland games can't be read and the engine's picture can't stay on top of the game")
});
match &p.portal {
None => v.push(Check::new("portal", Status::Missing, "xdg-desktop-portal didn't answer: native Wayland games can't be captured, no global save key")),
Some(text) => {
let types = introspect_u32(text, "AvailableSourceTypes").unwrap_or(0);
v.push(if text.contains("org.freedesktop.portal.ScreenCast") && types & 2 != 0 {
Check::new("screencast", Status::Ok, "ScreenCast portal shares single windows: native Wayland games (a dialog the first time)")
} else if text.contains("org.freedesktop.portal.ScreenCast") {
Check::new("screencast", Status::Missing, "the ScreenCast portal can't share a single window here: native Wayland games can't be captured")
} else {
Check::new("screencast", Status::Missing, "no ScreenCast portal (install xdg-desktop-portal-kde, -gnome, -wlr or -hyprland): native Wayland games can't be captured")
});
let shortcuts = text.contains("org.freedesktop.portal.GlobalShortcuts");
v.push(match (shortcuts, p.desktop_file) {
(true, true) => Check::new("save key", Status::Ok, "Ctrl+Alt+R from any window, through the GlobalShortcuts portal"),
(true, false) => Check::new("save key", Status::Warn, "summit.desktop isn't installed, so the GlobalShortcuts portal won't give Summit an app id: Ctrl+Alt+R works only while an XWayland game has the keyboard (install.sh installs it)"),
(false, _) => Check::new("save key", Status::Warn, "no GlobalShortcuts portal: Ctrl+Alt+R works only while an XWayland game has the keyboard; R in the engine window is not reachable while the game has it"),
});
}
}
v.push(match (p.pipewire, p.gst_pipewire) {
(true, true) => Check::new("pipewire", Status::Ok, "PipeWire and GStreamer's pipewiresrc: frames of native Wayland games"),
(false, _) => Check::new("pipewire", Status::Missing, "no PipeWire socket: native Wayland games can't be captured"),
(true, false) => Check::new("pipewire", Status::Missing, "gst-launch-1.0 or GStreamer's PipeWire plugin is missing (gst-plugin-pipewire / gstreamer1.0-pipewire): native Wayland games can't be captured"),
});
match p.desktop {
Some(Desktop::Kde) => v.push(if p.kwin {
Check::new("kwin", Status::Ok, "KWin's window list: finds the game's native Wayland window and puts the picture over it")
} else {
Check::new("kwin", Status::Warn, "KWin isn't on the session bus: a native Wayland game has to be picked in the share dialog, the picture covers the --monitor screen")
}),
_ => v.push(Check::new("windows", Status::Warn, "not KDE: a native Wayland game has to be picked in the share dialog each time Summit can't tell it apart, and the picture goes over the monitor (untested)")),
}
if let Some(false) = p.jeepney {
v.push(Check::new("jeepney", Status::Missing, "the engine's venv has no jeepney (D-Bus): no portals, no KWin list (uv pip install jeepney)"));
}
match p.monitor_tool {
Some((name, true)) => v.push(Check::new("monitors", Status::Ok, format!("{name}: sets and restores the monitor mode"))),
Some((name, false)) => v.push(Check::new("monitors", Status::Missing, format!("{name} not on PATH: display profiles (resolution, refresh) do nothing"))),
None => v.push(Check::new("monitors", Status::Warn, "no monitor tool for this Wayland desktop (GNOME has none): display profiles are skipped with a message")),
}
v.push(match &p.gpu {
Some(g) => Check::new("gpu", Status::Ok, g.clone()),
None => Check::new("gpu", Status::Warn, "nvidia-smi found no NVIDIA GPU: Enhance needs one (see the torch line)"),
});
v
}
#[cfg(test)]
mod tests {
use super::*;
@@ -117,7 +239,7 @@ mod tests {
}
#[test] fn missing_engine_is_named() {
let c = checks(Session::Wayland, None, None);
assert_eq!(c[0].status, Status::Warn);
assert_eq!(c[0].status, Status::Ok);
assert!(c.iter().any(|c| c.name == "engine" && c.status == Status::Missing));
assert!(!c.iter().any(|c| c.name == "xrandr"), "xrandr is not used on Wayland");
}
@@ -129,4 +251,33 @@ mod tests {
assert!(c.iter().any(|c| c.name == "model" && c.status == Status::Warn), "{c:?}");
std::fs::remove_dir_all(&d).unwrap();
}
const INTROSPECT: &str = "node /org/freedesktop/portal/desktop {\n interface org.freedesktop.portal.GlobalShortcuts {\n };\n interface org.freedesktop.portal.ScreenCast {\n properties:\n readonly u AvailableSourceTypes = 7;\n readonly u AvailableCursorModes = 7;\n };\n};\n";
fn plasma() -> WaylandProbe {
WaylandProbe { desktop: Some(crate::display::Desktop::Kde), xwayland: true, portal: Some(INTROSPECT.into()), pipewire: true, gst_pipewire: true,
kwin: true, desktop_file: true, jeepney: Some(true), monitor_tool: Some(("kscreen-doctor", true)), gpu: Some("NVIDIA GeForce RTX 5080, 615.78.08".into()) }
}
#[test] fn introspect_values() {
assert_eq!(introspect_u32(INTROSPECT, "AvailableSourceTypes"), Some(7));
assert_eq!(introspect_u32(INTROSPECT, "Missing"), None);
}
#[test] fn plasma_wayland_all_ok() {
let c = wayland_checks(&plasma());
assert!(c.iter().all(|c| c.status == Status::Ok), "{c:?}");
}
#[test] fn wayland_says_what_each_missing_piece_turns_off() {
let p = WaylandProbe { xwayland: false, desktop_file: false, gst_pipewire: false, jeepney: Some(false), ..plasma() };
let c = wayland_checks(&p);
let find = |n: &str| c.iter().find(|c| c.name == n).unwrap().clone();
assert_eq!(find("xwayland").status, Status::Missing);
assert!(find("save key").detail.contains("summit.desktop"));
assert!(find("pipewire").detail.contains("gst-plugin-pipewire"));
assert_eq!(find("jeepney").status, Status::Missing);
let none = wayland_checks(&WaylandProbe { portal: None, ..plasma() });
assert!(none.iter().any(|c| c.name == "portal" && c.status == Status::Missing));
let window_less = "interface org.freedesktop.portal.ScreenCast {\n readonly u AvailableSourceTypes = 1;\n";
let mon = wayland_checks(&WaylandProbe { portal: Some(window_less.into()), ..plasma() });
assert!(mon.iter().any(|c| c.name == "screencast" && c.status == Status::Missing));
let gnome = wayland_checks(&WaylandProbe { desktop: Some(crate::display::Desktop::Gnome), monitor_tool: None, ..plasma() });
assert!(gnome.iter().any(|c| c.name == "monitors" && c.status == Status::Warn));
}
}
+17 -2
View File
@@ -131,7 +131,10 @@ pub fn extra_args(env: Option<&str>) -> Vec<String> {
/// Which of the two processes of `summit run --enhance` ended first, or `Stopped`: `should_stop` said so (summit
/// itself got SIGTERM, SIGINT or SIGHUP) and both were stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ended { Game, Engine, Stopped }
pub enum Ended { Game, Engine, Stopped,
/// The engine failed (a non-zero exit: no capture, the share dialog cancelled, a crash): the game was left
/// running, without Enhance, and waited for.
EngineFailed }
/// Wait until the game or the engine exits, then stop the other one: SIGTERM first (the engine closes its window and
/// prints its summary; a game saves), SIGKILL if it is still there after `grace`. Returns who ended first and the
@@ -151,7 +154,9 @@ pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Chil
if !handed_off && game.try_wait()?.is_some() {
if detached { handed_off = true; } else { return Ok(Ended::Game); }
}
if engine.try_wait()?.is_some() { return Ok(if handed_off { Ended::Game } else { Ended::Engine }); }
if let Some(st) = engine.try_wait()? {
return Ok(if handed_off { Ended::Game } else if st.success() { Ended::Engine } else { Ended::EngineFailed });
}
std::thread::sleep(poll);
}
};
@@ -164,6 +169,7 @@ pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Chil
_ if handed_off => {}
Ended::Game => stop(engine, grace)?,
Ended::Engine => stop(game, grace)?,
Ended::EngineFailed => { let (st, _) = wait_or_stop(game, grace, should_stop)?; return Ok((first, st)); }
}
Ok((first, game.wait()?))
}
@@ -331,6 +337,15 @@ mod tests {
assert_eq!(who, Ended::Engine);
assert!(!status.success(), "the game was terminated, not left running");
}
#[test] fn supervise_leaves_the_game_running_when_the_engine_fails() {
// e.g. the Wayland share dialog was cancelled: the game goes on without Enhance
let (mut game, mut eng) = (sh("sleep 0.6; exit 5"), sh("exit 1"));
let t = std::time::Instant::now();
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), false, &|| false).unwrap();
assert_eq!(who, Ended::EngineFailed);
assert_eq!(status.code(), Some(5), "the game ran to its own end");
assert!(t.elapsed() >= std::time::Duration::from_millis(500));
}
#[test] fn supervise_detached_waits_for_the_engine() {
// the launcher command returns at once; the engine (the game's window) goes on, and is not stopped
let (mut game, mut eng) = (sh("exit 0"), sh("sleep 0.6"));
+2 -2
View File
@@ -17,7 +17,7 @@ pub fn portal_has_global_shortcuts() -> Option<bool> {
pub fn status(session: Session, portal: Option<bool>) -> String {
match (session, portal) {
(Session::X11, _) => format!("{SAVE_KEY} saves from any window (X11 key grab)."),
(Session::Wayland, Some(true)) => format!("{SAVE_KEY} through the GlobalShortcuts portal (untested)."),
(Session::Wayland, Some(true)) => format!("{SAVE_KEY} through the GlobalShortcuts portal (needs summit.desktop installed; else only while an XWayland game has the keys)."),
(Session::Wayland, Some(false)) => "No global save key: this desktop has no GlobalShortcuts portal. R in the engine window.".into(),
(Session::Wayland, None) => "No global save key: the desktop portal did not answer. R in the engine window.".into(),
(Session::Unknown, _) => "No global save key: no X11 or Wayland session found.".into(),
@@ -30,7 +30,7 @@ mod tests {
#[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("untested"));
assert!(status(Session::Wayland, Some(true)).contains("GlobalShortcuts portal"));
assert!(status(Session::Wayland, Some(false)).starts_with("No global save key"));
assert!(status(Session::Unknown, Some(true)).starts_with("No global save key"));
}
+2 -1
View File
@@ -221,8 +221,9 @@ impl App {
match launch::plan(e, self.cli().as_deref(), true) {
_ if launch::is_install(e) => (false, "Enhance needs the game installed.".to_string()),
launch::Plan::Unsupported(why) => (false, format!("Enhance is not available: {why}.")),
launch::Plan::Run(_) if session != display::Session::X11 => (false, format!("Enhance needs an X11 session; this is {session:?} (Wayland window capture is not built).")),
launch::Plan::Run(_) if session == display::Session::Unknown => (false, "Enhance needs a desktop session (X11 or Wayland); none was found.".to_string()),
launch::Plan::Run(_) if e.source == Source::Steam => (true, "Enhance: the engine waits for the window of class steam_app_<id> (Proton games) and runs on it until it closes. Not tested with a real Steam game yet.".to_string()),
launch::Plan::Run(_) if session == display::Session::Wayland => (true, "Enhance: frame generation and the upscaler from this game's profile run on its window, live, until either one exits. Wayland: XWayland games directly; a native Wayland game asks once to share its window.".to_string()),
launch::Plan::Run(_) => (true, "Enhance: frame generation and the upscaler from this game's profile run on its window, live, until either one exits.".to_string()),
}
}
+154
View File
@@ -0,0 +1,154 @@
WAYLAND: PASS
# Wayland report
Run on 2026-11-24 on the owner's desktop: Arch Linux, KDE Plasma 6.8.2 Wayland (KWin 6.8.2, `wayland-1`, XWayland
`:0`), NVIDIA GeForce RTX 5080 (driver 615.78.08), three monitors at scale 1 (HDMI-A-1 1920x1080 left, DP-1
1920x1080 @ 240 Hz middle, DP-2 2560x1600 right). Everything ran from `~/summit-test` (source, `cargo build
--release` there, engine venv made with `uv venv -p 3.12` plus torch 2.11.0+cu128; torch lists `sm_120` and ran a
CUDA matmul on the 5080). Summit's config, data, cache and clips were pointed into `~/summit-test` with the XDG
variables. Tests ran on HDMI-A-1 except where noted.
PASS means the whole path below ran on that desktop and was looked at: **Voidrunner started with Enhance on
Wayland, from the launcher's Play button and from `summit run custom:voidrunner --enhance`; the engine's picture
with the stats line and the watermark sat over the game; the game kept getting keys; Ctrl+Alt+R through the
GlobalShortcuts portal saved a clip; killing the game stopped the engine and put the monitor's mode back.**
It does **not** mean every Wayland case works. Most importantly: **Voidrunner itself cannot run as a native Wayland
program** (its GLFW is built without the Wayland backend: `X11: The DISPLAY environment variable is missing`, then
it crashes), so the Voidrunner runs are **XWayland** runs. The native Wayland capture path (portal + PipeWire) was
run with a stand-in test window (`engine/devtools/wayland_standin.py`), not with a real game.
## How it works now
| Game's window | Capture | Picture on top | Clip key |
|---|---|---|---|
| XWayland (Proton, Wine, most older native games, Voidrunner) | as on X11: Composite + `ffmpeg x11grab` through XWayland's `DISPLAY`; no dialog | an override-redirect window through XWayland: KWin keeps it above everything (a fullscreen game too), it never gets the keyboard, the pointer goes through | GlobalShortcuts portal; without it, an X11 key grab through XWayland (fires while an XWayland window has the keyboard) |
| Native Wayland (KDE) | `xdg-desktop-portal` ScreenCast (one window, pointer hidden, `persist_mode` 2) to a PipeWire stream, read by `gst-launch-1.0 pipewiresrc` piping raw BGR (CPU copy) | the same XWayland window, placed from KWin's window list (a one-shot KWin script reports pid, title, place and focus over D-Bus) | GlobalShortcuts portal |
The engine picks between the two by looking for the game (`pid:N`, title, `class:`) every half second among
XWayland windows and among KWin's native windows. The share dialog shows once; the restore token is kept in
`~/.config/summit/screencast-token` (mode 600).
## Verified (each was run on the owner's desktop and its output or image looked at)
1. **XWayland windows can be read with x11grab** on KWin Wayland + NVIDIA (the engine's old docstring said they
could not): a 30-frame grab of Voidrunner's 1280x720 window decoded with the right picture.
2. **Overlay through XWayland**: GLFW picked its Wayland backend by default (so the first try was not the X11
path); the engine now asks GLFW for X11 when the overlay is needed on a Wayland session. The override-redirect
window covered HDMI-A-1 over the game, `_NET_ACTIVE_WINDOW` stayed on the game.
3. **Found and fixed (not Wayland-only): `--monitor` with the fullscreen overlay never matched** (GLFW monitor
pointers compared by identity), so the picture covered the whole X screen, all three monitors (seen once, about
10 s). Now matched by name: it covers HDMI-A-1 only. The single-monitor X11 test VM never showed this.
4. **Keys reach the game under the picture**. Keys were injected with `xdotool` (XTest, through KWin's input
emulation for XWayland: **KDE asked the owner to allow it once, he did**) and only while the game was the active
window (checked before every key; it caught the owner clicking elsewhere several times and sent nothing). The game
went from its splash to New Run and the artifact choice and moved the selection with `a`/`d`. For the native
stand-in, its own log shows `key a`, `key b`, `key c` with the picture on top, and no focus change.
5. **`summit run custom:voidrunner --enhance`** (profile: RIFE, FSR, fullscreen, HDMI-A-1, 1920x1080 @ 60): game
and engine started, engine picture over HDMI-A-1 (`60 fps game 60 delay 20-28 ms` on the stats line), the
watermark bottom-left, Ctrl+Alt+R saved `Voidrunner ….mp4` (13.4 s, the buffer was 13 s old), killing the game
ended `summit run` in 250-700 ms with no process left.
6. **From the launcher**: `summit-gui` on Voidrunner's page, Enhance on, Play (Return, sent only while KWin said the
launcher was the active window): it ran `summit run custom:voidrunner --enhance --title=Voidrunner -- …`; then as
in 5; clip 14.75 s, H.264 1280x720, 884 frames, `ffmpeg -f null` decodes all of it (one "non monotonically
increasing dts" warning, as on X11). **Found and fixed**: the launcher refused Enhance on any non-X11 session.
7. **Display profile on KDE Wayland**, for real: HDMI-A-1 went from mode id 49 (1920x1080 @ 119.98) to 51 (@ 60)
during the game and back to **49** after, four times. **Found and fixed**: the old plan asked by name
(`1920x1080@120`), which this monitor has twice (ids 48 @ 119.88 and 49 @ 119.98), so the restore could pick the
wrong one; it also ran `output.X.enable` on an output that was on, as a separate call. Now: one `kscreen-doctor`
call (as its `--help` says), the mode by **id** from `kscreen-doctor -j`, no `enable` for an output that is on.
Syntax checked against the installed kscreen-doctor 6.8.2 (`--help`, `-j`).
8. **Found and fixed**: `summit profile set --width 0 --height 0` made `summit run` call
`kscreen-doctor output.HDMI-A-1.mode.0x0@60`. kscreen-doctor refused it and the monitors stayed as they were
(checked: DP-2 1, DP-1 17, HDMI-A-1 49, the same as at the start); zeros now mean "not set".
9. **GlobalShortcuts portal**: Plasma refuses a host program without an app id (`An app id is required`). Summit now
calls `org.freedesktop.host.portal.Registry.Register("summit")` first. That needs `summit.desktop` in an
applications folder whose `Exec` program exists (GLib skips it otherwise: the first try failed until
`summit-gui` was built). With the file there (the owner allowed `~/.local/share/applications/summit.desktop`
for the test; `install.sh` installs one), the shortcut was bound in 1.7 s with no dialog, and Ctrl+Alt+R saved
clips. The game also sees the Ctrl and Alt presses (KWin swallows only the R).
10. **XWayland key grab fallback**: before the app id fix, the portal failed and the engine fell back to an X11
grab through XWayland; Ctrl+Alt+R with the XWayland game focused saved a 15.4 s clip.
11. **Native Wayland window through the portal** (stand-in window): the **share dialog appeared and the owner
picked the window within 9 s**. 299 new frames in 6 s (49.7 a second) at 1280x720. The next run, **with a new
window of the same program**, was restored from the token with **no dialog** (`shared after 0.0 s`), and so
were the three runs after it. Picture over the window (windowed: lined up with the window's frame; KWin's window
stream includes the title bar) and over its monitor (fullscreen), stats and watermark drawn, clip saved with the
portal key (4.3 s: RIFE's warm-up took most of the short run), stream end noticed 603 ms after the window
closed.
12. **Fullscreen games under the picture**: Voidrunner in its own fullscreen mode (XWayland) and the stand-in
fullscreen on HDMI-A-1 (native): the picture stayed on top in both. With the native one fullscreen and nothing
else touched, KWin's active window stayed the stand-in for 16 s while the engine drew (polled every 0.5 s).
13. **A failing engine no longer kills the game**: `summit run … --enhance --window class:nothing --wait 3`: the
engine said `no window matches 'class:nothing' after 3 s`, the game kept running, `summit run` printed
`Enhance could not run (exit status: 1; …): the game went on without it`, and ended when the game ended.
14. **`summit doctor`** on the desktop: session, XWayland, ScreenCast (window sharing), save key (portal + desktop
file), PipeWire + `pipewiresrc`, KWin, `kscreen-doctor`, GPU and driver, torch with CUDA: all ok. With the
desktop file absent it warns that Ctrl+Alt+R only works while an XWayland game has the keyboard.
15. **`install.sh --dry-run`** on the desktop: detects `wayland` and adds `gstreamer gst-plugins-base
gst-plugin-pipewire` to the pacman line (all three were already installed there). Not run for real.
16. **Gamescope 3.17.0** (evaluated, not wired in): `gamescope -w 1280 -h 720 -W 1920 -H 1080 -F fsr --
./top_down_shooter` runs nested on Plasma Wayland on the 5080 (Vulkan, its Wayland backend) and showed
Voidrunner upscaled with its own FSR. It is an upscaler and a nested compositor, no frame generation; its window
is a native Wayland window, so Summit's engine could only read it through the portal. Could be offered later as
a profile option ("upscale with gamescope"); not a dependency.
17. Tests: `cargo test --workspace` (1 + 104 + 19) and the engine's pytest on the desktop's venv (38 passed, 1
skipped) before the commits.
## Measured
| | XWayland game (Voidrunner 1280x720) | Native stand-in (PipeWire) |
|---|---|---|
| Frames read | ~60 grabs a second, 0-1 % unchanged | ~50 new frames a second at 1280x720 alone; 744 in about 12 s inside the engine |
| Engine output | 59.2-59.7 frames a second (60 Hz target) | 59.5 |
| FSR draw on the GPU | 0.06 ms at 1920x1080 | 0.06 ms at 1860x1080 |
| Frame reaches the engine -> on screen | p50 21-38 ms, p95 22-55 ms (five runs) | p50 21.8-22.6 ms, p95 24-25 ms |
| CPU | ffmpeg x11grab (not measured here) | `gst-launch-1.0` 18-19 % of one core at 1920x1080; the engine process 69 % |
"Reaches the engine -> on screen" is the engine's own measure. The time from the game drawing a frame to the engine
receiving it (x11grab polling, KWin's screencast) was **not** measured. The CPU copy was kept: DMA-BUF import was
not tried.
## Not verified, or known limits
- **A real native Wayland game** (only the stand-in). Voidrunner can't run on Wayland natively.
- **Pressing keys on a real keyboard**: all keys were injected (XTest through KWin, allowed by the owner).
- **Other desktops**: GNOME, sway, Hyprland were not available. Without KWin the engine can't tell which native
window is the game: the dialog lets the user pick it and the picture goes over the `--monitor` screen (written,
untested). GNOME has no monitor tool (`summit doctor` says so).
- **Fractional scaling**: all three monitors were at scale 1. With scaling, XWayland's coordinates and KWin's
differ and the picture may not line up. Untested.
- **The restore token across a reboot or for a different game** was not tried; the dialog will likely show again
for a different program.
- **One unexplained focus change**: in one run the native stand-in logged `focus out` about 5 s after it started,
right after an XWayland run on the same monitor had been stopped; a clean repeat (item 12) kept the focus. Not
understood.
- **The share dialog's window choice is the user's**: if they pick another window, the engine enhances that one.
- **Output at 90/120/240 Hz, VRR, HDR**: the engine ran at 60 Hz; DP-1 runs at 240 Hz and was not used for output
tests.
- **`install.sh` for real** on the desktop (only `--dry-run`). The global key through the portal needs the
installed `summit.desktop`; a Summit run from a checkout without it gets the XWayland grab only.
- The launcher's other keys on Wayland (only Return on Play was pressed); which backend the launcher window used
(native Wayland or XWayland) was not checked.
- DMA-BUF / zero copy (see above). Clip audio. Steam or Proton games on Wayland.
## On the owner's machine during and after the run
- Left: `~/summit-test` (8.9 GB: source, `target/`, the engine venv with torch, uv's cache and Python, the game
copy, logs, the two clips). Delete it with `rm -rf ~/summit-test` when done.
- Created and **removed again**: `~/.local/share/applications/summit.desktop` (allowed by the owner for the portal
test), the `[summit]` component in `~/.config/kglobalshortcutsrc` that the portal created (removed through
kglobalaccel's `cleanUp`), the ScreenCast permission entry for app `summit` (deleted from the permission store by
its token id), `~/.local/share/summit` (made by one `summit add` before I pointed `XDG_DATA_HOME` away; moved
into `~/summit-test`), the full-desktop screenshots.
- **Still there, the owner's choice**: KDE's permission for legacy X11 programs to send input (the dialog for
`xdotool`); it can be revoked in System Settings. I did not remove anything from the `remote-desktop` permission
table because I could not tell which entry was that one.
- **Mistakes**: my first test scripts started the game through a subshell and killed only the subshell, so five
Voidrunner windows stayed open on HDMI-A-1 for a few minutes. All five were killed by PID after checking that
each one's executable was `~/summit-test/game/top_down_shooter`. The overlay covered all three monitors once for
about 10 s (the `--monitor` bug, item 3) and DP-1, the owner's main screen, for about 12 s in one native test.
HDMI-A-1's refresh rate was switched to 60 Hz and back four times.
- Nothing was installed system-wide, no sudo, nothing under `~/Games`, `~/Projects` or Steam was written; the
launcher read the Steam library while it ran.
+44
View File
@@ -0,0 +1,44 @@
# wayland-capture (agent report)
Full report with every check: [docs/WAYLAND_REPORT.md](../WAYLAND_REPORT.md) (first line `WAYLAND: PASS`).
**What changed**
- `engine/framegen/window_portal.py` (new): Wayland window capture. It finds the game among XWayland windows (read as on X11) and KWin's native windows. Native ones go through the ScreenCast portal (one window, pointer hidden, persist_mode 2, restore token in `~/.config/summit/screencast-token`), and `gst-launch-1.0 pipewiresrc` pipes the frames as raw BGR (a CPU copy).
- `engine/framegen/kwin.py` (new): KWin's window list (pid, title, frame geometry, focus, XWayland or not) from a one-shot KWin script that reports back over D-Bus.
- `engine/framegen/io.py`: the overlay uses GLFW's X11 platform on a Wayland session (an override-redirect XWayland window). Fixed `--monitor` with the fullscreen overlay: it used to cover every monitor.
- `engine/framegen/window_x11.py`: allowed on Wayland when XWayland is there.
- `engine/framegen/globalkeys.py`: GlobalShortcuts registers app id `summit` through `host.portal.Registry` first. Falls back to an XWayland key grab.
- `engine/run.py`: Wayland sessions use window_portal.
- `engine/devtools/wayland_standin.py`: a native Wayland test window that logs its keys and focus.
- `engine/requirements.txt`: jeepney is now required.
- `crates/summit-core/src/display.rs`: KDE plan is one `kscreen-doctor` call, picks the mode by id, adds no `enable` for an output that is on, and treats 0 sizes as not set.
- `crates/summit-core/src/engine.rs` + CLI: an engine that fails leaves the game running.
- `crates/summit-core/src/doctor.rs`: Wayland checks.
- `crates/summit-core/src/hotkey.rs`: the status text.
- `crates/summit-gui/src/main.rs`: Enhance is allowed on Wayland.
- `install.sh`: GStreamer + PipeWire plugin on Wayland.
- README status rows; `docs/media/wayland/`.
**How it was verified**
- Everything ran on the owner's desktop (Plasma 6.8.2 Wayland, RTX 5080) from `~/summit-test`.
- Voidrunner (XWayland only) ran with Enhance from `summit run` and from the launcher's Play.
- Overlay + watermark seen in screenshots; keys reached the game (xdotool, guarded by the active window; KDE asked the owner once to allow it).
- Ctrl+Alt+R through the portal saved clips; ffprobe/ffmpeg read them.
- Clean stop; HDMI-A-1's mode switched and was restored by id four times.
- Native path: a stand-in window, the share dialog (the owner clicked it within 9 s), then restored with no dialog.
- Fullscreen games under the overlay, the fallback when the engine fails, `summit doctor`, `install.sh --dry-run`, a gamescope trial.
- `cargo test --workspace` and the engine pytest (on the desktop's venv) passed before every commit.
**Not done / not verified**
- A real native Wayland game.
- GNOME/sway/Hyprland.
- Fractional scaling.
- A real keyboard.
- A restore token after a reboot or for another program.
- DMA-BUF zero copy.
- 90/120/240 Hz output, HDR, VRR.
- `install.sh` run for real on the desktop.
- Gamescope as a Summit option (evaluated only).
- 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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 736 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+64
View File
@@ -0,0 +1,64 @@
"""A stand-in game for testing window capture on Wayland: a native Wayland window (GLFW's Wayland backend) with
moving bars, that prints each key it gets and each focus change, so a test can tell whether the game still has the
keyboard with the engine's picture over it.
python devtools/wayland_standin.py [--seconds 60] [--size 1280x720] [--title "Summit stand-in"] [--fullscreen DP-1]
"""
import argparse
import sys
import time
import glfw
from OpenGL import GL
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--seconds", type=float, default=60)
ap.add_argument("--size", default="1280x720")
ap.add_argument("--title", default="Summit stand-in (native Wayland)")
ap.add_argument("--fullscreen", default="", metavar="MONITOR", help="fullscreen on the monitor of that name")
a = ap.parse_args()
w, h = map(int, a.size.split("x"))
glfw.init_hint(glfw.PLATFORM, glfw.PLATFORM_WAYLAND)
if not glfw.init():
print("glfw init failed", flush=True)
return 1
print("platform:", "wayland" if glfw.get_platform() == glfw.PLATFORM_WAYLAND else glfw.get_platform(), flush=True)
mon = next((m for m in glfw.get_monitors() if a.fullscreen and a.fullscreen in glfw.get_monitor_name(m).decode()), None)
if mon is not None:
mode = glfw.get_video_mode(mon)
w, h = mode.size.width, mode.size.height
win = glfw.create_window(w, h, a.title, mon, None)
glfw.make_context_current(win)
glfw.swap_interval(1)
keys = []
glfw.set_key_callback(win, lambda _w, key, _sc, action, _m: action == glfw.PRESS and (
keys.append(key), print(f"key {glfw.get_key_name(key, 0) or key} at {time.time():.3f}", flush=True)))
glfw.set_window_focus_callback(win, lambda _w, f: print(f"focus {'in' if f else 'out'} at {time.time():.3f}", flush=True))
t0, frames = time.perf_counter(), 0
GL.glEnable(GL.GL_SCISSOR_TEST)
while not glfw.window_should_close(win) and time.perf_counter() - t0 < a.seconds:
t = time.perf_counter() - t0
fw, fh = glfw.get_framebuffer_size(win)
GL.glScissor(0, 0, fw, fh)
GL.glClearColor(0.08, 0.1, 0.16, 1)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
x = int((t * 400) % max(1, fw - 120)) # a bar sweeping across, 400 px a second
GL.glScissor(x, 0, 120, fh)
GL.glClearColor(0.9, 0.5, 0.1, 1)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
for i in range(len(keys) % 20): # one green block per key received (up to 19)
GL.glScissor(20 + i * 50, fh - 60, 40, 40)
GL.glClearColor(0.2, 0.9, 0.3, 1)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
glfw.swap_buffers(win)
glfw.poll_events()
frames += 1
print(f"{frames} frames in {time.perf_counter() - t0:.1f} s, {len(keys)} keys", flush=True)
glfw.terminate()
return 0
if __name__ == "__main__":
sys.exit(main())
+33 -4
View File
@@ -3,8 +3,11 @@
X11 XGrabKey on the root window, through libX11 with ctypes (no extra package). A key another program
already grabbed is reported as taken.
Wayland xdg-desktop-portal's GlobalShortcuts, if the desktop has it and the `jeepney` package is installed.
The desktop asks the user to confirm the key, and may give a different one. NOT TESTED: no Wayland
desktop with that portal was available while this was written.
Summit registers itself as the host app "summit" first (org.freedesktop.host.portal.Registry): without
an app id the portal refuses ("An app id is required", seen on Plasma 6.8). The desktop may ask the user
to confirm the key, and may give a different one. If the portal can't be had and XWayland is there
(DISPLAY set), the X11 grab below is used through XWayland: it fires while an XWayland window (most
games: Proton, Wine, older native ones) has the keyboard.
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().
@@ -190,8 +193,27 @@ class X11Keys:
self._thread.join(timeout=2)
APP_ID = "summit" # matches packaging/summit.desktop
def register_host_app(conn, app_id: str = APP_ID) -> str | None:
"""Tells xdg-desktop-portal (1.19 and newer) which app this connection is: portals that need an app id
(GlobalShortcuts) refuse a host program without one. Returns why it couldn't, or None. Must come before any
other portal call on `conn`."""
from jeepney import DBusAddress, new_method_call
reg = DBusAddress("/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop",
interface="org.freedesktop.host.portal.Registry")
try:
reply = conn.send_and_get_reply(new_method_call(reg, "Register", "sa{sv}", (app_id, {})), timeout=5)
except Exception as e: # noqa: BLE001
return str(e)
if reply.header.message_type.name == "error":
return str(reply.body)
return None
class PortalKeys:
"""xdg-desktop-portal GlobalShortcuts over D-Bus with jeepney. Untested (see the module's note)."""
"""xdg-desktop-portal GlobalShortcuts over D-Bus with jeepney (see the module's note)."""
IFACE = "org.freedesktop.portal.GlobalShortcuts"
@@ -227,6 +249,7 @@ class PortalKeys:
interface=self.IFACE)
bus = Proxy(message_bus, conn)
sender = conn.unique_name[1:].replace(".", "_")
register_host_app(conn)
def request(method: str, sig: str, args: tuple, token: str):
path = f"/org/freedesktop/portal/desktop/request/{sender}/{token}"
@@ -284,7 +307,7 @@ class GlobalKeys:
"""Picks X11 or the portal for this session; `status` says what it got, in words."""
def __init__(self, keys: dict, env=os.environ) -> None:
self.keys = keys
self.keys, self.env = keys, env
self.kind, self.why = backend(env)
self.impl = X11Keys(keys) if self.kind == "x11" else PortalKeys(keys) if self.kind == "portal" else None
self.status = ""
@@ -294,6 +317,12 @@ class GlobalKeys:
self.status = f"global keys unavailable: {self.why}"
else:
self.impl.start()
if self.impl.error and self.kind == "portal" and self.env.get("DISPLAY"):
print(f"[keys] GlobalShortcuts portal: {self.impl.error}; using an XWayland key grab instead "
"(it works while an XWayland window, most games, has the keyboard)")
self.kind, self.why = "xwayland", "Wayland session: X11 key grab through XWayland"
self.impl = X11Keys(self.keys, self.env.get("DISPLAY"))
self.impl.start()
if self.impl.error:
self.status = f"global keys unavailable ({self.why}): {self.impl.error}"
else:
+10 -4
View File
@@ -306,7 +306,11 @@ WAYLAND = sys.platform.startswith("linux") and os.environ.get("XDG_SESSION_TYPE"
MONITOR = os.environ.get("SMOOVPLAY_MONITOR", "")
# The window's title (SMOOVPLAY_TITLE): lets a window rule tell launchers apart (the projector one vs. the desktop one).
WINDOW_TITLE = os.environ.get("SMOOVPLAY_TITLE", "SmoovPlay")
X11 = sys.platform.startswith("linux") and not WAYLAND # window capture's overlay there: framegen/window_x11.py
# Window capture's overlay on Linux is an X11 override-redirect window (framegen/window_x11.py): on X11, and on a
# Wayland session through XWayland (DISPLAY set). KWin keeps such a window above everything, a fullscreen game
# included, never gives it the keyboard, and lets the pointer through (checked on Plasma 6.8 Wayland). Wayland itself
# has no way for a program to place its window, keep it on top or refuse the focus.
X11 = sys.platform.startswith("linux") and (not WAYLAND or bool(os.environ.get("DISPLAY")))
# SMOOVPLAY_SUPERSAMPLE=2: RTX VSR runs even when the window is no bigger than the picture (it renders at 2x and the GPU
# shrinks that back), so it cleans up a capture card's compression blocks on a 1080p screen too.
try:
@@ -692,6 +696,8 @@ class GLWindowSink:
self.settings = st = settings if settings is not None else Settings()
scaler, sharpness, vsr_quality = st.scaler, st.fsr_sharpness, st.vsr_quality
self.glfw, self.GL, self.w, self.h = glfw, GL, w, h
if overlay_of is not None and X11 and WAYLAND: # GLFW would pick Wayland: the overlay needs XWayland
glfw.init_hint(glfw.PLATFORM, glfw.PLATFORM_X11)
if not glfw.init():
raise RuntimeError("glfw init failed")
self.dx = None # a DxgiPresenter when the window presents through DXGI (_choose_presentation)
@@ -1337,9 +1343,9 @@ class GLWindowSink:
for m in glfw.get_monitors():
(x, y), mode = glfw.get_monitor_pos(m), glfw.get_video_mode(m)
rects.append((m, type(client)(x, y, mode.size.width, mode.size.height)))
if MONITOR:
want = pick_monitor(glfw)
return next(r for m, r in rects if m == want)
if MONITOR: # (by name: GLFW hands out a new pointer object for the same monitor on every call)
want = glfw.get_monitor_name(pick_monitor(glfw))
return next(r for m, r in rects if glfw.get_monitor_name(m) == want)
cx, cy = client.x + client.w // 2, client.y + client.h // 2
return next((r for _, r in rects if r.x <= cx < r.x + r.w and r.y <= cy < r.y + r.h), None)
except Exception: # noqa: BLE001
+109
View File
@@ -0,0 +1,109 @@
"""KDE Plasma's window manager (KWin) on Wayland: which windows there are, where, and which is active.
A Wayland program can't see other programs' windows. KWin can run a small script for us (org.kde.kwin.Scripting
over D-Bus), and the script calls back on our D-Bus connection with the list. Used for window capture on a
Wayland session: to find a game's native Wayland window by its process, title or class, to tell it from an
XWayland one, and to know where it is so the engine's picture can sit over it (framegen/window_portal.py).
Checked on Plasma 6.8 Wayland. Needs the `jeepney` package. Other desktops: `available()` is False.
"""
from __future__ import annotations
import json
import os
import tempfile
from dataclasses import dataclass
SCRIPT = """
const out = [];
for (const w of workspace.windowList()) {
if (!w.normalWindow) continue;
const f = w.frameGeometry; // a window's screencast holds its title bar too
out.push({pid: w.pid, caption: w.caption, cls: w.resourceClass, x: f.x, y: f.y, w: f.width, h: f.height,
active: w === workspace.activeWindow, x11: w.windowId !== undefined && w.windowId !== 0,
minimized: w.minimized, output: w.output ? w.output.name : "", id: String(w.internalId)});
}
callDBus("%s", "/summit/kwin", "org.summit.KWinReport", "windows", JSON.stringify(out));
"""
@dataclass(frozen=True)
class KWindow:
pid: int
caption: str
cls: str
x: int
y: int
w: int
h: int
active: bool
x11: bool # an XWayland window (framegen/window_x11.py reads those directly)
minimized: bool
output: str # the monitor it is on, e.g. "DP-1"
id: str # KWin's own id for it (stays the same while it's open)
def parse(text: str) -> list[KWindow]:
"""The script's JSON as KWindows (pure: unit tested)."""
out = []
for d in json.loads(text):
try:
out.append(KWindow(int(d.get("pid") or 0), str(d.get("caption") or ""), str(d.get("cls") or "").lower(),
int(d["x"]), int(d["y"]), int(d["w"]), int(d["h"]), bool(d.get("active")),
bool(d.get("x11")), bool(d.get("minimized")), str(d.get("output") or ""),
str(d.get("id") or "")))
except (KeyError, TypeError, ValueError):
continue
return out
def available(env=os.environ) -> bool:
return "kde" in env.get("XDG_CURRENT_DESKTOP", "").lower() and bool(env.get("WAYLAND_DISPLAY"))
class KWin:
"""One D-Bus connection to KWin; windows() runs the script once (about 10 ms) and returns what it reported."""
def __init__(self) -> None:
from jeepney.io.blocking import open_dbus_connection
self.conn = open_dbus_connection(bus="SESSION")
self._n = 0
def windows(self, timeout: float = 3.0) -> list[KWindow]:
from jeepney import DBusAddress, MatchRule, new_method_call, new_method_return
scripting = DBusAddress("/Scripting", bus_name="org.kde.KWin", interface="org.kde.kwin.Scripting")
self._n += 1
name = f"summit-windows-{os.getpid()}-{self._n}"
fd, path = tempfile.mkstemp(prefix="summit-kwin-", suffix=".js")
try:
with os.fdopen(fd, "w") as f:
f.write(SCRIPT % self.conn.unique_name)
reply = self.conn.send_and_get_reply(new_method_call(scripting, "loadScript", "ss", (path, name)), timeout=timeout)
if reply.header.message_type.name == "error":
raise RuntimeError(f"KWin would not load the script: {reply.body}")
sid = reply.body[0]
rule = MatchRule(type="method_call", path="/summit/kwin")
with self.conn.filter(rule) as q:
script = DBusAddress(f"/Scripting/Script{sid}", bus_name="org.kde.KWin", interface="org.kde.kwin.Script")
self.conn.send_and_get_reply(new_method_call(script, "run"), timeout=timeout)
msg = self.conn.recv_until_filtered(q, timeout=timeout)
self.conn.send(new_method_return(msg))
return parse(msg.body[0])
finally:
try:
self.conn.send_and_get_reply(new_method_call(scripting, "unloadScript", "s", (name,)), timeout=timeout)
except Exception: # noqa: BLE001 - cleaning up
pass
os.unlink(path)
def close(self) -> None:
try:
self.conn.close()
except Exception: # noqa: BLE001
pass
def as_xwindows(windows: list[KWindow]):
"""KWin's windows in window_x11's form, so window_x11.pick() chooses among them by the same rules ("pid:N",
"class:NAME", part of a title); xid is the index in `windows`."""
from .window_x11 import XWindow
return [XWindow(i, w.caption, w.cls, w.pid, w.w, w.h) for i, w in enumerate(windows)]
+387
View File
@@ -0,0 +1,387 @@
"""Window capture on a Wayland session (Experimental): XWayland windows as on X11, native Wayland windows through
xdg-desktop-portal's ScreenCast and PipeWire.
python run.py --source window --window pid:4242 --window-wait 60 --display # what `summit run --enhance` does
python -m framegen.window_portal --window "part of a title" --seconds 5 --png frame.png # capture test
How a game's window is found (open_window): every half second, among the XWayland windows (framegen/window_x11.py,
read through XWayland's DISPLAY: no dialog, as on X11) and, on KDE Plasma, among KWin's native Wayland windows
(framegen/kwin.py), by the same rules: "pid:N", "class:NAME" or part of the title. An XWayland window is captured
the X11 way. A native Wayland window can only be captured through the ScreenCast portal:
- The desktop shows its share dialog, where the user picks the window (a program can't choose it). The portal
hands back a restore token (persist_mode 2, "until revoked"), kept in ~/.config/summit/screencast-token, and the
next capture passes it so the desktop can skip the dialog. Whether it does for a window of a game that was
restarted is up to the desktop (see docs/WAYLAND_REPORT.md for what Plasma 6.8 did).
- Frames come from the PipeWire stream through `gst-launch-1.0 pipewiresrc` (GStreamer's PipeWire plugin), as an
own process that pipes raw BGR frames here, scaled to the size the stream started with: the frames are copied
through the CPU (no DMA-BUF import), measured in the report.
- The compositor sends a frame when the window changes, so frames come at the game's own rate.
- KWin's list also says where the window is, so the engine's picture can sit over it, and which monitor it is on.
Without KWin (other desktops: untested) the picture goes over the monitor --monitor names, in fullscreen only.
Needs: the `jeepney` package (D-Bus), the `gst-launch-1.0` program with the pipewire plugin (gst-plugin-pipewire,
gstreamer1.0-pipewire), xdg-desktop-portal with a ScreenCast backend (-kde, -gnome, -wlr, -hyprland).
"""
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
import sys
import threading
import time
from .window_x11 import MIN_SIZE, FfmpegGrab, Rect, even, pick
WINDOW_SOURCE = 2 # ScreenCast source types: 1 monitor, 2 window, 4 virtual
CURSOR_HIDDEN = 1
PERSIST_UNTIL_REVOKED = 2
DIALOG_TIMEOUT_S = 600 # the user may be away from the desk when the share dialog opens
def config_dir(env=os.environ) -> str:
return os.path.join(env.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "summit")
def token_path(env=os.environ) -> str:
return os.path.join(config_dir(env), "screencast-token")
def load_token(path: str | None = None) -> str:
try:
with open(path or token_path()) as f:
return f.read().strip()
except OSError:
return ""
def save_token(token: str, path: str | None = None) -> None:
path = path or token_path()
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".part"
with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(token)
os.replace(tmp, path)
def select_options(token: str, cursor_modes: int, handle: str) -> dict:
"""SelectSources' options: one window, the pointer left out if the portal can, kept until revoked (pure)."""
o = {"handle_token": ("s", handle), "types": ("u", WINDOW_SOURCE), "multiple": ("b", False),
"persist_mode": ("u", PERSIST_UNTIL_REVOKED)}
if cursor_modes & CURSOR_HIDDEN:
o["cursor_mode"] = ("u", CURSOR_HIDDEN)
if token:
o["restore_token"] = ("s", token)
return o
def gst_argv(exe: str, fd: int, node: int, w: int, h: int) -> list[str]:
"""The GStreamer command: the PipeWire stream (fd from the portal, node from Start) as raw BGR of w x h on stdout."""
return [exe, "-q", "pipewiresrc", f"fd={fd}", f"path={node}", "do-timestamp=true", "!", "videoconvert", "!",
"videoscale", "!", f"video/x-raw,format=BGR,width={w},height={h}", "!", "fdsink", "fd=1", "sync=false"]
class ScreenCast:
"""One ScreenCast portal session on its own D-Bus connection. The session (and the stream) lives as long as the
connection: close() ends both."""
IFACE = "org.freedesktop.portal.ScreenCast"
def __init__(self) -> None:
try:
from jeepney import DBusAddress
from jeepney.io.blocking import open_dbus_connection
except ImportError as e:
raise RuntimeError("capturing a Wayland window needs the jeepney package (pip install jeepney)") from e
from .globalkeys import register_host_app
self.conn = open_dbus_connection(bus="SESSION", enable_fds=True)
register_host_app(self.conn) # (some portals want an app id; ScreenCast works without one on Plasma)
self.portal = DBusAddress("/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop",
interface=self.IFACE)
self.session = ""
self._n = 0
def _property(self, name: str):
from jeepney import DBusAddress, new_method_call
props = DBusAddress("/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop",
interface="org.freedesktop.DBus.Properties")
reply = self.conn.send_and_get_reply(new_method_call(props, "Get", "ss", (self.IFACE, name)), timeout=5)
if reply.header.message_type.name == "error":
raise RuntimeError(f"the desktop portal has no ScreenCast ({reply.body})")
return reply.body[0][1]
def _request(self, method: str, sig: str, args: tuple, timeout: float) -> dict:
from jeepney import MatchRule, message_bus, new_method_call
from jeepney.io.blocking import Proxy
handle = args[-1]["handle_token"][1]
sender = self.conn.unique_name[1:].replace(".", "_")
path = f"/org/freedesktop/portal/desktop/request/{sender}/{handle}"
rule = MatchRule(type="signal", interface="org.freedesktop.portal.Request", member="Response", path=path)
Proxy(message_bus, self.conn).AddMatch(rule)
with self.conn.filter(rule) as q:
reply = self.conn.send_and_get_reply(new_method_call(self.portal, method, sig, args), timeout=10)
if reply.header.message_type.name == "error":
raise RuntimeError(f"{method}: {reply.body}")
code, results = self.conn.recv_until_filtered(q, timeout=timeout).body
if code == 1:
raise RuntimeError(f"{method}: the share dialog was cancelled")
if code != 0:
raise RuntimeError(f"{method} failed (code {code})")
return results
def _handle(self) -> str:
self._n += 1
return f"summit{os.getpid()}_{self._n}"
def start(self, token: str = "", timeout: float = DIALOG_TIMEOUT_S) -> tuple[int, tuple[int, int] | None, str]:
"""Asks for one window: (PipeWire node, its size if the portal said, the new restore token). Shows the
desktop's dialog unless `token` lets it restore the last choice; waits up to `timeout` for the user."""
try:
cursor_modes = int(self._property("AvailableCursorModes"))
except Exception: # noqa: BLE001 - only the pointer
cursor_modes = 0
if not int(self._property("AvailableSourceTypes")) & WINDOW_SOURCE:
raise RuntimeError("this desktop's ScreenCast portal can't share a single window")
h = self._handle()
res = self._request("CreateSession", "a{sv}", ({"handle_token": ("s", h), "session_handle_token": ("s", h + "s")},), 30)
self.session = res["session_handle"][1]
self._request("SelectSources", "oa{sv}", (self.session, select_options(token, cursor_modes, self._handle())), 30)
res = self._request("Start", "osa{sv}", (self.session, "", {"handle_token": ("s", self._handle())}), timeout)
streams = res.get("streams", ("", []))[1]
if not streams:
raise RuntimeError("the desktop shared nothing")
node, props = streams[0]
size = props.get("size", ("", None))[1]
return int(node), (tuple(size) if size else None), res.get("restore_token", ("", ""))[1]
def open_remote(self) -> int:
"""The PipeWire connection for the stream, as a file descriptor this process owns."""
from jeepney import new_method_call
reply = self.conn.send_and_get_reply(new_method_call(self.portal, "OpenPipeWireRemote", "oa{sv}", (self.session, {})), timeout=10)
if reply.header.message_type.name == "error":
raise RuntimeError(f"OpenPipeWireRemote: {reply.body}")
return reply.body[0].to_raw_fd()
def close(self) -> None:
if self.session:
try:
from jeepney import DBusAddress, new_method_call
s = DBusAddress(self.session, bus_name="org.freedesktop.portal.Desktop", interface="org.freedesktop.portal.Session")
self.conn.send(new_method_call(s, "Close"))
except Exception: # noqa: BLE001
pass
try:
self.conn.close()
except Exception: # noqa: BLE001
pass
class GstGrab(FfmpegGrab):
"""`gst-launch-1.0 pipewiresrc ...` piping raw BGR frames of w x h; read(), error() and close() as FfmpegGrab."""
def __init__(self, fd: int, node: int, w: int, h: int, exe: str | None = None) -> None:
exe = exe or shutil.which("gst-launch-1.0")
if not exe:
raise RuntimeError("capturing a Wayland window needs gst-launch-1.0 and GStreamer's pipewire plugin "
"(gst-plugin-pipewire on Arch, gstreamer1.0-pipewire on Debian/Ubuntu)")
self.w, self.h = w, h
self.proc = subprocess.Popen(gst_argv(exe, fd, node, w, h), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, bufsize=0, pass_fds=(fd,))
try:
import fcntl
fcntl.fcntl(self.proc.stdout.fileno(), 1031, 1 << 22) # F_SETPIPE_SZ: room for a whole frame
except Exception: # noqa: BLE001
pass
class Tracker:
"""Where a native Wayland window is, from KWin once a second on a thread of its own (window id = KWin's)."""
def __init__(self, kw, win) -> None:
self.kw, self.win, self.gone = kw, win, False
self._stop = threading.Event()
threading.Thread(target=self._run, name="kwin-follow", daemon=True).start()
def _run(self) -> None:
while not self._stop.wait(1.0):
try:
found = [w for w in self.kw.windows() if w.id == self.win.id]
except Exception: # noqa: BLE001 - KWin didn't answer this time
continue
if found:
self.win = found[0]
else:
self.gone = True
def stop(self) -> None:
self._stop.set()
class PortalWindowSource:
"""Ticks from a native Wayland window through the ScreenCast portal (a variable rate: wrap it in
sources.Clock60). `where()` as window_x11.X11WindowSource: (the window's picture area, its monitor) in screen
pixels, or None while it's minimised."""
def __init__(self, win=None, kw=None, token_file: str | None = None) -> None:
from .sources import source_info
self.win, self.kw = win, kw
self.cast = ScreenCast()
self._token_file = token_file
app = win.caption if win is not None else "game"
token = load_token(token_file)
print(f"[window] asking the desktop to share the {app} window"
+ (" (restoring the last choice)" if token else ": pick it in the dialog that opens (once: Summit "
"keeps the permission)"), flush=True)
t0 = time.perf_counter()
try:
self.node, size, new_token = self.cast.start(token)
except Exception:
self.cast.close()
raise
if new_token:
save_token(new_token, token_file)
waited = time.perf_counter() - t0
print(f"[window] shared after {waited:.1f} s" + ("" if new_token else " (the desktop gave no restore token: "
"it will ask again next time)"), flush=True)
if size is None and win is not None:
size = (win.w, win.h)
self.w, self.h = even(size[0]) if size else 1280, even(size[1]) if size else 720
if self.w < MIN_SIZE[0] or self.h < MIN_SIZE[1]:
self.cast.close()
raise RuntimeError(f"the shared window is too small to capture ({self.w}x{self.h})")
self.info = source_info("window", name=f"{app} window (Wayland)", hz=60.0)
self.tracker = Tracker(kw, win) if (kw is not None and win is not None) else None
self.grabs, self.same = 0, 0
self._stop, self._grab = False, None
print(f"[window] PipeWire node {self.node}: {self.w}x{self.h}"
+ ("" if self.tracker else "; where it is on screen is unknown here (no KWin): the picture goes over "
"the monitor --monitor names, in fullscreen"), flush=True)
def where(self) -> tuple[Rect, Rect] | None:
if self.tracker is None:
r = Rect(0, 0, self.w, self.h)
return r, r
w = self.tracker.win
if w.minimized:
return None
r = Rect(w.x, w.y, even(w.w), even(w.h))
return r, r # (io.VideoWindow finds the monitor from the middle of the window, or --monitor)
def __iter__(self):
import numpy as np
from .io import Tick
fd = self.cast.open_remote()
self._grab = grab = GstGrab(fd, self.node, self.w, self.h)
os.close(fd) # (gst-launch has its own copy)
n, last = 0, None
try:
while not self._stop:
raw = grab.read()
now = time.perf_counter()
if self._stop:
return
if raw is None:
err = grab.error()
print(f"[window] the stream ended" + (f" ({err[:160]})" if err else " (the window closed)"))
return
self.grabs += 1
if last is not None and np.array_equal(raw, last):
self.same += 1
continue
last = raw
yield Tick(raw, now, n, t_ready=time.perf_counter())
n += 1
if self.tracker is not None and self.tracker.gone:
print("[window] the window closed")
return
finally:
grab.close()
def close(self) -> None:
self._stop = True
if self.tracker is not None:
self.tracker.stop()
if self._grab is not None:
self._grab.close()
self.cast.close()
print(f"[window] {self.grabs} frames from PipeWire, {self.same} unchanged (left out)")
def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.environ):
"""--window QUERY on a Wayland session: an XWayland window that matches (window_x11, no dialog), else a native
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
x = X() if session_problem(env) is None else None
kw = None
if kwin.available(env):
try:
kw = kwin.KWin()
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
while True:
if x is not None:
target = pick(query, find_windows(x))
if target is not None:
if wait_s: # a splash that grows: give it a moment, as window_x11.open_window
sleep(1.0)
target = pick(query, find_windows(x)) or target
if kw is not None:
kw.close()
print("[window] an XWayland window: captured through XWayland")
return X11WindowSource(target, x)
if kw is not None:
try:
native = [w for w in kw.windows() if not w.x11 and w.pid != os.getpid()]
except Exception as e: # noqa: BLE001
print(f"[window] KWin didn't list its windows ({str(e)[:120]})")
native = []
t = pick(query, kwin.as_xwindows(native))
if t is not None:
if x is not None:
x.close()
print(f"[window] a native Wayland window ({native[t.xid].caption}): captured through the ScreenCast portal")
return PortalWindowSource(native[t.xid], kw)
if time.monotonic() >= deadline:
if x is not None:
x.close()
if kw is None:
print(f"[window] no XWayland window matches {query!r}; this desktop can't say which Wayland window is "
"the game, so pick it in the share dialog")
return PortalWindowSource(None, None)
kw.close()
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)
sleep(0.5)
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--window", required=True, help='"pid:N", "class:NAME" or part of a title')
ap.add_argument("--seconds", type=float, default=5.0)
ap.add_argument("--png", help="save the last frame here")
a = ap.parse_args(argv)
src = open_window(a.window, wait_s=10)
t0, n, last = time.perf_counter(), 0, None
for tick in src:
n, last = n + 1, tick
if time.perf_counter() - t0 >= a.seconds:
break
dt = time.perf_counter() - t0
print(f"{n} new frames in {dt:.1f} s ({n / dt:.1f} a second)")
if a.png and last is not None:
import cv2
cv2.imwrite(a.png, last.frame)
src.close()
return 0
if __name__ == "__main__":
sys.exit(main())
+8 -7
View File
@@ -1,4 +1,4 @@
"""Window capture on Linux, X11 only (Experimental): frames from a game's (or any app's) window, live.
"""Window capture on Linux, X11 and XWayland windows (Experimental): frames from a game's (or any app's) window, live.
python -m framegen.window_x11 --list [--json] # the windows it could capture
python run.py --source window --window "Voidrunner" --display
@@ -21,8 +21,8 @@ How it works:
Limits:
- Needs the `ffmpeg` program (with x11grab; any distribution's package has it).
- X11 sessions only. On Wayland this refuses to start: capture there needs xdg-desktop-portal's ScreenCast and
PipeWire, which isn't built. (XWayland windows can't be read this way either.)
- X11 windows only: on an X11 session any window, on a Wayland session the XWayland ones (read through XWayland's
DISPLAY; checked on KDE Plasma 6.8 Wayland with an NVIDIA GPU). Native Wayland windows: framegen/window_portal.py.
- The grab polls at 60 Hz without knowing when the game draws, so a 60 fps game can show an occasional repeated or
skipped frame. The mouse pointer isn't captured.
- The game plays its own sound, a little ahead of the picture.
@@ -133,11 +133,12 @@ _ERROR_HANDLER = ctypes.CFUNCTYPE(c_int, c_void_p, c_void_p)(lambda _d, _e: 0)
def session_problem(env=os.environ) -> str | None:
"""Why window capture can't run in this session, or None if it can."""
if env.get("XDG_SESSION_TYPE", "").lower() == "wayland" or (env.get("WAYLAND_DISPLAY") and not env.get("DISPLAY")):
return ("window capture on Linux works in X11 sessions only for now: this is a Wayland session (capture "
"there needs xdg-desktop-portal ScreenCast, which isn't built). Log in to an X11 session to use it.")
"""Why X11 window capture can't run in this session, or None if it can. On a Wayland session it reads XWayland
windows (games that run through XWayland: Proton, Wine and most older native games), so it needs DISPLAY there
too; native Wayland windows go through framegen/window_portal.py instead."""
if not env.get("DISPLAY"):
if env.get("XDG_SESSION_TYPE", "").lower() == "wayland" or env.get("WAYLAND_DISPLAY"):
return "no XWayland in this Wayland session (DISPLAY isn't set), so X11 windows can't be read"
return "no X display (DISPLAY isn't set): window capture needs a desktop session"
return None
+2 -1
View File
@@ -9,5 +9,6 @@ av
sounddevice
# TensorRT engines (optional): tensorrt-cu12, onnx, onnxscript; see installer/requirements-runtime.txt
# AMD / Intel cards (DirectML, Experimental): onnxruntime-directml, onnx
# Global save-clip key on Wayland (optional, untested): jeepney (xdg-desktop-portal GlobalShortcuts)
# Wayland: window capture (ScreenCast portal), KWin window list and the global save-clip key (D-Bus)
jeepney
pytest
+5
View File
@@ -419,6 +419,11 @@ def main() -> int:
if sys.platform == "win32":
from framegen.window import open_window
src = Clock60(open_window(a.window))
elif os.environ.get("XDG_SESSION_TYPE", "").lower() == "wayland" or (
os.environ.get("WAYLAND_DISPLAY") and not os.environ.get("DISPLAY")):
# Wayland: XWayland windows as on X11, native ones through the portal (framegen/window_portal.py)
from framegen.window_portal import open_window
src = Clock60(open_window(a.window, wait_s=a.window_wait))
else: # Linux, X11 (framegen/window_x11.py)
from framegen.window_x11 import open_window
src = Clock60(open_window(a.window, wait_s=a.window_wait))
+9
View File
@@ -47,6 +47,15 @@ def test_portal_without_jeepney_says_so(monkeypatch):
assert "jeepney" in k.status and "unavailable" in k.status
def test_wayland_falls_back_to_an_xwayland_grab_when_the_portal_fails(monkeypatch):
monkeypatch.setitem(sys.modules, "jeepney", None) # the portal can't be asked
started = []
monkeypatch.setattr(gk.X11Keys, "start", lambda self: started.append(self.name))
k = gk.GlobalKeys({"ctrl+alt+r": lambda: None}, env={"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":5"})
k.start()
assert started == [":5"] and k.kind == "xwayland"
@pytest.fixture
def xserver():
if os.environ.get("DISPLAY"):
+61
View File
@@ -0,0 +1,61 @@
"""Wayland window capture (framegen/window_portal.py, framegen/kwin.py): the pure parts. The portal, PipeWire and
KWin themselves were run on a Plasma 6.8 desktop (docs/WAYLAND_REPORT.md), not here."""
import json
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from framegen import kwin
from framegen import window_portal as wp
from framegen.window_x11 import XWindow, pick
def test_kwin_report_parses_and_skips_broken_entries():
text = json.dumps([
{"pid": 42, "caption": "My Game", "cls": "MyGame", "x": 1920, "y": 251, "w": 1288, "h": 749, "active": True,
"x11": False, "minimized": False, "output": "DP-1", "id": "{abc}"},
{"pid": 7, "caption": "broken"},
])
ws = kwin.parse(text)
assert len(ws) == 1 and ws[0].cls == "mygame" and ws[0].output == "DP-1" and not ws[0].x11
def test_kwin_windows_are_picked_by_the_same_rules_as_x11_ones():
ws = kwin.parse(json.dumps([
{"pid": 10, "caption": "Editor", "cls": "kate", "x": 0, "y": 0, "w": 800, "h": 600, "id": "a"},
{"pid": 42, "caption": "Voidrunner", "cls": "game", "x": 0, "y": 0, "w": 1280, "h": 720, "id": "b"},
]))
xs = kwin.as_xwindows(ws)
assert ws[pick("pid:42", xs, family=lambda p: {p}).xid].id == "b"
assert ws[pick("class:kate", xs).xid].id == "a"
assert ws[pick("void", xs).xid].id == "b"
assert pick("nothing", xs) is None
def test_kwin_only_on_kde_wayland():
assert kwin.available({"XDG_CURRENT_DESKTOP": "KDE", "WAYLAND_DISPLAY": "wayland-1"})
assert not kwin.available({"XDG_CURRENT_DESKTOP": "GNOME", "WAYLAND_DISPLAY": "wayland-0"})
assert not kwin.available({"XDG_CURRENT_DESKTOP": "KDE"})
def test_select_options_ask_for_one_window_kept_until_revoked():
o = wp.select_options("", 7, "h1")
assert o["types"] == ("u", 2) and o["multiple"] == ("b", False) and o["persist_mode"] == ("u", 2)
assert o["cursor_mode"] == ("u", 1) and "restore_token" not in o
o = wp.select_options("tok", 2, "h2") # a portal that can't hide the pointer: don't ask it to
assert o["restore_token"] == ("s", "tok") and "cursor_mode" not in o
def test_gst_command_reads_the_portal_stream_as_raw_bgr():
a = wp.gst_argv("gst-launch-1.0", 9, 161, 1288, 748)
assert a[a.index("pipewiresrc") + 1:a.index("pipewiresrc") + 3] == ["fd=9", "path=161"]
assert "video/x-raw,format=BGR,width=1288,height=748" in a and a[-2:] == ["fd=1", "sync=false"]
def test_restore_token_is_kept_private_under_summit_config(tmp_path):
assert wp.token_path({"XDG_CONFIG_HOME": str(tmp_path)}) == str(tmp_path / "summit" / "screencast-token")
p = str(tmp_path / "summit" / "screencast-token")
assert wp.load_token(p) == ""
wp.save_token("abc-123", p)
assert wp.load_token(p) == "abc-123"
assert (pathlib.Path(p).stat().st_mode & 0o777) == 0o600
+3 -2
View File
@@ -48,8 +48,9 @@ def test_pid_family_reads_proc(tmp_path):
assert wx.pid_family(5, "/nonexistent-proc") == {5}
def test_wayland_is_refused_with_a_clear_reason():
assert "Wayland" in wx.session_problem({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"})
def test_wayland_reads_xwayland_windows_and_says_why_without_xwayland():
assert wx.session_problem({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"}) is None
assert "XWayland" in wx.session_problem({"XDG_SESSION_TYPE": "wayland", "WAYLAND_DISPLAY": "wayland-0"})
assert "DISPLAY" in wx.session_problem({})
assert wx.session_problem({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"}) is None
+10
View File
@@ -184,6 +184,16 @@ install_dependencies() {
runtime=""
;;
esac
# Wayland: native Wayland games reach the engine through the ScreenCast portal and GStreamer's PipeWire plugin
# (gst-launch-1.0 pipewiresrc). Package names checked on Arch only; the others are each distro's usual names.
if [ "$SESSION_TYPE" = wayland ] && [ -n "$runtime" ]; then
case "$DISTRO_FAMILY" in
arch) runtime="$runtime gstreamer gst-plugins-base gst-plugin-pipewire" ;;
debian) runtime="$runtime gstreamer1.0-tools gstreamer1.0-plugins-base gstreamer1.0-pipewire" ;;
fedora) runtime="$runtime gstreamer1 gstreamer1-plugins-base pipewire-gstreamer" ;;
opensuse) runtime="$runtime gstreamer-utils gstreamer-plugins-base gstreamer-plugin-pipewire" ;;
esac
fi
if [ -n "$runtime" ]; then
step "Installing the tools Summit runs (a failure here only disables a feature)"
# shellcheck disable=SC2086