diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 41108a86e..35de188f9 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -366,7 +366,7 @@ MCP: `instance_export`. ## `horizon-launcher instance launch` -Show or set what runs around an instance's game: a shell command before it (the game starts only if it succeeds), a wrapper it runs through (`nice -n 5`), and environment variables ("NAME=value NAME2=value"). An empty value clears one. +Show or set what runs around an instance's game: a shell command before it (the game starts only if it succeeds), a wrapper it runs through (`nice -n 5`), and environment variables ("NAME=value NAME2=value"). An empty value clears one. On Linux, also GameMode, MangoHud and the dedicated graphics card, when the computer has them. horizon-launcher instance launch @@ -374,6 +374,9 @@ Show or set what runs around an instance's game: a shell command before it (the - `--pre-launch` - `--wrapper` - `--env` +- `--gamemode`: Linux: run it through GameMode (gamemoderun), on or off +- `--mangohud`: Linux: MangoHud's overlay, on or off +- `--dedicated-gpu`: Linux: the dedicated graphics card (DRI_PRIME, or NVIDIA's offload), on or off MCP: `instance_launch`, needs `confirm: true`. diff --git a/launcher/README.md b/launcher/README.md index 41ff3c915..104285c5a 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -108,6 +108,13 @@ The opening, then Play ([clip](docs/opening.webm)): through `"$@"` untouched; on Windows `cmd /C` runs ` && `. Both the window's Play and `play` use them. `horizon-launcher instance launch [--pre-launch …] [--wrapper …] [--env …]` (an MCP agent needs `confirm: true`: it sets commands Play runs). + On Linux the panel also has switches for what the computer has: **GameMode** (`gamemoderun` + on the PATH), **MangoHud** (`mangohud`), and, with two graphics cards under + `/sys/class/drm`, the **dedicated graphics card** (`DRI_PRIME=1`, or NVIDIA's + `__NV_PRIME_RENDER_OFFLOAD`, `__VK_LAYER_NV_optimus` and `__GLX_VENDOR_LIBRARY_NAME` when its + driver is loaded). A switch whose tool is gone does nothing. `instance launch --gamemode + on|off --mangohud on|off --dedicated-gpu on|off`; `HORIZON_LAUNCHER_LINUX_TOOLS` makes any + system show them, for tests. - **Desktop shortcut**: Home's Instance row has **Shortcut**: a shortcut on the desktop that plays the selected instance without opening the launcher (`horizon-launcher play --instance `). A `.desktop` file on Linux (also put in the applications menu, and marked trusted with `gio` diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 38150917f..e88144fe3 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -200,7 +200,8 @@ enum InstanceCmd { }, /// Show or set what runs around an instance's game: a shell command before it (the game /// starts only if it succeeds), a wrapper it runs through (`nice -n 5`), and environment - /// variables ("NAME=value NAME2=value"). An empty value clears one + /// variables ("NAME=value NAME2=value"). An empty value clears one. On Linux, also GameMode, + /// MangoHud and the dedicated graphics card, when the computer has them Launch { instance: String, #[arg(long)] @@ -209,6 +210,15 @@ enum InstanceCmd { wrapper: Option, #[arg(long)] env: Option, + /// Linux: run it through GameMode (gamemoderun), on or off + #[arg(long)] + gamemode: Option, + /// Linux: MangoHud's overlay, on or off + #[arg(long)] + mangohud: Option, + /// Linux: the dedicated graphics card (DRI_PRIME, or NVIDIA's offload), on or off + #[arg(long)] + dedicated_gpu: Option, }, /// Put a shortcut on the desktop that plays an instance (`play --instance`): a .desktop /// file (also in the applications menu) on Linux, an app on macOS, a .lnk on Windows @@ -1853,10 +1863,37 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { pre_launch, wrapper, env, + gamemode, + mangohud, + dedicated_gpu, } => { use horizon_launcher::launch; let env = env.as_deref().map(launch::parse_env).transpose()?; - let changing = pre_launch.is_some() || wrapper.is_some() || env.is_some(); + let [gamemode, mangohud, dedicated_gpu] = + [gamemode, mangohud, dedicated_gpu].map(|v| v.as_deref().map(on_off)); + let [gamemode, mangohud, dedicated_gpu] = [ + gamemode.transpose()?, + mangohud.transpose()?, + dedicated_gpu.transpose()?, + ]; + let found = launch::Found::here(); + for (on, has, name) in [ + (gamemode, found.gamemode, "GameMode (gamemoderun)"), + (mangohud, found.mangohud, "MangoHud"), + (dedicated_gpu, found.two_gpus, "A second graphics card"), + ] { + if on == Some(true) && !has { + eprintln!( + "{name} isn't on this computer: the switch does nothing until it is." + ); + } + } + let changing = pre_launch.is_some() + || wrapper.is_some() + || env.is_some() + || gamemode.is_some() + || mangohud.is_some() + || dedicated_gpu.is_some(); let i = match changing { false => instances::find(&instance)?, true => instances::edit(&instance, |m| { @@ -1869,12 +1906,26 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { if let Some(e) = env { m.launch.env = e; } + if let Some(on) = gamemode { + m.launch.gamemode = on; + } + if let Some(on) = mangohud { + m.launch.mangohud = on; + } + if let Some(on) = dedicated_gpu { + m.launch.dedicated_gpu = on; + } })?, }; let l = &i.launch; if as_json { json(serde_json::json!({ "instance": i.id, "pre_launch": l.pre_launch, "wrapper": l.wrapper, "env": l.env, + "gamemode": l.gamemode, "mangohud": l.mangohud, "dedicated_gpu": l.dedicated_gpu, + "found": { + "gamemode": found.gamemode, "mangohud": found.mangohud, + "two_gpus": found.two_gpus, "nvidia": found.nvidia, + }, })); } else { println!( @@ -1885,6 +1936,15 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { println!(" pre-launch: {}", l.pre_launch); println!(" wrapper: {}", l.wrapper); println!(" env: {}", launch::env_line(&l.env)); + let yes = |b: bool| if b { "on" } else { "off" }; + for (name, on, has) in [ + ("gamemode:", l.gamemode, found.gamemode), + ("mangohud:", l.mangohud, found.mangohud), + ("gpu:", l.dedicated_gpu, found.two_gpus), + ] { + let note = if has { "" } else { " (not on this computer)" }; + println!(" {name:<11} {}{note}", yes(on)); + } } } InstanceCmd::Shortcut { instance, remove } => { diff --git a/launcher/src/launch.rs b/launcher/src/launch.rs index 486f5f469..0219c88ba 100644 --- a/launcher/src/launch.rs +++ b/launcher/src/launch.rs @@ -29,6 +29,118 @@ pub struct Launch { /// Environment variables for the game (and the two commands above). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub env: BTreeMap, + /// Linux: run the game through Feral's GameMode (`gamemoderun`), when it is installed. + #[serde(default, skip_serializing_if = "is_false")] + pub gamemode: bool, + /// Linux: MangoHud's overlay (`mangohud`), when it is installed. + #[serde(default, skip_serializing_if = "is_false")] + pub mangohud: bool, + /// Linux: the dedicated graphics card of a computer with two (PRIME render offload). + #[serde(default, skip_serializing_if = "is_false")] + pub dedicated_gpu: bool, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +/// What this Linux computer has for the three switches. Elsewhere, nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Found { + pub gamemode: bool, + pub mangohud: bool, + /// More than one graphics card. + pub two_gpus: bool, + /// NVIDIA's own driver is loaded: offload asks for it, not Mesa. + pub nvidia: bool, +} + +/// `HORIZON_LAUNCHER_LINUX_TOOLS=gamemode,mangohud,gpu,nvidia`: what [`Found::here`] says is +/// installed, on any system (for tests and screenshots). +pub const TOOLS_ENV: &str = "HORIZON_LAUNCHER_LINUX_TOOLS"; + +fn on_path(program: &str) -> bool { + std::env::var_os("PATH").is_some_and(|path| { + std::env::split_paths(&path).any(|dir| { + let file = dir.join(program); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.metadata() + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + } + #[cfg(not(unix))] + file.is_file() + }) + }) +} + +impl Found { + /// What is installed here: on Linux, `gamemoderun` and `mangohud` on the PATH, the cards + /// under `/sys/class/drm`, and `/proc/driver/nvidia`. + pub fn here() -> Found { + if let Some(list) = std::env::var_os(TOOLS_ENV) { + let list = list.to_string_lossy(); + let has = |n: &str| list.split(',').any(|w| w.trim() == n); + return Found { + gamemode: has("gamemode"), + mangohud: has("mangohud"), + two_gpus: has("gpu"), + nvidia: has("nvidia"), + }; + } + if !cfg!(target_os = "linux") { + return Found::default(); + } + let cards = std::fs::read_dir("/sys/class/drm") + .into_iter() + .flatten() + .flatten() + .filter(|e| { + let name = e.file_name(); + let name = name.to_string_lossy(); + name.strip_prefix("card") + .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) + }) + .count(); + Found { + gamemode: on_path("gamemoderun"), + mangohud: on_path("mangohud"), + two_gpus: cards >= 2, + nvidia: std::path::Path::new("/proc/driver/nvidia/gpus").is_dir(), + } + } + + /// Whether any switch can be shown. + pub fn any(&self) -> bool { + self.gamemode || self.mangohud || self.two_gpus + } +} + +/// The programs the switches put before the game (and the player's wrapper), outermost first. +fn switch_programs(launch: &Launch, found: &Found) -> Vec { + let mut out = Vec::new(); + if launch.gamemode && found.gamemode { + out.push("gamemoderun".into()); + } + if launch.mangohud && found.mangohud { + out.push("mangohud".into()); + } + out +} + +/// The variables the dedicated GPU switch sets: NVIDIA's offload variables with its driver, +/// else Mesa's `DRI_PRIME`. The player's own variables come after and win. +pub fn switch_env(launch: &Launch, found: &Found) -> Vec<(&'static str, &'static str)> { + match (launch.dedicated_gpu && found.two_gpus, found.nvidia) { + (false, _) => vec![], + (true, true) => vec![ + ("__NV_PRIME_RENDER_OFFLOAD", "1"), + ("__VK_LAYER_NV_optimus", "NVIDIA_only"), + ("__GLX_VENDOR_LIBRARY_NAME", "nvidia"), + ], + (true, false) => vec![("DRI_PRIME", "1")], + } } impl Launch { @@ -45,6 +157,15 @@ impl Launch { if !self.wrapper.trim().is_empty() { parts.push(format!("through {}", self.wrapper.trim())); } + if self.gamemode { + parts.push("with GameMode".into()); + } + if self.mangohud { + parts.push("with MangoHud".into()); + } + if self.dedicated_gpu { + parts.push("on the dedicated GPU".into()); + } match self.env.len() { 0 => {} 1 => parts.push("with 1 variable".into()), @@ -144,12 +265,11 @@ pub enum Plan { Cmd { line: String }, } -/// The plan for `words` (the game's program and arguments) with `launch`, on Windows or not. -pub fn plan(launch: &Launch, words: Vec, windows: bool) -> Plan { - let mut all: Vec = split_args(&launch.wrapper) - .into_iter() - .map(OsString::from) - .collect(); +/// The plan for `words` (the game's program and arguments) with `launch`, on Windows or not, +/// with what the computer has for the switches. +pub fn plan(launch: &Launch, words: Vec, windows: bool, found: &Found) -> Plan { + let mut all = switch_programs(launch, found); + all.extend(split_args(&launch.wrapper).into_iter().map(OsString::from)); all.extend(words); let pre = launch.pre_launch.trim(); match (pre.is_empty(), windows) { @@ -179,7 +299,12 @@ pub fn wrap(cmd: Command, launch: &Launch) -> Command { let words: Vec = std::iter::once(cmd.get_program().to_owned()) .chain(cmd.get_args().map(OsStr::to_owned)) .collect(); - let mut out = match plan(launch, words, cfg!(windows)) { + // The override only shows the switches: they act on Linux. + let found = match cfg!(target_os = "linux") { + true => Found::here(), + false => Found::default(), + }; + let mut out = match plan(launch, words, cfg!(windows), &found) { Plan::Direct(words) => { let mut c = Command::new(&words[0]); c.args(&words[1..]); @@ -211,6 +336,7 @@ pub fn wrap(cmd: Command, launch: &Launch) -> Command { None => out.env_remove(key), }; } + out.envs(switch_env(launch, &found)); out.envs(&launch.env); out } diff --git a/launcher/src/launch/tests.rs b/launcher/src/launch/tests.rs index 32d29cdec..3940488b6 100644 --- a/launcher/src/launch/tests.rs +++ b/launcher/src/launch/tests.rs @@ -29,6 +29,7 @@ fn a_summary_says_what_runs() { pre_launch: "./sync.sh".into(), wrapper: "nice -n 5".into(), env: parse_env("A=1 B=2").unwrap(), + ..Launch::default() }; assert_eq!( launch.summary().unwrap(), @@ -44,7 +45,7 @@ fn each_system_gets_its_plan() { ..Launch::default() }; assert_eq!( - plan(&wrapper, game.clone(), false), + plan(&wrapper, game.clone(), false, &Found::default()), Plan::Direct(os(&[ "nice", "-n", @@ -58,7 +59,7 @@ fn each_system_gets_its_plan() { pre_launch: "echo hi".into(), ..wrapper.clone() }; - let Plan::Shell { script, words } = plan(&both, game.clone(), false) else { + let Plan::Shell { script, words } = plan(&both, game.clone(), false, &Found::default()) else { panic!() }; assert!(script.starts_with("(\necho hi\n) || ")); @@ -68,7 +69,8 @@ fn each_system_gets_its_plan() { plan( &both, os(&[r"C:\Horizon\horizon-client.exe", "--world", "My World"]), - true + true, + &Found::default() ), Plan::Cmd { line: r#"echo hi && nice -n 5 C:\Horizon\horizon-client.exe --world "My World""#.into() @@ -116,6 +118,7 @@ fn the_wrapped_game_runs_after_its_pre_launch_command_in_its_folder() { pre_launch: "echo ran > pre.txt".into(), wrapper: "/usr/bin/env WRAPPED=1".into(), env: parse_env("FROM_INSTANCE=\"it works\"").unwrap(), + ..Launch::default() }; let out = wrap(game, &launch).output().unwrap(); assert!(out.status.success(), "{out:?}"); @@ -141,3 +144,52 @@ fn the_wrapped_game_runs_after_its_pre_launch_command_in_its_folder() { assert!(!dir.join("started.txt").exists()); std::fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn the_linux_switches_act_only_where_their_tools_are() { + let all = Found { + gamemode: true, + mangohud: true, + two_gpus: true, + nvidia: false, + }; + let launch = Launch { + wrapper: "nice".into(), + gamemode: true, + mangohud: true, + dedicated_gpu: true, + ..Launch::default() + }; + assert_eq!( + plan(&launch, os(&["game"]), false, &all), + Plan::Direct(os(&["gamemoderun", "mangohud", "nice", "game"])) + ); + assert_eq!(switch_env(&launch, &all), [("DRI_PRIME", "1")]); + let nvidia = Found { + nvidia: true, + ..all + }; + assert_eq!( + switch_env(&launch, &nvidia), + [ + ("__NV_PRIME_RENDER_OFFLOAD", "1"), + ("__VK_LAYER_NV_optimus", "NVIDIA_only"), + ("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + ] + ); + // Not installed (or not Linux): switched on, but nothing is added. + let none = Found::default(); + assert_eq!( + plan(&launch, os(&["game"]), false, &none), + Plan::Direct(os(&["nice", "game"])) + ); + assert!(switch_env(&launch, &none).is_empty()); + assert!(!none.any() && all.any()); + assert_eq!( + launch.summary().unwrap(), + "through nice, with GameMode, with MangoHud, on the dedicated GPU" + ); + // Off switches aren't written. + let text = serde_json::to_string(&Launch::default()).unwrap(); + assert_eq!(text, "{}"); +} diff --git a/launcher/src/launch_page.rs b/launcher/src/launch_page.rs index fa8311873..4cfad986a 100644 --- a/launcher/src/launch_page.rs +++ b/launcher/src/launch_page.rs @@ -9,6 +9,16 @@ pub(super) struct LaunchPanel { instance: String, /// What Save did, or why not. saved: Option>, + /// What this computer has for the Linux switches, looked at when the panel opens. + found: launch::Found, +} + +/// A Linux switch: which one, its label, and what it does. +#[derive(Clone, Copy)] +enum Toggle { + GameMode, + MangoHud, + Gpu, } impl Launcher { @@ -25,6 +35,7 @@ impl Launcher { self.launch = Some(LaunchPanel { instance: i.id, saved: None, + found: launch::Found::here(), }); } @@ -40,6 +51,7 @@ impl Launcher { pre_launch: pre, wrapper, env, + ..m.launch.clone() } }) }); @@ -56,6 +68,93 @@ impl Launcher { } } + /// Flips a Linux switch, saved at once. + fn flip(&mut self, toggle: Toggle) { + let Some(panel) = &mut self.launch else { + return; + }; + let saved = instances::edit(&panel.instance, |m| { + let on = match toggle { + Toggle::GameMode => &mut m.launch.gamemode, + Toggle::MangoHud => &mut m.launch.mangohud, + Toggle::Gpu => &mut m.launch.dedicated_gpu, + }; + *on = !*on; + }); + panel.saved = Some(saved.map(|i| match i.launch.summary() { + Some(what) => format!("Saved: the next Play {what}."), + None => "Saved: nothing runs around the game.".to_string(), + })); + self.reload_instances(); + } + + /// The Linux switches this computer can use: GameMode and MangoHud when installed, the + /// dedicated GPU with two cards. + fn linux_switches(&self, cx: &mut Context) -> Option
{ + let t = self.theme; + let found = self.launch.as_ref()?.found; + let now = self.selected_instance()?.launch.clone(); + let gpu_about = match found.nvidia { + true => "NVIDIA render offload: __NV_PRIME_RENDER_OFFLOAD and its Vulkan layer.", + false => "Mesa's DRI_PRIME=1, so Vulkan picks the other card.", + }; + let mut list = div().flex().flex_col().gap(px(10.)); + for (toggle, shown, on, label, about) in [ + ( + Toggle::GameMode, + found.gamemode, + now.gamemode, + "GameMode", + "Feral's gamemoderun: CPU and scheduler tuned while you play.", + ), + ( + Toggle::MangoHud, + found.mangohud, + now.mangohud, + "MangoHud", + "The frame time, CPU and GPU overlay.", + ), + ( + Toggle::Gpu, + found.two_gpus, + now.dedicated_gpu, + "Dedicated graphics card", + gpu_about, + ), + ] { + if !shown { + continue; + } + list = list.child( + div() + .id(SharedString::from(format!("launch-switch-{label}"))) + .flex() + .items_center() + .gap(px(10.)) + .cursor_pointer() + .child(switch( + SharedString::from(format!("launch-switch-{label}-s")), + on, + &t, + )) + .child(text(theme::LABEL).text_color(t.ink_soft).child(label)) + .child(text(theme::CAPTION).text_color(t.muted).child(about)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.flip(toggle); + cx.notify(); + })), + ); + } + found.any().then(|| { + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(caps("On this computer").text_color(t.muted)) + .child(list) + }) + } + /// The panel under the Instance row, while open for the selected instance. pub(super) fn launch_panel(&mut self, cx: &mut Context) -> Option
{ let t = self.theme; @@ -124,6 +223,7 @@ impl Launcher { .child(pre) .child(wrapper) .child(env) + .children(self.linux_switches(cx)) .child( div() .flex()