Merge ap/steam-shortcuts
This commit is contained in:
commit
9a1ec8759e
9 files changed
+960
-3
No files matched your search
@@ -63,6 +63,20 @@ enum Cmd {
|
||||
},
|
||||
/// Per-game profile
|
||||
Profile { #[command(subcommand)] cmd: ProfileCmd },
|
||||
/// Add a non-Steam shortcut (from ~/.config/summit/ui.toml `[[shortcuts]]`, default: "ps5", "capture")
|
||||
SteamAdd {
|
||||
id: String,
|
||||
/// Steam user id (the folder name under userdata/); auto-detected if there is only one
|
||||
#[arg(long)] user: Option<String>,
|
||||
/// Write even if Steam looks like it's running
|
||||
#[arg(long)] force: bool,
|
||||
},
|
||||
/// Remove a non-Steam shortcut previously added with `steam-add`
|
||||
SteamRemove {
|
||||
id: String,
|
||||
#[arg(long)] user: Option<String>,
|
||||
#[arg(long)] force: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -88,6 +102,23 @@ enum ProfileCmd {
|
||||
|
||||
fn hours(m: u64) -> String { format!("{:.1} h", m as f64 / 60.0) }
|
||||
|
||||
/// Picks the Steam `userdata/<id>` folder to write shortcuts into.
|
||||
fn resolve_userdata(user: Option<&str>) -> Result<std::path::PathBuf> {
|
||||
let dirs = summit_core::steam::userdata_dirs();
|
||||
if let Some(u) = user {
|
||||
return dirs.into_iter().find(|d| d.file_name().map(|n| n.to_string_lossy() == u).unwrap_or(false))
|
||||
.ok_or_else(|| anyhow::anyhow!("no Steam userdata folder for user id {u}"));
|
||||
}
|
||||
match dirs.len() {
|
||||
0 => anyhow::bail!("no Steam userdata found; has Steam run at least once on this machine?"),
|
||||
1 => Ok(dirs.into_iter().next().unwrap()),
|
||||
_ => anyhow::bail!(
|
||||
"multiple Steam users found ({}); pick one with --user",
|
||||
dirs.iter().filter_map(|d| d.file_name()).map(|n| n.to_string_lossy().into_owned()).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
match Cli::parse().cmd {
|
||||
Cmd::Scan { path, depth, json, why } => {
|
||||
@@ -226,6 +257,47 @@ fn main() -> Result<()> {
|
||||
if model.is_some() { p.model = model; }
|
||||
println!("saved {}", profile::save(&id, &p)?.display());
|
||||
}
|
||||
Cmd::SteamAdd { id, user, force } => {
|
||||
let ui = summit_core::ui::load();
|
||||
let def = ui.shortcuts.iter().find(|s| s.id == id)
|
||||
.ok_or_else(|| anyhow::anyhow!("no shortcut '{id}' in ~/.config/summit/ui.toml [[shortcuts]] (defaults: ps5, capture)"))?
|
||||
.clone();
|
||||
let userdata = resolve_userdata(user.as_deref())?;
|
||||
let config_dir = userdata.join("config");
|
||||
let shortcuts_path = config_dir.join("shortcuts.vdf");
|
||||
let summit_bin = std::env::current_exe()?;
|
||||
let exe = format!("\"{}\"", summit_bin.display());
|
||||
let start_dir = format!("\"{}\"", summit_bin.parent().unwrap_or(std::path::Path::new("/")).display());
|
||||
let shortcut_id = format!("steam-shortcut:{id}");
|
||||
let launch_options = format!("run {shortcut_id} -- {} enhance {}", summit_bin.display(), def.target);
|
||||
|
||||
let mut root = summit_core::shortcuts::load(&shortcuts_path)?;
|
||||
let appid = summit_core::shortcuts::add_shortcut(&mut root, &summit_core::shortcuts::NewShortcut {
|
||||
app_name: &def.name, exe: &exe, launch_options: &launch_options, start_dir: &start_dir, icon: "",
|
||||
});
|
||||
summit_core::shortcuts::save(&shortcuts_path, &root, force)?;
|
||||
|
||||
let grid_id = summit_core::shortcuts::grid_file_id(appid);
|
||||
let state = summit_core::state::load();
|
||||
let sgdb_key = summit_core::sgdb::key();
|
||||
let outcomes = summit_core::shortcuts::install_art(
|
||||
&config_dir.join("grid"), grid_id, &def.name, None, &state, &shortcut_id, sgdb_key.as_deref(),
|
||||
);
|
||||
println!("added '{}' (appid {appid}) to {}", def.name, shortcuts_path.display());
|
||||
for o in outcomes { println!(" {}", o.message); }
|
||||
}
|
||||
Cmd::SteamRemove { id, user, force } => {
|
||||
let ui = summit_core::ui::load();
|
||||
let def = ui.shortcuts.iter().find(|s| s.id == id)
|
||||
.ok_or_else(|| anyhow::anyhow!("no shortcut '{id}' in ~/.config/summit/ui.toml [[shortcuts]]"))?
|
||||
.clone();
|
||||
let userdata = resolve_userdata(user.as_deref())?;
|
||||
let shortcuts_path = userdata.join("config/shortcuts.vdf");
|
||||
let mut root = summit_core::shortcuts::load(&shortcuts_path)?;
|
||||
anyhow::ensure!(summit_core::shortcuts::remove_shortcut(&mut root, &def.name), "'{}' is not in {}", def.name, shortcuts_path.display());
|
||||
summit_core::shortcuts::save(&shortcuts_path, &root, force)?;
|
||||
println!("removed '{}' from {}", def.name, shortcuts_path.display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,7 +7,10 @@ pub mod model;
|
||||
pub mod names;
|
||||
pub mod profile;
|
||||
pub mod scan;
|
||||
pub mod sgdb;
|
||||
pub mod shortcuts;
|
||||
pub mod state;
|
||||
pub mod steam;
|
||||
pub mod ui;
|
||||
pub mod vdf;
|
||||
pub mod vdf_bin;
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Minimal SteamGridDB client: look up a game by title, get one art URL for a grid kind, download it.
|
||||
//! Used only as the last resort in the shortcut artwork chain (see `shortcuts::install_art`);
|
||||
//! a missing API key is not an error, just a reason to skip.
|
||||
use crate::shortcuts::ArtKind;
|
||||
use anyhow::{anyhow, Result};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// `SGDB_API_KEY` env var, else `~/.config/summit/steamgriddb.key`. Empty/missing means "no key".
|
||||
pub fn key() -> Option<String> {
|
||||
if let Ok(k) = std::env::var("SGDB_API_KEY") {
|
||||
let k = k.trim().to_string();
|
||||
if !k.is_empty() { return Some(k); }
|
||||
}
|
||||
let p: PathBuf = dirs::config_dir()?.join("summit/steamgriddb.key");
|
||||
std::fs::read_to_string(p).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// Percent-encodes a title for use in a URL path segment. Only the characters that matter for the
|
||||
/// SteamGridDB search endpoint (space and the usual URL-reserved set) need escaping here.
|
||||
pub fn encode_path_segment(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for b in s.as_bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(*b as char),
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn first_u64(body: &str, path: &[&str]) -> Option<u64> {
|
||||
let v: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
if v.get("success").and_then(|s| s.as_bool()) != Some(true) { return None; }
|
||||
let mut cur = v.get("data")?.as_array()?.first()?;
|
||||
for p in path { cur = cur.get(p)?; }
|
||||
cur.as_u64()
|
||||
}
|
||||
|
||||
fn first_str(body: &str, path: &[&str]) -> Option<String> {
|
||||
let v: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
if v.get("success").and_then(|s| s.as_bool()) != Some(true) { return None; }
|
||||
let mut cur = v.get("data")?.as_array()?.first()?;
|
||||
for p in path { cur = cur.get(p)?; }
|
||||
cur.as_str().map(String::from)
|
||||
}
|
||||
|
||||
pub fn parse_search(body: &str) -> Option<u64> { first_u64(body, &["id"]) }
|
||||
pub fn parse_art_url(body: &str) -> Option<String> { first_str(body, &["url"]) }
|
||||
|
||||
fn endpoint(kind: ArtKind) -> (&'static str, Option<&'static str>) {
|
||||
match kind {
|
||||
ArtKind::Portrait => ("grids", Some("600x900")),
|
||||
ArtKind::Wide => ("grids", Some("460x215,920x430")),
|
||||
ArtKind::Hero => ("heroes", None),
|
||||
ArtKind::Logo => ("logos", None),
|
||||
ArtKind::Icon => ("icons", None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the SteamGridDB game id for a title. `None` means "no match", not an error.
|
||||
pub fn search_game(key: &str, title: &str) -> Result<Option<u64>> {
|
||||
let url = format!("https://www.steamgriddb.com/api/v2/search/autocomplete/{}", encode_path_segment(title));
|
||||
let body = ureq::get(&url).set("Authorization", &format!("Bearer {key}")).call()
|
||||
.map_err(|e| anyhow!("SteamGridDB search for {title:?} failed: {e}"))?
|
||||
.into_string()?;
|
||||
Ok(parse_search(&body))
|
||||
}
|
||||
|
||||
/// Finds one art URL of `kind` for a SteamGridDB game id. `None` means "none published", not an error.
|
||||
pub fn art_url(key: &str, game_id: u64, kind: ArtKind) -> Result<Option<String>> {
|
||||
let (ep, dims) = endpoint(kind);
|
||||
let mut url = format!("https://www.steamgriddb.com/api/v2/{ep}/game/{game_id}");
|
||||
if let Some(d) = dims { url = format!("{url}?dimensions={d}"); }
|
||||
let body = ureq::get(&url).set("Authorization", &format!("Bearer {key}")).call()
|
||||
.map_err(|e| anyhow!("SteamGridDB {ep} lookup failed: {e}"))?
|
||||
.into_string()?;
|
||||
Ok(parse_art_url(&body))
|
||||
}
|
||||
|
||||
pub fn download(url: &str) -> Result<Vec<u8>> {
|
||||
let resp = ureq::get(url).call().map_err(|e| anyhow!("downloading {url} failed: {e}"))?;
|
||||
let mut buf = Vec::new();
|
||||
std::io::copy(&mut resp.into_reader(), &mut buf)?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_search_result() {
|
||||
let body = r#"{"success":true,"data":[{"id":5247,"name":"Portal 2"},{"id":9}]}"#;
|
||||
assert_eq!(parse_search(body), Some(5247));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_art_url() {
|
||||
let body = r#"{"success":true,"data":[{"id":1,"url":"https://cdn/x.png"}]}"#;
|
||||
assert_eq!(parse_art_url(body), Some("https://cdn/x.png".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_and_empty_are_none() {
|
||||
assert_eq!(parse_search(r#"{"success":false}"#), None);
|
||||
assert_eq!(parse_search(r#"{"success":true,"data":[]}"#), None);
|
||||
assert_eq!(parse_search("not json"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_spaces_and_punctuation() {
|
||||
assert_eq!(encode_path_segment("My PS5: Game!"), "My%20PS5%3A%20Game%21");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoints_pick_expected_dimensions() {
|
||||
assert_eq!(endpoint(ArtKind::Portrait), ("grids", Some("600x900")));
|
||||
assert_eq!(endpoint(ArtKind::Hero), ("heroes", None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
//! Non-Steam shortcuts: add/remove entries in `userdata/<id>/config/shortcuts.vdf`, and install
|
||||
//! grid artwork for them into `userdata/<id>/config/grid`.
|
||||
//!
|
||||
//! Writing is careful on purpose: the file is backed up before every write, and a write is
|
||||
//! refused while Steam is running (it keeps the file open and caches it in memory) unless the
|
||||
//! caller passes `force`. Unknown fields in existing entries are preserved byte-for-byte.
|
||||
use crate::vdf_bin::{self, BVal};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ---- appid, the way Steam computes it for a non-Steam shortcut ----
|
||||
|
||||
/// CRC-32/ISO-HDLC (the same one `zlib.crc32`/Python's `binascii.crc32` use).
|
||||
pub fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc: u32 = 0xFFFF_FFFF;
|
||||
for &byte in data {
|
||||
crc ^= byte as u32;
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// The 32-bit "legacy" id Steam stores in the shortcut's `appid` field: CRC-32 of the exe path
|
||||
/// and app name concatenated, with the top bit forced on to mark it as a non-Steam shortcut.
|
||||
pub fn legacy_app_id(exe: &str, app_name: &str) -> u32 {
|
||||
crc32(format!("{exe}{app_name}").as_bytes()) | 0x8000_0000
|
||||
}
|
||||
|
||||
/// The id that names grid artwork files (`<id>p.png`, `<id>_hero.png`, ...) in the current Steam
|
||||
/// client: the shortcut's unsigned 32-bit appid.
|
||||
pub fn grid_file_id(legacy: u32) -> u64 { legacy as u64 }
|
||||
|
||||
/// The older 64-bit "Big Picture" id (legacy id in the high 32 bits, 0x02000000 in the low).
|
||||
/// Not used for artwork file names by the current client; kept for reference/tests.
|
||||
pub fn grid_app_id(legacy: u32) -> u64 { ((legacy as u64) << 32) | 0x0200_0000 }
|
||||
|
||||
// ---- the shortcuts list itself ----
|
||||
|
||||
pub fn empty_root() -> Vec<(String, BVal)> { vec![("shortcuts".to_string(), BVal::Map(vec![]))] }
|
||||
|
||||
fn ensure_shortcuts(root: &mut Vec<(String, BVal)>) -> &mut Vec<(String, BVal)> {
|
||||
if !root.iter().any(|(k, _)| k.eq_ignore_ascii_case("shortcuts")) {
|
||||
root.push(("shortcuts".to_string(), BVal::Map(vec![])));
|
||||
}
|
||||
match &mut root.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case("shortcuts")).unwrap().1 {
|
||||
BVal::Map(m) => m,
|
||||
_ => unreachable!("shortcuts key is always a map"),
|
||||
}
|
||||
}
|
||||
|
||||
fn shortcuts_ref(root: &[(String, BVal)]) -> &[(String, BVal)] {
|
||||
root.iter().find(|(k, _)| k.eq_ignore_ascii_case("shortcuts")).and_then(|(_, v)| v.map()).unwrap_or(&[])
|
||||
}
|
||||
|
||||
fn find_field<'a>(entry: &'a [(String, BVal)], key: &str) -> Option<&'a BVal> {
|
||||
entry.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// Finds a shortcut entry by its `AppName`.
|
||||
pub fn find_by_name<'a>(root: &'a [(String, BVal)], app_name: &str) -> Option<&'a [(String, BVal)]> {
|
||||
shortcuts_ref(root).iter().find_map(|(_, v)| match v {
|
||||
BVal::Map(m) if find_field(m, "AppName").and_then(|v| v.str()) == Some(app_name) => Some(m.as_slice()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// All `AppName`s currently in the file, in order.
|
||||
pub fn list_names(root: &[(String, BVal)]) -> Vec<String> {
|
||||
shortcuts_ref(root).iter().filter_map(|(_, v)| find_field(v.map()?, "AppName")?.str()).map(String::from).collect()
|
||||
}
|
||||
|
||||
pub struct NewShortcut<'a> {
|
||||
pub app_name: &'a str,
|
||||
/// Quoted path to the executable Steam launches (for Summit shortcuts, the `summit` binary).
|
||||
pub exe: &'a str,
|
||||
pub launch_options: &'a str,
|
||||
pub start_dir: &'a str,
|
||||
/// Icon shown in the Steam library list; empty string if none.
|
||||
pub icon: &'a str,
|
||||
}
|
||||
|
||||
/// Adds (or replaces, if an entry with the same `AppName` exists) a shortcut. Returns its appid.
|
||||
pub fn add_shortcut(root: &mut Vec<(String, BVal)>, s: &NewShortcut) -> u32 {
|
||||
let legacy = legacy_app_id(s.exe, s.app_name);
|
||||
let fields = vec![
|
||||
("appid".to_string(), BVal::Int32(legacy as i32)),
|
||||
("AppName".to_string(), BVal::Str(s.app_name.to_string())),
|
||||
("Exe".to_string(), BVal::Str(s.exe.to_string())),
|
||||
("StartDir".to_string(), BVal::Str(s.start_dir.to_string())),
|
||||
("icon".to_string(), BVal::Str(s.icon.to_string())),
|
||||
("ShortcutPath".to_string(), BVal::Str(String::new())),
|
||||
("LaunchOptions".to_string(), BVal::Str(s.launch_options.to_string())),
|
||||
("IsHidden".to_string(), BVal::Int32(0)),
|
||||
("AllowDesktopConfig".to_string(), BVal::Int32(1)),
|
||||
("AllowOverlay".to_string(), BVal::Int32(1)),
|
||||
("OpenVR".to_string(), BVal::Int32(0)),
|
||||
("Devkit".to_string(), BVal::Int32(0)),
|
||||
("DevkitGameID".to_string(), BVal::Str(String::new())),
|
||||
("DevkitOverrideAppID".to_string(), BVal::Int32(0)),
|
||||
("LastPlayTime".to_string(), BVal::Int32(0)),
|
||||
("FlatpakAppID".to_string(), BVal::Str(String::new())),
|
||||
("tags".to_string(), BVal::Map(vec![])),
|
||||
];
|
||||
let map = ensure_shortcuts(root);
|
||||
map.retain(|(_, v)| match v { BVal::Map(m) => find_field(m, "AppName").and_then(|v| v.str()) != Some(s.app_name), _ => true });
|
||||
let next_index = map.len();
|
||||
map.push((next_index.to_string(), BVal::Map(fields)));
|
||||
renumber(map);
|
||||
legacy
|
||||
}
|
||||
|
||||
/// Removes the shortcut with this `AppName`. Returns whether one was found.
|
||||
pub fn remove_shortcut(root: &mut Vec<(String, BVal)>, app_name: &str) -> bool {
|
||||
let map = ensure_shortcuts(root);
|
||||
let before = map.len();
|
||||
map.retain(|(_, v)| match v { BVal::Map(m) => find_field(m, "AppName").and_then(|v| v.str()) != Some(app_name), _ => true });
|
||||
let removed = map.len() != before;
|
||||
if removed { renumber(map); }
|
||||
removed
|
||||
}
|
||||
|
||||
/// Steam keys entries "0", "1", ... in order; keep that true after add/remove.
|
||||
fn renumber(map: &mut [(String, BVal)]) {
|
||||
for (i, (k, _)) in map.iter_mut().enumerate() { *k = i.to_string(); }
|
||||
}
|
||||
|
||||
// ---- file I/O: backup, and refuse to write while Steam runs unless forced ----
|
||||
|
||||
pub fn backup_path(p: &Path) -> PathBuf {
|
||||
let mut s = p.as_os_str().to_os_string();
|
||||
s.push(".bak");
|
||||
PathBuf::from(s)
|
||||
}
|
||||
|
||||
/// Checked against `/proc` so it can be unit tested with a fake directory.
|
||||
pub fn is_steam_running_in(proc_dir: &Path) -> bool {
|
||||
let Ok(rd) = std::fs::read_dir(proc_dir) else { return false };
|
||||
for e in rd.flatten() {
|
||||
if !e.file_name().to_string_lossy().chars().all(|c| c.is_ascii_digit()) { continue; }
|
||||
if let Ok(comm) = std::fs::read_to_string(e.path().join("comm")) {
|
||||
if comm.trim().eq_ignore_ascii_case("steam") { return true; }
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn is_steam_running() -> bool { is_steam_running_in(Path::new("/proc")) }
|
||||
|
||||
/// Missing file reads as an empty shortcuts list.
|
||||
pub fn load(path: &Path) -> Result<Vec<(String, BVal)>> {
|
||||
if !path.exists() { return Ok(empty_root()); }
|
||||
let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?;
|
||||
vdf_bin::parse(&bytes).map_err(|e| anyhow::anyhow!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Backs up the existing file (if any), then writes atomically. Refuses while Steam is running
|
||||
/// unless `force` is set, since Steam keeps the file open and would overwrite our change on exit.
|
||||
pub fn save(path: &Path, root: &[(String, BVal)], force: bool) -> Result<()> {
|
||||
save_checking(path, root, force, Path::new("/proc"))
|
||||
}
|
||||
|
||||
fn save_checking(path: &Path, root: &[(String, BVal)], force: bool, proc_dir: &Path) -> Result<()> {
|
||||
if !force && is_steam_running_in(proc_dir) {
|
||||
bail!("Steam appears to be running; close it first, or pass --force (Steam may overwrite this change on exit)");
|
||||
}
|
||||
if let Some(d) = path.parent() { std::fs::create_dir_all(d)?; }
|
||||
if path.exists() { std::fs::copy(path, backup_path(path))?; }
|
||||
let tmp = path.with_extension("vdf.tmp");
|
||||
std::fs::write(&tmp, vdf_bin::write(root))?;
|
||||
std::fs::rename(tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- grid artwork ----
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ArtKind { Portrait, Wide, Hero, Logo, Icon }
|
||||
|
||||
impl ArtKind {
|
||||
fn suffix(&self) -> &'static str {
|
||||
match self { ArtKind::Portrait => "p", ArtKind::Wide => "", ArtKind::Hero => "_hero", ArtKind::Logo => "_logo", ArtKind::Icon => "_icon" }
|
||||
}
|
||||
pub const ALL: [ArtKind; 5] = [ArtKind::Portrait, ArtKind::Wide, ArtKind::Hero, ArtKind::Logo, ArtKind::Icon];
|
||||
}
|
||||
|
||||
pub fn grid_filename(grid_id: u64, kind: ArtKind, ext: &str) -> String { format!("{grid_id}{}.{ext}", kind.suffix()) }
|
||||
|
||||
fn ext_of(p: &Path) -> &str { p.extension().and_then(|e| e.to_str()).unwrap_or("png") }
|
||||
|
||||
/// Copies `src` into `grid_dir` under the filename Steam expects for `kind`.
|
||||
pub fn install_from_file(grid_dir: &Path, grid_id: u64, kind: ArtKind, src: &Path) -> Result<PathBuf> {
|
||||
std::fs::create_dir_all(grid_dir)?;
|
||||
let dest = grid_dir.join(grid_filename(grid_id, kind, ext_of(src)));
|
||||
std::fs::copy(src, &dest).with_context(|| format!("copying {} to {}", src.display(), dest.display()))?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
pub fn install_from_bytes(grid_dir: &Path, grid_id: u64, kind: ArtKind, ext: &str, bytes: &[u8]) -> Result<PathBuf> {
|
||||
std::fs::create_dir_all(grid_dir)?;
|
||||
let dest = grid_dir.join(grid_filename(grid_id, kind, ext));
|
||||
std::fs::write(&dest, bytes)?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
/// Where custom art for an entry's own id would come from, per art kind (mirrors how the GUI
|
||||
/// already stores "primary", "#hero" and "#logo" custom art in `State::artwork`).
|
||||
pub fn custom_art_path(state: &crate::state::State, id: &str, kind: ArtKind) -> Option<PathBuf> {
|
||||
let s = match kind {
|
||||
ArtKind::Portrait | ArtKind::Wide | ArtKind::Icon => state.artwork.get(id).map(String::as_str),
|
||||
ArtKind::Hero => state.hero_art(id),
|
||||
ArtKind::Logo => state.logo_art(id),
|
||||
}?;
|
||||
let p = PathBuf::from(s);
|
||||
p.is_file().then_some(p)
|
||||
}
|
||||
|
||||
/// Steam's own library cache, for entries that have a Steam app id.
|
||||
pub fn steam_cache_path(app_id: u32, kind: ArtKind) -> Option<PathBuf> {
|
||||
match kind {
|
||||
ArtKind::Portrait => crate::steam::cover(app_id),
|
||||
ArtKind::Wide => crate::steam::wide(app_id),
|
||||
ArtKind::Hero => crate::steam::hero(app_id),
|
||||
ArtKind::Logo => crate::steam::logo(app_id),
|
||||
ArtKind::Icon => None, // Steam's cache has no reliably-named icon file
|
||||
}
|
||||
}
|
||||
|
||||
/// One art kind's outcome, for the CLI to print.
|
||||
pub struct ArtOutcome { pub kind: ArtKind, pub message: String }
|
||||
|
||||
fn kind_name(k: ArtKind) -> &'static str {
|
||||
match k { ArtKind::Portrait => "portrait", ArtKind::Wide => "wide", ArtKind::Hero => "hero", ArtKind::Logo => "logo", ArtKind::Icon => "icon" }
|
||||
}
|
||||
|
||||
/// Tries, in order: the entry's own custom art, Steam's library cache (if it has a Steam app id),
|
||||
/// then SteamGridDB (if a key is configured). Never returns an error for a missing source or a
|
||||
/// missing SteamGridDB key -- those are reported as a skip message so one missing image never
|
||||
/// fails the whole `steam-add`.
|
||||
pub fn install_art(
|
||||
grid_dir: &Path,
|
||||
grid_id: u64,
|
||||
title: &str,
|
||||
steam_app_id: Option<u32>,
|
||||
state: &crate::state::State,
|
||||
entry_id: &str,
|
||||
sgdb_key: Option<&str>,
|
||||
) -> Vec<ArtOutcome> {
|
||||
ArtKind::ALL.iter().map(|&kind| {
|
||||
let message = if let Some(p) = custom_art_path(state, entry_id, kind) {
|
||||
match install_from_file(grid_dir, grid_id, kind, &p) {
|
||||
Ok(dest) => format!("{}: installed from your custom art ({})", kind_name(kind), dest.display()),
|
||||
Err(e) => format!("{}: failed to copy your custom art: {e}", kind_name(kind)),
|
||||
}
|
||||
} else if let Some(p) = steam_app_id.and_then(|id| steam_cache_path(id, kind)) {
|
||||
match install_from_file(grid_dir, grid_id, kind, &p) {
|
||||
Ok(dest) => format!("{}: installed from Steam's library cache ({})", kind_name(kind), dest.display()),
|
||||
Err(e) => format!("{}: failed to copy from Steam's library cache: {e}", kind_name(kind)),
|
||||
}
|
||||
} else if let Some(key) = sgdb_key {
|
||||
match fetch_from_sgdb(grid_dir, grid_id, kind, title, key) {
|
||||
Ok(Some(dest)) => format!("{}: installed from SteamGridDB ({})", kind_name(kind), dest.display()),
|
||||
Ok(None) => format!("{}: skipped, no matching art on SteamGridDB", kind_name(kind)),
|
||||
Err(e) => format!("{}: SteamGridDB lookup failed: {e}", kind_name(kind)),
|
||||
}
|
||||
} else {
|
||||
format!(
|
||||
"{}: skipped, no SteamGridDB key (set SGDB_API_KEY or ~/.config/summit/steamgriddb.key)",
|
||||
kind_name(kind)
|
||||
)
|
||||
};
|
||||
ArtOutcome { kind, message }
|
||||
}).collect()
|
||||
}
|
||||
|
||||
fn fetch_from_sgdb(grid_dir: &Path, grid_id: u64, kind: ArtKind, title: &str, key: &str) -> Result<Option<PathBuf>> {
|
||||
let Some(game_id) = crate::sgdb::search_game(key, title)? else { return Ok(None) };
|
||||
let Some(url) = crate::sgdb::art_url(key, game_id, kind)? else { return Ok(None) };
|
||||
let bytes = crate::sgdb::download(&url)?;
|
||||
let ext = url.rsplit('.').next().filter(|e| e.len() <= 4).unwrap_or("png");
|
||||
Ok(Some(install_from_bytes(grid_dir, grid_id, kind, ext, &bytes)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("summit-shortcuts-test-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crc32_matches_known_vector() {
|
||||
// Standard CRC-32/ISO-HDLC test vector.
|
||||
assert_eq!(crc32(b"The quick brown fox jumps over the lazy dog"), 0x414F_A339);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_id_has_top_bit_set_and_grid_id_shifts_it() {
|
||||
let legacy = legacy_app_id("/usr/bin/summit", "My PS5");
|
||||
assert_ne!(legacy & 0x8000_0000, 0);
|
||||
let grid = grid_app_id(legacy);
|
||||
assert_eq!(grid >> 32, legacy as u64);
|
||||
assert_eq!(grid & 0xFFFF_FFFF, 0x0200_0000);
|
||||
assert_eq!(grid_file_id(legacy), legacy as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_then_find_then_remove() {
|
||||
let mut root = empty_root();
|
||||
let appid = add_shortcut(&mut root, &NewShortcut {
|
||||
app_name: "My PS5", exe: "\"/usr/bin/summit\"", launch_options: "run x -- y",
|
||||
start_dir: "\"/home/u\"", icon: "",
|
||||
});
|
||||
assert_eq!(appid, legacy_app_id("\"/usr/bin/summit\"", "My PS5"));
|
||||
let e = find_by_name(&root, "My PS5").unwrap();
|
||||
assert_eq!(find_field(e, "AppName").unwrap().str(), Some("My PS5"));
|
||||
assert_eq!(find_field(e, "LaunchOptions").unwrap().str(), Some("run x -- y"));
|
||||
assert_eq!(list_names(&root), vec!["My PS5".to_string()]);
|
||||
assert!(remove_shortcut(&mut root, "My PS5"));
|
||||
assert!(find_by_name(&root, "My PS5").is_none());
|
||||
assert!(!remove_shortcut(&mut root, "My PS5")); // already gone
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn re_adding_same_name_replaces_and_keeps_others() {
|
||||
let mut root = empty_root();
|
||||
add_shortcut(&mut root, &NewShortcut { app_name: "A", exe: "a", launch_options: "", start_dir: "", icon: "" });
|
||||
add_shortcut(&mut root, &NewShortcut { app_name: "B", exe: "b", launch_options: "", start_dir: "", icon: "" });
|
||||
add_shortcut(&mut root, &NewShortcut { app_name: "A", exe: "a2", launch_options: "", start_dir: "", icon: "" });
|
||||
assert_eq!(list_names(&root).len(), 2);
|
||||
let e = find_by_name(&root, "A").unwrap();
|
||||
assert_eq!(find_field(e, "Exe").unwrap().str(), Some("a2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_fields_in_an_existing_entry_survive_add_and_remove() {
|
||||
let mut root = empty_root();
|
||||
let shortcuts = ensure_shortcuts(&mut root);
|
||||
shortcuts.push(("0".to_string(), BVal::Map(vec![
|
||||
("AppName".to_string(), BVal::Str("Existing".to_string())),
|
||||
("SomeFutureField".to_string(), BVal::Int32(99)),
|
||||
])));
|
||||
add_shortcut(&mut root, &NewShortcut { app_name: "New", exe: "e", launch_options: "", start_dir: "", icon: "" });
|
||||
let e = find_by_name(&root, "Existing").unwrap();
|
||||
assert_eq!(find_field(e, "SomeFutureField").unwrap().int32(), Some(99));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_roundtrip_through_a_file() {
|
||||
let d = tmp("roundtrip");
|
||||
let path = d.join("shortcuts.vdf");
|
||||
let mut root = load(&path).unwrap(); // missing file -> empty
|
||||
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
|
||||
let reloaded = load(&path).unwrap();
|
||||
assert_eq!(list_names(&reloaded), vec!["My PS5".to_string()]);
|
||||
// second write backs up the first
|
||||
add_shortcut(&mut root, &NewShortcut { app_name: "Capture Card", exe: "/usr/bin/summit", launch_options: "run capture", start_dir: "/", icon: "" });
|
||||
save_checking(&path, &root, false, &tmp("no-steam-proc2")).unwrap();
|
||||
assert!(backup_path(&path).exists());
|
||||
let reloaded = load(&path).unwrap();
|
||||
assert_eq!(list_names(&reloaded), vec!["My PS5".to_string(), "Capture Card".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_to_write_while_steam_runs_unless_forced() {
|
||||
let proc = tmp("fake-proc-steam");
|
||||
let pid = proc.join("4242");
|
||||
fs::create_dir_all(&pid).unwrap();
|
||||
fs::write(pid.join("comm"), "steam\n").unwrap();
|
||||
assert!(is_steam_running_in(&proc));
|
||||
|
||||
let d = tmp("refuse-write");
|
||||
let path = d.join("shortcuts.vdf");
|
||||
let root = empty_root();
|
||||
let err = save_checking(&path, &root, false, &proc).unwrap_err();
|
||||
assert!(err.to_string().contains("Steam appears to be running"));
|
||||
assert!(!path.exists());
|
||||
save_checking(&path, &root, true, &proc).unwrap(); // forced: succeeds
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steam_not_running_when_no_process_named_steam() {
|
||||
let proc = tmp("fake-proc-clean");
|
||||
fs::create_dir_all(proc.join("1")).unwrap();
|
||||
fs::write(proc.join("1/comm"), "systemd\n").unwrap();
|
||||
fs::create_dir_all(proc.join("not-a-pid")).unwrap(); // ignored: not all digits
|
||||
assert!(!is_steam_running_in(&proc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_filenames_match_steams_convention() {
|
||||
let id = 12345u64;
|
||||
assert_eq!(grid_filename(id, ArtKind::Portrait, "jpg"), "12345p.jpg");
|
||||
assert_eq!(grid_filename(id, ArtKind::Wide, "jpg"), "12345.jpg");
|
||||
assert_eq!(grid_filename(id, ArtKind::Hero, "jpg"), "12345_hero.jpg");
|
||||
assert_eq!(grid_filename(id, ArtKind::Logo, "png"), "12345_logo.png");
|
||||
assert_eq!(grid_filename(id, ArtKind::Icon, "png"), "12345_icon.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_art_prefers_custom_then_steam_cache_then_skips() {
|
||||
let d = tmp("art-chain");
|
||||
let grid_dir = d.join("grid");
|
||||
// Custom art set for the entry id.
|
||||
let custom_img = d.join("cover.png");
|
||||
fs::write(&custom_img, b"custom").unwrap();
|
||||
let mut state = crate::state::State::default();
|
||||
state.artwork.insert("custom:x".to_string(), custom_img.to_string_lossy().into_owned());
|
||||
|
||||
let outcomes = install_art(&grid_dir, 999, "Some Game", None, &state, "custom:x", None);
|
||||
let portrait = outcomes.iter().find(|o| o.kind == ArtKind::Portrait).unwrap();
|
||||
assert!(portrait.message.contains("your custom art"));
|
||||
assert!(grid_dir.join("999p.png").exists());
|
||||
|
||||
let hero = outcomes.iter().find(|o| o.kind == ArtKind::Hero).unwrap();
|
||||
assert!(hero.message.contains("skipped, no SteamGridDB key"));
|
||||
assert!(!grid_dir.join("999_hero.png").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_art_falls_back_to_steam_cache_for_steam_entries() {
|
||||
// steam::cover reads from Steam's own roots, which we cannot fake without touching a real
|
||||
// Steam install; this test only checks that a Steam app id with no cache present still
|
||||
// produces a clean skip message rather than an error.
|
||||
let d = tmp("art-steam-fallback");
|
||||
let grid_dir = d.join("grid");
|
||||
let state = crate::state::State::default();
|
||||
let outcomes = install_art(&grid_dir, 1, "No Cache Game", Some(999_999_999), &state, "steam:999999999", None);
|
||||
assert!(outcomes.iter().all(|o| o.message.contains("skipped")));
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,20 @@ pub fn playtime(root: &Path) -> HashMap<u32, (u64, u64)> {
|
||||
map
|
||||
}
|
||||
|
||||
/// Every `userdata/<id>` folder across all detected Steam installs (one per local Steam account).
|
||||
pub fn userdata_dirs() -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for root in steam_roots() {
|
||||
let Ok(rd) = std::fs::read_dir(root.join("userdata")) else { continue };
|
||||
for e in rd.flatten() {
|
||||
if e.path().is_dir() && e.file_name().to_string_lossy().chars().all(|c| c.is_ascii_digit()) {
|
||||
out.push(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn is_tool(name: &str) -> bool {
|
||||
let n = name.to_ascii_lowercase();
|
||||
n.starts_with("proton") || n.starts_with("steam linux runtime") || n.starts_with("steamworks common")
|
||||
@@ -148,6 +162,9 @@ pub fn hero(app_id: u32) -> Option<PathBuf> { 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<PathBuf> { art(app_id, &["logo.png"]) }
|
||||
|
||||
/// Wide library capsule (header.jpg), distinct from the portrait cover.
|
||||
pub fn wide(app_id: u32) -> Option<PathBuf> { art(app_id, &["header.jpg"]) }
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -27,11 +27,36 @@ pub struct UiSettings {
|
||||
pub replay_seconds: u32,
|
||||
/// Instant replay: how many seconds a save writes. Never more than `replay_seconds`.
|
||||
pub clip_seconds: u32,
|
||||
/// Steam shortcuts `summit steam-add`/`steam-remove` know about. Defaults to the two
|
||||
/// built-ins ("My PS5", "Capture Card"); edit or add to this list to change what they do.
|
||||
#[serde(default = "default_shortcuts")]
|
||||
pub shortcuts: Vec<ShortcutDef>,
|
||||
}
|
||||
|
||||
/// One entry `summit steam-add <id>` can create as a non-Steam Steam shortcut.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ShortcutDef {
|
||||
/// What `summit steam-add`/`steam-remove` take on the command line.
|
||||
pub id: String,
|
||||
/// The name Steam shows for the shortcut.
|
||||
pub name: String,
|
||||
/// Passed to `summit enhance <target>` (e.g. "ps5" or "capture:0").
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
fn default_shortcuts() -> Vec<ShortcutDef> {
|
||||
vec![
|
||||
ShortcutDef { id: "ps5".into(), name: "My PS5".into(), target: "ps5".into() },
|
||||
ShortcutDef { id: "capture".into(), name: "Capture Card".into(), target: "capture:0".into() },
|
||||
]
|
||||
}
|
||||
|
||||
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 }
|
||||
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, shortcuts: default_shortcuts(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +119,7 @@ mod tests {
|
||||
#[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 };
|
||||
let s = UiSettings { layout: "list".into(), theme: "violet".into(), anim_speed: 0.0, anim_style: "snappy".into(), ui_scale: 1.25, replay_seconds: 600, clip_seconds: 180, shortcuts: default_shortcuts() };
|
||||
save_to(&p, &s).unwrap();
|
||||
assert_eq!(load_from(&p), s);
|
||||
assert!(!p.with_extension("toml.tmp").exists());
|
||||
@@ -116,7 +141,7 @@ mod tests {
|
||||
}
|
||||
#[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();
|
||||
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, shortcuts: vec![] }.sanitized();
|
||||
assert_eq!(s.layout, "bigpicture");
|
||||
assert_eq!(s.theme, "midnight");
|
||||
assert_eq!(s.anim_speed, 2.0);
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Binary KeyValues (the format Steam uses for `userdata/<id>/config/shortcuts.vdf`).
|
||||
//!
|
||||
//! Layout: one key-type byte, a nul-terminated key name, then a value whose shape depends on
|
||||
//! the type byte. Type 0x00 is a nested map (itself a sequence of key/value pairs, closed by a
|
||||
//! 0x08 byte); the file as a whole is one unclosed map at the top level (EOF ends it instead of
|
||||
//! a 0x08). Types we don't otherwise interpret (float32, pointer, color, (u)int64, wstring) are
|
||||
//! kept as raw bytes so a round trip never drops a field Steam wrote that we don't understand.
|
||||
use std::fmt;
|
||||
|
||||
const T_MAP: u8 = 0x00;
|
||||
const T_STR: u8 = 0x01;
|
||||
const T_INT32: u8 = 0x02;
|
||||
const T_FLOAT32: u8 = 0x03;
|
||||
const T_POINTER: u8 = 0x04;
|
||||
const T_WSTRING: u8 = 0x05;
|
||||
const T_COLOR: u8 = 0x06;
|
||||
const T_UINT64: u8 = 0x07;
|
||||
const T_END: u8 = 0x08;
|
||||
const T_INT64: u8 = 0x0A;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BVal {
|
||||
Map(Vec<(String, BVal)>),
|
||||
Str(String),
|
||||
Int32(i32),
|
||||
/// A type we don't give special meaning to; kept byte-exact so writing it back is lossless.
|
||||
Raw(u8, Vec<u8>),
|
||||
}
|
||||
|
||||
impl BVal {
|
||||
pub fn get(&self, key: &str) -> Option<&BVal> {
|
||||
match self {
|
||||
BVal::Map(kv) => kv.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn str(&self) -> Option<&str> { match self { BVal::Str(s) => Some(s), _ => None } }
|
||||
pub fn int32(&self) -> Option<i32> { match self { BVal::Int32(i) => Some(*i), _ => None } }
|
||||
pub fn map(&self) -> Option<&[(String, BVal)]> { match self { BVal::Map(m) => Some(m), _ => None } }
|
||||
}
|
||||
|
||||
fn tag_of(v: &BVal) -> u8 {
|
||||
match v { BVal::Map(_) => T_MAP, BVal::Str(_) => T_STR, BVal::Int32(_) => T_INT32, BVal::Raw(t, _) => *t }
|
||||
}
|
||||
|
||||
fn raw_len(tag: u8) -> Option<usize> {
|
||||
match tag {
|
||||
T_FLOAT32 | T_POINTER | T_COLOR => Some(4),
|
||||
T_UINT64 | T_INT64 => Some(8),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_cstr(b: &[u8], i: &mut usize) -> Result<String, String> {
|
||||
let start = *i;
|
||||
while *i < b.len() && b[*i] != 0 { *i += 1; }
|
||||
if *i >= b.len() { return Err("unterminated string".into()); }
|
||||
let s = String::from_utf8_lossy(&b[start..*i]).into_owned();
|
||||
*i += 1; // skip the nul
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Reads a nul-terminated UTF-16LE string's raw bytes (including the trailing 2-byte nul), for
|
||||
/// the rare BIN_WSTRING field. We don't need the text, just to preserve it untouched.
|
||||
fn read_wstr_raw(b: &[u8], i: &mut usize) -> Result<Vec<u8>, String> {
|
||||
let start = *i;
|
||||
loop {
|
||||
if *i + 1 >= b.len() { return Err("unterminated wide string".into()); }
|
||||
if b[*i] == 0 && b[*i + 1] == 0 { *i += 2; break; }
|
||||
*i += 2;
|
||||
}
|
||||
Ok(b[start..*i].to_vec())
|
||||
}
|
||||
|
||||
fn parse_map(b: &[u8], i: &mut usize, bounded: bool) -> Result<Vec<(String, BVal)>, String> {
|
||||
let mut kv = Vec::new();
|
||||
loop {
|
||||
if *i >= b.len() {
|
||||
if bounded { return Err("unexpected end of file inside a map".into()); }
|
||||
return Ok(kv);
|
||||
}
|
||||
let tag = b[*i]; *i += 1;
|
||||
if tag == T_END {
|
||||
if bounded { return Ok(kv); }
|
||||
return Err("unexpected end-of-map marker at the top level".into());
|
||||
}
|
||||
let key = read_cstr(b, i)?;
|
||||
let val = match tag {
|
||||
T_MAP => BVal::Map(parse_map(b, i, true)?),
|
||||
T_STR => BVal::Str(read_cstr(b, i)?),
|
||||
T_INT32 => {
|
||||
if *i + 4 > b.len() { return Err("truncated int32".into()); }
|
||||
let v = i32::from_le_bytes(b[*i..*i + 4].try_into().unwrap());
|
||||
*i += 4; BVal::Int32(v)
|
||||
}
|
||||
T_WSTRING => BVal::Raw(tag, read_wstr_raw(b, i)?),
|
||||
other => match raw_len(other) {
|
||||
Some(n) => {
|
||||
if *i + n > b.len() { return Err(format!("truncated value for type 0x{other:02x}")); }
|
||||
let v = b[*i..*i + n].to_vec(); *i += n; BVal::Raw(other, v)
|
||||
}
|
||||
None => return Err(format!("unsupported binary VDF type 0x{other:02x}")),
|
||||
},
|
||||
};
|
||||
kv.push((key, val));
|
||||
}
|
||||
}
|
||||
|
||||
fn write_map(out: &mut Vec<u8>, kv: &[(String, BVal)], bounded: bool) {
|
||||
for (k, v) in kv {
|
||||
out.push(tag_of(v));
|
||||
out.extend_from_slice(k.as_bytes());
|
||||
out.push(0);
|
||||
match v {
|
||||
BVal::Map(m) => write_map(out, m, true),
|
||||
BVal::Str(s) => { out.extend_from_slice(s.as_bytes()); out.push(0); }
|
||||
BVal::Int32(n) => out.extend_from_slice(&n.to_le_bytes()),
|
||||
BVal::Raw(_, bytes) => out.extend_from_slice(bytes),
|
||||
}
|
||||
}
|
||||
if bounded { out.push(T_END); }
|
||||
}
|
||||
|
||||
/// Parses a whole `shortcuts.vdf`-style file: one unclosed map at the top level.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Vec<(String, BVal)>, String> {
|
||||
let mut i = 0;
|
||||
parse_map(bytes, &mut i, false)
|
||||
}
|
||||
|
||||
pub fn write(kv: &[(String, BVal)]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
write_map(&mut out, kv, false);
|
||||
out
|
||||
}
|
||||
|
||||
impl fmt::Display for BVal {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
BVal::Str(s) => write!(f, "{s:?}"),
|
||||
BVal::Int32(n) => write!(f, "{n}"),
|
||||
BVal::Map(_) => write!(f, "<map>"),
|
||||
BVal::Raw(t, b) => write!(f, "<raw 0x{t:02x}, {} bytes>", b.len()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_simple_map() {
|
||||
let kv = vec![("shortcuts".to_string(), BVal::Map(vec![
|
||||
("0".to_string(), BVal::Map(vec![
|
||||
("appid".to_string(), BVal::Int32(-123)),
|
||||
("AppName".to_string(), BVal::Str("Capture Card".to_string())),
|
||||
])),
|
||||
]))];
|
||||
let bytes = write(&kv);
|
||||
let back = parse(&bytes).unwrap();
|
||||
assert_eq!(back, kv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_preserves_unknown_raw_types() {
|
||||
let kv = vec![("root".to_string(), BVal::Map(vec![
|
||||
("f".to_string(), BVal::Raw(T_FLOAT32, vec![1, 2, 3, 4])),
|
||||
("u".to_string(), BVal::Raw(T_UINT64, vec![0, 1, 2, 3, 4, 5, 6, 7])),
|
||||
]))];
|
||||
let bytes = write(&kv);
|
||||
assert_eq!(parse(&bytes).unwrap(), kv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_real_looking_shortcuts_file() {
|
||||
// Hand-built to match the layout Steam writes: one "shortcuts" map, entries keyed "0", "1", ...
|
||||
let mut bytes = Vec::new();
|
||||
bytes.push(T_MAP); bytes.extend_from_slice(b"shortcuts\0");
|
||||
bytes.push(T_MAP); bytes.extend_from_slice(b"0\0");
|
||||
bytes.push(T_INT32); bytes.extend_from_slice(b"appid\0"); bytes.extend_from_slice(&42i32.to_le_bytes());
|
||||
bytes.push(T_STR); bytes.extend_from_slice(b"AppName\0"); bytes.extend_from_slice(b"My PS5\0");
|
||||
bytes.push(T_END); // close entry "0"
|
||||
bytes.push(T_END); // close "shortcuts"
|
||||
let v = parse(&bytes).unwrap();
|
||||
assert_eq!(v.len(), 1);
|
||||
let shortcuts = &v[0].1;
|
||||
assert_eq!(shortcuts.get("0").unwrap().get("AppName").unwrap().str(), Some("My PS5"));
|
||||
assert_eq!(shortcuts.get("0").unwrap().get("appid").unwrap().int32(), Some(42));
|
||||
// and it comes back out byte-identical
|
||||
assert_eq!(write(&v), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_file_is_an_error() {
|
||||
assert!(parse(&[T_MAP]).is_err());
|
||||
assert!(parse(&[T_INT32]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_insensitive_get() {
|
||||
let m = BVal::Map(vec![("AppName".to_string(), BVal::Str("x".to_string()))]);
|
||||
assert_eq!(m.get("appname").unwrap().str(), Some("x"));
|
||||
}
|
||||
}
|
||||
@@ -285,6 +285,7 @@ impl App {
|
||||
ui_scale: prefs::UI_SCALES[pick(p.get_scale(), prefs::UI_SCALES.len())],
|
||||
replay_seconds: prefs::CLIP_LENGTHS[pick(p.get_replay(), 6)],
|
||||
clip_seconds: prefs::CLIP_LENGTHS[pick(p.get_clip(), 6)],
|
||||
shortcuts: prefs::load().shortcuts,
|
||||
}.sanitized()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# steam-shortcuts
|
||||
|
||||
## What changed
|
||||
|
||||
- `crates/summit-core/src/vdf_bin.rs`: a reader/writer for Steam's binary KeyValues format
|
||||
(used by `shortcuts.vdf`). Unknown field types (float32, pointer, color, (u)int64, wide
|
||||
string) are kept as raw bytes so an unrecognized field round-trips byte-for-byte.
|
||||
- `crates/summit-core/src/shortcuts.rs`:
|
||||
- `legacy_app_id`/`grid_file_id`: Steam's non-Steam-shortcut appid (CRC-32 of `exe+AppName`,
|
||||
top bit set); grid artwork files are named with that unsigned 32-bit id (`<id>p.png` etc.).
|
||||
The older 64-bit Big Picture id (`grid_app_id`) is kept but not used for file names.
|
||||
- `add_shortcut`/`remove_shortcut`/`find_by_name`/`list_names`: edit the shortcuts list by
|
||||
`AppName`, preserving unknown fields on existing entries and renumbering the `"0"`, `"1"`, ...
|
||||
keys after any change.
|
||||
- `load`/`save`: `save` backs up the existing file to `shortcuts.vdf.bak` before writing, and
|
||||
refuses to write while a `steam` process is running unless `force` is set (checked via
|
||||
`/proc/*/comm`, injectable for tests).
|
||||
- `install_art`: installs grid artwork (`<id>p`, `<id>`, `<id>_hero`, `<id>_logo`, `<id>_icon`)
|
||||
trying, per kind: the entry's own custom art (`State::artwork`/`hero_art`/`logo_art`), then
|
||||
Steam's library cache (for entries with a Steam app id), then SteamGridDB. A missing source
|
||||
or missing SteamGridDB key produces a skip message, never an error.
|
||||
- `crates/summit-core/src/sgdb.rs`: minimal SteamGridDB v2 client (`search/autocomplete`,
|
||||
`grids`/`heroes`/`logos`/`icons` by game id) and the key lookup (`SGDB_API_KEY` env var, else
|
||||
`~/.config/summit/steamgriddb.key`).
|
||||
- `crates/summit-core/src/steam.rs`: added `wide()` (header.jpg, distinct from the portrait
|
||||
cover) and `userdata_dirs()` (every `userdata/<id>` across detected Steam installs).
|
||||
- `crates/summit-core/src/ui.rs`: added `UiSettings.shortcuts: Vec<ShortcutDef>` (`id`, `name`,
|
||||
`target`), defaulting to the two built-ins — `ps5` → "My PS5" (`summit enhance ps5`) and
|
||||
`capture` → "Capture Card" (`summit enhance capture:0`). Editable in `~/.config/summit/ui.toml`
|
||||
as `[[shortcuts]]`.
|
||||
- `crates/summit-cli/src/main.rs`: `summit steam-add <id>` / `summit steam-remove <id>`. Looks
|
||||
up `<id>` in the configured shortcut list, resolves the Steam userdata folder (auto-detected
|
||||
if there's exactly one, otherwise `--user <id>` is required), writes/removes the shortcut, and
|
||||
(on add) installs grid artwork, printing a per-kind outcome line. `--force` bypasses the
|
||||
Steam-running check. The shortcut's `Exe`/`LaunchOptions` always run `summit run <id> -- <summit
|
||||
binary> enhance <target>`, so Steam always launches through `summit run`.
|
||||
- `crates/summit-gui/src/main.rs`: one-line fix so `settings_from_ui()` (which builds a fresh
|
||||
`UiSettings` from the settings page) carries the current `shortcuts` list through instead of
|
||||
losing it on every settings save. No GUI feature work: grepped for an existing "Add to Steam"
|
||||
button first and there isn't one, so per the task I left the GUI itself alone.
|
||||
|
||||
## What I verified
|
||||
|
||||
- `cargo test --workspace`: 78 tests pass (64 in `summit-core`, 14 in `summit-gui`, 0 in
|
||||
`summit-cli`), including new round-trip tests for the binary VDF reader/writer (plain map,
|
||||
unknown raw types, a hand-built realistic `shortcuts.vdf`), the appid/grid-id math (checked
|
||||
against the standard CRC-32/ISO-HDLC test vector), add/remove/re-add semantics, unknown-field
|
||||
preservation across an edit, the full load→add→save→reload round trip through a real temp
|
||||
file, the backup-on-second-write behavior, and the refuse-while-Steam-runs/`--force` override
|
||||
(using a fake `/proc`-shaped directory, not a real process).
|
||||
- `cargo build --workspace` and a manual smoke test of the built `summit` binary: `summit
|
||||
--help` lists `steam-add`/`steam-remove`; `summit steam-add nope` reports the unknown-id error
|
||||
cleanly; `summit steam-add ps5` on this machine (no Steam installed) reports "no Steam userdata
|
||||
found" rather than crashing or writing anywhere. No real Steam installation was touched, per
|
||||
instructions — none exists on this machine, by design of the tests (fixtures only).
|
||||
- Second pass: end-to-end CLI run against a throwaway `$HOME` with a fake `Steam/userdata/123/config` (no real Steam): `steam-add ps5`, `steam-add capture`, `steam-remove ps5` produced/edited `shortcuts.vdf` (+ `.bak`), `strings` showed the expected `AppName`/`LaunchOptions` (`run steam-shortcut:ps5 -- <summit> enhance ps5`), and the no-key art step printed one skip line per art kind without failing. Fixed grid file naming to use the unsigned 32-bit appid (`<appid>p.png`), which the current Steam client uses, instead of the old 64-bit Big Picture id; this naming is from my knowledge of the client, not checked against a real Steam.
|
||||
- Did **not** verify: an actual SteamGridDB lookup (no key configured here, and I didn't want to
|
||||
spend the user's quota on a live network call that isn't required for correctness — JSON
|
||||
parsing and URL building are unit tested against fixture strings instead), or opening a real
|
||||
`userdata/<id>/config/shortcuts.vdf` in an actual Steam client to confirm Steam itself reads
|
||||
the written file as expected (would need a real Steam install, which this task explicitly says
|
||||
not to touch).
|
||||
|
||||
## Not done / known limitations
|
||||
|
||||
- Icon art (`<id>_icon`) has no Steam-library-cache source wired up — Steam's cache doesn't
|
||||
store icons under a reliably-named file the way it does `header.jpg`/`library_hero.jpg`, so
|
||||
that kind only tries custom art, then SteamGridDB.
|
||||
- No live-Steam verification (can't do this without a real Steam client, which is explicitly out
|
||||
of scope here). The binary format and appid math are implemented to the documented/observed
|
||||
Valve format; if Steam's actual on-disk format has drifted since, that would only surface
|
||||
against a real client.
|
||||
- GUI "Add to Steam" button: not added, since no such button existed to wire up (task said leave
|
||||
the GUI alone in that case).
|
||||
Reference in new issue
Block a user