diff --git a/crates/summit-cli/src/main.rs b/crates/summit-cli/src/main.rs index e41b6df..40779e9 100644 --- a/crates/summit-cli/src/main.rs +++ b/crates/summit-cli/src/main.rs @@ -1,6 +1,8 @@ use anyhow::Result; use clap::{Parser, Subcommand}; use summit_core::{console, display, doctor, engine, model::Entry, profile, scan, signals, state}; +use summit_core::profiles::{Ref, Store}; +use summit_core::resolve; #[derive(Parser)] #[command(name = "summit", version, about = "One launcher for every game and app on Linux")] @@ -124,11 +126,54 @@ enum NvidiaCmd { Remove, } -/// Profiles are layered: `default` holds the launcher's defaults, a game's own profile only what it changes. +/// Every game is on one profile: Default (the global settings), a built-in one (quality, balanced, performance, +/// lowest-delay), one of yours, or Individual (its own settings). A profile is named by its id (`user:couch`, +/// `builtin:quality`, `default`) or by its name. Which screen a game runs on, its window, its launch options and +/// Enhance always stay with the game (`summit profile set --monitor ...`). #[derive(Subcommand)] enum ProfileCmd { - /// What the entry launches with (the defaults with its own settings on top); `--own`: only its own settings + /// Every profile with the games on it, and the Individual games + List, + /// A profile: its settings, its games, what it comes to on each screen. Or a game (by its id): what it launches + /// with and which profile that is from; `--own`: only what the game's own file holds Show { id: String, #[arg(long)] own: bool }, + /// Make a profile. It starts native: the screen's own resolution and as many frames as the screen shows + New { + name: String, + /// Start as a copy of this profile instead + #[arg(long)] from: Option, + }, + /// Change a profile's settings; every game on it gets the change. Settings go by the engine's own key + /// (`python -m framegen.settings` lists them): --set scaler=vsr --set motion=full + Edit { + profile: String, + /// An engine setting, KEY=VALUE (repeat for more) + #[arg(long = "set", value_name = "KEY=VALUE")] set: Vec, + /// Stop setting KEY: the global settings decide it again (repeat for more) + #[arg(long = "unset", value_name = "KEY")] unset: Vec, + /// Frame multiplier: `native` (as many frames as the screen shows), a number from 2 to 10 (pinned on every + /// screen), or `global` (the global settings decide) + #[arg(long)] rate: Option, + /// Output resolution: `native` (the screen's), a size like 2560x1440 (pinned), or `global` + #[arg(long)] output: Option, + }, + /// An editable copy of a profile (the way to change a built-in one) + Duplicate { profile: String, name: String }, + Rename { profile: String, name: String }, + /// Delete one of your profiles. Its games become Individual and keep the settings they had + Delete { profile: String }, + /// Put a game on a profile (`individual` is the same as `detach`) + Assign { game: String, profile: String }, + /// Take a game off its profile: it becomes Individual and keeps the profile's settings as its own + Detach { game: String }, + /// Make a profile from an Individual game's settings; the game then uses it + FromGame { game: String, name: String }, + /// The profile for games that were never given one + NewGames { profile: String }, + /// Write a profile to a file + Export { profile: String, file: std::path::PathBuf }, + /// Add a profile from a file made by `export` + Import { file: std::path::PathBuf }, /// Change settings. Use the id `default` for the launcher's defaults, which every game follows until it sets /// its own value. An empty text value ("") or 0 means "not chosen" (e.g. `--monitor ""`: never switch monitors). Set { @@ -184,6 +229,9 @@ enum ProfileCmd { #[arg(long)] game_fps: Option, /// Output resolution: the upscaler makes the picture at this size, e.g. 2560x1440 ("screen": the screen's) #[arg(long)] output_res: Option, + /// The game is on a shared profile and an engine setting is given: make the game Individual first (it keeps + /// the profile's settings as its own), then change it + #[arg(long)] individual: bool, }, /// Forget settings, so the defaults decide again: the ones named (e.g. `upscaler window_mode`), or all of them Reset { id: String, keys: Vec }, @@ -224,8 +272,265 @@ fn resolve_userdata(user: Option<&str>) -> Result { } } +/// The library's ids and titles: what profiles are listed with. (A scan of the launchers on this machine.) +fn library() -> Vec<(String, String)> { + let st = state::load(); + let mut all: Vec = scan::full(&[], 1); + state::apply(&mut all, &st); + let mut v: Vec<(String, String)> = all.into_iter().map(|e| (e.id, e.title)).collect(); + for c in &st.custom { if !v.iter().any(|(i, _)| *i == c.id) { v.push((c.id.clone(), c.title.clone())); } } + for c in &st.consoles { if !v.iter().any(|(i, _)| *i == c.id) { v.push((c.id.clone(), c.title.clone())); } } + v +} + +/// Files of an older Summit are brought up to this one once, after a backup (profiles::Store::migrate). +fn migrate_profiles() { + let Ok(store) = Store::user() else { return }; + if store.index_file().exists() { return; } + let known: Vec = library().into_iter().map(|(i, _)| i).collect(); + match store.migrate(&known) { + Ok(Some(m)) => { + if let Some(b) = &m.backup { err!("profiles: updated for shared profiles; the files as they were are in {}", b.display()); } + if !m.individual.is_empty() { err!("profiles: games with their own engine settings are now Individual games, with the same settings: {}", m.individual.join(", ")); } + for (f, e) in &m.skipped { err!("profiles: {f}.toml could not be read and was left as it is: {e}"); } + } + Ok(None) => {} + Err(e) => err!("profiles: could not update the profile files ({e:#}); they are used as they are"), + } +} + +/// What the game's profile comes to on its screen: printed, and put into the profile the engine is started with. +fn resolve_for_run(p: &mut profile::Profile, outs: &[display::Output]) { + let (r, unknown) = resolve::for_game(p, &resolve::saved_settings(), outs, &resolve::SourceFacts::default()); + if let Some(why) = &unknown { out!("profile: the screen is not known ({why})"); } + out!("profile: {}", r.line()); + for w in &r.why { out!("profile: {w}"); } + for s in &r.suggestions { out!("profile: suggestion: {}", s.line()); } + r.apply_to(p); +} + +/// `KEY=VALUE` for a profile: the value as JSON when it reads as JSON (true, 60, "fsr"), else as the bare word (fsr). +fn parse_set(s: &str) -> Result<(String, serde_json::Value)> { + let (k, v) = s.split_once('=').ok_or_else(|| anyhow::anyhow!("{s:?} is not KEY=VALUE"))?; + let k = k.trim(); + anyhow::ensure!(!k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), "{k:?} is not a setting's key (letters, digits and _)"); + let v = v.trim(); + let value = match serde_json::from_str::(v) { + Ok(j) if j.is_boolean() || j.is_number() || j.is_string() => j, + _ => serde_json::Value::String(v.to_string()), + }; + Ok((k.to_string(), value)) +} + +/// Check `KEY=VALUE` pairs against the engine's own list, when the engine is here to ask. A setting with choices +/// takes one of them (the frame multiplier and the output size also take their custom values, which the engine checks). +fn check_settings(pairs: &[(String, serde_json::Value)], unset: &[String]) -> Result<()> { + let Some(reg) = engine::find_engine().and_then(|e| summit_core::registry::Registry::load(&e).ok()) else { + if !pairs.is_empty() || !unset.is_empty() { err!("note: the engine is not here to check these settings against; they are saved as given"); } + return Ok(()); + }; + let keys = || reg.specs.iter().map(|s| s.key.as_str()).collect::>().join(", "); + for k in unset { anyhow::ensure!(reg.get(k).is_some(), "the engine has no setting {k:?}: one of {}", keys()); } + for (k, v) in pairs { + let spec = reg.get(k).ok_or_else(|| anyhow::anyhow!("the engine has no setting {k:?}: one of {}", keys()))?; + anyhow::ensure!(spec.saved, "{k} is for one session only: it cannot be saved in a profile"); + let free = matches!(k.as_str(), "hz" | "output_res"); + anyhow::ensure!(spec.choices.is_empty() || free || spec.position(v).is_some(), "{k} is one of: {}", spec.choices.iter().map(|c| summit_core::registry::plain(&c.value)).collect::>().join(", ")); + } + Ok(()) +} + +fn title_of(lib: &[(String, String)], id: &str) -> String { + match lib.iter().find(|(i, _)| i == id) { Some((_, t)) => format!("{t} ({id})"), None => id.to_string() } +} + +fn kind_of(r: &Ref) -> &'static str { + match r { Ref::Default => "Default", Ref::Builtin(_) => "Built-in, read-only", Ref::User(_) => "Yours", Ref::Individual => "Individual" } +} + +/// A profile's settings as short words: "scaler=fsr, motion=half, frame rate native". +fn settings_line(l: &profile::Layer) -> String { + let p = profile::resolve(&[l]); + let mut v: Vec = summit_core::registry::forced(&p).iter().map(|(k, v)| format!("{k}={}", summit_core::registry::plain(v))).collect(); + if p.native_rate() { v.push("frame rate native".into()); } + if v.is_empty() { "nothing of its own: the global settings".into() } else { v.join(", ") } +} + +fn profile_cmd(cmd: ProfileCmd) -> Result<()> { + let store = Store::user()?; + let lib = library(); + let known: Vec = lib.iter().map(|(i, _)| i.clone()).collect(); + let games = |r: &Ref| -> String { + let g = store.games_of(r, &known); + if g.is_empty() { "no games".into() } else { g.iter().map(|i| title_of(&lib, i)).collect::>().join(", ") } + }; + match cmd { + ProfileCmd::List => { + let all = store.list(); + let new = store.new_games(); + let show = |s: &summit_core::profiles::Shared| { + println!(" {:<22} {}{}", s.r.text(), s.name, if s.r == new { " [games never given a profile use this]" } else { "" }); + println!(" {:<22} {}", "", settings_line(&s.layer)); + println!(" {:<22} games: {}", "", games(&s.r)); + }; + println!("Default"); + all.iter().filter(|s| s.r == Ref::Default).for_each(show); + println!("Built-in"); + all.iter().filter(|s| matches!(s.r, Ref::Builtin(_))).for_each(show); + println!("My profiles"); + let mine: Vec<_> = all.iter().filter(|s| matches!(s.r, Ref::User(_))).collect(); + if mine.is_empty() { println!(" none yet: summit profile new , or summit profile from-game "); } + mine.into_iter().for_each(show); + println!("Individual games"); + let ind = store.games_of(&Ref::Individual, &known); + if ind.is_empty() { println!(" none: no game has settings of its own"); } + for g in ind { println!(" {:<22} {}", title_of(&lib, &g), settings_line(&store.layer(&g)?.shared_part())); } + } + ProfileCmd::Show { id, own } => { + // a game's id first (it has ':' in it, or a file of its own); anything else is looked up as a profile + let is_game = id != profile::DEFAULT_ID && Ref::parse(&id).is_none() && (known.contains(&id) || store.file(&id).is_file()); + if is_game || own { + let layer = store.layer(&id)?; + if own { print!("{}", toml::to_string_pretty(&profile::Layer { version: None, ..layer })?); return Ok(()); } + let p = store.effective(&id)?; + print!("{}", toml::to_string_pretty(&p)?); + let r = store.assignment(&id); + let name = if r == Ref::Individual { "Individual (its own settings)".to_string() } else { format!("{} ({})", store.get(&r)?.name, r.text()) }; + println!("# profile: {name}"); + let set: Vec<&str> = profile::KEYS.iter().copied().filter(|k| layer.has(k) && (r == Ref::Individual || !profile::is_shared(k))).collect(); + println!("# set by {id} itself: {}; the rest from its profile and the global settings ({})", if set.is_empty() { "nothing".to_string() } else { set.join(", ") }, store.file(profile::DEFAULT_ID).display()); + let (s, d) = (display::detect_session(), display::detect_desktop()); + match display::outputs(s, d) { + Ok(outs) => { + let (res, unknown) = resolve::for_game(&p, &resolve::saved_settings(), &outs, &resolve::SourceFacts::default()); + if let Some(w) = unknown { println!("# the screen is not known: {w}"); } + println!("# {}", res.line()); + for w in &res.why { println!("# {w}"); } + for s in &res.suggestions { println!("# suggestion: {}", s.line()); } + } + Err(e) => println!("# screens can't be listed here ({e}): nothing is resolved"), + } + return Ok(()); + } + let r = store.find(&id)?; + let s = store.get(&r)?; + println!("{} ({}; {})", s.name, r.text(), kind_of(&r)); + if !s.summary.is_empty() { println!("{}", s.summary); } + println!("settings: {}", settings_line(&s.layer)); + let text = toml::to_string_pretty(&profile::Layer { version: None, ..s.layer.clone() })?; + for l in text.lines() { println!(" {l}"); } + println!("games: {}", games(&r)); + let p = if r == Ref::Default { store.effective(profile::DEFAULT_ID)? } else { store.effective(&r.text())? }; + let (ses, d) = (display::detect_session(), display::detect_desktop()); + match display::outputs(ses, d) { + Ok(outs) => { + let lines = resolve::per_screen(&p, &resolve::saved_settings(), &outs); + if lines.is_empty() { println!("no screen is on: nothing to resolve"); } + for res in lines { + println!("{}", res.line()); + for w in &res.why { println!(" {w}"); } + for s in &res.suggestions { println!(" suggestion: {}", s.line()); } + } + } + Err(e) => println!("screens can't be listed here ({e}): nothing is resolved"), + } + } + ProfileCmd::New { name, from } => { + let r = match from { Some(f) => store.duplicate(&store.find(&f)?, &name)?, None => store.create(&name, &Store::blank())? }; + println!("made {} ({}): {}", store.get(&r)?.name, r.text(), settings_line(&store.get(&r)?.layer)); + println!("put a game on it: summit profile assign {}", r.text()); + } + ProfileCmd::Edit { profile: name, set, unset, rate, output } => { + let r = store.find(&name)?; + let pairs: Vec<(String, serde_json::Value)> = set.iter().map(|s| parse_set(s)).collect::>()?; + check_settings(&pairs, &unset)?; + let rate = match rate.as_deref() { + None => None, + Some("native") => Some(Some(None)), + Some("global") => Some(None), + Some(n) => Some(Some(Some(n.trim_end_matches('x').parse::().ok().filter(|n| profile::MULTIPLIER_RANGE.contains(n)).ok_or_else(|| anyhow::anyhow!("--rate is native, global or a multiplier from 2 to 10"))?))), + }; + let output = match output.as_deref() { + None => None, + Some("native") | Some("screen") => Some(Some("screen".to_string())), + Some("global") => Some(None), + Some(o) => Some(Some(profile::parse_res(o).map(|(w, h)| format!("{w}x{h}")).ok_or_else(|| anyhow::anyhow!("--output is native, global or a size like 2560x1440"))?)), + }; + anyhow::ensure!(!pairs.is_empty() || !unset.is_empty() || rate.is_some() || output.is_some(), "nothing to change: give --set KEY=VALUE, --unset KEY, --rate or --output"); + let n = store.games_of(&r, &known).len(); + let l = store.update(&r, |l| { + for k in &unset { l.set_engine(k, None); } + for (k, v) in &pairs { l.set_engine(k, Some(v)); } + match rate { + Some(Some(None)) => { l.set_engine("hz", None); l.rate = Some(profile::NATIVE.into()); } + Some(Some(Some(m))) => l.set_engine("hz", Some(&serde_json::Value::from(30 * u32::from(m)))), + Some(None) => l.set_engine("hz", None), + None => {} + } + if let Some(o) = &output { l.set_engine("output_res", o.as_ref().map(|o| serde_json::Value::String(o.clone())).as_ref()); } + })?; + println!("{}: {}", r.text(), settings_line(&l.shared_part())); + println!("{}", match n { 0 => "no game is on it yet".to_string(), 1 => format!("1 game gets the change: {}", games(&r)), n => format!("{n} games get the change: {}", games(&r)) }); + } + ProfileCmd::Duplicate { profile: from, name } => { + let r = store.duplicate(&store.find(&from)?, &name)?; + println!("made {} ({})", store.get(&r)?.name, r.text()); + } + ProfileCmd::Rename { profile: name, name: to } => { + let r = store.find(&name)?; + store.rename(&r, &to)?; + println!("{} is now called {}", r.text(), store.get(&r)?.name); + } + ProfileCmd::Delete { profile: name } => { + let r = store.find(&name)?; + let gone = store.delete(&r, &known)?; + println!("deleted {} (its file is kept under {})", r.text(), store.root.join("backups").display()); + if !gone.is_empty() { println!("now Individual, with the settings they had: {}", gone.iter().map(|g| title_of(&lib, g)).collect::>().join(", ")); } + } + ProfileCmd::Assign { game, profile: name } => { + let r = if name.eq_ignore_ascii_case("individual") { Ref::Individual } else { store.find(&name)? }; + if !known.contains(&game) && !store.file(&game).is_file() { err!("note: {game} is not in the library here; the profile is saved for that id all the same"); } + let kept = store.assign(&game, &r)?; + match &r { + Ref::Individual => println!("{} is Individual: it keeps the settings it had as its own", title_of(&lib, &game)), + r => println!("{} uses {} ({})", title_of(&lib, &game), store.get(r)?.name, r.text()), + } + if let Some(k) = kept { println!("the settings it had of its own are replaced by the profile's; a copy of its file is in {}", k.display()); } + } + ProfileCmd::Detach { game } => { + let was = store.detach(&game)?; + match was { + Ref::Individual => println!("{} already is Individual", title_of(&lib, &game)), + r => println!("{} is off {} and Individual: it keeps those settings as its own", title_of(&lib, &game), r.text()), + } + } + ProfileCmd::FromGame { game, name } => { + let r = store.from_game(&game, &name)?; + println!("made {} ({}) from {}, which now uses it", store.get(&r)?.name, r.text(), title_of(&lib, &game)); + } + ProfileCmd::NewGames { profile: name } => { + let r = store.find(&name)?; + store.set_new_games(&r)?; + println!("games that were never given a profile use {} ({})", store.get(&r)?.name, r.text()); + } + ProfileCmd::Export { profile: name, file } => { + let r = store.find(&name)?; + store.export(&r, &file)?; + println!("wrote {} to {}", r.text(), file.display()); + } + ProfileCmd::Import { file } => { + let r = store.import(&file)?; + println!("added {} ({})", store.get(&r)?.name, r.text()); + } + ProfileCmd::Set { .. } | ProfileCmd::Reset { .. } => unreachable!("handled in main"), + } + Ok(()) +} + fn main() -> Result<()> { - match Cli::parse().cmd { + let cli = Cli::parse(); + migrate_profiles(); + match cli.cmd { Cmd::Scan { path, depth, json, why } => { let mut all: Vec = scan::full(&path, depth); state::apply(&mut all, &state::load()); @@ -261,7 +566,11 @@ fn main() -> Result<()> { let src = engine::parse_source(&source).map_err(|e| anyhow::anyhow!(e))?; anyhow::ensure!(out.is_none() || matches!(src, engine::Source::File(_)), "--out needs a video file as the source"); if let Some(o) = &out { state::path_text(o)?; } - let p = profile::load(&profile)?; + let mut p = profile::load(&profile)?; + if out.is_none() { + let (s, d) = (display::detect_session(), display::detect_desktop()); + resolve_for_run(&mut p, &display::outputs(s, d).unwrap_or_default()); + } let mut args = engine::plan(&eng, &src, &p, out.is_none(), out.as_deref(), max_ticks); if out.is_none() { if let Some(w) = p.watermark { args.extend(["--watermark".to_string(), if w { "on" } else { "off" }.to_string()]); } } // Instant replay only exists while playing on screen. Lengths and the overlay key come from the launcher's @@ -358,6 +667,10 @@ fn main() -> Result<()> { let title = title.or(custom.map(|c| c.title)).or(console.as_ref().map(|c| c.title.clone())).unwrap_or_else(|| id.clone()); let mut p = profile::load(&id)?; if focus { p.focus = true; } + let (s, d) = (display::detect_session(), display::detect_desktop()); + // The screens: to switch the game's one, and to work out what its profile comes to there (Enhance). + let outs = if p.monitor.is_some() || enhance || console.is_some() { display::outputs(s, d) } else { Ok(vec![]) }; + if enhance || console.is_some() { resolve_for_run(&mut p, outs.as_deref().unwrap_or_default()); } // A console: what to start comes from its entry (console_command), not from after `--`. let mut enhance = enhance; let mut remote_play = false; @@ -374,8 +687,6 @@ fn main() -> Result<()> { if id.starts_with("steam:") && cmd.iter().any(|a| a.starts_with("steam://rungameid/")) { steam_account_for(&id, &st)?; } // Found before the game starts, so a missing engine never leaves a game running without it. let eng = if enhance { Some(engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: set SUMMIT_ENGINE to the engine/ folder"))?) } else { None }; - let (s, d) = (display::detect_session(), display::detect_desktop()); - let 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() && (p.width.is_some() || p.refresh_hz.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 @@ -506,20 +817,25 @@ fn main() -> Result<()> { if let Some(sig) = signals::requested() { std::process::exit(128 + sig); } } Cmd::Console { cmd } => console_cmd(cmd)?, - Cmd::Profile { cmd: ProfileCmd::Show { id, own } } => { - let layer = profile::load_layer(&id)?; - if own { - print!("{}", toml::to_string_pretty(&profile::Layer { version: None, ..layer })?); - } else { - print!("{}", toml::to_string_pretty(&profile::load(&id)?)?); - let set: Vec<&str> = profile::KEYS.iter().copied().filter(|k| layer.has(k)).collect(); - if id != profile::DEFAULT_ID { - println!("# set by {id} itself: {}; the rest from the defaults ({})", if set.is_empty() { "nothing".to_string() } else { set.join(", ") }, profile::file(profile::DEFAULT_ID)?.display()); + Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, window_mode, fullscreen, focus, enhance, upscaler, fsr_sharpness, vsr_quality, framegen, multiplier, target_hz, model, vfg_quality, motion, ai_engine, steady_hud, fill, vsync, watermark, args, env, unset_env, window, game_fps, output_res, individual } } => { + use profile as pr; + // Engine and picture settings belong to the profile the game is on: nothing sits on top of a shared one. + let shared = upscaler.is_some() || fsr_sharpness.is_some() || vsr_quality.is_some() || framegen.is_some() || multiplier.is_some() || target_hz.is_some() || model.is_some() + || vfg_quality.is_some() || motion.is_some() || ai_engine.is_some() || steady_hud.is_some() || fill.is_some() || vsync.is_some() || watermark.is_some() || game_fps.is_some() || output_res.is_some(); + if shared && id != pr::DEFAULT_ID { + let store = Store::user()?; + let r = store.assignment(&id); + if r != Ref::Individual { + if individual { + store.detach(&id)?; + println!("{id} is off {} and Individual: it keeps those settings as its own", r.text()); + } else { + let n = store.games_of(&r, &library().into_iter().map(|(i, _)| i).collect::>()).len(); + anyhow::bail!("{id} uses the profile {} ({n} game{}), and these are a profile's settings.\n change the profile for all of them: summit profile edit {} --set KEY=VALUE{}\n or only this game: add --individual (the game keeps the profile's settings as its own, then this change)", + r.text(), if n == 1 { "" } else { "s" }, r.text(), if r.editable() { "" } else { " (built-in: duplicate it first)" }); + } } } - } - Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, window_mode, fullscreen, focus, enhance, upscaler, fsr_sharpness, vsr_quality, framegen, multiplier, target_hz, model, vfg_quality, motion, ai_engine, steady_hud, fill, vsync, watermark, args, env, unset_env, window, game_fps, output_res } } => { - use profile as pr; let window_mode = match (window_mode, fullscreen) { (Some(m), _) => Some(pick("window-mode", m, pr::WINDOW_MODES, true)?), (None, Some(f)) => Some(if f { "borderless".to_string() } else { String::new() }), @@ -543,7 +859,13 @@ fn main() -> Result<()> { let ai_engine = ai_engine.map(|v| pick("ai-engine", v, pr::AI_ENGINES, true)).transpose()?; let fill = fill.map(|v| pick("fill", v, pr::FILLS, true)).transpose()?; let env: Vec<(String, String)> = env.iter().map(|e| pr::parse_env(e)).collect::>().map_err(|e| anyhow::anyhow!("--env: {e}"))?; + let given: Vec<&str> = [("upscaler", upscaler.is_some()), ("fsr_sharpness", fsr_sharpness.is_some()), ("vsr_quality", vsr_quality.is_some()), ("framegen", framegen.is_some()), + ("framegen_multiplier", multiplier.is_some()), ("target_hz", target_hz.is_some()), ("model", model.is_some()), ("vfg_quality", vfg_quality.is_some()), ("motion", motion.is_some()), + ("ai_engine", ai_engine.is_some()), ("steady_hud", steady_hud.is_some()), ("fill", fill.is_some()), ("vsync", vsync.is_some()), ("watermark", watermark.is_some()), + ("game_fps", game_fps.is_some()), ("output_res", output_res.is_some())].iter().filter(|(_, g)| *g).map(|(k, _)| *k).collect(); let l = pr::update_layer(&id, |l| { + // a value given here by its older name wins over the same setting in the file's [engine] table + for k in &given { l.named_was_set(k); } if let Some(m) = monitor { // a new monitor brings its own mode: the old one's resolution is not kept if l.monitor.as_deref() != Some(m.as_str()) { l.width = None; l.height = None; l.refresh_hz = None; } @@ -588,9 +910,11 @@ fn main() -> Result<()> { if let Some(bad) = keys.iter().find(|k| !profile::KEYS.contains(&k.as_str())) { anyhow::bail!("no setting called {bad}: one of {}", profile::KEYS.join(", ")); } - profile::update_layer(&id, |l| if keys.is_empty() { *l = profile::Layer::default(); } else { for k in &keys { l.unset(k); } })?; + // (which profile the game uses is not a setting: it stays) + profile::update_layer(&id, |l| if keys.is_empty() { *l = profile::Layer { profile: l.profile.clone(), ..Default::default() }; } else { for k in &keys { l.unset(k); } })?; println!("{id}: {} the defaults again", if keys.is_empty() { "everything follows".to_string() } else { format!("{} follow", keys.join(", ")) }); } + Cmd::Profile { cmd } => profile_cmd(cmd)?, Cmd::SteamAdd { id, user, force } => { let ui = summit_core::ui::load(); let def = ui.shortcuts.iter().find(|s| s.id == id) diff --git a/crates/summit-cli/tests/profiles_cli.rs b/crates/summit-cli/tests/profiles_cli.rs new file mode 100644 index 0000000..81bbc76 --- /dev/null +++ b/crates/summit-cli/tests/profiles_cli.rs @@ -0,0 +1,130 @@ +//! The profile commands and the launch planner, through the real `summit` binary: a home of its own, a fake +//! `xrandr` that reports the owner's two screens (a 4K 144 Hz monitor and a 1080p 60 Hz projector), and +//! `summit enhance --dry-run`, which prints the engine command a game would be started with. + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const XRANDR: &str = "#!/bin/sh\ncat <<'X'\nScreen 0: minimum 8 x 8, current 5760 x 2160, maximum 32767 x 32767\nDP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 697mm x 392mm\n 3840x2160 143.99*+ 120.00 60.00\n 2560x1440 143.99 60.00\nHDMI-A-1 connected 1920x1080+3840+0 (normal left inverted right x axis y axis) 1600mm x 900mm\n 1920x1080 60.00*+ 50.00\n 1280x720 60.00\nX\n"; + +struct Home { dir: PathBuf } +impl Home { + fn new(name: &str) -> Home { + let dir = std::env::temp_dir().join(format!("summit-cli-profiles-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("bin")).unwrap(); + let x = dir.join("bin/xrandr"); + std::fs::write(&x, XRANDR).unwrap(); + std::fs::set_permissions(&x, std::fs::Permissions::from_mode(0o755)).unwrap(); + // an engine folder: only its path is used by --dry-run + std::fs::create_dir_all(dir.join("engine")).unwrap(); + std::fs::write(dir.join("engine/run.py"), "").unwrap(); + Home { dir } + } + fn config(&self) -> PathBuf { self.dir.join("config/summit") } + fn run(&self, args: &[&str]) -> (bool, String) { + let path = format!("{}:{}", self.dir.join("bin").display(), std::env::var("PATH").unwrap_or_default()); + let out = Command::new(env!("CARGO_BIN_EXE_summit")).args(args) + .env("HOME", &self.dir).env("XDG_CONFIG_HOME", self.dir.join("config")).env("XDG_DATA_HOME", self.dir.join("data")) + .env("XDG_CACHE_HOME", self.dir.join("cache")).env("XDG_STATE_HOME", self.dir.join("state")) + .env("PATH", path).env("XDG_SESSION_TYPE", "x11").env("DISPLAY", ":99").env_remove("WAYLAND_DISPLAY") + .env("SUMMIT_ENGINE", self.dir.join("engine")).env_remove("SUMMIT_ENGINE_ARGS") + .output().expect("run summit"); + (out.status.success(), format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr))) + } + fn ok(&self, args: &[&str]) -> String { + let (ok, out) = self.run(args); + assert!(ok, "summit {} failed:\n{out}", args.join(" ")); + out + } + fn write(&self, rel: &str, text: &str) { + let f = self.config().join(rel); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + std::fs::write(f, text).unwrap(); + } + fn read(&self, rel: &str) -> String { std::fs::read_to_string(self.config().join(rel)).unwrap_or_default() } +} +impl Drop for Home { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.dir); } } + +fn engine_line(out: &str) -> &str { out.lines().find(|l| l.contains("run.py")).unwrap_or_else(|| panic!("no engine command in:\n{out}")) } + +#[test] +fn one_profile_two_games_two_screens() { + let h = Home::new("two"); + h.ok(&["profile", "new", "Couch"]); + h.ok(&["profile", "edit", "couch", "--set", "scaler=fsr", "--set", "motion=half"]); + h.ok(&["profile", "set", "game:desk", "--monitor", "DP-1", "--window-mode", "borderless"]); + h.ok(&["profile", "set", "game:projector", "--monitor", "HDMI-A-1", "--window-mode", "borderless"]); + h.ok(&["profile", "assign", "game:desk", "couch"]); + h.ok(&["profile", "assign", "game:projector", "Couch"]); + + let desk = h.ok(&["enhance", "window:Desk", "--profile", "game:desk", "--dry-run"]); + let proj = h.ok(&["enhance", "window:Proj", "--profile", "game:projector", "--dry-run"]); + assert!(desk.contains("profile: on DP-1 3840x2160 144 Hz: 3840x2160 (native) · 4x = 120 fps"), "{desk}"); + assert!(proj.contains("profile: on HDMI-A-1 1920x1080 60 Hz: 1920x1080 (native) · 2x = 60 fps"), "{proj}"); + let (d, p) = (engine_line(&desk), engine_line(&proj)); + assert!(d.contains("--hz 120 --fullscreen --monitor=DP-1") && d.contains("--set=output_res=\"screen\"") && d.contains("--set=scaler=\"fsr\""), "{d}"); + assert!(p.contains("--hz 60 --fullscreen --monitor=HDMI-A-1") && p.contains("--set=output_res=\"screen\"") && p.contains("--set=scaler=\"fsr\""), "{p}"); + // the projector needs only 2x: a suggestion says so, with the reason + assert!(proj.contains("suggestion: There is headroom on this screen: try Motion detail Full instead of Half (60 Hz needs only 2x"), "{proj}"); + + // the profile's page: its games and what it comes to on each screen + let show = h.ok(&["profile", "show", "couch"]); + assert!(show.contains("games: game:desk, game:projector"), "{show}"); + assert!(show.contains("on DP-1 3840x2160 144 Hz: 3840x2160 (native) · 4x = 120 fps") && show.contains("on HDMI-A-1 1920x1080 60 Hz: 1920x1080 (native) · 2x = 60 fps"), "{show}"); + + // a change to the profile reaches both games + h.ok(&["profile", "edit", "couch", "--set", "scaler=vsr"]); + for g in ["game:desk", "game:projector"] { + let out = h.ok(&["enhance", "window:X", "--profile", g, "--dry-run"]); + assert!(engine_line(&out).contains("--set=scaler=\"vsr\""), "{out}"); + } + + // an engine setting on a game that uses a shared profile is refused with the two ways on + let (ok, out) = h.run(&["profile", "set", "game:projector", "--upscaler", "bilinear"]); + assert!(!ok && out.contains("uses the profile user:couch (2 games)") && out.contains("summit profile edit user:couch") && out.contains("--individual"), "{out}"); + // only this game: it keeps the profile's settings as its own, then the change + h.ok(&["profile", "set", "game:projector", "--upscaler", "bilinear", "--individual"]); + let out = h.ok(&["enhance", "window:X", "--profile", "game:projector", "--dry-run"]); + let p = engine_line(&out); + assert!(p.contains("--scaler bilinear") && p.contains("--hz 60") && p.contains("--set=motion=\"half\"") && !p.contains("scaler=\"vsr\""), "{p}"); + let list = h.ok(&["profile", "list"]); + let individual = list.split("Individual games").nth(1).unwrap_or_default(); + assert!(individual.contains("game:projector") && !individual.contains("game:desk"), "{list}"); + + // delete: the remaining game keeps what it had + h.ok(&["profile", "delete", "couch"]); + let out = h.ok(&["enhance", "window:X", "--profile", "game:desk", "--dry-run"]); + assert!(engine_line(&out).contains("--hz 120") && engine_line(&out).contains("--set=scaler=\"vsr\""), "{out}"); + assert!(h.read("profiles/game_desk.toml").contains("profile = \"individual\"")); +} + +#[test] +fn older_files_are_migrated_on_the_first_run_and_launch_the_same() { + let h = Home::new("migrate"); + let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("../summit-core/tests/fixtures/profiles-v2"); + for e in std::fs::read_dir(&fixtures).unwrap().flatten() { + h.write(&format!("profiles/{}", e.file_name().to_string_lossy()), &std::fs::read_to_string(e.path()).unwrap()); + } + let before = h.read("profiles/custom_voidrunner.toml"); + let out = h.ok(&["enhance", "window:V", "--profile", "custom:voidrunner", "--dry-run"]); + assert!(out.contains("profiles: updated for shared profiles; the files as they were are in"), "{out}"); + let line = engine_line(&out).to_string(); + // round 2's "Lowest delay" on this game, its own overlay style, its screen: all still passed + for want in ["--monitor=HDMI-A-1", "--set=interp=false", "--set=hz=60", "--set=overlay_style=\"graphs\"", "--set=scaler=\"fsr\"", "--fullscreen"] { assert!(line.contains(want), "{want} in {line}"); } + // the backup has the file as it was, the new file says Individual + let backups: Vec = std::fs::read_dir(h.config().join("backups")).unwrap().flatten().map(|e| e.path()).collect(); + assert_eq!(backups.len(), 1); + assert_eq!(std::fs::read_to_string(backups[0].join("custom_voidrunner.toml")).unwrap(), before); + assert!(h.read("profiles/custom_voidrunner.toml").contains("profile = \"individual\"")); + assert!(h.read("profiles.toml").contains("version = 1")); + // the second run says nothing about it and gives the same command + let again = h.ok(&["enhance", "window:V", "--profile", "custom:voidrunner", "--dry-run"]); + assert!(!again.contains("profiles: updated"), "{again}"); + assert_eq!(engine_line(&again), line); + let list = h.ok(&["profile", "list"]); + let individual = list.split("Individual games").nth(1).unwrap_or_default(); + for g in ["custom_voidrunner", "heroic_oldgame", "steam_1091500"] { assert!(individual.contains(g), "{g} in {list}"); } + assert!(!individual.contains("steam_570"), "{list}"); +} diff --git a/crates/summit-core/src/registry.rs b/crates/summit-core/src/registry.rs index 1989460..7842c6e 100644 --- a/crates/summit-core/src/registry.rs +++ b/crates/summit-core/src/registry.rs @@ -329,6 +329,15 @@ impl Layer { self.engine = (!map.is_empty()).then_some(map); } + /// An older named setting (`upscaler`, `motion`...) was just set in this layer: the same thing in its `engine` + /// table goes, because inside one layer the table wins and the new value would never be used. + pub fn named_was_set(&mut self, named: &str) { + let Some(map) = self.engine.as_mut() else { return }; + map.retain(|k, _| !named_for(k).contains(&named)); + if map.is_empty() { self.engine = None; } + if matches!(named, "framegen_multiplier" | "target_hz") { self.rate = None; } + } + /// Whether this layer by itself decides registry key `key` (through the `engine` table or an older named setting). pub fn sets_engine(&self, key: &str) -> bool { self.engine.as_ref().is_some_and(|m| m.contains_key(key)) || forced(&crate::profile::resolve(&[self])).contains_key(key) @@ -486,6 +495,21 @@ mod tests { assert!(l.is_empty(), "{l:?}"); } + #[test] + fn a_named_setting_set_later_replaces_the_engine_tables_value() { + let mut l = Layer { rate: Some("native".into()), ..Default::default() }; + l.set_engine("scaler", Some(&json!("fsr"))); + l.set_engine("motion", Some(&json!("half"))); + l.rate = Some("native".into()); + l.upscaler = Some("rtx-vsr".into()); + l.named_was_set("upscaler"); + l.framegen_multiplier = Some(3); + l.named_was_set("framegen_multiplier"); + let f = forced(&crate::profile::resolve(&[&l])); + assert_eq!((f.get("scaler"), f.get("motion"), f.get("hz")), (Some(&json!("vsr")), Some(&json!("half")), Some(&json!(90)))); + assert!(l.rate.is_none()); + } + #[test] fn compare_is_built_from_what_the_engine_lists() { let r = Registry::parse(r#"{"path": "/x", "specs": [], "compare": {"dimensions": [ diff --git a/crates/summit-core/src/resolve.rs b/crates/summit-core/src/resolve.rs index b2d6bf8..a28e743 100644 --- a/crates/summit-core/src/resolve.rs +++ b/crates/summit-core/src/resolve.rs @@ -333,6 +333,19 @@ pub fn for_game(p: &Profile, saved: &BTreeMap, outs: &[Output], s } } +/// What a profile comes to on each screen that is on: the lines the Profiles page and `summit profile show` print. +pub fn per_screen(p: &Profile, saved: &BTreeMap, outs: &[Output]) -> Vec { + let want = Wanted::of(p, saved); + // (the window belongs to each game, not to the profile: that sentence is left out here) + screens(outs).iter().map(|s| { let mut r = resolve(&want, Some(s), &SourceFacts::default()); r.why.retain(|w| !w.starts_with("Window:")); r }).collect() +} + +/// The engine's saved settings, read from where the engine keeps them on Linux (`~/.config/smoovplay/settings.json`, +/// framegen/oslayer.py) without starting it. Empty when there is no such file: the engine's defaults then apply. +pub fn saved_settings() -> BTreeMap { + dirs::config_dir().map(|d| crate::registry::read_values(&d.join("smoovplay/settings.json"))).unwrap_or_default() +} + /// Two fake screens for tests and for renders without a display: the owner's desk monitor and projector. pub fn sample_outputs() -> Vec { use crate::display::Mode;