diff --git a/crates/summit-cli/src/main.rs b/crates/summit-cli/src/main.rs index 977c068..3e2c44e 100644 --- a/crates/summit-cli/src/main.rs +++ b/crates/summit-cli/src/main.rs @@ -114,7 +114,13 @@ fn main() -> Result<()> { f => engine::Source::File(f.into()), }; let p = profile::load(&profile)?; - let args = engine::plan(&eng, &src, &p, out.is_none(), out.as_deref(), max_ticks); + 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()) { + let ui = summit_core::ui::load(); + args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds)); + } let py = engine::python(&eng); println!("{} {}", py.display(), args.join(" ")); if !dry_run { diff --git a/crates/summit-core/src/engine.rs b/crates/summit-core/src/engine.rs index f47857b..5598607 100644 --- a/crates/summit-core/src/engine.rs +++ b/crates/summit-core/src/engine.rs @@ -69,6 +69,17 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option a } +/// 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 { + const OK: [u32; 6] = [15, 30, 60, 180, 300, 600]; + if !OK.contains(&replay_seconds) { return vec![]; } + let mut a = vec!["--replay".to_string(), replay_seconds.to_string()]; + let clip = clip_seconds.min(replay_seconds); + if OK.contains(&clip) { a.push("--clip-length".into()); a.push(clip.to_string()); } + a +} + #[cfg(test)] mod tests { use super::*; @@ -82,6 +93,11 @@ mod tests { let a = plan(Path::new("/e"), &Source::File("c.mp4".into()), &pr, false, Some(Path::new("o.mp4")), Some(120)); assert_eq!(a[1..].join(" "), "c.mp4 --out o.mp4 --max-ticks 120"); } + #[test] fn clip_args_follow_the_engine_choices() { + assert_eq!(clip_args(60, 30).join(" "), "--replay 60 --clip-length 30"); + assert_eq!(clip_args(30, 300).join(" "), "--replay 30 --clip-length 30"); + assert!(clip_args(45, 15).is_empty()); + } #[test] fn dlss_is_not_an_engine_scaler() { assert_eq!(scaler_arg("dlss"), None); } #[test] fn framegen_none_turns_interp_off() { let pr = Profile { framegen: "none".into(), ..Default::default() }; diff --git a/crates/summit-core/src/launch.rs b/crates/summit-core/src/launch.rs new file mode 100644 index 0000000..9557d10 --- /dev/null +++ b/crates/summit-core/src/launch.rs @@ -0,0 +1,88 @@ +//! How to start an entry from the launcher. Pure planning (argv only), so it is unit tested; the caller spawns it. +use crate::model::{Entry, Source}; +use std::path::Path; + +#[derive(Debug, Clone, PartialEq)] +pub enum Plan { + /// Run this argv. + Run(Vec), + /// Summit cannot start this entry yet; the string says why. + Unsupported(String), +} + +/// What "Play" does for an entry. +/// +/// * Steam: hands over to the Steam client (`steam steam://rungameid/`). Steam tracks its own playtime. +/// A game that is not installed gets `steam://install/`, which opens Steam's install dialog. +/// * Added by hand, with a file path: goes through `summit run -- ` so the display profile is applied +/// and the session is tracked. `summit_cli` is the path of the `summit` binary. +/// * Lutris: `lutris lutris:rungame/`. +/// * Heroic and folders found on disk: not wired yet. +pub fn plan(e: &Entry, summit_cli: Option<&Path>) -> Plan { + match e.source { + Source::Steam => match e.steam_app_id { + Some(id) if e.installed => Plan::Run(vec!["steam".into(), format!("steam://rungameid/{id}")]), + Some(id) => Plan::Run(vec!["steam".into(), format!("steam://install/{id}")]), + None => Plan::Unsupported("this Steam entry has no app id".into()), + }, + Source::Custom => { + let Some(path) = e.path.as_deref() else { return Plan::Unsupported("no path stored for this entry".into()) }; + if !Path::new(path).is_file() { return Plan::Unsupported(format!("{path} is not a file Summit can run")); } + match summit_cli { + Some(cli) => Plan::Run(vec![cli.to_string_lossy().into_owned(), "run".into(), e.id.clone(), "--".into(), path.into()]), + None => Plan::Unsupported("the summit command line tool was not found next to summit-gui".into()), + } + } + Source::Lutris => match e.id.strip_prefix("lutris:") { + Some(slug) if !slug.is_empty() => Plan::Run(vec!["lutris".into(), format!("lutris:rungame/{slug}")]), + _ => Plan::Unsupported("no Lutris slug for this entry".into()), + }, + Source::Heroic => Plan::Unsupported("launching Heroic games from Summit is not built yet".into()), + Source::Heuristic => Plan::Unsupported("found on disk: add it with `summit add` and pick its executable to launch it".into()), + } +} + +/// True when Play would install rather than start (owned Steam game that is not on disk). +pub fn is_install(e: &Entry) -> bool { e.source == Source::Steam && !e.installed && e.steam_app_id.is_some() } + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Kind; + fn entry(id: &str, source: Source, installed: bool, app: Option, 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![] } + } + #[test] + fn steam_installed_runs_through_the_client() { + let e = entry("steam:620", Source::Steam, true, Some(620), None); + assert_eq!(plan(&e, None), Plan::Run(vec!["steam".into(), "steam://rungameid/620".into()])); + assert!(!is_install(&e)); + } + #[test] + fn steam_not_installed_opens_install() { + let e = entry("steam:730", Source::Steam, false, Some(730), None); + assert_eq!(plan(&e, None), Plan::Run(vec!["steam".into(), "steam://install/730".into()])); + assert!(is_install(&e)); + } + #[test] + fn custom_goes_through_summit_run() { + let f = std::env::temp_dir().join(format!("summit-launch-test-{}.sh", std::process::id())); + std::fs::write(&f, "#!/bin/sh\n").unwrap(); + let p = f.to_string_lossy().into_owned(); + let e = entry("custom:voidrunner", Source::Custom, true, None, Some(&p)); + assert_eq!(plan(&e, Some(Path::new("/usr/bin/summit"))), Plan::Run(vec!["/usr/bin/summit".into(), "run".into(), "custom:voidrunner".into(), "--".into(), p])); + assert!(matches!(plan(&e, None), Plan::Unsupported(_))); + let _ = std::fs::remove_file(f); + } + #[test] + fn custom_with_missing_file_is_unsupported() { + let e = entry("custom:gone", Source::Custom, false, None, Some("/nonexistent/summit/game.sh")); + assert!(matches!(plan(&e, Some(Path::new("/usr/bin/summit"))), Plan::Unsupported(_))); + } + #[test] + fn lutris_and_unwired_sources() { + assert_eq!(plan(&entry("lutris:celeste", Source::Lutris, true, None, None), None), Plan::Run(vec!["lutris".into(), "lutris:rungame/celeste".into()])); + assert!(matches!(plan(&entry("heroic:epic:x", Source::Heroic, true, None, None), None), Plan::Unsupported(_))); + assert!(matches!(plan(&entry("scan:/g", Source::Heuristic, true, None, Some("/g")), None), Plan::Unsupported(_))); + } +} diff --git a/crates/summit-core/src/lib.rs b/crates/summit-core/src/lib.rs index c7578f6..ffbe2ab 100644 --- a/crates/summit-core/src/lib.rs +++ b/crates/summit-core/src/lib.rs @@ -2,10 +2,12 @@ pub mod display; pub mod engine; pub mod epic; +pub mod launch; pub mod model; pub mod names; pub mod profile; pub mod scan; pub mod state; pub mod steam; +pub mod ui; pub mod vdf; diff --git a/crates/summit-core/src/state.rs b/crates/summit-core/src/state.rs index 21125c3..8f7dd07 100644 --- a/crates/summit-core/src/state.rs +++ b/crates/summit-core/src/state.rs @@ -39,6 +39,15 @@ pub fn save(s: &State) -> Result<()> { impl State { pub fn pin(&mut self, id: &str) { if !self.pinned.iter().any(|p| p == id) { self.pinned.push(id.into()); } } pub fn unpin(&mut self, id: &str) { self.pinned.retain(|p| p != id); } + pub fn is_pinned(&self, id: &str) -> bool { self.pinned.iter().any(|p| p == id) } + /// Flip the pin and return the new state. + pub fn toggle_pin(&mut self, id: &str) -> bool { + if self.is_pinned(id) { self.unpin(id); false } else { self.pin(id); true } + } + /// Custom wide background art for an entry. Stored in `artwork` under "#hero", next to the cover under "". + pub fn hero_art(&self, id: &str) -> Option<&str> { self.artwork.get(&format!("{id}#hero")).map(String::as_str) } + /// Custom logo (transparent title image), stored under "#logo". + pub fn logo_art(&self, id: &str) -> Option<&str> { self.artwork.get(&format!("{id}#logo")).map(String::as_str) } pub fn record_session(&mut self, id: &str, seconds: u64, now: u64) { let t = self.tracked.entry(id.into()).or_default(); t.seconds += seconds; t.sessions += 1; t.last_played = now; @@ -88,5 +97,16 @@ mod tests { assert_eq!(v[1].last_played, Some(9)); } #[test] + fn toggle_pin_and_extra_art_keys() { + let mut s = State::default(); + assert!(s.toggle_pin("a")); assert!(s.is_pinned("a")); + assert!(!s.toggle_pin("a")); assert!(!s.is_pinned("a")); + s.artwork.insert("custom:v".into(), "/c.png".into()); + s.artwork.insert("custom:v#hero".into(), "/h.png".into()); + assert_eq!(s.hero_art("custom:v"), Some("/h.png")); + assert_eq!(s.logo_art("custom:v"), None); + assert_eq!(s.artwork.get("custom:v").map(String::as_str), Some("/c.png")); + } + #[test] fn pin_idempotent() { let mut s = State::default(); s.pin("a"); s.pin("a"); assert_eq!(s.pinned.len(), 1); s.unpin("a"); assert!(s.pinned.is_empty()); } } diff --git a/crates/summit-core/src/steam.rs b/crates/summit-core/src/steam.rs index 97fcdab..1d7ba89 100644 --- a/crates/summit-core/src/steam.rs +++ b/crates/summit-core/src/steam.rs @@ -120,21 +120,61 @@ pub fn scan() -> Vec { out } -/// Cover art from Steam's own library cache (portrait 600x900 preferred, then header). Works without network. -pub fn cover(app_id: u32) -> Option { - for root in steam_roots() { - let d = root.join("appcache/librarycache").join(app_id.to_string()); - for n in ["library_600x900.jpg", "header.jpg"] { - if d.join(n).is_file() { return Some(d.join(n)); } - } - // newer clients nest the files in a hash folder - if let Ok(rd) = std::fs::read_dir(&d) { - for sub in rd.flatten().filter(|e| e.path().is_dir()) { - for n in ["library_600x900.jpg", "header.jpg"] { - if sub.path().join(n).is_file() { return Some(sub.path().join(n)); } - } - } +/// First of `names` that exists for `app_id` under one Steam root's library cache. +/// Newer clients nest the files in a hash folder, so one level of sub-folders is checked too. +pub fn art_in(root: &Path, app_id: u32, names: &[&str]) -> Option { + let d = root.join("appcache/librarycache").join(app_id.to_string()); + for n in names { + if d.join(n).is_file() { return Some(d.join(n)); } + } + let mut subs: Vec = std::fs::read_dir(&d).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect(); + subs.sort(); + for n in names { + for sub in &subs { + if sub.join(n).is_file() { return Some(sub.join(n)); } } } None } + +fn art(app_id: u32, names: &[&str]) -> Option { steam_roots().iter().find_map(|r| art_in(r, app_id, names)) } + +/// Cover art from Steam's own library cache (portrait 600x900 preferred, then header). Works without network. +pub fn cover(app_id: u32) -> Option { art(app_id, &["library_600x900.jpg", "header.jpg"]) } + +/// Wide background art (library_hero.jpg) for the Big Picture backdrop. No fallback: callers blur the cover instead. +pub fn hero(app_id: u32) -> Option { art(app_id, &["library_hero.jpg"]) } + +/// The game's logo on a transparent background (logo.png), if Steam cached one. +pub fn logo(app_id: u32) -> Option { art(app_id, &["logo.png"]) } + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + fn root(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("summit-steam-test-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); fs::create_dir_all(&d).unwrap(); d + } + #[test] + fn hero_and_cover_flat_layout() { + let r = root("flat"); let d = r.join("appcache/librarycache/620"); fs::create_dir_all(&d).unwrap(); + for n in ["library_600x900.jpg", "library_hero.jpg", "header.jpg"] { fs::write(d.join(n), b"x").unwrap(); } + assert_eq!(art_in(&r, 620, &["library_600x900.jpg", "header.jpg"]), Some(d.join("library_600x900.jpg"))); + assert_eq!(art_in(&r, 620, &["library_hero.jpg"]), Some(d.join("library_hero.jpg"))); + assert_eq!(art_in(&r, 620, &["logo.png"]), None); + } + #[test] + fn nested_hash_folders_and_preference_order() { + let r = root("nested"); let d = r.join("appcache/librarycache/271590"); + fs::create_dir_all(d.join("aaa")).unwrap(); fs::create_dir_all(d.join("bbb")).unwrap(); + fs::write(d.join("aaa/header.jpg"), b"x").unwrap(); + fs::write(d.join("bbb/library_600x900.jpg"), b"x").unwrap(); + fs::write(d.join("bbb/library_hero.jpg"), b"x").unwrap(); + // the portrait wins over the header even though the header's folder sorts first + assert_eq!(art_in(&r, 271590, &["library_600x900.jpg", "header.jpg"]), Some(d.join("bbb/library_600x900.jpg"))); + assert_eq!(art_in(&r, 271590, &["library_hero.jpg"]), Some(d.join("bbb/library_hero.jpg"))); + } + #[test] + fn missing_app_has_no_art() { assert_eq!(art_in(&root("none"), 1, &["library_hero.jpg"]), None); } +} diff --git a/crates/summit-core/src/ui.rs b/crates/summit-core/src/ui.rs new file mode 100644 index 0000000..37800e6 --- /dev/null +++ b/crates/summit-core/src/ui.rs @@ -0,0 +1,140 @@ +//! Launcher GUI preferences, stored in ~/.config/summit/ui.toml. +//! Everything is sanitized on load, so a hand-edited or damaged file can never break the launcher. +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +pub const LAYOUTS: &[&str] = &["bigpicture", "grid", "list"]; +pub const ANIM_STYLES: &[&str] = &["smooth", "snappy", "bouncy"]; +/// Lengths the engine accepts for `--replay` and `--clip-length`, in seconds. +pub const CLIP_LENGTHS: &[u32] = &[15, 30, 60, 180, 300, 600]; +pub const UI_SCALES: &[f32] = &[0.8, 0.9, 1.0, 1.1, 1.25, 1.5]; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(default)] +pub struct UiSettings { + /// "bigpicture" | "grid" | "list" + pub layout: String, + /// Theme key, e.g. "midnight". Unknown keys are kept as written (the GUI falls back to its first theme). + pub theme: String, + /// Animation speed multiplier. 0 turns animations off, 1 is the default, 2 is twice as fast. + pub anim_speed: f32, + /// "smooth" | "snappy" | "bouncy" + pub anim_style: String, + /// Multiplier on top of the system scale factor. + pub ui_scale: f32, + /// Instant replay: how many seconds the engine keeps. + pub replay_seconds: u32, + /// Instant replay: how many seconds a save writes. Never more than `replay_seconds`. + pub clip_seconds: u32, +} + +impl Default for UiSettings { + fn default() -> Self { + Self { layout: "bigpicture".into(), theme: "midnight".into(), anim_speed: 1.0, anim_style: "smooth".into(), ui_scale: 1.0, replay_seconds: 60, clip_seconds: 30 } + } +} + +fn nearest_u32(v: u32, allowed: &[u32]) -> u32 { *allowed.iter().min_by_key(|a| a.abs_diff(v)).unwrap() } + +impl UiSettings { + /// Clamp every field to something the GUI and the engine can use. + pub fn sanitized(mut self) -> Self { + let d = Self::default(); + if !LAYOUTS.contains(&self.layout.as_str()) { self.layout = d.layout; } + if !ANIM_STYLES.contains(&self.anim_style.as_str()) { self.anim_style = d.anim_style; } + if self.theme.trim().is_empty() { self.theme = d.theme; } + self.anim_speed = if self.anim_speed.is_finite() { self.anim_speed.clamp(0.0, 2.0) } else { d.anim_speed }; + self.ui_scale = if self.ui_scale.is_finite() { self.ui_scale.clamp(0.8, 1.5) } else { d.ui_scale }; + self.replay_seconds = nearest_u32(self.replay_seconds, CLIP_LENGTHS); + self.clip_seconds = nearest_u32(self.clip_seconds, CLIP_LENGTHS).min(self.replay_seconds); + self + } + pub fn layout_index(&self) -> usize { LAYOUTS.iter().position(|l| *l == self.layout).unwrap_or(0) } + pub fn anim_style_index(&self) -> usize { ANIM_STYLES.iter().position(|l| *l == self.anim_style).unwrap_or(0) } +} + +pub fn path() -> Result { Ok(dirs::config_dir().context("no config dir")?.join("summit/ui.toml")) } + +/// Missing or unreadable file gives the defaults. +pub fn load_from(p: &Path) -> UiSettings { + std::fs::read_to_string(p).ok().and_then(|s| toml::from_str::(&s).ok()).unwrap_or_default().sanitized() +} + +pub fn save_to(p: &Path, s: &UiSettings) -> Result<()> { + if let Some(d) = p.parent() { std::fs::create_dir_all(d)?; } + let tmp = p.with_extension("toml.tmp"); + std::fs::write(&tmp, toml::to_string_pretty(&s.clone().sanitized())?)?; + std::fs::rename(tmp, p)?; // atomic, like state.json + Ok(()) +} + +pub fn load() -> UiSettings { path().map(|p| load_from(&p)).unwrap_or_default() } +pub fn save(s: &UiSettings) -> Result<()> { save_to(&path()?, s) } + +/// Short label for a clip length: 15 -> "15 s", 180 -> "3 min". +pub fn clip_label(seconds: u32) -> String { + if seconds < 60 { format!("{seconds} s") } else { format!("{} min", seconds / 60) } +} + +#[cfg(test)] +mod tests { + use super::*; + fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("summit-ui-test-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d.join("summit/ui.toml") + } + #[test] + fn missing_file_gives_defaults() { + let s = load_from(&tmp("missing")); + assert_eq!(s, UiSettings::default()); + assert_eq!((s.layout.as_str(), s.theme.as_str(), s.anim_speed), ("bigpicture", "midnight", 1.0)); + } + #[test] + fn roundtrip_through_file() { + let p = tmp("roundtrip"); + let s = UiSettings { layout: "list".into(), theme: "violet".into(), anim_speed: 0.0, anim_style: "snappy".into(), ui_scale: 1.25, replay_seconds: 600, clip_seconds: 180 }; + save_to(&p, &s).unwrap(); + assert_eq!(load_from(&p), s); + assert!(!p.with_extension("toml.tmp").exists()); + } + #[test] + fn garbage_file_gives_defaults() { + let p = tmp("garbage"); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, "layout = [this is not toml").unwrap(); + assert_eq!(load_from(&p), UiSettings::default()); + } + #[test] + fn partial_file_keeps_other_defaults() { + let p = tmp("partial"); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, "theme = \"daylight\"\nanim_speed = 1.5\n").unwrap(); + let s = load_from(&p); + assert_eq!((s.theme.as_str(), s.anim_speed, s.layout.as_str(), s.replay_seconds), ("daylight", 1.5, "bigpicture", 60)); + } + #[test] + fn bad_values_are_clamped() { + let s = UiSettings { layout: "hologram".into(), theme: " ".into(), anim_speed: 9.0, anim_style: "wobbly".into(), ui_scale: 0.1, replay_seconds: 100, clip_seconds: 9999 }.sanitized(); + assert_eq!(s.layout, "bigpicture"); + assert_eq!(s.theme, "midnight"); + assert_eq!(s.anim_speed, 2.0); + assert_eq!(s.anim_style, "smooth"); + assert_eq!(s.ui_scale, 0.8); + assert_eq!(s.replay_seconds, 60); // 100 is nearest to 60 + assert_eq!(s.clip_seconds, 60); // capped at what the buffer holds + assert_eq!(UiSettings { anim_speed: f32::NAN, ..Default::default() }.sanitized().anim_speed, 1.0); + } + #[test] + fn clip_never_longer_than_replay() { + let s = UiSettings { replay_seconds: 30, clip_seconds: 300, ..Default::default() }.sanitized(); + assert_eq!((s.replay_seconds, s.clip_seconds), (30, 30)); + } + #[test] + fn indexes_and_labels() { + let s = UiSettings { layout: "list".into(), anim_style: "bouncy".into(), ..Default::default() }; + assert_eq!((s.layout_index(), s.anim_style_index()), (2, 2)); + assert_eq!((clip_label(15).as_str(), clip_label(60).as_str(), clip_label(600).as_str()), ("15 s", "1 min", "10 min")); + } +}