Merge ap/play-integration

This commit is contained in:
bonzi committed 2026-11-24 07:45:12 +00:00
commit c6e6e57eda
24 files changed
+1268 -72

No files matched your search

+20 -8
View File
@@ -43,7 +43,7 @@
<p align="center"><sub><b>These are headless renders, not window captures.</b> They are the real UI drawn by Slint's software renderer with <code>docs/demo/screenshots.sh</code>: still frames, so they show no animation. <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. <b>Voidrunner</b> is real (the author's own game), added by hand with its own artwork. Nothing was running in a game; the in-game overlay does not exist yet.</sub></p>
> [!NOTE]
> **Pre-alpha.** What works today is the command-line core (library scanning with detection reasons, playtime tracking, Home pins, custom artwork, per-game display profiles applied at launch) and the launcher window that sits on top of it. Steam shortcut export, the in-game overlay and applying upscaling or frame generation to a launched game are planned and are **not built yet**. Nothing below is marked as working unless it is.
> **Pre-alpha.** What works today is the command-line core (library scanning with detection reasons, playtime tracking, Home pins, custom artwork, per-game display profiles applied at launch), the launcher window on top of it, and live frame generation + upscaling on a launched game's window (X11 only). Wayland capture, a full in-game overlay and many launch paths (Heroic, real Steam games) are **not built or not tested yet**. Nothing below is marked as working unless it is.
## Why
@@ -60,17 +60,17 @@
| Hours played: Steam's own playtime for Steam games, Summit-tracked sessions for everything else (never added together) | Working |
| Windows `.exe` files outside a Wine prefix listed as Software in Unfiltered, with the reason | Working |
| Pin to Home and custom artwork per entry | Working. Pin and unpin from the CLI or the launcher (both write `state.json`). Artwork is CLI only (`summit art`); the launcher's "Change artwork" button is marked Soon. |
| Display profile applied at launch: monitor, resolution, refresh rate | Working for KDE Wayland (`kscreen-doctor`), wlroots Wayland (`wlr-randr`) and X11 (`xrandr`). **GNOME Wayland has no stable tool, so Summit says so and skips it. Command plans are unit tested; real monitor changes are not yet verified on hardware.** |
| Per-game fullscreen, focus, upscaler and frame-gen settings | Stored. Fullscreen, focus and the upscaling are not applied yet. |
| Launcher window (Slint): Home, Library, Unfiltered, a page per game, Settings | Working. Run `summit-gui`. Home has a hero for the focused game (its wide art as backdrop, logo, hours, Play) over shelves: Jump back in, Pinned, Most played. Library is a cover grid that fits the window, or a dense list, with All / Installed / Not installed, three sort orders and search. Checked in headless renders at 1600x900, 1280x800 and 900x600, and in a real window under Xvfb. **Not checked on a real desktop, GPU or TV yet.** |
| Display profile applied at launch: monitor, resolution, refresh rate | **Working on X11** (`xrandr`): checked on the KDE neon X11 test VM: `summit run` switched the output from its custom `1920x1080_120.00` mode to 1280x800 @ 74.99 Hz, the game came up at 1280x800, and the old mode was put back when the game exited. The monitor list comes from the same tool (`summit doctor` prints it). KDE Wayland (`kscreen-doctor`) and wlroots (`wlr-randr`): command plans and output parsing are unit tested, **not run on a real Wayland desktop**. GNOME Wayland has no stable tool, so Summit says so and skips it. A detached launch (Steam) without Enhance cannot know when the game ends, so the mode is not put back then. |
| Per-game profile editor in the launcher (Profile on a game's page): monitor and its real modes and refresh rates, fullscreen, focus, upscaler, frame generation, target rate | **Working** (used on the test VM: the editor listed `Virtual-1`'s 19 xrandr modes; every change is written through `summit-core::profile`). Upscaler, frame generation, target rate and fullscreen are used by Enhance (fullscreen means the engine's picture covers the monitor; the game's own window mode is not changed). **Focus is stored only**: raising the game window is not built. 90/120 Hz and RTX VSR are wired, not tested. |
| Launcher window (Slint): Home, Library, Unfiltered, a page per game, Settings | Working. Run `summit-gui`. Home has a hero for the focused game (its wide art as backdrop, logo, hours, Play) over shelves: Jump back in, Pinned, Most played. Library is a cover grid that fits the window, or a dense list, with All / Installed / Not installed, three sort orders and search. Checked in headless renders at 1600x900, 1280x800 and 900x600, in a real window under Xvfb, and on the KDE neon X11 desktop of the test VM (software OpenGL there). **Not checked on a GPU-rendered desktop or a TV yet.** |
| Layouts (Big picture, Grid, List) and six themes (Midnight, Steam blue, Daylight, Violet, High contrast, OLED black) | Working. Saved to `~/.config/summit/ui.toml` with interface size and the animation settings, and loaded at start. |
| Animations with a speed slider (0 turns them off) and three styles | Working in a real window under Xvfb (frames captured mid-transition). How smooth they are on real hardware has not been judged. |
| Keyboard navigation: arrows, Enter, Esc, Tab between sections, `/` to search, P to pin, F11 fullscreen | Working (driven by synthetic key events in the headless renders and in the Xvfb window). |
| Game controller navigation (d-pad or left stick, A, B, X, LB/RB) | Written, reads `/dev/input/js*`. Decoding and mapping are unit tested. **Not tested with a real controller.** |
| Play from the launcher | Steam games are handed to the Steam client (`steam steam://rungameid/<id>`, or `steam://install/<id>` when not installed). Games added by hand go through `summit run`, so the profile is applied and the session tracked. Lutris uses `lutris lutris:rungame/<slug>`. The commands are unit tested; **no game was actually started from the launcher yet** (no Steam on the build machine). Heroic and folders found on disk cannot be started yet and the button says so. |
| Play from the launcher, with an Enhance toggle | Everything goes through `summit run`, so the display profile is applied first. Games added by hand: `summit run <id> [--enhance] -- <path>`. **Working**: Voidrunner was started from the launcher on the test VM, once plain and once with Enhance on (see [Play from the launcher](#play-from-the-launcher)). Steam: `summit run steam:<id> --detached [--enhance --window class:steam_app_<id>] -- steam steam://rungameid/<id>` (`steam://install/<id>` when not installed); **not tested**, there is no Steam on the test machines, and the `steam_app_<id>` window class is what Proton games get, not every native game. Lutris: `summit run <id> --detached -- lutris lutris:rungame/<slug>`, untested, no Enhance. Heroic and folders found on disk cannot be started yet and the button says so. Enhance needs an X11 session; the button is disabled with the reason otherwise. The output of the last run goes to `~/.cache/summit/last-run.log`. |
| Covers for 600+ games | Lists only create the rows on screen, and covers are decoded to thumbnails on a worker thread when a card first appears. Rendered headless with a 662-game library. Not profiled on real hardware. |
| Instant replay with a PS5-style length picker: keep 15 s to 10 min, save 15 s, 30 s, 1 m, 3 m, 5 m or 10 m with Ctrl+1..6 (R saves the default length) | **Engine working** (tested with a synthetic stream on the 3090: a 15 s save and a 600 s request capped at the 40 s actually buffered). Not tested on a live game. The launcher's settings page stores both lengths in `ui.toml` and `summit enhance` passes them to the engine; that path is unit tested, not run against the engine. Key binds work in the engine's own window only; a global key is not built for Linux yet. |
| Live enhance: `summit run <id> --enhance` starts the game and runs frame generation + upscaling on its window, no recording step | **Working on X11** (tested on KDE neon X11 with Voidrunner, RTX 3090): the game is launched, its window is found by process id, the enhanced picture sits on top of it (the game keeps keyboard and mouse), and both stop when either exits. **X11 only**: on Wayland it refuses to start (portal/PipeWire capture is not built). No hotkeys for the engine while it sits over a game yet. See [Live enhance](#live-enhance-play-a-game-with-frame-generation-on-top). |
| Instant replay with a PS5-style length picker: keep 15 s to 10 min, save 15 s, 30 s, 1 m, 3 m, 5 m or 10 m with Ctrl+1..6 (R saves the default length) | **Engine working** (tested with a synthetic stream on the 3090: a 15 s save and a 600 s request capped at the 40 s actually buffered). **Working on a live game on X11**: the launcher's settings page wrote 3 min / 3 min to `ui.toml`, Play with Enhance passed `--replay 180 --clip-length 180` to the engine, and Ctrl+Alt+R pressed while Voidrunner had the keyboard saved a 30.3 s clip (all that was buffered by then; checked with ffprobe). **Global save key**: X11 through `XGrabKey` (ctypes libX11, no extra package; tested on the KDE desktop and under Xvfb, a key another program holds is reported as taken; it does not fire while the KDE lock screen is up). Wayland through xdg-desktop-portal GlobalShortcuts with the optional `jeepney` package: written, **not tested** (no such desktop available). Without either the engine and the settings page say there is no global key. |
| Live enhance: `summit run <id> --enhance` starts the game and runs frame generation + upscaling on its window, no recording step | **Working on X11** (tested on KDE neon X11 with Voidrunner, RTX 3090): the game is launched, its window is found by process id, the enhanced picture sits on top of it (the game keeps keyboard and mouse), and both stop when either exits. **X11 only**: on Wayland it refuses to start (portal/PipeWire capture is not built). The engine's own keys (stats, menu) still need its window; only the clip keys are global. See [Live enhance](#live-enhance-play-a-game-with-frame-generation-on-top). |
| In-game overlay with a watermark showing the project URL | **Working** in the engine's video window: a small `summit - git.molberg.cloud/alex/summit` line in a bottom corner, next to the existing stats. Setting `watermark`, on by default; `--no-watermark` turns it off. Not drawn into saved clips or files. |
| One-click "Add to Steam" with SteamGridDB artwork | Planned |
| "My PS5" and "Capture Card" entries (Remote Play, capture cards, Moonlight, Sunshine) | Planned. Reuses the SmoovPlay pipeline. |
@@ -87,7 +87,19 @@
| AppImage (`packaging/appimage/build.sh`) | Untested. Needs `linuxdeploy` and `appimagetool`, neither available in this environment. |
| Flatpak | Planned |
## Install
## Play from the launcher
A game's page has Play, an **Enhance** toggle and **Profile**. With Enhance on, Play runs `summit run <id> --enhance`: the display profile is applied, the game starts, and the engine runs the profile's frame generation and upscaler on its window until either one exits. Clip lengths come from Settings, and Ctrl+Alt+R saves a clip from any window on X11. These captures are from the KDE neon X11 test VM (software OpenGL, RTX 3090 for the engine):
| | |
|---|---|
| ![Voidrunner's page with Enhance on](docs/media/live/gui-detail-enhance.png) | ![The launch profile editor listing the monitor's real modes](docs/media/live/gui-profile-editor.png) |
| Enhance toggle on a game's page | Profile editor: monitor, resolution and refresh from xrandr |
| ![Voidrunner running with RIFE and FSR after Play](docs/media/live/gui-play-enhanced.png) | ![The engine's toast after Ctrl+Alt+R: saved the last 30 s](docs/media/live/gui-clip-saved-global-key.png) |
| After Play: RIFE + FSR on the game's 720p window, full screen | Ctrl+Alt+R pressed while the game had the keyboard |
![Clip settings: keep the last 3 min, a save writes 3 min, Ctrl+Alt+R from any window](docs/media/live/gui-clip-settings.png)
```sh
curl -fsSL https://git.molberg.cloud/alex/summit/raw/branch/main/install.sh | sh
+42 -9
View File
@@ -32,6 +32,9 @@ enum Cmd {
#[arg(long, default_value_t = 60)] wait: u32,
/// With --enhance: hide the "summit - git.molberg.cloud/alex/summit" line in the corner
#[arg(long)] no_watermark: bool,
/// The command hands the game to another program and returns at once (`steam steam://rungameid/N`).
/// With --enhance, Summit then waits for the engine (the game's window) instead of the command.
#[arg(long)] detached: bool,
/// The command to run. Not needed for an entry added with `summit add`.
#[arg(last = true)] cmd: Vec<String>,
},
@@ -97,6 +100,8 @@ enum ProfileCmd {
#[arg(long)] target_hz: Option<u32>,
/// RIFE model for the engine, e.g. 4.22.lite
#[arg(long)] model: Option<String>,
/// Play from the launcher also runs the engine on the game's window
#[arg(long)] enhance: Option<bool>,
},
}
@@ -188,13 +193,20 @@ fn main() -> Result<()> {
Cmd::Doctor { id } => {
let (s, d) = (display::detect_session(), display::detect_desktop());
println!("session: {s:?}\ndesktop: {d:?}");
match display::outputs(s, d) {
Ok(outs) => for o in outs {
let cur = o.current.map(|(w, h, r)| format!("{w}x{h} @ {r} Hz")).unwrap_or_else(|| "off".into());
println!("output {}: {} ({}, {} modes)", o.name, if o.connected { "connected" } else { "disconnected" }, cur, o.modes.len());
},
Err(e) => println!("outputs: {e}"),
}
if let Some(id) = id {
let cmds = display::plan(s, d, &profile::load(&id)?);
let cmds = display::plan_for(s, d, &profile::load(&id)?, &display::outputs(s, d).unwrap_or_default());
if cmds.is_empty() { println!("no display commands for this profile on this session (nothing set, or unsupported compositor)"); }
for c in cmds { println!("would run: {}", c.join(" ")); }
}
}
Cmd::Run { id, enhance, window, wait, no_watermark, mut cmd } => {
Cmd::Run { id, enhance, window, wait, no_watermark, detached, mut cmd } => {
if cmd.is_empty() { // an entry added with `summit add` knows its own path
if let Some(c) = state::load().custom.iter().find(|c| c.id == id) { cmd = vec![c.path.clone()]; }
}
@@ -203,9 +215,21 @@ fn main() -> Result<()> {
// Found before the game starts, so a missing engine never leaves a game running without it.
let eng = if enhance { Some(engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: set SUMMIT_ENGINE to the engine/ folder"))?) } else { None };
let (s, d) = (display::detect_session(), display::detect_desktop());
let plan = display::plan(s, d, &p);
let outs = if p.monitor.is_some() { display::outputs(s, d) } else { Ok(vec![]) };
let plan = display::plan_for(s, d, &p, outs.as_deref().unwrap_or_default());
if plan.is_empty() && p.monitor.is_some() { eprintln!("note: no display control for {s:?}/{d:?}; launching without mode change"); }
for (c, r) in display::apply(&plan) { if let Err(e) = r { eprintln!("display step failed ({}): {e}", c.join(" ")); } }
// The mode in use now, to put back when the game is over. A detached game without the engine runs on
// after this command returns, so there is no "after" to restore in.
let restore = if plan.is_empty() || (detached && eng.is_none()) { None } else {
match &outs {
Ok(o) => display::restore_profile(o, &p).map(|r| display::plan_for(s, d, &r, o)),
Err(e) => { eprintln!("note: could not read the current monitor mode ({e}); it will not be restored"); None }
}
};
let run_display = |cmds: &[display::Cmd]| for (c, r) in display::apply(cmds) {
match r { Ok(()) => println!("display: ran {}", c.join(" ")), Err(e) => eprintln!("display step failed ({}): {e}", c.join(" ")) }
};
run_display(&plan);
let start = std::time::Instant::now();
let mut child = std::process::Command::new(&cmd[0]);
child.args(&cmd[1..]).args(&p.launch_args).envs(display::launch_env(s, &p));
@@ -227,22 +251,30 @@ fn main() -> Result<()> {
Ok(c) => c,
Err(e) => { let _ = engine::stop(&mut game, grace); anyhow::bail!("could not start the engine ({}): {e}", py.display()); }
};
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace)?;
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace, detached)?;
match who {
engine::Ended::Game if detached => println!("the game's window closed; the engine ended ({})", eng_proc.wait()?),
engine::Ended::Game => println!("the game exited; the engine was stopped"),
engine::Ended::Engine => println!("the engine exited ({}); the game was stopped", eng_proc.wait()?),
}
status
} else { child.status()? };
if let Some(r) = &restore { run_display(r); }
let secs = start.elapsed().as_secs();
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
let mut st = state::load(); st.record_session(&id, secs, now); state::save(&st)?;
println!("{id} exited ({status}) after {secs}s; tracked");
if detached && !enhance {
println!("{id}: handed over ({status}); its own launcher keeps the playtime");
} else if id.starts_with("steam:") {
println!("{id} ended after {secs}s; Steam keeps the playtime");
} else {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
let mut st = state::load(); st.record_session(&id, secs, now); state::save(&st)?;
println!("{id} exited ({status}) after {secs}s; tracked");
}
}
Cmd::Profile { cmd: ProfileCmd::Show { id } } => {
print!("{}", toml::to_string_pretty(&profile::load(&id)?)?);
}
Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, fullscreen, focus, upscaler, framegen, multiplier, target_hz, model } } => {
Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, fullscreen, focus, upscaler, framegen, multiplier, target_hz, model, enhance } } => {
let mut p = profile::load(&id)?;
if monitor.is_some() { p.monitor = monitor; }
if width.is_some() { p.width = width; }
@@ -255,6 +287,7 @@ fn main() -> Result<()> {
if let Some(v) = multiplier { p.framegen_multiplier = v; }
if let Some(v) = target_hz { anyhow::ensure!([60, 90, 120].contains(&v), "--target-hz is 60, 90 or 120"); p.target_hz = Some(v); }
if model.is_some() { p.model = model; }
if let Some(v) = enhance { p.enhance = v; }
println!("saved {}", profile::save(&id, &p)?.display());
}
Cmd::SteamAdd { id, user, force } => {
+200
View File
@@ -76,6 +76,153 @@ pub fn launch_env(session: Session, p: &Profile) -> Vec<(String, String)> {
e
}
/// One display output, as the session's tool reports it.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Output {
pub name: String,
pub connected: bool,
/// (width, height, refresh) in use now, if the output is on.
pub current: Option<(u32, u32, f32)>,
/// Every mode it offers, largest first, each with its refresh rates.
pub modes: Vec<Mode>,
}
#[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.
pub named: Vec<(f32, String)>,
}
fn push_mode(modes: &mut Vec<Mode>, w: u32, h: u32, r: Option<f32>) {
let m = match modes.iter_mut().position(|m| m.width == w && m.height == h) {
Some(i) => &mut modes[i],
None => { modes.push(Mode { width: w, height: h, ..Default::default() }); modes.last_mut().unwrap() }
};
if let Some(r) = r { if !m.rates.iter().any(|x| (x - r).abs() < 0.005) { m.rates.push(r); } }
}
fn sort_modes(modes: &mut [Mode]) {
modes.sort_by(|a, b| (b.width * b.height).cmp(&(a.width * a.height)).then(b.width.cmp(&a.width)));
for m in modes { m.rates.sort_by(|a, b| b.total_cmp(a)); }
}
/// `xrandr --query`. Interlaced modes ("1920x1080i") are left out: games want progressive ones.
pub fn parse_xrandr(text: &str) -> Vec<Output> {
let mut out: Vec<Output> = vec![];
for line in text.lines() {
if line.starts_with("Screen ") || line.trim().is_empty() { continue; }
if !line.starts_with(char::is_whitespace) {
let mut w = line.split_whitespace();
let name = w.next().unwrap_or_default().to_string();
let connected = w.next() == Some("connected");
out.push(Output { name, connected, ..Default::default() });
continue;
}
let Some(o) = out.last_mut() else { continue };
let mut w = line.split_whitespace();
let Some(size) = w.next() else { continue };
let Some((ws, hs)) = size.split_once('x') else { continue };
// custom modes are named like "1920x1080_120.00"; the size is what counts
let hs = hs.split('_').next().unwrap_or_default();
let (Ok(wd), Ok(ht)) = (ws.parse::<u32>(), hs.parse::<u32>()) else { continue };
for tok in w {
let cur = tok.contains('*');
let Ok(r) = tok.trim_end_matches(['*', '+']).parse::<f32>() else { continue };
push_mode(&mut o.modes, wd, ht, Some(r));
if size != format!("{wd}x{ht}") {
if let Some(m) = o.modes.iter_mut().find(|m| m.width == wd && m.height == ht) { m.named.push((r, size.to_string())); }
}
if cur { o.current = Some((wd, ht, r)); }
}
}
for o in &mut out { sort_modes(&mut o.modes); }
out
}
/// `kscreen-doctor -j` (KDE).
pub fn parse_kscreen_json(text: &str) -> Vec<Output> {
let Ok(v) = serde_json::from_str::<serde_json::Value>(text) else { return vec![] };
let mut out = vec![];
for o in v["outputs"].as_array().into_iter().flatten() {
let mut x = Output { name: o["name"].as_str().unwrap_or_default().into(), connected: o["connected"].as_bool().unwrap_or(false), ..Default::default() };
let cur_id = match &o["currentModeId"] { serde_json::Value::String(s) => s.clone(), n => n.to_string() };
let enabled = o["enabled"].as_bool().unwrap_or(false);
for m in o["modes"].as_array().into_iter().flatten() {
let (w, h) = (m["size"]["width"].as_u64().unwrap_or(0) as u32, m["size"]["height"].as_u64().unwrap_or(0) as u32);
if w == 0 || h == 0 { continue; }
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 enabled && id == cur_id { x.current = Some((w, h, r.unwrap_or(0.0))); }
}
sort_modes(&mut x.modes);
out.push(x);
}
out
}
/// `wlr-randr --json` (sway, Hyprland and other wlroots compositors).
pub fn parse_wlr_json(text: &str) -> Vec<Output> {
let Ok(v) = serde_json::from_str::<serde_json::Value>(text) else { return vec![] };
let mut out = vec![];
for o in v.as_array().into_iter().flatten() {
let mut x = Output { name: o["name"].as_str().unwrap_or_default().into(), connected: true, ..Default::default() };
let enabled = o["enabled"].as_bool().unwrap_or(false);
for m in o["modes"].as_array().into_iter().flatten() {
let (w, h) = (m["width"].as_u64().unwrap_or(0) as u32, m["height"].as_u64().unwrap_or(0) as u32);
if w == 0 || h == 0 { continue; }
let r = m["refresh"].as_f64().map(|r| (r * 100.0).round() as f32 / 100.0);
push_mode(&mut x.modes, w, h, r);
if enabled && m["current"].as_bool().unwrap_or(false) { x.current = Some((w, h, r.unwrap_or(0.0))); }
}
sort_modes(&mut x.modes);
out.push(x);
}
out
}
/// The outputs of this machine, from the same tool `plan()` uses for the session. Err says why there is no list
/// (GNOME Wayland, the tool missing).
pub fn outputs(session: Session, desktop: Desktop) -> Result<Vec<Output>, String> {
let run = |argv: &[&str]| -> Result<String, String> {
let o = Command::new(argv[0]).args(&argv[1..]).output().map_err(|e| format!("{}: {e}", argv[0]))?;
if !o.status.success() { return Err(format!("{} exited {}", argv[0], o.status)); }
Ok(String::from_utf8_lossy(&o.stdout).into_owned())
};
match (session, desktop) {
(Session::X11, _) => run(&["xrandr", "--query"]).map(|t| parse_xrandr(&t)),
(Session::Wayland, Desktop::Kde) => run(&["kscreen-doctor", "-j"]).map(|t| parse_kscreen_json(&t)),
(Session::Wayland, Desktop::Wlroots) => run(&["wlr-randr", "--json"]).map(|t| parse_wlr_json(&t)),
(Session::Wayland, Desktop::Gnome) => Err("GNOME Wayland has no stable tool to list or change monitors".into()),
_ => Err(format!("no monitor tool for a {session:?} {desktop:?} session")),
}
}
/// A profile that puts `monitor` back into the mode it has now, for undoing `plan()` after the game.
/// 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()?;
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.map_or(true, |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.
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; }
}
cmds
}
pub fn apply(cmds: &[Cmd]) -> Vec<(Cmd, Result<(), String>)> {
cmds.iter().map(|cmd| {
let r = Command::new(&cmd[0]).args(&cmd[1..]).status()
@@ -103,4 +250,57 @@ mod tests {
assert_eq!(p[0].join(" "), "xrandr --output HDMI-A-1 --mode 3840x2160 --rate 60");
}
#[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
1920x1080 60.00*+ 59.94 50.00
1280x720 60.00 50.00 59.94
1920x1080i 60.00 50.00
2560x1600 59.99 59.97
HDMI-1 disconnected (normal left inverted right x axis y axis)
";
#[test] fn xrandr_outputs() {
let o = parse_xrandr(XRANDR);
assert_eq!(o.len(), 2);
assert_eq!((o[0].name.as_str(), o[0].connected, o[0].current), ("Virtual-1", true, Some((1920, 1080, 60.0))));
let sizes: Vec<(u32, u32)> = o[0].modes.iter().map(|m| (m.width, m.height)).collect();
assert_eq!(sizes, vec![(2560, 1600), (1920, 1080), (1280, 720)]); // largest first, the interlaced one merged
assert_eq!(o[0].modes[1].rates, vec![60.0, 59.94, 50.0]);
assert_eq!((o[1].name.as_str(), o[1].connected, o[1].current), ("HDMI-1", false, None));
}
#[test] fn xrandr_custom_mode_names() {
// as on the test VM: the mode in use is a custom one, with its own name
let o = parse_xrandr("Virtual-1 connected primary 1920x1080+0+0 (normal) 325mm x 203mm\n 1280x800 74.99 +\n 1920x1080_120.00 119.93*\n 1920x1080 60.00 50.00\n");
assert_eq!(o[0].current, Some((1920, 1080, 119.93)));
assert_eq!(o[0].modes[0].rates, vec![119.93, 60.0, 50.0]);
let p = Profile { monitor: Some("Virtual-1".into()), width: Some(1280), height: Some(800), refresh_hz: Some(74.99), ..Default::default() };
let back = restore_profile(&o, &p).unwrap();
assert_eq!(plan_for(Session::X11, Desktop::Kde, &back, &o)[0].join(" "), "xrandr --output Virtual-1 --mode 1920x1080_120.00 --rate 119.93");
let sixty = Profile { refresh_hz: Some(60.0), ..back };
assert_eq!(plan_for(Session::X11, Desktop::Kde, &sixty, &o)[0].join(" "), "xrandr --output Virtual-1 --mode 1920x1080 --rate 60");
}
#[test] fn kscreen_outputs() {
let j = r#"{"outputs":[{"name":"DP-1","connected":true,"enabled":true,"currentModeId":"2","modes":[
{"id":"1","name":"3840x2160@60","refreshRate":59.997,"size":{"width":3840,"height":2160}},
{"id":"2","name":"1920x1080@120","refreshRate":119.98,"size":{"width":1920,"height":1080}}]},
{"name":"HDMI-A-1","connected":false,"enabled":false,"currentModeId":"","modes":[]}]}"#;
let o = parse_kscreen_json(j);
assert_eq!(o[0].current, Some((1920, 1080, 119.98)));
assert_eq!(o[0].modes[0].width, 3840);
assert!(!o[1].connected);
}
#[test] fn wlr_outputs() {
let j = r#"[{"name":"DP-2","enabled":true,"modes":[{"width":2560,"height":1440,"refresh":143.912,"preferred":true,"current":true},{"width":2560,"height":1440,"refresh":59.951}]}]"#;
let o = parse_wlr_json(j);
assert_eq!(o[0].current, Some((2560, 1440, 143.91)));
assert_eq!(o[0].modes[0].rates, vec![143.91, 59.95]);
}
#[test] fn restore_puts_the_old_mode_back() {
let o = parse_xrandr(XRANDR);
let p = Profile { monitor: Some("Virtual-1".into()), width: Some(1280), height: Some(720), refresh_hz: Some(60.0), ..Default::default() };
let r = restore_profile(&o, &p).unwrap();
assert_eq!(plan(Session::X11, Desktop::Kde, &r)[0].join(" "), "xrandr --output Virtual-1 --mode 1920x1080 --rate 60");
let same = Profile { width: Some(1920), height: Some(1080), refresh_hz: Some(60.0), ..p.clone() };
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);
}
}
+26 -7
View File
@@ -125,15 +125,24 @@ pub enum Ended { Game, Engine }
/// 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
/// game's exit status.
pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Child, grace: std::time::Duration) -> std::io::Result<(Ended, std::process::ExitStatus)> {
///
/// `detached`: the "game" process is a launcher command that hands the game to another program and returns
/// (`steam steam://rungameid/...`). Its exit then says nothing, so this waits for the engine alone, which ends when
/// the game's window closes.
pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Child, grace: std::time::Duration, detached: bool) -> std::io::Result<(Ended, std::process::ExitStatus)> {
let poll = std::time::Duration::from_millis(100);
let mut handed_off = false;
let first = loop {
if game.try_wait()?.is_some() { break Ended::Game; }
if engine.try_wait()?.is_some() { break Ended::Engine; }
if !handed_off && game.try_wait()?.is_some() {
if detached { handed_off = true; } else { break Ended::Game; }
}
if engine.try_wait()?.is_some() { break if handed_off { Ended::Game } else { Ended::Engine }; }
std::thread::sleep(poll);
};
let other = match first { Ended::Game => &mut *engine, Ended::Engine => &mut *game };
stop(other, grace)?;
if !handed_off {
let other = match first { Ended::Game => &mut *engine, Ended::Engine => &mut *game };
stop(other, grace)?;
}
Ok((first, game.wait()?))
}
@@ -217,7 +226,7 @@ mod tests {
#[test] fn supervise_stops_the_engine_when_the_game_exits() {
let (mut game, mut eng) = (sh("exit 3"), sh("exec sleep 30"));
let t = std::time::Instant::now();
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5)).unwrap();
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), false).unwrap();
assert_eq!(who, Ended::Game);
assert_eq!(status.code(), Some(3));
assert!(eng.try_wait().unwrap().is_some(), "engine was stopped");
@@ -225,10 +234,20 @@ mod tests {
}
#[test] fn supervise_stops_the_game_when_the_engine_exits() {
let (mut game, mut eng) = (sh("exec sleep 30"), sh("exit 0"));
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5)).unwrap();
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), false).unwrap();
assert_eq!(who, Ended::Engine);
assert!(!status.success(), "the game was terminated, not left running");
}
#[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"));
let t = std::time::Instant::now();
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), true).unwrap();
assert_eq!(who, Ended::Game);
assert!(status.success());
assert!(eng.wait().unwrap().success(), "the engine ended by itself");
assert!(t.elapsed() >= std::time::Duration::from_millis(500));
}
#[test] fn stop_kills_what_ignores_sigterm() {
let mut c = sh("trap '' TERM; sleep 30 & wait");
std::thread::sleep(std::time::Duration::from_millis(200));
+37
View File
@@ -0,0 +1,37 @@
//! The global "save a clip" key. The engine owns it (engine/framegen/globalkeys.py); this says, for the launcher,
//! whether this session can have one at all.
use crate::display::Session;
use std::process::Command;
/// The engine's save key; Ctrl+Alt+B saves a before & after.
pub const SAVE_KEY: &str = "Ctrl+Alt+R";
/// Whether xdg-desktop-portal offers GlobalShortcuts. None: the portal could not be asked (no gdbus, no session bus).
pub fn portal_has_global_shortcuts() -> Option<bool> {
let o = Command::new("gdbus").args(["introspect", "--session", "--dest", "org.freedesktop.portal.Desktop", "--object-path", "/org/freedesktop/portal/desktop"]).output().ok()?;
if !o.status.success() { return None; }
Some(String::from_utf8_lossy(&o.stdout).contains("org.freedesktop.portal.GlobalShortcuts"))
}
/// One line for the settings page.
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(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(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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(false)).starts_with("No global save key"));
assert!(status(Session::Unknown, Some(true)).starts_with("No global save key"));
}
}
+60 -20
View File
@@ -10,31 +10,61 @@ pub enum Plan {
Unsupported(String),
}
/// What "Play" does for an entry.
/// What "Play" does for an entry. `summit_cli` is the path of the `summit` binary; `enhance` asks for the engine
/// on the game's window (the game profile's frame generation and upscaler).
///
/// * Steam: hands over to the Steam client (`steam steam://rungameid/<id>`). Steam tracks its own playtime.
/// A game that is not installed gets `steam://install/<id>`, which opens Steam's install dialog.
/// * Added by hand, with a file path: goes through `summit run <id> -- <path>` so the display profile is applied
/// and the session is tracked. `summit_cli` is the path of the `summit` binary.
/// * Lutris: `lutris lutris:rungame/<slug>`.
/// * Steam: `summit run steam:<id> --detached -- steam steam://rungameid/<id>`, so the display profile is applied
/// first. The `steam` command hands the game to the Steam client and returns, hence `--detached`. With `enhance`
/// the engine takes the window of class `steam_app_<id>` (what Steam gives Proton games) and waits up to 120 s
/// for it. Steam keeps the playtime. Without the summit binary it falls back to `steam steam://rungameid/<id>`.
/// A game that is not installed gets `steam steam://install/<id>`, which opens Steam's install dialog.
/// * Added by hand: `summit run <id> [--enhance] -- <path>`: profile applied, session tracked.
/// * Lutris: `summit run <id> --detached -- lutris lutris:rungame/<slug>` (no enhance: Lutris games have no
/// window rule Summit can know in advance).
/// * Heroic and folders found on disk: not wired yet.
pub fn plan(e: &Entry, summit_cli: Option<&Path>) -> Plan {
pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
let cli = summit_cli.map(|c| c.to_string_lossy().into_owned());
let via_run = |cli: &str, extra: &[String], cmd: Vec<String>| {
let mut v = vec![cli.to_string(), "run".into(), e.id.clone()];
v.extend(extra.iter().cloned());
v.push("--".into());
v.extend(cmd);
v
};
match e.source {
Source::Steam => match e.steam_app_id {
Some(id) if e.installed => Plan::Run(vec!["steam".into(), format!("steam://rungameid/{id}")]),
Some(id) if e.installed => {
let steam = vec!["steam".to_string(), format!("steam://rungameid/{id}")];
match cli {
Some(cli) => {
let mut extra = vec!["--detached".to_string()];
if enhance { extra.extend(["--enhance".into(), "--window".into(), format!("class:steam_app_{id}"), "--wait".into(), "120".into()]); }
Plan::Run(via_run(&cli, &extra, steam))
}
None if enhance => Plan::Unsupported("Enhance needs the summit command line tool next to summit-gui".into()),
None => Plan::Run(steam),
}
}
Some(id) => Plan::Run(vec!["steam".into(), format!("steam://install/{id}")]),
None => Plan::Unsupported("this Steam entry has no app id".into()),
},
Source::Custom => {
let Some(path) = e.path.as_deref() else { return Plan::Unsupported("no path stored for this entry".into()) };
if !Path::new(path).is_file() { return Plan::Unsupported(format!("{path} is not a file Summit can run")); }
match summit_cli {
Some(cli) => Plan::Run(vec![cli.to_string_lossy().into_owned(), "run".into(), e.id.clone(), "--".into(), path.into()]),
match cli {
Some(cli) => {
let extra: Vec<String> = if enhance { vec!["--enhance".into()] } else { vec![] };
Plan::Run(via_run(&cli, &extra, vec![path.into()]))
}
None => Plan::Unsupported("the summit command line tool was not found next to summit-gui".into()),
}
}
Source::Lutris => match e.id.strip_prefix("lutris:") {
Some(slug) if !slug.is_empty() => Plan::Run(vec!["lutris".into(), format!("lutris:rungame/{slug}")]),
Some(slug) if !slug.is_empty() => {
let lutris = vec!["lutris".to_string(), format!("lutris:rungame/{slug}")];
if enhance { return Plan::Unsupported("Enhance is not wired for Lutris games yet".into()); }
match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], lutris)), None => Plan::Run(lutris) }
}
_ => Plan::Unsupported("no Lutris slug for this entry".into()),
},
Source::Heroic => Plan::Unsupported("launching Heroic games from Summit is not built yet".into()),
@@ -52,16 +82,22 @@ mod tests {
fn entry(id: &str, source: Source, installed: bool, app: Option<u32>, path: Option<&str>) -> Entry {
Entry { id: id.into(), title: id.into(), source, kind: Kind::Game, installed, path: path.map(Into::into), steam_app_id: app, playtime_minutes: 0, last_played: None, reasons: vec![] }
}
const CLI: &str = "/usr/bin/summit";
fn cli() -> Option<&'static Path> { Some(Path::new(CLI)) }
fn argv(p: Plan) -> String { match p { Plan::Run(v) => v.join(" "), Plan::Unsupported(w) => format!("unsupported: {w}") } }
#[test]
fn steam_installed_runs_through_the_client() {
fn steam_installed_goes_through_summit_run() {
let e = entry("steam:620", Source::Steam, true, Some(620), None);
assert_eq!(plan(&e, None), Plan::Run(vec!["steam".into(), "steam://rungameid/620".into()]));
assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam:620 --detached -- steam steam://rungameid/620");
assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam:620 --detached --enhance --window class:steam_app_620 --wait 120 -- steam steam://rungameid/620");
assert_eq!(plan(&e, None, false), Plan::Run(vec!["steam".into(), "steam://rungameid/620".into()]));
assert!(matches!(plan(&e, None, true), Plan::Unsupported(_)));
assert!(!is_install(&e));
}
#[test]
fn steam_not_installed_opens_install() {
let e = entry("steam:730", Source::Steam, false, Some(730), None);
assert_eq!(plan(&e, None), Plan::Run(vec!["steam".into(), "steam://install/730".into()]));
assert_eq!(plan(&e, cli(), true), Plan::Run(vec!["steam".into(), "steam://install/730".into()]));
assert!(is_install(&e));
}
#[test]
@@ -70,19 +106,23 @@ mod tests {
std::fs::write(&f, "#!/bin/sh\n").unwrap();
let p = f.to_string_lossy().into_owned();
let e = entry("custom:voidrunner", Source::Custom, true, None, Some(&p));
assert_eq!(plan(&e, Some(Path::new("/usr/bin/summit"))), Plan::Run(vec!["/usr/bin/summit".into(), "run".into(), "custom:voidrunner".into(), "--".into(), p]));
assert!(matches!(plan(&e, None), Plan::Unsupported(_)));
assert_eq!(argv(plan(&e, cli(), false)), format!("/usr/bin/summit run custom:voidrunner -- {p}"));
assert_eq!(argv(plan(&e, cli(), true)), format!("/usr/bin/summit run custom:voidrunner --enhance -- {p}"));
assert!(matches!(plan(&e, None, false), Plan::Unsupported(_)));
let _ = std::fs::remove_file(f);
}
#[test]
fn custom_with_missing_file_is_unsupported() {
let e = entry("custom:gone", Source::Custom, false, None, Some("/nonexistent/summit/game.sh"));
assert!(matches!(plan(&e, Some(Path::new("/usr/bin/summit"))), Plan::Unsupported(_)));
assert!(matches!(plan(&e, cli(), false), Plan::Unsupported(_)));
}
#[test]
fn lutris_and_unwired_sources() {
assert_eq!(plan(&entry("lutris:celeste", Source::Lutris, true, None, None), None), Plan::Run(vec!["lutris".into(), "lutris:rungame/celeste".into()]));
assert!(matches!(plan(&entry("heroic:epic:x", Source::Heroic, true, None, None), None), Plan::Unsupported(_)));
assert!(matches!(plan(&entry("scan:/g", Source::Heuristic, true, None, Some("/g")), None), Plan::Unsupported(_)));
let l = entry("lutris:celeste", Source::Lutris, true, None, None);
assert_eq!(argv(plan(&l, cli(), false)), "/usr/bin/summit run lutris:celeste --detached -- lutris lutris:rungame/celeste");
assert_eq!(plan(&l, None, false), Plan::Run(vec!["lutris".into(), "lutris:rungame/celeste".into()]));
assert!(matches!(plan(&l, cli(), true), Plan::Unsupported(_)));
assert!(matches!(plan(&entry("heroic:epic:x", Source::Heroic, true, None, None), cli(), false), Plan::Unsupported(_)));
assert!(matches!(plan(&entry("scan:/g", Source::Heuristic, true, None, Some("/g")), cli(), false), Plan::Unsupported(_)));
}
}
+1
View File
@@ -1,6 +1,7 @@
//! Summit core: library scanning, per-game profiles, and the detection-reason model.
pub mod display;
pub mod engine;
pub mod hotkey;
pub mod epic;
pub mod launch;
pub mod model;
+13 -1
View File
@@ -25,6 +25,8 @@ pub struct Profile {
/// RIFE model, e.g. "4.22.lite" (default), "4.25", "4.26".
pub model: Option<String>,
pub launch_args: Vec<String>,
/// Play from the launcher runs the engine on the game's window (`summit run --enhance`).
pub enhance: bool,
}
pub fn dir() -> Result<PathBuf> {
@@ -54,8 +56,18 @@ mod tests {
use super::*;
#[test]
fn roundtrip_toml() {
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(60.0), fullscreen: true, focus: true, upscaler: "fsr".into(), framegen: "rife".into(), framegen_multiplier: 2, launch_args: vec![], target_hz: Some(90), model: None };
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(60.0), fullscreen: true, focus: true, upscaler: "fsr".into(), framegen: "rife".into(), framegen_multiplier: 2, launch_args: vec![], target_hz: Some(90), model: None, enhance: true };
let s = toml::to_string_pretty(&p).unwrap();
assert_eq!(toml::from_str::<Profile>(&s).unwrap(), p);
}
}
#[cfg(test)]
mod compat {
#[test]
fn old_files_without_enhance_still_load() {
let p: super::Profile = toml::from_str("upscaler = \"fsr\"\nframegen = \"rife\"\n").unwrap();
assert!(!p.enhance);
assert_eq!(p.upscaler, "fsr");
}
}
+151
View File
@@ -1,5 +1,6 @@
//! What the views show, computed from the scanned entries. No UI types here, so it is unit tested.
use summit_core::model::{Entry, Kind, Source};
use summit_core::display::Output;
use summit_core::profile::Profile;
pub const SHELF_MAX: usize = 24;
@@ -122,6 +123,104 @@ pub fn profile_summary(p: &Profile) -> ProfileSummary {
}
}
// ---- the profile editor ----
/// One row of the profile editor: a value picked from `options`.
#[derive(Debug, Clone, PartialEq)]
pub struct EditRow { pub label: &'static str, pub hint: String, pub options: Vec<String>, pub value: usize }
pub const UPSCALERS: [&str; 3] = ["none", "fsr", "rtx-vsr"];
pub const TARGET_HZ: [u32; 3] = [60, 90, 120];
#[cfg(test)]
pub const EDIT_ROWS: usize = 8;
fn rate_label(r: f32) -> String { if (r - r.round()).abs() < 0.005 { format!("{r:.0} Hz") } else { format!("{r:.2} Hz") } }
fn same_rate(a: f32, b: f32) -> bool { (a - b).abs() < 0.01 }
/// The monitors to choose from: connected outputs, plus the profile's own if it is not connected now.
pub fn monitor_names(p: &Profile, outs: &[Output]) -> Vec<String> {
let mut v: Vec<String> = outs.iter().filter(|o| o.connected).map(|o| o.name.clone()).collect();
if let Some(m) = &p.monitor { if !v.contains(m) { v.push(m.clone()); } }
v
}
fn sizes(p: &Profile, outs: &[Output]) -> Vec<(u32, u32)> {
let mut v: Vec<(u32, u32)> = p.monitor.as_ref().and_then(|m| outs.iter().find(|o| &o.name == m))
.map(|o| o.modes.iter().map(|m| (m.width, m.height)).collect()).unwrap_or_default();
if let (Some(w), Some(h)) = (p.width, p.height) { if !v.contains(&(w, h)) { v.push((w, h)); } }
v
}
fn rates(p: &Profile, outs: &[Output]) -> Vec<f32> {
let mut v: Vec<f32> = match (p.monitor.as_ref(), p.width, p.height) {
(Some(m), Some(w), Some(h)) => outs.iter().find(|o| &o.name == m)
.and_then(|o| o.modes.iter().find(|x| x.width == w && x.height == h)).map(|x| x.rates.clone()).unwrap_or_default(),
_ => vec![],
};
if let Some(r) = p.refresh_hz { if !v.iter().any(|x| same_rate(*x, r)) { v.push(r); } }
v
}
/// Editor rows for `p`. `outs` is what the display module listed; `list_err` why there is no list.
pub fn edit_rows(p: &Profile, outs: &[Output], list_err: Option<&str>, tool: &str) -> Vec<EditRow> {
let onoff = |b: bool| (vec!["Off".to_string(), "On".to_string()], b as usize);
let mons = monitor_names(p, outs);
let mut mon_opts = vec!["Default".to_string()];
mon_opts.extend(mons.iter().map(|m| if outs.iter().any(|o| &o.name == m && o.connected) { m.clone() } else { format!("{m} (not connected)") }));
let mon_val = p.monitor.as_ref().and_then(|m| mons.iter().position(|x| x == m)).map_or(0, |i| i + 1);
let sz = sizes(p, outs);
let mut sz_opts = vec!["Default".to_string()];
sz_opts.extend(sz.iter().map(|(w, h)| format!("{w} × {h}")));
let sz_val = match (p.width, p.height) { (Some(w), Some(h)) => sz.iter().position(|x| *x == (w, h)).map_or(0, |i| i + 1), _ => 0 };
let rt = rates(p, outs);
let mut rt_opts = vec!["Default".to_string()];
rt_opts.extend(rt.iter().map(|r| rate_label(*r)));
let rt_val = p.refresh_hz.and_then(|r| rt.iter().position(|x| same_rate(*x, r))).map_or(0, |i| i + 1);
let (fs, fs_v) = onoff(p.fullscreen);
let (fo, fo_v) = onoff(p.focus);
let up_v = UPSCALERS.iter().position(|u| *u == p.upscaler || (*u == "rtx-vsr" && p.upscaler == "vsr")).unwrap_or(0);
let hz_v = TARGET_HZ.iter().position(|h| Some(*h) == p.target_hz).unwrap_or(0);
let mon_hint = match list_err {
Some(e) => format!("Monitors could not be listed: {e}."),
None => format!("Listed with {tool}. Switched with {tool} when Summit starts the game, and put back when it ends."),
};
vec![
EditRow { label: "Monitor", hint: mon_hint, options: mon_opts, value: mon_val },
EditRow { label: "Resolution", hint: if p.monitor.is_none() { "Pick a monitor first.".into() } else { "The monitor's mode while the game runs.".into() }, options: sz_opts, value: sz_val },
EditRow { label: "Refresh rate", hint: if p.width.is_none() { "Pick a resolution first.".into() } else { "Rates this mode offers.".into() }, options: rt_opts, value: rt_val },
EditRow { label: "Fullscreen", hint: "With Enhance: the engine's picture covers the whole monitor (where the upscaler has work to do). The game's own window mode is not changed.".into(), options: fs, value: fs_v },
EditRow { label: "Focus", hint: "Stored only: raising the game window after launch is not built yet.".into(), options: fo, value: fo_v },
EditRow { label: "Upscaler", hint: "Used by Enhance. FSR was run on the test machine; RTX VSR is wired but untested.".into(), options: vec!["None".into(), "FSR".into(), "RTX VSR".into()], value: up_v },
EditRow { label: "Frame generation", hint: "Used by Enhance: RIFE needs an NVIDIA GPU and the engine's Python environment.".into(), options: vec!["None".into(), "RIFE".into()], value: (p.framegen == "rife") as usize },
EditRow { label: "Target rate", hint: "The engine's output rate. 60 Hz was tested; 90 and 120 Hz are wired, not tested.".into(), options: TARGET_HZ.iter().map(|h| format!("{h} Hz")).collect(), value: hz_v },
]
}
/// `p` with editor row `row` set to option `value` (as indexed in `edit_rows`).
pub fn edit_apply(p: &Profile, outs: &[Output], row: usize, value: usize) -> Profile {
let mut p = p.clone();
match row {
0 => {
let mons = monitor_names(&p, outs);
let new = if value == 0 { None } else { mons.get(value - 1).cloned() };
if new != p.monitor { p.monitor = new; p.width = None; p.height = None; p.refresh_hz = None; }
}
1 => {
let sz = sizes(&p, outs);
let new = if value == 0 { None } else { sz.get(value - 1).copied() };
if new != p.width.zip(p.height) {
p.width = new.map(|x| x.0); p.height = new.map(|x| x.1);
if let Some(r) = p.refresh_hz { p.refresh_hz = None; if rates(&p, outs).iter().any(|x| same_rate(*x, r)) { p.refresh_hz = Some(r); } }
}
}
2 => { p.refresh_hz = if value == 0 { None } else { rates(&p, outs).get(value - 1).copied() }; }
3 => p.fullscreen = value == 1,
4 => p.focus = value == 1,
5 => p.upscaler = UPSCALERS[value.min(2)].into(),
6 => p.framegen = if value == 1 { "rife".into() } else { "none".into() },
7 => p.target_hz = Some(TARGET_HZ[value.min(2)]),
_ => {}
}
p
}
#[cfg(test)]
mod tests {
use super::*;
@@ -187,4 +286,56 @@ mod tests {
}
#[test]
fn colours_are_stable_per_title() { assert_eq!(colors("Portal 2"), colors("Portal 2")); }
fn outs() -> Vec<Output> {
summit_core::display::parse_xrandr("Screen 0: minimum 320 x 200\nVirtual-1 connected primary 1920x1080+0+0 (normal)\n 1920x1080 60.00*+ 50.00\n 1280x720 60.00 59.94\nHDMI-1 disconnected (normal)\n")
}
#[test]
fn editor_lists_real_outputs_and_their_modes() {
let o = outs();
let r = edit_rows(&Profile::default(), &o, None, "xrandr");
assert_eq!(r.len(), EDIT_ROWS);
assert_eq!(r[0].options, vec!["Default", "Virtual-1"]); // disconnected outputs are left out
assert_eq!((r[0].value, r[1].options.len(), r[2].options.len()), (0, 1, 1));
let p = edit_apply(&Profile::default(), &o, 0, 1);
assert_eq!(p.monitor.as_deref(), Some("Virtual-1"));
let r = edit_rows(&p, &o, None, "xrandr");
assert_eq!(r[1].options, vec!["Default", "1920 × 1080", "1280 × 720"]);
let p = edit_apply(&p, &o, 1, 2);
assert_eq!((p.width, p.height), (Some(1280), Some(720)));
let r = edit_rows(&p, &o, None, "xrandr");
assert_eq!(r[2].options, vec!["Default", "60 Hz", "59.94 Hz"]);
let p = edit_apply(&p, &o, 2, 2);
assert_eq!(p.refresh_hz, Some(59.94));
// a size without that rate drops the rate; switching monitor drops the whole mode
let q = edit_apply(&p, &o, 1, 1);
assert_eq!((q.width, q.refresh_hz), (Some(1920), None));
let q = edit_apply(&p, &o, 0, 0);
assert_eq!((q.monitor, q.width, q.refresh_hz), (None, None, None));
}
#[test]
fn editor_keeps_a_monitor_that_is_not_connected() {
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(120.0), ..Default::default() };
let r = edit_rows(&p, &outs(), None, "xrandr");
assert_eq!(r[0].options[r[0].value], "HDMI-A-1 (not connected)");
assert_eq!(r[1].options[r[1].value], "3840 × 2160");
assert_eq!(r[2].options[r[2].value], "120 Hz");
let r = edit_rows(&p, &[], Some("GNOME Wayland has no stable tool"), "");
assert!(r[0].hint.contains("could not be listed"));
}
#[test]
fn editor_switches_and_engine_settings() {
let o = outs();
let p = Profile::default();
let p = edit_apply(&p, &o, 3, 1);
let p = edit_apply(&p, &o, 4, 1);
let p = edit_apply(&p, &o, 5, 1);
let p = edit_apply(&p, &o, 6, 1);
let p = edit_apply(&p, &o, 7, 2);
assert!(p.fullscreen && p.focus);
assert_eq!((p.upscaler.as_str(), p.framegen.as_str(), p.target_hz), ("fsr", "rife", Some(120)));
let r = edit_rows(&p, &o, None, "xrandr");
assert_eq!((r[3].value, r[4].value, r[5].value, r[6].value, r[7].value), (1, 1, 1, 1, 2));
let p = edit_apply(&p, &o, 6, 0);
assert_eq!(p.framegen, "none");
}
}
+102 -10
View File
@@ -9,7 +9,7 @@ use std::cell::{Cell, RefCell};
use std::collections::{HashSet, VecDeque};
use std::path::PathBuf;
use std::rc::Rc;
use summit_core::{display, launch, model::{Entry, Kind, Source}, profile, scan, state, steam, ui as prefs};
use summit_core::{display, hotkey, launch, model::{Entry, Kind, Source}, profile, scan, state, steam, ui as prefs};
slint::include_modules!();
@@ -40,6 +40,8 @@ pub struct App {
base_scale: Cell<f32>,
fullscreen: Cell<bool>,
save_timer: slint::Timer,
/// The profile editor's game id and the outputs listed when it opened (or why there is no list).
editing: RefCell<Option<(usize, Result<Vec<display::Output>, String>)>>,
}
impl App {
@@ -58,7 +60,7 @@ impl App {
fn row(&self, e: &Entry, keep: Option<&Game>) -> Game {
let (c1, c2) = data::colors(&e.title);
let action = match launch::plan(e, self.cli().as_deref()) {
let action = match launch::plan(e, self.cli().as_deref(), false) {
launch::Plan::Run(_) if launch::is_install(e) => "INSTALL",
launch::Plan::Run(_) => "PLAY",
launch::Plan::Unsupported(_) => "",
@@ -180,19 +182,29 @@ impl App {
} else {
(st.tracked.get(&e.id).map_or(0, |t| t.sessions).to_string(), "Counted when Summit starts it")
};
let (label, can, play_note) = match launch::plan(&e, self.cli().as_deref()) {
let (label, can, play_note) = match launch::plan(&e, self.cli().as_deref(), false) {
launch::Plan::Run(_) if launch::is_install(&e) => ("INSTALL", true, "Opens Steam's install dialog for this game.".to_string()),
launch::Plan::Run(_) if e.source == Source::Steam => ("PLAY", true, "Starts through the Steam client. Steam keeps the playtime.".to_string()),
launch::Plan::Run(_) if e.source == Source::Lutris => ("PLAY", true, "Starts through Lutris. Not tested yet.".to_string()),
launch::Plan::Run(_) if e.source == Source::Steam => ("PLAY", true, "Starts through summit run and the Steam client: the display profile is applied, Steam keeps the playtime. Not tested with a real Steam yet.".to_string()),
launch::Plan::Run(_) if e.source == Source::Lutris => ("PLAY", true, "Starts through summit run and Lutris. Not tested yet.".to_string()),
launch::Plan::Run(_) => ("PLAY", true, "Summit starts it, applies the launch profile and tracks the session.".to_string()),
launch::Plan::Unsupported(why) => ("PLAY", false, format!("Summit cannot start this yet: {why}.")),
};
let session = display::detect_session();
let (can_enhance, enhance_note) = 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 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(_) => (true, "Enhance: frame generation and the upscaler from this game's profile run on its window, live, until either one exits.".to_string()),
};
let reasons: Vec<SharedString> = e.reasons.iter().map(|r| short(r).into()).collect();
let prof = profile::load(&e.id).unwrap_or_default();
self.ui.global::<Lib>().set_detail(Detail {
idx, sessions: sessions.into(), sessions_note: note.into(), reasons: ModelRc::new(VecModel::from(reasons)),
path: short(&e.path.clone().unwrap_or_default()).into(),
monitor: p.monitor.into(), mode: p.mode.into(), upscaler: p.upscaler.into(), framegen: p.framegen.into(), window: p.window.into(), profile_set: p.set,
play_label: label.into(), play_note: play_note.into(), can_play: can,
enhance: prof.enhance && can_enhance, can_enhance, enhance_note: enhance_note.into(),
});
drop(st);
self.want_cover(idx as usize);
@@ -202,13 +214,24 @@ impl App {
fn play(&self, idx: i32) {
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
let argv = match launch::plan(&e, self.cli().as_deref()) {
let enhance = profile::load(&e.id).map(|p| p.enhance).unwrap_or(false) && self.ui.global::<Lib>().get_detail().can_enhance;
let argv = match launch::plan(&e, self.cli().as_deref(), enhance) {
launch::Plan::Run(argv) => argv,
launch::Plan::Unsupported(why) => return self.toast(format!("Cannot start {}: {why}", e.title)),
};
if self.headless { return self.toast(format!("Headless render, nothing started. Would run: {}", argv.join(" "))); }
use std::process::{Command, Stdio};
let spawn = |argv: &[String]| Command::new(&argv[0]).args(&argv[1..]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn();
// What `summit run` prints (display steps, the engine's command, how it ended) goes to a log, for when it fails.
let log = dirs_log().and_then(|p| std::fs::File::create(&p).ok().map(|f| (p, f)));
let spawn = |argv: &[String]| {
let mut c = Command::new(&argv[0]);
c.args(&argv[1..]).stdin(Stdio::null());
match log.as_ref().and_then(|(_, f)| Some((f.try_clone().ok()?, f.try_clone().ok()?))) {
Some((o, e)) => { c.stdout(o).stderr(e); }
None => { c.stdout(Stdio::null()).stderr(Stdio::null()); }
}
c.spawn()
};
// Flatpak and Snap installs have no `steam` on PATH; the desktop's steam:// handler reaches them.
let started = match spawn(&argv) {
Err(err) if err.kind() == std::io::ErrorKind::NotFound && argv[0] == "steam" => spawn(&["xdg-open".to_string(), argv[1].clone()]),
@@ -216,7 +239,8 @@ impl App {
};
match started {
Ok(mut child) => {
self.toast(if launch::is_install(&e) { format!("Asked Steam to install {}", e.title) } else if e.source == Source::Steam { format!("Starting {} through Steam", e.title) } else { format!("Starting {}", e.title) });
let what = if launch::is_install(&e) { format!("Asked Steam to install {}", e.title) } else if e.source == Source::Steam { format!("Starting {} through Steam", e.title) } else { format!("Starting {}", e.title) };
self.toast(if enhance { format!("{what}, with Enhance") } else { what });
// When it exits, pick up the session `summit run` recorded.
std::thread::spawn(move || { let _ = child.wait(); let _ = slint::invoke_from_event_loop(|| with_app(|a| a.refresh_tracked())); });
}
@@ -224,6 +248,59 @@ impl App {
}
}
// ---- launch profile ----
fn toggle_enhance(&self, idx: i32) {
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
let mut p = profile::load(&e.id).unwrap_or_default();
p.enhance = !p.enhance;
// An empty frame generation setting means the engine's default (RIFE): say it in the profile, so the page shows it.
if p.enhance && p.framegen.is_empty() { p.framegen = "rife".into(); }
match profile::save(&e.id, &p) {
Ok(_) => { self.toast(if p.enhance { format!("Enhance on for {}", e.title) } else { format!("Enhance off for {}", e.title) }); self.open_detail(idx); }
Err(err) => self.toast(format!("Could not save the profile: {err}")),
}
}
fn open_profile(&self, idx: i32) {
if idx < 0 || idx as usize >= self.entries.borrow().len() { return; }
let (s, d) = (display::detect_session(), display::detect_desktop());
let outs = display::outputs(s, d);
*self.editing.borrow_mut() = Some((idx as usize, outs));
let lib = self.ui.global::<Lib>();
lib.set_editor_row(0);
self.fill_editor();
lib.set_editor_open(true);
}
fn fill_editor(&self) {
let ed = self.editing.borrow();
let Some((idx, outs)) = ed.as_ref() else { return };
let id = self.entries.borrow()[*idx].id.clone();
let p = profile::load(&id).unwrap_or_default();
let tool = match (display::detect_session(), display::detect_desktop()) {
(display::Session::X11, _) => "xrandr", (_, display::Desktop::Kde) => "kscreen-doctor", (_, display::Desktop::Wlroots) => "wlr-randr", _ => "",
};
let (list, err) = match outs { Ok(o) => (o.as_slice(), None), Err(e) => (&[][..], Some(e.as_str())) };
let rows: Vec<PRow> = data::edit_rows(&p, list, err, tool).into_iter().map(|r| PRow {
label: r.label.into(), hint: r.hint.into(), value: r.value as i32,
options: ModelRc::new(VecModel::from(r.options.into_iter().map(SharedString::from).collect::<Vec<_>>())),
}).collect();
let lib = self.ui.global::<Lib>();
lib.set_prof_rows(ModelRc::new(VecModel::from(rows)));
lib.set_prof_file(profile::dir().map(|d| tilde(&d.join(format!("{}.toml", id.replace(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_', "_"))))).unwrap_or_default().into());
}
fn prof_set(&self, row: i32, value: i32) {
let Some((idx, outs)) = self.editing.borrow().as_ref().map(|(i, o)| (*i, o.clone().unwrap_or_default())) else { return };
let id = self.entries.borrow()[idx].id.clone();
let old = profile::load(&id).unwrap_or_default();
let new = data::edit_apply(&old, &outs, row.max(0) as usize, value.max(0) as usize);
if new == old { return; }
if let Err(err) = profile::save(&id, &new) { return self.toast(format!("Could not save the profile: {err}")); }
self.fill_editor();
self.open_detail(idx as i32);
}
fn refresh_row(&self, idx: usize) {
let old = self.games.row_data(idx);
let row = self.row(&self.entries.borrow()[idx], old.as_ref());
@@ -334,6 +411,12 @@ impl App {
fn nearest(all: &[f32], v: f32) -> usize {
(0..all.len()).min_by(|a, b| (all[*a] - v).abs().total_cmp(&(all[*b] - v).abs())).unwrap_or(0)
}
/// ~/.cache/summit/last-run.log: the output of the last game started from the launcher.
fn dirs_log() -> Option<PathBuf> {
let d = std::env::var_os("XDG_CACHE_HOME").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))?.join("summit");
std::fs::create_dir_all(&d).ok()?;
Some(d.join("last-run.log"))
}
fn tilde(p: &std::path::Path) -> String { short(&p.to_string_lossy()) }
/// Paths under the home folder read better as ~/...; detection reasons are full of them.
fn short(text: &str) -> String {
@@ -364,7 +447,7 @@ pub fn build(headless: bool) -> Rc<App> {
requested: Default::default(), loaded: Default::default(), keep: Default::default(),
backdrop_seq: Cell::new(0), backdrop_for: Cell::new(-1),
settings: RefCell::new(prefs::load()), default_profile: RefCell::new(profile::load("default").unwrap_or_default()),
theme_keys, headless, base_scale: Cell::new(1.0), fullscreen: Cell::new(false), save_timer: slint::Timer::default(),
theme_keys, headless, base_scale: Cell::new(1.0), fullscreen: Cell::new(false), save_timer: slint::Timer::default(), editing: RefCell::new(None),
});
APP.with(|a| *a.borrow_mut() = Some(app.clone()));
@@ -388,6 +471,12 @@ pub fn build(headless: bool) -> Rc<App> {
lib.on_toggle_pin(|i| with_app(|a| a.toggle_pin(i)));
lib.on_settings_changed(|| with_app(|a| a.settings_changed()));
lib.on_toggle_fullscreen(|| with_app(|a| a.toggle_fullscreen()));
lib.on_toggle_enhance(|i| with_app(|a| a.toggle_enhance(i)));
lib.on_open_profile(|i| with_app(|a| a.open_profile(i)));
lib.on_prof_set(|r, v| with_app(|a| a.prof_set(r, v)));
let session = display::detect_session();
let portal = if session == display::Session::Wayland && !headless { hotkey::portal_has_global_shortcuts() } else { None };
lib.set_hotkey_status(hotkey::status(session, portal).into());
// Overrides for screenshots and testing. They are not written to ui.toml unless a setting is changed afterwards.
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
@@ -403,7 +492,10 @@ pub fn build(headless: bool) -> Rc<App> {
if let Some(want) = env("SUMMIT_DETAIL") {
let w = want.to_lowercase();
let hit = app.entries.borrow().iter().position(|e| e.id.to_lowercase() == w).or_else(|| app.entries.borrow().iter().position(|e| e.title.to_lowercase().contains(&w)));
if let Some(i) = hit { app.open_detail(i as i32); }
if let Some(i) = hit {
app.open_detail(i as i32);
if env("SUMMIT_EDITOR").is_some() { app.open_profile(i as i32); }
}
}
app
}
+3 -2
View File
@@ -1,11 +1,11 @@
// Summit launcher window: navbar, the four views, a game's page, the art backdrop and keyboard navigation.
import { Theme, Palette } from "theme.slint";
import { Lib, Prefs, Game, URow, Detail, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint";
import { Lib, Prefs, Game, URow, Detail, PRow, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint";
import { HomeView } from "home.slint";
import { LibraryView, UnfilteredView } from "library.slint";
import { DetailView } from "detail.slint";
import { SettingsView } from "settings.slint";
export { Lib, Prefs, Game, URow, Detail, Palette }
export { Lib, Prefs, Game, URow, Detail, PRow, Palette }
component NavTab inherits Rectangle {
in property <string> label;
@@ -86,6 +86,7 @@ export component MainWindow inherits Window {
}
public function close-detail() {
root.detail-open = false;
Lib.editor-open = false;
if (root.view == 0) { Lib.focus-game(home.hero-idx); }
}
+80 -11
View File
@@ -1,6 +1,6 @@
// A game's page: art, stats, why Summit lists it, its launch profile and the actions.
import { Theme } from "theme.slint";
import { Lib, Game, Detail, Icon, Icons, Btn, Tag, CoverArt } from "widgets.slint";
import { Lib, Game, Detail, PRow, Icon, Icons, Btn, Tag, CoverArt, FocusRing } from "widgets.slint";
component Stat inherits Rectangle {
in property <string> label;
@@ -33,9 +33,64 @@ component Field inherits Rectangle {
Text { x: 150px; width: parent.width - 150px; height: parent.height; text: root.value; color: root.unset ? Theme.p.faint : Theme.p.text; font-size: Theme.t-sm; font-weight: 600; vertical-alignment: center; overflow: elide; }
}
// The launch profile editor, over the game's page. Up/Down picks a row, Left/Right changes it; every change is saved.
component Picker inherits Rectangle {
in property <PRow> r;
in property <bool> focused;
callback set(int);
height: 64px; border-radius: Theme.r-md;
background: root.focused ? Theme.p.raised : Theme.p.surface.with-alpha(0.7);
border-width: Theme.p.border-w; border-color: Theme.p.border;
Text { x: 18px; y: 12px; text: root.r.label; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; }
Text { x: 18px; y: 36px; width: parent.width - 360px; text: root.r.hint; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
Rectangle { x: parent.width - 330px; y: 12px; width: 312px; height: 40px; border-radius: 20px; background: Theme.p.surface; border-width: Theme.p.border-w; border-color: Theme.p.border;
Text { x: 14px; width: 24px; height: parent.height; text: "‹"; font-size: 22px; vertical-alignment: center; color: root.r.value > 0 ? Theme.p.text : Theme.p.faint; }
Text { x: 40px; width: parent.width - 80px; height: parent.height; text: root.r.options[root.r.value]; horizontal-alignment: center; vertical-alignment: center; color: root.r.value == 0 && root.r.options[0] == "Default" ? Theme.p.dim : Theme.p.text; font-size: Theme.t-sm; font-weight: 700; overflow: elide; }
Text { x: parent.width - 32px; width: 24px; height: parent.height; text: "›"; font-size: 22px; vertical-alignment: center; color: root.r.value < root.r.options.length - 1 ? Theme.p.text : Theme.p.faint; }
TouchArea { x: 0; width: 48px; mouse-cursor: pointer; clicked => { if (root.r.value > 0) { root.set(root.r.value - 1); } } }
TouchArea { x: parent.width - 48px; width: 48px; mouse-cursor: pointer; clicked => { if (root.r.value < root.r.options.length - 1) { root.set(root.r.value + 1); } } }
}
FocusRing { on: root.focused; radius: Theme.r-md; }
}
component ProfileEditor inherits Rectangle {
in property <string> title;
callback close();
public function key(e: KeyEvent) -> bool {
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
else if (e.text == Key.DownArrow) { Lib.editor-row = Math.min(Lib.prof-rows.length - 1, Lib.editor-row + 1); }
else if (e.text == Key.UpArrow) { Lib.editor-row = Math.max(0, Lib.editor-row - 1); }
else if (e.text == Key.RightArrow || e.text == Key.Return || e.text == " ") {
if (Lib.prof-rows[Lib.editor-row].value < Lib.prof-rows[Lib.editor-row].options.length - 1) { Lib.prof-set(Lib.editor-row, Lib.prof-rows[Lib.editor-row].value + 1); }
else if (e.text != Key.RightArrow) { Lib.prof-set(Lib.editor-row, 0); }
}
else if (e.text == Key.LeftArrow) { if (Lib.prof-rows[Lib.editor-row].value > 0) { Lib.prof-set(Lib.editor-row, Lib.prof-rows[Lib.editor-row].value - 1); } }
else { return false; }
return true;
}
background: Theme.p.bg.with-alpha(0.82);
TouchArea { clicked => { root.close(); } }
panel := Rectangle {
property <length> w: Math.min(root.width - 48px, 980px);
x: (root.width - self.w) / 2; width: self.w; y: Math.max(16px, (root.height - self.height) / 2); height: Math.min(root.height - 32px, 64px * Lib.prof-rows.length + 10px * (Lib.prof-rows.length - 1) + 150px);
border-radius: Theme.r-lg; background: Theme.p.bg2; border-width: Theme.p.border-w; border-color: Theme.p.border;
drop-shadow-blur: 40px; drop-shadow-color: #00000090;
TouchArea { }
Icon { x: 24px; y: 26px; size: 20px; color: Theme.p.accent; commands: Icons.sliders; }
Text { x: 56px; y: 22px; text: "Launch profile · " + root.title; color: Theme.p.text; font-size: Theme.t-lg; font-weight: 800; }
Text { x: 56px; y: 52px; width: parent.width - 200px; text: "Saved to " + Lib.prof-file + " as you change it."; color: Theme.p.dim; font-size: Theme.t-xs; overflow: elide; }
Btn { x: parent.width - self.width - 20px; y: 18px; h: 40px; text: "Done"; clicked => { root.close(); } }
VerticalLayout { x: 20px; y: 88px; width: parent.width - 40px; spacing: 10px; alignment: start;
for r[i] in Lib.prof-rows: Picker { r: r; focused: Lib.editor-row == i; set(v) => { Lib.editor-row = i; Lib.prof-set(i, v); } }
}
Text { x: 20px; y: parent.height - 30px; width: parent.width - 40px; text: "Up / Down: setting · Left / Right: change · Esc: done"; color: Theme.p.faint; font-size: Theme.t-xs; horizontal-alignment: center; }
}
}
export component DetailView inherits Rectangle {
in property <bool> open;
in-out property <int> btn: 0; // 0 play, 1 pin, 2 artwork, 3 settings
in-out property <int> btn: 0; // 0 play, 1 enhance, 2 pin, 3 profile, 4 artwork
callback close();
property <Detail> d: Lib.detail;
property <Game> g: Lib.games[root.d.idx];
@@ -49,14 +104,19 @@ export component DetailView inherits Rectangle {
property <length> profile-h: 56px + 5 * 28px + 62px;
public function key(e: KeyEvent) -> bool {
if (Lib.editor-open) { return editor.key(e); }
if (e.text == Key.Escape || e.text == Key.Backspace) { root.close(); }
else if (e.text == Key.RightArrow) { root.btn = Math.min(3, root.btn + 1); }
else if (e.text == Key.RightArrow) { root.btn = Math.min(4, root.btn + 1); }
else if (e.text == Key.LeftArrow) { root.btn = Math.max(0, root.btn - 1); }
else if (e.text == Key.DownArrow) { body.content-y = Math.max(Math.min(0px, body.height - body.content-height), body.content-y - 96px); }
else if (e.text == Key.UpArrow) { body.content-y = Math.min(0px, body.content-y + 96px); }
else if (e.text == Key.Return || e.text == " ") {
if (root.btn == 0) { if (root.d.can-play) { Lib.play(root.d.idx); } } else if (root.btn == 1) { Lib.toggle-pin(root.d.idx); }
if (root.btn == 0) { if (root.d.can-play) { Lib.play(root.d.idx); } }
else if (root.btn == 1) { if (root.d.can-enhance) { Lib.toggle-enhance(root.d.idx); } }
else if (root.btn == 2) { Lib.toggle-pin(root.d.idx); }
else if (root.btn == 3) { Lib.open-profile(root.d.idx); }
} else if (e.text == "p" || e.text == "P") { Lib.toggle-pin(root.d.idx); }
else if (e.text == "e" || e.text == "E") { if (root.d.can-enhance) { Lib.toggle-enhance(root.d.idx); } }
else { return false; }
return true;
}
@@ -91,14 +151,17 @@ export component DetailView inherits Rectangle {
HorizontalLayout { alignment: start; spacing: 12px; padding-top: 8px;
Btn { h: 56px; primary: true; enabled: root.d.can-play; text: root.d.play-label; icon: root.d.play-label == "INSTALL" ? Icons.download : Icons.play; icon-solid: root.d.play-label != "INSTALL";
focused: root.open && root.btn == 0; clicked => { Lib.play(root.d.idx); } }
Btn { h: 56px; text: root.g.pinned ? "Unpin" : "Pin"; icon: Icons.pin; icon-solid: root.g.pinned; focused: root.open && root.btn == 1; clicked => { Lib.toggle-pin(root.d.idx); } }
Btn { h: 56px; enabled: false; text: root.compact ? "" : "Change artwork"; icon: Icons.picture; badge: "Soon"; focused: root.open && root.btn == 2; }
Btn { h: 56px; enabled: false; text: root.compact ? "" : "Settings"; icon: Icons.sliders; badge: "Soon"; focused: root.open && root.btn == 3; }
Btn { h: 56px; enabled: root.d.can-enhance; text: root.compact ? "" : (root.d.enhance ? "Enhance on" : "Enhance off"); icon: Icons.sparkle; icon-solid: root.d.enhance;
badge: root.d.can-enhance ? "" : "N/A"; focused: root.open && root.btn == 1; clicked => { Lib.toggle-enhance(root.d.idx); } }
Btn { h: 56px; text: root.g.pinned ? "Unpin" : "Pin"; icon: Icons.pin; icon-solid: root.g.pinned; focused: root.open && root.btn == 2; clicked => { Lib.toggle-pin(root.d.idx); } }
Btn { h: 56px; text: root.compact ? "" : "Profile"; icon: Icons.sliders; focused: root.open && root.btn == 3; clicked => { Lib.open-profile(root.d.idx); } }
Btn { h: 56px; enabled: false; text: root.compact || !root.wide ? "" : "Change artwork"; icon: Icons.picture; badge: "Soon"; focused: root.open && root.btn == 4; }
}
Text {
text: root.btn == 2 ? "Changing artwork here is not built yet. For now: summit art " + root.g.id + " cover.png"
: root.btn == 3 ? "Editing the launch profile here is not built yet. For now: summit profile set " + root.g.id + " --monitor … --width … --height … --refresh …"
: root.d.play-note;
text: root.btn == 4 ? "Changing artwork here is not built yet. For now: summit art " + root.g.id + " cover.png"
: root.btn == 3 ? "Monitor, resolution, refresh rate, fullscreen, focus, upscaler, frame generation and target rate for this game."
: root.btn == 1 ? root.d.enhance-note
: root.d.play-note + (root.d.enhance && root.d.can-enhance ? " Enhance is on: " + root.d.framegen + " + " + root.d.upscaler + "." : "");
color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; min-height: 18px;
}
HorizontalLayout { spacing: 16px;
@@ -118,7 +181,7 @@ export component DetailView inherits Rectangle {
Field { label: "Frame generation"; value: root.d.framegen; unset: root.d.framegen == "None"; }
Field { label: "Window"; value: root.d.window; unset: root.d.window == "Default"; }
Rectangle { height: 8px; }
Text { text: root.g.source == "Steam" ? "Steam games start through the Steam client, so this profile is not applied to them yet." : "Monitor and mode are applied when Summit starts the game. Upscaling and frame generation are stored, not applied yet."; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
Text { text: "Monitor and mode are switched when Summit starts the game and put back when it ends" + (root.g.source == "Steam" ? " (Steam games: put back only with Enhance, when the window closes)" : "") + ". Upscaler and frame generation are used when Enhance is on. Focus is stored only."; color: Theme.p.faint; font-size: Theme.t-xs; wrap: word-wrap; }
}
}
Panel {
@@ -136,4 +199,10 @@ export component DetailView inherits Rectangle {
}
}
}
editor := ProfileEditor {
title: root.g.title;
visible: Lib.editor-open; opacity: Lib.editor-open ? 1 : 0;
close => { Lib.editor-open = false; }
}
}
+3 -3
View File
@@ -112,15 +112,15 @@ export component SettingsView inherits Rectangle {
}
Section { x: root.cx; y: 688px; width: root.cw; title: "CLIPS"; icon: Icons.film; }
Row { x: root.cx; y: root.ry(5); width: root.cw; label: "Keep the last"; hint: "Instant replay buffer. Used by the engine (summit enhance)."; focused: root.active && root.srow == 5; hit => { root.srow = 5; }
Row { x: root.cx; y: root.ry(5); width: root.cw; label: "Keep the last"; hint: "Instant replay buffer, passed to the engine as --replay."; focused: root.active && root.srow == 5; hit => { root.srow = 5; }
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.clip-lengths; value <=> Prefs.replay; changed => { root.srow = 5; Prefs.clip = Math.min(Prefs.clip, Prefs.replay); root.save(); } }
}
Row { x: root.cx; y: root.ry(6); width: root.cw; label: "A save writes"; hint: "Never longer than the buffer. No in-game overlay yet."; focused: root.active && root.srow == 6; hit => { root.srow = 6; }
Row { x: root.cx; y: root.ry(6); width: root.cw; label: "A save writes"; hint: "Passed as --clip-length. " + Lib.hotkey-status; focused: root.active && root.srow == 6; hit => { root.srow = 6; }
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 6 * 76px + 8px; options: Prefs.clip-lengths; limit: Prefs.replay; value <=> Prefs.clip; changed => { root.srow = 6; root.save(); } }
}
Section { x: root.cx; y: 904px; width: root.cw; title: "ENHANCE DEFAULTS"; icon: Icons.monitor; }
Row { x: root.cx; y: root.ry(7); width: root.cw; label: "Default upscaler"; hint: "Stored in the \"default\" profile for summit enhance. Not applied to launched games yet."; focused: root.active && root.srow == 7; hit => { root.srow = 7; }
Row { x: root.cx; y: root.ry(7); width: root.cw; label: "Default upscaler"; hint: "Stored in the \"default\" profile for summit enhance. Each game has its own on its page (Profile)."; focused: root.active && root.srow == 7; hit => { root.srow = 7; }
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 100px + 8px; options: ["None", "FSR", "RTX VSR"]; value <=> Prefs.upscaler; changed => { root.srow = 7; root.save(); } }
}
Row { x: root.cx; y: root.ry(8); width: root.cw; label: "Default frame generation"; hint: "RIFE needs an NVIDIA GPU and the engine's Python environment."; focused: root.active && root.srow == 8; hit => { root.srow = 8; }
+15
View File
@@ -37,8 +37,14 @@ export struct Detail {
play-label: string,
play-note: string,
can-play: bool,
enhance: bool, // Play also runs the engine (frame generation + upscaler) on the game's window
can-enhance: bool,
enhance-note: string,
}
// One row of the profile editor: a value picked from options.
export struct PRow { label: string, hint: string, options: [string], value: int }
// Preferences edited on the settings page (layout, theme and motion live in Theme). Rust saves them to ui.toml.
export global Prefs {
in-out property <int> scale: 2; // index into scales
@@ -75,6 +81,15 @@ export global Lib {
callback toggle-pin(int);
callback settings-changed();
callback toggle-fullscreen();
// profile editor
in property <[PRow]> prof-rows;
in property <string> prof-file;
in-out property <bool> editor-open;
in-out property <int> editor-row;
callback open-profile(int);
callback prof-set(int, int); // row, option index
callback toggle-enhance(int);
in property <string> hotkey-status; // the global save-clip key, for the settings page
}
// 24x24 line icons, drawn as paths so they follow the theme and scale cleanly.
+97
View File
@@ -0,0 +1,97 @@
# play-integration
Goal: make the launcher usable end to end. Play starts games through `summit run`, with an Enhance toggle,
a per-game profile editor, clip settings, a global save-clip key on Linux, and verification on the GPU VM.
## What changed
**summit-core**
- `display`: `Output`/`Mode`, parsers for `xrandr --query`, `kscreen-doctor -j` and `wlr-randr --json`,
`outputs()` (runs the session's tool), `restore_profile()` (the mode in use now, to put back afterwards) and
`plan_for()` (on X11, asks for a custom mode such as `1920x1080_120.00` by its name; xrandr matches
`--mode` by name).
- `launch::plan(entry, cli, enhance)`: Steam and Lutris now also go through `summit run` (with `--detached`).
Steam with Enhance adds `--enhance --window class:steam_app_<id> --wait 120`. Custom entries:
`summit run <id> [--enhance] -- <path>`. Without the summit binary, Steam/Lutris fall back to the bare
client command (and Enhance is unavailable).
- `engine::supervise(.., detached)`: when the launcher command returns at once (`steam steam://…`), it waits
for the engine alone, which ends when the game's window closes.
- `profile.enhance` (serde default, so old files load with it off). `hotkey::status()` gives the settings
page one line saying whether a global key exists in this session (X11, or the portal on Wayland via `gdbus introspect`).
**summit (CLI)**
- `summit run`: prints each display step it runs, reads the current mode first and puts it back when the
game ends (or, detached + enhance, when the engine ends). `--detached`. Steam ids and detached runs are not
tracked (their own launcher keeps playtime).
- `summit profile set --enhance true|false`. `summit doctor` lists the outputs.
**summit-gui**
- The game page has Play, an **Enhance on/off** toggle (key E), Pin, **Profile**, and Change artwork (still Soon).
Enhance is disabled, with the reason shown, for Lutris, Heroic, disk finds, games that aren't installed, and
non-X11 sessions.
- Profile editor overlay: Monitor (real outputs), Resolution and Refresh (that output's real modes and rates),
Fullscreen, Focus, Upscaler, Frame generation, Target rate. Every change is saved through `profile::save`.
Rows are built by pure functions in `data.rs` (`edit_rows`, `edit_apply`), which are unit tested.
- Play's output goes to `~/.cache/summit/last-run.log`.
- Settings → Clips shows the global-key status. Layout, theme, size and animation were already persisted to
`ui.toml` (no change needed). Clip lengths were already passed as `--replay/--clip-length`.
**engine**
- `framegen/globalkeys.py`:
- X11: `XGrabKey` on the root window via ctypes libX11, with NumLock/CapsLock variants and auto-repeat
debounce. A key another client holds is reported as taken (BadAccess caught).
- Wayland: xdg-desktop-portal GlobalShortcuts via the optional `jeepney` package.
- Otherwise it reports itself unavailable.
- `replay.Recorder` uses it on Linux for Ctrl+Alt+R / Ctrl+Alt+B; Windows keeps `RegisterHotKey`.
## Verified, and how
- `cargo test --workspace`: 89 tests pass (new: output parsers incl. a custom xrandr mode, restore plan,
launch plans with enhance/detached, detached supervise, profile compat, editor rows).
- `engine/tests/test_globalkeys.py` (5 tests) passes locally under Xvfb. Ctrl+Alt+R/B were injected with XTest:
they fired, a bare `r` did not, and a second grab was reported as taken. It also passes on the VM's real KDE X11
desktop, but only with the screen unlocked (see "Not done").
- On the GPU VM (KDE neon X11, RTX 3090, software OpenGL), release build in `/home/user/summit-play`, engine
copy in `/home/user/engine-play`:
- **Display plan really runs**: profile set to `Virtual-1` 1280x800 @ 74.99. `summit run custom:voidrunner`
logged `display: ran xrandr --output Virtual-1 --mode 1280x800 --rate 74.99`. xrandr showed
`1280x800 74.99*` during the run and the game reported a 1280x800 display. After the game was killed:
`display: ran xrandr --output Virtual-1 --mode 1920x1080_120.00 --rate 119.93`, and xrandr was back to
`1920x1080_120.00 119.93*`.
- **Plain Play from the GUI**: started `summit run custom:voidrunner -- …/top_down_shooter`.
- **Clip settings page**: arrow keys in the real window set 3 min / 3 min, and `ui.toml` then held
`replay_seconds = 180`, `clip_seconds = 180`.
- **GUI path with Enhance** (`gui-*.png` in docs/media/live):
1. Enhance toggled on (profile got `enhance = true`).
2. The editor opened and listed `Virtual-1`'s modes.
3. Play ran `summit run custom:voidrunner --enhance -- …`. The engine got
`--source window --window pid:<game> --scaler fsr --display --hz 60 --fullscreen --window-wait 60 --replay 180 --clip-length 180 --no-graph`
(the last flag from `SUMMIT_ENGINE_ARGS`, because the GPU is short of memory).
4. The engine printed `[keys] global keys (x11): ctrl+alt+r, ctrl+alt+b`. Ctrl+Alt+R (XTest, game focused)
gave `[replay] saved 30.3 s -> /home/user/Videos/SmoovPlay/SmoovPlay 2026-11-24 08-38-36.mp4`.
ffprobe: 30.29 s, 1280x720.
5. Killing the game printed "the game exited; the engine was stopped" and the session was tracked.
- VM state was put back afterwards: Voidrunner profile restored from backup, temporary `data/settings.cfg`
(720p window) deleted, `~/.config/summit/ui.toml` removed (it did not exist before), no processes left.
The saved test clip is still in `~/Videos/SmoovPlay/`.
## NOT done / not verified
- **Steam path untested**: no Steam on either machine. It's also unknown whether native (non-Proton) Steam games
have a `steam_app_<id>` window class; if they don't, Enhance waits 120 s and gives up.
- **Lutris** via `summit run --detached`: untested. Enhance is not offered for Lutris.
- **Wayland, all of it**:
- `kscreen-doctor` / `wlr-randr` output parsing is tested only against sample JSON.
- The GlobalShortcuts portal backend has never run.
- Live window capture is still X11-only, so Enhance is disabled on Wayland.
- **Focus** is stored only (nothing raises the game window).
- **Fullscreen** affects only the engine's output, not the game's own window mode.
- **Display restore gaps**: a detached launch without Enhance (Steam) does not restore the mode, because
Summit can't see when the game ends. If `summit run` itself is killed, nothing is restored either.
- **Lock screen**: the global X11 key does not fire while the KDE lock screen holds the keyboard. That is expected
X behaviour, but it confused the first VM test.
- **Engine toast quirk** (inherited from SmoovPlay, not touched): the toast shows the clip path with Windows
backslashes (`Videos\SmoovPlay\…`). The file itself is fine.
- 90/120 Hz output and RTX VSR are still untested, as the UI labels say.
- **Build machine disk**: the root volume was 100% full during this task (only root-reserved blocks left), from
things outside this worktree. I only deleted this worktree's own `target/debug/incremental`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 351 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

+306
View File
@@ -0,0 +1,306 @@
"""System-wide keys on Linux: the save-a-clip key works while the game, not the engine, has the keyboard.
X11 XGrabKey on the root window, through libX11 with ctypes (no extra package). A key another program
already grabbed is reported as taken.
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.
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().
"""
from __future__ import annotations
import ctypes
import ctypes.util
import os
import select
import threading
import time
from ctypes import POINTER, Structure, Union, byref, c_char_p, c_int, c_long, c_uint, c_ulong, c_void_p
# X11 modifier masks
SHIFT, LOCK, CONTROL, MOD1, MOD2, MOD4 = 1, 2, 4, 8, 16, 64
MODS = {"shift": SHIFT, "ctrl": CONTROL, "control": CONTROL, "alt": MOD1, "super": MOD4, "win": MOD4}
# NumLock (usually Mod2) and CapsLock change the modifier state: a grab is made for each combination of them
IGNORED = (0, LOCK, MOD2, LOCK | MOD2)
KEYPRESS = 2
REPEAT_S = 0.4 # holding the keys down repeats KeyPress: one save per press
def parse(combo: str) -> tuple[int, str]:
""""ctrl+alt+r" -> (X11 modifier mask, key name for XStringToKeysym). ValueError if it has no key or no
modifier (a key on its own would be taken from the game)."""
parts = [p.strip().lower() for p in combo.split("+") if p.strip()]
mods, key = 0, None
for p in parts:
if p in MODS:
mods |= MODS[p]
elif key is None:
key = p
else:
raise ValueError(f"{combo!r}: more than one key")
if key is None:
raise ValueError(f"{combo!r}: no key")
if not mods & (CONTROL | MOD1 | MOD4):
raise ValueError(f"{combo!r}: needs Ctrl, Alt or Super")
return mods, key
def portal_trigger(combo: str) -> str:
""""ctrl+alt+r" -> "CTRL+ALT+r", the shortcuts spec's form for the portal's preferred_trigger."""
mods, key = parse(combo)
names = [n for n, m in (("CTRL", CONTROL), ("ALT", MOD1), ("SHIFT", SHIFT), ("LOGO", MOD4)) if mods & m]
return "+".join(names + [key])
def backend(env=os.environ) -> tuple[str, str]:
"""Which way to get global keys in this session: ("x11" | "portal" | "none", why)."""
kind = env.get("XDG_SESSION_TYPE", "").lower()
if kind == "wayland" or (not kind and env.get("WAYLAND_DISPLAY")):
return "portal", "Wayland session: xdg-desktop-portal GlobalShortcuts"
if env.get("DISPLAY"):
return "x11", f"X11 session (DISPLAY={env['DISPLAY']}): XGrabKey"
return "none", "no X11 or Wayland session"
class _XKeyEvent(Structure):
_fields_ = [("type", c_int), ("serial", c_ulong), ("send_event", c_int), ("display", c_void_p),
("window", c_ulong), ("root", c_ulong), ("subwindow", c_ulong), ("time", c_ulong),
("x", c_int), ("y", c_int), ("x_root", c_int), ("y_root", c_int), ("state", c_uint),
("keycode", c_uint), ("same_screen", c_int)]
class _XEvent(Union):
_fields_ = [("type", c_int), ("xkey", _XKeyEvent), ("pad", c_long * 24)]
class _XErrorEvent(Structure):
_fields_ = [("type", c_int), ("display", c_void_p), ("resourceid", c_ulong), ("serial", c_ulong),
("error_code", ctypes.c_ubyte), ("request_code", ctypes.c_ubyte), ("minor_code", ctypes.c_ubyte)]
_x_errors: list[int] = []
_ERR_FN = ctypes.CFUNCTYPE(c_int, c_void_p, POINTER(_XErrorEvent))
_ERROR_HANDLER = _ERR_FN(lambda _d, e: (_x_errors.append(e.contents.error_code), 0)[1]) # kept alive: Xlib holds it
BAD_ACCESS = 10
class X11Keys:
"""XGrabKey on the root window of its own X connection, read on a thread of its own."""
def __init__(self, keys: dict, display: str | None = None) -> None:
self.keys, self.name = keys, display or os.environ.get("DISPLAY", ":0")
self.got: list[str] = [] # combos grabbed
self.taken: list[str] = [] # combos another program has
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._ready = threading.Event()
self.error: str | None = None
def start(self) -> None:
self._thread = threading.Thread(target=self._run, name="globalkeys-x11", daemon=True)
self._thread.start()
self._ready.wait(5)
def _run(self) -> None:
try:
x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
except OSError as e:
self.error = f"libX11 not found ({e})"
self._ready.set()
return
x.XOpenDisplay.restype, x.XOpenDisplay.argtypes = c_void_p, [c_char_p]
x.XDefaultRootWindow.restype, x.XDefaultRootWindow.argtypes = c_ulong, [c_void_p]
x.XStringToKeysym.restype, x.XStringToKeysym.argtypes = c_ulong, [c_char_p]
x.XKeysymToKeycode.restype, x.XKeysymToKeycode.argtypes = ctypes.c_ubyte, [c_void_p, c_ulong]
x.XGrabKey.argtypes = [c_void_p, c_int, c_uint, c_ulong, c_int, c_int, c_int]
x.XUngrabKey.argtypes = [c_void_p, c_int, c_uint, c_ulong]
x.XSync.argtypes = [c_void_p, c_int]
x.XPending.argtypes = [c_void_p]
x.XNextEvent.argtypes = [c_void_p, POINTER(_XEvent)]
x.XConnectionNumber.argtypes = [c_void_p]
x.XCloseDisplay.argtypes = [c_void_p]
x.XSetErrorHandler.restype, x.XSetErrorHandler.argtypes = c_void_p, [c_void_p]
d = x.XOpenDisplay(self.name.encode())
if not d:
self.error = f"can't open the X display {self.name}"
self._ready.set()
return
root = x.XDefaultRootWindow(d)
fns: dict[tuple[int, int], tuple[str, object]] = {}
try:
for combo, fn in self.keys.items():
mods, key = parse(combo)
sym = x.XStringToKeysym(key.encode())
code = x.XKeysymToKeycode(d, sym) if sym else 0
if not code:
print(f"[keys] {combo}: no key {key!r} on this keyboard")
continue
x.XSetErrorHandler(_ERROR_HANDLER)
_x_errors.clear()
for extra in IGNORED:
x.XGrabKey(d, code, mods | extra, root, 1, 1, 1) # owner_events, GrabModeAsync x2
x.XSync(d, 0)
if BAD_ACCESS in _x_errors:
for extra in IGNORED:
x.XUngrabKey(d, code, mods | extra, root)
self.taken.append(combo)
print(f"[keys] {combo} is taken by another program; use the engine window's own key")
continue
fns[(code, mods)] = (combo, fn)
self.got.append(combo)
except ValueError as e:
print(f"[keys] {e}")
self._ready.set()
fd = x.XConnectionNumber(d)
ev, last = _XEvent(), {}
try:
while not self._stop.is_set():
if not x.XPending(d):
select.select([fd], [], [], 0.25)
continue
x.XNextEvent(d, byref(ev))
if ev.type != KEYPRESS:
continue
k = (ev.xkey.keycode, ev.xkey.state & (SHIFT | CONTROL | MOD1 | MOD4))
hit = fns.get(k)
if hit is None:
continue
now = time.monotonic()
if now - last.get(k, 0) < REPEAT_S:
last[k] = now
continue
last[k] = now
combo, fn = hit
try:
fn()
except Exception as e: # noqa: BLE001 - a failing save must not end the key thread
print(f"[keys] {combo}: {e}")
finally:
for code, mods in fns:
for extra in IGNORED:
x.XUngrabKey(d, code, mods | extra, root)
x.XSync(d, 0)
x.XCloseDisplay(d)
def stop(self) -> None:
self._stop.set()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=2)
class PortalKeys:
"""xdg-desktop-portal GlobalShortcuts over D-Bus with jeepney. Untested (see the module's note)."""
IFACE = "org.freedesktop.portal.GlobalShortcuts"
def __init__(self, keys: dict) -> None:
self.keys = keys
self.got: list[str] = []
self.taken: list[str] = []
self.error: str | None = None
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._ready = threading.Event()
def start(self) -> None:
self._thread = threading.Thread(target=self._run, name="globalkeys-portal", daemon=True)
self._thread.start()
self._ready.wait(60) # the desktop may show a dialog to confirm the keys
def _run(self) -> None:
try:
from jeepney import DBusAddress, MatchRule, message_bus, new_method_call
from jeepney.io.blocking import Proxy, open_dbus_connection
except ImportError:
self.error = "the jeepney package is not installed (pip install jeepney)"
self._ready.set()
return
try:
conn = open_dbus_connection(bus="SESSION")
except Exception as e: # noqa: BLE001
self.error = f"no session D-Bus ({e})"
self._ready.set()
return
portal = DBusAddress("/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop",
interface=self.IFACE)
bus = Proxy(message_bus, conn)
sender = conn.unique_name[1:].replace(".", "_")
def request(method: str, sig: str, args: tuple, token: str):
path = f"/org/freedesktop/portal/desktop/request/{sender}/{token}"
rule = MatchRule(type="signal", interface="org.freedesktop.portal.Request", member="Response", path=path)
bus.AddMatch(rule)
with conn.filter(rule) as q:
reply = conn.send_and_get_reply(new_method_call(portal, method, sig, args), timeout=10)
if reply.header.message_type.name == "error":
raise RuntimeError(f"{method}: {reply.body}")
code, results = conn.recv_until_filtered(q, timeout=60).body
if code != 0:
raise RuntimeError(f"{method} was refused or cancelled (code {code})")
return results
try:
tok = f"summit{os.getpid()}"
res = request("CreateSession", "a{sv}", ({"handle_token": ("s", tok + "a"), "session_handle_token": ("s", tok)},), tok + "a")
session = res["session_handle"][1]
ids = {f"key{i}": (combo, fn) for i, (combo, fn) in enumerate(self.keys.items())}
shortcuts = [(sid, {"description": ("s", "Summit: save a clip" if i == 0 else f"Summit: {combo}"),
"preferred_trigger": ("s", portal_trigger(combo))})
for i, (sid, (combo, _fn)) in enumerate(ids.items())]
res = request("BindShortcuts", "oa(sa{sv})sa{sv}", (session, shortcuts, "", {"handle_token": ("s", tok + "b")}), tok + "b")
bound = {sid for sid, _ in res.get("shortcuts", ("", []))[1]}
self.got = [ids[s][0] for s in ids if s in bound]
self.taken = [ids[s][0] for s in ids if s not in bound]
except Exception as e: # noqa: BLE001
self.error = f"GlobalShortcuts portal: {e}"
self._ready.set()
return
self._ready.set()
rule = MatchRule(type="signal", interface=self.IFACE, member="Activated")
bus.AddMatch(rule)
with conn.filter(rule) as q:
while not self._stop.is_set():
try:
msg = conn.recv_until_filtered(q, timeout=0.5)
except TimeoutError:
continue
_sess, sid, *_ = msg.body
if sid in ids:
try:
ids[sid][1]()
except Exception as e: # noqa: BLE001
print(f"[keys] {ids[sid][0]}: {e}")
conn.close()
def stop(self) -> None:
self._stop.set()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=2)
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.kind, self.why = backend(env)
self.impl = X11Keys(keys) if self.kind == "x11" else PortalKeys(keys) if self.kind == "portal" else None
self.status = ""
def start(self) -> None:
if self.impl is None:
self.status = f"global keys unavailable: {self.why}"
else:
self.impl.start()
if self.impl.error:
self.status = f"global keys unavailable ({self.why}): {self.impl.error}"
else:
got = ", ".join(self.impl.got) or "none"
self.status = f"global keys ({self.kind}): {got}" + (f"; taken: {', '.join(self.impl.taken)}" if self.impl.taken else "")
print(f"[keys] {self.status}")
def stop(self) -> None:
if self.impl is not None:
self.impl.stop()
+6 -1
View File
@@ -443,7 +443,12 @@ class Recorder:
print(f"[replay] keeping the last {_dur(self.length)}")
if self._hotkeys_wanted:
if self.length and self._hotkeys is None:
self._hotkeys = Hotkeys({"ctrl+alt+r": lambda: self.save(), "ctrl+alt+b": lambda: self.save("compare")})
keys = {"ctrl+alt+r": lambda: self.save(), "ctrl+alt+b": lambda: self.save("compare")}
if sys.platform.startswith("linux"):
from .globalkeys import GlobalKeys # X11 key grab, or the Wayland portal
self._hotkeys = GlobalKeys(keys)
else:
self._hotkeys = Hotkeys(keys)
self._hotkeys.start()
elif not self.length and self._hotkeys is not None:
self._hotkeys.stop()
+1
View File
@@ -9,4 +9,5 @@ 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)
pytest
+105
View File
@@ -0,0 +1,105 @@
"""Linux global keys (framegen/globalkeys.py): parsing, picking X11 / portal / none, and a real XGrabKey on an X
server (Xvfb here, or the desktop's) with key presses sent through XTest. That test is skipped without one."""
import ctypes
import ctypes.util
import os
import pathlib
import shutil
import subprocess
import sys
import time
import pytest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from framegen import globalkeys as gk
def test_parse_and_portal_trigger():
assert gk.parse("ctrl+alt+r") == (gk.CONTROL | gk.MOD1, "r")
assert gk.parse(" Ctrl + Shift + F9 ") == (gk.CONTROL | gk.SHIFT, "f9")
assert gk.portal_trigger("ctrl+alt+r") == "CTRL+ALT+r"
for bad in ("r", "shift+r", "ctrl+alt", "ctrl+r+t"):
with pytest.raises(ValueError):
gk.parse(bad)
def test_backend_follows_the_session():
assert gk.backend({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"})[0] == "x11"
assert gk.backend({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"})[0] == "portal"
assert gk.backend({"WAYLAND_DISPLAY": "wayland-0"})[0] == "portal"
assert gk.backend({"DISPLAY": ":1"})[0] == "x11"
assert gk.backend({})[0] == "none"
def test_no_session_is_reported_not_hidden(capsys):
k = gk.GlobalKeys({"ctrl+alt+r": lambda: None}, env={})
k.start()
k.stop()
assert k.status == "global keys unavailable: no X11 or Wayland session"
assert "unavailable" in capsys.readouterr().out
def test_portal_without_jeepney_says_so(monkeypatch):
monkeypatch.setitem(sys.modules, "jeepney", None) # import fails
k = gk.GlobalKeys({"ctrl+alt+r": lambda: None}, env={"XDG_SESSION_TYPE": "wayland"})
k.start()
assert "jeepney" in k.status and "unavailable" in k.status
@pytest.fixture
def xserver():
if os.environ.get("DISPLAY"):
yield os.environ["DISPLAY"]
return
if not shutil.which("Xvfb"):
pytest.skip("no X server and no Xvfb")
disp = ":97"
p = subprocess.Popen(["Xvfb", disp, "-screen", "0", "640x480x24"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(1.0)
yield disp
p.terminate()
p.wait(5)
def _press(disp, keys):
"""XTest: press and release `keys` (keysym names) like a keyboard would."""
tst = ctypes.util.find_library("Xtst")
if not tst:
pytest.skip("no libXtst")
x, t = ctypes.CDLL(ctypes.util.find_library("X11")), ctypes.CDLL(tst)
x.XOpenDisplay.restype = ctypes.c_void_p
x.XOpenDisplay.argtypes = [ctypes.c_char_p]
x.XStringToKeysym.restype, x.XStringToKeysym.argtypes = ctypes.c_ulong, [ctypes.c_char_p]
x.XKeysymToKeycode.restype, x.XKeysymToKeycode.argtypes = ctypes.c_ubyte, [ctypes.c_void_p, ctypes.c_ulong]
x.XFlush.argtypes = x.XCloseDisplay.argtypes = [ctypes.c_void_p]
t.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong]
d = x.XOpenDisplay(disp.encode())
codes = [x.XKeysymToKeycode(d, x.XStringToKeysym(k.encode())) for k in keys]
for c in codes:
t.XTestFakeKeyEvent(d, c, 1, 0)
for c in reversed(codes):
t.XTestFakeKeyEvent(d, c, 0, 0)
x.XFlush(d)
x.XCloseDisplay(d)
def test_x11_grab_fires_on_the_key_only(xserver):
hits = []
k = gk.X11Keys({"ctrl+alt+r": lambda: hits.append("r"), "ctrl+alt+b": lambda: hits.append("b")}, display=xserver)
k.start()
try:
assert k.error is None and k.got == ["ctrl+alt+r", "ctrl+alt+b"], (k.error, k.got, k.taken)
_press(xserver, ["Control_L", "Alt_L", "r"])
time.sleep(0.6)
_press(xserver, ["r"]) # without the modifiers: not ours
_press(xserver, ["Control_L", "Alt_L", "b"])
time.sleep(0.6)
assert hits == ["r", "b"]
# a second grab of the same key is refused by the X server and reported as taken
other = gk.X11Keys({"ctrl+alt+r": lambda: None}, display=xserver)
other.start()
assert other.taken == ["ctrl+alt+r"] and other.got == []
other.stop()
finally:
k.stop()