Merge pull request #2626 from ludovic111/feat/launcher-instance-commands
🤖 Agent: launcher-features-1: base main, merge-tree clean against main, CI verify + launcher green; queued.
This commit is contained in:
@@ -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>
|
||||
|
||||
- `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.
|
||||
|
||||
@@ -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 <file>`.
|
||||
- **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 `<command> && <game>`. Both the window's Play
|
||||
and `play` use them. `horizon-launcher instance launch <instance> [--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 <id>`).
|
||||
A `.desktop` file on Linux (also put in the applications menu, and marked trusted with `gio`
|
||||
|
||||
+52
-1
@@ -198,6 +198,18 @@ enum InstanceCmd {
|
||||
#[arg(long)]
|
||||
out: Option<PathBuf>,
|
||||
},
|
||||
/// 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<String>,
|
||||
#[arg(long)]
|
||||
wrapper: Option<String>,
|
||||
#[arg(long)]
|
||||
env: Option<String>,
|
||||
},
|
||||
/// 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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -48,6 +48,7 @@ fn maker(root: &Path) -> impl Fn(&str) -> Result<Instance, String> + '_ {
|
||||
version: None,
|
||||
played: Duration::ZERO,
|
||||
last_played: None,
|
||||
launch: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<u64>,
|
||||
/// 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<String>,
|
||||
pub played: Duration,
|
||||
pub last_played: Option<SystemTime>,
|
||||
/// 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<Instance> {
|
||||
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}."));
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -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 '(<pre-launch>) || exit; exec "$@"' horizon <wrapper…> <game> <args…>`.
|
||||
//! 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 "<pre-launch> && <wrapper…> <game> <args…>"`, 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<String, String>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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<BTreeMap<String, String>, 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, String>) -> String {
|
||||
env.iter()
|
||||
.map(
|
||||
|(k, v)| match v.is_empty() || v.contains([' ', '"', '\'', '\\']) {
|
||||
true => format!("{k}=\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\"")),
|
||||
false => format!("{k}={v}"),
|
||||
},
|
||||
)
|
||||
.collect::<Vec<_>>()
|
||||
.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<OsString>),
|
||||
/// `/bin/sh -c <script> horizon <words…>`.
|
||||
Shell {
|
||||
script: String,
|
||||
words: Vec<OsString>,
|
||||
},
|
||||
/// `cmd /D /S /C "<line>"`: the line as cmd reads it.
|
||||
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<OsString>, windows: bool) -> Plan {
|
||||
let mut all: Vec<OsString> = split_args(&launch.wrapper)
|
||||
.into_iter()
|
||||
.map(OsString::from)
|
||||
.collect();
|
||||
all.extend(words);
|
||||
let pre = launch.pre_launch.trim();
|
||||
match (pre.is_empty(), windows) {
|
||||
(true, _) => Plan::Direct(all),
|
||||
(false, false) => Plan::Shell {
|
||||
script: script(pre),
|
||||
words: all,
|
||||
},
|
||||
(false, true) => Plan::Cmd {
|
||||
line: format!(
|
||||
"{pre} && {}",
|
||||
all.iter()
|
||||
.map(|w| windows_quote(w))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The game's command run with `launch`: a new command with the same folder and variables,
|
||||
/// plus the instance's variables. Call it last, after every argument is added.
|
||||
pub fn wrap(cmd: Command, launch: &Launch) -> Command {
|
||||
if launch.is_empty() {
|
||||
return cmd;
|
||||
}
|
||||
let words: Vec<OsString> = 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)) {
|
||||
Plan::Direct(words) => {
|
||||
let mut c = Command::new(&words[0]);
|
||||
c.args(&words[1..]);
|
||||
c
|
||||
}
|
||||
Plan::Shell { script, words } => {
|
||||
let mut c = Command::new("/bin/sh");
|
||||
c.arg("-c").arg(script).arg("horizon").args(words);
|
||||
c
|
||||
}
|
||||
Plan::Cmd { line } => {
|
||||
let mut c = Command::new("cmd.exe");
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
c.raw_arg(format!("/D /S /C \"{line}\""));
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
c.args(["/D", "/S", "/C", &line]);
|
||||
c
|
||||
}
|
||||
};
|
||||
if let Some(dir) = cmd.get_current_dir() {
|
||||
out.current_dir(dir);
|
||||
}
|
||||
for (key, value) in cmd.get_envs() {
|
||||
match value {
|
||||
Some(value) => out.env(key, value),
|
||||
None => out.env_remove(key),
|
||||
};
|
||||
}
|
||||
out.envs(&launch.env);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "launch/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
fn os(words: &[&str]) -> Vec<OsString> {
|
||||
words.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_are_read_and_written_back() {
|
||||
let env = parse_env("MANGOHUD=1 DRI_PRIME=1\nNAME=\"two words\" EMPTY=").unwrap();
|
||||
assert_eq!(env["MANGOHUD"], "1");
|
||||
assert_eq!(env["NAME"], "two words");
|
||||
assert_eq!(env["EMPTY"], "");
|
||||
assert_eq!(parse_env(&env_line(&env)).unwrap(), env);
|
||||
assert_eq!(
|
||||
env_line(&env),
|
||||
"DRI_PRIME=1 EMPTY=\"\" MANGOHUD=1 NAME=\"two words\""
|
||||
);
|
||||
assert!(parse_env("JUSTANAME").unwrap_err().contains("NAME=value"));
|
||||
assert!(parse_env("1X=2")
|
||||
.unwrap_err()
|
||||
.contains("letters, digits and _"));
|
||||
assert!(parse_env("").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_summary_says_what_runs() {
|
||||
assert_eq!(Launch::default().summary(), None);
|
||||
let launch = Launch {
|
||||
pre_launch: "./sync.sh".into(),
|
||||
wrapper: "nice -n 5".into(),
|
||||
env: parse_env("A=1 B=2").unwrap(),
|
||||
};
|
||||
assert_eq!(
|
||||
launch.summary().unwrap(),
|
||||
"runs ./sync.sh first, through nice -n 5, with 2 variables"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_system_gets_its_plan() {
|
||||
let game = os(&["/opt/horizon-client", "--world", "My World"]);
|
||||
let wrapper = Launch {
|
||||
wrapper: "nice -n 5".into(),
|
||||
..Launch::default()
|
||||
};
|
||||
assert_eq!(
|
||||
plan(&wrapper, game.clone(), false),
|
||||
Plan::Direct(os(&[
|
||||
"nice",
|
||||
"-n",
|
||||
"5",
|
||||
"/opt/horizon-client",
|
||||
"--world",
|
||||
"My World"
|
||||
]))
|
||||
);
|
||||
let both = Launch {
|
||||
pre_launch: "echo hi".into(),
|
||||
..wrapper.clone()
|
||||
};
|
||||
let Plan::Shell { script, words } = plan(&both, game.clone(), false) else {
|
||||
panic!()
|
||||
};
|
||||
assert!(script.starts_with("(\necho hi\n) || "));
|
||||
assert!(script.ends_with("\nexec \"$@\""));
|
||||
assert_eq!(words[0], "nice");
|
||||
assert_eq!(
|
||||
plan(
|
||||
&both,
|
||||
os(&[r"C:\Horizon\horizon-client.exe", "--world", "My World"]),
|
||||
true
|
||||
),
|
||||
Plan::Cmd {
|
||||
line: r#"echo hi && nice -n 5 C:\Horizon\horizon-client.exe --world "My World""#.into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_words_are_quoted_as_the_c_runtime_reads_them() {
|
||||
let q = |w: &str| windows_quote(OsStr::new(w));
|
||||
assert_eq!(q("plain"), "plain");
|
||||
assert_eq!(q("two words"), "\"two words\"");
|
||||
assert_eq!(q(""), "\"\"");
|
||||
assert_eq!(q(r#"say "hi""#), r#""say \"hi\"""#);
|
||||
assert_eq!(q(r"C:\My Folder\"), r#""C:\My Folder\\""#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_add_leaves_the_command_as_it_is() {
|
||||
let mut cmd = Command::new("/opt/game");
|
||||
cmd.arg("--x").env("A", "1");
|
||||
let out = wrap(cmd, &Launch::default());
|
||||
assert_eq!(out.get_program(), "/opt/game");
|
||||
assert_eq!(out.get_args().collect::<Vec<_>>(), ["--x"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_wrapped_game_runs_after_its_pre_launch_command_in_its_folder() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-launch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut game = Command::new("/bin/sh");
|
||||
// The "game" prints its words and two variables: one from the launcher, one the instance's.
|
||||
game.args([
|
||||
"-c",
|
||||
"echo \"$1|$2|$FROM_LAUNCHER|$FROM_INSTANCE\"",
|
||||
"game",
|
||||
"a b",
|
||||
"$HOME",
|
||||
])
|
||||
.current_dir(&dir)
|
||||
.env("FROM_LAUNCHER", "yes");
|
||||
let launch = Launch {
|
||||
pre_launch: "echo ran > pre.txt".into(),
|
||||
wrapper: "/usr/bin/env WRAPPED=1".into(),
|
||||
env: parse_env("FROM_INSTANCE=\"it works\"").unwrap(),
|
||||
};
|
||||
let out = wrap(game, &launch).output().unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
"a b|$HOME|yes|it works\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("pre.txt")).unwrap(),
|
||||
"ran\n"
|
||||
);
|
||||
|
||||
let failing = Launch {
|
||||
pre_launch: "exit 3".into(),
|
||||
..Launch::default()
|
||||
};
|
||||
let mut game = Command::new("/bin/sh");
|
||||
game.args(["-c", "echo started > started.txt"])
|
||||
.current_dir(&dir);
|
||||
let out = wrap(game, &failing).output().unwrap();
|
||||
assert_eq!(out.status.code(), Some(3));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("pre-launch command failed (exit 3)"));
|
||||
assert!(!dir.join("started.txt").exists());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Launch… on Home's Instance row: what runs around the selected instance's game
|
||||
//! (`horizon_launcher::launch`): a command before it, a wrapper, and environment variables.
|
||||
use super::servers_page::Field;
|
||||
use super::*;
|
||||
use horizon_launcher::launch;
|
||||
|
||||
pub(super) struct LaunchPanel {
|
||||
/// The instance it is for: picking another closes it.
|
||||
instance: String,
|
||||
/// What Save did, or why not.
|
||||
saved: Option<Result<String, String>>,
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
pub(super) fn toggle_launch(&mut self) {
|
||||
if self.launch.take().is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(i) = self.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
*self.servers.text(Field::PreLaunch) = i.launch.pre_launch.clone();
|
||||
*self.servers.text(Field::Wrapper) = i.launch.wrapper.clone();
|
||||
*self.servers.text(Field::LaunchEnv) = launch::env_line(&i.launch.env);
|
||||
self.launch = Some(LaunchPanel {
|
||||
instance: i.id,
|
||||
saved: None,
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn save_launch(&mut self) {
|
||||
let Some(id) = self.launch.as_ref().map(|p| p.instance.clone()) else {
|
||||
return;
|
||||
};
|
||||
let pre = self.servers.value(Field::PreLaunch).trim().to_string();
|
||||
let wrapper = self.servers.value(Field::Wrapper).trim().to_string();
|
||||
let saved = launch::parse_env(self.servers.value(Field::LaunchEnv)).and_then(|env| {
|
||||
instances::edit(&id, |m| {
|
||||
m.launch = launch::Launch {
|
||||
pre_launch: pre,
|
||||
wrapper,
|
||||
env,
|
||||
}
|
||||
})
|
||||
});
|
||||
let saved = saved.map(|i| {
|
||||
let said = match i.launch.summary() {
|
||||
Some(what) => format!("Saved: the next Play {what}."),
|
||||
None => "Saved: nothing runs around the game.".to_string(),
|
||||
};
|
||||
self.reload_instances();
|
||||
said
|
||||
});
|
||||
if let Some(p) = &mut self.launch {
|
||||
p.saved = Some(saved);
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel under the Instance row, while open for the selected instance.
|
||||
pub(super) fn launch_panel(&mut self, cx: &mut Context<Self>) -> Option<Div> {
|
||||
let t = self.theme;
|
||||
let selected = self.selected_instance().map(|i| i.id.clone());
|
||||
if self.launch.as_ref().map(|p| &p.instance) != selected.as_ref() {
|
||||
self.launch = None;
|
||||
}
|
||||
let saved = self.launch.as_ref()?.saved.clone();
|
||||
let row = |this: &mut Self,
|
||||
cx: &mut Context<Self>,
|
||||
label: &'static str,
|
||||
field: Field,
|
||||
placeholder: &'static str,
|
||||
about: &'static str| {
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(6.))
|
||||
.child(caps(label).text_color(t.muted))
|
||||
.child(this.field(field, placeholder, 520., cx))
|
||||
.child(text(theme::CAPTION).text_color(t.muted).child(about))
|
||||
};
|
||||
let pre = row(
|
||||
self,
|
||||
cx,
|
||||
"Before the game",
|
||||
Field::PreLaunch,
|
||||
"For example ./backup.sh",
|
||||
"A shell command, run in the instance's folder. The game starts only if it succeeds.",
|
||||
);
|
||||
let wrapper = row(
|
||||
self,
|
||||
cx,
|
||||
"Run the game through",
|
||||
Field::Wrapper,
|
||||
"For example nice -n 5",
|
||||
"A program and its arguments; the game's command line goes after them.",
|
||||
);
|
||||
let env = row(
|
||||
self,
|
||||
cx,
|
||||
"Environment variables",
|
||||
Field::LaunchEnv,
|
||||
"For example NAME=value OTHER=\"two words\"",
|
||||
"For the game and both commands above.",
|
||||
);
|
||||
let save = button("launch-save", "Save", Kind::Secondary, &t).on_click(cx.listener(
|
||||
|this, _: &ClickEvent, _, cx| {
|
||||
this.save_launch();
|
||||
cx.notify();
|
||||
},
|
||||
));
|
||||
let result = saved.map(|s| match s {
|
||||
Ok(said) => text(theme::CAPTION).text_color(t.muted).child(said),
|
||||
Err(e) => text(theme::CAPTION).text_color(t.danger).child(e),
|
||||
});
|
||||
Some(
|
||||
plate(&t)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(14.))
|
||||
.px(px(14.))
|
||||
.py(px(12.))
|
||||
.ml(px(40.))
|
||||
.child(caps("When it starts").text_color(t.muted))
|
||||
.child(pre)
|
||||
.child(wrapper)
|
||||
.child(env)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(12.))
|
||||
.child(save)
|
||||
.children(result),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod game_log;
|
||||
pub mod heads;
|
||||
pub mod import;
|
||||
pub mod instances;
|
||||
pub mod launch;
|
||||
pub mod modpacks;
|
||||
pub mod mojang;
|
||||
pub mod packs;
|
||||
|
||||
@@ -18,6 +18,7 @@ mod game_tools;
|
||||
mod import_page;
|
||||
mod instances_page;
|
||||
mod internet;
|
||||
mod launch_page;
|
||||
mod markdown;
|
||||
mod mcp;
|
||||
mod modpacks_page;
|
||||
@@ -247,6 +248,7 @@ struct Launcher {
|
||||
game_packs: packs_page::Packs,
|
||||
world_packs: datapacks_page::WorldPacks,
|
||||
export: Option<export_page::ExportPanel>,
|
||||
launch: Option<launch_page::LaunchPanel>,
|
||||
importing: import_page::Importing,
|
||||
console: console_page::Console,
|
||||
/// What the window did when the game started (`while_playing.rs`).
|
||||
@@ -418,6 +420,7 @@ impl Launcher {
|
||||
game_packs: packs_page::Packs::default(),
|
||||
world_packs: datapacks_page::WorldPacks::default(),
|
||||
export: None,
|
||||
launch: None,
|
||||
importing: Default::default(),
|
||||
console: Default::default(),
|
||||
aside: while_playing::Aside::new(window.window_handle()),
|
||||
@@ -609,6 +612,14 @@ impl Launcher {
|
||||
cmd.arg(flag).arg(value);
|
||||
}
|
||||
backend::append_game_args(&mut cmd);
|
||||
// Last, around every argument: the instance's pre-launch command,
|
||||
// wrapper and variables.
|
||||
let launch = run
|
||||
.as_ref()
|
||||
.and_then(|id| instances::list().into_iter().find(|i| &i.id == id))
|
||||
.map(|i| i.launch)
|
||||
.unwrap_or_default();
|
||||
let cmd = horizon_launcher::launch::wrap(cmd, &launch);
|
||||
self.client_home = cmd.get_current_dir().map(|d| d.to_path_buf());
|
||||
match backend::spawn(Job::Client, cmd, self.tx.clone()) {
|
||||
Ok(r) => {
|
||||
@@ -2129,6 +2140,7 @@ impl Launcher {
|
||||
.child(section_title("Ready to play", "check", &t).mb(px(12.)))
|
||||
.children(self.instance_row(1, cx))
|
||||
.children(self.export_panel(cx))
|
||||
.children(self.launch_panel(cx))
|
||||
.child(index_row(
|
||||
2,
|
||||
"Resources",
|
||||
|
||||
@@ -40,10 +40,14 @@ pub(super) enum Field {
|
||||
ServerAddress,
|
||||
/// Home's Console's search (`console_page.rs`).
|
||||
ConsoleSearch,
|
||||
/// The Launch panel's (`launch_page.rs`).
|
||||
PreLaunch,
|
||||
Wrapper,
|
||||
LaunchEnv,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
const ALL: [Field; 14] = [
|
||||
const ALL: [Field; 17] = [
|
||||
Field::Name,
|
||||
Field::Seed,
|
||||
Field::Players,
|
||||
@@ -58,6 +62,9 @@ impl Field {
|
||||
Field::ServerName,
|
||||
Field::ServerAddress,
|
||||
Field::ConsoleSearch,
|
||||
Field::PreLaunch,
|
||||
Field::Wrapper,
|
||||
Field::LaunchEnv,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1035,6 +1042,7 @@ impl Launcher {
|
||||
Field::Token => self.save_token(),
|
||||
Field::Email => self.invite_friend(),
|
||||
Field::InstanceName | Field::InstanceGroup | Field::ConsoleSearch => {}
|
||||
Field::PreLaunch | Field::Wrapper | Field::LaunchEnv => self.save_launch(),
|
||||
Field::ServerName | Field::ServerAddress => self.add_server(),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user