Merge ap/release-candidate: Add a game, summit doctor, report updates
This commit is contained in:
commit
58cff12700
50 files changed
+955
-146
No files matched your search
Generated
+1
@@ -4202,6 +4202,7 @@ version = "0.0.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dirs",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml 0.8.23",
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
curl -fsSL https://git.molberg.cloud/alex/summit/raw/branch/main/install.sh | sh
|
||||
```
|
||||
|
||||
The installer detects your distro (Arch/CachyOS/Manjaro, Debian/Ubuntu/neon/Mint, Fedora, openSUSE), your GPU vendor and your session type, prints exactly what it is about to do, and asks before any `sudo` step (`--yes` skips that, `--dry-run` only prints, `--uninstall` removes what it installed). It builds Summit from source with `cargo` (no release packages are published yet) and sets up the engine's Python environment with `uv` (Python 3.12; CUDA 12.8 torch if it finds an NVIDIA GPU). Then run `summit-gui`.
|
||||
The installer detects your distro (Arch/CachyOS/Manjaro, Debian/Ubuntu/neon/Mint, Fedora, openSUSE), your GPU vendor and your session type, prints exactly what it is about to do, and asks before any `sudo` step (`--yes` skips that, `--dry-run` only prints, `--uninstall` removes what it installed). It builds Summit from source with `cargo` (no release packages are published yet) and sets up the engine's Python environment with `uv` (Python 3.12; CUDA 12.8 torch if it finds an NVIDIA GPU). It also installs the tools Summit calls (`ffmpeg`, `xrandr`, `xdg-open`, `zenity`; a failure there only warns), downloads the default RIFE model, and adds **Summit** to the app menu. Then run `summit doctor` to see whether Enhance can work on this machine, and `summit-gui` (or Summit in the app menu).
|
||||
|
||||
What was really run: see [Status](#status) (a real install into a scratch prefix on one Ubuntu machine; dry-runs for the other distros).
|
||||
|
||||
@@ -84,13 +84,15 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
|
||||
| Steam scan (all library folders, installed or not), Steam playtime, "most played" | **Tested** | Sample libraries, including the demo one above. Not run against a real Steam install in this run. |
|
||||
| Heroic (Epic, GOG) and Lutris detection | **Tested** | Sample files only. |
|
||||
| A reason for every detected entry (Unfiltered); heuristic detection; Windows `.exe` outside a Wine prefix listed as Software | **Tested** | The Unfiltered screenshot shows the reasons for the demo library's Steam entries on the real window. Heuristic and `.exe` detection: unit tests and sample folders, not a real disk full of games. |
|
||||
| Hours played: Steam's own for Steam games, Summit-tracked sessions for everything else | **Tested** | Unit tests and the demo library; Summit's own tracker ran with Voidrunner earlier. |
|
||||
| Pin to Home, custom artwork | **Working** | Pins from the CLI and the launcher. Artwork through `summit art`; the launcher's "Change artwork" button is marked Soon. |
|
||||
| Hours played: Steam's own for Steam games, Summit-tracked sessions for everything else | **Tested** | Unit tests and the demo library; Summit's own tracker ran with Voidrunner earlier. `state.json` is now changed under a file lock, so the launcher and `summit run` saving at once both keep their change (checked: 2 x 40 parallel `summit pin`). |
|
||||
| Add a game from the launcher (Library > **+ Add a game**, or **ADD** on a folder found on disk) | **Tested** | New since the RC run: the desktop's file dialog picks the file that starts the game, a second dialog asks for its name (guessed from the folder, skipping `bin`, `x86_64` and the like), the library reloads and the game's page opens. Checked on Xvfb with a stand-in zenity, both ways in; not on a real desktop or with kdialog. |
|
||||
| `summit doctor` readiness list | **Tested** | New since the RC run: says whether the engine, its venv, torch with CUDA, the model, `ffmpeg`, `xrandr`, `xdg-open` and a file dialog are there, and what each missing one turns off. Run on the build machine (no venv there, so the torch line was not exercised for real); unit tests. |
|
||||
| Pin to Home, custom artwork | **Working** / **Tested** | Pins from the CLI and the launcher; `summit art`. **New since the RC run**: the launcher's **Change artwork** opens the desktop's file dialog (kdialog on KDE, zenity elsewhere) and the cover and backdrop change at once: checked on Xvfb with a stand-in zenity, not on a real desktop. |
|
||||
| Display profile applied at launch (monitor, resolution, refresh) and put back | **Working on X11** | Earlier on the test machine: `summit run` switched the output from its custom mode to 1280x800 @ 74.99 Hz and back when the game exited. Not repeated in this run (the profile used had the default mode). KDE Wayland and wlroots command plans: unit tests only. GNOME Wayland: skipped with a message. |
|
||||
| Per-game profile editor (Profile on a game's page) | **Working** (earlier run) | Listed the monitor's real xrandr modes; every change is written to the profile. Not opened in this run. Focus is stored only (raising the game window is not built). |
|
||||
| `summit enhance clip.mp4` (RIFE on a file) | **Working** (earlier run) | 30 fps 1080p to 60 fps at 14 ms per generated frame on the RTX 3090. |
|
||||
| Game controller navigation | **Experimental** | Reads `/dev/input/js*`; decoding and mapping unit tested, no real controller. |
|
||||
| Steam, Lutris games started from the launcher | **Experimental** | Command lines are built and unit tested; no Steam or Lutris on the test machines. Heroic and folders found on disk cannot be started yet and the button says so. |
|
||||
| Steam, Lutris, Heroic games started from the launcher | **Experimental** | Command lines are built and unit tested; no Steam, Lutris or Heroic on the test machines. Heroic (new): Epic and GOG games start through `xdg-open heroic://launch?appName=..&runner=..` (the format in Heroic's source), and the Flatpak Heroic's games are now found too. No Enhance for Lutris and Heroic games. Folders found on disk are not started directly: their button is **ADD** (see the Add a game row). |
|
||||
| RTX Video Super Resolution (`rtx-vsr`) | **Experimental** | Wired to the engine, not tested. |
|
||||
| 90/120 Hz output, choosing a monitor by name | **Experimental** | Wired, one virtual display only. |
|
||||
| PS5 Remote Play and capture cards | **Experimental** | Wired as `ps5` / `capture:<name>` sources, no hardware. |
|
||||
@@ -101,7 +103,7 @@ What was really run: see [Status](#status) (a real install into a scratch prefix
|
||||
|
||||
## Clips
|
||||
|
||||
The engine keeps a rolling buffer of what you played (hardware encoded where possible), like the PS5's Share button. Pick how far back to keep (15 s to 10 min) and what a save writes (15 s, 30 s, 1 m, 3 m, 5 m or 10 m) in Settings. **Ctrl+Alt+R saves a clip from any window on X11**, so you never have to leave the game; in the engine's own window **R** saves the default length and **Ctrl+1 to Ctrl+6** a chosen one. A clip is never longer than the buffer holds. Clips land in `~/Videos/SmoovPlay/` as plain MP4 files.
|
||||
The engine keeps a rolling buffer of what you played (hardware encoded where possible), like the PS5's Share button. Pick how far back to keep (15 s to 10 min) and what a save writes (15 s, 30 s, 1 m, 3 m, 5 m or 10 m) in Settings. **Ctrl+Alt+R saves a clip from any window on X11**, so you never have to leave the game; in the engine's own window **R** saves the default length and **Ctrl+1 to Ctrl+6** a chosen one. A clip is never longer than the buffer holds. Clips land in `~/Videos/Summit/<game>/` (a folder per game, named after the library entry) as plain MP4 files; **Settings > Clips folder** opens it. The folder per game is new since the RC run (unit tested; the RC clip went to the old `~/Videos/SmoovPlay/`).
|
||||
|
||||

|
||||
|
||||
@@ -134,7 +136,8 @@ cargo build --release
|
||||
./target/release/summit add "My Game" ~/Games/mygame/run.sh # add anything by hand (--software for apps)
|
||||
./target/release/summit pin steam:620 # show on Home
|
||||
./target/release/summit art steam:620 cover.png # custom artwork
|
||||
./target/release/summit doctor my-game # Wayland or X11? what would run?
|
||||
./target/release/summit doctor # what is missing for Enhance, profiles, clips, artwork
|
||||
./target/release/summit doctor my-game # also: the display commands this game's profile would run
|
||||
./target/release/summit profile set my-game --monitor HDMI-A-1 --width 3840 --height 2160 --refresh 60 --fullscreen true --focus true
|
||||
```
|
||||
|
||||
@@ -180,7 +183,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, 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.
|
||||
Limits: X11 sessions only (on Wayland it stops with a message). Needs the `ffmpeg` program. The grab polls, so it does not know when the game draws: a 60 fps game can show an occasional repeated or skipped frame. While the picture sits over a game the engine has no keys of its own (they all go to the game): close the game to stop. SIGTERM, SIGINT or SIGHUP to `summit` itself stops the game and the engine and puts the monitor's mode back (exit code 128 + the signal; SIGKILL cannot be caught). Checked with stand-in processes; the mode restore after a signal has not been tried on a real display yet. `SUMMIT_ENGINE_ARGS` passes extra flags to the engine, e.g. `SUMMIT_ENGINE_ARGS=--no-graph` on a GPU short of memory.
|
||||
|
||||
## The launcher
|
||||
|
||||
@@ -191,10 +194,11 @@ Limits: X11 sessions only (on Wayland it stops with a message). Needs the `ffmpe
|
||||
```
|
||||
|
||||
- **Home**: the focused game as a hero, over shelves: Jump back in (recently played), Pinned, Most played. Hours come from Steam's own playtime for Steam games and from Summit's sessions for everything else.
|
||||
- **Library**: every game, installed or not. Cover grid or dense list, filter, sort, search.
|
||||
- **Library**: every game, installed or not. Cover grid or dense list, filter, sort, search, **+ Add a game**.
|
||||
- **Unfiltered**: everything on this machine, grouped by source, with the reason each entry was detected.
|
||||
- **A game's page** (Enter on a game): stats, launch profile, detection reasons, Play, Pin.
|
||||
- **Settings** (the gear): layout, theme, interface size, animation speed and style, clip lengths, default upscaler and frame generation for `summit enhance`.
|
||||
- **Settings** (the gear): layout, theme, interface size, animation speed and style, clip lengths and the clips folder, default upscaler and frame generation for `summit enhance`.
|
||||
- If a game started from the launcher fails (`summit run` ends with an error), a toast says why; the full output is in `~/.cache/summit/last-run.log`.
|
||||
|
||||
| Key | Controller | Does |
|
||||
|---|---|---|
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use summit_core::{display, engine, model::Entry, profile, scan, state};
|
||||
use summit_core::{display, doctor, engine, model::Entry, profile, scan, signals, state};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "summit", version, about = "One launcher for every game and app on Linux")]
|
||||
@@ -35,6 +35,9 @@ enum Cmd {
|
||||
/// The command hands the game to another program and returns at once (`steam steam://rungameid/N`).
|
||||
/// With --enhance, Summit then waits for the engine (the game's window) instead of the command.
|
||||
#[arg(long)] detached: bool,
|
||||
/// The game's name, for the clips folder (Videos/Summit/<title>). Default: the title it was added
|
||||
/// with (`summit add`), else the id.
|
||||
#[arg(long)] title: Option<String>,
|
||||
/// The command to run. Not needed for an entry added with `summit add`.
|
||||
#[arg(last = true)] cmd: Vec<String>,
|
||||
},
|
||||
@@ -46,7 +49,8 @@ enum Cmd {
|
||||
Unpin { id: String },
|
||||
/// Set custom artwork (image file) for an entry
|
||||
Art { id: String, image: std::path::PathBuf },
|
||||
/// Show detected session (Wayland/X11), desktop and the display commands a profile would run
|
||||
/// Check this machine: session, monitors, and whether the engine, torch with CUDA, the model, ffmpeg, xrandr
|
||||
/// and a file dialog are there (with an id: the display commands that game's profile would run)
|
||||
Doctor { id: Option<String> },
|
||||
/// Look up names for Steam games you own but have not installed (cached)
|
||||
Names { #[arg(long, default_value_t = 60)] limit: usize },
|
||||
@@ -107,6 +111,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.
|
||||
/// println!/eprintln! that never panic: after SIGHUP (the terminal closed) writing fails, and `summit run` still
|
||||
/// has to stop the game and put the display mode back.
|
||||
macro_rules! out { ($($t:tt)*) => {{ use std::io::Write as _; let _ = writeln!(std::io::stdout(), $($t)*); }} }
|
||||
macro_rules! err { ($($t:tt)*) => {{ use std::io::Write as _; let _ = writeln!(std::io::stderr(), $($t)*); }} }
|
||||
|
||||
struct OnDrop<F: FnMut()>(F);
|
||||
impl<F: FnMut()> Drop for OnDrop<F> { fn drop(&mut self) { (self.0)() } }
|
||||
|
||||
@@ -134,7 +143,7 @@ fn main() -> Result<()> {
|
||||
Cmd::Scan { path, depth, json, why } => {
|
||||
let mut all: Vec<Entry> = scan::full(&path, depth);
|
||||
state::apply(&mut all, &state::load());
|
||||
all.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase()));
|
||||
all.sort_by_key(|a| a.title.to_lowercase());
|
||||
if json { println!("{}", serde_json::to_string_pretty(&all)?); return Ok(()); }
|
||||
for e in &all {
|
||||
println!("[{:?}/{:?}] {}{}", e.source, e.kind, e.title, if e.installed { "" } else { " (not installed)" });
|
||||
@@ -159,12 +168,7 @@ fn main() -> Result<()> {
|
||||
println!("resolved {n}");
|
||||
}
|
||||
Cmd::Add { title, path, software } => {
|
||||
anyhow::ensure!(path.exists(), "{} does not exist", path.display());
|
||||
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: state::path_text(&path.canonicalize()?)?, software });
|
||||
state::save(&st)?; println!("added {id}");
|
||||
println!("added {}", state::add_custom(&title, &path, software)?);
|
||||
}
|
||||
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"))?;
|
||||
@@ -175,7 +179,7 @@ fn main() -> Result<()> {
|
||||
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;
|
||||
// without a ui.toml the engine keeps whatever it has stored itself.
|
||||
if out.is_none() && summit_core::ui::path().map_or(false, |p| p.exists()) {
|
||||
if out.is_none() && summit_core::ui::path().is_ok_and(|p| p.exists()) {
|
||||
let ui = summit_core::ui::load();
|
||||
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
|
||||
}
|
||||
@@ -188,13 +192,12 @@ fn main() -> Result<()> {
|
||||
anyhow::ensure!(st.success(), "engine exited with {st}");
|
||||
}
|
||||
}
|
||||
Cmd::Pin { id } => { let mut st = state::load(); st.pin(&id); state::save(&st)?; println!("pinned {id}"); }
|
||||
Cmd::Unpin { id } => { let mut st = state::load(); st.unpin(&id); state::save(&st)?; println!("unpinned {id}"); }
|
||||
Cmd::Pin { id } => { state::update(|st| st.pin(&id))?; println!("pinned {id}"); }
|
||||
Cmd::Unpin { id } => { state::update(|st| st.unpin(&id))?; println!("unpinned {id}"); }
|
||||
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(), state::path_text(&image.canonicalize()?)?);
|
||||
state::save(&st)?; println!("artwork set for {id}");
|
||||
let text = state::path_text(&image.canonicalize()?)?;
|
||||
state::update(|st| { st.artwork.insert(id.clone(), text); })?; println!("artwork set for {id}");
|
||||
}
|
||||
Cmd::Doctor { id } => {
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
@@ -206,16 +209,26 @@ fn main() -> Result<()> {
|
||||
},
|
||||
Err(e) => println!("outputs: {e}"),
|
||||
}
|
||||
if let Some(id) = 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)"); }
|
||||
let p = profile::load(id.as_deref().unwrap_or("default"))?;
|
||||
if let Some(id) = &id {
|
||||
let cmds = display::plan_for(s, d, &p, &display::outputs(s, d).unwrap_or_default());
|
||||
if cmds.is_empty() { println!("no display commands for {id} on this session (nothing set, or unsupported compositor)"); }
|
||||
for c in cmds { println!("would run: {}", c.join(" ")); }
|
||||
}
|
||||
println!("\nWhat Summit needs:");
|
||||
let checks = doctor::checks(s, engine::find_engine().as_deref(), p.model.as_deref());
|
||||
for c in &checks { println!("{}", c.line()); }
|
||||
let missing = checks.iter().filter(|c| c.status == doctor::Status::Missing).count();
|
||||
if missing == 0 { println!("all set"); } else { println!("{missing} missing: see the lines marked MISS"); }
|
||||
}
|
||||
Cmd::Run { id, enhance, window, wait, no_watermark, detached, mut cmd } => {
|
||||
Cmd::Run { id, enhance, window, wait, no_watermark, detached, title, mut cmd } => {
|
||||
// From here on a signal to summit stops the game and the engine and puts the display mode back.
|
||||
signals::install();
|
||||
let custom = state::load().custom.into_iter().find(|c| c.id == id);
|
||||
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()]; }
|
||||
if let Some(c) = &custom { cmd = vec![c.path.clone()]; }
|
||||
}
|
||||
let title = title.or(custom.map(|c| c.title)).unwrap_or_else(|| id.clone());
|
||||
anyhow::ensure!(!cmd.is_empty(), "give the command after --, e.g. summit run my-game -- ./game.sh");
|
||||
let p = profile::load(&id)?;
|
||||
// Found before the game starts, so a missing engine never leaves a game running without it.
|
||||
@@ -223,17 +236,17 @@ fn main() -> Result<()> {
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
let outs = if p.monitor.is_some() { display::outputs(s, d) } else { Ok(vec![]) };
|
||||
let plan = display::plan_for(s, d, &p, outs.as_deref().unwrap_or_default());
|
||||
if plan.is_empty() && p.monitor.is_some() { eprintln!("note: no display control for {s:?}/{d:?}; launching without mode change"); }
|
||||
if plan.is_empty() && p.monitor.is_some() { err!("note: no display control for {s:?}/{d:?}; launching without mode change"); }
|
||||
// The mode in use now, to put back when the game is over. A detached game without the engine runs on
|
||||
// after this command returns, so there is no "after" to restore in.
|
||||
let restore = if plan.is_empty() || (detached && eng.is_none()) { None } else {
|
||||
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 }
|
||||
Err(e) => { err!("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(" ")) }
|
||||
match r { Ok(()) => out!("display: ran {}", c.join(" ")), Err(e) => err!("display step failed ({}): {e}", c.join(" ")) }
|
||||
};
|
||||
run_display(&plan);
|
||||
let restore_guard = OnDrop(|| if let Some(r) = &restore { run_display(r); });
|
||||
@@ -246,37 +259,45 @@ fn main() -> Result<()> {
|
||||
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()) {
|
||||
if summit_core::ui::path().is_ok_and(|p| p.exists()) {
|
||||
let ui = summit_core::ui::load();
|
||||
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
|
||||
}
|
||||
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
|
||||
let py = engine::python(&eng);
|
||||
println!("{} {}", py.display(), args.join(" "));
|
||||
out!("{} {}", py.display(), args.join(" "));
|
||||
let grace = std::time::Duration::from_secs(8);
|
||||
let mut eng_proc = match std::process::Command::new(&py).args(&args).env("SMOOVPLAY_TITLE", "Summit").spawn() {
|
||||
let mut eng_proc = match std::process::Command::new(&py).args(&args).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title).spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => { let _ = engine::stop(&mut game, grace); anyhow::bail!("could not start the engine ({}): {e}", py.display()); }
|
||||
};
|
||||
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace, detached)?;
|
||||
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace, detached, &|| signals::requested().is_some())?;
|
||||
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()?),
|
||||
engine::Ended::Stopped => out!("{}: stopped the engine and the game", signals::requested().map_or("asked to stop", signals::name)),
|
||||
engine::Ended::Game if detached => out!("the game's window closed; the engine ended ({})", eng_proc.wait()?),
|
||||
engine::Ended::Game => out!("the game exited; the engine was stopped"),
|
||||
engine::Ended::Engine => out!("the engine exited ({}); the game was stopped", eng_proc.wait()?),
|
||||
}
|
||||
status
|
||||
} else { child.status().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))? };
|
||||
} else {
|
||||
let mut game = child.spawn().map_err(|e| anyhow::anyhow!("could not start {}: {e}", cmd[0]))?;
|
||||
let (status, stopped) = engine::wait_or_stop(&mut game, std::time::Duration::from_secs(8), &|| signals::requested().is_some())?;
|
||||
if stopped { out!("{}: stopped the game", signals::requested().map_or("asked to stop", signals::name)); }
|
||||
status
|
||||
};
|
||||
drop(restore_guard);
|
||||
let secs = start.elapsed().as_secs();
|
||||
if detached && !enhance {
|
||||
println!("{id}: handed over ({status}); its own launcher keeps the playtime");
|
||||
out!("{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");
|
||||
out!("{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");
|
||||
state::update(|st| st.record_session(&id, secs, now))?;
|
||||
out!("{id} exited ({status}) after {secs}s; tracked");
|
||||
}
|
||||
// A stop asked for by a signal ends like the signal would have (128 + its number), for process managers.
|
||||
if let Some(sig) = signals::requested() { std::process::exit(128 + sig); }
|
||||
}
|
||||
Cmd::Profile { cmd: ProfileCmd::Show { id } } => {
|
||||
print!("{}", toml::to_string_pretty(&profile::load(&id)?)?);
|
||||
|
||||
@@ -11,3 +11,4 @@ serde_json.workspace = true
|
||||
toml.workspace = true
|
||||
dirs.workspace = true
|
||||
ureq = "2"
|
||||
libc = "0.2"
|
||||
@@ -205,7 +205,7 @@ 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; }
|
||||
if p.width == Some(w) && p.height == Some(h) && p.refresh_hz.is_none_or(|x| (x - r).abs() < 0.01) { return None; }
|
||||
Some(Profile { monitor: Some(mon.into()), width: Some(w), height: Some(h), refresh_hz: if r > 0.0 { Some(r) } else { None }, ..Default::default() })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//! `summit doctor`'s readiness list: is everything that Enhance, display profiles and the launcher call there?
|
||||
//! Each check says what it is for, so a missing piece names the feature it turns off.
|
||||
use crate::display::Session;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Status { Ok, Warn, Missing }
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Check { pub name: &'static str, pub status: Status, pub detail: String }
|
||||
|
||||
impl Check {
|
||||
fn new(name: &'static str, status: Status, detail: impl Into<String>) -> Self { Check { name, status, detail: detail.into() } }
|
||||
pub fn line(&self) -> String {
|
||||
let mark = match self.status { Status::Ok => "ok ", Status::Warn => "warn", Status::Missing => "MISS" };
|
||||
format!("[{mark}] {:<12} {}", self.name, self.detail)
|
||||
}
|
||||
}
|
||||
|
||||
/// A program of that name is on PATH.
|
||||
pub fn on_path(name: &str) -> bool {
|
||||
std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(name).is_file()))
|
||||
}
|
||||
|
||||
/// The RIFE weights file the engine loads for `model` (the engine's default is 4.22.lite).
|
||||
pub fn weights_path(engine: &Path, model: Option<&str>) -> PathBuf {
|
||||
engine.join("models").join(format!("flownet_v{}.pkl", model.unwrap_or("4.22.lite")))
|
||||
}
|
||||
|
||||
/// What `python -c <TORCH_PROBE>` printed: "<torch version> <cuda available> <device name>".
|
||||
pub fn parse_torch_probe(out: &str) -> Option<(String, bool, String)> {
|
||||
let line = out.lines().rev().find(|l| !l.trim().is_empty())?;
|
||||
let mut it = line.splitn(3, ' ');
|
||||
let ver = it.next()?.to_string();
|
||||
let cuda = it.next()? == "True";
|
||||
Some((ver, cuda, it.next().unwrap_or("").trim().to_string()))
|
||||
}
|
||||
const TORCH_PROBE: &str = "import torch; c = torch.cuda.is_available(); print(torch.__version__, c, torch.cuda.get_device_name(0) if c else '')";
|
||||
|
||||
fn writable(dir: &Path) -> bool {
|
||||
// An existing folder we can make a file in, or a missing one whose parent we can.
|
||||
let d = if dir.exists() { dir.to_path_buf() } else { match dir.parent() { Some(p) => p.to_path_buf(), None => return false } };
|
||||
let probe = d.join(format!(".summit-doctor-{}", std::process::id()));
|
||||
let ok = std::fs::write(&probe, b"").is_ok();
|
||||
let _ = std::fs::remove_file(&probe);
|
||||
ok
|
||||
}
|
||||
|
||||
/// Everything below is read from this machine; `model` is the profile's RIFE model (None: the default).
|
||||
pub fn checks(session: Session, engine: Option<&Path>, model: Option<&str>) -> Vec<Check> {
|
||||
let mut v = vec![];
|
||||
match session {
|
||||
Session::X11 => v.push(Check::new("session", Status::Ok, "X11: Enhance, the save-clip key and display profiles work here")),
|
||||
Session::Wayland => v.push(Check::new("session", Status::Warn, "Wayland: Enhance can't capture a window here (needs an X11 session); the launcher works")),
|
||||
Session::Unknown => v.push(Check::new("session", Status::Warn, "no display found (DISPLAY and WAYLAND_DISPLAY are unset)")),
|
||||
}
|
||||
match engine {
|
||||
None => v.push(Check::new("engine", Status::Missing, "not found: Enhance is off. Run install.sh, or set SUMMIT_ENGINE to the engine/ folder")),
|
||||
Some(e) => {
|
||||
v.push(Check::new("engine", Status::Ok, e.display().to_string()));
|
||||
let venv = e.join(".venv/bin/python");
|
||||
if !venv.is_file() {
|
||||
v.push(Check::new("python", Status::Missing, format!("no venv at {} (install.sh makes it with uv)", e.join(".venv").display())));
|
||||
} else {
|
||||
match Command::new(&venv).args(["-c", TORCH_PROBE]).output() {
|
||||
Ok(o) if o.status.success() => match parse_torch_probe(&String::from_utf8_lossy(&o.stdout)) {
|
||||
Some((ver, true, gpu)) => v.push(Check::new("torch", Status::Ok, format!("{ver}, CUDA on {gpu}"))),
|
||||
Some((ver, false, _)) => v.push(Check::new("torch", Status::Missing, format!("{ver} without a usable CUDA GPU: Enhance needs an NVIDIA GPU and a CUDA build of torch"))),
|
||||
None => v.push(Check::new("torch", Status::Warn, "could not read torch's answer")),
|
||||
},
|
||||
Ok(o) => {
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
let last = err.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim().to_string();
|
||||
v.push(Check::new("torch", Status::Missing, format!("the venv can't import torch: {last}")));
|
||||
}
|
||||
Err(e) => v.push(Check::new("torch", Status::Missing, format!("could not start {}: {e}", venv.display()))),
|
||||
}
|
||||
}
|
||||
let w = weights_path(e, model);
|
||||
if w.is_file() {
|
||||
v.push(Check::new("model", Status::Ok, w.display().to_string()));
|
||||
} else if writable(&e.join("models")) {
|
||||
v.push(Check::new("model", Status::Warn, format!("{} not downloaded yet: the first Enhance downloads it (needs internet)", w.display())));
|
||||
} else {
|
||||
v.push(Check::new("model", Status::Missing, format!("{} is missing and {} is not writable: download it there by hand", w.display(), e.join("models").display())));
|
||||
}
|
||||
}
|
||||
}
|
||||
let tool = |name: &'static str, ok: bool, what: &str, fix: &str| {
|
||||
Check::new(name, if ok { Status::Ok } else { Status::Missing }, if ok { what.to_string() } else { format!("not on PATH: {fix}") })
|
||||
};
|
||||
v.push(tool("ffmpeg", on_path("ffmpeg"), "reads the game window for Enhance", "Enhance can't capture a window"));
|
||||
if session != Session::Wayland {
|
||||
v.push(tool("xrandr", on_path("xrandr"), "sets and restores the monitor mode", "display profiles (resolution, refresh) do nothing"));
|
||||
}
|
||||
v.push(tool("xdg-open", on_path("xdg-open"), "starts Heroic games, opens the clips folder", "Heroic games and Open clips folder fail"));
|
||||
let picker = ["kdialog", "zenity"].into_iter().find(|n| on_path(n));
|
||||
v.push(match picker {
|
||||
Some(p) => Check::new("file dialog", Status::Ok, format!("{p}, for Change artwork")),
|
||||
None => Check::new("file dialog", Status::Missing, "neither kdialog nor zenity: Change artwork can't open a file dialog"),
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test] fn torch_probe_lines() {
|
||||
assert_eq!(parse_torch_probe("2.11.0+cu128 True NVIDIA GeForce RTX 3090\n"), Some(("2.11.0+cu128".into(), true, "NVIDIA GeForce RTX 3090".into())));
|
||||
assert_eq!(parse_torch_probe("some warning\n2.11.0+cpu False \n"), Some(("2.11.0+cpu".into(), false, "".into())));
|
||||
assert_eq!(parse_torch_probe(""), None);
|
||||
}
|
||||
#[test] fn weights_follow_the_model() {
|
||||
assert_eq!(weights_path(Path::new("/e"), None), PathBuf::from("/e/models/flownet_v4.22.lite.pkl"));
|
||||
assert_eq!(weights_path(Path::new("/e"), Some("4.26")), PathBuf::from("/e/models/flownet_v4.26.pkl"));
|
||||
}
|
||||
#[test] fn missing_engine_is_named() {
|
||||
let c = checks(Session::Wayland, None, None);
|
||||
assert_eq!(c[0].status, Status::Warn);
|
||||
assert!(c.iter().any(|c| c.name == "engine" && c.status == Status::Missing));
|
||||
assert!(!c.iter().any(|c| c.name == "xrandr"), "xrandr is not used on Wayland");
|
||||
}
|
||||
#[test] fn engine_without_venv_or_weights() {
|
||||
let d = std::env::temp_dir().join(format!("summit-doctor-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let c = checks(Session::X11, Some(&d), None);
|
||||
assert!(c.iter().any(|c| c.name == "python" && c.status == Status::Missing));
|
||||
assert!(c.iter().any(|c| c.name == "model" && c.status == Status::Warn), "{c:?}");
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -128,34 +128,56 @@ pub fn extra_args(env: Option<&str>) -> Vec<String> {
|
||||
env.map(|v| v.split_whitespace().map(String::from).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Which of the two processes of `summit run --enhance` ended first.
|
||||
/// Which of the two processes of `summit run --enhance` ended first, or `Stopped`: `should_stop` said so (summit
|
||||
/// itself got SIGTERM, SIGINT or SIGHUP) and both were stopped.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Ended { Game, Engine }
|
||||
pub enum Ended { Game, Engine, Stopped }
|
||||
|
||||
/// 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.
|
||||
/// game's exit status. `should_stop` is asked every 100 ms; when it says yes, the engine and then the game are
|
||||
/// stopped. If waiting fails, both are stopped before the error is returned, so neither is left running.
|
||||
///
|
||||
/// `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)> {
|
||||
pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Child, grace: std::time::Duration, detached: bool,
|
||||
should_stop: &dyn Fn() -> 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 !handed_off && game.try_wait()?.is_some() {
|
||||
if detached { handed_off = true; } else { break Ended::Game; }
|
||||
let mut watch = || -> std::io::Result<Ended> {
|
||||
loop {
|
||||
if should_stop() { return Ok(Ended::Stopped); }
|
||||
if !handed_off && game.try_wait()?.is_some() {
|
||||
if detached { handed_off = true; } else { return Ok(Ended::Game); }
|
||||
}
|
||||
if engine.try_wait()?.is_some() { return Ok(if handed_off { Ended::Game } else { Ended::Engine }); }
|
||||
std::thread::sleep(poll);
|
||||
}
|
||||
if engine.try_wait()?.is_some() { break if handed_off { Ended::Game } else { Ended::Engine }; }
|
||||
std::thread::sleep(poll);
|
||||
};
|
||||
if !handed_off {
|
||||
let other = match first { Ended::Game => &mut *engine, Ended::Engine => &mut *game };
|
||||
stop(other, grace)?;
|
||||
let first = match watch() {
|
||||
Ok(f) => f,
|
||||
Err(e) => { let _ = stop(engine, grace); let _ = stop(game, grace); return Err(e); }
|
||||
};
|
||||
match first {
|
||||
Ended::Stopped => { stop(engine, grace)?; stop(game, grace)?; }
|
||||
_ if handed_off => {}
|
||||
Ended::Game => stop(engine, grace)?,
|
||||
Ended::Engine => stop(game, grace)?,
|
||||
}
|
||||
Ok((first, game.wait()?))
|
||||
}
|
||||
|
||||
/// Wait for one process (`summit run` without the engine), stopping it (and what it started) if `should_stop` says
|
||||
/// so. Returns its exit status and whether it was stopped.
|
||||
pub fn wait_or_stop(child: &mut std::process::Child, grace: std::time::Duration, should_stop: &dyn Fn() -> bool) -> std::io::Result<(std::process::ExitStatus, bool)> {
|
||||
loop {
|
||||
if let Some(st) = child.try_wait()? { return Ok((st, false)); }
|
||||
if should_stop() { stop(child, grace)?; return Ok((child.wait()?, true)); }
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -223,6 +245,13 @@ pub fn stop(child: &mut std::process::Child, grace: std::time::Duration) -> std:
|
||||
child.wait().map(|_| ())
|
||||
}
|
||||
|
||||
/// Where the engine saves clips: $SMOOVPLAY_REPLAY_DIR if set, else Summit in the Videos folder (XDG_VIDEOS_DIR),
|
||||
/// with a folder per game inside (see engine/framegen/replay.py videos_folder()).
|
||||
pub fn clips_dir() -> Option<PathBuf> {
|
||||
if let Some(d) = std::env::var_os("SMOOVPLAY_REPLAY_DIR").filter(|d| !d.is_empty()) { return Some(d.into()); }
|
||||
Some(dirs::video_dir().or_else(|| dirs::home_dir().map(|h| h.join("Videos")))?.join("Summit"))
|
||||
}
|
||||
|
||||
/// Instant replay flags for the engine, from the launcher's clip settings.
|
||||
/// The engine only accepts 15, 30, 60, 180, 300 or 600 seconds, and a save is never longer than the buffer.
|
||||
pub fn clip_args(replay_seconds: u32, clip_seconds: u32) -> Vec<String> {
|
||||
@@ -290,7 +319,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), false).unwrap();
|
||||
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), false, &|| false).unwrap();
|
||||
assert_eq!(who, Ended::Game);
|
||||
assert_eq!(status.code(), Some(3));
|
||||
assert!(eng.try_wait().unwrap().is_some(), "engine was stopped");
|
||||
@@ -298,7 +327,7 @@ 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), false).unwrap();
|
||||
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), false, &|| false).unwrap();
|
||||
assert_eq!(who, Ended::Engine);
|
||||
assert!(!status.success(), "the game was terminated, not left running");
|
||||
}
|
||||
@@ -306,12 +335,40 @@ mod tests {
|
||||
// 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();
|
||||
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), true, &|| false).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 supervise_stops_both_when_asked() {
|
||||
let (mut game, mut eng) = (sh("exec sleep 30"), sh("exec sleep 30"));
|
||||
let t = std::time::Instant::now();
|
||||
let asked = || t.elapsed() > std::time::Duration::from_millis(300);
|
||||
let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), false, &asked).unwrap();
|
||||
assert_eq!(who, Ended::Stopped);
|
||||
assert!(!status.success());
|
||||
assert!(eng.try_wait().unwrap().is_some(), "engine was stopped");
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(3));
|
||||
}
|
||||
#[test] fn supervise_stops_both_when_asked_after_a_detached_hand_off() {
|
||||
let (mut game, mut eng) = (sh("exit 0"), sh("exec sleep 30"));
|
||||
let t = std::time::Instant::now();
|
||||
let asked = || t.elapsed() > std::time::Duration::from_millis(400);
|
||||
let (who, _) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5), true, &asked).unwrap();
|
||||
assert_eq!(who, Ended::Stopped);
|
||||
assert!(eng.try_wait().unwrap().is_some(), "engine was stopped");
|
||||
}
|
||||
#[test] fn wait_or_stop_waits_or_stops() {
|
||||
let mut c = sh("exit 4");
|
||||
let (st, stopped) = wait_or_stop(&mut c, std::time::Duration::from_secs(5), &|| false).unwrap();
|
||||
assert_eq!((st.code(), stopped), (Some(4), false));
|
||||
let mut c = sh("exec sleep 30");
|
||||
let t = std::time::Instant::now();
|
||||
let (st, stopped) = wait_or_stop(&mut c, std::time::Duration::from_secs(5), &|| t.elapsed().as_millis() > 200).unwrap();
|
||||
assert!(stopped && !st.success());
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(3));
|
||||
}
|
||||
#[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));
|
||||
|
||||
@@ -3,13 +3,30 @@ use crate::model::{Entry, Kind, Source};
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn heroic() -> Vec<Entry> {
|
||||
let mut roots = vec![];
|
||||
if let Some(cfg) = dirs::config_dir() { roots.push(cfg.join("heroic")); }
|
||||
if let Some(home) = dirs::home_dir() { roots.push(home.join(".var/app/com.heroicgameslauncher.hgl/config/heroic")); } // Flatpak
|
||||
let mut out: Vec<Entry> = vec![];
|
||||
for root in roots {
|
||||
for e in heroic_in(&root) { if !out.iter().any(|o| o.id == e.id) { out.push(e); } }
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Heroic's `heroic://` launch URL: Heroic starts the game itself (its Wine/Proton, its playtime).
|
||||
pub fn heroic_uri(runner: &str, app_name: &str) -> String {
|
||||
let enc: String = app_name.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect();
|
||||
format!("heroic://launch?appName={enc}&runner={runner}")
|
||||
}
|
||||
|
||||
/// The installed Epic and GOG games of one Heroic config folder (`~/.config/heroic` or the Flatpak's).
|
||||
pub fn heroic_in(root: &std::path::Path) -> Vec<Entry> {
|
||||
let mut out = Vec::new();
|
||||
let Some(cfg) = dirs::config_dir() else { return out };
|
||||
let files = [
|
||||
("Epic", cfg.join("heroic/legendaryConfig/legendary/installed.json")),
|
||||
("GOG", cfg.join("heroic/gog_store/installed.json")),
|
||||
("Epic", "legendary", root.join("legendaryConfig/legendary/installed.json")),
|
||||
("GOG", "gog", root.join("gog_store/installed.json")),
|
||||
];
|
||||
for (store, f) in files {
|
||||
for (store, runner, f) in files {
|
||||
let Ok(txt) = std::fs::read_to_string(&f) else { continue };
|
||||
let Ok(v) = serde_json::from_str::<Value>(&txt) else { continue };
|
||||
// legendary: { appName: {title, install_path} }; gog: { installed: [ {appName, install_path} ] }
|
||||
@@ -27,11 +44,13 @@ pub fn heroic() -> Vec<Entry> {
|
||||
}
|
||||
}
|
||||
for (id, title, path) in items {
|
||||
if id.is_empty() { continue; }
|
||||
out.push(Entry {
|
||||
id: format!("heroic:{store}:{id}").to_lowercase(), title, source: Source::Heroic, kind: Kind::Game,
|
||||
installed: true, path: if path.is_empty() { None } else { Some(path) },
|
||||
steam_app_id: None, playtime_minutes: 0, last_played: None,
|
||||
reasons: vec![format!("listed as installed in Heroic {store} store ({})", f.display())],
|
||||
launch_uri: Some(heroic_uri(runner, &id)),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -54,8 +73,29 @@ pub fn lutris() -> Vec<Entry> {
|
||||
out.push(Entry {
|
||||
id: format!("lutris:{slug}"), title: slug.replace('-', " "), source: Source::Lutris, kind: Kind::Game,
|
||||
installed: true, path: exe, steam_app_id: None, playtime_minutes: 0, last_played: None,
|
||||
reasons: vec![format!("Lutris game config {} (runner: {runner})", p.display())],
|
||||
launch_uri: None, reasons: vec![format!("Lutris game config {} (runner: {runner})", p.display())],
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn heroic_keeps_the_app_name_for_its_launch_url() {
|
||||
let d = std::env::temp_dir().join(format!("summit-heroic-{}", std::process::id()));
|
||||
std::fs::create_dir_all(d.join("legendaryConfig/legendary")).unwrap();
|
||||
std::fs::create_dir_all(d.join("gog_store")).unwrap();
|
||||
std::fs::write(d.join("legendaryConfig/legendary/installed.json"), r#"{"Quail": {"title": "Celeste & Co", "install_path": "/g/q"}}"#).unwrap();
|
||||
std::fs::write(d.join("gog_store/installed.json"), r#"{"installed": [{"appName": "1207658924", "install_path": "/g/w"}, {"install_path": "/g/none"}]}"#).unwrap();
|
||||
let mut es = super::heroic_in(&d);
|
||||
es.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
let got: Vec<_> = es.iter().map(|e| (e.id.as_str(), e.launch_uri.as_deref().unwrap())).collect();
|
||||
assert_eq!(got, vec![
|
||||
("heroic:epic:quail", "heroic://launch?appName=Quail&runner=legendary"),
|
||||
("heroic:gog:1207658924", "heroic://launch?appName=1207658924&runner=gog"),
|
||||
]);
|
||||
assert_eq!(super::heroic_uri("legendary", "a b&c"), "heroic://launch?appName=a%20b%26c&runner=legendary");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,15 @@ pub enum Plan {
|
||||
/// * 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.
|
||||
/// * Heroic: `summit run <id> --detached -- xdg-open heroic://launch?appName=..&runner=..`: Heroic starts the game
|
||||
/// with its own Wine/Proton settings and keeps the playtime. No enhance yet (no window rule known in advance).
|
||||
/// * Folders found on disk: not wired (add them with `summit add`).
|
||||
pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
|
||||
let cli = summit_cli.map(|c| c.to_string_lossy().into_owned());
|
||||
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());
|
||||
if !e.title.is_empty() { v.push(format!("--title={}", e.title)); } // names the clips folder
|
||||
v.push("--".into());
|
||||
v.extend(cmd);
|
||||
v
|
||||
@@ -67,7 +70,14 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan {
|
||||
}
|
||||
_ => Plan::Unsupported("no Lutris slug for this entry".into()),
|
||||
},
|
||||
Source::Heroic => Plan::Unsupported("launching Heroic games from Summit is not built yet".into()),
|
||||
Source::Heroic => match e.launch_uri.as_deref() {
|
||||
Some(uri) => {
|
||||
if enhance { return Plan::Unsupported("Enhance is not wired for Heroic games yet".into()); }
|
||||
let open = vec!["xdg-open".to_string(), uri.to_string()];
|
||||
match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], open)), None => Plan::Run(open) }
|
||||
}
|
||||
None => Plan::Unsupported("no Heroic app name for this entry".into()),
|
||||
},
|
||||
Source::Heuristic => Plan::Unsupported("found on disk: add it with `summit add` and pick its executable to launch it".into()),
|
||||
}
|
||||
}
|
||||
@@ -80,7 +90,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::model::Kind;
|
||||
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![] }
|
||||
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, launch_uri: None, reasons: vec![] }
|
||||
}
|
||||
const CLI: &str = "/usr/bin/summit";
|
||||
fn cli() -> Option<&'static Path> { Some(Path::new(CLI)) }
|
||||
@@ -88,8 +98,8 @@ mod tests {
|
||||
#[test]
|
||||
fn steam_installed_goes_through_summit_run() {
|
||||
let e = entry("steam:620", Source::Steam, true, Some(620), None);
|
||||
assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam:620 --detached -- 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!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam:620 --detached --title=steam:620 -- steam steam://rungameid/620");
|
||||
assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam:620 --detached --enhance --window class:steam_app_620 --wait 120 --title=steam:620 -- steam steam://rungameid/620");
|
||||
assert_eq!(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));
|
||||
@@ -106,8 +116,8 @@ 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!(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_eq!(argv(plan(&e, cli(), false)), format!("/usr/bin/summit run custom:voidrunner --title=custom:voidrunner -- {p}"));
|
||||
assert_eq!(argv(plan(&e, cli(), true)), format!("/usr/bin/summit run custom:voidrunner --enhance --title=custom:voidrunner -- {p}"));
|
||||
assert!(matches!(plan(&e, None, false), Plan::Unsupported(_)));
|
||||
let _ = std::fs::remove_file(f);
|
||||
}
|
||||
@@ -119,10 +129,15 @@ mod tests {
|
||||
#[test]
|
||||
fn lutris_and_unwired_sources() {
|
||||
let l = entry("lutris:celeste", Source::Lutris, true, None, None);
|
||||
assert_eq!(argv(plan(&l, cli(), false)), "/usr/bin/summit run lutris:celeste --detached -- lutris lutris:rungame/celeste");
|
||||
assert_eq!(argv(plan(&l, cli(), false)), "/usr/bin/summit run lutris:celeste --detached --title=lutris:celeste -- lutris lutris:rungame/celeste");
|
||||
assert_eq!(plan(&l, None, false), Plan::Run(vec!["lutris".into(), "lutris:rungame/celeste".into()]));
|
||||
assert!(matches!(plan(&l, cli(), true), Plan::Unsupported(_)));
|
||||
assert!(matches!(plan(&entry("heroic:epic:x", Source::Heroic, true, None, None), cli(), false), Plan::Unsupported(_)));
|
||||
let mut h = entry("heroic:epic:quail", Source::Heroic, true, None, None);
|
||||
h.launch_uri = Some("heroic://launch?appName=Quail&runner=legendary".into());
|
||||
assert_eq!(argv(plan(&h, cli(), false)), "/usr/bin/summit run heroic:epic:quail --detached --title=heroic:epic:quail -- xdg-open heroic://launch?appName=Quail&runner=legendary");
|
||||
assert_eq!(plan(&h, None, false), Plan::Run(vec!["xdg-open".into(), "heroic://launch?appName=Quail&runner=legendary".into()]));
|
||||
assert!(matches!(plan(&h, cli(), true), Plan::Unsupported(_)));
|
||||
assert!(matches!(plan(&entry("scan:/g", Source::Heuristic, true, None, Some("/g")), cli(), false), Plan::Unsupported(_)));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Summit core: library scanning, per-game profiles, and the detection-reason model.
|
||||
pub mod display;
|
||||
pub mod doctor;
|
||||
pub mod engine;
|
||||
pub mod hotkey;
|
||||
pub mod epic;
|
||||
@@ -10,6 +11,7 @@ pub mod profile;
|
||||
pub mod scan;
|
||||
pub mod sgdb;
|
||||
pub mod shortcuts;
|
||||
pub mod signals;
|
||||
pub mod state;
|
||||
pub mod steam;
|
||||
pub mod ui;
|
||||
|
||||
@@ -21,4 +21,7 @@ pub struct Entry {
|
||||
pub playtime_minutes: u64,
|
||||
pub last_played: Option<u64>,
|
||||
pub reasons: Vec<String>,
|
||||
/// A URL that starts the entry through its own launcher (Heroic: `heroic://launch?appName=..&runner=..`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub launch_uri: Option<String>,
|
||||
}
|
||||
@@ -37,7 +37,7 @@ pub fn fetch_missing(ids: &[u32], limit: usize, pause_ms: u64, mut progress: imp
|
||||
let todo: Vec<u32> = ids.iter().copied().filter(|i| !names.contains_key(i)).take(limit).collect();
|
||||
for id in todo {
|
||||
let url = format!("https://store.steampowered.com/api/appdetails?appids={id}&filters=basic");
|
||||
let n = match ureq::get(&url).set("User-Agent", "summit-launcher").call().and_then(|r| r.into_string().map_err(Into::into)) {
|
||||
let n = match ureq::get(&url).set("User-Agent", "summit-launcher").call().map_err(Box::new).and_then(|r| r.into_string().map_err(|e| Box::new(e.into()))) {
|
||||
Ok(body) => parse_details(id, &body),
|
||||
Err(_) => break, // network/rate-limit: keep what we have, try again next run
|
||||
};
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn inspect_dir(dir: &Path) -> Option<Entry> {
|
||||
return Some(Entry {
|
||||
id: format!("scan:{}", dir.display()), title, source: Source::Heuristic, kind: Kind::Game,
|
||||
installed: true, path: Some(dir.to_string_lossy().into_owned()), steam_app_id: None,
|
||||
playtime_minutes: 0, last_played: None, reasons,
|
||||
playtime_minutes: 0, last_played: None, reasons, launch_uri: None,
|
||||
});
|
||||
}
|
||||
// No engine/store signal, but a Windows .exe on Linux stands out: list it as Software with the reason.
|
||||
@@ -66,7 +66,7 @@ pub fn inspect_dir(dir: &Path) -> Option<Entry> {
|
||||
id: format!("scan:{}", dir.display()), title, source: Source::Heuristic, kind: Kind::Software,
|
||||
installed: true, path: Some(dir.to_string_lossy().into_owned()), steam_app_id: None,
|
||||
playtime_minutes: 0, last_played: None,
|
||||
reasons: vec![format!("Windows executable {first} (.exe) found outside a Wine prefix"), "no game-engine or store signature, so listed as software".into()],
|
||||
launch_uri: None, reasons: vec![format!("Windows executable {first} (.exe) found outside a Wine prefix"), "no game-engine or store signature, so listed as software".into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,7 @@ mod tests {
|
||||
}
|
||||
#[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 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, launch_uri: 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();
|
||||
|
||||
@@ -367,7 +367,7 @@ mod tests {
|
||||
assert_eq!(root, empty_root());
|
||||
add_shortcut(&mut root, &NewShortcut { app_name: "My PS5", exe: "/usr/bin/summit", launch_options: "run ps5", start_dir: "/", icon: "" });
|
||||
save_checking(&path, &root, false, &tmp("no-steam-proc")).unwrap();
|
||||
assert!(backup_path(&path).exists() == false); // nothing to back up on first write
|
||||
assert!(!backup_path(&path).exists()); // nothing to back up on first write
|
||||
let reloaded = load(&path).unwrap();
|
||||
assert_eq!(list_names(&reloaded), vec!["My PS5".to_string()]);
|
||||
// second write backs up the first
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! SIGTERM, SIGINT and SIGHUP as a request to stop, for `summit run`: without this a signal to summit alone (a
|
||||
//! process manager, closing the terminal, `kill <summit>`) ended summit at once and left the game, the engine and
|
||||
//! a changed display mode behind. The handler only stores the signal's number; `summit run` polls for it, stops
|
||||
//! what it started and puts the mode back on its normal way out.
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
|
||||
static GOT: AtomicI32 = AtomicI32::new(0);
|
||||
|
||||
extern "C" fn on_signal(sig: libc::c_int) { GOT.store(sig, Ordering::SeqCst); }
|
||||
|
||||
/// Catch SIGTERM, SIGINT and SIGHUP from now on (only an atomic store happens in the handler).
|
||||
pub fn install() {
|
||||
for sig in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] {
|
||||
// SAFETY: the handler is async-signal-safe (one atomic store) and lives for the whole program.
|
||||
unsafe {
|
||||
let mut sa: libc::sigaction = std::mem::zeroed();
|
||||
sa.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||
sa.sa_flags = libc::SA_RESTART;
|
||||
libc::sigemptyset(&mut sa.sa_mask);
|
||||
libc::sigaction(sig, &sa, std::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The signal that asked to stop, if one came.
|
||||
pub fn requested() -> Option<i32> { match GOT.load(Ordering::SeqCst) { 0 => None, s => Some(s) } }
|
||||
|
||||
/// The signal's usual name, for messages.
|
||||
pub fn name(sig: i32) -> &'static str {
|
||||
match sig { libc::SIGTERM => "SIGTERM", libc::SIGINT => "SIGINT", libc::SIGHUP => "SIGHUP", _ => "a signal" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_caught_signal_is_remembered_not_fatal() {
|
||||
super::install();
|
||||
assert_eq!(super::requested(), None);
|
||||
// SAFETY: raising a signal whose handler was just installed.
|
||||
unsafe { libc::raise(libc::SIGHUP); }
|
||||
assert_eq!(super::requested(), Some(libc::SIGHUP));
|
||||
assert_eq!(super::name(libc::SIGHUP), "SIGHUP");
|
||||
super::GOT.store(0, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,57 @@ pub fn load() -> State {
|
||||
|
||||
pub fn save(s: &State) -> Result<()> { write_atomic(&path()?, serde_json::to_string_pretty(s)?.as_bytes()) }
|
||||
|
||||
/// The entry `summit add` (and the launcher's Add a game) stores: id `custom:<title, lower case, spaces as ->`.
|
||||
pub fn custom_for(title: &str, path: &std::path::Path, software: bool) -> Result<Custom> {
|
||||
let title = title.trim();
|
||||
anyhow::ensure!(!title.is_empty(), "the name is empty");
|
||||
anyhow::ensure!(path.exists(), "{} does not exist", path.display());
|
||||
let id = format!("custom:{}", title.to_lowercase().replace(' ', "-"));
|
||||
Ok(Custom { id, title: title.to_string(), path: path_text(&path.canonicalize()?)?, software })
|
||||
}
|
||||
|
||||
/// Add (or replace, same id) an entry by hand. Returns its id.
|
||||
pub fn add_custom(title: &str, path: &std::path::Path, software: bool) -> Result<String> {
|
||||
let c = custom_for(title, path, software)?;
|
||||
let id = c.id.clone();
|
||||
update(|st| { st.custom.retain(|x| x.id != id); st.custom.push(c); })?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// A name for a game from the file picked to start it: its folder's name, unless that folder is a generic one
|
||||
/// (`bin`, `x86_64`, `Binaries/Linux`...), then the next folder up; the file name if no folder fits.
|
||||
pub fn title_guess(file: &std::path::Path) -> String {
|
||||
const GENERIC: &[&str] = &["bin", "bin32", "bin64", "x86", "x64", "x86_64", "amd64", "linux", "linux64", "linux32",
|
||||
"win32", "win64", "windows", "binaries", "game", "games", "release", "build", "data", "app", "files", "home", "opt", "usr", "local", "applications"];
|
||||
let tidy = |s: &str| s.replace(['_', '-'], " ").split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
for dir in file.ancestors().skip(1).take(3) {
|
||||
let Some(name) = dir.file_name().and_then(|n| n.to_str()) else { break };
|
||||
if !name.starts_with('.') && !GENERIC.contains(&name.to_ascii_lowercase().as_str()) { return tidy(name); }
|
||||
}
|
||||
let stem = file.file_stem().and_then(|n| n.to_str()).unwrap_or("Game");
|
||||
tidy(stem.split('.').next().unwrap_or(stem))
|
||||
}
|
||||
|
||||
/// Load, change and save `state.json` while holding a lock (`flock` on `state.json.lock`), so the launcher saving a
|
||||
/// pin and `summit run` saving a session at the same moment both keep their change. Returns the saved state.
|
||||
pub fn update(f: impl FnOnce(&mut State)) -> Result<State> { update_at(&path()?, f) }
|
||||
|
||||
pub fn update_at(p: &std::path::Path, f: impl FnOnce(&mut State)) -> Result<State> {
|
||||
use std::os::fd::AsRawFd;
|
||||
if let Some(d) = p.parent() { std::fs::create_dir_all(d)?; }
|
||||
let mut lp = p.as_os_str().to_os_string();
|
||||
lp.push(".lock");
|
||||
let lock = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lp)
|
||||
.with_context(|| format!("could not open {}", std::path::Path::new(&lp).display()))?;
|
||||
// SAFETY: flock on a descriptor this function owns; the lock goes when `lock` is closed at the end.
|
||||
if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 { return Err(std::io::Error::last_os_error()).context("could not lock state.json"); }
|
||||
let mut st: State = std::fs::read_to_string(p).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
|
||||
f(&mut st);
|
||||
write_atomic(p, serde_json::to_string_pretty(&st)?.as_bytes())?;
|
||||
drop(lock);
|
||||
Ok(st)
|
||||
}
|
||||
|
||||
/// 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).
|
||||
@@ -72,7 +123,7 @@ pub fn custom_entries(st: &State) -> Vec<crate::model::Entry> {
|
||||
kind: if c.software { Kind::Software } else { Kind::Game },
|
||||
installed: std::path::Path::new(&c.path).exists(), path: Some(c.path.clone()), steam_app_id: None,
|
||||
playtime_minutes: 0, last_played: None,
|
||||
reasons: vec![format!("added by you: {}", c.path)],
|
||||
launch_uri: None, reasons: vec![format!("added by you: {}", c.path)],
|
||||
}).collect()
|
||||
}
|
||||
|
||||
@@ -92,10 +143,39 @@ pub fn apply(entries: &mut [crate::model::Entry], st: &State) {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn title_guess_skips_generic_folders() {
|
||||
use std::path::Path;
|
||||
assert_eq!(super::title_guess(Path::new("/home/u/Games/Voidrunner/top_down_shooter")), "Voidrunner");
|
||||
assert_eq!(super::title_guess(Path::new("/games/Hollow_Knight/bin/x86_64/hollow_knight.x86_64")), "Hollow Knight");
|
||||
assert_eq!(super::title_guess(Path::new("/games/Cool-Game/Binaries/Linux/CoolGame-Linux-Shipping")), "Cool Game");
|
||||
assert_eq!(super::title_guess(Path::new("/opt/bin/launch.sh")), "launch");
|
||||
}
|
||||
#[test]
|
||||
fn custom_ids_and_refusals() {
|
||||
let f = std::env::current_exe().unwrap();
|
||||
let c = super::custom_for(" My Game ", &f, false).unwrap();
|
||||
assert_eq!((c.id.as_str(), c.title.as_str()), ("custom:my-game", "My Game"));
|
||||
assert!(super::custom_for(" ", &f, false).is_err());
|
||||
assert!(super::custom_for("X", std::path::Path::new("/nonexistent/summit/x"), false).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn concurrent_updates_all_land() {
|
||||
let d = std::env::temp_dir().join(format!("summit-state-lock-{}", std::process::id()));
|
||||
let p = d.join("state.json");
|
||||
let hs: Vec<_> = (0..8).map(|i| { let p = p.clone(); std::thread::spawn(move || {
|
||||
for j in 0..10 { super::update_at(&p, |st| st.pin(&format!("g{i}-{j}"))).unwrap(); }
|
||||
}) }).collect();
|
||||
for h in hs { h.join().unwrap(); }
|
||||
let st: super::State = serde_json::from_str(&std::fs::read_to_string(&p).unwrap()).unwrap();
|
||||
assert_eq!(st.pinned.len(), 80);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use crate::model::*;
|
||||
fn entry(id: &str, src: Source, pt: u64) -> Entry {
|
||||
Entry { id: id.into(), title: id.into(), source: src, kind: Kind::Game, installed: true, path: None, steam_app_id: None, playtime_minutes: pt, last_played: None, reasons: vec![] }
|
||||
Entry { id: id.into(), title: id.into(), source: src, kind: Kind::Game, installed: true, path: None, steam_app_id: None, playtime_minutes: pt, last_played: None, launch_uri: None, reasons: vec![] }
|
||||
}
|
||||
#[test]
|
||||
fn steam_not_double_counted_others_tracked() {
|
||||
|
||||
@@ -114,6 +114,7 @@ pub fn scan() -> Vec<Entry> {
|
||||
steam_app_id: Some(id),
|
||||
playtime_minutes: minutes,
|
||||
last_played: if last > 0 { Some(last) } else { None },
|
||||
launch_uri: None,
|
||||
reasons,
|
||||
});
|
||||
}
|
||||
@@ -127,7 +128,7 @@ pub fn scan() -> Vec<Entry> {
|
||||
id: format!("steam:{id}"), title: n.name.clone(), source: Source::Steam, kind: Kind::Game,
|
||||
installed: false, path: None, steam_app_id: Some(*id), playtime_minutes: *minutes,
|
||||
last_played: if *last > 0 { Some(*last) } else { None },
|
||||
reasons: vec![format!("app {id} is in your Steam account (localconfig.vdf)"), "not installed".into()],
|
||||
launch_uri: None, reasons: vec![format!("app {id} is in your Steam account (localconfig.vdf)"), "not installed".into()],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,12 +11,12 @@ pub type Rgb = SharedPixelBuffer<Rgb8Pixel>;
|
||||
pub type Rgba = SharedPixelBuffer<Rgba8Pixel>;
|
||||
|
||||
pub enum Job {
|
||||
Cover { idx: usize, path: PathBuf },
|
||||
Cover { idx: usize, gen: u64, path: PathBuf },
|
||||
Backdrop { idx: usize, seq: u64, hero: Option<PathBuf>, cover: Option<PathBuf>, logo: Option<PathBuf>, c1: [u8; 3], c2: [u8; 3] },
|
||||
}
|
||||
|
||||
pub enum Done {
|
||||
Cover { idx: usize, img: Option<Rgb> },
|
||||
Cover { idx: usize, gen: u64, img: Option<Rgb> },
|
||||
Backdrop { idx: usize, seq: u64, img: Rgb, logo: Option<Rgba> },
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ pub fn logo(path: &Path) -> Option<Rgba> {
|
||||
|
||||
pub fn run(job: Job) -> Done {
|
||||
match job {
|
||||
Job::Cover { idx, path } => Done::Cover { idx, img: cover(&path) },
|
||||
Job::Cover { idx, gen, path } => Done::Cover { idx, gen, img: cover(&path) },
|
||||
Job::Backdrop { idx, seq, hero, cover, logo: l, c1, c2 } => Done::Backdrop {
|
||||
idx, seq, img: backdrop(hero.as_deref(), cover.as_deref(), c1, c2), logo: l.as_deref().and_then(logo),
|
||||
},
|
||||
@@ -175,7 +175,7 @@ mod tests {
|
||||
#[test]
|
||||
fn queue_loader_hands_jobs_back() {
|
||||
let l = Loader::queued();
|
||||
l.push(Job::Cover { idx: 3, path: "/x".into() });
|
||||
l.push(Job::Cover { idx: 3, gen: 0, path: "/x".into() });
|
||||
assert_eq!(l.take().len(), 1);
|
||||
assert!(l.take().is_empty());
|
||||
}
|
||||
|
||||
@@ -221,11 +221,76 @@ pub fn edit_apply(p: &Profile, outs: &[Output], row: usize, value: usize) -> Pro
|
||||
p
|
||||
}
|
||||
|
||||
/// The error `summit run` ended with, from its output: the last "Error: ..." line, else the last line.
|
||||
pub fn last_error(log: &str) -> Option<String> {
|
||||
let lines: Vec<&str> = log.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
let line = lines.iter().rev().find(|l| l.starts_with("Error: ")).or(lines.last())?;
|
||||
let s = line.strip_prefix("Error: ").unwrap_or(line);
|
||||
Some(if s.chars().count() > 160 { format!("{}...", s.chars().take(160).collect::<String>()) } else { s.to_string() })
|
||||
}
|
||||
|
||||
/// The desktop's file dialog for picking a cover: kdialog on KDE, zenity elsewhere (whichever is installed, the
|
||||
/// desktop's own first). `None` when neither is there.
|
||||
pub fn art_picker(kde: bool, have: impl Fn(&str) -> bool, start: &str) -> Option<Vec<String>> {
|
||||
file_picker(kde, have, start, "Summit: pick a cover image", Some(("Images", "*.png *.jpg *.jpeg *.webp")))
|
||||
}
|
||||
|
||||
/// Add a game: pick the file that starts it (any file: Linux games rarely have an extension).
|
||||
pub fn exe_picker(kde: bool, have: impl Fn(&str) -> bool, start: &str) -> Option<Vec<String>> {
|
||||
file_picker(kde, have, start, "Summit: pick the file that starts the game", None)
|
||||
}
|
||||
|
||||
/// The desktop's own dialog first (kdialog on KDE, zenity elsewhere); `filter` is (label, "*.a *.b").
|
||||
fn file_picker(kde: bool, have: impl Fn(&str) -> bool, start: &str, title: &str, filter: Option<(&str, &str)>) -> Option<Vec<String>> {
|
||||
let order = if kde { ["kdialog", "zenity"] } else { ["zenity", "kdialog"] };
|
||||
let name = order.into_iter().find(|n| have(n))?;
|
||||
let mut v = if name == "kdialog" {
|
||||
vec!["kdialog".to_string(), "--title".into(), title.into(), "--getopenfilename".into(), start.into()]
|
||||
} else {
|
||||
vec!["zenity".to_string(), "--file-selection".into(), format!("--title={title}"), format!("--filename={start}/")]
|
||||
};
|
||||
if let Some((label, pats)) = filter {
|
||||
v.push(if name == "kdialog" { format!("{pats}|{label}") } else { format!("--file-filter={label} | {pats}") });
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// After picking the file: ask for the game's name, with a guess filled in. Same tool as the file dialog.
|
||||
pub fn name_prompt(tool: &str, guess: &str) -> Vec<String> {
|
||||
if tool == "kdialog" {
|
||||
vec!["kdialog".into(), "--title".into(), "Summit: add a game".into(), "--inputbox".into(), "Name of the game".into(), guess.into()]
|
||||
} else {
|
||||
vec!["zenity".into(), "--entry".into(), "--title=Summit: add a game".into(), "--text=Name of the game".into(), format!("--entry-text={guess}")]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn last_error_finds_summits_error_line() {
|
||||
assert_eq!(super::last_error("display: ran xrandr\nError: engine not found: set SUMMIT_ENGINE\n\n").as_deref(), Some("engine not found: set SUMMIT_ENGINE"));
|
||||
assert_eq!(super::last_error("a\nb\n").as_deref(), Some("b"));
|
||||
assert_eq!(super::last_error("\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_picker_prefers_the_desktops_own_dialog() {
|
||||
let both = |_: &str| true;
|
||||
assert_eq!(super::art_picker(true, both, "/h").unwrap()[0], "kdialog");
|
||||
assert_eq!(super::art_picker(false, both, "/h").unwrap()[0], "zenity");
|
||||
assert_eq!(super::art_picker(true, |n: &str| n == "zenity", "/h").unwrap()[0], "zenity");
|
||||
assert!(super::art_picker(false, |_: &str| false, "/h").is_none());
|
||||
assert!(super::art_picker(false, both, "/h").unwrap().contains(&"--filename=/h/".to_string()));
|
||||
assert_eq!(super::art_picker(true, both, "/h").unwrap().last().unwrap(), "*.png *.jpg *.jpeg *.webp|Images");
|
||||
assert_eq!(super::exe_picker(true, both, "/g").unwrap().last().unwrap(), "/g");
|
||||
assert!(super::exe_picker(false, both, "/g").unwrap().iter().all(|a| !a.starts_with("--file-filter")));
|
||||
assert_eq!(super::name_prompt("zenity", "Voidrunner").last().unwrap(), "--entry-text=Voidrunner");
|
||||
assert_eq!(super::name_prompt("kdialog", "Voidrunner").last().unwrap(), "Voidrunner");
|
||||
}
|
||||
|
||||
use super::*;
|
||||
fn e(id: &str, title: &str, kind: Kind, src: Source, installed: bool, minutes: u64, last: u64) -> Entry {
|
||||
Entry { id: id.into(), title: title.into(), source: src, kind, installed, path: None, steam_app_id: None, playtime_minutes: minutes, last_played: if last > 0 { Some(last) } else { None }, reasons: vec![] }
|
||||
Entry { id: id.into(), title: title.into(), source: src, kind, installed, path: None, steam_app_id: None, playtime_minutes: minutes, last_played: if last > 0 { Some(last) } else { None }, launch_uri: None, reasons: vec![] }
|
||||
}
|
||||
fn lib() -> Vec<Entry> {
|
||||
vec![
|
||||
|
||||
+151
-10
@@ -41,9 +41,16 @@ pub struct App {
|
||||
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>)>>,
|
||||
editing: RefCell<Option<(usize, Outputs)>>,
|
||||
/// Folders given on the command line, scanned again when the library reloads.
|
||||
folders: Vec<PathBuf>,
|
||||
/// Bumped when the library reloads: a cover loaded for the old list is dropped, not put on the wrong row.
|
||||
gen: Cell<u64>,
|
||||
}
|
||||
|
||||
/// The monitors listed when the profile editor opened, or why there is no list.
|
||||
type Outputs = Result<Vec<display::Output>, String>;
|
||||
|
||||
impl App {
|
||||
fn cover_path(&self, e: &Entry) -> Option<PathBuf> {
|
||||
self.state.borrow().artwork.get(&e.id).map(PathBuf::from).filter(|p| p.is_file()).or_else(|| e.steam_app_id.and_then(steam::cover))
|
||||
@@ -63,6 +70,7 @@ impl App {
|
||||
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(_) if e.source == Source::Heuristic => "ADD",
|
||||
launch::Plan::Unsupported(_) => "",
|
||||
};
|
||||
Game {
|
||||
@@ -71,7 +79,7 @@ impl App {
|
||||
last: data::ago(e.last_played, now()).into(),
|
||||
source: data::source_label(e.source).into(), kind: data::kind_label(e.kind).into(),
|
||||
installed: e.installed, pinned: self.state.borrow().is_pinned(&e.id),
|
||||
cover: keep.map(|g| g.cover.clone()).unwrap_or_default(), has_cover: keep.map_or(false, |g| g.has_cover),
|
||||
cover: keep.map(|g| g.cover.clone()).unwrap_or_default(), has_cover: keep.is_some_and(|g| g.has_cover),
|
||||
c1: rgb(c1), c2: rgb(c2), reasons: short(&e.reasons.join(" · ")).into(), action: action.into(),
|
||||
}
|
||||
}
|
||||
@@ -113,7 +121,7 @@ impl App {
|
||||
fn want_cover(&self, idx: usize) {
|
||||
if idx >= self.entries.borrow().len() || !self.requested.borrow_mut().insert(idx) { return; }
|
||||
let path = self.cover_path(&self.entries.borrow()[idx]);
|
||||
if let Some(path) = path { self.loader.push(art::Job::Cover { idx, path }); }
|
||||
if let Some(path) = path { self.loader.push(art::Job::Cover { idx, gen: self.gen.get(), path }); }
|
||||
}
|
||||
|
||||
fn focus_game(&self, idx: i32) {
|
||||
@@ -128,7 +136,8 @@ impl App {
|
||||
|
||||
pub fn apply(&self, done: art::Done) {
|
||||
match done {
|
||||
art::Done::Cover { idx, img } => {
|
||||
art::Done::Cover { idx, gen, img } => {
|
||||
if gen != self.gen.get() { return; }
|
||||
let Some(img) = img else { return };
|
||||
let Some(mut g) = self.games.row_data(idx) else { return };
|
||||
g.cover = Image::from_rgb8(img); g.has_cover = true;
|
||||
@@ -187,6 +196,7 @@ impl App {
|
||||
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(_) if e.source == Source::Heuristic => ("ADD", true, "Found on disk. ADD asks for the file that starts it and a name, then the game can be played from Summit.".to_string()),
|
||||
launch::Plan::Unsupported(why) => ("PLAY", false, format!("Summit cannot start this yet: {why}.")),
|
||||
};
|
||||
let (can_enhance, enhance_note) = self.enhance_available(&e);
|
||||
@@ -219,6 +229,7 @@ impl App {
|
||||
|
||||
fn play(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
if e.source == Source::Heuristic { return self.add_game(idx); }
|
||||
// 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) {
|
||||
@@ -248,12 +259,136 @@ impl App {
|
||||
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())); });
|
||||
// If it failed (summit run exits 1 on an error, such as a missing engine), say why: the log's last line.
|
||||
let (title, log_path) = (e.title.clone(), log.as_ref().map(|(p, _)| p.clone()));
|
||||
std::thread::spawn(move || {
|
||||
let failed = child.wait().map(|st| st.code() == Some(1)).unwrap_or(false);
|
||||
let why = if failed { log_path.as_deref().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| data::last_error(&t)) } else { None };
|
||||
let _ = slint::invoke_from_event_loop(move || with_app(|a| {
|
||||
a.refresh_tracked();
|
||||
if failed { a.toast(format!("{title} did not start: {}", why.unwrap_or_else(|| "see ~/.cache/summit/last-run.log".into()))); }
|
||||
}));
|
||||
});
|
||||
}
|
||||
Err(err) => self.toast(format!("Could not run {}: {err}", argv[0])),
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings > Clips folder: open it in the file manager (made first, so there is something to open).
|
||||
fn open_clips(&self) {
|
||||
let Some(dir) = summit_core::engine::clips_dir() else { return self.toast("No Videos folder found") };
|
||||
if self.headless { return self.toast(format!("Headless render, would open {}", tilde(&dir))); }
|
||||
if let Err(err) = std::fs::create_dir_all(&dir) { return self.toast(format!("Could not make {}: {err}", tilde(&dir))); }
|
||||
match std::process::Command::new("xdg-open").arg(&dir).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn() {
|
||||
Ok(mut c) => { std::thread::spawn(move || { let _ = c.wait(); }); self.toast(format!("Opened {}", tilde(&dir))); }
|
||||
Err(err) => self.toast(format!("Could not run xdg-open: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- adding games ----
|
||||
/// "Add a game" (idx -1, from the Library) or ADD on a folder found on disk: the desktop's file dialog picks the
|
||||
/// file that starts the game, a second dialog asks for its name, then the library reloads with it.
|
||||
fn add_game(&self, idx: i32) {
|
||||
let found = usize::try_from(idx).ok().and_then(|i| self.entries.borrow().get(i).cloned());
|
||||
let hint = "or from a terminal: summit add \"My Game\" /path/to/game";
|
||||
if self.headless { return self.toast(format!("Headless render, no file dialog ({hint})")); }
|
||||
let kde = display::detect_desktop() == display::Desktop::Kde;
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| "/".into());
|
||||
let start = found.as_ref().and_then(|e| e.path.clone()).into_iter()
|
||||
.chain([format!("{home}/Games"), home.clone()])
|
||||
.find(|d| std::path::Path::new(d).is_dir()).unwrap_or(home);
|
||||
let Some(argv) = data::exe_picker(kde, summit_core::doctor::on_path, &start) else {
|
||||
return self.toast(format!("No file dialog found: install zenity or kdialog, {hint}"));
|
||||
};
|
||||
let found_title = found.map(|e| e.title);
|
||||
std::thread::spawn(move || {
|
||||
let ask = |argv: &[String]| -> Option<String> {
|
||||
let o = std::process::Command::new(&argv[0]).args(&argv[1..]).stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null()).output().ok()?;
|
||||
if !o.status.success() { return None; } // cancelled
|
||||
Some(String::from_utf8_lossy(&o.stdout).trim_end_matches(['\n', '\r']).to_string()).filter(|s| !s.trim().is_empty())
|
||||
};
|
||||
let Some(file) = ask(&argv).map(PathBuf::from) else { return };
|
||||
let guess = found_title.unwrap_or_else(|| state::title_guess(&file));
|
||||
let Some(title) = ask(&data::name_prompt(&argv[0], &guess)) else { return };
|
||||
let _ = slint::invoke_from_event_loop(move || with_app(|a| a.finish_add(&title, &file)));
|
||||
});
|
||||
}
|
||||
|
||||
fn finish_add(&self, title: &str, file: &std::path::Path) {
|
||||
if file.is_dir() { return self.toast(format!("{} is a folder: pick the file that starts the game", tilde(file))); }
|
||||
let id = match state::add_custom(title, file, false) {
|
||||
Ok(id) => id,
|
||||
Err(err) => return self.toast(format!("Could not add {title}: {err}")),
|
||||
};
|
||||
self.reload();
|
||||
let idx = self.entries.borrow().iter().position(|e| e.id == id);
|
||||
if let Some(i) = idx { self.open_detail(i as i32); }
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let runnable = std::fs::metadata(file).map(|m| m.permissions().mode() & 0o111 != 0).unwrap_or(false);
|
||||
self.toast(if runnable { format!("Added {title}") } else {
|
||||
format!("Added {title}, but {} is not executable: Play will fail until it is (chmod +x)", tilde(file))
|
||||
});
|
||||
}
|
||||
|
||||
/// Scan everything again (after adding a game): new list, shelves, counts; covers load again as cards ask.
|
||||
fn reload(&self) {
|
||||
let mut entries = scan::full(&self.folders, 4);
|
||||
let st = state::load();
|
||||
state::apply(&mut entries, &st);
|
||||
*self.state.borrow_mut() = st;
|
||||
*self.entries.borrow_mut() = entries;
|
||||
self.gen.set(self.gen.get() + 1);
|
||||
self.requested.borrow_mut().clear();
|
||||
self.loaded.borrow_mut().clear();
|
||||
self.backdrop_for.set(-1);
|
||||
let rows: Vec<Game> = self.entries.borrow().iter().map(|e| self.row(e, None)).collect();
|
||||
self.games.set_vec(rows);
|
||||
self.fill_static();
|
||||
self.rebuild_shelves();
|
||||
self.requery();
|
||||
}
|
||||
|
||||
// ---- artwork ----
|
||||
/// "Change artwork": the desktop's file dialog runs on a thread of its own; the picked file becomes the cover.
|
||||
fn change_art(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
let hint = format!("or from a terminal: summit art {} cover.png", e.id);
|
||||
if self.headless { return self.toast(format!("Headless render, no file dialog ({hint})")); }
|
||||
let kde = display::detect_desktop() == display::Desktop::Kde;
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| "/".into());
|
||||
let start = [format!("{home}/Pictures"), home.clone()].into_iter().find(|d| std::path::Path::new(d).is_dir()).unwrap_or(home);
|
||||
let Some(argv) = data::art_picker(kde, summit_core::doctor::on_path, &start) else {
|
||||
return self.toast(format!("No file dialog found: install zenity or kdialog, {hint}"));
|
||||
};
|
||||
let id = e.id.clone();
|
||||
std::thread::spawn(move || {
|
||||
let out = std::process::Command::new(&argv[0]).args(&argv[1..]).stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null()).output();
|
||||
let picked = match out {
|
||||
Ok(o) if o.status.success() => Some(String::from_utf8_lossy(&o.stdout).trim_end_matches(['\n', '\r']).to_string()).filter(|p| !p.is_empty()),
|
||||
_ => None, // cancelled
|
||||
};
|
||||
if let Some(path) = picked { let _ = slint::invoke_from_event_loop(move || with_app(|a| a.set_art(&id, PathBuf::from(path)))); }
|
||||
});
|
||||
}
|
||||
|
||||
fn set_art(&self, id: &str, path: PathBuf) {
|
||||
let Some(idx) = self.entries.borrow().iter().position(|e| e.id == id) else { return };
|
||||
let title = self.entries.borrow()[idx].title.clone();
|
||||
if art::cover(&path).is_none() { return self.toast(format!("{} is not an image Summit can read (PNG, JPEG or WebP)", tilde(&path))); }
|
||||
let text = match path.canonicalize().map_err(|e| e.to_string()).and_then(|p| state::path_text(&p).map_err(|e| e.to_string())) {
|
||||
Ok(t) => t, Err(err) => return self.toast(format!("Could not use {}: {err}", tilde(&path))),
|
||||
};
|
||||
// update() loads first: a change made elsewhere while the dialog was open is kept
|
||||
match state::update(|st| { st.artwork.insert(id.to_string(), text); }) {
|
||||
Ok(st) => *self.state.borrow_mut() = st,
|
||||
Err(err) => return self.toast(format!("Could not save the artwork: {err}")),
|
||||
}
|
||||
self.requested.borrow_mut().remove(&idx);
|
||||
self.want_cover(idx);
|
||||
if self.backdrop_for.get() == idx as i64 { self.backdrop_for.set(-1); self.focus_game(idx as i32); }
|
||||
self.toast(format!("New cover for {title}"));
|
||||
}
|
||||
|
||||
// ---- launch profile ----
|
||||
fn toggle_enhance(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
@@ -325,10 +460,9 @@ impl App {
|
||||
fn toggle_pin(&self, idx: i32) {
|
||||
let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return };
|
||||
// Load first, so a pin made from the command line while the window is open is not lost.
|
||||
let mut st = state::load();
|
||||
let pinned = st.toggle_pin(&e.id);
|
||||
match state::save(&st) {
|
||||
Ok(()) => {
|
||||
let mut pinned = false;
|
||||
match state::update(|st| pinned = st.toggle_pin(&e.id)) {
|
||||
Ok(st) => {
|
||||
*self.state.borrow_mut() = st;
|
||||
self.refresh_row(idx as usize);
|
||||
self.rebuild_shelves();
|
||||
@@ -423,6 +557,7 @@ fn dirs_log() -> Option<PathBuf> {
|
||||
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 {
|
||||
@@ -439,6 +574,7 @@ fn pick(v: &str, names: &[String]) -> Option<i32> {
|
||||
pub fn build(headless: bool) -> Rc<App> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let folders: Vec<PathBuf> = args.iter().filter(|a| !a.starts_with("--")).map(Into::into).collect();
|
||||
let scan_folders = folders.clone();
|
||||
let mut entries = scan::full(&folders, 4);
|
||||
let st = state::load();
|
||||
state::apply(&mut entries, &st);
|
||||
@@ -454,6 +590,7 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
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(), editing: RefCell::new(None),
|
||||
folders: scan_folders, gen: Cell::new(0),
|
||||
});
|
||||
APP.with(|a| *a.borrow_mut() = Some(app.clone()));
|
||||
|
||||
@@ -479,6 +616,10 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
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_change_art(|i| with_app(|a| a.change_art(i)));
|
||||
lib.on_add_game(|i| with_app(|a| a.add_game(i)));
|
||||
lib.on_open_clips(|| with_app(|a| a.open_clips()));
|
||||
lib.set_clips_dir(summit_core::engine::clips_dir().map(|d| tilde(&d)).unwrap_or_default().into());
|
||||
lib.on_prof_set(|r, v| with_app(|a| a.prof_set(r, v)));
|
||||
let session = display::detect_session();
|
||||
let portal = if session == display::Session::Wayland && !headless { hotkey::portal_has_global_shortcuts() } else { None };
|
||||
@@ -494,7 +635,7 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
app.rebuild_shelves();
|
||||
app.requery();
|
||||
if let Some(v) = env("SUMMIT_VIEW").or_else(|| env("SUMMIT_TAB")).and_then(|v| pick(&v, &names(&["home", "library", "unfiltered", "settings"]))) { app.ui.invoke_goto(v.clamp(0, 3)); }
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { app.ui.set_lib_focus(v); app.ui.set_unf_focus(v); app.ui.set_settings_row(v.clamp(0, 8)); }
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { app.ui.set_lib_focus(v); app.ui.set_unf_focus(v); app.ui.set_settings_row(v.clamp(0, 9)); }
|
||||
if let Some(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)));
|
||||
|
||||
@@ -68,8 +68,7 @@ impl Repeater {
|
||||
}
|
||||
}
|
||||
|
||||
fn reader(path: std::path::PathBuf, id: usize, tx: Sender<(usize, Option<Event>)>) {
|
||||
let Ok(mut f) = std::fs::File::open(&path) else { let _ = tx.send((id, None)); return };
|
||||
fn reader(mut f: std::fs::File, id: usize, tx: Sender<(usize, Option<Event>)>) {
|
||||
let mut buf = [0u8; 8];
|
||||
while f.read_exact(&mut buf).is_ok() {
|
||||
if let Some(e) = decode(&buf) { if tx.send((id, Some(e))).is_err() { return; } }
|
||||
@@ -95,16 +94,18 @@ impl Pads {
|
||||
fn scan(&mut self) {
|
||||
for id in 0..8 {
|
||||
let path = std::path::PathBuf::from(format!("/dev/input/js{id}"));
|
||||
if !self.open[id] && path.exists() {
|
||||
self.open[id] = true;
|
||||
let tx = self.tx.clone();
|
||||
let _ = std::thread::Builder::new().name(format!("summit-pad{id}")).spawn(move || reader(path, id, tx));
|
||||
}
|
||||
if self.open[id] || !path.exists() { continue; }
|
||||
// Opened here, so a device that cannot be opened (no permission yet) is tried again on the next scan
|
||||
// without starting a thread that fails at once.
|
||||
let Ok(f) = std::fs::File::open(&path) else { continue };
|
||||
self.open[id] = true;
|
||||
let tx = self.tx.clone();
|
||||
let _ = std::thread::Builder::new().name(format!("summit-pad{id}")).spawn(move || reader(f, id, tx));
|
||||
}
|
||||
}
|
||||
pub fn connected(&self) -> bool { self.open.iter().any(|o| *o) }
|
||||
pub fn poll(&mut self, now: Instant) -> Vec<&'static str> {
|
||||
if self.last_scan.map_or(true, |t| now.duration_since(t) > Duration::from_secs(2)) { self.last_scan = Some(now); self.scan(); }
|
||||
if self.last_scan.is_none_or(|t| now.duration_since(t) > Duration::from_secs(2)) { self.last_scan = Some(now); self.scan(); }
|
||||
let mut keys = vec![];
|
||||
while let Ok((id, ev)) = self.rx.try_recv() {
|
||||
match ev {
|
||||
|
||||
@@ -115,6 +115,7 @@ export component DetailView inherits Rectangle {
|
||||
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 (root.btn == 4) { Lib.change-art(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; }
|
||||
@@ -149,16 +150,16 @@ export component DetailView inherits Rectangle {
|
||||
if root.g.pinned: Tag { text: "Pinned to Home"; tint: Theme.p.accent; }
|
||||
}
|
||||
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";
|
||||
Btn { h: 56px; primary: true; enabled: root.d.can-play; text: root.d.play-label; icon: root.d.play-label == "INSTALL" ? Icons.download : root.d.play-label == "ADD" ? Icons.plus : Icons.play; icon-solid: root.d.play-label == "PLAY";
|
||||
focused: root.open && root.btn == 0; clicked => { Lib.play(root.d.idx); } }
|
||||
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; }
|
||||
Btn { h: 56px; text: root.compact || !root.wide ? "" : "Change artwork"; icon: Icons.picture; focused: root.open && root.btn == 4; clicked => { Lib.change-art(root.d.idx); } }
|
||||
}
|
||||
Text {
|
||||
text: root.btn == 4 ? "Changing artwork here is not built yet. For now: summit art " + root.g.id + " cover.png"
|
||||
text: root.btn == 4 ? "Pick a cover image (PNG, JPEG or WebP; portrait 2:3 looks best). Summit keeps a link to the file, so leave it where it is."
|
||||
: root.btn == 3 ? "Monitor, resolution, refresh rate, fullscreen, focus, upscaler, frame generation and target rate for this game."
|
||||
: 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 + "." : "");
|
||||
|
||||
@@ -122,7 +122,7 @@ export component HomeView inherits Rectangle {
|
||||
HorizontalLayout { alignment: center; LogoMark { size: 88px; } }
|
||||
Text { text: "No games yet"; color: Theme.p.text; font-size: Theme.t-2xl; font-weight: 800; horizontal-alignment: center; }
|
||||
Text { text: "Summit looks in Steam, Heroic and Lutris. Nothing was found on this machine."; color: Theme.p.dim; font-size: Theme.t-md; horizontal-alignment: center; }
|
||||
Text { text: "Add anything by hand: summit add \"My Game\" ~/Games/mygame/run.sh"; color: Theme.p.faint; font-size: Theme.t-sm; horizontal-alignment: center; }
|
||||
Text { text: "Add anything by hand: Library > + Add a game (or summit add \"My Game\" ~/Games/mygame/run.sh)"; color: Theme.p.faint; font-size: Theme.t-sm; horizontal-alignment: center; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ export component HomeView inherits Rectangle {
|
||||
}
|
||||
HorizontalLayout {
|
||||
alignment: start; spacing: 12px; padding-top: 4px;
|
||||
Btn { h: Theme.big ? 56px : 48px; primary: true; enabled: root.g.action != ""; text: root.g.action == "" ? "PLAY" : root.g.action; icon: root.g.action == "INSTALL" ? Icons.download : Icons.play; icon-solid: root.g.action != "INSTALL";
|
||||
Btn { h: Theme.big ? 56px : 48px; primary: true; enabled: root.g.action != ""; text: root.g.action == "" ? "PLAY" : root.g.action; icon: root.g.action == "INSTALL" ? Icons.download : root.g.action == "ADD" ? Icons.plus : Icons.play; icon-solid: root.g.action == "" || root.g.action == "PLAY";
|
||||
focused: root.active && root.srow == -1 && root.btn == 0; clicked => { root.hero-action(0); } }
|
||||
Btn { h: Theme.big ? 56px : 48px; text: "Details"; icon: Icons.info; focused: root.active && root.srow == -1 && root.btn == 1; clicked => { root.hero-action(1); } }
|
||||
Btn { h: Theme.big ? 56px : 48px; text: root.g.pinned ? "Pinned" : "Pin"; icon: Icons.pin; icon-solid: root.g.pinned; focused: root.active && root.srow == -1 && root.btn == 2; clicked => { root.hero-action(2); } }
|
||||
|
||||
@@ -67,7 +67,7 @@ component EmptyState inherits Rectangle {
|
||||
export component LibraryView inherits Rectangle {
|
||||
in property <bool> active;
|
||||
in-out property <int> zone: 1; // 0 toolbar, 1 items
|
||||
in-out property <int> tool: 0; // 0..2 filter chips, 3 sort chip, 4 search
|
||||
in-out property <int> tool: 0; // 0..2 filter chips, 3 sort chip, 4 add a game, 5 search
|
||||
in-out property <int> sel: 0;
|
||||
out property <bool> typing: search.typing;
|
||||
callback exit-up();
|
||||
@@ -84,7 +84,7 @@ export component LibraryView inherits Rectangle {
|
||||
property <length> top-pad: root.list ? 0px : 12px;
|
||||
property <[string]> sorts: ["Recently played", "Most played", "A to Z"];
|
||||
|
||||
public function focus-search() { root.zone = 0; root.tool = 4; search.grab(); }
|
||||
public function focus-search() { root.zone = 0; root.tool = 5; search.grab(); }
|
||||
function reveal() {
|
||||
if (root.zone != 1) { return; }
|
||||
if (root.list) { list-view.show(root.sel); } else { grid-view.show(Math.floor(root.sel / root.cols)); }
|
||||
@@ -92,13 +92,15 @@ export component LibraryView inherits Rectangle {
|
||||
function activate(t: int) {
|
||||
if (t <= 2) { Lib.filter = t; Lib.query(); }
|
||||
else if (t == 3) { Lib.sort = Math.mod(Lib.sort + 1, 3); Lib.query(); }
|
||||
else if (t == 4) { Lib.add-game(-1); }
|
||||
else { search.grab(); }
|
||||
}
|
||||
changed n => { if (root.sel > Math.max(0, root.n - 1)) { root.sel = 0; } if (root.n == 0) { root.zone = 0; } }
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (root.n == 0) { root.zone = 0; } // nothing to focus below: an empty library starts empty, so `changed n` never ran
|
||||
if (root.zone == 0) {
|
||||
if (e.text == Key.LeftArrow) { root.tool = Math.max(0, root.tool - 1); }
|
||||
else if (e.text == Key.RightArrow) { root.tool = Math.min(4, root.tool + 1); }
|
||||
else if (e.text == Key.RightArrow) { root.tool = Math.min(5, root.tool + 1); }
|
||||
else if (e.text == Key.DownArrow) { if (root.n > 0) { root.zone = 1; root.reveal(); } }
|
||||
else if (e.text == Key.UpArrow) { root.exit-up(); }
|
||||
else if (e.text == Key.Return || e.text == " ") { root.activate(root.tool); }
|
||||
@@ -135,7 +137,7 @@ export component LibraryView inherits Rectangle {
|
||||
Text { x: Theme.pad + 104px; y: 30px; text: root.n == Lib.total-games ? root.n + " games" : root.n + " of " + Lib.total-games + " games"; color: Theme.p.dim; font-size: Theme.t-sm; }
|
||||
search := SearchBox {
|
||||
x: root.width - Theme.pad - self.width; y: 16px; width: Math.min(320px, root.width - 2 * Theme.pad - 260px);
|
||||
focused: root.active && root.zone == 0 && root.tool == 4;
|
||||
focused: root.active && root.zone == 0 && root.tool == 5;
|
||||
done => { root.refocus(); if (root.n > 0) { root.zone = 1; root.sel = 0; root.reveal(); } }
|
||||
}
|
||||
HorizontalLayout {
|
||||
@@ -145,11 +147,13 @@ export component LibraryView inherits Rectangle {
|
||||
Chip { text: "Not installed"; active: Lib.filter == 2; focused: root.active && root.zone == 0 && root.tool == 2; clicked => { root.activate(2); } }
|
||||
Rectangle { width: 16px; Rectangle { x: 8px; y: 7px; width: 1px; height: 20px; background: Theme.p.border; } }
|
||||
Chip { text: "Sort: " + root.sorts[Lib.sort]; focused: root.active && root.zone == 0 && root.tool == 3; clicked => { root.activate(3); } }
|
||||
Rectangle { width: 16px; Rectangle { x: 8px; y: 7px; width: 1px; height: 20px; background: Theme.p.border; } }
|
||||
Chip { text: "+ Add a game"; focused: root.active && root.zone == 0 && root.tool == 4; clicked => { root.activate(4); } }
|
||||
}
|
||||
|
||||
if root.n == 0: EmptyState { y: root.head-h; height: root.height - root.head-h;
|
||||
title: Lib.total-games == 0 ? "No games yet" : "Nothing matches";
|
||||
hint: Lib.total-games == 0 ? "Summit found no games on this machine. Add one with: summit add \"My Game\" /path/to/game" : "Try another filter, or clear the search."; }
|
||||
hint: Lib.total-games == 0 ? "Summit found no games on this machine. Add one with + Add a game above (it asks for the file that starts it)." : "Try another filter, or clear the search."; }
|
||||
|
||||
// ---- cover grid: one ListView row per grid row, so only the rows on screen exist ----
|
||||
grid-view := ListView {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Settings: layout, theme, UI scale, motion, clip lengths and the default enhance profile.
|
||||
import { Theme, Palette } from "theme.slint";
|
||||
import { Lib, Prefs, Icon, Icons, Segmented, SliderBar, FocusRing } from "widgets.slint";
|
||||
import { Lib, Prefs, Icon, Icons, Segmented, SliderBar, FocusRing, Btn } from "widgets.slint";
|
||||
|
||||
component Section inherits Rectangle {
|
||||
in property <string> title;
|
||||
@@ -48,7 +48,7 @@ export component SettingsView inherits Rectangle {
|
||||
property <length> cw: Math.min(root.width - 2 * Theme.pad, 1040px);
|
||||
property <length> cx: Math.max(Theme.pad, (root.width - root.cw) / 2);
|
||||
pure function ry(i: int) -> length {
|
||||
return i == 0 ? 136px : i == 1 ? 216px : i == 2 ? 384px : i == 3 ? 520px : i == 4 ? 600px : i == 5 ? 736px : i == 6 ? 816px : i == 7 ? 952px : 1032px;
|
||||
return i == 0 ? 136px : i == 1 ? 216px : i == 2 ? 384px : i == 3 ? 520px : i == 4 ? 600px : i == 5 ? 736px : i == 6 ? 816px : i == 7 ? 896px : i == 8 ? 1032px : 1112px;
|
||||
}
|
||||
pure function rh(i: int) -> length { return i == 1 ? 160px : 72px; }
|
||||
function reveal() {
|
||||
@@ -65,12 +65,14 @@ export component SettingsView inherits Rectangle {
|
||||
else if (root.srow == 4) { Theme.style = Math.clamp(Theme.style + d, 0, 2); }
|
||||
else if (root.srow == 5) { Prefs.replay = Math.clamp(Prefs.replay + d, 0, 5); Prefs.clip = Math.min(Prefs.clip, Prefs.replay); }
|
||||
else if (root.srow == 6) { Prefs.clip = Math.clamp(Prefs.clip + d, 0, Prefs.replay); }
|
||||
else if (root.srow == 7) { Prefs.upscaler = Math.clamp(Prefs.upscaler + d, 0, 2); }
|
||||
else if (root.srow == 7) { return; }
|
||||
else if (root.srow == 8) { Prefs.upscaler = Math.clamp(Prefs.upscaler + d, 0, 2); }
|
||||
else { Prefs.framegen = Math.clamp(Prefs.framegen + d, 0, 1); }
|
||||
root.save();
|
||||
}
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (e.text == Key.DownArrow) { root.srow = Math.min(8, root.srow + 1); }
|
||||
if (e.text == Key.DownArrow) { root.srow = Math.min(9, root.srow + 1); }
|
||||
else if ((e.text == Key.Return || e.text == " ") && root.srow == 7) { Lib.open-clips(); }
|
||||
else if (e.text == Key.UpArrow) { if (root.srow == 0) { root.exit-up(); } else { root.srow -= 1; } }
|
||||
else if (e.text == Key.RightArrow) { root.adjust(1); }
|
||||
else if (e.text == Key.LeftArrow) { root.adjust(-1); }
|
||||
@@ -80,7 +82,7 @@ export component SettingsView inherits Rectangle {
|
||||
}
|
||||
|
||||
flick := Flickable {
|
||||
width: root.width; height: root.height; content-width: root.width; content-height: 1180px;
|
||||
width: root.width; height: root.height; content-width: root.width; content-height: 1260px;
|
||||
animate content-y { duration: Theme.ms(220); easing: ease-out; }
|
||||
Text { x: root.cx; y: 20px; text: "Settings"; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; }
|
||||
Text { x: root.cx; y: 58px; width: root.cw; text: "Saved to " + Prefs.file + " as you change them."; color: Theme.p.dim; font-size: Theme.t-sm; overflow: elide; }
|
||||
@@ -119,13 +121,17 @@ export component SettingsView inherits Rectangle {
|
||||
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. 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(7); width: root.cw; label: "Clips folder"; hint: Lib.clips-dir + "/<game>/ (Enter opens it)"; focused: root.active && root.srow == 7; hit => { root.srow = 7; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 160px; text: "Open"; icon: Icons.film; focused: root.active && root.srow == 7; clicked => { root.srow = 7; Lib.open-clips(); } }
|
||||
}
|
||||
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; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 2 * 100px + 8px; options: ["None", "RIFE"]; value <=> Prefs.framegen; changed => { root.srow = 8; root.save(); } }
|
||||
|
||||
Section { x: root.cx; y: 984px; width: root.cw; title: "ENHANCE DEFAULTS"; icon: Icons.monitor; }
|
||||
Row { x: root.cx; y: root.ry(8); width: root.cw; label: "Default upscaler"; hint: "Stored in the \"default\" profile for summit enhance. Each game has its own on its page (Profile)."; focused: root.active && root.srow == 8; hit => { root.srow = 8; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 3 * 100px + 8px; options: ["None", "FSR", "RTX VSR"]; value <=> Prefs.upscaler; changed => { root.srow = 8; root.save(); } }
|
||||
}
|
||||
Text { x: root.cx; y: 1124px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
Row { x: root.cx; y: root.ry(9); width: root.cw; label: "Default frame generation"; hint: "RIFE needs an NVIDIA GPU and the engine's Python environment."; focused: root.active && root.srow == 9; hit => { root.srow = 9; }
|
||||
Segmented { x: parent.width - self.width - 16px; y: 16px; width: 2 * 100px + 8px; options: ["None", "RIFE"]; value <=> Prefs.framegen; changed => { root.srow = 9; root.save(); } }
|
||||
}
|
||||
Text { x: root.cx; y: 1204px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export struct Game {
|
||||
c1: color, // fallback gradient, from the title
|
||||
c2: color,
|
||||
reasons: string, // detection reasons on one line
|
||||
action: string, // "Play", "Install", or "" when Summit cannot start it yet
|
||||
action: string, // "PLAY", "INSTALL", "ADD" (found on disk), or "" when Summit cannot start it yet
|
||||
}
|
||||
|
||||
export struct URow { header: bool, label: string, count: int, idx: int }
|
||||
@@ -89,6 +89,10 @@ export global Lib {
|
||||
callback open-profile(int);
|
||||
callback prof-set(int, int); // row, option index
|
||||
callback toggle-enhance(int);
|
||||
callback change-art(int);
|
||||
callback add-game(int); // -1: Add a game; an entry found on disk: add that folder's game
|
||||
in property <string> clips-dir; // where saved clips go
|
||||
callback open-clips(); // pick a cover image with the desktop's file dialog
|
||||
in property <string> hotkey-status; // the global save-clip key, for the settings page
|
||||
}
|
||||
|
||||
@@ -116,6 +120,7 @@ export global Icons {
|
||||
out property <string> search: "M11 4a7 7 0 1 0 0 14a7 7 0 0 0 0-14z M20.5 20.5l-4.4-4.4";
|
||||
out property <string> play: "M7 4.5 L19.5 12 L7 19.5 Z";
|
||||
out property <string> pin: "M7 3.5 H17 V20.5 L12 16.5 L7 20.5 Z";
|
||||
out property <string> plus: "M12 5 V19 M5 12 H19";
|
||||
out property <string> check: "M5 12.5 L10 17.5 L19 7";
|
||||
out property <string> download: "M12 4 V15 M7 10.5 L12 15.5 L17 10.5 M5 20 H19";
|
||||
out property <string> picture: "M4 5 H20 V19 H4 Z M4 16 L9 11 L13 15 L16 12 L20 16 M8.5 8.5 H8.51";
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Polish pass after the release candidate (2026-11-24)
|
||||
|
||||
Work done on `ap/release-candidate` after the RC report, before the owner's own testing. Each item has its own commit.
|
||||
|
||||
## Added or fixed
|
||||
|
||||
| Item | Was | Now | How it was checked |
|
||||
|---|---|---|---|
|
||||
| Signal to `summit run` (audit: Medium, not fixed) | Killing `summit` alone left the game, the engine and a changed display mode | SIGTERM/SIGINT/SIGHUP stop the engine and the game, then the normal exit path restores the mode; exit 128+signal; output can't panic on a closed terminal | Unit tests; `kill -TERM/-HUP/-INT` to summit with a game script that starts a child (both gone, exit 143/129/130); `--enhance` with a stand-in engine (both gone). **Not tried**: the mode restore on a real display |
|
||||
| `supervise()` on a `try_wait` error (audit: Low) | Returned and left both running | Stops both, then returns the error | Code review only (the error can't be produced on demand) |
|
||||
| Clips folder | `~/Videos/SmoovPlay/SmoovPlay <date>.mp4`, toast with `\` | `~/Videos/Summit/<game>/<game> <date>.mp4` (game name from the launcher's title); toast uses `/`; before & after label says Summit | pytest (`test_clip_folder.py`); not a real clip save |
|
||||
| Heroic | Play said "not built" | Epic and GOG games start through `xdg-open heroic://launch?appName=..&runner=..`; Flatpak Heroic's config is scanned too | Unit tests, `summit scan` on a fake Flatpak config. **Not tried** with a real Heroic |
|
||||
| Change artwork | Button disabled, "Soon" | kdialog/zenity file dialog, the cover and backdrop reload | Xvfb, synthetic keys, a stand-in zenity: state.json got the file, the screen showed the new cover |
|
||||
| `state.json` races (audit: Low) | Last writer wins | Every write is load-change-save under `flock` | Unit test (8 threads); 2 x 40 parallel `summit pin`: 80/80 (77/80 before) |
|
||||
| Controller device without permission (audit: Low) | A new failing thread every 2 s | Opened on the scan; a thread only for an open device | Builds; no real controller |
|
||||
| Clips folder in Settings | — | A row shows the path; Enter / Open runs `xdg-open` on it | Headless renders |
|
||||
| Failed launch from the launcher | Silent (only `~/.cache/summit/last-run.log`) | Toast: "<game> did not start: <error>" | Xvfb: a non-executable entry showed the Permission denied message |
|
||||
| clippy | 9 warnings | 0 | `cargo clippy --workspace --all-targets` |
|
||||
| Engine messages | "SmoovPlay needs...", frame-spacing toasts | Say Summit (only the ones a Linux user sees) | `py_compile`, pytest |
|
||||
| Installer: build deps | A fresh Debian/Ubuntu build of `summit-gui` would stop: the fontconfig crate's build script needs `fontconfig.pc` (`libfontconfig1-dev`), which was not installed | Build deps include the fontconfig headers on all four families | Read the crate's `build.rs` (`pkg_config::find_library("fontconfig").unwrap()`); `sh -n`, shellcheck |
|
||||
| Installer: runtime tools | `ffmpeg` (Enhance's capture), `xrandr`, `xdg-open`, `zenity` were assumed | Installed in their own step; a failure only warns, and the end of the install lists what is still missing | Clean `ubuntu:24.04` container: the step installed them, and with a broken mirror it warned and went on |
|
||||
| Installer: app menu | No `.desktop` entry or icon (only the `.deb` had them) | `summit.desktop` (Exec = the installed binary's full path) and the icon; `--uninstall` removes both | Functions run against a scratch prefix: files written, Exec right, uninstall left no file |
|
||||
| Installer: RIFE model | Downloaded on the first Enhance, into the engine folder; an install as root left that folder unwritable for the user, so that download would fail | The default model (4.22.lite, 21 MB) is fetched during install; skipped when present | Scratch run: a 21 MB torch zip checkpoint; a second call did nothing |
|
||||
| Installer: rustup/uv failure | `curl | sh` succeeds when curl fails, so the install went on and died later at `cargo: not found` | Stops right away, saying what to install by hand | Seen in the container run (network reset), then fixed; `sh -n`, shellcheck |
|
||||
| Installer: `SUMMIT_SRC_DIR` | An existing checkout was switched to `main` and pulled | Built as it is (no clone, no pull) | Scratch-prefix runs |
|
||||
| `summit doctor` | Session and monitors only | Plus a readiness list: engine, venv, torch + CUDA (with the GPU name), the model, ffmpeg, xrandr, xdg-open, a file dialog; each missing one names what it turns off | Unit tests; run on the build machine |
|
||||
| Add a game | Only `summit add` in a terminal; Play on a folder found on disk was disabled | Library toolbar **+ Add a game**; **ADD** on found folders. File dialog, then a name dialog (guess from the folder name), then the library reloads and the page opens. Warns if the file is not executable | Xvfb with a stand-in zenity: both ways in, `state.json` written, the found folder replaced (no duplicate), toast shown |
|
||||
| Empty library and the keyboard | Arrows in an empty library moved focus to item -1; the toolbar was unreachable by keys | Keys go to the toolbar when there is nothing below | Xvfb: Tab, Right x4 put the focus ring on Add a game |
|
||||
| Covers after a reload | — (no reload existed) | Cover jobs carry a generation; one loaded for the old list is dropped | Builds; by reading |
|
||||
|
||||
Tests after this second pass: `cargo test --workspace` 1 + 98 + 19 pass; clippy clean. **Not done**: a whole `install.sh` run in the clean container. This host ran out of disk (2.7 GB free; Rust, the build and torch need more), so the parts were tested on their own.
|
||||
|
||||
Tests at the end of the first pass: `cargo test --workspace` 1 + 92 + 19 pass; engine pytest 31 passed, 1 skipped.
|
||||
|
||||
## Worth checking in your own test
|
||||
|
||||
1. `install.sh` on a clean machine, then `summit doctor`: every line should be `ok` on the GPU machine. Summit should be in the app menu.
|
||||
2. Library > **+ Add a game** with the real kdialog on KDE: pick a game's binary, change the name, Play.
|
||||
3. `summit-gui` on the real desktop: a game's page, **Change artwork** (needs `kdialog` on KDE or `zenity`), then Settings > **Clips folder** > Open.
|
||||
4. Play Voidrunner with Enhance, Ctrl+Alt+R: the clip should be in `~/Videos/Summit/Voidrunner/` and the toast should say `Summit/Voidrunner/...`.
|
||||
5. A profile that changes the mode, then `kill <pid of summit>` while the game runs: the game and the engine should stop and the mode should come back.
|
||||
6. If Heroic is installed: Play on an Epic or GOG game.
|
||||
7. Play on something broken (for example an entry whose file is not executable): a toast should say why.
|
||||
|
||||
## Still open
|
||||
|
||||
- Focus ("raise the game window") is still stored only.
|
||||
- Enhance for Steam games through Proton, Lutris and Heroic games; Wayland capture.
|
||||
- `steam-add` LaunchOptions quoting; profile file names for ids that differ only in punctuation; KDE Wayland monitor names with dots (all from the audit, unchanged).
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -646,14 +646,14 @@ class Pipeline:
|
||||
print("[pipeline] game dipping below 30 fps: timing its frames as they arrived")
|
||||
if hasattr(sink, "toast") and "dips" not in toasted:
|
||||
toasted.add("dips")
|
||||
sink.toast("Game dipping below 30 fps: SmoovPlay is spacing its frames by when they "
|
||||
sink.toast("Game dipping below 30 fps: Summit is spacing its frames by when they "
|
||||
"arrived (Dip smoothing)", 6.0)
|
||||
elif timed:
|
||||
unshown = None
|
||||
print(f"[pipeline] game at about {timeline.fps()} fps: evening out its frames")
|
||||
if hasattr(sink, "toast") and "even" not in toasted:
|
||||
toasted.add("even")
|
||||
sink.toast(f"Game at about {timeline.fps()} fps: SmoovPlay is spacing its frames evenly "
|
||||
sink.toast(f"Game at about {timeline.fps()} fps: Summit is spacing its frames evenly "
|
||||
"(Even out 40-60 fps)", 6.0)
|
||||
else:
|
||||
sched = CadenceScheduler() # starts afresh, from the next new frame
|
||||
|
||||
+18
-10
@@ -9,7 +9,7 @@ oldest can be dropped and any stretch cut out at a keyframe (one every second):
|
||||
- sound: the game's sound (PS5 Remote Play through chiaki-ng's frame tap, chiaki_tap/frametap.h, or a capture
|
||||
card's), timed the same way, so it meets both pictures.
|
||||
|
||||
Saving (R in the video window, or Ctrl+Alt+R from anywhere) copies a stretch into an MP4 in Videos\\SmoovPlay without
|
||||
Saving (R in the video window, or Ctrl+Alt+R from anywhere) copies a stretch into an MP4 in Videos\\Summit\\<game> without
|
||||
encoding it again: a second or two. A before & after video (B, Ctrl+Alt+B, or the "Saved clip" setting) is encoded
|
||||
afresh by `python -m framegen.replay compose`, in a process of its own at low priority, so play isn't disturbed.
|
||||
|
||||
@@ -278,12 +278,19 @@ def _cut(ring: list, start: int, end: int, at_key: bool = True) -> list:
|
||||
|
||||
|
||||
# ---- saving ---------------------------------------------------------------------------------------------------
|
||||
def game_name() -> str:
|
||||
"""The game being played (SUMMIT_GAME, set by `summit run`), made safe as a folder and file name; "" if unknown."""
|
||||
name = "".join(" " if c in '<>:"/\\|?*' or ord(c) < 32 else c for c in os.environ.get("SUMMIT_GAME", ""))
|
||||
return " ".join(name.split()).strip(" .")[:100]
|
||||
|
||||
|
||||
def videos_folder() -> Path:
|
||||
"""Where clips go: SMOOVPLAY_REPLAY_DIR if set, else SmoovPlay in the Videos folder (wherever Windows keeps it;
|
||||
XDG_VIDEOS_DIR on Linux)."""
|
||||
"""Where clips go: SMOOVPLAY_REPLAY_DIR if set, else Summit in the Videos folder (wherever Windows keeps it;
|
||||
XDG_VIDEOS_DIR on Linux), in a folder for the game when Summit says which one is running."""
|
||||
if os.environ.get("SMOOVPLAY_REPLAY_DIR"):
|
||||
return Path(os.environ["SMOOVPLAY_REPLAY_DIR"])
|
||||
return oslayer.videos_dir() / "SmoovPlay"
|
||||
root = oslayer.videos_dir() / "Summit"
|
||||
return root / game_name() if game_name() else root
|
||||
|
||||
|
||||
def _unique(path: Path) -> Path:
|
||||
@@ -303,7 +310,7 @@ def _dur(secs: float) -> str:
|
||||
|
||||
|
||||
def _short(path: Path) -> str:
|
||||
return f"{path.parent.parent.name}\\{path.parent.name}\\{path.name}"
|
||||
return os.sep.join((path.parent.parent.name, path.parent.name, path.name))
|
||||
|
||||
|
||||
def _snap_fps(fps: float) -> int:
|
||||
@@ -861,9 +868,10 @@ class Recorder:
|
||||
folder = self.out_dir or videos_folder()
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
stamp = time.strftime("%Y-%m-%d %H-%M-%S")
|
||||
prefix = game_name() or "Summit"
|
||||
saved = []
|
||||
if kind in ("smoovplay", "both"):
|
||||
path = _unique(folder / f"SmoovPlay {stamp}.mp4")
|
||||
path = _unique(folder / f"{prefix} {stamp}.mp4")
|
||||
t0 = time.perf_counter()
|
||||
to_mp4(path, (head, after), sound, base, end)
|
||||
print(f"[replay] saved {secs:.1f} s -> {path} ({path.stat().st_size / 1e6:.0f} MB, "
|
||||
@@ -879,8 +887,8 @@ class Recorder:
|
||||
span_b = max(1e-6, (before[-1][0] - max(base, before[0][0])) / TB)
|
||||
n_b = sum(1 for p in before if p[0] >= base)
|
||||
labels = (f"Original {_snap_fps(max(1, n_b - 1) / span_b)} fps",
|
||||
f"SmoovPlay {_snap_fps((len(after) - 1) / max(1e-6, secs))} fps")
|
||||
path = _unique(folder / f"SmoovPlay {stamp} before and after.mp4")
|
||||
f"Summit {_snap_fps((len(after) - 1) / max(1e-6, secs))} fps")
|
||||
path = _unique(folder / f"{prefix} {stamp} before and after.mp4")
|
||||
tmp = Path(tempfile.mkdtemp(prefix="smoovplay-replay-"))
|
||||
_write_ts(tmp / "after.ts", head, after)
|
||||
_write_ts(tmp / "before.ts", bhead, before)
|
||||
@@ -1044,7 +1052,7 @@ def _yuv(frame):
|
||||
|
||||
|
||||
def compose(after: str, before: str, out_path: str, sound: str | None = None, layout: str = "split",
|
||||
labels: tuple = ("Original", "SmoovPlay"), encoder: str | None = None) -> float:
|
||||
labels: tuple = ("Original", "Summit"), encoder: str | None = None) -> float:
|
||||
"""A before & after video: `before`'s frames (the game's own, held until the next) and `after`'s (every frame
|
||||
shown), at after's times, split down the middle or side by side, with labels; `sound` copied in. Returns its
|
||||
length in seconds."""
|
||||
@@ -1153,7 +1161,7 @@ def main(argv=None) -> int:
|
||||
c.add_argument("--sound")
|
||||
c.add_argument("--out", required=True)
|
||||
c.add_argument("--layout", choices=["split", "side"], default="split")
|
||||
c.add_argument("--labels", nargs=2, default=["Original", "SmoovPlay"])
|
||||
c.add_argument("--labels", nargs=2, default=["Original", "Summit"])
|
||||
c.add_argument("--encoder", default=None)
|
||||
c.add_argument("--cleanup", metavar="FOLDER", help="delete this folder (the tracks) when done")
|
||||
c.add_argument("--mark", metavar="FOLDER", help="keep FOLDER/<process id>.txt (the video's path) while making it, "
|
||||
|
||||
+2
-2
@@ -366,7 +366,7 @@ def main() -> int:
|
||||
from framegen import dml
|
||||
why = dml.unavailable_reason()
|
||||
if why:
|
||||
print("SmoovPlay needs an NVIDIA RTX card (CUDA), or DirectML for AMD and Intel cards (Experimental), and "
|
||||
print("Summit's engine needs an NVIDIA RTX card (CUDA), or DirectML for AMD and Intel cards (Experimental), and "
|
||||
f"neither works here: {why}. Update the graphics driver, then try again.", file=sys.stderr)
|
||||
return 1
|
||||
print(f"[run] no NVIDIA CUDA here: RIFE runs through DirectML (Experimental) on {dml.pick_adapter()['name']}")
|
||||
@@ -468,7 +468,7 @@ def main() -> int:
|
||||
hdr_out, hdr_why, hdr_peak = None, "", None
|
||||
if kind == "chiaki" and settings.hdr != "off" and getattr(src, "hdr_stream", False):
|
||||
if dml_mode:
|
||||
hdr_why = "SmoovPlay's HDR needs an NVIDIA card for now"
|
||||
hdr_why = "HDR in Summit's engine needs an NVIDIA card for now"
|
||||
else:
|
||||
hdr_out = "sdr8"
|
||||
if settings.hdr == "hdr10":
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,42 @@
|
||||
"""Clips go to Videos/Summit/<game>, the game named by `summit run` (SUMMIT_GAME)."""
|
||||
import sys
|
||||
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parents[1]))
|
||||
from pathlib import Path
|
||||
|
||||
from framegen import oslayer, replay
|
||||
|
||||
|
||||
def _folder(monkeypatch, game=None):
|
||||
monkeypatch.delenv("SMOOVPLAY_REPLAY_DIR", raising=False)
|
||||
monkeypatch.setattr(oslayer, "videos_dir", lambda: Path("/v"))
|
||||
if game is None:
|
||||
monkeypatch.delenv("SUMMIT_GAME", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("SUMMIT_GAME", game)
|
||||
return replay.videos_folder()
|
||||
|
||||
|
||||
def test_a_folder_per_game(monkeypatch):
|
||||
assert _folder(monkeypatch, "Portal 2") == Path("/v/Summit/Portal 2")
|
||||
|
||||
|
||||
def test_no_game_saves_in_summit(monkeypatch):
|
||||
assert _folder(monkeypatch) == Path("/v/Summit")
|
||||
assert _folder(monkeypatch, " ") == Path("/v/Summit")
|
||||
|
||||
|
||||
def test_names_are_made_safe(monkeypatch):
|
||||
assert _folder(monkeypatch, 'Half-Life: "Alyx"/VR?') == Path("/v/Summit/Half-Life Alyx VR")
|
||||
assert _folder(monkeypatch, "../..") == Path("/v/Summit")
|
||||
|
||||
|
||||
def test_override_still_wins(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("SMOOVPLAY_REPLAY_DIR", str(tmp_path))
|
||||
monkeypatch.setenv("SUMMIT_GAME", "Portal 2")
|
||||
assert replay.videos_folder() == tmp_path
|
||||
|
||||
|
||||
def test_toast_path_uses_this_systems_separator():
|
||||
import os
|
||||
p = Path("/home/u/Videos/Summit/Portal 2/Portal 2 2026-11-24 09-27-53.mp4")
|
||||
assert replay._short(p) == os.sep.join(("Summit", "Portal 2", "Portal 2 2026-11-24 09-27-53.mp4"))
|
||||
+91
-6
@@ -14,6 +14,10 @@
|
||||
# --dry-run print what would happen, change nothing
|
||||
# --uninstall remove what this installer installed
|
||||
# --help, -h show this message
|
||||
#
|
||||
# Environment:
|
||||
# SUMMIT_PREFIX where to install (default /usr/local)
|
||||
# SUMMIT_SRC_DIR build this checkout as it is (no clone, no git pull)
|
||||
|
||||
set -eu
|
||||
|
||||
@@ -23,6 +27,8 @@ PREFIX="${SUMMIT_PREFIX:-/usr/local}"
|
||||
SHARE_DIR="$PREFIX/share/summit"
|
||||
BIN_DIR="$PREFIX/bin"
|
||||
SRC_DIR="${SUMMIT_SRC_DIR:-$HOME/.cache/summit/src}"
|
||||
APPS_DIR="$PREFIX/share/applications"
|
||||
ICON_DIR="$PREFIX/share/icons/hicolor/64x64/apps"
|
||||
|
||||
ASSUME_YES=0
|
||||
DRY_RUN=0
|
||||
@@ -61,6 +67,11 @@ usage() {
|
||||
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
|
||||
}
|
||||
|
||||
# Tools Summit calls at run time. A missing one only disables a feature, so a failure here warns instead of
|
||||
# stopping the install: ffmpeg (Enhance reads the game window with it), xrandr (display profiles on X11),
|
||||
# xdg-open (Heroic games, the clips folder) and zenity (Change artwork outside KDE; KDE has kdialog).
|
||||
RUNTIME_TOOLS="ffmpeg xrandr xdg-open zenity"
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--yes|-y) ASSUME_YES=1 ;;
|
||||
@@ -150,23 +161,49 @@ install_dependencies() {
|
||||
step "Installing build and runtime dependencies for $DISTRO_FAMILY"
|
||||
case "$DISTRO_FAMILY" in
|
||||
arch)
|
||||
run_sudo pacman -Sy --needed --noconfirm base-devel git curl pkgconf
|
||||
run_sudo pacman -Sy --needed --noconfirm base-devel git curl pkgconf fontconfig
|
||||
runtime="ffmpeg xorg-xrandr xdg-utils zenity"
|
||||
;;
|
||||
debian)
|
||||
run_sudo apt-get update
|
||||
run_sudo apt-get install -y build-essential git curl pkg-config libssl-dev
|
||||
run_sudo apt-get install -y build-essential git curl pkg-config libssl-dev libfontconfig1-dev
|
||||
runtime="ffmpeg x11-xserver-utils xdg-utils zenity"
|
||||
;;
|
||||
fedora)
|
||||
run_sudo dnf install -y @development-tools git curl pkgconf-pkg-config openssl-devel
|
||||
run_sudo dnf install -y @development-tools git curl pkgconf-pkg-config openssl-devel fontconfig-devel
|
||||
# Fedora's own ffmpeg build; RPM Fusion's "ffmpeg" has more encoders if you have that repo.
|
||||
runtime="ffmpeg-free xrandr xdg-utils zenity"
|
||||
;;
|
||||
opensuse)
|
||||
run_sudo zypper install -y -t pattern devel_basis
|
||||
run_sudo zypper install -y git curl pkg-config libopenssl-devel
|
||||
run_sudo zypper install -y git curl pkg-config libopenssl-devel fontconfig-devel
|
||||
runtime="ffmpeg xrandr xdg-utils zenity"
|
||||
;;
|
||||
*)
|
||||
log " unrecognized distro family ($DISTRO_ID) — skipping package manager, assuming build tools are present"
|
||||
runtime=""
|
||||
;;
|
||||
esac
|
||||
if [ -n "$runtime" ]; then
|
||||
step "Installing the tools Summit runs (a failure here only disables a feature)"
|
||||
# shellcheck disable=SC2086
|
||||
case "$DISTRO_FAMILY" in
|
||||
arch) run_sudo pacman -S --needed --noconfirm $runtime || log " warning: could not install: $runtime" ;;
|
||||
debian) run_sudo apt-get install -y $runtime || log " warning: could not install: $runtime" ;;
|
||||
fedora) run_sudo dnf install -y $runtime || log " warning: could not install: $runtime" ;;
|
||||
opensuse) run_sudo zypper install -y $runtime || log " warning: could not install: $runtime" ;;
|
||||
esac
|
||||
fi
|
||||
}
|
||||
|
||||
check_runtime_tools() {
|
||||
missing=""
|
||||
for t in $RUNTIME_TOOLS; do
|
||||
command -v "$t" >/dev/null 2>&1 || missing="$missing $t"
|
||||
done
|
||||
if [ -n "$missing" ]; then
|
||||
log " missing :$missing (see 'summit doctor' for what each one is for)"
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_rust() {
|
||||
@@ -180,6 +217,10 @@ ensure_rust() {
|
||||
# shellcheck disable=SC1090
|
||||
. "$RUSTUP_ENV"
|
||||
fi
|
||||
# `curl | sh` succeeds when curl fails (sh just reads nothing), so check the result instead.
|
||||
if [ "$DRY_RUN" -eq 0 ] && ! command -v cargo >/dev/null 2>&1; then
|
||||
die "rustup did not install cargo (no internet?). Install Rust from https://rustup.rs and run this again"
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_uv() {
|
||||
@@ -194,6 +235,9 @@ ensure_uv() {
|
||||
fi
|
||||
PATH="$HOME/.local/bin:$PATH"
|
||||
export PATH
|
||||
if [ "$DRY_RUN" -eq 0 ] && ! command -v uv >/dev/null 2>&1; then
|
||||
die "uv did not install (no internet?). Install it from https://docs.astral.sh/uv/ and run this again"
|
||||
fi
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -236,7 +280,10 @@ install_native_package() {
|
||||
build_from_source() {
|
||||
step "No usable release package found, building from source"
|
||||
ensure_rust
|
||||
if [ -d "$SRC_DIR/.git" ]; then
|
||||
if [ -n "${SUMMIT_SRC_DIR:-}" ]; then
|
||||
[ -f "$SRC_DIR/Cargo.toml" ] || die "SUMMIT_SRC_DIR=$SRC_DIR is not a Summit checkout (no Cargo.toml)"
|
||||
log " building the checkout in SUMMIT_SRC_DIR as it is: $SRC_DIR"
|
||||
elif [ -d "$SRC_DIR/.git" ]; then
|
||||
run git -C "$SRC_DIR" fetch --tags
|
||||
run git -C "$SRC_DIR" checkout main
|
||||
run git -C "$SRC_DIR" pull --ff-only
|
||||
@@ -249,6 +296,7 @@ build_from_source() {
|
||||
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/"
|
||||
install_desktop_entry "$SRC_DIR/packaging"
|
||||
# The engine's venv is made in there next, without sudo (uv and the Python it downloads live in the user's home),
|
||||
# so the folder has to belong to the user who runs Summit.
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
@@ -256,6 +304,38 @@ build_from_source() {
|
||||
fi
|
||||
}
|
||||
|
||||
install_desktop_entry() {
|
||||
# The app menu entry, pointing at the installed binary by its full path (a custom SUMMIT_PREFIX is often not
|
||||
# on the menu's PATH).
|
||||
pkg="$1"
|
||||
run_sudo install -Dm644 "$pkg/icons/summit.png" "$ICON_DIR/summit.png"
|
||||
desktop_tmp="$(mktemp)"
|
||||
sed "s|^Exec=summit-gui|Exec=$BIN_DIR/summit-gui|" "$pkg/summit.desktop" > "$desktop_tmp"
|
||||
run_sudo install -Dm644 "$desktop_tmp" "$APPS_DIR/summit.desktop"
|
||||
rm -f "$desktop_tmp"
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
run_sudo update-desktop-database "$APPS_DIR" || true
|
||||
fi
|
||||
}
|
||||
|
||||
fetch_default_model() {
|
||||
# RIFE's default weights (4.22.lite), so the first Play with Enhance does not stop to download them, and so a
|
||||
# root-owned engine folder (installed as root) still has them. Other models download on first use.
|
||||
engine_dir="$1"
|
||||
model="$engine_dir/models/flownet_v4.22.lite.pkl"
|
||||
if [ -f "$model" ]; then
|
||||
return
|
||||
fi
|
||||
step "Downloading the default RIFE model (about 20 MB)"
|
||||
run mkdir -p "$engine_dir/models"
|
||||
if run curl -fsSL -o "$model.part" "https://github.com/HolyWu/vs-rife/releases/download/model/flownet_v4.22.lite.pkl"; then
|
||||
run mv "$model.part" "$model"
|
||||
else
|
||||
run rm -f "$model.part"
|
||||
log " warning: download failed; the engine will try again the first time Enhance runs"
|
||||
fi
|
||||
}
|
||||
|
||||
setup_engine_venv() {
|
||||
step "Setting up the engine's Python environment (uv, Python 3.12)"
|
||||
ensure_uv
|
||||
@@ -277,6 +357,7 @@ setup_engine_venv() {
|
||||
log " no NVIDIA GPU detected, skipping CUDA torch (engine will run CPU-only or be unavailable)"
|
||||
fi
|
||||
run uv pip install --python "$engine_dir/.venv" -r "$engine_dir/requirements.txt"
|
||||
fetch_default_model "$engine_dir"
|
||||
}
|
||||
|
||||
do_install() {
|
||||
@@ -314,11 +395,15 @@ do_install() {
|
||||
log " summit -> $BIN_DIR/summit"
|
||||
log " summit-gui -> $BIN_DIR/summit-gui"
|
||||
log " engine -> $SHARE_DIR/engine (venv at $SHARE_DIR/engine/.venv)"
|
||||
log " app menu -> $APPS_DIR/summit.desktop"
|
||||
check_runtime_tools
|
||||
log ""
|
||||
log " Next: 'summit doctor' checks what Enhance needs; 'summit-gui' (or Summit in the app menu) starts the launcher."
|
||||
}
|
||||
|
||||
do_uninstall() {
|
||||
step "Uninstalling Summit"
|
||||
run_sudo rm -f "$BIN_DIR/summit" "$BIN_DIR/summit-gui"
|
||||
run_sudo rm -f "$BIN_DIR/summit" "$BIN_DIR/summit-gui" "$APPS_DIR/summit.desktop" "$ICON_DIR/summit.png"
|
||||
run_sudo rm -rf "$SHARE_DIR"
|
||||
log "Left in place: $SRC_DIR (build cache), ~/.config/summit, ~/.local/share/summit (your data)"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user