From 7f5e3384b375c822d634f00a020f13f4992263f1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:07:11 +0100 Subject: [PATCH 1/4] Play mining hit sounds once, from the server's destroy level events The server now sends level events 2019 and 2020 every tick a player digs (ServerPlayerGameMode.tick), and clients handle them like LevelEventHandler: a crack on the face, plus the hit sound for 2020. A remote client plays only the first hit itself and no longer adds its own sound every fourth tick, so the hit was heard twice, out of phase, for every block. --- crates/horizon-client/src/game.rs | 45 ++++++++++++------- crates/horizon-client/src/game/lan.rs | 5 ++- .../src/game/level_particles.rs | 24 ++++++++++ crates/horizon-client/src/game/remote.rs | 17 ++----- 4 files changed, 60 insertions(+), 31 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8448f0837..a0bc6c339 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2844,6 +2844,16 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + // LevelEventHandler 2019 and 2020: the crack on a face of the + // block being mined, with its hit sound for 2020. + LevelEvent::LevelEvent { + id: id @ (2019 | 2020), + pos, + data, + } => { + let face = horizon_core::geometry::Direction::ALL[data.clamp(0, 5) as usize]; + self.breaking_block_effects([pos.x, pos.y, pos.z], face.normal(), id == 2020); + } LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } @@ -4042,6 +4052,17 @@ impl Game<'_> { _ => {} } } + /// `ServerPlayerGameMode.tick` while a player digs: level event 2020 every + /// fourth tick since the START (the hit sound), else 2019 (the crack only), + /// for everyone around, the digger included (`levelEvent(null, ...)`). + fn destroy_progress_event(&mut self, pos: [i32; 3], face: [i32; 3], ticks: u32) { + let id = if ticks.is_multiple_of(4) { 2020 } else { 2019 }; + let direction = horizon_core::geometry::Direction::ALL + .iter() + .position(|d| d.normal() == face) + .unwrap_or(1); + self.level_event_at(id, pos, direction as i32); + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; @@ -4085,6 +4106,11 @@ impl Game<'_> { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let facts = self.res.facts().get(state); if facts.hardness < 0.0 { + // The server still counts its destroy ticks on an unbreakable block. + let m = self.mining.as_mut().ok_or("mining")?; + m.ticks += 1; + let (pos, ticks) = (m.pos, m.ticks); + self.destroy_progress_event(pos, hit.face, ticks); return Ok(()); } // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. @@ -4115,26 +4141,15 @@ impl Game<'_> { } else { speed / facts.hardness / if harvest { 30.0 } else { 100.0 } }; - let hit_sound = facts.sounds.clone(); self.swing_arm(); let m = self.mining.as_mut().ok_or("mining")?; m.progress += progress; m.ticks += 1; - let crack = (m.pos, hit.face); - if m.ticks % 4 == 1 { - let c = [ - f64::from(m.pos[0]) + 0.5, - f64::from(m.pos[1]) + 0.5, - f64::from(m.pos[2]) + 0.5, - ]; - self.audio.play( - &hit_sound.hit, - Some(c), - (hit_sound.volume + 1.0) / 8.0, - hit_sound.pitch * 0.5, - ); + // An instant break at START sends no destroy events. + if m.progress < 1.0 || m.ticks > 1 { + let (pos, ticks) = (m.pos, m.ticks); + self.destroy_progress_event(pos, hit.face, ticks); } - self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..3a172073d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1188,8 +1188,9 @@ impl Game<'_> { horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { // The acting guest does not predict the egg's teleport // particles, bone meal's growth, or anvil result sounds - // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + // (these levelEvent calls name no excluded player), nor + // the digger's own crack and hit sound (2019, 2020). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030 | 2019 | 2020) { None } else { self.lan_acting diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..69fbcfc2e 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -134,6 +134,30 @@ impl Game<'_> { // Each guest plays it from the global packet. self.audio.play_unshared(sound, at, volume, 1.0); } + /// `ClientLevel.addBreakingBlockEffects`: the block's hit sound (only for + /// `play_sound`) and one crumb on the face being mined; nothing for air. + pub(super) fn breaking_block_effects( + &mut self, + pos: [i32; 3], + face: [i32; 3], + play_sound: bool, + ) { + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts().is_air(state) { + return; + } + if play_sound { + let sounds = self.res.facts().get(state).sounds.clone(); + // Each guest plays it from the level event itself. + self.audio.play_unshared( + &sounds.hit, + Some(pos.map(|v| f64::from(v) + 0.5)), + (sounds.volume + 1.0) / 8.0, + sounds.pitch * 0.5, + ); + } + self.crack_particle(pos, face, state); + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..1cc659cc0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3866,6 +3866,9 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.destroying = Some((hit.pos, face, 0.0)); } + // startDestroyBlock plays the first hit and crack itself; the + // server's level events 2019 and 2020 do the rest. + self.breaking_block_effects(hit.pos, hit.face, true); self.mining = Some(Mining { pos: hit.pos, progress: 0.0, @@ -3878,20 +3881,6 @@ impl Game<'_> { }; let done = done + progress; let ticks = self.mining.as_ref().map_or(0, |m| m.ticks) + 1; - if ticks % 4 == 1 { - let c = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - &facts.sounds.hit, - Some(c), - (facts.sounds.volume + 1.0) / 8.0, - facts.sounds.pitch * 0.5, - ); - } - self.crack_particle(pos, hit.face, state); if done >= 1.0 { let seq = self.next_sequence(); self.predict_break(pos, state, seq); From 0c127ec1d9285a225d0cee0f29755b8f8fcaff8b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:23:34 +0100 Subject: [PATCH 2/4] Stub breaking_block_effects in the remote mining test fixture --- tests/test_remote_mining.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 9feb255fa..4c77f989d 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -90,6 +90,7 @@ impl Game { fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); } fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); } fn crack_particle(&mut self, _: [i32; 3], _: u8, _: u32) {} + fn breaking_block_effects(&mut self, _: [i32; 3], _: u8, _: bool) {} METHOD } fn main() { From 82c8398c6b3ba361e5f57342e927fb7c94956af3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:02:20 +0100 Subject: [PATCH 3/4] launcher: desktop shortcut that plays an instance Home's Instance row gets Shortcut / Remove shortcut, and the CLI and MCP instance shortcut [instance] [--remove]. The shortcut runs horizon-launcher play --instance : a .desktop file on Linux (and in the applications menu), a script app with Horizon's icon on macOS, and a Shell Link written from Microsoft's published MS-SHLLINK layout on Windows. HORIZON_LAUNCHER_DESKTOP points it at a scratch folder. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/launcher-commands.md | 11 + launcher/README.md | 7 + launcher/src/cli.rs | 30 +++ launcher/src/desktop.rs | 4 +- launcher/src/desktop_seams.rs | 6 +- launcher/src/instances_page.rs | 19 +- launcher/src/lib.rs | 1 + launcher/src/main.rs | 4 + launcher/src/shortcut.rs | 427 +++++++++++++++++++++++++++++++++ launcher/src/shortcut/tests.rs | 197 +++++++++++++++ launcher/src/shortcut_page.rs | 69 ++++++ 12 files changed, 766 insertions(+), 11 deletions(-) create mode 100644 launcher/src/shortcut.rs create mode 100644 launcher/src/shortcut/tests.rs create mode 100644 launcher/src/shortcut_page.rs diff --git a/AGENTS.md b/AGENTS.md index 932eb1067..9c702e8ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] - **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the - launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to + launcher, `HORIZON_LAUNCHER_TRASH`, `HORIZON_LAUNCHER_CLIPBOARD` and `HORIZON_LAUNCHER_DESKTOP` pointing into the scratch home. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. - **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 432b76e72..03a631cf0 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -364,6 +364,17 @@ Export an instance (or a port) to share: its settings, packs, Horizon mods and t MCP: `instance_export`. +## `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. + + horizon-launcher instance shortcut [INSTANCE] + +- `INSTANCE`: The instance (default: the selected one) +- `--remove`: Move the instance's shortcuts to the trash instead + +MCP: `instance_shortcut`. + ## `horizon-launcher instance import` Import what a file is, as dropping it on the window does: a shared instance (a .mrpack without mod loaders, such as `instance export` writes, or a game folder zip) becomes a new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into the instance (default: the selected one). diff --git a/launcher/README.md b/launcher/README.md index ad96eece1..963ddd187 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -100,6 +100,13 @@ 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 `. +- **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` + where it exists), a small app with Horizon's icon on macOS, a `.lnk` on Windows + (`horizon_launcher::shortcut`). **Remove shortcut** moves it to the trash; it is found by the + instance id inside it, so a rename doesn't lose it. `horizon-launcher instance shortcut + [instance] [--remove]`; `HORIZON_LAUNCHER_DESKTOP` points it at another folder. - **Console**: Home's Console shows the game's output of this run as it comes: a search (every word, any case), Follow to keep the newest line in view, Copy, and Open logs folder. Warnings and errors stand out. **Share log…** uploads the log to [mclo.gs](https://mclo.gs), a paste diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 246538b08..00c21ec66 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -198,6 +198,15 @@ enum InstanceCmd { #[arg(long)] out: 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 { + /// The instance (default: the selected one) + instance: Option, + /// Move the instance's shortcuts to the trash instead + #[arg(long)] + remove: bool, + }, /// Import what a file is, as dropping it on the window does: a shared instance (a .mrpack /// without mod loaders, such as `instance export` writes, or a game folder zip) becomes a /// new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into @@ -1827,6 +1836,27 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { }; changed(instances::edit(&instance, |m| m.version = pin)?) } + InstanceCmd::Shortcut { instance, remove } => { + use horizon_launcher::shortcut; + let i = match instance { + Some(name) => instances::find(&name)?, + None => instances::selected(), + }; + let paths = match remove { + false => shortcut::make(backend::exe_path(), &i.id, &i.name)?, + true => shortcut::remove(&i.id)?, + }; + if as_json { + json(serde_json::json!({ "instance": i.id, "paths": paths })); + } else if remove && paths.is_empty() { + println!("{} has no shortcut.", i.name); + } else { + let did = if remove { "Moved to the trash" } else { "Made" }; + for path in paths { + println!("{did}: {}", path.display()); + } + } + } InstanceCmd::Import { file, instance } => { use horizon_launcher::import::{self, Dropped}; use horizon_launcher::modpacks; diff --git a/launcher/src/desktop.rs b/launcher/src/desktop.rs index 281850cb6..863923acb 100644 --- a/launcher/src/desktop.rs +++ b/launcher/src/desktop.rs @@ -65,7 +65,7 @@ pub fn data_home() -> Option { } /// Quotes a path for an `Exec` key: inside double quotes, `"`, `` ` ``, `$` and `\` are escaped. -fn quote(path: &Path) -> String { +pub(crate) fn quote(path: &Path) -> String { let mut out = String::from("\""); for c in path.to_string_lossy().chars() { if matches!(c, '"' | '`' | '$' | '\\') { @@ -215,7 +215,7 @@ pub fn needs_repair_in(data: &Path, path: Option<&OsStr>) -> bool { /// What the entry starts: a distributor's wrapper (`HORIZON_LAUNCHER_DESKTOP_EXEC`) when one is /// configured, else the binary at `exe`. -fn target(exe: &Path) -> PathBuf { +pub(crate) fn target(exe: &Path) -> PathBuf { std::env::var_os("HORIZON_LAUNCHER_DESKTOP_EXEC") .filter(|path| !path.is_empty()) .map_or_else(|| exe.to_path_buf(), PathBuf::from) diff --git a/launcher/src/desktop_seams.rs b/launcher/src/desktop_seams.rs index edec7ab8d..2815748ea 100644 --- a/launcher/src/desktop_seams.rs +++ b/launcher/src/desktop_seams.rs @@ -7,7 +7,8 @@ //! (text as UTF-8, a picture as its PNG or JPEG bytes). //! //! Test runs point both into their scratch folders, beside `HORIZON_HOME` and -//! `HORIZON_LAUNCHER_HOME`. +//! `HORIZON_LAUNCHER_HOME`, and `HORIZON_LAUNCHER_DESKTOP` too (`shortcut`: where desktop +//! shortcuts go). use std::path::{Path, PathBuf}; pub const TRASH_ENV: &str = "HORIZON_LAUNCHER_TRASH"; @@ -22,7 +23,8 @@ pub fn to_trash(path: &Path) -> Result<(), String> { } } -fn to_folder(path: &Path, dir: &Path) -> Result<(), String> { +/// Moves `path` into `dir` under a free name: the trash of a test run. +pub fn to_folder(path: &Path, dir: &Path) -> Result<(), String> { std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let name = path.file_name().ok_or("Nothing to move")?.to_string_lossy(); let target = (1..) diff --git a/launcher/src/instances_page.rs b/launcher/src/instances_page.rs index 273f967df..9af5051fe 100644 --- a/launcher/src/instances_page.rs +++ b/launcher/src/instances_page.rs @@ -590,6 +590,7 @@ impl Launcher { cx.notify(); })), ) + .child(self.shortcut_button(&instance, cx)) .child( button("instance-folder", "Open folder", Kind::Ghost, &t).on_click( move |_, _, cx| { @@ -604,14 +605,20 @@ impl Launcher { Some( div() .flex() - .items_baseline() - .gap(px(10.)) - .child(instance.name.clone()) + .flex_col() .child( - text(theme::CAPTION) - .text_color(t.muted) - .child(played_line(&instance)), + div() + .flex() + .items_baseline() + .gap(px(10.)) + .child(instance.name.clone()) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .child(played_line(&instance)), + ), ) + .children(self.shortcut_note(&instance.id)) .into_any_element(), ), Some(actions.into_any_element()), diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 28c6d21bd..ea896aa21 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -21,6 +21,7 @@ pub mod proxy; pub mod screenshots; pub mod server_list; pub mod servers; +pub mod shortcut; pub mod signed; pub mod sources; pub mod tailscale; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 352ae7e98..257b83226 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -30,6 +30,7 @@ mod perf; mod screenshots_page; mod scrollbar; mod servers_page; +mod shortcut_page; mod theme; mod titlebar; mod while_playing; @@ -250,6 +251,8 @@ struct Launcher { console: console_page::Console, /// What the window did when the game started (`while_playing.rs`). aside: while_playing::Aside, + /// The selected instance's desktop shortcut (`shortcut_page.rs`). + shortcuts: shortcut_page::Shortcuts, /// The name the game made up for an offline player (`horizon-player.txt`), for the top bar. offline_name: Option, /// The player's servers, for the sidebar until the Servers page has read them. @@ -418,6 +421,7 @@ impl Launcher { importing: Default::default(), console: Default::default(), aside: while_playing::Aside::new(window.window_handle()), + shortcuts: Default::default(), offline_name: offline_name(), side_servers: horizon_launcher::servers::list(), art: art::Art::default(), diff --git a/launcher/src/shortcut.rs b/launcher/src/shortcut.rs new file mode 100644 index 000000000..b4e97abd4 --- /dev/null +++ b/launcher/src/shortcut.rs @@ -0,0 +1,427 @@ +//! A shortcut on the desktop that plays one instance: it runs +//! `horizon-launcher play --instance `, so the game starts without the launcher's window. +//! +//! - Linux: ` (Horizon).desktop` on the desktop (executable, and marked trusted with `gio` +//! where it exists, so GNOME starts it), and the same entry in the applications menu +//! (`applications/horizon-instance-.desktop`, `desktop::data_home`). +//! - macOS: ` (Horizon).app`, a small app whose program is a shell script, with Horizon's +//! icon. It has no Dock icon of its own (`LSUIElement`): the game's window is the one to see. +//! - Windows: ` (Horizon).lnk`, a Shell Link as Microsoft's published [MS-SHLLINK] format +//! lays it out, to the launcher's `.exe` with Horizon's icon. +//! +//! Each shortcut names its instance's id inside it, so removing finds it after a rename. +//! `HORIZON_LAUNCHER_DESKTOP` points the desktop folder elsewhere, for tests. +//! +//! [MS-SHLLINK]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/ +use crate::desktop; +use crate::desktop_seams; +use std::fs; +use std::path::{Path, PathBuf}; + +pub const DESKTOP_ENV: &str = "HORIZON_LAUNCHER_DESKTOP"; +const MAC_ICON: &[u8] = include_bytes!("../../packaging/icons/horizon.icns"); +/// The key a Linux shortcut names its instance with. +const INSTANCE_KEY: &str = "X-Horizon-Instance"; +/// And a macOS one, in its Info.plist. +const MAC_KEY: &str = "HorizonInstance"; + +/// The kinds of shortcut, one per system: all of them can be written and tested anywhere. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum System { + Linux, + Mac, + Windows, +} + +impl System { + pub fn here() -> Self { + if cfg!(target_os = "macos") { + Self::Mac + } else if cfg!(windows) { + Self::Windows + } else { + Self::Linux + } + } + + fn extension(self) -> &'static str { + match self { + Self::Linux => "desktop", + Self::Mac => "app", + Self::Windows => "lnk", + } + } +} + +/// The desktop folder: `HORIZON_LAUNCHER_DESKTOP`, else the system's. +pub fn desktop_dir() -> Option { + std::env::var_os(DESKTOP_ENV) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(dirs::desktop_dir) +} + +/// The shortcut's file name: the instance's name without the characters a file name can't +/// hold on any of the three systems. +pub fn file_name(name: &str, system: System) -> String { + let clean: String = name + .chars() + .map(|c| match c { + '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-', + c if c.is_control() => '-', + c => c, + }) + .collect(); + let clean = clean.trim().trim_matches('.'); + let clean = if clean.is_empty() { "Instance" } else { clean }; + format!("{clean} (Horizon).{}", system.extension()) +} + +/// The id as a file name or bundle id part: letters, digits and `-`. +fn slug(id: &str) -> String { + id.chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect() +} + +/// A Linux `.desktop` entry that plays the instance. +pub fn desktop_entry(exe: &Path, id: &str, name: &str) -> String { + let field = |s: &str| s.replace(['\n', '\r'], " "); + format!( + "[Desktop Entry]\n\ + Type=Application\n\ + Name={name}\n\ + Comment=Play {name} in Horizon\n\ + Exec={} play --instance {}\n\ + TryExec={}\n\ + Icon=horizon\n\ + Terminal=false\n\ + Categories=Game;\n\ + StartupWMClass=horizon\n\ + {INSTANCE_KEY}={id}\n", + desktop::quote(exe), + desktop::quote(Path::new(id)), + exe.display(), + name = field(name), + id = field(id), + ) +} + +/// `'text'` for a POSIX shell. +fn sh_quote(text: &str) -> String { + format!("'{}'", text.replace('\'', r"'\''")) +} + +fn xml(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// A macOS app's files, by path inside the `.app`, and whether each is a program. +pub fn mac_app(exe: &Path, id: &str, name: &str) -> Vec<(&'static str, Vec, bool)> { + let plist = format!( + r#" + + + + CFBundleExecutable + play + CFBundleIdentifier + dev.horizon.instance.{} + CFBundleName + {} + CFBundleIconFile + horizon + CFBundlePackageType + APPL + LSUIElement + + {MAC_KEY} + {} + + +"#, + slug(id), + xml(name), + xml(id), + ); + let script = format!( + "#!/bin/sh\n# Plays the Horizon instance {}.\nexec {} play --instance {}\n", + name.replace('\n', " "), + sh_quote(&exe.to_string_lossy()), + sh_quote(id), + ); + vec![ + ("Contents/Info.plist", plist.into_bytes(), false), + ("Contents/MacOS/play", script.into_bytes(), true), + ("Contents/Resources/horizon.icns", MAC_ICON.to_vec(), false), + ] +} + +/// The arguments of a Windows shortcut: the id in quotes, with its own quotes escaped. +fn windows_args(id: &str) -> String { + format!("play --instance \"{}\"", id.replace('"', "\\\"")) +} + +fn utf16(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +/// A Windows Shell Link ([MS-SHLLINK]) to `exe` (a Windows path) with `args`: the header, a +/// LinkInfo with the local path (ANSI and Unicode), then the name, working folder, arguments and +/// icon as Unicode strings. +pub fn lnk(exe: &str, args: &str, comment: &str) -> Vec { + const HAS_LINK_INFO: u32 = 0x02; + const HAS_NAME: u32 = 0x04; + const HAS_WORKING_DIR: u32 = 0x10; + const HAS_ARGUMENTS: u32 = 0x20; + const HAS_ICON_LOCATION: u32 = 0x40; + const IS_UNICODE: u32 = 0x80; + const FILE_ATTRIBUTE_NORMAL: u32 = 0x80; + const SW_SHOWNORMAL: u32 = 1; + let flags = + HAS_LINK_INFO | HAS_NAME | HAS_WORKING_DIR | HAS_ARGUMENTS | HAS_ICON_LOCATION | IS_UNICODE; + let mut out = Vec::new(); + out.extend(0x4Cu32.to_le_bytes()); + // CLSID 00021401-0000-0000-C000-000000000046. + out.extend([ + 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x46, + ]); + out.extend(flags.to_le_bytes()); + out.extend(FILE_ATTRIBUTE_NORMAL.to_le_bytes()); + out.extend([0; 24]); // creation, access and write times: unknown + out.extend(0u32.to_le_bytes()); // file size + out.extend(0i32.to_le_bytes()); // icon index + out.extend(SW_SHOWNORMAL.to_le_bytes()); + out.extend([0; 2 + 2 + 4 + 4]); // hot key, reserved + + // LinkInfo: a header with the Unicode offsets (0x24 bytes), a VolumeID for a fixed drive + // with no label, the path in ANSI (anything else as '?') and in UTF-16, and empty suffixes. + let header = 0x24u32; + let volume: Vec = [0x11u32, 3, 0, 0x10] + .iter() + .flat_map(|v| v.to_le_bytes()) + .chain([0]) + .collect(); + let ansi: Vec = exe + .chars() + .map(|c| if c.is_ascii() { c as u8 } else { b'?' }) + .chain([0]) + .collect(); + let wide: Vec = utf16(exe).into_iter().chain([0, 0]).collect(); + let volume_at = header; + let path_at = volume_at + volume.len() as u32; + let suffix_at = path_at + ansi.len() as u32; + let wide_at = suffix_at + 1; + let wide_suffix_at = wide_at + wide.len() as u32; + let size = wide_suffix_at + 2; + for v in [ + size, + header, + 1, // VolumeIDAndLocalBasePath + volume_at, + path_at, + 0, // no network path + suffix_at, + wide_at, + wide_suffix_at, + ] { + out.extend(v.to_le_bytes()); + } + out.extend(volume); + out.extend(ansi); + out.push(0); + out.extend(wide); + out.extend([0, 0]); + + let folder = exe.rsplit_once('\\').map_or("", |(dir, _)| dir); + for text in [comment, folder, args, exe] { + out.extend((text.encode_utf16().count() as u16).to_le_bytes()); + out.extend(utf16(text)); + } + out.extend(0u32.to_le_bytes()); // no extra data + out +} + +/// Whether the shortcut at `path` plays the instance `id`. +fn plays(path: &Path, id: &str) -> bool { + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or(""); + match ext { + "desktop" => fs::read_to_string(path) + .is_ok_and(|t| t.lines().any(|l| l == format!("{INSTANCE_KEY}={id}"))), + "app" => fs::read_to_string(path.join("Contents/Info.plist")) + .is_ok_and(|t| t.contains(&format!("{MAC_KEY}\n\t{}", xml(id)))), + "lnk" => fs::read(path).is_ok_and(|b| { + let want = utf16(&windows_args(id)); + b.windows(want.len()).any(|w| w == want) + }), + _ => false, + } +} + +/// Writes `bytes` beside `path` and renames it in, so nothing reads half a file. +fn write(path: &Path, bytes: &[u8], program: bool) -> Result<(), String> { + let fail = |e: std::io::Error| format!("{}: {e}", path.display()); + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(fail)?; + } + let temp = path.with_extension("horizon-tmp"); + fs::write(&temp, bytes).map_err(fail)?; + #[cfg(unix)] + if program { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&temp, fs::Permissions::from_mode(0o755)).map_err(fail)?; + } + #[cfg(not(unix))] + let _ = program; + fs::rename(&temp, path).map_err(fail) +} + +/// Moves a file or folder out of the way, where the player can get it back. +pub type Trash<'a> = &'a dyn Fn(&Path) -> Result<(), String>; + +/// Makes the shortcut for `system` in `desktop` (and, for Linux, the menu entry under +/// `menu`, an `applications` folder). The instance's shortcut of the same name is rewritten; +/// one under an older name goes to `trash`. Returns what it wrote. +pub fn make_in( + system: System, + desktop: &Path, + menu: Option<&Path>, + exe: &Path, + id: &str, + name: &str, + trash: Trash, +) -> Result, String> { + let path = desktop.join(file_name(name, system)); + let item = menu.map(|m| m.join(format!("horizon-instance-{}.desktop", slug(id)))); + for old in find_in(desktop, menu, id) { + if old != path && Some(&old) != item.as_ref() { + trash(&old)?; + } + } + if path.exists() && !plays(&path, id) { + return Err(format!( + "{} is already on the desktop, and isn't this instance's shortcut.", + path.file_name().unwrap().to_string_lossy() + )); + } + let mut made = vec![path.clone()]; + match system { + System::Linux => { + let entry = desktop_entry(exe, id, name); + write(&path, entry.as_bytes(), true)?; + if let Some(item) = item { + write(&item, entry.as_bytes(), false)?; + made.push(item); + } + } + System::Mac => { + for (inside, bytes, program) in mac_app(exe, id, name) { + write(&path.join(inside), &bytes, program)?; + } + } + System::Windows => write( + &path, + &lnk( + &exe.to_string_lossy(), + &windows_args(id), + &format!("Play {name} in Horizon"), + ), + false, + )?, + } + Ok(made) +} + +/// The instance's shortcuts in `desktop` and the menu. +pub fn find_in(desktop: &Path, menu: Option<&Path>, id: &str) -> Vec { + let mut found: Vec = fs::read_dir(desktop) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| plays(p, id)) + .collect(); + if let Some(item) = menu + .map(|m| m.join(format!("horizon-instance-{}.desktop", slug(id)))) + .filter(|p| plays(p, id)) + { + found.push(item); + } + found.sort(); + found +} + +/// Moves the instance's shortcuts to `trash`. Returns what it moved. +pub fn remove_in( + desktop: &Path, + menu: Option<&Path>, + id: &str, + trash: Trash, +) -> Result, String> { + let found = find_in(desktop, menu, id); + for path in &found { + trash(path)?; + } + Ok(found) +} + +fn menu() -> Option { + (System::here() == System::Linux) + .then(desktop::data_home) + .flatten() + .map(|d| d.join("applications")) +} + +fn desktop_or_err() -> Result { + desktop_dir().ok_or_else(|| "This computer has no desktop folder.".into()) +} + +/// Makes the shortcut on this computer's desktop that plays `id`, starting `exe`. +pub fn make(exe: &Path, id: &str, name: &str) -> Result, String> { + let desktop = desktop_or_err()?; + let made = make_in( + System::here(), + &desktop, + menu().as_deref(), + &desktop::target(exe), + id, + name, + &desktop_seams::to_trash, + )?; + if System::here() == System::Linux { + // GNOME starts a desktop file only once it is trusted; elsewhere this does nothing. + let _ = std::process::Command::new("gio") + .args(["set", "-t", "string"]) + .arg(&made[0]) + .args(["metadata::trusted", "true"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); + } + Ok(made) +} + +/// The instance's shortcuts on this computer. +pub fn find(id: &str) -> Vec { + desktop_dir() + .map(|d| find_in(&d, menu().as_deref(), id)) + .unwrap_or_default() +} + +/// Moves the instance's shortcuts on this computer to the trash. +pub fn remove(id: &str) -> Result, String> { + remove_in( + &desktop_or_err()?, + menu().as_deref(), + id, + &desktop_seams::to_trash, + ) +} + +#[cfg(test)] +#[path = "shortcut/tests.rs"] +mod tests; diff --git a/launcher/src/shortcut/tests.rs b/launcher/src/shortcut/tests.rs new file mode 100644 index 000000000..ce49d5b20 --- /dev/null +++ b/launcher/src/shortcut/tests.rs @@ -0,0 +1,197 @@ +use super::*; + +fn scratch(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-shortcut-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root +} + +#[test] +fn names_fit_every_system() { + assert_eq!( + file_name("Hardcore", System::Linux), + "Hardcore (Horizon).desktop" + ); + assert_eq!( + file_name("A/B: C?", System::Windows), + "A-B- C- (Horizon).lnk" + ); + assert_eq!(file_name(" .. ", System::Mac), "Instance (Horizon).app"); + assert_eq!(slug("port:all the mods"), "port-all-the-mods"); +} + +#[test] +fn a_linux_entry_plays_its_instance() { + let entry = desktop_entry( + Path::new("/opt/My Horizon/horizon-launcher"), + "port:atm", + "ATM", + ); + assert!(entry.starts_with("[Desktop Entry]\nType=Application\nName=ATM\n")); + assert!(entry + .contains("\nExec=\"/opt/My Horizon/horizon-launcher\" play --instance \"port:atm\"\n")); + assert!(entry.contains("\nTryExec=/opt/My Horizon/horizon-launcher\n")); + assert!(entry.ends_with("\nX-Horizon-Instance=port:atm\n")); + let odd = desktop_entry(Path::new("/x"), "a", "Two\nlines"); + assert!(odd.contains("Name=Two lines\n")); +} + +#[test] +fn a_mac_app_runs_a_script_that_plays_its_instance() { + let files = mac_app( + Path::new("/Applications/Horizon Launcher.app/Contents/MacOS/horizon-launcher"), + "it's", + "Tom & Jerry", + ); + let (_, plist, _) = &files[0]; + let plist = String::from_utf8(plist.clone()).unwrap(); + assert!(plist.contains("Tom & Jerry")); + assert!(plist.contains("dev.horizon.instance.it-s")); + assert!(plist.contains("LSUIElement\n\t")); + let (path, script, program) = &files[1]; + assert_eq!((*path, *program), ("Contents/MacOS/play", true)); + assert!(String::from_utf8(script.clone()).unwrap().ends_with( + "exec '/Applications/Horizon Launcher.app/Contents/MacOS/horizon-launcher' play \ + --instance 'it'\\''s'\n" + )); + assert_eq!(files[2].1, MAC_ICON); +} + +/// Reads a Shell Link back by its spec: the header, the LinkInfo's paths, and the strings. +fn read_lnk(b: &[u8]) -> (u32, String, String, Vec) { + let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + assert_eq!(u32_at(0), 0x4C); + assert_eq!( + &b[4..20], + &[1, 0x14, 2, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46] + ); + let flags = u32_at(20); + assert_eq!(u32_at(60), 1, "show normal"); + let info = 76; + let size = u32_at(info) as usize; + assert_eq!(u32_at(info + 4), 0x24); + assert_eq!(u32_at(info + 8), 1); + let volume = info + u32_at(info + 12) as usize; + assert_eq!((u32_at(volume), u32_at(volume + 4)), (0x11, 3)); + let cstr = |at: usize| { + let end = b[at..].iter().position(|&c| c == 0).unwrap(); + String::from_utf8(b[at..at + end].to_vec()).unwrap() + }; + let ansi = cstr(info + u32_at(info + 16) as usize); + assert_eq!(cstr(info + u32_at(info + 24) as usize), ""); + let wide_at = info + u32_at(info + 28) as usize; + let wide: Vec = b[wide_at..] + .chunks(2) + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .take_while(|&c| c != 0) + .collect(); + let wide = String::from_utf16(&wide).unwrap(); + assert_eq!( + ansi.replace('?', ""), + wide.replace(|c: char| !c.is_ascii(), "") + ); + let mut at = info + size; + let mut strings = Vec::new(); + for _ in 0..4 { + let n = u16::from_le_bytes([b[at], b[at + 1]]) as usize; + let units: Vec = b[at + 2..at + 2 + 2 * n] + .chunks(2) + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .collect(); + strings.push(String::from_utf16(&units).unwrap()); + at += 2 + 2 * n; + } + assert_eq!(&b[at..], &[0, 0, 0, 0], "the terminal block ends it"); + (flags, ansi, wide, strings) +} + +#[test] +fn a_windows_shortcut_is_a_shell_link_to_the_launcher() { + let exe = r"C:\Users\Zoé\AppData\Local\Horizon\horizon-launcher.exe"; + let b = lnk(exe, &windows_args("port:atm"), "Play ATM in Horizon"); + let (flags, ansi, wide, strings) = read_lnk(&b); + assert_eq!(flags, 0x02 | 0x04 | 0x10 | 0x20 | 0x40 | 0x80); + assert_eq!( + ansi, + r"C:\Users\Zo?\AppData\Local\Horizon\horizon-launcher.exe" + ); + assert_eq!(wide, exe); + assert_eq!( + strings, + [ + "Play ATM in Horizon", + r"C:\Users\Zoé\AppData\Local\Horizon", + "play --instance \"port:atm\"", + exe, + ] + ); +} + +#[test] +fn shortcuts_are_made_found_renamed_and_removed() { + let root = scratch("make"); + let (desktop, menu, trash) = ( + root.join("Desktop"), + root.join("applications"), + root.join("trash"), + ); + let bin = trash.clone(); + let trash_fn = move |p: &Path| desktop_seams::to_folder(p, &bin); + let t: Trash = &trash_fn; + let exe = Path::new("/opt/horizon-launcher"); + for system in [System::Linux, System::Mac, System::Windows] { + let made = make_in( + system, + &desktop, + Some(&menu), + exe, + "hardcore", + "Hardcore", + t, + ) + .unwrap(); + assert_eq!(made[0], desktop.join(file_name("Hardcore", system))); + assert_eq!(find_in(&desktop, Some(&menu), "hardcore"), { + let mut m = made.clone(); + m.sort(); + m + }); + // Again: rewritten in place, nothing in the trash. + make_in( + system, + &desktop, + Some(&menu), + exe, + "hardcore", + "Hardcore", + t, + ) + .unwrap(); + assert!(!trash.exists()); + // Renamed: the old one goes, the new one is there. + let made = make_in(system, &desktop, Some(&menu), exe, "hardcore", "Hard", t).unwrap(); + assert!(made[0].ends_with(file_name("Hard", system))); + assert!(!desktop.join(file_name("Hardcore", system)).exists()); + assert!(find_in(&desktop, Some(&menu), "skyblock").is_empty()); + let gone = remove_in(&desktop, Some(&menu), "hardcore", t).unwrap(); + assert_eq!(gone.len(), made.len()); + assert!(find_in(&desktop, Some(&menu), "hardcore").is_empty()); + fs::remove_dir_all(&trash).unwrap(); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let made = make_in(System::Mac, &desktop, None, exe, "a", "A", t).unwrap(); + let mode = fs::metadata(made[0].join("Contents/MacOS/play")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o111, 0o111); + } + // Someone else's file of that name stays. + fs::write(desktop.join("Mine (Horizon).desktop"), "not ours").unwrap(); + let err = make_in(System::Linux, &desktop, None, exe, "mine", "Mine", t).unwrap_err(); + assert!(err.contains("isn't this instance's shortcut"), "{err}"); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/launcher/src/shortcut_page.rs b/launcher/src/shortcut_page.rs new file mode 100644 index 000000000..68eb9ca2d --- /dev/null +++ b/launcher/src/shortcut_page.rs @@ -0,0 +1,69 @@ +//! The Instance row's desktop shortcut (`horizon_launcher::shortcut`): make one that plays the +//! selected instance, or take it away. +use super::*; +use horizon_launcher::shortcut; + +#[derive(Default)] +pub(super) struct Shortcuts { + /// The instance last looked at, and whether it has a shortcut: read again only when the + /// selection changes or a button is pressed, not on every frame. + seen: Option<(String, bool)>, + /// What the last press did, for that instance. + note: Option<(String, Result)>, +} + +impl Launcher { + fn has_shortcut(&mut self, id: &str) -> bool { + match &self.shortcuts.seen { + Some((seen, has)) if seen == id => *has, + _ => { + let has = !shortcut::find(id).is_empty(); + self.shortcuts.seen = Some((id.to_string(), has)); + has + } + } + } + + fn toggle_shortcut(&mut self, id: String, name: String) { + let has = self.has_shortcut(&id); + let done = match has { + false => shortcut::make(backend::exe_path(), &id, &name).map(|made| { + let file = made[0].file_name().unwrap_or_default().to_string_lossy(); + format!("{file} is on your desktop: it plays {name}.") + }), + true => shortcut::remove(&id).map(|_| format!("{name}'s shortcut is in the trash.")), + }; + self.shortcuts.seen = None; + self.shortcuts.note = Some((id, done)); + } + + /// The row's button. + pub(super) fn shortcut_button( + &mut self, + instance: &instances::Instance, + cx: &mut Context, + ) -> Stateful
{ + let t = self.theme; + let label = match self.has_shortcut(&instance.id) { + true => "Remove shortcut", + false => "Shortcut", + }; + let (id, name) = (instance.id.clone(), instance.name.clone()); + button("instance-shortcut", label, Kind::Ghost, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.toggle_shortcut(id.clone(), name.clone()); + cx.notify(); + }, + )) + } + + /// What the last press did, under the row, while that instance is selected. + pub(super) fn shortcut_note(&self, id: &str) -> Option
{ + let t = self.theme; + let (_, said) = self.shortcuts.note.as_ref().filter(|(n, _)| n == id)?; + Some(match said { + Ok(said) => text(theme::CAPTION).text_color(t.muted).child(said.clone()), + Err(e) => text(theme::CAPTION).text_color(t.danger).child(e.clone()), + }) + } +} From 7115c708e110e7077f8c4ca037295ad52e3db267 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:22:34 +0100 Subject: [PATCH 4/4] launcher: pre-launch command, wrapper and environment per instance Home's Instance row gets Launch...: a shell command run in the instance's folder before the game (which starts only if it succeeds), a wrapper the game runs through, and environment variables, kept in instances.json. The game stays one process: /bin/sh runs the command and execs the wrapper and game through "$@" on Unix, cmd /C on Windows. The window's Play and `play` both use them. CLI and MCP: instance launch (confirm needed over MCP). The Instance row's actions move under its name, and editing an instance that shares its name with an import works again. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 13 ++ launcher/README.md | 8 ++ launcher/src/cli.rs | 53 +++++++- launcher/src/cli_tools.rs | 2 + launcher/src/import/tests.rs | 1 + launcher/src/instances.rs | 17 ++- launcher/src/instances/tests.rs | 12 ++ launcher/src/instances_page.rs | 23 +++- launcher/src/launch.rs | 220 ++++++++++++++++++++++++++++++++ launcher/src/launch/tests.rs | 143 +++++++++++++++++++++ launcher/src/launch_page.rs | 137 ++++++++++++++++++++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 12 ++ launcher/src/servers_page.rs | 10 +- 14 files changed, 646 insertions(+), 6 deletions(-) create mode 100644 launcher/src/launch.rs create mode 100644 launcher/src/launch/tests.rs create mode 100644 launcher/src/launch_page.rs 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