Merge feat/modbrowser-project-page (now with main) into feat/modbrowser-modpacks-port

No conflicts: carries the stack's merge of origin/main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-23 01:08:33 +02:00
179 changed files with 9170 additions and 5894 deletions
+100 -101
View File
@@ -995,6 +995,78 @@ fn download_for_owner(
}
}
/// A JDK of at least `major` for the preparation. `None` when horizon-prepare finds one by
/// itself (JAVA_HOME, the PATH, an installed JDK): the preparation then runs as before, in an
/// unchanged environment (a JDK found on the PATH can be a stub such as macOS's
/// /usr/bin/javac, whose folder is no Java home: `JAVA_HOME=/usr` makes it call itself
/// forever). Else the home of the Java the official launcher downloaded into one of the
/// `games` folders, else of Minecraft's own Java downloaded from Mojang into Horizon's game
/// folder, the runtime the version JSON at `manifest` names (Mojang's runtimes are whole JDKs).
fn java(
major: i64,
games: &[PathBuf],
manifest: &Path,
log: &dyn Fn(String),
) -> Result<Option<PathBuf>, String> {
if horizon_prepare::java::find(major, &[]).is_ok() {
return Ok(None);
}
let mut runtimes: Vec<PathBuf> = Vec::new();
for home in games
.iter()
.flat_map(|game| horizon_prepare::java::minecraft_runtimes(&game.join("runtime")))
{
if !runtimes.contains(&home) {
runtimes.push(home);
}
}
let missing = match horizon_prepare::java::find(major, &runtimes) {
Ok(jdk) => return Ok(Some(jdk.home())),
Err(e) => e,
};
let component = read_json(manifest)
.and_then(|json| json["javaVersion"]["component"].as_str().map(String::from))
.ok_or_else(|| missing.clone())?;
// Mojang builds its Linux Java for glibc: without glibc's loader (NixOS without nix-ld,
// musl distributions) it cannot start, so don't download it.
if cfg!(all(target_os = "linux", target_arch = "x86_64")) && !Path::new(GLIBC_LOADER).exists() {
return Err(format!(
"{missing}\n • Minecraft's own Java from Mojang needs glibc ({GLIBC_LOADER} is missing; on NixOS, enable programs.nix-ld), so install a JDK instead."
));
}
let fetch = |url: &str| -> Result<Vec<u8>, String> {
let mut body = Vec::new();
get(url)?
.into_reader()
.read_to_end(&mut body)
.map_err(|e| e.to_string())?;
Ok(body)
};
let runtime = data_dir().join("minecraft").join("runtime");
let home = mojang::java_runtime(&component, &runtime, 8, &fetch, log).map_err(|e| {
format!("{missing}\n • Horizon also tried to download Minecraft's own Java from Mojang, but: {e}")
})?;
horizon_prepare::java::find(major, &[home]).map(|jdk| Some(jdk.home()))
}
/// The dynamic loader glibc programs on x86-64 Linux start through.
const GLIBC_LOADER: &str = "/lib64/ld-linux-x86-64.so.2";
/// Runs `cmd` with the JDK at `home`: JAVA_HOME names it and its `bin` leads the PATH, as the
/// versions' own preparers look for Java.
fn with_java(cmd: &mut Command, home: &Path) {
let mut path = vec![home.join("bin")];
path.extend(
std::env::var_os("PATH")
.iter()
.flat_map(std::env::split_paths),
);
cmd.env("JAVA_HOME", home);
if let Ok(path) = std::env::join_paths(path) {
cmd.env("PATH", path);
}
}
/// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same
/// steps: the player's own launcher install, the server jar from that version's own json, and
/// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder
@@ -1008,6 +1080,7 @@ pub fn preparer(
let version = game_version(tag);
let dir = version_dir(tag);
let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?;
let chosen = minecraft.to_path_buf();
let minecraft = if reused {
minecraft.to_path_buf()
} else {
@@ -1044,25 +1117,27 @@ pub fn preparer(
.join(&version)
.join(format!("{version}.json"));
let binary = preparer_binary(&dir);
let python = if binary.is_some() {
// The JDK the version pins, found as horizon-prepare finds it, so a missing one is
// reported before the server jar is downloaded.
let major = read_json(&dir.join("research-lock.json"))
.and_then(|lock| lock["minecraft"]["java_major"].as_i64())
.ok_or("The version's research-lock.json has no java_major")?;
horizon_prepare::java::find(major)?;
None
} else {
let python = python()
.ok_or("This version prepares with Python: Python 3.10 or newer is needed. Install it, or pick a newer version.")?;
if !found("java", "-version") {
return Err(
"Java 25 is needed (a JDK, e.g. Eclipse Temurin 25). Install it and try again."
.into(),
);
}
Some(python)
let python = match binary {
Some(_) => None,
None => Some(python().ok_or(
"This version prepares with Python: Python 3.10 or newer is needed. Install it, or pick a newer version.",
)?),
};
// The JDK the version pins, found as horizon-prepare finds it, so a missing one is
// reported (or downloaded) before the server jar is downloaded. Versions from before
// java_major ran Java 25.
let major = read_json(&dir.join("research-lock.json"))
.and_then(|lock| lock["minecraft"]["java_major"].as_i64())
.unwrap_or(25);
let mut games = vec![chosen, minecraft.clone(), data_dir().join("minecraft")];
games.extend(
sources::Folders::current()
.map(|f| sources::known_folders(sources::Os::current(), &f))
.unwrap_or_default()
.into_iter()
.map(|(_, dir)| dir),
);
let java_home = java(major, &games, &manifest, log)?;
let jar = data_dir()
.join("server-jars")
.join(format!("{version}.jar"));
@@ -1094,10 +1169,14 @@ pub fn preparer(
import: !reused,
minecraft_dir: Some(minecraft.clone()),
server_jar: (!reused).then_some(jar),
java_home: java_home.clone(),
};
return Ok((Preparer::InProcess(options), minecraft));
}
let mut cmd = Command::new(binary);
if let Some(home) = &java_home {
with_java(&mut cmd, home);
}
cmd.current_dir(&dir).arg("--root").arg(&dir);
if !reused {
cmd.args(["--prepare", "--server-jar"]).arg(&jar);
@@ -1106,6 +1185,9 @@ pub fn preparer(
return Ok((Preparer::Process(cmd), minecraft));
}
let mut cmd = Command::new(python.unwrap());
if let Some(home) = &java_home {
with_java(&mut cmd, home);
}
cmd.current_dir(&dir)
.args(["-u", "tools/prepare_native_client.py"]);
if !reused {
@@ -1328,65 +1410,6 @@ pub fn read_logs(lines: usize, crash: bool) -> Result<(PathBuf, String), String>
Ok((path, text))
}
/// Which drawing the game's menus use. Classic is vanilla's own screens, which have no way to
/// switch back, so the launcher is where the player returns to Horizon's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MenuStyle {
Horizon,
Classic,
}
impl MenuStyle {
pub fn name(self) -> &'static str {
match self {
MenuStyle::Horizon => "horizon",
MenuStyle::Classic => "classic",
}
}
pub fn parse(name: &str) -> Option<Self> {
match name {
"horizon" => Some(MenuStyle::Horizon),
"classic" => Some(MenuStyle::Classic),
_ => None,
}
}
/// The style `horizon.txt` holds: Horizon unless it has the line `menuStyle:classic`, as the
/// game reads it (crates/horizon-client/src/ui_theme.rs).
fn from_file(text: &str) -> Self {
if text.lines().any(|l| l.trim() == "menuStyle:classic") {
MenuStyle::Classic
} else {
MenuStyle::Horizon
}
}
/// `text` with its `menuStyle:` line set to this style and every other line kept.
fn into_file(self, text: &str) -> String {
let mut out: Vec<String> = text
.lines()
.filter(|l| !l.trim().starts_with("menuStyle:"))
.map(String::from)
.collect();
out.insert(0, format!("menuStyle:{}", self.name()));
out.join("\n") + "\n"
}
}
/// The menu style saved in the game home's `horizon.txt` (Horizon when there is none).
pub fn menu_style() -> MenuStyle {
MenuStyle::from_file(&fs::read_to_string(game_home().join("horizon.txt")).unwrap_or_default())
}
pub fn set_menu_style(style: MenuStyle) -> Result<(), String> {
let home = game_home();
fs::create_dir_all(&home).map_err(|e| e.to_string())?;
let file = home.join("horizon.txt");
let text = style.into_file(&fs::read_to_string(&file).unwrap_or_default());
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).
@@ -2837,30 +2860,6 @@ mod tests {
assert_eq!(Links::parse(r#"{"mastodon": "https://x.y/z"}"#), defaults);
}
#[test]
fn menu_style_file_matches_the_games() {
assert_eq!(MenuStyle::from_file(""), MenuStyle::Horizon);
assert_eq!(
MenuStyle::from_file("menuStyle:horizon\n"),
MenuStyle::Horizon
);
assert_eq!(
MenuStyle::from_file("menuStyle:classic\n"),
MenuStyle::Classic
);
assert_eq!(
MenuStyle::from_file("other:1\nmenuStyle:classic\n"),
MenuStyle::Classic
);
assert_eq!(MenuStyle::Classic.into_file(""), "menuStyle:classic\n");
assert_eq!(
MenuStyle::Horizon.into_file("menuStyle:classic\nother:1\n"),
"menuStyle:horizon\nother:1\n"
);
assert_eq!(MenuStyle::parse("classic"), Some(MenuStyle::Classic));
assert_eq!(MenuStyle::parse("vanilla"), None);
}
#[test]
fn a_new_version_reuses_resources_prepared_by_a_compatible_one() {
let versions =
-17
View File
@@ -281,12 +281,6 @@ enum Cmd {
#[command(subcommand)]
action: Option<AccountCmd>,
},
/// Show or set the game's menu style (classic is vanilla's own screens)
MenuStyle {
/// Omit to show the current style
#[arg(value_parser = ["horizon", "classic"])]
style: Option<String>,
},
/// Show or set which Horizon releases install by themselves: stable (a tested build about once
/// a day) or alpha (every release as soon as it is built; can break)
UpdateChannel {
@@ -559,17 +553,6 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
}
}
}
Cmd::MenuStyle { style } => {
if let Some(style) = style.as_deref().and_then(backend::MenuStyle::parse) {
backend::set_menu_style(style)?;
}
let style = backend::menu_style().name();
if as_json {
json(serde_json::json!({ "menu_style": style }));
} else {
println!("Menu style: {style}");
}
}
Cmd::UpdateChannel { channel } => {
let mut settings = backend::Settings::load();
if let Some(channel) = channel.as_deref().and_then(backend::UpdateChannel::parse) {
+7 -36
View File
@@ -123,7 +123,6 @@ struct Launcher {
settings: Settings,
/// The Discord, sponsor and website links: built in until links.json on main has been read.
links: backend::Links,
menu_style: backend::MenuStyle,
preparing: bool,
prepare_log: VecDeque<String>,
prepare_error: Option<String>,
@@ -256,7 +255,6 @@ impl Launcher {
args_focus: cx.focus_handle(),
settings,
links: backend::Links::default(),
menu_style: backend::menu_style(),
preparing: false,
prepare_log: VecDeque::new(),
prepare_error: None,
@@ -1869,24 +1867,6 @@ impl Launcher {
cx.notify();
}),
);
let this = cx.entity().downgrade();
let menus = segments(
"menu-style",
&[
(backend::MenuStyle::Horizon, "Horizon"),
(backend::MenuStyle::Classic, "Classic"),
],
self.menu_style,
&t,
move |style, _, cx| {
let _ = this.update(cx, |this, cx| {
if backend::set_menu_style(style).is_ok() {
this.menu_style = style;
}
cx.notify();
});
},
);
let horizon = match (&self.updates.horizon, &self.update_error) {
(Some(r), _) => format!("{} available", r.tag),
(None, Some(e)) => e.clone(),
@@ -1982,7 +1962,7 @@ impl Launcher {
.gap(px(32.))
.child(page_header(
"Settings",
"Accounts, updates, menus, and the launcher itself.",
"Accounts, updates, and the launcher itself.",
&t,
))
.child(
@@ -2024,33 +2004,24 @@ impl Launcher {
Some(opening.into_any_element()),
&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 + 4,
"Game menus",
Some(plain(
"Classic is vanilla's own screens, with no way back inside the game: switch back here. Applies the next time the game starts.",
)),
Some(menus.into_any_element()),
&t,
))
.child(self.game_args_row(n + 5, cx))
.child(index_row(n + 6, "Horizon", Some(plain(&horizon)), horizon_action, &t))
.child(index_row(
n + 7,
n + 6,
"Launcher",
Some(plain(&launcher)),
launcher_action,
&t,
))
.child(index_row(
n + 8,
n + 7,
"Data folder",
Some(mono(short(&backend::data_dir()))),
None,
&t,
))
.child(index_row(
n + 9,
n + 8,
"Logs",
Some(mono(format!(
"{} · crash reports beside it",
@@ -2069,7 +2040,7 @@ impl Launcher {
))
.when(cfg!(target_os = "linux"), |d| {
d.child(index_row(
n + 10,
n + 9,
"Applications menu",
Some(plain(if self.settings.desktop_entry() {
"Horizon and its icon are in your desktop's menu."
-10
View File
@@ -49,8 +49,6 @@ fn tools() -> Value {
{ "name": "patch_notes", "description": "A release's patch notes as markdown.",
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "Default: the newest release." } } } },
{ "name": "links", "description": "The Horizon links: the Discord invite, the GitHub Sponsors page and the website (an empty one is not offered).", "inputSchema": none },
{ "name": "menu_style", "description": "Show or set the game's menu style. \"horizon\" is Horizon's own menus, \"classic\" is vanilla's screens, which have no way back inside the game. The game reads it when it starts.",
"inputSchema": { "type": "object", "properties": { "style": { "type": "string", "enum": ["horizon", "classic"], "description": "Omit to show the current style." } } } },
{ "name": "update_channel", "description": "Show or set which Horizon releases install by themselves. \"stable\" (the default) is a tested build about once a day; \"alpha\" is every release as soon as it is built, several times a day, and can break. Only when the player asks to change it.",
"inputSchema": { "type": "object", "properties": { "channel": { "type": "string", "enum": ["stable", "alpha"], "description": "Omit to show the current channel." } } } },
{ "name": "logs", "description": "Read the game's log: the last lines of logs/latest.log in the game folder, or with crash the newest crash report (what the game wrote when it last crashed). Read-only.",
@@ -279,14 +277,6 @@ impl Session {
let (path, text) = backend::read_logs(lines.clamp(1, 5000) as usize, crash)?;
Ok(format!("{}\n\n{text}", path.display()))
}
"menu_style" => {
if let Some(name) = arg_str(args, "style") {
let style = backend::MenuStyle::parse(name)
.ok_or("style is \"horizon\" or \"classic\"")?;
backend::set_menu_style(style)?;
}
Ok(format!("Menu style: {}", backend::menu_style().name()))
}
"update_channel" => {
let mut settings = backend::Settings::load();
if let Some(name) = arg_str(args, "channel") {
+116
View File
@@ -13,6 +13,8 @@ use std::sync::Mutex;
use std::time::Duration;
const OBJECTS: &str = "https://resources.download.minecraft.net";
/// The index of Mojang's Java runtimes, the one the official launcher reads.
const JAVA_RUNTIMES: &str = "https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json";
/// One file to download.
struct File {
@@ -84,6 +86,120 @@ pub fn download(
Ok(())
}
/// Mojang's name for this system in its Java runtime index.
fn java_platform() -> Option<&'static str> {
Some(match (std::env::consts::OS, std::env::consts::ARCH) {
("macos", "aarch64") => "mac-os-arm64",
("macos", "x86_64") => "mac-os",
("linux", "x86_64") => "linux",
("linux", "x86") => "linux-i386",
("windows", "x86_64") => "windows-x64",
("windows", "aarch64") => "windows-arm64",
("windows", "x86") => "windows-x86",
_ => return None,
})
}
/// Downloads Mojang's Java runtime `component` (the version JSON's `javaVersion.component`, e.g.
/// `java-runtime-epsilon`) into the game directory's `runtime` folder, as the official launcher
/// lays it out: `<component>/<platform>/<component>/`. Each file is checked against its sha1;
/// files already there and whole are kept. Mojang's runtimes are whole JDKs, javac included,
/// which is what the exporters need.
pub fn java_runtime(
component: &str,
runtime: &Path,
jobs: usize,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<PathBuf, String> {
let platform = java_platform().ok_or("Mojang has no Java for this system")?;
let index: Value = serde_json::from_slice(&fetch(JAVA_RUNTIMES)?)
.map_err(|e| format!("Mojang's Java index: {e}"))?;
let entry = &index[platform][component][0];
if entry.is_null() {
return Err(format!("Mojang has no {component} for {platform}"));
}
let manifest = &entry["manifest"];
let manifest: Value = serde_json::from_slice(&fetch_checked(
fetch,
&text(manifest, "url")?,
&text(manifest, "sha1")?,
)?)
.map_err(|e| format!("Mojang's {component} manifest: {e}"))?;
let files = manifest["files"]
.as_object()
.ok_or_else(|| format!("Mojang's {component} manifest lists no files"))?;
let home = runtime.join(component).join(platform).join(component);
let mut downloads = Vec::new();
let mut executables = Vec::new();
let mut links = Vec::new();
for (name, file) in files {
let path = home.join(relative(name)?);
match file["type"].as_str() {
Some("file") => {
let raw = &file["downloads"]["raw"];
if file["executable"] == true {
executables.push(path.clone());
}
downloads.push(File {
url: text(raw, "url")?,
sha1: text(raw, "sha1")?,
path,
});
}
Some("link") => links.push((path, text(file, "target")?)),
_ => {}
}
}
let name = entry["version"]["name"].as_str().unwrap_or(component);
log(format!(
"Downloading Minecraft's Java {name} from Mojang ({} files)",
downloads.len()
));
fetch_all(&downloads, jobs, fetch, log)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for path in &executables {
fs::set_permissions(path, fs::Permissions::from_mode(0o755))
.map_err(|e| format!("{}: {e}", path.display()))?;
}
for (path, target) in &links {
if !link_stays_inside(name_in(&home, path), target) {
return Err(format!(
"Unsafe link {target:?} in Mojang's {component} manifest"
));
}
let _ = fs::remove_file(path);
fs::create_dir_all(path.parent().unwrap())
.and_then(|_| std::os::unix::fs::symlink(target, path))
.map_err(|e| format!("{}: {e}", path.display()))?;
}
}
#[cfg(not(unix))]
let _ = (executables, links);
Ok(home)
}
fn name_in<'a>(home: &Path, path: &'a Path) -> &'a Path {
path.strip_prefix(home).unwrap_or(path)
}
/// Whether a link at `link` (relative to the runtime's home) pointing at `target` stays in the
/// home.
fn link_stays_inside(link: &Path, target: &str) -> bool {
let mut depth = link.components().count().saturating_sub(1);
for c in Path::new(target).components() {
match c {
Component::Normal(_) => depth += 1,
Component::CurDir => {}
Component::ParentDir if depth > 0 => depth -= 1,
_ => return false,
}
}
true
}
fn read_json(path: &Path) -> Result<Value, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
+96
View File
@@ -230,3 +230,99 @@ fn version_file_paths_stay_in_the_folder() {
assert!(relative(bad).is_err(), "{bad}");
}
}
#[test]
fn links_stay_inside_the_runtime() {
let at = |p: &str| PathBuf::from(p);
assert!(link_stays_inside(
&at("legal/java.compiler/LICENSE"),
"../java.base/LICENSE"
));
assert!(link_stays_inside(&at("lib/a"), "b"));
assert!(!link_stays_inside(&at("lib/a"), "../../b"));
assert!(!link_stays_inside(&at("a"), "/etc/passwd"));
}
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[test]
fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() {
const JAVAC: &[u8] = b"#!/bin/sh\necho javac 25.0.1\n";
const LICENSE: &[u8] = b"a fake license";
let manifest = serde_json::json!({"files": {
"bin": {"type": "directory"},
"bin/javac": {"type": "file", "executable": true, "downloads": {"raw":
{"sha1": sha1_hex(JAVAC), "size": JAVAC.len(), "url": "https://piston-data.mojang.com/javac"}}},
"legal/java.base/LICENSE": {"type": "file", "executable": false, "downloads": {"raw":
{"sha1": sha1_hex(LICENSE), "size": LICENSE.len(), "url": "https://piston-data.mojang.com/license"}}},
"legal/java.compiler/LICENSE": {"type": "link", "target": "../java.base/LICENSE"},
}})
.to_string();
let index = serde_json::json!({"linux": {"java-runtime-epsilon": [{
"manifest": {"sha1": sha1_hex(manifest.as_bytes()), "url": "https://piston-meta.mojang.com/m.json"},
"version": {"name": "25.0.1"},
}]}})
.to_string();
let server = Server {
files: HashMap::from([
(JAVA_RUNTIMES.to_string(), index.into_bytes()),
(
"https://piston-meta.mojang.com/m.json".into(),
manifest.into_bytes(),
),
(
"https://piston-data.mojang.com/javac".into(),
JAVAC.to_vec(),
),
(
"https://piston-data.mojang.com/license".into(),
LICENSE.to_vec(),
),
]),
asked: Mutex::new(Vec::new()),
};
let dir = scratch("java");
let home = java_runtime(
"java-runtime-epsilon",
&dir,
2,
&|url| server.fetch(url),
&|_| {},
)
.unwrap();
assert_eq!(
home,
dir.join("java-runtime-epsilon/linux/java-runtime-epsilon")
);
use std::os::unix::fs::PermissionsExt;
let mode = fs::metadata(home.join("bin/javac"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o111, 0o111);
assert_eq!(
fs::read(home.join("legal/java.compiler/LICENSE")).unwrap(),
LICENSE
);
// horizon-prepare finds it where the official launcher would have put it.
assert_eq!(horizon_prepare::java::minecraft_runtimes(&dir), [home]);
// A second call keeps the files: only the index and manifest are asked again.
server.asked();
java_runtime(
"java-runtime-epsilon",
&dir,
2,
&|url| server.fetch(url),
&|_| {},
)
.unwrap();
assert_eq!(server.asked().len(), 2);
assert!(java_runtime(
"java-runtime-zeta",
&dir,
2,
&|url| server.fetch(url),
&|_| {}
)
.is_err());
fs::remove_dir_all(&dir).unwrap();
}