Merge ap/audit
This commit is contained in:
commit
8a1b622505
14 files changed
+406
-70
No files matched your search
@@ -70,7 +70,7 @@
|
||||
| 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). **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). |
|
||||
| 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 (also when the game was started by a launch script: what the script started is stopped too, checked on the VM). **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. |
|
||||
@@ -81,8 +81,8 @@
|
||||
| PS5 Remote Play (needs chiaki-ng with SmoovPlay's frame tap) and capture cards | Wired as `ps5` / `capture:<name>` sources, **not tested** without the hardware. |
|
||||
| lsfg-vk frame generation for any game | Planned |
|
||||
| DLSS | Planned. Depends on what each game and driver really supports. |
|
||||
| One-line installer (`install.sh`) | Working on Debian/Ubuntu/neon/Mint, Arch/CachyOS/Manjaro and Fedora (tested with `--dry-run` against real and container `/etc/os-release` fixtures for each, and a real build + install on this machine). openSUSE path runs without error in a container but hasn't built there. No release packages are published yet, so it always builds from source with cargo. |
|
||||
| `.deb` (`packaging/deb/build.sh`) | Working: builds and installs on this machine (Debian trixie host). Not tested on a target Debian/Ubuntu install, no postinst/prerm. |
|
||||
| One-line installer (`install.sh`) | **Only dry-run tested**: `--dry-run` picks the right commands on Debian/Ubuntu/neon/Mint, Arch/CachyOS/Manjaro, Fedora and openSUSE (this machine and containers). It has **not been run for real end to end** on any distro. Until the audit it would also have failed for a non-root user at the engine venv step (fixed, that fix is only dry-run tested too). No release packages are published yet, so it always builds from source with cargo. |
|
||||
| `.deb` (`packaging/deb/build.sh`) | Builds on this machine (Debian trixie host), and the contents were checked with `dpkg-deb`. **Not installed anywhere yet**, no postinst/prerm. |
|
||||
| AUR (`packaging/arch/PKGBUILD`) | Untested. Needs a pushed git tag to build against; not run through `makepkg` here. |
|
||||
| AppImage (`packaging/appimage/build.sh`) | Untested. Needs `linuxdeploy` and `appimagetool`, neither available in this environment. |
|
||||
| Flatpak | Planned |
|
||||
@@ -137,7 +137,7 @@ summit enhance capture:0 --profile my-console # capture card, live window (unt
|
||||
summit enhance window:Voidrunner # a running game's window, live (X11)
|
||||
```
|
||||
|
||||
The engine needs an NVIDIA GPU and its own Python environment (`engine/`, torch with CUDA). The installer for that is not built yet.
|
||||
The engine needs an NVIDIA GPU and its own Python environment (`engine/`, torch with CUDA). `install.sh` sets that up with `uv`; that step has only been dry-run tested.
|
||||
|
||||
### Live enhance: play a game with frame generation on top
|
||||
|
||||
@@ -167,7 +167,7 @@ What was measured, and what was not (test VM: RTX 3090 shared with another job,
|
||||
- Fullscreen with FSR to 1080p: only about 33 output frames a second, because software OpenGL takes 15 ms to draw each one. **On that VM fullscreen is slower than the game itself.** With a real GPU-driven display this step is expected to take well under a millisecond, but that has not been measured.
|
||||
- Not tested: a real 30 fps game (Voidrunner ran at about 50), 90/120 Hz output, two monitors and `--monitor`, a compositor with direct scanout, games started through Steam or Proton, exclusive-fullscreen games, mouse-driven games in fullscreen mode (clicks go through to whatever is under the pointer, and the picture is scaled, so the pointer does not line up).
|
||||
|
||||
Limits: X11 sessions only (on Wayland it stops with a message). Needs the `ffmpeg` program. The grab polls, so it does not know when the game draws: a 60 fps game can show an occasional repeated or skipped frame. While the picture sits over a game the engine has no keys of its own (they all go to the game): close the game to stop. Killing `summit` itself with a signal does not stop the two it started. `SUMMIT_ENGINE_ARGS` passes extra flags to the engine, e.g. `SUMMIT_ENGINE_ARGS=--no-graph` on a GPU short of memory.
|
||||
Limits: X11 sessions only (on Wayland it stops with a message). Needs the `ffmpeg` program. The grab polls, so it does not know when the game draws: a 60 fps game can show an occasional repeated or skipped frame. While the picture sits over a game the engine has no keys of its own (they all go to the game): close the game to stop. Killing `summit` itself with a signal does not stop the two it started, and does not put the monitor's mode back. `SUMMIT_ENGINE_ARGS` passes extra flags to the engine, e.g. `SUMMIT_ENGINE_ARGS=--no-graph` on a GPU short of memory.
|
||||
|
||||
## Clips
|
||||
|
||||
|
||||
@@ -105,6 +105,11 @@ enum ProfileCmd {
|
||||
},
|
||||
}
|
||||
|
||||
/// Runs its closure when dropped. `summit run` puts the display mode back with it, so an error on the way (the game
|
||||
/// or the engine cannot be started, waiting on them fails) does not leave the monitor in the game's mode.
|
||||
struct OnDrop<F: FnMut()>(F);
|
||||
impl<F: FnMut()> Drop for OnDrop<F> { fn drop(&mut self) { (self.0)() } }
|
||||
|
||||
fn hours(m: u64) -> String { format!("{:.1} h", m as f64 / 60.0) }
|
||||
|
||||
/// Picks the Steam `userdata/<id>` folder to write shortcuts into.
|
||||
@@ -158,13 +163,14 @@ fn main() -> Result<()> {
|
||||
let id = format!("custom:{}", title.to_lowercase().replace(' ', "-"));
|
||||
let mut st = state::load();
|
||||
st.custom.retain(|c| c.id != id);
|
||||
st.custom.push(state::Custom { id: id.clone(), title, path: path.canonicalize()?.to_string_lossy().into_owned(), software });
|
||||
st.custom.push(state::Custom { id: id.clone(), title, path: state::path_text(&path.canonicalize()?)?, software });
|
||||
state::save(&st)?; println!("added {id}");
|
||||
}
|
||||
Cmd::Enhance { profile, source, no_watermark, out, max_ticks, dry_run } => {
|
||||
let eng = engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: set SUMMIT_ENGINE to the engine/ folder"))?;
|
||||
let src = engine::parse_source(&source).map_err(|e| anyhow::anyhow!(e))?;
|
||||
anyhow::ensure!(out.is_none() || matches!(src, engine::Source::File(_)), "--out needs a video file as the source");
|
||||
if let Some(o) = &out { state::path_text(o)?; }
|
||||
let p = profile::load(&profile)?;
|
||||
let mut args = engine::plan(&eng, &src, &p, out.is_none(), out.as_deref(), max_ticks);
|
||||
// Instant replay only exists while playing on screen. Lengths come from the launcher's settings page;
|
||||
@@ -187,7 +193,7 @@ fn main() -> Result<()> {
|
||||
Cmd::Art { id, image } => {
|
||||
anyhow::ensure!(image.is_file(), "{} is not a file", image.display());
|
||||
let mut st = state::load();
|
||||
st.artwork.insert(id.clone(), image.canonicalize()?.to_string_lossy().into_owned());
|
||||
st.artwork.insert(id.clone(), state::path_text(&image.canonicalize()?)?);
|
||||
state::save(&st)?; println!("artwork set for {id}");
|
||||
}
|
||||
Cmd::Doctor { id } => {
|
||||
@@ -230,13 +236,14 @@ fn main() -> Result<()> {
|
||||
match r { Ok(()) => println!("display: ran {}", c.join(" ")), Err(e) => eprintln!("display step failed ({}): {e}", c.join(" ")) }
|
||||
};
|
||||
run_display(&plan);
|
||||
let restore_guard = OnDrop(|| if let Some(r) = &restore { run_display(r); });
|
||||
let start = std::time::Instant::now();
|
||||
let mut child = std::process::Command::new(&cmd[0]);
|
||||
child.args(&cmd[1..]).args(&p.launch_args).envs(display::launch_env(s, &p));
|
||||
// A game given by its full path is started from its own folder: many look for their data there.
|
||||
if let Some(dir) = std::path::Path::new(&cmd[0]).parent().filter(|d| d.is_absolute() && d.is_dir()) { child.current_dir(dir); }
|
||||
let status = if let Some(eng) = eng {
|
||||
let mut game = child.spawn()?;
|
||||
let mut game = child.spawn().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))?;
|
||||
let live = engine::Live { wait_secs: wait, watermark: if no_watermark { Some(false) } else { None } };
|
||||
let mut args = engine::run_enhance_plan(&eng, game.id(), window.as_deref(), &p, &live);
|
||||
if summit_core::ui::path().map_or(false, |p| p.exists()) {
|
||||
@@ -258,8 +265,8 @@ fn main() -> Result<()> {
|
||||
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); }
|
||||
} else { child.status().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))? };
|
||||
drop(restore_guard);
|
||||
let secs = start.elapsed().as_secs();
|
||||
if detached && !enhance {
|
||||
println!("{id}: handed over ({status}); its own launcher keeps the playtime");
|
||||
@@ -334,3 +341,20 @@ fn main() -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn on_drop_runs_on_early_return_too() {
|
||||
use std::cell::Cell;
|
||||
let ran = Cell::new(0);
|
||||
let f = |fail: bool| -> anyhow::Result<()> {
|
||||
let _g = super::OnDrop(|| ran.set(ran.get() + 1));
|
||||
anyhow::ensure!(!fail, "spawn failed");
|
||||
Ok(())
|
||||
};
|
||||
assert!(f(true).is_err());
|
||||
assert!(f(false).is_ok());
|
||||
assert_eq!(ran.get(), 2);
|
||||
}
|
||||
}
|
||||
@@ -62,26 +62,36 @@ pub fn scaler_arg(upscaler: &str) -> Option<&'static str> {
|
||||
/// `display` = true shows the output window; false needs `out` (render to a file).
|
||||
pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option<&Path>, max_ticks: Option<u32>) -> Vec<String> {
|
||||
let mut a: Vec<String> = vec![engine.join("run.py").to_string_lossy().into_owned()];
|
||||
// Values that come from the user (file names, window titles, profile fields) go as `--opt=value`, so one that
|
||||
// starts with '-' is never read by the engine's argparse as another option.
|
||||
let opt = |k: &str, v: &str| format!("--{k}={v}");
|
||||
match src {
|
||||
Source::File(f) => a.push(f.to_string_lossy().into_owned()),
|
||||
Source::File(f) => a.push(file_arg(f)),
|
||||
Source::Ps5 => a.push("--chiaki".into()),
|
||||
Source::Capture(n) => { a.push("--capture".into()); a.push(n.clone()); }
|
||||
Source::Window(n) => { a.extend(["--source".into(), "window".into(), "--window".into(), n.clone()]); }
|
||||
Source::Capture(n) => a.push(opt("capture", n)),
|
||||
Source::Window(n) => { a.extend(["--source".into(), "window".into(), opt("window", n)]); }
|
||||
}
|
||||
if p.framegen == "none" { a.push("--off".into()); }
|
||||
if let Some(m) = &p.model { a.push("--model".into()); a.push(m.clone()); }
|
||||
if let Some(m) = &p.model { a.push(opt("model", m)); }
|
||||
if let Some(s) = scaler_arg(&p.upscaler) { a.push("--scaler".into()); a.push(s.into()); }
|
||||
if display {
|
||||
a.push("--display".into());
|
||||
let hz = p.target_hz.unwrap_or(60);
|
||||
if [60, 90, 120].contains(&hz) { a.push("--hz".into()); a.push(hz.to_string()); }
|
||||
if p.fullscreen { a.push("--fullscreen".into()); }
|
||||
if let Some(m) = &p.monitor { a.push("--monitor".into()); a.push(m.clone()); }
|
||||
} else if let Some(o) = out { a.push("--out".into()); a.push(o.to_string_lossy().into_owned()); }
|
||||
if let Some(m) = &p.monitor { a.push(opt("monitor", m)); }
|
||||
} else if let Some(o) = out { a.push(opt("out", &o.to_string_lossy())); }
|
||||
if let Some(t) = max_ticks { a.push("--max-ticks".into()); a.push(t.to_string()); }
|
||||
a
|
||||
}
|
||||
|
||||
/// The input file as the engine's positional argument: a relative name starting with '-' gets a "./" so argparse
|
||||
/// takes it as a file, not an option.
|
||||
fn file_arg(f: &Path) -> String {
|
||||
let s = f.to_string_lossy().into_owned();
|
||||
if s.starts_with('-') { format!("./{s}") } else { s }
|
||||
}
|
||||
|
||||
/// Options for enhancing a live game window (`summit run <id> --enhance`, `summit enhance window:...`).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Live {
|
||||
@@ -146,15 +156,69 @@ pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Chil
|
||||
Ok((first, game.wait()?))
|
||||
}
|
||||
|
||||
/// SIGTERM, then SIGKILL after `grace` if the process has not gone. Fine to call on one that already exited.
|
||||
/// The processes `pid` started, their children and so on (not `pid` itself), from `/proc/<n>/stat`.
|
||||
/// A launch script's game is a child of the script: stopping only the script would leave the game running.
|
||||
pub fn descendants_in(proc_dir: &Path, pid: u32) -> Vec<u32> {
|
||||
let mut parent: Vec<(u32, u32)> = vec![];
|
||||
for e in std::fs::read_dir(proc_dir).into_iter().flatten().flatten() {
|
||||
let Some(n) = e.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let Ok(stat) = std::fs::read(e.path().join("stat")) else { continue };
|
||||
// "<pid> (<comm>) <state> <ppid> ...": comm may hold spaces and ')', so split after the last ')'
|
||||
let stat = String::from_utf8_lossy(&stat);
|
||||
let Some(rest) = stat.rfind(')').map(|i| &stat[i + 1..]) else { continue };
|
||||
if let Some(pp) = rest.split_whitespace().nth(1).and_then(|x| x.parse::<u32>().ok()) { parent.push((n, pp)); }
|
||||
}
|
||||
let mut family = vec![pid];
|
||||
let mut i = 0;
|
||||
while i < family.len() {
|
||||
let p = family[i];
|
||||
for &(c, pp) in &parent { if pp == p && !family.contains(&c) { family.push(c); } }
|
||||
i += 1;
|
||||
}
|
||||
family.remove(0);
|
||||
family
|
||||
}
|
||||
|
||||
/// Still running (not gone, not a zombie waiting for its parent).
|
||||
fn alive(proc_dir: &Path, pid: u32) -> bool {
|
||||
match std::fs::read(proc_dir.join(pid.to_string()).join("stat")) {
|
||||
Ok(stat) => {
|
||||
let stat = String::from_utf8_lossy(&stat);
|
||||
stat.rfind(')').and_then(|i| stat[i + 1..].split_whitespace().next()).is_some_and(|st| st != "Z" && st != "X")
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn signal(sig: &str, pids: &[u32]) {
|
||||
if pids.is_empty() { return; }
|
||||
let mut c = std::process::Command::new("kill");
|
||||
c.arg(sig).args(pids.iter().map(|p| p.to_string()));
|
||||
let _ = c.stderr(std::process::Stdio::null()).status();
|
||||
}
|
||||
|
||||
/// SIGTERM to the process and everything it started, then SIGKILL after `grace` to whatever of them is still
|
||||
/// there. Fine to call on one that already exited.
|
||||
pub fn stop(child: &mut std::process::Child, grace: std::time::Duration) -> std::io::Result<()> {
|
||||
if child.try_wait()?.is_some() { return Ok(()); }
|
||||
let _ = std::process::Command::new("kill").args(["-TERM", &child.id().to_string()]).status();
|
||||
let proc_dir = Path::new("/proc");
|
||||
// Collected while `child` still runs: once it is gone its children are re-parented and can no longer be found.
|
||||
let mut tree = descendants_in(proc_dir, child.id());
|
||||
let mut all = vec![child.id()];
|
||||
all.extend(&tree);
|
||||
signal("-TERM", &all);
|
||||
let until = std::time::Instant::now() + grace;
|
||||
while std::time::Instant::now() < until {
|
||||
if child.try_wait()?.is_some() { return Ok(()); }
|
||||
loop {
|
||||
let child_done = child.try_wait()?.is_some();
|
||||
tree.retain(|p| alive(proc_dir, *p));
|
||||
if child_done && tree.is_empty() { return Ok(()); }
|
||||
if std::time::Instant::now() >= until { break; }
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
if child.try_wait()?.is_none() {
|
||||
for p in descendants_in(proc_dir, child.id()) { if !tree.contains(&p) { tree.push(p); } }
|
||||
}
|
||||
signal("-KILL", &tree);
|
||||
let _ = child.kill();
|
||||
child.wait().map(|_| ())
|
||||
}
|
||||
@@ -176,12 +240,12 @@ mod tests {
|
||||
fn p() -> Profile { Profile { monitor: Some("HDMI-A-1".into()), fullscreen: true, upscaler: "rtx-vsr".into(), framegen: "rife".into(), target_hz: Some(120), model: Some("4.25".into()), ..Default::default() } }
|
||||
#[test] fn ps5_display_plan() {
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &p(), true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --model 4.25 --scaler vsr --display --hz 120 --fullscreen --monitor HDMI-A-1");
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --model=4.25 --scaler vsr --display --hz 120 --fullscreen --monitor=HDMI-A-1");
|
||||
}
|
||||
#[test] fn file_to_out_plan() {
|
||||
let pr = Profile { framegen: "rife".into(), upscaler: "none".into(), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::File("c.mp4".into()), &pr, false, Some(Path::new("o.mp4")), Some(120));
|
||||
assert_eq!(a[1..].join(" "), "c.mp4 --out o.mp4 --max-ticks 120");
|
||||
assert_eq!(a[1..].join(" "), "c.mp4 --out=o.mp4 --max-ticks 120");
|
||||
}
|
||||
#[test] fn clip_args_follow_the_engine_choices() {
|
||||
assert_eq!(clip_args(60, 30).join(" "), "--replay 60 --clip-length 30");
|
||||
@@ -191,7 +255,7 @@ mod tests {
|
||||
#[test] fn window_plan_names_the_source() {
|
||||
let pr = Profile { framegen: "rife".into(), upscaler: "fsr".into(), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("Voidrunner".into()), &pr, true, None, None);
|
||||
assert_eq!(a[1..].join(" "), "--source window --window Voidrunner --scaler fsr --display --hz 60");
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=Voidrunner --scaler fsr --display --hz 60");
|
||||
}
|
||||
#[test] fn parse_source_kinds() {
|
||||
assert_eq!(parse_source("ps5"), Ok(Source::Ps5));
|
||||
@@ -207,12 +271,12 @@ mod tests {
|
||||
#[test] fn run_enhance_applies_the_profile() {
|
||||
let a = run_enhance_plan(Path::new("/e"), 4242, None, &p(), &Live::default());
|
||||
assert_eq!(a[0], "/e/run.py");
|
||||
assert_eq!(a[1..].join(" "), "--source window --window pid:4242 --model 4.25 --scaler vsr --display --hz 120 --fullscreen --monitor HDMI-A-1 --window-wait 60");
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=pid:4242 --model=4.25 --scaler vsr --display --hz 120 --fullscreen --monitor=HDMI-A-1 --window-wait 60");
|
||||
}
|
||||
#[test] fn run_enhance_window_override_and_watermark_off() {
|
||||
let pr = Profile { framegen: "none".into(), upscaler: "fsr".into(), ..Default::default() };
|
||||
let a = run_enhance_plan(Path::new("/e"), 1, Some("class:steam_app_620"), &pr, &Live { wait_secs: 0, watermark: Some(false) });
|
||||
assert_eq!(a[1..].join(" "), "--source window --window class:steam_app_620 --off --scaler fsr --display --hz 60 --watermark off");
|
||||
assert_eq!(a[1..].join(" "), "--source window --window=class:steam_app_620 --off --scaler fsr --display --hz 60 --watermark off");
|
||||
}
|
||||
#[test] fn live_args_leave_the_saved_watermark_alone_by_default() {
|
||||
assert_eq!(live_args(&Live::default()).join(" "), "--window-wait 60");
|
||||
@@ -256,6 +320,48 @@ mod tests {
|
||||
assert!(c.try_wait().unwrap().is_some());
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5));
|
||||
}
|
||||
#[test] fn stop_also_stops_what_the_process_started() {
|
||||
// a launch script that starts the game and waits for it, as Voidrunner's run.sh does
|
||||
let mut c = sh("sleep 30 & echo $! ; wait");
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
let kids = descendants_in(Path::new("/proc"), c.id());
|
||||
assert_eq!(kids.len(), 1, "the script's sleep is found: {kids:?}");
|
||||
stop(&mut c, std::time::Duration::from_secs(3)).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
assert!(!alive(Path::new("/proc"), kids[0]), "the game the script started was stopped too");
|
||||
}
|
||||
#[test] fn stop_kills_a_child_that_ignores_sigterm() {
|
||||
let mut c = sh("sh -c \"trap '' TERM; sleep 30\" & wait");
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
let kids = descendants_in(Path::new("/proc"), c.id());
|
||||
assert!(!kids.is_empty());
|
||||
let t = std::time::Instant::now();
|
||||
stop(&mut c, std::time::Duration::from_millis(400)).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
assert!(kids.iter().all(|k| !alive(Path::new("/proc"), *k)), "{kids:?} still running");
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5));
|
||||
}
|
||||
#[test] fn descendants_parse_a_fake_proc() {
|
||||
let d = std::env::temp_dir().join(format!("summit-engine-proc-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
for (pid, stat) in [(10, "10 (run.sh) S 1 10"), (11, "11 (my game (x) y) S 10 10"), (12, "12 (helper) S 11 10"), (13, "13 (other) S 1 13"), (14, "garbage")] {
|
||||
std::fs::create_dir_all(d.join(pid.to_string())).unwrap();
|
||||
std::fs::write(d.join(format!("{pid}/stat")), stat).unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(d.join("self")).unwrap();
|
||||
let mut k = descendants_in(&d, 10); k.sort();
|
||||
assert_eq!(k, vec![11, 12]);
|
||||
assert!(descendants_in(&d, 13).is_empty());
|
||||
assert!(descendants_in(Path::new("/nonexistent-proc"), 1).is_empty());
|
||||
}
|
||||
#[test] fn user_values_cannot_become_engine_options() {
|
||||
let pr = Profile { model: Some("--settings".into()), monitor: Some("-x".into()), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::Window("--out".into()), &pr, true, None, None);
|
||||
assert!(a.contains(&"--window=--out".to_string()) && a.contains(&"--model=--settings".to_string()) && a.contains(&"--monitor=-x".to_string()), "{a:?}");
|
||||
let f = plan(Path::new("/e"), &Source::File("-clip.mp4".into()), &Profile::default(), false, Some(Path::new("-o.mp4")), None);
|
||||
assert_eq!(f[1..].join(" "), "./-clip.mp4 --out=-o.mp4");
|
||||
assert_eq!(plan(Path::new("/e"), &Source::File("/abs/-c.mp4".into()), &Profile::default(), false, None, None)[1], "/abs/-c.mp4");
|
||||
}
|
||||
#[test] fn dlss_is_not_an_engine_scaler() { assert_eq!(scaler_arg("dlss"), None); }
|
||||
#[test] fn framegen_none_turns_interp_off() {
|
||||
let pr = Profile { framegen: "none".into(), ..Default::default() };
|
||||
|
||||
@@ -18,8 +18,7 @@ pub fn load() -> Names {
|
||||
}
|
||||
|
||||
pub fn save(n: &Names) -> Result<()> {
|
||||
let p = path()?; std::fs::create_dir_all(p.parent().unwrap())?;
|
||||
std::fs::write(p, serde_json::to_string(n)?)?; Ok(())
|
||||
crate::state::write_atomic(&path()?, serde_json::to_string(n)?.as_bytes())
|
||||
}
|
||||
|
||||
/// Parse one appdetails response body for `id`.
|
||||
|
||||
@@ -46,8 +46,7 @@ pub fn load(id: &str) -> Result<Profile> {
|
||||
|
||||
pub fn save(id: &str, p: &Profile) -> Result<PathBuf> {
|
||||
let f = file(id)?;
|
||||
std::fs::create_dir_all(f.parent().unwrap())?;
|
||||
std::fs::write(&f, toml::to_string_pretty(p)?)?;
|
||||
crate::state::write_atomic(&f, toml::to_string_pretty(p)?.as_bytes())?;
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
|
||||
@@ -95,14 +95,19 @@ pub fn full(extra: &[std::path::PathBuf], depth: usize) -> Vec<Entry> {
|
||||
let known: Vec<String> = all.iter().filter_map(|e| e.path.clone()).collect();
|
||||
let mut found = Vec::new();
|
||||
for r in extra { walk(r, depth, &mut found); }
|
||||
for f in found {
|
||||
if !known.iter().any(|k| f.path.as_deref().map_or(false, |p| p.starts_with(k.as_str()) || k.starts_with(p))) {
|
||||
all.push(f);
|
||||
}
|
||||
}
|
||||
all.extend(dedupe(found, &known));
|
||||
all
|
||||
}
|
||||
|
||||
/// Heuristic finds that are not already known: inside a known path, or holding one (a custom entry's run.sh).
|
||||
/// Compared by path components, so a known `/games/Foo` does not hide `/games/FooBar`.
|
||||
fn dedupe(found: Vec<Entry>, known: &[String]) -> Vec<Entry> {
|
||||
found.into_iter().filter(|f| {
|
||||
let Some(p) = f.path.as_deref().map(Path::new) else { return true };
|
||||
!known.iter().map(Path::new).any(|k| !k.as_os_str().is_empty() && (p.starts_with(k) || k.starts_with(p)))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -120,6 +125,24 @@ mod tests {
|
||||
assert!(out[0].reasons.iter().any(|r| r.contains("Unity")));
|
||||
}
|
||||
#[test]
|
||||
fn dedupe_compares_whole_path_components() {
|
||||
let e = |p: &str| Entry { id: format!("scan:{p}"), title: p.into(), source: Source::Heuristic, kind: Kind::Game, installed: true, path: Some(p.into()), steam_app_id: None, playtime_minutes: 0, last_played: None, reasons: vec![] };
|
||||
let known = vec!["/games/Foo".to_string(), "/games/Bar/run.sh".to_string(), String::new()];
|
||||
let kept: Vec<String> = dedupe(vec![e("/games/FooBar"), e("/games/Foo/sub"), e("/games/Bar"), e("/games/Baz")], &known)
|
||||
.into_iter().filter_map(|x| x.path).collect();
|
||||
assert_eq!(kept, vec!["/games/FooBar", "/games/Baz"]);
|
||||
}
|
||||
#[test]
|
||||
fn missing_and_odd_dirs_find_nothing() {
|
||||
let mut out = vec![]; walk(Path::new("/nonexistent/summit"), 3, &mut out); assert!(out.is_empty());
|
||||
let d = tmp("odd"); use std::os::unix::ffi::OsStrExt;
|
||||
let g = d.join(std::ffi::OsStr::from_bytes(b"caf\xe9_game")); fs::create_dir_all(&g).unwrap();
|
||||
fs::write(g.join("game.x86_64"), b"").unwrap(); fs::write(g.join("UnityPlayer.so"), b"").unwrap();
|
||||
walk(&d, 2, &mut out);
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].title, "caf\u{fffd} game");
|
||||
}
|
||||
#[test]
|
||||
fn lone_exe_is_software_with_reason() {
|
||||
let d = tmp("lone"); let g = d.join("Tool"); fs::create_dir_all(&g).unwrap();
|
||||
fs::write(g.join("setup.exe"), b"MZ").unwrap();
|
||||
|
||||
@@ -278,8 +278,16 @@ fn fetch_from_sgdb(grid_dir: &Path, grid_id: u64, kind: ArtKind, title: &str, ke
|
||||
let Some(game_id) = crate::sgdb::search_game(key, title)? else { return Ok(None) };
|
||||
let Some(url) = crate::sgdb::art_url(key, game_id, kind)? else { return Ok(None) };
|
||||
let bytes = crate::sgdb::download(&url)?;
|
||||
let ext = url.rsplit('.').next().filter(|e| e.len() <= 4).unwrap_or("png");
|
||||
Ok(Some(install_from_bytes(grid_dir, grid_id, kind, ext, &bytes)?))
|
||||
Ok(Some(install_from_bytes(grid_dir, grid_id, kind, url_ext(&url), &bytes)?))
|
||||
}
|
||||
|
||||
/// The image type from an art URL's last path segment, for the grid file's name. Only known image types: whatever
|
||||
/// else the URL ends in (a query, a '/', a long suffix) must not end up in a file name.
|
||||
fn url_ext(url: &str) -> &'static str {
|
||||
let path = url.split(['?', '#']).next().unwrap_or("");
|
||||
let last = path.rsplit('/').next().unwrap_or("");
|
||||
let ext = last.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
|
||||
match ext.as_str() { "jpg" | "jpeg" => "jpg", "webp" => "webp", "ico" => "ico", _ => "png" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -397,6 +405,16 @@ mod tests {
|
||||
assert!(!is_steam_running_in(&proc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn url_ext_only_yields_image_types() {
|
||||
assert_eq!(url_ext("https://cdn2.steamgriddb.com/grid/abc.JPG"), "jpg");
|
||||
assert_eq!(url_ext("https://cdn/x.webp?v=2"), "webp");
|
||||
assert_eq!(url_ext("https://e.vil/a/b"), "png");
|
||||
assert_eq!(url_ext("https://e.vil/x.png/../../c"), "png");
|
||||
assert_eq!(url_ext("https://e.vil/x.sh"), "png");
|
||||
assert_eq!(url_ext(""), "png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_filenames_match_steams_convention() {
|
||||
let id = 12345u64;
|
||||
|
||||
@@ -21,18 +21,29 @@ pub struct State {
|
||||
pub tracked: HashMap<String, Tracked>,
|
||||
}
|
||||
|
||||
/// A path as the text stored in `state.json`. JSON holds UTF-8 only, and a lossy copy (U+FFFD for the odd bytes)
|
||||
/// would name a file that does not exist, so a path that is not UTF-8 is refused with a clear message instead.
|
||||
pub fn path_text(p: &std::path::Path) -> Result<String> {
|
||||
p.to_str().map(String::from).with_context(|| format!("{} is not valid UTF-8; Summit can only store UTF-8 paths, rename it", p.display()))
|
||||
}
|
||||
|
||||
pub fn path() -> Result<PathBuf> { Ok(dirs::data_dir().context("no data dir")?.join("summit/state.json")) }
|
||||
|
||||
pub fn load() -> State {
|
||||
path().ok().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn save(s: &State) -> Result<()> {
|
||||
let p = path()?;
|
||||
std::fs::create_dir_all(p.parent().unwrap())?;
|
||||
let tmp = p.with_extension("tmp");
|
||||
std::fs::write(&tmp, serde_json::to_string_pretty(s)?)?;
|
||||
std::fs::rename(tmp, p)?; // atomic: a crash mid-write never corrupts the file
|
||||
pub fn save(s: &State) -> Result<()> { write_atomic(&path()?, serde_json::to_string_pretty(s)?.as_bytes()) }
|
||||
|
||||
/// Write through a temporary file and rename it over `p`: a crash mid-write never leaves half a file. The temporary
|
||||
/// name carries the process id, so the launcher and a `summit run` saving at the same moment do not write into one
|
||||
/// temporary file (each rename is whole; the later one wins).
|
||||
pub fn write_atomic(p: &std::path::Path, bytes: &[u8]) -> Result<()> {
|
||||
if let Some(d) = p.parent() { std::fs::create_dir_all(d)?; }
|
||||
let mut tmp = p.as_os_str().to_os_string();
|
||||
tmp.push(format!(".{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, bytes)?;
|
||||
std::fs::rename(&tmp, p).inspect_err(|_| { let _ = std::fs::remove_file(&tmp); })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -108,5 +119,22 @@ mod tests {
|
||||
assert_eq!(s.artwork.get("custom:v").map(String::as_str), Some("/c.png"));
|
||||
}
|
||||
#[test]
|
||||
fn non_utf8_paths_are_refused_not_mangled() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let bad = std::path::Path::new(std::ffi::OsStr::from_bytes(b"/games/caf\xe9/run.sh"));
|
||||
assert!(path_text(bad).unwrap_err().to_string().contains("not valid UTF-8"));
|
||||
assert_eq!(path_text(std::path::Path::new("/games/café/run.sh")).unwrap(), "/games/café/run.sh");
|
||||
}
|
||||
#[test]
|
||||
fn write_atomic_replaces_and_leaves_no_temp() {
|
||||
let d = std::env::temp_dir().join(format!("summit-state-atomic-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let p = d.join("sub/state.json");
|
||||
write_atomic(&p, b"one").unwrap();
|
||||
write_atomic(&p, b"two").unwrap();
|
||||
assert_eq!(std::fs::read(&p).unwrap(), b"two");
|
||||
assert_eq!(std::fs::read_dir(d.join("sub")).unwrap().count(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn pin_idempotent() { let mut s = State::default(); s.pin("a"); s.pin("a"); assert_eq!(s.pinned.len(), 1); s.unpin("a"); assert!(s.pinned.is_empty()); }
|
||||
}
|
||||
@@ -87,11 +87,7 @@ pub fn load_from(p: &Path) -> UiSettings {
|
||||
}
|
||||
|
||||
pub fn save_to(p: &Path, s: &UiSettings) -> Result<()> {
|
||||
if let Some(d) = p.parent() { std::fs::create_dir_all(d)?; }
|
||||
let tmp = p.with_extension("toml.tmp");
|
||||
std::fs::write(&tmp, toml::to_string_pretty(&s.clone().sanitized())?)?;
|
||||
std::fs::rename(tmp, p)?; // atomic, like state.json
|
||||
Ok(())
|
||||
crate::state::write_atomic(p, toml::to_string_pretty(&s.clone().sanitized())?.as_bytes())
|
||||
}
|
||||
|
||||
pub fn load() -> UiSettings { path().map(|p| load_from(&p)).unwrap_or_default() }
|
||||
@@ -122,7 +118,7 @@ mod tests {
|
||||
let s = UiSettings { layout: "list".into(), theme: "violet".into(), anim_speed: 0.0, anim_style: "snappy".into(), ui_scale: 1.25, replay_seconds: 600, clip_seconds: 180, shortcuts: default_shortcuts() };
|
||||
save_to(&p, &s).unwrap();
|
||||
assert_eq!(load_from(&p), s);
|
||||
assert!(!p.with_extension("toml.tmp").exists());
|
||||
assert_eq!(std::fs::read_dir(p.parent().unwrap()).unwrap().count(), 1, "no temporary file left");
|
||||
}
|
||||
#[test]
|
||||
fn garbage_file_gives_defaults() {
|
||||
|
||||
@@ -73,7 +73,12 @@ fn lex(src: &str) -> Result<Vec<Tok>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn parse_obj(toks: &[Tok], i: &mut usize, top: bool) -> Result<Value, String> {
|
||||
/// Deeper than any file Steam writes; a crafted or corrupt file with more nesting is refused instead of
|
||||
/// overflowing the stack (the parser recurses once per level).
|
||||
pub const MAX_DEPTH: usize = 64;
|
||||
|
||||
fn parse_obj(toks: &[Tok], i: &mut usize, top: bool, depth: usize) -> Result<Value, String> {
|
||||
if depth > MAX_DEPTH { return Err(format!("nested deeper than {MAX_DEPTH} levels")); }
|
||||
let mut kv = Vec::new();
|
||||
loop {
|
||||
match toks.get(*i) {
|
||||
@@ -86,7 +91,7 @@ fn parse_obj(toks: &[Tok], i: &mut usize, top: bool) -> Result<Value, String> {
|
||||
*i += 1;
|
||||
match toks.get(*i) {
|
||||
Some(Tok::Str(v)) => { kv.push((k.clone(), Value::Str(v.clone()))); *i += 1; }
|
||||
Some(Tok::Open) => { *i += 1; let o = parse_obj(toks, i, false)?; kv.push((k.clone(), o)); }
|
||||
Some(Tok::Open) => { *i += 1; let o = parse_obj(toks, i, false, depth + 1)?; kv.push((k.clone(), o)); }
|
||||
_ => return Err(format!("key '{k}' has no value")),
|
||||
}
|
||||
}
|
||||
@@ -97,7 +102,7 @@ fn parse_obj(toks: &[Tok], i: &mut usize, top: bool) -> Result<Value, String> {
|
||||
pub fn parse(src: &str) -> Result<Value, String> {
|
||||
let toks = lex(src)?;
|
||||
let mut i = 0;
|
||||
parse_obj(&toks, &mut i, true)
|
||||
parse_obj(&toks, &mut i, true, 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -111,4 +116,17 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn rejects_unbalanced() { assert!(parse("\"a\" {").is_err()); }
|
||||
#[test]
|
||||
fn deep_nesting_is_an_error_not_a_stack_overflow() {
|
||||
let deep = "\"k\" {".repeat(200_000);
|
||||
assert!(parse(&deep).unwrap_err().contains("nested deeper"));
|
||||
let ok = format!("{}\"x\" \"1\"{}", "\"k\" {".repeat(MAX_DEPTH), "}".repeat(MAX_DEPTH));
|
||||
assert!(parse(&ok).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn odd_input_never_panics() {
|
||||
for s in ["", "}", "{", "\"", "\"a\"", "/", "a b c", "\"a\" \"b\" }", "\"a\" \\", "\u{feff}\"a\" \"b\"", r#""a" { "b" "c\"}"#, r#""a" "b\"#] {
|
||||
let _ = parse(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,15 +51,32 @@ fn raw_len(tag: u8) -> Option<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_cstr(b: &[u8], i: &mut usize) -> Result<String, String> {
|
||||
fn read_cstr_bytes<'a>(b: &'a [u8], i: &mut usize) -> Result<&'a [u8], String> {
|
||||
let start = *i;
|
||||
while *i < b.len() && b[*i] != 0 { *i += 1; }
|
||||
if *i >= b.len() { return Err("unterminated string".into()); }
|
||||
let s = String::from_utf8_lossy(&b[start..*i]).into_owned();
|
||||
let s = &b[start..*i];
|
||||
*i += 1; // skip the nul
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn read_cstr(b: &[u8], i: &mut usize) -> Result<String, String> {
|
||||
read_cstr_bytes(b, i).map(|s| String::from_utf8_lossy(s).into_owned())
|
||||
}
|
||||
|
||||
/// A string value. Steam does not promise UTF-8 here (an old shortcut can hold a Latin-1 path), so one that is
|
||||
/// not valid UTF-8 is kept as raw bytes: writing the file back must not turn someone's other shortcuts into U+FFFD.
|
||||
fn read_str_val(b: &[u8], i: &mut usize) -> Result<BVal, String> {
|
||||
let s = read_cstr_bytes(b, i)?;
|
||||
Ok(match std::str::from_utf8(s) {
|
||||
Ok(t) => BVal::Str(t.to_string()),
|
||||
Err(_) => { let mut raw = s.to_vec(); raw.push(0); BVal::Raw(T_STR, raw) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Deeper than any shortcuts.vdf; a corrupt file with more nesting is refused instead of overflowing the stack.
|
||||
pub const MAX_DEPTH: usize = 64;
|
||||
|
||||
/// Reads a nul-terminated UTF-16LE string's raw bytes (including the trailing 2-byte nul), for
|
||||
/// the rare BIN_WSTRING field. We don't need the text, just to preserve it untouched.
|
||||
fn read_wstr_raw(b: &[u8], i: &mut usize) -> Result<Vec<u8>, String> {
|
||||
@@ -72,7 +89,8 @@ fn read_wstr_raw(b: &[u8], i: &mut usize) -> Result<Vec<u8>, String> {
|
||||
Ok(b[start..*i].to_vec())
|
||||
}
|
||||
|
||||
fn parse_map(b: &[u8], i: &mut usize, bounded: bool) -> Result<Vec<(String, BVal)>, String> {
|
||||
fn parse_map(b: &[u8], i: &mut usize, bounded: bool, depth: usize) -> Result<Vec<(String, BVal)>, String> {
|
||||
if depth > MAX_DEPTH { return Err(format!("maps nested deeper than {MAX_DEPTH} levels")); }
|
||||
let mut kv = Vec::new();
|
||||
loop {
|
||||
if *i >= b.len() {
|
||||
@@ -86,8 +104,8 @@ fn parse_map(b: &[u8], i: &mut usize, bounded: bool) -> Result<Vec<(String, BVal
|
||||
}
|
||||
let key = read_cstr(b, i)?;
|
||||
let val = match tag {
|
||||
T_MAP => BVal::Map(parse_map(b, i, true)?),
|
||||
T_STR => BVal::Str(read_cstr(b, i)?),
|
||||
T_MAP => BVal::Map(parse_map(b, i, true, depth + 1)?),
|
||||
T_STR => read_str_val(b, i)?,
|
||||
T_INT32 => {
|
||||
if *i + 4 > b.len() { return Err("truncated int32".into()); }
|
||||
let v = i32::from_le_bytes(b[*i..*i + 4].try_into().unwrap());
|
||||
@@ -124,7 +142,7 @@ fn write_map(out: &mut Vec<u8>, kv: &[(String, BVal)], bounded: bool) {
|
||||
/// Parses a whole `shortcuts.vdf`-style file: one unclosed map at the top level.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Vec<(String, BVal)>, String> {
|
||||
let mut i = 0;
|
||||
parse_map(bytes, &mut i, false)
|
||||
parse_map(bytes, &mut i, false, 0)
|
||||
}
|
||||
|
||||
pub fn write(kv: &[(String, BVal)]) -> Vec<u8> {
|
||||
@@ -196,6 +214,33 @@ mod tests {
|
||||
assert!(parse(&[T_INT32]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_utf8_strings_survive_a_round_trip() {
|
||||
let mut bytes = Vec::new();
|
||||
bytes.push(T_MAP); bytes.extend_from_slice(b"shortcuts\0");
|
||||
bytes.push(T_MAP); bytes.extend_from_slice(b"0\0");
|
||||
bytes.push(T_STR); bytes.extend_from_slice(b"AppName\0"); bytes.extend_from_slice(b"Caf\xe9\0"); // Latin-1
|
||||
bytes.push(T_STR); bytes.extend_from_slice(b"Exe\0"); bytes.extend_from_slice(b"/g/caf\xe9.sh\0");
|
||||
bytes.push(T_END); bytes.push(T_END);
|
||||
let v = parse(&bytes).unwrap();
|
||||
assert_eq!(write(&v), bytes, "byte-identical, not U+FFFD");
|
||||
assert_eq!(v[0].1.get("0").unwrap().get("AppName").unwrap().str(), None); // not text we can use, but kept
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_is_an_error_not_a_stack_overflow() {
|
||||
let mut bytes = Vec::new();
|
||||
for _ in 0..200_000 { bytes.push(T_MAP); bytes.extend_from_slice(b"k\0"); }
|
||||
assert!(parse(&bytes).unwrap_err().contains("nested deeper"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_input_never_panics() {
|
||||
for b in [&b""[..], &[T_END], &[0xff], &[T_STR, b'k'], &[T_STR, b'k', 0], &[T_WSTRING, b'k', 0, 1], &[T_UINT64, b'k', 0, 1, 2], &[T_MAP, 0, T_END, T_END]] {
|
||||
let _ = parse(b);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_insensitive_get() {
|
||||
let m = BVal::Map(vec![("AppName".to_string(), BVal::Str("x".to_string()))]);
|
||||
|
||||
@@ -189,14 +189,7 @@ impl App {
|
||||
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 (can_enhance, enhance_note) = self.enhance_available(&e);
|
||||
let reasons: Vec<SharedString> = e.reasons.iter().map(|r| short(r).into()).collect();
|
||||
let prof = profile::load(&e.id).unwrap_or_default();
|
||||
self.ui.global::<Lib>().set_detail(Detail {
|
||||
@@ -212,9 +205,22 @@ impl App {
|
||||
self.focus_game(idx);
|
||||
}
|
||||
|
||||
/// Whether Enhance can run for `e` here, and the line the game's page shows about it.
|
||||
fn enhance_available(&self, e: &Entry) -> (bool, String) {
|
||||
let session = display::detect_session();
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
fn play(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
let enhance = profile::load(&e.id).map(|p| p.enhance).unwrap_or(false) && self.ui.global::<Lib>().get_detail().can_enhance;
|
||||
// Checked for this entry: Play on Home's hero is not the game whose page was opened last.
|
||||
let enhance = profile::load(&e.id).map(|p| p.enhance).unwrap_or(false) && self.enhance_available(&e).0;
|
||||
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)),
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Audit (independent review)
|
||||
|
||||
Branch `ap/audit`, on top of `c6e6e57` (play-integration merged). I read all of the Rust code (summit-core, summit-cli,
|
||||
summit-gui), the README, `install.sh`, and the engine code on the paths Summit calls: `run.py`'s arguments,
|
||||
`window_x11.py` (window pick, pid family, grab), and the SIGTERM handling. The rest of the Python engine (~18k lines:
|
||||
capture, replay, looks, chiaki tap, ...) was **not** audited line by line.
|
||||
|
||||
Severity: **High** = wrong behaviour in a normal use the README advertises; **Medium** = data loss, a crash on odd
|
||||
input, or a wrong result in a plausible case; **Low** = edge case, hardening, or cosmetic.
|
||||
|
||||
## Fixed (each with a test unless stated)
|
||||
|
||||
| # | Severity | Finding | Fix | Test / check |
|
||||
|---|---|---|---|---|
|
||||
| 1 | High | `summit run --enhance`: when the engine ended first, Summit sent SIGTERM only to its direct child. A game started by a launch script (`run.sh` that does not `exec`) kept running, orphaned. | `engine::stop()` now finds the process's descendants in `/proc` before signalling, sends SIGTERM to all of them, and SIGKILLs what is left after the grace time. | `stop_also_stops_what_the_process_started`, `stop_kills_a_child_that_ignores_sigterm`, `descendants_parse_a_fake_proc`. **On the VM** with Voidrunner behind a non-exec script: the old binary left `top_down_shooter` running (re-parented to 1), the new one stopped it. |
|
||||
| 2 | Medium | `summit run`: the display mode was applied before the game was spawned, but put back only on the success path. A command that could not be started (or an error while supervising) left the monitor in the game's mode. | A drop guard puts the old mode back on every way out of `run`. The error now names the command. | `on_drop_runs_on_early_return_too`. **On the VM**: `summit run <id> -- /nonexistent/game` with a 1280x800@74.99 profile: the old binary left the screen at 1280x800, the new one went back to `1920x1080_120.00`. |
|
||||
| 3 | Medium | Text VDF and binary VDF parsers recurse once per nesting level with no limit: a corrupt or crafted `localconfig.vdf`/`shortcuts.vdf` with deep nesting overflowed the stack (process abort, not an error). | Depth limit 64 (far above anything Steam writes); deeper is an `Err`. | `deep_nesting_is_an_error_not_a_stack_overflow` (both parsers, 200 000 levels), `odd_input_never_panics` (both). |
|
||||
| 4 | Medium | Binary VDF read strings with `from_utf8_lossy`; `steam-add`/`steam-remove` then wrote the whole file back, so another shortcut with a non-UTF-8 name or path was silently rewritten with U+FFFD. | Non-UTF-8 string values are kept as raw bytes and written back byte-identical. | `non_utf8_strings_survive_a_round_trip`. |
|
||||
| 5 | Medium | GUI: Play on Home's hero used `can_enhance` from whichever game's page was opened last, not the game being started. For example, a Lutris game with `enhance = true` could fail with "Enhance is not wired". | Enhance availability is computed for the entry being started. | No unit test (it needs a Slint window); it builds, and the page uses the same function. |
|
||||
| 6 | Medium | `install.sh`: the engine was copied to `/usr/local/share/summit/engine` with sudo, then the venv was made there **without** sudo, which fails for any non-root user. | `chown` the engine folder to the installing user (non-root only) before the venv step. | `--dry-run` as user `nobody` prints the chown before the venv step. Not run for real (see below). |
|
||||
| 7 | Low | `install.sh` built `sh -c "cd '$DIR' && ..."` strings: a `'` in `$SUMMIT_SRC_DIR`/`$SUMMIT_PREFIX` broke out of the quotes. | Commands take the paths as arguments (`cargo --manifest-path`, `uv venv <path>`, `uv pip --python <path>`). | `sh -n`, dry run. |
|
||||
| 8 | Low | Engine argv: user values (file name, window title, profile `model`/`monitor`, `--out`, capture name) were separate argv items, so the engine's argparse read a value starting with `-` as an option. | `--opt=value` form; a relative file name starting with `-` gets `./`. | `user_values_cannot_become_engine_options`; the existing plan tests now expect the new form. On the VM the engine accepted `--window=pid:N` and found the game window. |
|
||||
| 9 | Low | `scan::full` deduplicated heuristic finds by string prefix: a known `/games/Foo` hid `/games/FooBar`, and a known empty path (a Lutris YAML with `exe: ''`) hid **every** heuristic find. | Path-component comparison; empty known paths are ignored. | `dedupe_compares_whole_path_components`, `missing_and_odd_dirs_find_nothing` (missing dir, non-UTF-8 folder name). |
|
||||
| 10 | Low | `summit add` / `summit art` stored non-UTF-8 paths lossily: the stored path named a file that does not exist, so the entry showed as not installed with no explanation. | Refused with a clear message (`state::path_text`); the same for `enhance --out`. | `non_utf8_paths_are_refused_not_mangled`. |
|
||||
| 11 | Low | SteamGridDB art: the grid file's extension was whatever followed the last `.` of the URL (up to 4 chars, `/` allowed), so a URL could put text like `b/c` into the file name. It could not escape the grid folder, but the name was garbage. | Only `png`/`jpg`/`webp`/`ico`, default `png`. | `url_ext_only_yields_image_types`. |
|
||||
| 12 | Low | Profiles and the Steam names cache were written in place (a crash mid-write left broken TOML/JSON). `state.json` and `ui.toml` used one fixed temp name, so the launcher and a `summit run` saving at the same moment could write into the same temp file. | One `write_atomic` with a per-process temp file for all four. | `write_atomic_replaces_and_leaves_no_temp`; `roundtrip_through_file` checks that no temp file is left. |
|
||||
| 13 | Medium (docs) | README said `install.sh` had "a real build + install on this machine" and the `.deb` "builds and installs". The packaging report says only dry runs were done and the `.deb` was never installed. README also said the engine installer "is not built yet", which contradicts the installer row. | README rows now say dry-run only, and built but not installed. The signal-kill note now also says the display mode is not put back. | – |
|
||||
|
||||
Checked and fine: profile ids cannot escape the profiles folder (every character except `[A-Za-z0-9_-]` becomes `_`).
|
||||
Artwork ids are only map keys, never file names. Grid file names are numeric. The engine never goes through a shell
|
||||
(no `shell=True`, every subprocess is an argv list). `summit run` passes the game command as argv. The engine already
|
||||
treats SIGTERM as a clean quit. A damaged `state.json`/`ui.toml` loads as defaults.
|
||||
|
||||
## Not fixed
|
||||
|
||||
| Severity | Finding | Why not |
|
||||
|---|---|---|
|
||||
| Medium | Killing `summit run` itself (a signal to summit only, e.g. from a process manager) leaves the game and the engine running and the display mode changed. Ctrl+C in a terminal reaches all three (same process group), so that case is fine. | It needs signal handling in the CLI (a new dependency or `libc`), which is more than a fix. Documented in the README. |
|
||||
| Low | `state.json` has no lock: if the launcher saves a pin while `summit run` saves a session, the later write wins and the other change is lost (each write is now whole, see #12). | Needs file locking. Rare: the GUI reloads the file just before every save. |
|
||||
| Low | `stop()` collects descendant PIDs and may signal them up to the grace time later; a PID reused within that time could get the signal. | Inherent in PID-based kill without pidfds or cgroups. The window is a few seconds. |
|
||||
| Low | `steam-add` writes `LaunchOptions` as `run <id> -- <summit path> enhance <target>` without quoting: a summit path or a `ui.toml` target with spaces breaks. | How Steam splits LaunchOptions for non-Steam shortcuts could not be checked (no Steam here), so a quoting change could not be tested. |
|
||||
| Low | Profile file names: ids that differ only in punctuation or non-ASCII characters (`custom:café` / `custom:cafè`) share one profile file. | Changing the file naming would orphan existing profiles. |
|
||||
| Low | Binary VDF keys (not values) are still read lossily. | Steam's keys are ASCII in practice. |
|
||||
| Low | KDE Wayland: a monitor name containing `.` would break the `kscreen-doctor output.<name>...` argument. | Untestable without KDE Wayland; real output names have no dots. |
|
||||
| Low | Controller: a `/dev/input/js*` that exists but cannot be opened (permissions) gets a new reader thread every 2 s, each of which fails at once. | Harmless apart from the churn; not tested with a real device. |
|
||||
| Low | `supervise()` returns early on a `try_wait` error and leaves both processes running. | Should not happen in practice. |
|
||||
| – | `cargo clippy --workspace --all-targets`: 9 warnings remain, all style (`map_or` → `is_some_and`, a `== false` in a test, a complex type, a large `Err` from `ureq`). None points at a bug, so I left them. | Style only. |
|
||||
| – | Most of the Python engine was not audited. Its tests were not run here (no numpy/pytest on this host); I changed no Python. | Size and scope. |
|
||||
|
||||
## What I verified and how
|
||||
|
||||
- `cargo test --workspace` before every commit. Final run: 1 (cli) + 86 (core) + 17 (gui) tests pass. Before the audit: 72 + 17.
|
||||
- On the GPU VM (KDE neon X11), with a release `summit` built from this branch in `/home/user/summit-audit` (built
|
||||
before the last code commit, which only changes an error message), and the old one from `/home/user/summit-live`
|
||||
for comparison:
|
||||
- `summit run custom:voidrunner --enhance -- vr.sh` (`vr.sh` starts `top_down_shooter` without `exec`), then SIGTERM
|
||||
to the engine's PID. New binary: the engine ran on the game (I looked at the screenshot: RIFE stats over
|
||||
Voidrunner's menu), it was started with `--window=pid:N`, and after the SIGTERM both `vr.sh` and
|
||||
`top_down_shooter` were gone. Old binary: `top_down_shooter` was still running with parent 1 (I then stopped it by PID).
|
||||
- A profile with a 1280x800@74.99 mode and a command that does not exist: the new binary put `1920x1080_120.00` back;
|
||||
the old one left the screen at 1280x800. The test profile was deleted and the mode restored afterwards.
|
||||
- `install.sh --dry-run --yes` as user `nobody`: the chown comes before the venv commands, and no `sh -c` wraps a path.
|
||||
- Not verified: `install.sh` for real, the GUI change in a window, anything that needs Steam or Wayland.
|
||||
|
||||
## Environment note
|
||||
|
||||
The host's root disk was 100% full at the start, so nothing would build. With the owner's OK I deleted the `target/`
|
||||
folders of the merged worktrees `summit-wt-play-integration`, `summit-wt-packaging` and `summit-wt-steam-shortcuts`.
|
||||
They are build output and can be rebuilt.
|
||||
+9
-4
@@ -244,11 +244,16 @@ build_from_source() {
|
||||
run mkdir -p "$(dirname "$SRC_DIR")"
|
||||
run git clone "$REPO_GIT" "$SRC_DIR"
|
||||
fi
|
||||
run sh -c "cd '$SRC_DIR' && cargo build --release -p summit -p summit-gui"
|
||||
run cargo build --release --manifest-path "$SRC_DIR/Cargo.toml" -p summit -p summit-gui
|
||||
run_sudo install -Dm755 "$SRC_DIR/target/release/summit" "$BIN_DIR/summit"
|
||||
run_sudo install -Dm755 "$SRC_DIR/target/release/summit-gui" "$BIN_DIR/summit-gui"
|
||||
run_sudo mkdir -p "$SHARE_DIR/engine"
|
||||
run_sudo cp -r "$SRC_DIR/engine/." "$SHARE_DIR/engine/"
|
||||
# The engine's venv is made in there next, without sudo (uv and the Python it downloads live in the user's home),
|
||||
# so the folder has to belong to the user who runs Summit.
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
run_sudo chown -R "$(id -u):$(id -g)" "$SHARE_DIR/engine"
|
||||
fi
|
||||
}
|
||||
|
||||
setup_engine_venv() {
|
||||
@@ -262,11 +267,11 @@ setup_engine_venv() {
|
||||
log " engine sources not found, skipping venv setup"
|
||||
return
|
||||
fi
|
||||
run sh -c "cd '$engine_dir' && uv venv --python 3.12 .venv"
|
||||
run sh -c "cd '$engine_dir' && uv pip install --python .venv -r requirements.txt"
|
||||
run uv venv --python 3.12 "$engine_dir/.venv"
|
||||
run uv pip install --python "$engine_dir/.venv" -r "$engine_dir/requirements.txt"
|
||||
if [ "$GPU_VENDOR" = "nvidia" ]; then
|
||||
step "NVIDIA GPU detected: installing CUDA 12.8 torch build"
|
||||
run sh -c "cd '$engine_dir' && uv pip install --python .venv torch --index-url https://download.pytorch.org/whl/cu128"
|
||||
run uv pip install --python "$engine_dir/.venv" torch --index-url https://download.pytorch.org/whl/cu128
|
||||
else
|
||||
log " no NVIDIA GPU detected, skipping CUDA torch (engine will run CPU-only or be unavailable)"
|
||||
fi
|
||||
|
||||
Reference in new issue
Block a user