diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 03a631cf0..41108a86e 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -364,6 +364,19 @@ Export an instance (or a port) to share: its settings, packs, Horizon mods and t 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. + + horizon-launcher instance launch + +- `INSTANCE` +- `--pre-launch` +- `--wrapper` +- `--env` + +MCP: `instance_launch`, needs `confirm: true`. + ## `horizon-launcher instance shortcut` 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. diff --git a/launcher/README.md b/launcher/README.md index 963ddd187..41ff3c915 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -100,6 +100,14 @@ The opening, then Play ([clip](docs/opening.webm)): pack into the selected instance. A data pack is pointed at the world rows, and the Packs section and the world rows keep taking their own drops. A note in the corner says what happened. `horizon-launcher instance import `. +- **Launch options**: Home's Instance row has **Launch…**: per instance, a shell command run in its + folder before the game (the game starts only if it succeeds), a wrapper the game runs through + (`nice -n 5`), and environment variables (`NAME=value OTHER="two words"`), kept in + `instances.json` (`horizon_launcher::launch`). The game stays one process the launcher follows: + on Unix `/bin/sh` runs the command and then `exec`s the wrapper and the game, whose words pass + 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). - **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 00c21ec66..38150917f 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -198,6 +198,18 @@ enum InstanceCmd { #[arg(long)] out: Option, }, + /// 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 + Launch { + instance: String, + #[arg(long)] + pre_launch: Option, + #[arg(long)] + wrapper: Option, + #[arg(long)] + env: 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 Shortcut { @@ -938,7 +950,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } cmd.args(arg); let started = std::time::Instant::now(); - let played = attached(cmd); + let played = attached(horizon_launcher::launch::wrap(cmd, &instance.launch)); if let Err(e) = instances::record_play(&instance.id, started.elapsed()) { eprintln!("Play time not saved: {e}"); } @@ -1836,6 +1848,45 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { }; changed(instances::edit(&instance, |m| m.version = pin)?) } + InstanceCmd::Launch { + instance, + pre_launch, + wrapper, + env, + } => { + 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 i = match changing { + false => instances::find(&instance)?, + true => instances::edit(&instance, |m| { + if let Some(p) = pre_launch { + m.launch.pre_launch = p.trim().to_string(); + } + if let Some(w) = wrapper { + m.launch.wrapper = w.trim().to_string(); + } + if let Some(e) = env { + m.launch.env = e; + } + })?, + }; + 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, + })); + } else { + println!( + "{}: {}", + i.name, + l.summary().unwrap_or("nothing around the game".into()) + ); + println!(" pre-launch: {}", l.pre_launch); + println!(" wrapper: {}", l.wrapper); + println!(" env: {}", launch::env_line(&l.env)); + } + } InstanceCmd::Shortcut { instance, remove } => { use horizon_launcher::shortcut; let i = match instance { diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index fad614d0f..a6ddbfa34 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -32,6 +32,8 @@ pub const DESTRUCTIVE: &[&str] = &[ "packs remove", "worlds datapack-remove", "unshare-log", + // It sets shell commands the next Play runs: the player says yes first. + "instance launch", ]; /// Commands that send something or reach other people: only when the player asks. diff --git a/launcher/src/import/tests.rs b/launcher/src/import/tests.rs index dcbe0e548..1287b475e 100644 --- a/launcher/src/import/tests.rs +++ b/launcher/src/import/tests.rs @@ -48,6 +48,7 @@ fn maker(root: &Path) -> impl Fn(&str) -> Result + '_ { version: None, played: Duration::ZERO, last_played: None, + launch: Default::default(), }) } } diff --git a/launcher/src/instances.rs b/launcher/src/instances.rs index 34d9bb408..38951bf02 100644 --- a/launcher/src/instances.rs +++ b/launcher/src/instances.rs @@ -8,6 +8,7 @@ //! launcher's data folder, so renaming one never moves a folder. use crate::backend; use crate::browser::horizon::pack as registry_pack; +use crate::launch::Launch; use crate::modpacks; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -97,6 +98,9 @@ pub struct Meta { /// When its last run ended, in seconds since 1970. #[serde(default, skip_serializing_if = "Option::is_none")] pub last_played: Option, + /// What runs around the game: a pre-launch command, a wrapper, variables (`launch`). + #[serde(default, skip_serializing_if = "Launch::is_empty")] + pub launch: Launch, } fn is_zero(n: &u64) -> bool { @@ -140,6 +144,8 @@ pub struct Instance { pub version: Option, pub played: Duration, pub last_played: Option, + /// What runs around the game (`launch::wrap`). + pub launch: Launch, } impl Instance { @@ -213,6 +219,7 @@ fn list_in(game_home: &Path, data: &Path) -> Vec { last_played: meta .last_played .map(|s| UNIX_EPOCH + Duration::from_secs(s)), + launch: meta.launch, id, kind, work, @@ -403,9 +410,13 @@ fn edit_in( if name.is_empty() { return Err("An instance needs a name.".into()); } - if all - .iter() - .any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name)) + // Only a new name is checked: an import can share a name, and changing anything + // else about it must still work. + let renamed = !name.eq_ignore_ascii_case(&instance.name); + if renamed + && all + .iter() + .any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name)) { return Err(format!("There is already an instance called {name}.")); } diff --git a/launcher/src/instances/tests.rs b/launcher/src/instances/tests.rs index 22f8f2b00..b2e2fe6fe 100644 --- a/launcher/src/instances/tests.rs +++ b/launcher/src/instances/tests.rs @@ -149,6 +149,18 @@ fn names_stay_unique_and_packs_are_not_copied() { // An empty group is no group. let grouped = edit_in(&home, &data, "Survival", |m| m.group = Some(" ".into())).unwrap(); assert_eq!(grouped.group, None); + // An import named like an instance: both can still change everything but their names. + let mut store = Store::load(&data); + store.instances.entry(port.id.clone()).or_default().name = Some("Survival".into()); + store.save(&data).unwrap(); + let launched = edit_in(&home, &data, "survival", |m| { + m.launch.wrapper = "nice".into() + }) + .unwrap(); + assert_eq!(launched.launch.wrapper, "nice"); + assert!(edit_in(&home, &data, "survival-2", |m| m.name = + Some("survival".into())) + .is_err()); fs::remove_dir_all(&root).unwrap(); } diff --git a/launcher/src/instances_page.rs b/launcher/src/instances_page.rs index 9af5051fe..b0777e9ba 100644 --- a/launcher/src/instances_page.rs +++ b/launcher/src/instances_page.rs @@ -551,9 +551,13 @@ impl Launcher { instance.clone(), instance.name.clone(), ); + // Under the name, wrapping: six actions don't fit beside it at the window's narrowest. let actions = div() .flex() + .flex_wrap() .gap(px(8.)) + .mt(px(6.)) + .ml(px(-14.)) .child( button("instance-edit", "Edit…", Kind::Ghost, &t).on_click(cx.listener( move |this, _: &ClickEvent, _, cx| { @@ -590,6 +594,22 @@ impl Launcher { cx.notify(); })), ) + .child( + button( + "instance-launch", + if self.launch.is_some() { + "Close launch" + } else { + "Launch…" + }, + Kind::Ghost, + &t, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.toggle_launch(); + cx.notify(); + })), + ) .child(self.shortcut_button(&instance, cx)) .child( button("instance-folder", "Open folder", Kind::Ghost, &t).on_click( @@ -619,9 +639,10 @@ impl Launcher { ), ) .children(self.shortcut_note(&instance.id)) + .child(actions) .into_any_element(), ), - Some(actions.into_any_element()), + None, &t, )) } diff --git a/launcher/src/launch.rs b/launcher/src/launch.rs new file mode 100644 index 000000000..486f5f469 --- /dev/null +++ b/launcher/src/launch.rs @@ -0,0 +1,220 @@ +//! What runs around the game for one instance (`instances::Meta::launch`): a command run before +//! it, a wrapper it runs through, and environment variables. All empty by default. +//! +//! [`wrap`] turns the game's command into one process that does all three, so the launcher still +//! follows one program (its output, its exit, Stop): +//! +//! - Unix: `/bin/sh -c '() || exit; exec "$@"' horizon `. +//! The pre-launch command is the player's own shell line, run in the instance's folder; the +//! game's words go through `"$@"`, so they are never parsed by the shell. `exec` makes the +//! shell become the wrapper (or the game). +//! - Windows: `cmd /D /S /C " && "`, each word quoted. +//! +//! Without a pre-launch command the wrapper is the program itself, and no shell runs. +use crate::backend::split_args; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::ffi::{OsStr, OsString}; +use std::process::Command; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Launch { + /// A shell command run in the instance's folder before the game; the game starts only if it + /// succeeds. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub pre_launch: String, + /// A command line the game runs through, such as `nice -n 5` (quotes group a word). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub wrapper: String, + /// Environment variables for the game (and the two commands above). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub env: BTreeMap, +} + +impl Launch { + pub fn is_empty(&self) -> bool { + self == &Launch::default() + } + + /// What it does, in one line, or None when nothing. + pub fn summary(&self) -> Option { + let mut parts = Vec::new(); + if !self.pre_launch.trim().is_empty() { + parts.push(format!("runs {} first", self.pre_launch.trim())); + } + if !self.wrapper.trim().is_empty() { + parts.push(format!("through {}", self.wrapper.trim())); + } + match self.env.len() { + 0 => {} + 1 => parts.push("with 1 variable".into()), + n => parts.push(format!("with {n} variables")), + } + (!parts.is_empty()).then(|| parts.join(", ")) + } +} + +fn valid_key(key: &str) -> bool { + let mut chars = key.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// `KEY=value KEY2="two words"` (one line, or one per line) as variables. +pub fn parse_env(text: &str) -> Result, String> { + let mut env = BTreeMap::new(); + for word in split_args(text) { + let (key, value) = word + .split_once('=') + .ok_or_else(|| format!("{word}: write it as NAME=value"))?; + if !valid_key(key) { + return Err(format!( + "{key}: a variable's name is letters, digits and _, not starting with a digit" + )); + } + env.insert(key.to_string(), value.to_string()); + } + Ok(env) +} + +/// The variables as [`parse_env`] reads them back. +pub fn env_line(env: &BTreeMap) -> String { + env.iter() + .map( + |(k, v)| match v.is_empty() || v.contains([' ', '"', '\'', '\\']) { + true => format!("{k}=\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\"")), + false => format!("{k}={v}"), + }, + ) + .collect::>() + .join(" ") +} + +/// The Unix script: the pre-launch command (in a subshell, so its `exit` doesn't end the script +/// before the message), then the rest of the arguments as the program. +fn script(pre_launch: &str) -> String { + format!( + "(\n{pre_launch}\n) || {{ s=$?; echo \"The pre-launch command failed (exit $s), so the \ + game did not start.\" >&2; exit $s; }}\nexec \"$@\"" + ) +} + +/// A word quoted for a Windows command line, as programs built with the C runtime read it back. +fn windows_quote(word: &OsStr) -> String { + let word = word.to_string_lossy(); + if !word.is_empty() && !word.contains([' ', '\t', '"']) { + return word.into_owned(); + } + let mut out = String::from("\""); + let mut slashes = 0; + for c in word.chars() { + match c { + '\\' => slashes += 1, + '"' => { + out.extend(std::iter::repeat_n('\\', slashes * 2 + 1)); + out.push('"'); + slashes = 0; + } + c => { + out.extend(std::iter::repeat_n('\\', slashes)); + out.push(c); + slashes = 0; + } + } + } + out.extend(std::iter::repeat_n('\\', slashes * 2)); + out.push('"'); + out +} + +/// How [`wrap`] runs a command on each system, apart from the variables and the folder: the +/// program and its arguments. +#[derive(Debug, PartialEq, Eq)] +pub enum Plan { + /// Run as given (`words[0]` is the program). + Direct(Vec), + /// `/bin/sh -c