From dd77fb8016a5c088c274b0cc486a2b4383edfe9b Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:36:21 +0100 Subject: [PATCH] Launcher: custom arguments for the game's command line Settings gains a one-line Game arguments field, kept as `game_args` in settings.json and appended to the client's command line after the launcher's own, so a player can pass things like `--server-thread` or `--render-distance 40`. Quotes group a word with spaces in it. `horizon-launcher game-args []` shows or sets the line, `play --arg ` passes one for a single run, and the MCP launch_client tool takes an args array. The same splitter feeds all three. Closes #716. Co-Authored-By: Claude Opus 5.5 --- launcher/README.md | 13 +++-- launcher/src/backend.rs | 113 ++++++++++++++++++++++++++++++++++++++++ launcher/src/cli.rs | 74 +++++++++++++++++++++++++- launcher/src/main.rs | 94 +++++++++++++++++++++++++++++++-- launcher/src/mcp.rs | 6 ++- 5 files changed, 290 insertions(+), 10 deletions(-) diff --git a/launcher/README.md b/launcher/README.md index b3dff7fde..b111113f2 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -43,7 +43,13 @@ Windows): `versions//`, `server-jars/`, `server/` and `settings.json`. - **Settings**: install new Horizon versions automatically (on unless you turn it off; the selected version only moves to the new one if you were on the newest), the opening animation, - the game's menu style, and the launcher's own version and update state. + the game's menu style, the game's extra command-line arguments, and the launcher's own version + and update state. +- **Game arguments**: extra arguments added to the game's command line (for example + `--server-thread`), one line where quotes group a word with spaces. They are appended after the + launcher's own arguments, kept as `game_args` in `settings.json`, and apply the next time the + game starts. `horizon-launcher game-args ""` sets them too, and `play --arg ` passes + one for a single run. - **Menu style**: Horizon's own menus or Classic (vanilla's screens). Classic has no way back inside the game, so the launcher is where you return to Horizon's. It is the `menuStyle:` line of `horizon.txt` in the game's home folder (`HORIZON_HOME`, else `horizon` in the data @@ -81,11 +87,12 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher install horizon-launcher remove horizon-launcher prepare [--minecraft ] [--version ] - horizon-launcher play [--version ] + horizon-launcher play [--version ] [--arg ]... start the client; --arg passes an extra argument through (repeatable) horizon-launcher server [--dir ] [--version ] [--accept-eula] horizon-launcher notes [] patch notes as plain text horizon-launcher links the Discord, sponsor and website links horizon-launcher menu-style [horizon|classic] show or set the game's menu style + horizon-launcher game-args [] show or set the extra arguments the game starts with horizon-launcher update [--check] Horizon and the launcher horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report horizon-launcher account [list] the Microsoft accounts signed in (* = plays) @@ -107,7 +114,7 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher data benchmark upload a benchmark report, printed first `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `menu-style`, `game-args`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 6082d1ee9..2f1425f45 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1089,6 +1089,74 @@ pub fn set_menu_style(style: MenuStyle) -> Result<(), String> { fs::write(file, text).map_err(|e| e.to_string()) } +/// Splits the player's extra game arguments (Settings' one line) into words, the way a shell +/// would: spaces separate them, single or double quotes group a word with spaces in it, and a +/// backslash escapes the next character (outside quotes, or inside double quotes). +pub fn split_args(line: &str) -> Vec { + let mut words = Vec::new(); + let mut word = String::new(); + let mut started = false; + let mut quote: Option = None; + let mut chars = line.chars(); + while let Some(c) = chars.next() { + match quote { + Some(q) => { + if c == q { + quote = None; + } else if c == '\\' && q == '"' { + // Inside double quotes only `"` and `\` are escaped, as a shell does. + match chars.next() { + Some(n @ ('"' | '\\')) => word.push(n), + Some(n) => { + word.push('\\'); + word.push(n); + } + None => word.push('\\'), + } + } else { + word.push(c); + } + } + None => match c { + '\'' | '"' => { + quote = Some(c); + started = true; + } + '\\' => { + if let Some(n) = chars.next() { + word.push(n); + started = true; + } + } + c if c.is_whitespace() => { + if started { + words.push(std::mem::take(&mut word)); + started = false; + } + } + _ => { + word.push(c); + started = true; + } + }, + } + } + if started { + words.push(word); + } + words +} + +/// The extra game arguments the player set in Settings, split into words. +pub fn game_args() -> Vec { + split_args(&Settings::load().game_args) +} + +/// Appends the player's extra game arguments, so they add to the launcher's own or override them. +pub fn append_game_args(cmd: &mut Command) { + cmd.args(game_args()); +} + pub fn client_command(tag: &str) -> Command { let home = game_home(); let _ = fs::create_dir_all(&home); @@ -1195,6 +1263,7 @@ pub fn client(tag: &str) -> Result { if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) { eprintln!("Playing offline: {e}"); } + append_game_args(&mut cmd); Ok(cmd) } @@ -1796,6 +1865,10 @@ pub struct Settings { /// means yes; removing the entry stores `false`, so it doesn't come back on the next start. #[serde(default, skip_serializing_if = "Option::is_none")] pub desktop_entry: Option, + /// Extra arguments for the game's command line, as one line (see [`split_args`]). Empty by + /// default. Appended after the launcher's own arguments, so they can add to or override them. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub game_args: String, } impl Settings { @@ -1846,6 +1919,46 @@ mod tests { .contains("application.name = \"Horizon\""))); } + #[test] + fn extra_game_arguments_split_like_a_shell() { + assert!(split_args("").is_empty()); + assert!(split_args(" ").is_empty()); + assert_eq!(split_args("--server-thread"), ["--server-thread"]); + assert_eq!( + split_args("--render-distance 32 --server-thread"), + ["--render-distance", "32", "--server-thread"] + ); + // Quotes keep a word with spaces together; either kind works. + assert_eq!( + split_args("--name 'Two Words' --world \"My World\""), + ["--name", "Two Words", "--world", "My World"] + ); + // An empty quoted word is still a word. + assert_eq!(split_args("--name \"\""), ["--name", ""]); + // A backslash escapes a space outside quotes, and " and \ inside double quotes. + assert_eq!(split_args("--name My\\ World"), ["--name", "My World"]); + assert_eq!(split_args("a\\tb c"), ["atb", "c"]); + assert_eq!(split_args("\"a\\\"b\" 'c\\d'"), ["a\"b", "c\\d"]); + } + + #[test] + fn the_game_arguments_setting_round_trips_and_reaches_the_command() { + let settings = Settings::parse(r#"{"game_args":"--server-thread"}"#); + assert_eq!(settings.game_args, "--server-thread"); + // Unset in an older settings.json: no arguments, and nothing is written for them. + let old = Settings::parse(r#"{"installed":true}"#); + assert_eq!(old.game_args, ""); + assert!(!serde_json::to_string(&old).unwrap().contains("game_args")); + + let mut cmd = Command::new("true"); + cmd.args(split_args("--server-thread --render-distance 40")); + let args: Vec<_> = cmd + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + assert_eq!(args, ["--server-thread", "--render-distance", "40"]); + } + #[test] fn tags_never_mix() { assert!(is_game_tag("v2026.10.13")); diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index b140979b3..d18a60dac 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -132,6 +132,10 @@ enum Cmd { /// Join a friend's world with its invite code #[arg(long)] join: Option, + /// An extra argument for the game, passed through as-is (repeatable), for example + /// --server-thread + #[arg(long = "arg", value_name = "ARG", allow_hyphen_values = true)] + arg: Vec, }, /// Run a dedicated server here; type commands into its console Server { @@ -159,6 +163,13 @@ enum Cmd { #[arg(value_parser = ["horizon", "classic"])] style: Option, }, + /// Show or set the extra arguments the game starts with (for example --server-thread); + /// quotes group a word with spaces in it + GameArgs { + /// Omit to show the current arguments + #[arg(allow_hyphen_values = true)] + args: Option, + }, /// Print the end of the game's log (logs/latest.log in the game folder), or its newest crash /// report Logs { @@ -344,11 +355,12 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } println!("{tag} is prepared."); } - Cmd::Play { version, join } => { + Cmd::Play { version, join, arg } => { let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; if let Some(code) = join { backend::join_friend(&mut cmd, &code)?; } + cmd.args(arg); attached(cmd)? } Cmd::Server { @@ -411,6 +423,24 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("Menu style: {style}"); } } + Cmd::GameArgs { args } => { + let mut settings = backend::Settings::load(); + if let Some(line) = args { + settings.game_args = line; + settings.save(); + } + let line = settings.game_args; + if as_json { + json(serde_json::json!({ + "game_args": line, + "parsed": backend::split_args(&line), + })); + } else if line.is_empty() { + println!("No extra game arguments."); + } else { + println!("Game arguments: {line}"); + } + } Cmd::Logs { lines, crash } => { let (path, text) = backend::read_logs(lines, crash)?; if as_json { @@ -695,3 +725,45 @@ fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[test] + fn play_takes_extra_arguments_that_start_with_hyphens() { + let cli = Cli::try_parse_from([ + "horizon-launcher", + "play", + "--arg", + "--server-thread", + "--arg", + "40", + ]) + .unwrap(); + match cli.command { + Some(Cmd::Play { arg, .. }) => assert_eq!(arg, ["--server-thread", "40"]), + _ => panic!("expected play"), + } + } + + #[test] + fn game_args_takes_one_line_that_starts_with_hyphens() { + let cli = Cli::try_parse_from([ + "horizon-launcher", + "game-args", + "--server-thread --render-distance 40", + ]) + .unwrap(); + match cli.command { + Some(Cmd::GameArgs { args }) => { + assert_eq!( + args.as_deref(), + Some("--server-thread --render-distance 40") + ); + } + _ => panic!("expected game-args"), + } + } +} diff --git a/launcher/src/main.rs b/launcher/src/main.rs index ec1dacf78..1b6cc5b55 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -151,6 +151,10 @@ struct Launcher { friend_focused: bool, friend_focus: FocusHandle, joining: Option, + /// Settings' Game arguments field: the line, whether it has focus, and its focus handle. + args_input: String, + args_focused: bool, + args_focus: FocusHandle, console_scroll: ScrollHandle, /// Opt-in data collection: the player's answer and Settings' section (`collection`). collection: collection::Collection, @@ -245,6 +249,9 @@ impl Launcher { install_error: None, confirm_remove: None, picker_open: false, + args_input: settings.game_args.clone(), + args_focused: false, + args_focus: cx.focus_handle(), settings, links: backend::Links::default(), menu_style: backend::menu_style(), @@ -441,6 +448,7 @@ impl Launcher { self.client_error = Some(e); } } + backend::append_game_args(&mut cmd); match backend::spawn(Job::Client, cmd, self.tx.clone()) { Ok(r) => self.client = Some(r), Err(e) => self.client_error = Some(e), @@ -2026,23 +2034,24 @@ impl Launcher { Some(menus.into_any_element()), &t, )) - .child(index_row(n + 4, "Horizon", Some(plain(&horizon)), horizon_action, &t)) + .child(self.game_args_row(n + 4, cx)) + .child(index_row(n + 5, "Horizon", Some(plain(&horizon)), horizon_action, &t)) .child(index_row( - n + 5, + n + 6, "Launcher", Some(plain(&launcher)), launcher_action, &t, )) .child(index_row( - n + 6, + n + 7, "Data folder", Some(mono(short(&backend::data_dir()))), None, &t, )) .child(index_row( - n + 7, + n + 8, "Logs", Some(mono(format!( "{} ยท crash reports beside it", @@ -2061,7 +2070,7 @@ impl Launcher { )) .when(cfg!(target_os = "linux"), |d| { d.child(index_row( - n + 8, + n + 9, "Applications menu", Some(plain(if self.settings.desktop_entry() { "Horizon and its icon are in your desktop's menu." @@ -2077,6 +2086,80 @@ impl Launcher { .child(agents) } + /// Settings' Game arguments row: the extra arguments the game starts with, kept in + /// `settings.json` and appended to the launcher's own (quotes group a word with spaces). + fn game_args_row(&self, n: usize, cx: &mut Context) -> Div { + let t = self.theme; + let focused = self.args_focused; + let field = div() + .id("game-args") + .track_focus(&self.args_focus) + .flex() + .items_center() + .w(px(300.)) + .h(px(30.)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(6.)) + .border_1() + .border_color(if focused { t.accent } else { t.rule }) + .bg(t.surface) + .font_family(theme::MONO) + .text_size(px(12.)) + .cursor_text() + .child(if self.args_input.is_empty() && !focused { + div() + .text_color(t.muted) + .child("For example --server-thread") + } else { + // The end of a long line stays in view while typing. + let chars: Vec = self.args_input.chars().collect(); + let shown: String = chars[chars.len().saturating_sub(44)..].iter().collect(); + div().text_color(t.ink).child(shown) + }) + .when(focused, |d| d.child(div().w(px(1.)).h(px(14.)).bg(t.ink))) + .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { + window.focus(&this.args_focus); + cx.notify(); + })) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| { + let k = &ev.keystroke; + let paste = k.key == "v" && (k.modifiers.control || k.modifiers.platform); + match k.key.as_str() { + "backspace" => { + this.args_input.pop(); + } + _ if paste => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + this.args_input.push_str(text.trim()); + } + } + _ if !k.modifiers.control && !k.modifiers.platform => { + if let Some(ch) = &k.key_char { + this.args_input.push_str(ch); + } + } + _ => return, + } + this.args_input.truncate(1024); + this.settings.game_args = this.args_input.clone(); + this.settings.save(); + cx.stop_propagation(); + cx.notify(); + })); + index_row( + n, + "Game arguments", + Some( + div() + .child("Extra arguments for the game, passed through as-is (quotes group a word with spaces). Applies the next time the game starts.") + .into_any_element(), + ), + Some(field.into_any_element()), + &t, + ) + } + /// Settings' Microsoft accounts: who is signed in and plays, the sign-in with its code. The /// rows are numbered from 01; returns them and how many there are. fn account_rows(&mut self, cx: &mut Context) -> (Div, usize) { @@ -2811,6 +2894,7 @@ impl Render for Launcher { self.perf.frame(); self.input_focused = self.focus.is_focused(window); self.friend_focused = self.friend_focus.is_focused(window); + self.args_focused = self.args_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 82304923f..2dd2aa5cb 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -37,7 +37,8 @@ fn tools() -> Value { "inputSchema": { "type": "object", "properties": { "version": version, "world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." }, "creative": { "type": "boolean", "description": "Creative mode for a new world." }, - "offscreen": { "type": "boolean", "description": "Render without showing a window (game_screenshot still works)." } } } }, + "offscreen": { "type": "boolean", "description": "Render without showing a window (game_screenshot still works)." }, + "args": { "type": "array", "items": { "type": "string" }, "description": "Extra game arguments, passed through as-is (for example \"--server-thread\")." } } } }, { "name": "start_server", "description": "Start a Horizon dedicated server. It runs until stop_server or the end of this MCP session. Requires agreeing to the Minecraft EULA.", "inputSchema": { "type": "object", "properties": { "version": version, "dir": { "type": "string", "description": "The server's folder. Default: the launcher's server folder." }, "accept_eula": { "type": "boolean", "description": "Agree to the Minecraft EULA (https://aka.ms/MinecraftEULA) on the player's behalf. Only with their consent." } } } }, { "name": "server_command", "description": "Send a console command to the running server (for example \"list\" or \"say hello\"), and return the lines it printed in reply.", @@ -166,6 +167,9 @@ impl Session { cmd.arg(format!("--{flag}")); } } + if let Some(extra) = args.get("args").and_then(Value::as_array) { + cmd.args(extra.iter().filter_map(Value::as_str)); + } let client = Logged::start(Job::Client, cmd)?; // Started once its control socket answers, as horizon-ctl launch waits. let deadline = std::time::Instant::now() + Duration::from_secs(120);