diff --git a/crates/summit-cli/src/main.rs b/crates/summit-cli/src/main.rs index 2a6532f..c2f1616 100644 --- a/crates/summit-cli/src/main.rs +++ b/crates/summit-cli/src/main.rs @@ -55,6 +55,8 @@ enum Cmd { /// Check this machine: session, monitors, and whether the engine, torch with CUDA, the model, ffmpeg, xrandr /// and a file dialog are there (with an id: the display commands that game's profile would run) Doctor { id: Option }, + /// The windows open now, and the rule Enhance would save for each (`summit profile set --window `) + Windows, /// Look up names for Steam games you own but have not installed (cached) Names { #[arg(long, default_value_t = 60)] limit: usize }, /// Run the frame-gen/upscale engine on a source, using a profile's settings @@ -156,6 +158,9 @@ enum ProfileCmd { #[arg(long = "env", value_name = "KEY=VALUE")] env: Vec, /// Remove one of this profile's environment variables #[arg(long = "unset-env", value_name = "KEY")] unset_env: Vec, + /// Which window Enhance takes: class:NAME, part of its title, dir:FOLDER ("|" between alternatives; see + /// `summit windows`). "" goes back to automatic + #[arg(long, allow_hyphen_values = true)] window: Option, }, /// Forget settings, so the defaults decide again: the ones named (e.g. `upscaler window_mode`), or all of them Reset { id: String, keys: Vec }, @@ -259,6 +264,12 @@ fn main() -> Result<()> { let text = state::path_text(&image.canonicalize()?)?; state::update(|st| { st.artwork.insert(id.clone(), text); })?; println!("artwork set for {id}"); } + Cmd::Windows => { + let (s, d) = (display::detect_session(), display::detect_desktop()); + let ws = summit_core::winmode::list_windows(s, d).map_err(|e| anyhow::anyhow!("can't list windows here: {e}"))?; + for w in &ws { println!("{:<8} {:<40} {}", w.pid, summit_core::winmode::rule_for(w), w.title); } + if ws.is_empty() { println!("no windows found"); } + } Cmd::Doctor { id } => { let (s, d) = (display::detect_session(), display::detect_desktop()); println!("session: {s:?}\ndesktop: {d:?}"); @@ -392,11 +403,21 @@ fn main() -> Result<()> { let py = engine::python(&eng); out!("{} {}", py.display(), args.join(" ")); let grace = std::time::Duration::from_secs(8); - let mut eng_proc = match std::process::Command::new(&py).args(&args).envs(engine::engine_env(&p)).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title).spawn() { + let mut eng_cmd = std::process::Command::new(&py); + eng_cmd.args(&args).envs(engine::engine_env(&p)).env("SMOOVPLAY_TITLE", "Summit").env("SUMMIT_GAME", &title); + // The launcher writes the window the player picks here while the engine waits (a rule from an + // earlier run must not count, so it starts empty). + let pick_file = engine::window_file(&id); + if let Some(f) = &pick_file { + if f.parent().is_some_and(|d| std::fs::create_dir_all(d).is_ok()) && std::fs::write(f, "").is_ok() { eng_cmd.env("SUMMIT_WINDOW_FILE", f); } + } + let mut eng_proc = match eng_cmd.spawn() { Ok(c) => c, Err(e) => { let _ = engine::stop(&mut game, grace); anyhow::bail!("could not start the engine ({}): {e}", py.display()); } }; - let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace, detached, &|| signals::requested().is_some())?; + let supervised = engine::supervise(&mut game, &mut eng_proc, grace, detached, &|| signals::requested().is_some()); + if let Some(f) = &pick_file { let _ = std::fs::remove_file(f); } + let (who, status) = supervised?; match who { engine::Ended::Stopped => out!("{}: stopped the engine and the game", signals::requested().map_or("asked to stop", signals::name)), engine::Ended::Game if detached => out!("the game's window closed; the engine ended ({})", eng_proc.wait()?), @@ -441,7 +462,7 @@ fn main() -> Result<()> { } } } - 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 } } => { + 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 } } => { use profile as pr; let window_mode = match (window_mode, fullscreen) { (Some(m), _) => Some(pick("window-mode", m, pr::WINDOW_MODES, true)?), @@ -469,6 +490,7 @@ fn main() -> Result<()> { if height.is_some() { l.height = height; } if refresh.is_some() { l.refresh_hz = refresh; } if window_mode.is_some() { l.window_mode = window_mode; } + if let Some(w) = window { l.window = Some(w.trim().to_string()).filter(|w| !w.is_empty()); } if focus.is_some() { l.focus = focus; } if enhance.is_some() { l.enhance = enhance; } if upscaler.is_some() { l.upscaler = upscaler; } @@ -563,10 +585,16 @@ fn steam_account_for(id: &str, st: &state::State) -> Result<()> { Ok(()) } -/// Which windows are the game's: `--window class:NAME` (or a Steam game's `steam_app_`), else the process. +/// Which windows are the game's, from `--window` (alternatives split by "|", launch::window_query): a Steam game's +/// `class:steam_app_`, else `dir:` (the processes running from the game's folder), else the first +/// `class:NAME`; with no `--window`, a Steam game's class or the process Summit started. fn place_target(id: &str, window: Option<&str>, pid: u32) -> summit_core::winmode::Target { use summit_core::winmode::Target; - if let Some(c) = window.and_then(|w| w.strip_prefix("class:")) { return Target::Class(c.to_string()); } + let alts: Vec<&str> = window.map(|w| w.split('|').map(str::trim).collect()).unwrap_or_default(); + let find = |pre: &str| alts.iter().find_map(|a| a.strip_prefix(pre).filter(|v| !v.is_empty())); + if let Some(c) = find("class:steam_app_") { return Target::Class(format!("steam_app_{c}")); } + if let Some(d) = find("dir:") { return Target::Dir(d.to_string()); } + if let Some(c) = find("class:") { return Target::Class(c.to_string()); } match id.strip_prefix("steam:").and_then(|n| n.parse::().ok()) { Some(n) => Target::Class(format!("steam_app_{n}")), None => Target::Pid(pid), diff --git a/crates/summit-core/src/engine.rs b/crates/summit-core/src/engine.rs index 30f1358..589e3de 100644 --- a/crates/summit-core/src/engine.rs +++ b/crates/summit-core/src/engine.rs @@ -233,6 +233,33 @@ pub fn descendants_in(proc_dir: &Path, pid: u32) -> Vec { family } +/// Whether `path` is `folder` or inside it, compared as the engine does (framegen/window_x11.py `under`): "/" +/// separators, case ignored, and Wine's `Z:\\games\\x.exe` read as `/games/x.exe`. +pub fn under(path: &str, folder: &str) -> bool { + fn norm(p: &str) -> String { + let p = p.trim().trim_matches('"').replace('\\', "/"); + let p = if p.len() > 2 && p.as_bytes()[1] == b':' && p[..1].eq_ignore_ascii_case("z") { p[2..].to_string() } else { p }; + p.trim_end_matches('/').to_lowercase() + } + let (p, f) = (norm(path), norm(folder)); + !f.is_empty() && (p == f || p.starts_with(&format!("{f}/"))) +} + +/// The processes that belong to the game in `folder`: running from it (working directory or program) or started +/// with a file in it on the command line (a Wine game's .exe). How a game Steam, Lutris or Heroic started is found. +pub fn procs_in_dir(proc_dir: &Path, folder: &str) -> Vec { + let mut out = vec![]; + for e in std::fs::read_dir(proc_dir).into_iter().flatten().flatten() { + let Some(n) = e.file_name().to_str().and_then(|n| n.parse::().ok()) else { continue }; + let link = |l: &str| std::fs::read_link(e.path().join(l)).ok().is_some_and(|t| under(&t.to_string_lossy(), folder)); + let cmd = || std::fs::read(e.path().join("cmdline")).ok().is_some_and(|c| { + c.split(|b| *b == 0).any(|a| !a.is_empty() && under(&String::from_utf8_lossy(a), folder)) + }); + if link("cwd") || link("exe") || cmd() { out.push(n); } + } + out +} + /// Still running (not gone, not a zombie waiting for its parent). fn alive(proc_dir: &Path, pid: u32) -> bool { match std::fs::read(proc_dir.join(pid.to_string()).join("stat")) { @@ -277,6 +304,15 @@ pub fn stop(child: &mut std::process::Child, grace: std::time::Duration) -> std: child.wait().map(|_| ()) } +/// The file through which the launcher hands a waiting engine the window the player picked for game `id` +/// (SUMMIT_WINDOW_FILE, framegen/window_x11.py LiveQuery): in the runtime folder, one per game, so the launcher can +/// find it from the game's id alone. None without a runtime folder (then picking still saves the game's rule). +pub fn window_file(id: &str) -> Option { + let dir = dirs::runtime_dir()?.join("summit"); + let safe: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); + Some(dir.join(format!("window-{safe}"))) +} + /// Where the engine saves clips: $SMOOVPLAY_REPLAY_DIR if set, else Summit in the Videos folder (XDG_VIDEOS_DIR), /// with a folder per game inside (see engine/framegen/replay.py videos_folder()). pub fn clips_dir() -> Option { @@ -487,4 +523,33 @@ mod tests { let pr = Profile { framegen: "none".into(), ..Default::default() }; assert!(plan(Path::new("/e"), &Source::Ps5, &pr, true, None, None).contains(&"--off".to_string())); } + #[test] + fn under_reads_wine_paths_and_keeps_folder_boundaries() { + assert!(under("/games/VR/bin/vr", "/games/VR")); + assert!(under("Z:\\games\\VR\\VR.exe", "/games/vr/")); + assert!(under("/games/VR", "/games/VR")); + assert!(!under("/games/VR2/vr", "/games/VR")); + assert!(!under("C:\\windows\\explorer.exe", "/games/VR")); + assert!(!under("/games/VR", "")); + } + #[test] + fn procs_in_dir_reads_cwd_exe_and_cmdline() { + let root = std::env::temp_dir().join(format!("summit-procs-in-dir-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let proc = |pid: u32, cwd: &str, exe: &str, cmd: &[&str]| { + let d = root.join(pid.to_string()); + std::fs::create_dir_all(&d).unwrap(); + std::os::unix::fs::symlink(cwd, d.join("cwd")).unwrap(); + std::os::unix::fs::symlink(exe, d.join("exe")).unwrap(); + std::fs::write(d.join("cmdline"), cmd.join("\0") + "\0").unwrap(); + }; + proc(1, "/games/VR", "/usr/bin/vr", &["vr"]); + proc(2, "/home/me", "/games/VR/vr", &["vr"]); + proc(3, "/home/me", "/proton/wine64", &["Z:\\games\\VR\\VR.exe"]); + proc(4, "/home/me", "/usr/bin/steam", &["steam", "steam://rungameid/1"]); + let mut got = procs_in_dir(&root, "/games/VR"); + got.sort(); + assert_eq!(got, vec![1, 2, 3]); + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/crates/summit-core/src/launch.rs b/crates/summit-core/src/launch.rs index d3d4c33..fac9adb 100644 --- a/crates/summit-core/src/launch.rs +++ b/crates/summit-core/src/launch.rs @@ -29,8 +29,13 @@ pub enum Plan { /// looks the console up and starts chiaki-ng (finding and waking the console) or the engine on the card, with /// the engine first and chiaki-ng's frame tap on when Enhance is on (console.rs). /// * Folders found on disk: not wired (add them with `summit add`). -pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { +pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { plan_with(e, summit_cli, enhance, None) } + +/// [`plan`], with the game's own window rule (its profile's `window`, picked in the launcher or typed in the profile +/// editor), which then wins over the one Summit works out. +pub fn plan_with(e: &Entry, summit_cli: Option<&Path>, enhance: bool, window: Option<&str>) -> Plan { let cli = summit_cli.map(|c| c.to_string_lossy().into_owned()); + let rule = enhance_rule(e, window); let via_run = |cli: &str, extra: &[String], cmd: Vec| { let mut v = vec![cli.to_string(), "run".into(), e.id.clone()]; v.extend(extra.iter().cloned()); @@ -46,7 +51,7 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { match cli { Some(cli) => { let mut extra = vec!["--detached".to_string()]; - if enhance { extra.extend(["--enhance".into(), "--window".into(), format!("class:steam_app_{id}"), "--wait".into(), "120".into()]); } + if enhance { extra.extend(enhance_args(rule.clone())); } Plan::Run(via_run(&cli, &extra, steam)) } None if enhance => Plan::Unsupported("Enhance needs the summit command line tool next to summit-gui".into()), @@ -57,9 +62,8 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { // A non-Steam game in the Steam library: Steam starts it (its Proton choice, its launch options). None => match e.launch_uri.as_deref() { Some(uri) => { - if enhance { return Plan::Unsupported("Enhance is not wired for non-Steam games in Steam yet".into()); } let steam = vec!["steam".to_string(), uri.to_string()]; - match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], steam)), None => Plan::Run(steam) } + detached(cli, steam, &via_run, enhance.then_some(rule)) } None => Plan::Unsupported("this Steam entry has no app id".into()), }, @@ -69,7 +73,9 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { if !Path::new(path).is_file() { return Plan::Unsupported(format!("{path} is not a file Summit can run")); } match cli { Some(cli) => { - let extra: Vec = if enhance { vec!["--enhance".into()] } else { vec![] }; + let mut extra: Vec = if enhance { vec!["--enhance".into()] } else { vec![] }; + // Summit holds this game's process, so the engine takes that one's window unless a rule says otherwise + if let (true, Some(w)) = (enhance, window.map(str::trim).filter(|w| !w.is_empty())) { extra.extend(["--window".into(), w.to_string()]); } Plan::Run(via_run(&cli, &extra, vec![path.into()])) } None => Plan::Unsupported("the summit command line tool was not found next to summit-gui".into()), @@ -78,16 +84,14 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { Source::Lutris => match e.launch_uri.clone().or_else(|| e.id.strip_prefix("lutris:").filter(|s| !s.is_empty()).map(|s| format!("lutris:rungame/{s}"))) { Some(uri) => { let lutris = vec!["lutris".to_string(), uri]; - if enhance { return Plan::Unsupported("Enhance is not wired for Lutris games yet".into()); } - match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], lutris)), None => Plan::Run(lutris) } + detached(cli, lutris, &via_run, enhance.then_some(rule)) } _ => Plan::Unsupported("no Lutris slug for this entry".into()), }, Source::Heroic => match e.launch_uri.as_deref() { Some(uri) => { - if enhance { return Plan::Unsupported("Enhance is not wired for Heroic games yet".into()); } let open = vec!["xdg-open".to_string(), uri.to_string()]; - match cli { Some(cli) => Plan::Run(via_run(&cli, &["--detached".to_string()], open)), None => Plan::Run(open) } + detached(cli, open, &via_run, enhance.then_some(rule)) } None => Plan::Unsupported("no Heroic app name for this entry".into()), }, @@ -104,6 +108,69 @@ pub fn plan(e: &Entry, summit_cli: Option<&Path>, enhance: bool) -> Plan { } } +/// A game handed to another launcher (Steam for a non-Steam game, Lutris, Heroic): `summit run --detached +/// [--enhance --window ] -- `. With Enhance the engine finds the game's window by [`window_query`]. +fn detached(cli: Option, cmd: Vec, via_run: &dyn Fn(&str, &[String], Vec) -> Vec, enhance: Option) -> Plan { + let mut extra = vec!["--detached".to_string()]; + if let Some(rule) = enhance { + let Some(cli) = cli else { return Plan::Unsupported("Enhance needs the summit command line tool next to summit-gui".into()) }; + extra.extend(enhance_args(rule)); + return Plan::Run(via_run(&cli, &extra, cmd)); + } + match cli { Some(cli) => Plan::Run(via_run(&cli, &extra, cmd)), None => Plan::Run(cmd) } +} + +/// The engine waits this long for the game's window: time for a slow start, and for the player to pick the window +/// in the launcher when Summit's own rule finds nothing. +pub const WINDOW_WAIT_S: u32 = 300; + +fn enhance_args(window: String) -> [String; 5] { + ["--enhance".into(), "--window".into(), window, "--wait".into(), WINDOW_WAIT_S.to_string()] +} + +/// The window rule Enhance starts with: the game's own (`window`), else Summit's guess ([`window_query`]), else +/// [`ASK`]: the engine waits for the player to pick the window in the launcher. +pub fn enhance_rule(e: &Entry, window: Option<&str>) -> String { + window.map(str::trim).filter(|w| !w.is_empty()).map(String::from).or_else(|| window_query(e)).unwrap_or_else(|| ASK.into()) +} + +/// The engine's `--window` for "no rule yet: wait for one picked in the launcher" (framegen/window_x11.py LiveQuery). +pub const ASK: &str = "ask:"; + +/// Which window is the game's, for a game another program starts (so Summit never sees its process), in the +/// engine's `--window` form, alternatives split by "|": +/// * Steam: `class:steam_app_` (Proton games), then `dir:` (native games); +/// * an executable (a non-Steam game in Steam, Lutris): `class:` (Wine names the window after its .exe), +/// then `dir:`; +/// * a folder (Heroic): `dir:`. +/// +/// `dir:` takes a window whose process runs from that folder or was started with a file in it: Steam, Lutris and +/// Heroic all start a game from its own folder. None when the entry has no usable path (a command such as +/// `flatpak run ...`, or a folder too broad to tell the game by, like the home folder). +pub fn window_query(e: &Entry) -> Option { + let mut alts: Vec = vec![]; + if let Some(id) = e.steam_app_id { alts.push(format!("class:steam_app_{id}")); } + if let Some(path) = e.path.as_deref().map(str::trim).filter(|p| p.starts_with('/') && !p.contains('|')) { + let p = Path::new(path); + // Steam (with an app id) and Heroic store the install folder; a non-Steam game in Steam and Lutris the program + let is_folder = e.steam_app_id.is_some() || e.source == Source::Heroic || p.is_dir(); + let folder = if is_folder { Some(p) } else { + if let Some(f) = p.file_name().map(|f| f.to_string_lossy().to_lowercase()) { alts.push(format!("class:{f}")); } + p.parent() + }; + if let Some(folder) = folder.filter(|f| specific(f)) { alts.push(format!("dir:{}", folder.display())); } + } + (alts.iter().any(|a| a.starts_with("dir:") || a.starts_with("class:steam_app_"))).then(|| alts.join("|")) +} + +/// A folder narrow enough that "runs from here" means this game: not /, /usr/bin, the home folder or above it. +fn specific(folder: &Path) -> bool { + let depth = folder.components().count(); // "/" counts as one + let home = std::env::var_os("HOME").map(std::path::PathBuf::from); + let wide = ["/usr", "/usr/bin", "/usr/local", "/usr/local/bin", "/bin", "/opt", "/tmp", "/mnt", "/media", "/run/media"]; + depth >= 3 && !wide.iter().any(|w| folder == Path::new(w)) && !home.is_some_and(|h| h.starts_with(folder)) +} + /// The same start, with the game's window given the keyboard once it opens (`summit run --focus`): Play in the /// launcher, which steps aside for the game. A start that does not go through `summit run` is left as it is. pub fn with_focus(mut argv: Vec) -> Vec { @@ -142,7 +209,7 @@ mod tests { fn steam_installed_goes_through_summit_run() { let e = entry("steam:620", Source::Steam, true, Some(620), None); assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam:620 --detached --title=steam:620 -- steam steam://rungameid/620"); - assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam:620 --detached --enhance --window class:steam_app_620 --wait 120 --title=steam:620 -- steam steam://rungameid/620"); + assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam:620 --detached --enhance --window class:steam_app_620 --wait 300 --title=steam:620 -- steam steam://rungameid/620"); assert_eq!(plan(&e, None, false), Plan::Run(vec!["steam".into(), "steam://rungameid/620".into()])); assert!(matches!(plan(&e, None, true), Plan::Unsupported(_))); assert!(!is_install(&e)); @@ -152,7 +219,8 @@ mod tests { let mut e = entry("steam-shortcut:3604730456", Source::Steam, true, None, None); e.launch_uri = Some("steam://rungameid/15482199419448721408".into()); assert_eq!(argv(plan(&e, cli(), false)), "/usr/bin/summit run steam-shortcut:3604730456 --detached --title=steam-shortcut:3604730456 -- steam steam://rungameid/15482199419448721408"); - assert!(matches!(plan(&e, cli(), true), Plan::Unsupported(_))); + // nothing to tell its window by: the engine waits for the player to pick it in the launcher + assert!(argv(plan(&e, cli(), true)).contains("--enhance --window ask: --wait 300")); assert!(!is_install(&e)); } #[test] @@ -191,7 +259,7 @@ mod tests { let l = entry("lutris:celeste", Source::Lutris, true, None, None); assert_eq!(argv(plan(&l, cli(), false)), "/usr/bin/summit run lutris:celeste --detached --title=lutris:celeste -- lutris lutris:rungame/celeste"); assert_eq!(plan(&l, None, false), Plan::Run(vec!["lutris".into(), "lutris:rungame/celeste".into()])); - assert!(matches!(plan(&l, cli(), true), Plan::Unsupported(_))); + assert!(argv(plan(&l, cli(), true)).contains("--window ask:")); let mut l2 = entry("lutris:celeste@5", Source::Lutris, true, None, None); l2.launch_uri = Some("lutris:rungameid/5".into()); assert_eq!(plan(&l2, None, false), Plan::Run(vec!["lutris".into(), "lutris:rungameid/5".into()])); @@ -200,7 +268,57 @@ mod tests { h.launch_uri = Some("heroic://launch?appName=Quail&runner=legendary".into()); assert_eq!(argv(plan(&h, cli(), false)), "/usr/bin/summit run heroic:epic:quail --detached --title=heroic:epic:quail -- xdg-open heroic://launch?appName=Quail&runner=legendary"); assert_eq!(plan(&h, None, false), Plan::Run(vec!["xdg-open".into(), "heroic://launch?appName=Quail&runner=legendary".into()])); - assert!(matches!(plan(&h, cli(), true), Plan::Unsupported(_))); + assert!(argv(plan(&h, cli(), true)).contains("--window ask:")); + assert!(matches!(plan(&h, None, true), Plan::Unsupported(_))); assert!(matches!(plan(&entry("scan:/g", Source::Heuristic, true, None, Some("/g")), cli(), false), Plan::Unsupported(_))); } + #[test] + fn games_other_launchers_start_can_be_enhanced_by_their_folder() { + // a non-Steam game in Steam: Wine names the window after the .exe, or a program running from its folder + let mut e = entry("steam-shortcut:1", Source::Steam, true, None, Some("/games/ULTRAKILL/ULTRAKILL.exe")); + e.launch_uri = Some("steam://rungameid/99".into()); + assert_eq!(window_query(&e).as_deref(), Some("class:ultrakill.exe|dir:/games/ULTRAKILL")); + assert_eq!(argv(plan(&e, cli(), true)), "/usr/bin/summit run steam-shortcut:1 --detached --enhance --window class:ultrakill.exe|dir:/games/ULTRAKILL --wait 300 --title=steam-shortcut:1 -- steam steam://rungameid/99"); + assert!(matches!(plan(&e, None, true), Plan::Unsupported(_))); + // a Steam game: Proton's class first, its install folder for native games + let s = entry("steam:620", Source::Steam, true, Some(620), Some("/games/steamapps/common/Portal 2")); + assert_eq!(window_query(&s).as_deref(), Some("class:steam_app_620|dir:/games/steamapps/common/Portal 2")); + // Lutris (an exe) and Heroic (a folder) + let mut l = entry("lutris:celeste", Source::Lutris, true, None, Some("/games/celeste/Celeste")); + l.launch_uri = Some("lutris:rungameid/5".into()); + assert!(argv(plan(&l, cli(), true)).contains("--enhance --window class:celeste|dir:/games/celeste --wait 300")); + let dir = std::env::temp_dir().join("summit-launch-test-heroic"); + std::fs::create_dir_all(&dir).unwrap(); + let mut h = entry("heroic:epic:quail", Source::Heroic, true, None, Some(&dir.to_string_lossy())); + h.launch_uri = Some("heroic://launch?appName=Quail&runner=legendary".into()); + assert_eq!(window_query(&h), Some(format!("dir:{}", dir.display()))); + assert!(matches!(plan(&h, cli(), true), Plan::Run(_))); + let _ = std::fs::remove_dir(&dir); + } + #[test] + fn a_folder_too_broad_or_a_command_gives_no_window_rule() { + let mk = |p: &str| entry("steam-shortcut:2", Source::Steam, true, None, Some(p)); + assert_eq!(window_query(&mk("flatpak run org.x.Game")), None); // a command, not a path + assert_eq!(window_query(&mk("/usr/bin/game")), None); // /usr/bin runs everything + assert_eq!(window_query(&mk("/game")), None); // the root + if let Some(home) = std::env::var_os("HOME") { + let exe = std::path::Path::new(&home).join("game.sh"); + assert_eq!(window_query(&mk(&exe.to_string_lossy())), None); // the home folder + } + let mut e = mk("/usr/bin/game"); + e.launch_uri = Some("steam://rungameid/99".into()); + assert!(argv(plan(&e, cli(), true)).contains("--window ask:")); + } + #[test] + fn the_games_own_window_rule_wins() { + let mut e = entry("steam-shortcut:1", Source::Steam, true, None, Some("/games/VR/run.sh")); + e.launch_uri = Some("steam://rungameid/99".into()); + assert!(argv(plan_with(&e, cli(), true, Some(" class:voidrunner "))).contains("--window class:voidrunner --wait 300")); + assert!(argv(plan_with(&e, cli(), true, Some(""))).contains("--window class:run.sh|dir:/games/VR")); // empty: automatic + assert!(!argv(plan_with(&e, cli(), false, Some("class:voidrunner"))).contains("--window")); // no Enhance + // a game Summit starts itself: its process is known, a rule only when one is saved + let c = entry("custom:x", Source::Custom, true, None, Some("/bin/sh")); + assert_eq!(argv(plan_with(&c, cli(), true, Some("title words"))), "/usr/bin/summit run custom:x --enhance --window title words --title=custom:x -- /bin/sh"); + assert_eq!(argv(plan_with(&c, cli(), true, None)), "/usr/bin/summit run custom:x --enhance --title=custom:x -- /bin/sh"); + } } diff --git a/crates/summit-core/src/profile.rs b/crates/summit-core/src/profile.rs index 553f989..cbe7d65 100644 --- a/crates/summit-core/src/profile.rs +++ b/crates/summit-core/src/profile.rs @@ -76,6 +76,9 @@ pub struct Profile { pub launch_args: Vec, /// Set for the game's process (e.g. MANGOHUD=1, PROTON_ENABLE_NVAPI=1). The game's own keys win over the defaults'. pub env: BTreeMap, + /// Which window Enhance takes, in the engine's `--window` form (`class:NAME`, part of the title, `dir:FOLDER`, + /// alternatives split by "|"). None: Summit works it out (launch::window_query), and asks when it can't. + pub window: Option, } impl Profile { @@ -112,6 +115,7 @@ pub struct Layer { #[serde(skip_serializing_if = "Option::is_none")] pub watermark: Option, #[serde(skip_serializing_if = "Option::is_none")] pub launch_args: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub env: Option>, + #[serde(skip_serializing_if = "Option::is_none")] pub window: Option, /// Files from before layers: `fullscreen = true` is `window_mode = "borderless"` (the engine's picture over the /// whole monitor, which is what it did). Read, never written. #[serde(skip_serializing)] pub fullscreen: Option, @@ -121,7 +125,7 @@ pub struct Layer { pub const KEYS: &[&str] = &[ "monitor", "width", "height", "refresh_hz", "window_mode", "focus", "enhance", "upscaler", "fsr_sharpness", "vsr_quality", "framegen", "framegen_multiplier", "target_hz", "model", "vfg_quality", "motion", "ai_engine", - "steady_hud", "fill", "vsync", "watermark", "launch_args", "env", + "steady_hud", "fill", "vsync", "watermark", "launch_args", "env", "window", ]; impl Layer { @@ -171,6 +175,7 @@ impl Layer { if let Some(v) = self.watermark { p.watermark = Some(v); } if let Some(v) = &self.launch_args { p.launch_args = v.clone(); } if let Some(v) = &self.env { for (k, val) in v { p.env.insert(k.clone(), val.clone()); } } + if let Some(v) = &self.window { p.window = Some(v.trim().to_string()).filter(|v| !v.is_empty()); } } /// Whether this layer sets `key` (one of [`KEYS`]). @@ -184,7 +189,7 @@ impl Layer { "model" => self.model.is_some(), "vfg_quality" => self.vfg_quality.is_some(), "motion" => self.motion.is_some(), "ai_engine" => self.ai_engine.is_some(), "steady_hud" => self.steady_hud.is_some(), "fill" => self.fill.is_some(), "vsync" => self.vsync.is_some(), "watermark" => self.watermark.is_some(), "launch_args" => self.launch_args.is_some(), - "env" => self.env.is_some(), + "env" => self.env.is_some(), "window" => self.window.is_some(), _ => false, } } @@ -201,7 +206,7 @@ impl Layer { "target_hz" => self.target_hz = None, "model" => self.model = None, "vfg_quality" => self.vfg_quality = None, "motion" => self.motion = None, "ai_engine" => self.ai_engine = None, "steady_hud" => self.steady_hud = None, "fill" => self.fill = None, "vsync" => self.vsync = None, "watermark" => self.watermark = None, - "launch_args" => self.launch_args = None, "env" => self.env = None, + "launch_args" => self.launch_args = None, "env" => self.env = None, "window" => self.window = None, _ => return false, } true diff --git a/crates/summit-core/src/winmode.rs b/crates/summit-core/src/winmode.rs index 1dbffe8..1da6c4c 100644 --- a/crates/summit-core/src/winmode.rs +++ b/crates/summit-core/src/winmode.rs @@ -19,6 +19,8 @@ pub enum Target { Pid(u32), /// A window class, e.g. `steam_app_620` (Steam gives Proton games that one). Class(String), + /// The processes running from the game's folder (a game Steam, Lutris or Heroic started: engine::procs_in_dir). + Dir(String), } /// What to do to the game's window. Built from a profile by [`wanted`]. @@ -58,7 +60,7 @@ fn js(s: &str) -> String { serde_json::to_string(s).unwrap_or_else(|_| "\"\"".in /// of windows already placed (left alone, so a window the player moved is not moved back). It reports what it /// changed to `reply_to` (our D-Bus connection's name) as JSON: `[{"id":..,"pid":..,"cls":..,"caption":..,"output":..}]`. pub fn kwin_script(target: &Target, pids: &[u32], want: &Want, done: &[String], reply_to: &str) -> String { - let (cls, pids) = match target { Target::Class(c) => (c.to_lowercase(), vec![]), Target::Pid(_) => (String::new(), pids.to_vec()) }; + let (cls, pids) = match target { Target::Class(c) => (c.to_lowercase(), vec![]), Target::Pid(_) | Target::Dir(_) => (String::new(), pids.to_vec()) }; let pids = pids.iter().map(|p| p.to_string()).collect::>().join(","); let done = done.iter().map(|d| js(d)).collect::>().join(","); format!(r#"const PIDS = [{pids}], CLS = {cls}, MODE = {mode}, MON = {mon}, FOCUS = {focus}, DONE = [{done}]; @@ -124,7 +126,7 @@ pub fn parse_wmctrl(text: &str) -> Vec { pub fn x_matches(w: &XWin, target: &Target, pids: &[u32]) -> bool { match target { Target::Class(c) => w.class.split('.').any(|p| p.eq_ignore_ascii_case(c)), - Target::Pid(_) => pids.contains(&w.pid), + Target::Pid(_) | Target::Dir(_) => pids.contains(&w.pid), } } @@ -151,6 +153,7 @@ pub fn wmctrl_cmds(xid: &str, want: &Want) -> Vec> { fn family(target: &Target) -> Vec { match target { Target::Pid(p) => { let mut v = vec![*p]; v.extend(crate::engine::descendants_in(std::path::Path::new("/proc"), *p)); v } + Target::Dir(d) => crate::engine::procs_in_dir(std::path::Path::new("/proc"), d), Target::Class(_) => vec![], } } @@ -176,6 +179,46 @@ pub fn place(session: Session, desktop: Desktop, target: &Target, want: &Want, w } } +/// An open window, for the launcher's "pick the game's window" list. +#[derive(Debug, Clone, PartialEq)] +pub struct OpenWindow { pub pid: u32, pub class: String, pub title: String } + +/// The KWin script that reports every normal window (pid, class, caption) without changing any. +pub fn kwin_list_script(reply_to: &str) -> String { + format!(r#"const out = []; +for (const w of workspace.windowList()) {{ + if (!w.normalWindow) continue; + out.push({{id: String(w.internalId), pid: w.pid, cls: String(w.resourceClass), caption: String(w.caption), output: w.output ? String(w.output.name) : ""}}); +}} +callDBus({reply}, "/summit/winmode", "org.summit.WinMode", "placed", JSON.stringify(out)); +"#, reply = js(reply_to)) +} + +/// The windows open now (KWin's on KDE, wmctrl's on other X11 desktops), or why they can't be listed. +pub fn list_windows(session: Session, desktop: Desktop) -> Result, String> { + let have = |t: &str| std::process::Command::new("sh").args(["-c", &format!("command -v {t}")]).stdout(std::process::Stdio::null()).status().is_ok_and(|s| s.success()); + match backend(session, desktop, have)? { + Backend::KWin => kwin::list(), + Backend::Wmctrl => { + let out = std::process::Command::new("wmctrl").arg("-lpx").output().map_err(|e| format!("wmctrl: {e}"))?; + Ok(parse_wmctrl(&String::from_utf8_lossy(&out.stdout)).into_iter() + // wmctrl gives "instance.Class": the engine compares WM_CLASS's class half + .map(|w| OpenWindow { pid: w.pid, class: w.class.rsplit('.').next().unwrap_or_default().to_string(), title: w.title }).collect()) + } + } +} + +/// Classes that many programs share (Wine's own, Java, Electron...), so they don't tell a game's window apart. +const GENERIC_CLASSES: &[&str] = &["", "wine", "explorer.exe", "steam", "java", "python", "python3", "electron", "sdl_app", "xterm", "unknown"]; + +/// The rule that finds this window again next time, in the engine's `--window` form: its class when that names the +/// program (Wine gives a game the class of its .exe, a native game its own), else its title. +pub fn rule_for(w: &OpenWindow) -> String { + let class = w.class.trim().to_lowercase(); + if !GENERIC_CLASSES.contains(&class.as_str()) && !class.contains('|') { return format!("class:{class}"); } + w.title.trim().replace('|', " ") +} + fn watch_loop(watch: Watch, stop: &dyn Fn() -> bool, mut round: impl FnMut() -> Result) -> Result { let start = Instant::now(); let mut first: Option = None; @@ -251,6 +294,15 @@ mod kwin { r } + pub fn list() -> Result, String> { + let (tx, rx) = mpsc::channel(); + let c = Connection::session().map_err(|e| format!("no D-Bus session: {e}"))?; + c.object_server().at("/summit/winmode", Reporter { tx: Mutex::new(tx) }).map_err(|e| format!("D-Bus: {e}"))?; + let me = c.unique_name().map(|n| n.to_string()).ok_or("no D-Bus name")?; + let seen = once(&c, &rx, &kwin_list_script(&me), 0)?; + Ok(seen.into_iter().map(|p| OpenWindow { pid: p.pid, class: p.class, title: p.caption }).collect()) + } + pub fn place(target: &Target, want: &Want, watch: Watch, stop: &dyn Fn() -> bool, log: &mut dyn FnMut(String)) -> Result { let (tx, rx) = mpsc::channel(); let c = Connection::session().map_err(|e| format!("no D-Bus session: {e}"))?; @@ -337,4 +389,13 @@ mod tests { assert_eq!(watch_loop(w, &|| true, || Ok(0)).unwrap(), 0); assert!(watch_loop(w, &|| false, || Err("x".into())).is_err()); } + #[test] + fn a_picked_window_is_found_again_by_its_class_or_title() { + let w = |class: &str, title: &str| OpenWindow { pid: 1, class: class.into(), title: title.into() }; + assert_eq!(rule_for(&w("ULTRAKILL.exe", "ULTRAKILL")), "class:ultrakill.exe"); + assert_eq!(rule_for(&w("voidrunner", "Voidrunner -- arena")), "class:voidrunner"); + assert_eq!(rule_for(&w("wine", "My Game")), "My Game"); // Wine's own class: by title + assert_eq!(rule_for(&w("", " A | B ")), "A B"); // "|" splits rules + assert!(kwin_list_script(":1.5").contains("\":1.5\"")); + } } diff --git a/crates/summit-gui/src/data.rs b/crates/summit-gui/src/data.rs index 9e62046..3bd7df7 100644 --- a/crates/summit-gui/src/data.rs +++ b/crates/summit-gui/src/data.rs @@ -255,6 +255,8 @@ pub struct EditCtx<'a> { pub tool: &'a str, /// How the game's window is placed here (KWin, wmctrl), or why it cannot be. pub placer: Result<&'a str, &'a str>, + /// The window rule Summit works out for this game (launch::window_query), shown while the game has none of its own. + pub auto_window: Option<&'a str>, } fn label_of(choices: &[Choice], v: &Option) -> String { @@ -323,6 +325,7 @@ fn text_of(l: &Layer, key: &str) -> Option { match key { "launch_args" => l.launch_args.as_ref().map(|a| summit_core::profile::join_args(a)), "env" => l.env.as_ref().map(summit_core::profile::join_env), + "window" => l.window.clone(), _ => None, } } @@ -367,8 +370,12 @@ pub fn edit_rows(cx: &EditCtx) -> Vec { ("#", "LAUNCH", String::new()), ("launch_args", "Launch arguments", "Added after the game's command, e.g. -windowed -dx11. Quotes group words. Enter to edit, Enter to save.".into()), ("env", "Environment", "KEY=VALUE pairs, e.g. MANGOHUD=1 PROTON_ENABLE_NVAPI=1. A game's keys win over the defaults'. Enter to edit.".into()), + ("#", "GAME WINDOW", String::new()), + ("window", "Game window", "Enhance's window: class:NAME, part of its title, or dir:FOLDER. Empty: automatic, and Summit asks when that finds nothing".into()), ]; for (key, label, hint) in spec { + // a window belongs to one game: not a default + if cx.defaults && (key == "window" || label == "GAME WINDOW") { continue; } if key == "#" { rows.push(header(label)); continue; } let skip = match key { "fsr_sharpness" => !matches!(up, "" | "fsr"), @@ -380,6 +387,11 @@ pub fn edit_rows(cx: &EditCtx) -> Vec { }; if skip && !cx.own.has(key) { continue; } let own = !cx.defaults && match key { "resolution" => cx.own.width.is_some() || cx.own.height.is_some(), k => cx.own.has(k) }; + if key == "window" { + let placeholder = match cx.auto_window { Some(q) => format!("Automatic: {q}"), None => "Automatic: asks you to pick it".into() }; + rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text: text_of(cx.own, key).unwrap_or_default(), placeholder, own }); + continue; + } if matches!(key, "launch_args" | "env") { let base_text = match key { "launch_args" => summit_core::profile::join_args(&cx.base.launch_args), _ => summit_core::profile::join_env(&cx.base.env) }; let placeholder = if cx.defaults || base_text.is_empty() { "None".to_string() } else { format!("Default: {base_text}") }; @@ -417,11 +429,37 @@ pub fn edit_text(own: &Layer, key: &str, text: &str) -> Result { match key { "launch_args" => l.launch_args = if t.is_empty() { None } else { Some(summit_core::profile::split_args(t)) }, "env" => l.env = if t.is_empty() { None } else { Some(summit_core::profile::parse_env_line(t)?) }, + "window" => l.window = if t.is_empty() { None } else { Some(t.to_string()) }, _ => {} } Ok(l) } +/// Where Enhance has got to in finding the game's window, from `summit run`'s log (the engine's lines). +#[derive(Debug, Clone, PartialEq)] +pub enum WindowWait { + /// Nothing said yet (the engine is starting). + NotYet, + /// Looking. `asking`: it has no rule at all and waits for one picked in the launcher. + Waiting { asking: bool }, + /// Enhancing this window. + Found(String), + /// It gave up: nothing matched in time. + GaveUp, +} + +pub fn window_wait(log: &str) -> WindowWait { + let mut w = WindowWait::NotYet; + for l in log.lines() { + if let Some(rest) = l.split("[run] source: ").nth(1) { w = WindowWait::Found(rest.trim().trim_end_matches(" window").trim().to_string()); } + else if l.contains("[window] waiting for the game's window to be picked") { w = WindowWait::Waiting { asking: true }; } + else if l.contains("[window] waiting for") { w = WindowWait::Waiting { asking: false }; } + else if l.contains("[window] now looking for") { w = WindowWait::Waiting { asking: false }; } + else if l.contains("no window matches") && !matches!(w, WindowWait::Found(_)) { w = WindowWait::GaveUp; } + } + w +} + /// The error `summit run` ended with, from its output: the last "Error: ..." line, else the last line. pub fn last_error(log: &str) -> Option { let lines: Vec<&str> = log.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); @@ -557,7 +595,7 @@ mod tests { summit_core::display::parse_xrandr("Screen 0: minimum 320 x 200\nVirtual-1 connected primary 1920x1080+0+0 (normal)\n 1920x1080 60.00*+ 50.00\n 1280x720 60.00 59.94\nHDMI-1 disconnected (normal)\n") } fn cx<'a>(own: &'a Layer, base: &'a Profile, defaults: bool, o: &'a [Output]) -> EditCtx<'a> { - EditCtx { own, base, defaults, outs: o, list_err: None, tool: "xrandr", placer: Ok("KWin") } + EditCtx { own, base, defaults, outs: o, list_err: None, tool: "xrandr", placer: Ok("KWin"), auto_window: None } } fn row<'a>(rows: &'a [EditRow], key: &str) -> &'a EditRow { rows.iter().find(|r| r.key == key).unwrap_or_else(|| panic!("no row {key}")) } fn set(own: &Layer, base: &Profile, defaults: bool, o: &[Output], key: &str, label: &str) -> Layer { @@ -673,4 +711,16 @@ mod tests { let e = EditCtx { list_err: Some("GNOME Wayland has no stable tool"), ..cx(&l, &base, true, &[]) }; assert!(row(&edit_rows(&e), "monitor").hint.contains("could not be listed")); } + #[test] + fn window_wait_follows_the_engine() { + assert_eq!(window_wait(""), WindowWait::NotYet); + let ask = "x\n[window] waiting for the game's window to be picked in Summit (up to 300 s)\n"; + assert_eq!(window_wait(ask), WindowWait::Waiting { asking: true }); + let picked = format!("{ask}[window] now looking for 'class:voidrunner' (picked in Summit)\n"); + assert_eq!(window_wait(&picked), WindowWait::Waiting { asking: false }); + let found = format!("{picked}[window] Voidrunner (xid 0x1, pid 2): 1280x720\n[run] source: Voidrunner window\n"); + assert_eq!(window_wait(&found), WindowWait::Found("Voidrunner".into())); + assert_eq!(window_wait("[window] waiting for a window matching 'class:a' (up to 300 s)\n"), WindowWait::Waiting { asking: false }); + assert_eq!(window_wait("[window] waiting for a window matching 'class:a'\nError: no window matches 'class:a' after 300 s\n"), WindowWait::GaveUp); + } } diff --git a/crates/summit-gui/src/main.rs b/crates/summit-gui/src/main.rs index d8c23be..fd5fdaa 100644 --- a/crates/summit-gui/src/main.rs +++ b/crates/summit-gui/src/main.rs @@ -61,6 +61,24 @@ pub struct App { /// Counts the starts, so a game that ends after the launcher was taken back does not end the next one. play_seq: Cell, play_timer: slint::Timer, + /// The windows in the "pick the game's window" list, in its order; when it was last listed, and which listing + /// is current (a slow one that comes back after a newer one is dropped). + pick: RefCell>, + pick_listed: Cell>, + pick_seq: Cell, +} + +/// Enhance on a game started with Play: how far the engine has got with the game's window (from `summit run`'s log), +/// and the windows that were open before the game, so the picker can put the new ones first. +struct EnhanceRun { + id: String, + log: Option, + wait: data::WindowWait, + /// When the engine started looking (and found nothing yet). + since: Option, + /// The picker was opened by itself once already (it is not forced on the player again). + asked: bool, + before: std::sync::Arc>>>, } /// A game started with Play, from the moment it is started until it is gone (ui/playing.slint). @@ -84,6 +102,8 @@ struct Playing { scanned: Option, /// The launcher's window lost the keyboard after the start: the game's window has it. lost_focus: bool, + /// Enhance is on for this run. + enh: Option, status: String, } @@ -352,7 +372,15 @@ impl App { _ if launch::is_install(e) => (false, "Enhance needs the game installed.".to_string()), launch::Plan::Unsupported(why) => (false, format!("Enhance is not available: {why}.")), launch::Plan::Run(_) if session == display::Session::Unknown => (false, "Enhance needs a desktop session (X11 or Wayland); none was found.".to_string()), - launch::Plan::Run(_) if e.source == Source::Steam => (true, "Enhance: the engine waits for the window of class steam_app_ (Proton games) and runs on it until it closes. Not tested with a real Steam game yet.".to_string()), + launch::Plan::Run(_) if let Some(w) = profile::load(&e.id).ok().and_then(|p| p.window) => + (true, format!("Enhance runs on the window this game's profile names ({w}) until it closes. Profile, Game window changes it; empty is automatic.")), + launch::Plan::Run(_) if matches!(e.source, Source::Steam | Source::Lutris | Source::Heroic) => { + let via = match e.source { Source::Lutris => "Lutris", Source::Heroic => "Heroic", _ => "Steam" }; + match launch::window_query(e) { + Some(q) => (true, format!("Enhance: {via} starts the game, then the engine looks for its window ({q}). If that finds nothing, Summit asks you to pick the window, and remembers it.")), + None => (true, format!("Enhance: {via} starts the game. Summit can't tell its window by itself, so it asks you to pick it once the game is up, and remembers it for next time.")), + } + } launch::Plan::Run(_) if session == display::Session::Wayland => (true, "Enhance: frame generation and the upscaler from this game's profile run on its window, live, until either one exits. Wayland: XWayland games directly; a native Wayland game asks once to share its window.".to_string()), launch::Plan::Run(_) => (true, "Enhance: frame generation and the upscaler from this game's profile run on its window, live, until either one exits.".to_string()), } @@ -362,8 +390,9 @@ impl App { let Some(e) = self.entries.borrow().get(idx.max(0) as usize).cloned() else { return }; if e.source == Source::Heuristic { return self.add_game(idx); } // Checked for this entry: Play on Home's hero is not the game whose page was opened last. - let enhance = profile::load(&e.id).map(|p| p.enhance).unwrap_or(false) && self.enhance_available(&e).0; - let argv = match launch::plan(&e, self.cli().as_deref(), enhance) { + let prof = profile::load(&e.id).unwrap_or_default(); + let enhance = prof.enhance && self.enhance_available(&e).0; + let argv = match launch::plan_with(&e, self.cli().as_deref(), enhance, prof.window.as_deref()) { launch::Plan::Run(argv) => argv, launch::Plan::Unsupported(why) => return self.toast(format!("Cannot start {}: {why}", e.title)), }; @@ -407,8 +436,19 @@ impl App { self.play_seq.set(seq); if install { self.toast(how); } else { let tracker = mark.zip(before).map(|(m, b)| (m, running::Tracker::new(&b, Instant::now()))); + // Enhance: the windows open before the game, listed now (off this thread), so the picker can tell + // the game's apart. Consoles are the engine's own picture: nothing to pick. + let enh = (enhance && e.source != Source::Console).then(|| { + let before: std::sync::Arc>>> = Default::default(); + let b = before.clone(); + std::thread::spawn(move || { + let w = winmode::list_windows(display::detect_session(), display::detect_desktop()).unwrap_or_default(); + if let Ok(mut g) = b.lock() { *g = Some(w); } + }); + EnhanceRun { id: e.id.clone(), log: log.as_ref().map(|(p, _)| p.clone()), wait: data::WindowWait::NotYet, since: None, asked: false, before } + }); self.begin_playing(Playing { seq, idx: idx.max(0) as usize, title: e.title.clone(), started: Instant::now(), phase: 0, status: how.clone(), how, child: Some(child.id()), - child_ran: None, tracker, track: running::Phase::Starting, scanned: None, lost_focus: false }); + child_ran: None, tracker, track: running::Phase::Starting, scanned: None, lost_focus: false, enh }); } // When it exits, pick up the session `summit run` recorded. // If it failed (summit run exits 1 on an error, such as a missing engine), say why: the log's last line. @@ -449,6 +489,10 @@ impl App { lib.set_play_phase(p.phase); // Summit can end a game whose process it holds. One that Steam, Lutris or Heroic started is theirs. lib.set_play_can_stop(p.tracker.is_none() && p.child.is_some()); + lib.set_play_enhance(p.enh.is_some()); + lib.set_play_window_note(if p.enh.is_some() { "Enhance starts once the game's window opens".into() } else { "".into() }); + lib.set_play_window_wanted(false); + lib.set_pick_open(false); lib.set_playing(true); self.ui.set_toast_shown(false); *self.playing.borrow_mut() = Some(p); @@ -462,6 +506,7 @@ impl App { let now = Instant::now(); let focused = self.window_focused(); let mut end: Option> = None; + let mut ask = false; { let mut guard = self.playing.borrow_mut(); let Some(p) = guard.as_mut() else { self.play_timer.stop(); return }; @@ -490,8 +535,126 @@ impl App { } let status = match p.phase { 0 => p.how.clone(), 2 => "Closing it".into(), _ => format!("Playing for {}", running::elapsed_label(up.as_secs())) }; if status != p.status { self.ui.global::().set_play_status(status.as_str().into()); p.status = status; } + if let Some(en) = p.enh.as_mut() { ask = self.enhance_tick(en, up, now); } + } + if let Some(note) = end { return self.end_playing(note, true); } + if ask { + // The engine has nothing to look for, or its guess found nothing: ask, with the launcher in front. + if !self.headless && !self.window_focused() { raise_window(); } + self.pick_show(); + } + // the open list keeps up with windows opening and closing + if self.ui.global::().get_pick_open() && self.pick_listed.get().is_some_and(|t| now.duration_since(t) >= Duration::from_secs(2)) { self.list_windows_for_pick(); } + } + + /// Enhance's part of play_tick: what the engine said about the game's window, on the screen. True when the + /// picker should open by itself now (once per run): no rule at all, or Summit's guess found nothing in 20 s. + fn enhance_tick(&self, en: &mut EnhanceRun, up: Duration, now: Instant) -> bool { + let lib = self.ui.global::(); + let wait = en.log.as_deref().and_then(|p| std::fs::read_to_string(p).ok()).map(|t| data::window_wait(&t)).unwrap_or(data::WindowWait::NotYet); + if matches!(wait, data::WindowWait::Waiting { .. }) { en.since.get_or_insert(now); } else { en.since = None; } + let waited = en.since.map(|t| now.duration_since(t)).unwrap_or_default(); + let (note, wanted) = match &wait { + data::WindowWait::NotYet => ("Enhance starts once the game's window opens".to_string(), false), + data::WindowWait::Waiting { asking: true } => ("Enhance waits for you to pick the game's window".into(), true), + data::WindowWait::Waiting { asking: false } if waited >= Duration::from_secs(20) => ("Enhance has not found the game's window yet: pick it".into(), true), + data::WindowWait::Waiting { asking: false } => ("Enhance is looking for the game's window".into(), false), + data::WindowWait::Found(w) => (format!("Enhancing {w}"), false), + data::WindowWait::GaveUp => ("Enhance found no window to run on: the game runs without it".into(), false), + }; + if lib.get_play_window_note().as_str() != note { lib.set_play_window_note(note.into()); } + if lib.get_play_window_wanted() != wanted { lib.set_play_window_wanted(wanted); } + let ask = !en.asked && match wait { + data::WindowWait::Waiting { asking: true } => up >= Duration::from_secs(5), + data::WindowWait::Waiting { asking: false } => waited >= Duration::from_secs(20), + _ => false, + }; + if ask { en.asked = true; } + en.wait = wait; + ask + } + + /// Open the "pick the game's window" list (Enhance, while a game runs) and fill it. + fn pick_show(&self) { + if self.playing.borrow().as_ref().and_then(|p| p.enh.as_ref()).is_none() { return; } + let lib = self.ui.global::(); + if !lib.get_pick_open() { + self.pick.borrow_mut().clear(); + lib.set_pick_rows(ModelRc::new(VecModel::from(Vec::::new()))); + lib.set_pick_sel(0); + lib.set_pick_note("Listing the open windows...".into()); + lib.set_pick_open(true); + } + self.list_windows_for_pick(); + } + + /// List the windows off the UI thread (KWin answers over D-Bus), then show them (pick_listed). + fn list_windows_for_pick(&self) { + let seq = self.pick_seq.get() + 1; + self.pick_seq.set(seq); + self.pick_listed.set(Some(Instant::now())); + if self.headless { return; } + std::thread::spawn(move || { + let r = winmode::list_windows(display::detect_session(), display::detect_desktop()); + let _ = slint::invoke_from_event_loop(move || with_app(|a| a.pick_got(seq, r))); + }); + } + + fn pick_got(&self, seq: u64, listed: Result, String>) { + let lib = self.ui.global::(); + if seq != self.pick_seq.get() || !lib.get_pick_open() { return; } + let before = self.playing.borrow().as_ref().and_then(|p| p.enh.as_ref()).and_then(|en| en.before.lock().ok().and_then(|g| g.clone())); + let me = std::process::id(); + let ws = match listed { + Ok(ws) => ws, + Err(e) => { + lib.set_pick_note(format!("The open windows can't be listed here ({e}). Type the window's rule in this game's Profile, under Game window.").into()); + return; + } + }; + let mut ws: Vec<(bool, winmode::OpenWindow)> = ws.into_iter() + .filter(|w| w.pid != me && !w.class.eq_ignore_ascii_case("summit")) + .map(|w| { + let fresh = before.as_ref().is_some_and(|b| !b.iter().any(|o| o.pid == w.pid && o.class == w.class)); + (fresh, w) + }).collect(); + ws.sort_by_key(|(fresh, _)| !*fresh); // new since Play first, otherwise as KWin lists them + // keep the highlighted window highlighted when the list changes under it + let was = self.pick.borrow().get(lib.get_pick_sel().max(0) as usize).cloned(); + let rows: Vec = ws.iter().map(|(fresh, w)| PickRow { + title: if w.title.trim().is_empty() { w.class.as_str().into() } else { w.title.as_str().into() }, + detail: format!("{} · pid {} · found by {}", if w.class.is_empty() { "no class" } else { &w.class }, w.pid, winmode::rule_for(w)).into(), + fresh: *fresh, + }).collect(); + let sel = was.and_then(|o| ws.iter().position(|(_, w)| w.pid == o.pid && w.title == o.title)).unwrap_or(0); + *self.pick.borrow_mut() = ws.into_iter().map(|(_, w)| w).collect(); + lib.set_pick_note(if rows.is_empty() { "No windows are open yet. Once the game's window is up, it shows here.".into() } else { "".into() }); + lib.set_pick_rows(ModelRc::new(VecModel::from(rows))); + lib.set_pick_sel(sel as i32); + } + + /// The player picked window `i`: Enhance takes it now (the waiting engine reads the rule from its window file) + /// and every time after (the game's profile keeps the rule). + fn pick_choose(&self, i: i32) { + let Some(w) = self.pick.borrow().get(i.max(0) as usize).cloned() else { return }; + let Some((id, found)) = self.playing.borrow().as_ref().and_then(|p| p.enh.as_ref()).map(|en| (en.id.clone(), en.wait.clone())) else { return }; + let rule = winmode::rule_for(&w); + let lib = self.ui.global::(); + lib.set_pick_open(false); + let name = if w.title.trim().is_empty() { w.class.clone() } else { w.title.clone() }; + if let Err(err) = profile::update_layer(&id, |l| l.window = Some(rule.clone())) { + return self.toast(format!("Could not save the window in the profile: {err}")); + } + match found { + data::WindowWait::Found(now) => self.toast(format!("Saved: Enhance takes \"{name}\" from the next start (it runs on {now} now). Profile, Game window changes it.")), + _ => { + let handed = summit_core::engine::window_file(&id).is_some_and(|f| f.exists() && std::fs::write(&f, &rule).is_ok()); + lib.set_play_window_note(format!("Enhance is starting on {name}").into()); + lib.set_play_window_wanted(false); + self.toast(if handed { format!("Enhance takes \"{name}\", now and next time (saved in the profile as {rule})") } + else { format!("Saved: Enhance takes \"{name}\" from the next start ({rule})") }); + } } - if let Some(note) = end { self.end_playing(note, true); } } /// `summit run` ended. For a game Summit started itself that is the game ending; one handed to Steam, Lutris @@ -519,6 +682,7 @@ impl App { fn end_playing(&self, note: Option, front: bool) { if self.playing.borrow_mut().take().is_none() { return; } self.play_timer.stop(); + self.ui.global::().set_pick_open(false); self.ui.global::().set_playing(false); self.refresh_tracked(); // the game's page, if that is where Play was pressed: its sessions and hours, with this one in @@ -889,7 +1053,8 @@ impl App { let placer = summit_core::winmode::backend(s, d, summit_core::doctor::on_path); let placer = match &placer { Ok(summit_core::winmode::Backend::KWin) => Ok("a KWin script"), Ok(_) => Ok("wmctrl"), Err(e) => Err(e.as_str()) }; let (list, err) = match &ed.outs { Ok(o) => (o.as_slice(), None), Err(e) => (&[][..], Some(e.as_str())) }; - let cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: err, tool, placer }; + let auto = ed.game.and_then(|i| self.entries.borrow().get(i).and_then(launch::window_query)); + let cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: err, tool, placer, auto_window: auto.as_deref() }; let rows = data::edit_rows(&cx); ed.keys = rows.iter().map(|r| r.key).collect(); let own_n = rows.iter().filter(|r| r.own).count(); @@ -928,7 +1093,7 @@ impl App { let Some(ed) = ed.as_ref() else { return }; let base = if ed.game.is_none() { profile::Profile::default() } else { profile::load_defaults().unwrap_or_default() }; let list = ed.outs.as_ref().map(|o| o.as_slice()).unwrap_or(&[]); - let cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: None, tool: "", placer: Ok("") }; + let cx = data::EditCtx { own: &own, base: &base, defaults: ed.game.is_none(), outs: list, list_err: None, tool: "", placer: Ok(""), auto_window: None }; data::edit_apply(&cx, key, value.max(0) as usize) }; if new != own { self.save_edit(&id, &new); } @@ -1136,6 +1301,7 @@ pub fn build(headless: bool) -> Rc { add_actions: Default::default(), remote_found: Default::default(), discover_seq: Cell::new(0), chiaki_tap: Default::default(), steam_accounts: Default::default(), playing: Default::default(), play_seq: Cell::new(0), play_timer: slint::Timer::default(), + pick: Default::default(), pick_listed: Cell::new(None), pick_seq: Cell::new(0), }); APP.with(|a| *a.borrow_mut() = Some(app.clone())); @@ -1176,6 +1342,9 @@ pub fn build(headless: bool) -> Rc { lib.on_open_defaults(|| with_app(|a| a.open_defaults())); lib.on_play_back(|| with_app(|a| a.play_back())); lib.on_play_stop(|| with_app(|a| a.play_stop())); + lib.on_pick_show(|| with_app(|a| a.pick_show())); + lib.on_pick_choose(|i| with_app(|a| a.pick_choose(i))); + lib.on_pick_close(|| with_app(|a| a.ui.global::().set_pick_open(false))); let session = display::detect_session(); let portal = if session == display::Session::Wayland && !headless { hotkey::portal_has_global_shortcuts() } else { None }; lib.set_hotkey_status(hotkey::status(session, portal).into()); @@ -1206,7 +1375,26 @@ pub fn build(headless: bool) -> Rc { let how = "Opening through Steam, with Enhance".to_string(); let status = if phase == 1 { "Playing for 12 min".to_string() } else if phase == 2 { "Closing it".into() } else { how.clone() }; app.begin_playing(Playing { seq: 0, idx, title: e.title, started: Instant::now(), phase: phase.clamp(0, 2), how, status, child: Some(0), child_ran: None, - tracker: None, track: running::Phase::Starting, scanned: None, lost_focus: false }); + tracker: None, track: running::Phase::Starting, scanned: None, lost_focus: false, enh: None }); + // SUMMIT_PICK=1: with Enhance waiting, and its window picker open on sample windows (for renders) + if env("SUMMIT_PICK").is_some() { + let w = |pid, class: &str, title: &str| winmode::OpenWindow { pid, class: class.into(), title: title.into() }; + let before = vec![w(6585, "signal", "Signal"), w(15435, "brave-browser", "YouTube - Brave")]; + let mut all = before.clone(); + all.insert(0, w(501, "steam-launch-dev.sh", "steam-launch-dev.sh")); + all.insert(1, w(502, "voidrunner", "Voidrunner -- top-down arena shooter")); + if let Some(p) = app.playing.borrow_mut().as_mut() { + p.enh = Some(EnhanceRun { id: e.id.clone(), log: None, wait: data::WindowWait::Waiting { asking: false }, since: None, asked: true, + before: std::sync::Arc::new(std::sync::Mutex::new(Some(before))) }); + } + let lib = app.ui.global::(); + lib.set_play_enhance(true); + lib.set_play_window_note("Enhance has not found the game's window yet: pick it".into()); + lib.set_play_window_wanted(true); + app.pick_show(); + app.pick_got(app.pick_seq.get(), Ok(all)); + lib.set_pick_sel(1); + } } } // SUMMIT_ADD=0|1|2: the Add dialog, on its first page (0) or on the capture card (1) or Remote Play (2) list. diff --git a/crates/summit-gui/ui/app.slint b/crates/summit-gui/ui/app.slint index ae21cf2..4aeb31f 100644 --- a/crates/summit-gui/ui/app.slint +++ b/crates/summit-gui/ui/app.slint @@ -1,6 +1,6 @@ // Summit launcher window: navbar, the four views, a game's page, the art backdrop and keyboard navigation. import { Theme, Palette } from "theme.slint"; -import { Lib, Prefs, Game, URow, Detail, PRow, AddItem, SteamAccount, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint"; +import { Lib, Prefs, Game, URow, Detail, PRow, PickRow, AddItem, SteamAccount, Icon, Icons, Wordmark, KeyCap, Toast, FocusRing } from "widgets.slint"; import { AddDialog } from "add.slint"; import { HomeView } from "home.slint"; import { LibraryView, UnfilteredView } from "library.slint"; @@ -8,7 +8,7 @@ import { DetailView } from "detail.slint"; import { SettingsView } from "settings.slint"; import { PlayingView } from "playing.slint"; import { Splash } from "splash.slint"; -export { Lib, Prefs, Game, URow, Detail, PRow, AddItem, SteamAccount, Palette } +export { Lib, Prefs, Game, URow, Detail, PRow, PickRow, AddItem, SteamAccount, Palette } component NavTab inherits Rectangle { in property label; diff --git a/crates/summit-gui/ui/playing.slint b/crates/summit-gui/ui/playing.slint index 0488a91..b182242 100644 --- a/crates/summit-gui/ui/playing.slint +++ b/crates/summit-gui/ui/playing.slint @@ -2,7 +2,7 @@ // Nothing else of the launcher is on screen or takes input then, so a controller in the game cannot press things // here. It goes away by itself when the game closes (Rust: App::end_playing). import { Theme } from "theme.slint"; -import { Lib, Icon, Icons, Btn, KeyCap, LogoMark } from "widgets.slint"; +import { Lib, Icon, Icons, Btn, KeyCap, LogoMark, FocusRing } from "widgets.slint"; // Three dots that pulse one after the other. component Dots inherits Rectangle { @@ -18,16 +18,31 @@ component Dots inherits Rectangle { export component PlayingView inherits Rectangle { in property phase: Lib.play-phase; // 0 starting, 1 running, 2 stopping - in-out property btn: 0; // 0 back to the launcher, 1 stop + in-out property btn: 0; // 0 back to the launcher, 1 pick the game's window, 2 stop background: Theme.p.bg; + function shown(b: int) -> bool { return b == 0 || (b == 1 && Lib.play-enhance) || (b == 2 && Lib.play-can-stop); } + function step(d: int) { + if (root.shown(root.btn + d)) { root.btn += d; } else if (root.shown(root.btn + 2 * d)) { root.btn += 2 * d; } + } + // keys come here while it is up; everything else is swallowed by the window (app.slint) public function key(e: KeyEvent) -> bool { + if (Lib.pick-open) { + if (e.text == Key.Escape || e.text == Key.Backspace) { Lib.pick-close(); return true; } + if (e.text == Key.UpArrow) { Lib.pick-sel = Math.max(0, Lib.pick-sel - 1); return true; } + if (e.text == Key.DownArrow) { Lib.pick-sel = Math.min(Lib.pick-rows.length - 1, Lib.pick-sel + 1); return true; } + if ((e.text == Key.Return || e.text == " ") && Lib.pick-rows.length > 0) { Lib.pick-choose(Lib.pick-sel); return true; } + return true; + } if (e.text == Key.Escape) { Lib.play-back(); return true; } - if (e.text == Key.LeftArrow || e.text == Key.UpArrow) { root.btn = 0; return true; } - if ((e.text == Key.RightArrow || e.text == Key.DownArrow) && Lib.play-can-stop) { root.btn = 1; return true; } + if (e.text == Key.LeftArrow || e.text == Key.UpArrow) { root.step(-1); return true; } + if (e.text == Key.RightArrow || e.text == Key.DownArrow) { root.step(1); return true; } + if (e.text == "w" || e.text == "W") { if (Lib.play-enhance) { Lib.pick-show(); } return true; } if (e.text == Key.Return || e.text == " ") { - if (root.btn == 1 && Lib.play-can-stop) { Lib.play-stop(); } else { Lib.play-back(); } + if (root.btn == 2 && Lib.play-can-stop) { Lib.play-stop(); } + else if (root.btn == 1 && Lib.play-enhance) { Lib.pick-show(); } + else { Lib.play-back(); } return true; } return false; @@ -65,6 +80,11 @@ export component PlayingView inherits Rectangle { if root.phase == 1: VerticalLayout { alignment: center; Rectangle { width: 10px; height: 10px; border-radius: 5px; background: Theme.p.ok; } } Text { text: Lib.play-status; color: Theme.p.dim; font-size: Theme.t-md; vertical-alignment: center; overflow: elide; } } + if Lib.play-enhance && Lib.play-window-note != "": HorizontalLayout { + alignment: start; spacing: 10px; height: 20px; + VerticalLayout { alignment: center; Icon { size: 16px; color: Lib.play-window-wanted ? Theme.p.accent : Theme.p.ok; commands: Icons.sparkle; } } + Text { text: Lib.play-window-note; color: Lib.play-window-wanted ? Theme.p.text : Theme.p.dim; font-size: Theme.t-sm; vertical-alignment: center; overflow: elide; } + } Text { text: root.phase == 0 ? "Summit steps aside while the game opens." : "Summit is paused while you play, controller included. It comes back when the game closes."; @@ -73,14 +93,62 @@ export component PlayingView inherits Rectangle { Rectangle { height: 6px; } HorizontalLayout { alignment: start; spacing: 12px; - Btn { text: "Back to the launcher"; icon: Icons.back; focused: root.btn == 0 || !Lib.play-can-stop; clicked => { root.btn = 0; Lib.play-back(); } } - if Lib.play-can-stop: Btn { text: "Stop the game"; icon: Icons.close; focused: root.btn == 1; clicked => { root.btn = 1; Lib.play-stop(); } } + Btn { text: "Back to the launcher"; icon: Icons.back; focused: root.btn == 0 || !root.shown(root.btn); clicked => { root.btn = 0; Lib.play-back(); } } + if Lib.play-enhance: Btn { text: "Pick the game's window"; icon: Icons.monitor; primary: Lib.play-window-wanted; focused: root.btn == 1; clicked => { root.btn = 1; Lib.pick-show(); } } + if Lib.play-can-stop: Btn { text: "Stop the game"; icon: Icons.close; focused: root.btn == 2; clicked => { root.btn = 2; Lib.play-stop(); } } } } HorizontalLayout { x: Theme.pad; y: parent.height - 48px; width: parent.width - 2 * Theme.pad; height: 22px; alignment: end; spacing: 24px; + if Lib.play-enhance: KeyCap { key: "W"; label: "Pick the game's window"; } KeyCap { key: "Esc"; label: "Back to the launcher"; } KeyCap { key: "Hold B"; label: "Back, when this window is in front"; } } + + // ---- pick the game's window: over the card, keys and clicks stay here ---- + if Lib.pick-open: ov := Rectangle { + background: Theme.p.bg.with-alpha(0.86); + TouchArea { clicked => { Lib.pick-close(); } } + property w: Math.min(root.width - 2 * Theme.pad, 760px); + property row-h: 58px; + property list-h: Math.min(root.height - 300px, Math.max(1, Lib.pick-rows.length) * self.row-h); + Rectangle { + x: (parent.width - parent.w) / 2; y: (parent.height - self.height) / 2; width: parent.w; height: col.preferred-height; + background: Theme.p.surface; border-radius: Theme.r-md; border-width: Theme.p.border-w; border-color: Theme.p.border; + TouchArea { } // clicks inside don't close it + col := VerticalLayout { + padding: 24px; spacing: 12px; + Text { text: "PICK THE GAME'S WINDOW"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px; } + Text { text: "Enhance runs on the window you pick, and Summit remembers it for " + Lib.play-title + " (Profile, Game window, changes it any time)."; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; } + if Lib.pick-note != "": Text { text: Lib.pick-note; color: Theme.p.faint; font-size: Theme.t-sm; wrap: word-wrap; } + Flickable { + height: ov.list-h; content-height: Lib.pick-rows.length * ov.row-h; + content-y: Math.min(0px, Math.max(self.height - self.content-height, -(Lib.pick-sel * ov.row-h) + self.height / 2 - ov.row-h / 2)); + for r[i] in Lib.pick-rows: Rectangle { + y: i * ov.row-h; height: ov.row-h - 6px; + border-radius: Theme.r-md; + background: i == Lib.pick-sel ? Theme.p.raised : rta.has-hover ? Theme.p.raised.with-alpha(0.6) : transparent; + HorizontalLayout { + padding-left: 14px; padding-right: 14px; spacing: 12px; + VerticalLayout { alignment: center; + Text { text: r.title; color: Theme.p.text; font-size: Theme.t-md; font-weight: 700; overflow: elide; } + Text { text: r.detail; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; } + } + if r.fresh: VerticalLayout { alignment: center; + Rectangle { width: fl.preferred-width + 16px; height: 22px; border-radius: 11px; background: Theme.p.accent.with-alpha(0.18); + fl := Text { text: "opened since Play"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 700; horizontal-alignment: center; vertical-alignment: center; } } + } + } + FocusRing { on: i == Lib.pick-sel; radius: Theme.r-md; } + rta := TouchArea { mouse-cursor: pointer; clicked => { Lib.pick-sel = i; Lib.pick-choose(i); } } + } + } + HorizontalLayout { alignment: end; spacing: 24px; + KeyCap { key: "Enter"; label: "Use this window"; } + KeyCap { key: "Esc"; label: "Cancel"; } + } + } + } + } } diff --git a/crates/summit-gui/ui/widgets.slint b/crates/summit-gui/ui/widgets.slint index 52aff22..70bb52c 100644 --- a/crates/summit-gui/ui/widgets.slint +++ b/crates/summit-gui/ui/widgets.slint @@ -74,6 +74,9 @@ export struct Detail { // One row of the profile editor. kind 0: a value picked from options; 1: a line of text; 2: a section header. // own: the game sets this itself (not following the launcher's defaults). +// A window in the "pick the game's window" list: what it shows, and whether it opened after Play was pressed. +export struct PickRow { title: string, detail: string, fresh: bool } + export struct PRow { label: string, hint: string, options: [string], value: int, kind: int, text: string, placeholder: string, own: bool } // Preferences edited on the settings page (layout, theme and motion live in Theme). Rust saves them to ui.toml. @@ -166,6 +169,17 @@ export global Lib { in property play-can-stop; // Summit holds the game's process, so it can end it callback play-back(); // show the launcher again; the game keeps running callback play-stop(); + // Enhance and the game's window (now playing): what the engine is doing, and picking the window by hand + in property play-enhance; // Enhance is on for this run + in property play-window-note; // "Enhancing ULTRAKILL", "Waiting for the game's window..." + in property play-window-wanted; // the engine is still looking: picking it helps now + in property pick-open; + in property <[PickRow]> pick-rows; + in property pick-note; // "Listing windows...", or why they can't be listed + in-out property pick-sel; + callback pick-show(); + callback pick-choose(int); + callback pick-close(); } // 24x24 line icons, drawn as paths so they follow the theme and scale cleanly. diff --git a/engine/framegen/io.py b/engine/framegen/io.py index 7c8131f..ff8328c 100644 --- a/engine/framegen/io.py +++ b/engine/framegen/io.py @@ -570,6 +570,11 @@ class GLWindowSink: def __init__(self, w: int, h: int, settings=None, restart_reasons=None, choices: dict | None = None, unavailable: dict | None = None, overlay_of=None, hdr: bool = False, hdr_peak: float = 1000.0, window_keys: dict | None = None, clean_source: bool = False, overlay_key: str | None = None) -> None: + if overlay_of is not None and X11 and WAYLAND: + # pyGLFW carries two builds of GLFW and loads its Wayland-only one in a Wayland session, which can't + # open the XWayland window the overlay needs ("glfw init failed"): load the X11 one. Read on the first + # `import glfw`, which is this one. + os.environ.setdefault("PYGLFW_LIBRARY_VARIANT", "x11") import glfw from OpenGL import GL diff --git a/engine/framegen/window_portal.py b/engine/framegen/window_portal.py index aa6b8d9..16767f3 100644 --- a/engine/framegen/window_portal.py +++ b/engine/framegen/window_portal.py @@ -315,7 +315,7 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.enviro Wayland one KWin knows (the portal), waiting up to wait_s for either. Without KWin, a window that isn't an XWayland one can't be looked for: after the wait the portal's dialog lets the user pick it.""" from . import kwin - from .window_x11 import X, X11WindowSource, find_windows, session_problem + from .window_x11 import LiveQuery, X, X11WindowSource, find_windows, session_problem, waiting_line x = X() if session_problem(env) is None else None kw = None if kwin.available(env): @@ -324,7 +324,11 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.enviro except Exception as e: # noqa: BLE001 print(f"[window] can't ask KWin for its windows ({str(e)[:120]})") deadline, said = time.monotonic() + wait_s, False + live = LiveQuery(query, env) while True: + before, query = live.now, live.get() + if query != before: + deadline = time.monotonic() + max(wait_s, 60.0) # a rule picked late still gets its time if x is not None: target = pick(query, find_windows(x)) if target is not None: @@ -358,7 +362,7 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep, env=os.enviro raise RuntimeError(f"no window matches {query!r}" + (f" after {wait_s:.0f} s" if wait_s else "")) if not said: said = True - print(f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)", flush=True) + print(waiting_line(query, wait_s), flush=True) sleep(0.5) diff --git a/engine/framegen/window_x11.py b/engine/framegen/window_x11.py index 021fdec..e5fff59 100644 --- a/engine/framegen/window_x11.py +++ b/engine/framegen/window_x11.py @@ -6,7 +6,8 @@ How it works: - The window is picked by part of its title, "class:NAME" (its WM_CLASS), "pid:N" (the process that owns it, or one it - started), or "xid:N" (its X window id; "hwnd:N" means the same). Windows come from the window manager's list + started), "dir:FOLDER" (a process running from the game's folder: games started through Steam, Lutris or Heroic), or + "xid:N" (its X window id; "hwnd:N" means the same). Windows come from the window manager's list (_NET_CLIENT_LIST), read with Xlib through ctypes: no extra package. - The window is redirected off screen with the Composite extension (XCompositeRedirectWindow, automatic: the X server still paints it as before), so its own picture can be read even while another window covers it. That is what lets @@ -91,13 +92,53 @@ def pid_family(pid: int, proc: str = "/proc") -> set[int]: return family -def pick(query: str, windows: list[XWindow], family=pid_family) -> XWindow | None: - """The window `query` names: "xid:N" (or "hwnd:N"), "pid:N", "class:NAME" (or "exe:NAME"), or part of a title. - Of several matches, the biggest. Several queries split by "|" are tried in turn.""" +def _norm_path(p: str) -> str: + """A path to compare by: "/" separators, lower case, no trailing "/". Wine's "Z:\\games\\x.exe" (drive Z: is the + Linux root) becomes "/games/x.exe".""" + p = p.strip().strip('"').replace("\\", "/") + if len(p) > 2 and p[1] == ":" and p[0].lower() == "z": + p = p[2:] + return p.rstrip("/").lower() + + +def under(path: str, folder: str) -> bool: + """Whether `path` is `folder` or inside it (Wine paths count, case is ignored: Wine's paths don't keep it).""" + p, f = _norm_path(path), _norm_path(folder) + return bool(f) and (p == f or p.startswith(f + "/")) + + +def pid_in_dir(pid: int, folder: str, proc: str = "/proc") -> bool: + """Whether process `pid` belongs to the game in `folder`: it runs from there (its working directory or its + program is in it) or was started with a file in it (a Wine game's command line names its .exe, often as + "Z:\\..."). Steam, Lutris and Heroic all start a game in its own folder, so this finds a game they started + without knowing its window class or process in advance.""" + if pid <= 0: + return False + base = os.path.join(proc, str(pid)) + for link in ("cwd", "exe"): + try: + if under(os.readlink(os.path.join(base, link)), folder): + return True + except OSError: + pass + try: + with open(os.path.join(base, "cmdline"), "rb") as f: + args = f.read().decode(errors="replace").split("\0") + except OSError: + return False + return any(a and under(a, folder) for a in args) + + +def pick(query: str, windows: list[XWindow], family=pid_family, in_dir=pid_in_dir) -> XWindow | None: + """The window `query` names: "xid:N" (or "hwnd:N"), "pid:N", "class:NAME" (or "exe:NAME"), "dir:FOLDER" (a + process running from that folder, see pid_in_dir), or part of a title. Of several matches, the biggest. Several + queries split by "|" are tried in turn.""" if "|" in query: - return next((w for q in query.split("|") if q.strip() and (w := pick(q, windows, family))), None) + return next((w for q in query.split("|") if q.strip() and (w := pick(q, windows, family, in_dir))), None) q = query.strip() low = q.lower() + if not q or low.startswith("ask:"): # "ask:": no rule yet, the window is picked in Summit (live_query) + return None try: if low.startswith(("xid:", "hwnd:")): xid = int(q.split(":", 1)[1], 0) @@ -105,6 +146,9 @@ def pick(query: str, windows: list[XWindow], family=pid_family) -> XWindow | Non if low.startswith("pid:"): pids = family(int(q[4:])) matches = [w for w in windows if w.pid in pids] + elif low.startswith("dir:"): + folder = q[4:].strip() + matches = [w for w in windows if folder and in_dir(w.pid, folder)] elif low.startswith(("class:", "exe:")): name = low.split(":", 1)[1].strip() matches = [w for w in windows if w.cls == name] @@ -470,6 +514,36 @@ class X11WindowSource: f"{self.restarts} time(s) for a resize") +class LiveQuery: + """The --window rule while the engine waits for the game's window, which the player can change from Summit's + launcher: `summit run` names a file in SUMMIT_WINDOW_FILE, and the launcher writes the rule of the window picked + there into it (and saves it in the game's profile). Read on every look; a new rule restarts the wait.""" + + def __init__(self, query: str, env=os.environ) -> None: + self.base, self.path, self.now = query, env.get("SUMMIT_WINDOW_FILE") or "", query + + def get(self) -> str: + """The rule now; when it changed, says so (the launcher reads that line).""" + q = self.base + if self.path: + try: + with open(self.path, encoding="utf-8") as f: + q = f.read().strip() or self.base + except OSError: + pass + if q != self.now: + self.now = q + print(f"[window] now looking for {q!r} (picked in Summit)", flush=True) + return q + + +def waiting_line(query: str, wait_s: float) -> str: + """What the engine says while it waits; Summit's launcher looks for "[window] waiting for".""" + if not query.strip() or query.strip().lower().startswith("ask:"): + return f"[window] waiting for the game's window to be picked in Summit (up to {wait_s:.0f} s)" + return f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)" + + def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowSource: """--window QUERY: the window, waiting up to wait_s for it to open (a game that was just started), or a clear error naming what was looked for.""" @@ -479,7 +553,11 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowS x = X() deadline = time.monotonic() + wait_s said = False + live = LiveQuery(query) while True: + before, query = live.now, live.get() + if query != before: + deadline = time.monotonic() + max(wait_s, 60.0) # a rule picked late still gets its time target = pick(query, find_windows(x)) if target is not None: if wait_s: # a game's window often opens small (a splash) and grows: give it a moment to settle @@ -492,7 +570,7 @@ def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowS + " (python -m framegen.window_x11 --list shows what's found)") if not said: said = True - print(f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)", flush=True) + print(waiting_line(query, wait_s), flush=True) sleep(0.25) diff --git a/engine/tests/test_window_x11.py b/engine/tests/test_window_x11.py index 5c88ed9..f155127 100644 --- a/engine/tests/test_window_x11.py +++ b/engine/tests/test_window_x11.py @@ -223,3 +223,69 @@ def test_real_x_server_lists_windows(): assert w.title and w.w >= wx.MIN_SIZE[0] finally: x.close() + + +def test_pick_by_dir_finds_a_game_a_launcher_started(): + # Steam/Lutris/Heroic start the game; Summit only knows its folder. 500 runs from it, 77 (Konsole) does not. + in_dir = lambda pid, folder: pid == 500 and folder == "/games/Voidrunner" + assert wx.pick("dir:/games/Voidrunner", WINS, in_dir=in_dir).xid == 10 + assert wx.pick("dir:/elsewhere", WINS, in_dir=in_dir) is None + assert wx.pick("class:voidrunner.exe|dir:/games/Voidrunner", WINS, in_dir=in_dir).xid == 10 + assert wx.pick("dir:", WINS, in_dir=lambda p, f: True) is None + + +def test_under_reads_wine_paths_and_keeps_folder_boundaries(): + assert wx.under("/games/Voidrunner/bin/vr", "/games/Voidrunner") + assert wx.under("Z:\\games\\Voidrunner\\VR.exe", "/games/voidrunner/") + assert wx.under("/games/Voidrunner", "/games/Voidrunner") + assert not wx.under("/games/Voidrunner2/vr", "/games/Voidrunner") + assert not wx.under("C:\\windows\\explorer.exe", "/games/Voidrunner") + + +def test_pid_in_dir_reads_cwd_exe_and_cmdline(tmp_path): + def proc(pid, cwd, exe, cmd): + d = tmp_path / str(pid) + d.mkdir() + os.symlink(cwd, d / "cwd") + os.symlink(exe, d / "exe") + (d / "cmdline").write_bytes("\0".join(cmd).encode() + b"\0") + proc(1, "/games/VR", "/usr/bin/vr", ["vr"]) # runs from the folder + proc(2, "/home/me", "/games/VR/vr", ["vr"]) # its program is in it + proc(3, "/home/me", "/proton/wine64", ["Z:\\games\\VR\\VR.exe"]) # Wine, the .exe on its command line + proc(4, "/home/me", "/usr/bin/steam", ["steam", "steam://rungameid/1"]) # not the game + got = [p for p in (1, 2, 3, 4, 5, 0) if wx.pid_in_dir(p, "/games/VR", proc=str(tmp_path))] + assert got == [1, 2, 3] + + +def test_ask_matches_nothing_until_a_rule_is_picked(): + assert wx.pick("ask:", WINS) is None + assert wx.pick("", WINS) is None + assert "picked in Summit" in wx.waiting_line("ask:", 300) + assert "matching 'class:x'" in wx.waiting_line("class:x", 60) + + +def test_live_query_follows_the_file_summit_writes(tmp_path, capsys): + f = tmp_path / "window-rule" + live = wx.LiveQuery("ask:", env={"SUMMIT_WINDOW_FILE": str(f)}) + assert live.get() == "ask:" # no file yet + f.write_text("class:voidrunner\n") + assert live.get() == "class:voidrunner" # picked in the launcher + assert "now looking for 'class:voidrunner'" in capsys.readouterr().out + f.write_text("") + assert live.get() == "ask:" # emptied: back to what it was started with + assert wx.LiveQuery("class:a", env={}).get() == "class:a" + + +def test_open_window_takes_a_rule_picked_while_it_waits(tmp_path, monkeypatch): + f = tmp_path / "window-rule" + monkeypatch.setenv("SUMMIT_WINDOW_FILE", str(f)) + monkeypatch.setattr(wx, "session_problem", lambda env=None: None) + monkeypatch.setattr(wx, "X", lambda *a: object()) + monkeypatch.setattr(wx, "find_windows", lambda x=None: WINS) + monkeypatch.setattr(wx, "X11WindowSource", lambda target, x: target) + looks = [] + def sleep(_s): + looks.append(1) + if len(looks) == 3: + f.write_text("class:konsole") # the player picks it in Summit + assert wx.open_window("ask:", wait_s=30, sleep=sleep).xid == 12