//! Everything that is not UI: GitHub, installs, resource preparation, the game's processes and //! updates. The GUI, the CLI and the MCP server all go through this module. Functions here //! block; the GUI runs them on threads and reads their messages. use crate::{account, mojang, sources}; use std::fs; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; pub const REPO: &str = "ludovic111/horizon"; pub const README_URL: &str = "https://github.com/ludovic111/horizon/blob/main/launcher/README.md"; /// The players' page on connecting an AI agent (website/docs/agents.md). pub const AGENT_DOCS_URL: &str = "https://playhorizon.dev/docs/agents"; /// This launcher's version: the release workflow sets `HORIZON_LAUNCHER_VERSION` from the /// tag it builds (no version-bump commits); other builds say Cargo.toml's. pub const VERSION: &str = version_or(option_env!("HORIZON_LAUNCHER_VERSION")); /// Launcher releases are tagged `launcher@X.Y.Z` from 0.2 on (docs/versioning.md), and Horizon's /// own `vX.Y.Z`. Before 0.2 they were `launcher-vX.Y.Z` and `vYYYY.MM.DD[.N]`: every 0.2 tag is /// newer than every one of those ([`release_order`]). pub const LAUNCHER_TAG_PREFIX: &str = "launcher@"; /// The launcher tags from before 0.2 (`launcher-v0.16.0`). pub const OLD_LAUNCHER_TAG_PREFIX: &str = "launcher-v"; const fn version_or(injected: Option<&'static str>) -> &'static str { match injected { Some(v) if !v.is_empty() => v, _ => env!("CARGO_PKG_VERSION"), } } #[derive(Clone, Debug, serde::Serialize)] pub struct Release { pub tag: String, pub name: String, pub body: String, pub date: String, pub asset: Option<(String, u64)>, /// A beta: a game release not promoted to stable yet (a GitHub pre-release, docs/release-flow.md). pub beta: bool, } #[cfg(all(target_os = "linux", target_arch = "x86_64"))] pub const ASSET: Option<&str> = Some("horizon-linux-x86_64.tar.gz"); #[cfg(all(target_os = "macos", target_arch = "aarch64"))] pub const ASSET: Option<&str> = Some("horizon-macos-arm64.zip"); #[cfg(all(target_os = "windows", target_arch = "x86_64"))] pub const ASSET: Option<&str> = Some("horizon-windows-x64.zip"); #[cfg(not(any( all(target_os = "linux", target_arch = "x86_64"), all(target_os = "macos", target_arch = "aarch64"), all(target_os = "windows", target_arch = "x86_64") )))] pub const ASSET: Option<&str> = None; #[cfg(all(target_os = "linux", target_arch = "x86_64"))] pub const LAUNCHER_ASSET: Option<&str> = Some("horizon-launcher-linux-x86_64.tar.gz"); #[cfg(all(target_os = "macos", target_arch = "aarch64"))] pub const LAUNCHER_ASSET: Option<&str> = Some("horizon-launcher-macos-arm64.zip"); #[cfg(all(target_os = "windows", target_arch = "x86_64"))] pub const LAUNCHER_ASSET: Option<&str> = Some("horizon-launcher-windows-x64.zip"); #[cfg(not(any( all(target_os = "linux", target_arch = "x86_64"), all(target_os = "macos", target_arch = "aarch64"), all(target_os = "windows", target_arch = "x86_64") )))] pub const LAUNCHER_ASSET: Option<&str> = None; const LAUNCHER_BINARY: &str = if cfg!(windows) { "horizon-launcher.exe" } else { "horizon-launcher" }; const CLIENT: &str = if cfg!(windows) { "horizon-client.exe" } else { "horizon-client" }; fn agent() -> ureq::Agent { ureq::AgentBuilder::new() .user_agent(&format!("horizon-launcher/{VERSION}")) .build() } fn get(url: &str) -> Result { let mut request = agent().get(url); // CI runners share addresses and hit GitHub's anonymous rate limit; they pass their own token. if let Some(token) = std::env::var("HORIZON_GITHUB_TOKEN") .ok() .filter(|t| !t.is_empty()) { if url.starts_with("https://api.github.com/") { request = request.set("Authorization", &format!("Bearer {token}")); } } request.call().map_err(|e| match e { ureq::Error::Status(403, _) => { "GitHub's rate limit was reached. Try again in a few minutes.".into() } ureq::Error::Status(code, _) => format!("{url} answered {code}"), ureq::Error::Transport(t) => format!("No connection: {t}"), }) } /// A Horizon game tag: `v` then a digit (`v2026.10.13`). Launcher tags never match. pub fn is_game_tag(tag: &str) -> bool { tag.strip_prefix('v') .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) } /// The launcher version in a `launcher@X.Y.Z` (or `launcher-vX.Y.Z`) tag, or None for any other tag. pub fn launcher_version(tag: &str) -> Option<&str> { tag.strip_prefix(LAUNCHER_TAG_PREFIX) .or_else(|| tag.strip_prefix(OLD_LAUNCHER_TAG_PREFIX)) .filter(|v| v.starts_with(|c: char| c.is_ascii_digit())) } /// The tag this launcher was released as. launcher.yml gives it (`HORIZON_LAUNCHER_TAG`); a release /// built before it did gave only the version, of a `launcher-v` tag; a build from source is /// Cargo.toml's version on the 0.2 line. pub fn own_tag() -> String { own_tag_of( option_env!("HORIZON_LAUNCHER_TAG"), option_env!("HORIZON_LAUNCHER_VERSION"), ) } fn own_tag_of(tag: Option<&str>, injected: Option<&str>) -> String { match ( tag.filter(|t| !t.is_empty()), injected.filter(|v| !v.is_empty()), ) { (Some(tag), _) => tag.to_string(), (None, Some(version)) => format!("{OLD_LAUNCHER_TAG_PREFIX}{version}"), (None, None) => format!("{LAUNCHER_TAG_PREFIX}{}", env!("CARGO_PKG_VERSION")), } } /// Where a tag or version stands among Horizon's releases (docs/versioning.md): the tags from /// before 0.2 (`vYYYY.MM.DD[.N]`, `launcher-vX.Y.Z`) and bare versions first, compared number by /// number with missing parts as zero and anything after a `-` ignored, as launchers always did; /// then the 0.2 tags (`vX.Y.Z`, `launcher@X.Y.Z`) in semver's order, a pre-release /// (`v0.3.0-rc.1`) before its release. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum ReleaseOrder { /// Numbers without trailing zeros, so 1.2 and 1.2.0 are equal. Before02(Vec), Semver([u64; 3], Prerelease), } /// (is a release, the pre-release's identifiers): a release follows every pre-release of its /// version; identifiers compare one by one, numbers before words, a shorter list first. pub type Prerelease = (bool, Vec); #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Identifier { Number(u64), Word(String), } /// Semver's majors stay below this; a date tag's first number is a year. const FIRST_YEAR: u64 = 1000; pub fn release_order(tag: &str) -> ReleaseOrder { let semver = tag .strip_prefix(LAUNCHER_TAG_PREFIX) .or_else(|| tag.strip_prefix('v')) .and_then(semver_order); semver.unwrap_or_else(|| { let v = tag .strip_prefix(OLD_LAUNCHER_TAG_PREFIX) .or_else(|| tag.strip_prefix(LAUNCHER_TAG_PREFIX)) .unwrap_or(tag); let v = v.strip_prefix('v').unwrap_or(v); let mut parts: Vec = v .split('-') .next() .unwrap_or("") .split('.') .map(|p| p.parse().unwrap_or(0)) .collect(); while parts.last() == Some(&0) { parts.pop(); } ReleaseOrder::Before02(parts) }) } /// `MAJOR.MINOR.PATCH[-PRE]` with a major below [`FIRST_YEAR`], or None. fn semver_order(version: &str) -> Option { let (core, pre) = match version.split_once('-') { Some((core, pre)) => (core, Some(pre)), None => (version, None), }; let numbers: Vec = core .split('.') .map(|n| n.parse().ok()) .collect::>()?; let &[major, minor, patch] = numbers.as_slice() else { return None; }; if major >= FIRST_YEAR { return None; } let pre = match pre { None => (true, Vec::new()), Some(pre) => ( false, pre.split('.') .map(|id| { (!id.is_empty()).then(|| { id.parse() .map_or_else(|_| Identifier::Word(id.to_string()), Identifier::Number) }) }) .collect::>()?, ), }; Some(ReleaseOrder::Semver([major, minor, patch], pre)) } /// Compares two tags or versions by [`release_order`]. pub fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering { release_order(a).cmp(&release_order(b)) } /// Every published release of the repository, both kinds, as GitHub's JSON. fn release_list() -> Result { let url = format!("https://api.github.com/repos/{REPO}/releases?per_page=100"); get(&url)?.into_json().map_err(|e| e.to_string()) } /// The releases in `list` whose tag passes `keep`, newest first, with the asset named `asset`. fn parse_releases( list: &serde_json::Value, asset: Option<&str>, keep: fn(&str) -> bool, ) -> Vec { let mut out = Vec::new(); for r in list.as_array().into_iter().flatten() { let tag = r["tag_name"].as_str().unwrap_or_default(); if r["draft"].as_bool().unwrap_or(false) || !keep(tag) { continue; } let found = r["assets"].as_array().into_iter().flatten().find_map(|a| { (Some(a["name"].as_str()?) == asset).then(|| { Some(( a["browser_download_url"].as_str()?.to_string(), a["size"].as_u64()?, )) })? }); out.push(Release { tag: tag.into(), name: r["name"].as_str().unwrap_or_default().into(), body: r["body"].as_str().unwrap_or_default().replace("\r\n", "\n"), date: r["published_at"] .as_str() .unwrap_or_default() .chars() .take(10) .collect(), asset: found, beta: r["prerelease"].as_bool().unwrap_or(false), }); } out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); out } fn is_launcher_tag(tag: &str) -> bool { launcher_version(tag).is_some() } /// Published Horizon releases, newest first. Drafts never reach the anonymous API, and launcher /// releases are left out. pub fn releases() -> Result, String> { Ok(parse_releases(&release_list()?, ASSET, is_game_tag)) } /// Published launcher releases (`launcher-v…`), newest first, with this platform's archive. pub fn launcher_releases() -> Result, String> { Ok(launcher_releases_in(&release_list()?)) } /// The launcher releases in `list` (the newest 100 releases). Game releases come out several times /// a day, so the newest launcher release can be older than all of those: then the newest /// `launcher@` and `launcher-v` tags are looked up one by one (a draft's tag is skipped: it has no /// public release). fn launcher_releases_in(list: &serde_json::Value) -> Vec { launcher_releases_in_with(list, |url| { get(&url)?.into_json().map_err(|e| e.to_string()) }) } fn launcher_releases_in_with( list: &serde_json::Value, json: impl Fn(String) -> Result, ) -> Vec { let found = parse_releases(list, LAUNCHER_ASSET, is_launcher_tag); if found.iter().any(|r| r.asset.is_some()) { return found; } let api = format!("https://api.github.com/repos/{REPO}"); let mut tags = Vec::new(); for prefix in [LAUNCHER_TAG_PREFIX, OLD_LAUNCHER_TAG_PREFIX] { // Every `launcher@` tag is newer than every `launcher-v` one: those only when there is none. if tags.is_empty() { if let Ok(refs) = json(format!("{api}/git/matching-refs/tags/{prefix}")) { tags = newest_launcher_tags(&refs); } } } for tag in tags.into_iter().take(3) { if let Ok(release) = json(format!("{api}/releases/tags/{tag}")) { let one = parse_releases( &serde_json::json!([release]), LAUNCHER_ASSET, is_launcher_tag, ); if one.iter().any(|r| r.asset.is_some()) { return one; } } } found } /// The launcher tags in GitHub's matching-refs answer, newest first. fn newest_launcher_tags(refs: &serde_json::Value) -> Vec { let mut tags: Vec = refs .as_array() .into_iter() .flatten() .filter_map(|r| r["ref"].as_str()?.strip_prefix("refs/tags/")) .filter(|t| is_launcher_tag(t)) .map(String::from) .collect(); tags.sort_by(|a, b| compare_versions(b, a)); tags } /// The newest Horizon release that has a build for this platform. pub fn latest(releases: &[Release]) -> Option<&Release> { releases.iter().find(|r| r.asset.is_some()) } /// The releases a launcher installs by itself: stable ones, and betas too on the Alpha channel. pub fn channel(releases: &[Release], channel: UpdateChannel) -> Vec { releases .iter() .filter(|r| channel.takes(r)) .cloned() .collect() } /// Which game releases install by themselves (Settings, "Updates"; docs/release-flow.md, "Channels"). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub enum UpdateChannel { /// A tested build about once a day: the betas promote.yml makes stable. #[default] Stable, /// Every release as soon as it is built, pre-releases included. It was called "nightly" /// while the channels were new: that name is still read. #[serde(alias = "nightly")] Alpha, } impl UpdateChannel { pub fn name(self) -> &'static str { match self { UpdateChannel::Stable => "stable", UpdateChannel::Alpha => "alpha", } } /// Its name in Settings and on the Versions page. pub fn label(self) -> &'static str { match self { UpdateChannel::Stable => "Stable", UpdateChannel::Alpha => "Alpha", } } pub fn parse(name: &str) -> Option { match name { "stable" => Some(UpdateChannel::Stable), "alpha" | "nightly" => Some(UpdateChannel::Alpha), _ => None, } } /// Whether this channel installs `release`: betas only reach Alpha. pub fn takes(self, release: &Release) -> bool { self == UpdateChannel::Alpha || !release.beta } /// How often a launcher left open looks for new releases: Alpha's come many times a day, /// Stable's once. pub fn check_every(self) -> std::time::Duration { std::time::Duration::from_secs(match self { UpdateChannel::Stable => 4 * 3600, UpdateChannel::Alpha => 30 * 60, }) } /// The channel a release is on when it is listed: betas are Alpha's only. pub fn of(release: &Release) -> Self { if release.beta { UpdateChannel::Alpha } else { UpdateChannel::Stable } } } /// The community, sponsor and website links, from `launcher/links.json` on main, so they can change /// without a launcher release. An empty address hides its button. #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct Links { pub discord: String, pub sponsor: String, pub website: String, } impl Default for Links { /// What the launcher uses until (or unless) it can read links.json. fn default() -> Self { Self { discord: "https://discord.gg/HcTeMZxe5E".into(), sponsor: "https://github.com/sponsors/ludovic111".into(), website: "https://playhorizon.dev".into(), } } } impl Links { /// Reads links.json. A key that is missing keeps its default, an empty one hides the link, /// and text that is not a JSON object gives the defaults. pub fn parse(text: &str) -> Self { let mut links = Self::default(); if let Ok(serde_json::Value::Object(map)) = serde_json::from_str(text) { for (key, slot) in [ ("discord", &mut links.discord), ("sponsor", &mut links.sponsor), ("website", &mut links.website), ] { if let Some(url) = map.get(key).and_then(|v| v.as_str()) { *slot = url.trim().to_string(); } } } links } } /// The links from main, or the built-in ones when offline. pub fn links() -> Links { let url = format!("https://raw.githubusercontent.com/{REPO}/main/launcher/links.json"); get(&url) .ok() .and_then(|r| r.into_string().ok()) .map_or_else(Links::default, |text| Links::parse(&text)) } /// The launcher's data folder; `HORIZON_LAUNCHER_HOME` overrides it (for tests and scripts). pub fn data_dir() -> PathBuf { if let Some(home) = std::env::var_os("HORIZON_LAUNCHER_HOME").filter(|h| !h.is_empty()) { return PathBuf::from(home); } dirs::data_dir() .unwrap_or_else(std::env::temp_dir) .join("horizon-launcher") } fn versions_dir() -> PathBuf { data_dir().join("versions") } pub fn version_dir(tag: &str) -> PathBuf { versions_dir().join(tag) } const COMPLETE: &str = ".installed"; /// Installed versions, newest tag first. pub fn installed() -> Vec { installed_in(&versions_dir()) } fn installed_in(versions: &Path) -> Vec { let mut tags: Vec = fs::read_dir(versions) .into_iter() .flatten() .flatten() .filter(|e| e.path().join(COMPLETE).exists()) .filter_map(|e| e.file_name().into_string().ok()) .collect(); tags.sort_by(|a, b| compare_versions(b, a)); tags } /// A small release file (its checksums or their signature), whole; None when it has none. fn fetch_small(url: &str) -> Result>, String> { let response = match get(url) { Ok(response) => response, Err(e) if e.ends_with("answered 404") => return Ok(None), Err(e) => return Err(e), }; let mut body = Vec::new(); response .into_reader() .take(1 << 20) .read_to_end(&mut body) .map_err(|e| format!("Download interrupted: {e}"))?; Ok(Some(body)) } /// The SHA-256 the release's signed checksums give for `asset`, or why it must not be installed. fn signed_digest(tag: &str, asset: &str) -> Result { crate::signed::digest( tag, asset, &horizon_release_sign::trusted_keys(), fetch_small, ) } /// Downloads `url` into `to`; the file is kept only if its SHA-256 is `sha256`, the signed one. fn download( url: &str, size: u64, sha256: &str, to: &Path, progress: &impl Fn(f32), ) -> Result<(), String> { let mut reader = get(url)?.into_reader(); let mut file = fs::File::create(to).map_err(|e| e.to_string())?; let mut hash = horizon_release_sign::Sha256::default(); let (mut done, mut buf) = (0u64, vec![0u8; 1 << 16]); loop { let n = reader .read(&mut buf) .map_err(|e| format!("Download interrupted: {e}"))?; if n == 0 { break; } hash.update(&buf[..n]); file.write_all(&buf[..n]).map_err(|e| e.to_string())?; done += n as u64; progress((done as f32 / size.max(1) as f32).min(1.0) * 0.9); } let name = url.rsplit('/').next().unwrap_or(url); horizon_release_sign::check(name, sha256, &hash.hex()).inspect_err(|_| { let _ = fs::remove_file(to); }) } fn unpack(archive: &Path, url: &str, to: &Path) -> Result<(), String> { let file = fs::File::open(archive).map_err(|e| e.to_string())?; if url.ends_with(".tar.gz") { tar::Archive::new(flate2::read::GzDecoder::new(file)) .unpack(to) .map_err(|e| e.to_string()) } else { zip::ZipArchive::new(file) .and_then(|mut z| z.extract(to)) .map_err(|e| e.to_string()) } } /// Downloads one release, checks it against its signed checksums and unpacks it; `progress` gets /// the fraction done. pub fn install(release: &Release, progress: impl Fn(f32)) -> Result<(), String> { let tag = release.tag.as_str(); if !is_game_tag(tag) { return Err(format!("{tag} is not a Horizon release.")); } let (url, size) = release .asset .clone() .ok_or_else(|| format!("{tag} has no build for this platform."))?; let sha256 = signed_digest(tag, ASSET.unwrap_or_default())?; let root = versions_dir(); let partial = root.join(format!(".{tag}.partial")); let _ = fs::remove_dir_all(&partial); fs::create_dir_all(&partial).map_err(|e| e.to_string())?; let archive = partial.join("download"); download(&url, size, &sha256, &archive, &progress)?; let unpacked = partial.join("unpacked"); unpack(&archive, &url, &unpacked)?; progress(0.97); // The archives hold one top folder (horizon-linux-x86_64/...); the version folder is its contents. let entries: Vec<_> = fs::read_dir(&unpacked) .map_err(|e| e.to_string())? .flatten() .collect(); let top = match entries.as_slice() { [only] if only.path().is_dir() => only.path(), _ => unpacked.clone(), }; if !top.join(CLIENT).exists() { return Err(format!("The download has no {CLIENT}")); } #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = fs::set_permissions(top.join(CLIENT), fs::Permissions::from_mode(0o755)); } let target = version_dir(tag); let _ = fs::remove_dir_all(&target); fs::rename(&top, &target).map_err(|e| e.to_string())?; fs::write(target.join(COMPLETE), "").map_err(|e| e.to_string())?; let _ = fs::remove_dir_all(&partial); reuse_prepared(&root, tag); progress(1.0); Ok(()) } pub fn remove(tag: &str) -> Result<(), String> { fs::remove_dir_all(version_dir(tag)).map_err(|e| e.to_string()) } /// The Minecraft version a Horizon build targets, from its research-lock.json. pub fn game_version(tag: &str) -> String { game_version_at(&version_dir(tag)) } fn read_json(path: &Path) -> Option { serde_json::from_str(&fs::read_to_string(path).ok()?).ok() } fn game_version_at(dir: &Path) -> String { read_json(&dir.join("research-lock.json")) .and_then(|v| v["minecraft"]["version"].as_str().map(String::from)) .unwrap_or_else(|| horizon_core::VANILLA_VERSION.into()) } pub fn resources(tag: &str) -> PathBuf { resources_at(&version_dir(tag)) } fn resources_at(dir: &Path) -> PathBuf { dir.join(".local/horizon-client").join(game_version_at(dir)) } const RESOURCES_MANIFEST: &str = "horizon-resources.json"; pub fn is_prepared(tag: &str) -> bool { resources(tag).join(RESOURCES_MANIFEST).exists() } /// Whether a version's resources hold Minecraft's sounds, which `sounds` copies from the player's own /// install beside the preparation. A version prepared while that copy failed (Mojang's republished 26.3 /// asset index, #1076), or one that reused such a version's resources, plays no sound at all (#1035). pub fn has_sounds(tag: &str) -> bool { sounds_in(&resources(tag)) } fn sounds_in(resources: &Path) -> bool { // What the game's sound registry reads (horizon-client sound_events.rs). resources.join("assets/minecraft/sounds.json").is_file() } /// What the Play page says of a version's resources. pub fn resources_summary(prepared: bool, sounds: bool, version: &str) -> String { match (prepared, sounds) { (false, _) => { format!("Not prepared. Horizon needs the files of your own Minecraft {version}.") } (true, true) => format!("Prepared for Minecraft {version}"), (true, false) => format!( "Prepared for Minecraft {version}, without its sounds: the game will be silent. \ Prepare again to copy them from your Minecraft install." ), } } /// Whether the resources `from` prepared are the ones preparing `to` would make. The output /// depends on the Horizon version, not only on Minecraft's: the manifest records the hashes of /// the vanilla exporters it was made with (mods/horizon/src/test/java/.../parity), and the /// preparer writes every file and the manifest's `schema`. So both need the same pinned /// Minecraft jars (research-lock.json), the same preparer and the same exporter sources. The /// preparer is crates/horizon-prepare (its sources ship in the release folder beside the /// binary) and tools/prepare_native_client.py (the Python preparer of older versions, a wrapper /// of the binary since); a file only one of the two versions has is a different preparer. The /// helpers the Python preparer imported (lab.py and the test_*_parity.py modules) change /// between releases in how they find and check the player's files, which the output does not /// depend on; they are not compared. fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) -> bool { let pins = |dir: &Path| { read_json(&dir.join("research-lock.json")).map(|lock| { ["version", "client_sha1", "server_sha1"].map(|k| lock["minecraft"][k].clone()) }) }; let (Some(a), Some(b)) = (pins(from), pins(to)) else { return false; }; if a != b || a.iter().any(|v| !v.is_string()) { return false; } let Some(fields) = manifest.as_object() else { return false; }; let mut preparer = vec![PathBuf::from("tools/prepare_native_client.py")]; for dir in [from, to] { preparer.extend(files_under(dir, Path::new(PREPARER_CRATE))); } let same_or_absent = |path: &Path| match (fs::read(from.join(path)), fs::read(to.join(path))) { (Ok(a), Ok(b)) => a == b, (Err(a), Err(b)) => { a.kind() == std::io::ErrorKind::NotFound && b.kind() == std::io::ErrorKind::NotFound } _ => false, }; if !preparer.iter().all(|p| same_or_absent(p)) { return false; } let mut sources = vec![ "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java".to_string(), ]; for (_, value) in fields .iter() .filter(|(key, _)| key.ends_with("_exporters_sha256")) { let Some(files) = value.as_object() else { return false; }; sources.extend(files.keys().cloned()); } let same = |source: &str| { let path = Path::new(source); path.is_relative() && path .components() .all(|c| matches!(c, std::path::Component::Normal(_))) && matches!((fs::read(from.join(path)), fs::read(to.join(path))), (Ok(a), Ok(b)) if a == b) }; sources.iter().all(|s| same(s)) } /// Where a version folder keeps the preparer's sources (the release package copies them). const PREPARER_CRATE: &str = "crates/horizon-prepare"; /// The files under `dir/relative`, as paths relative to `dir`. fn files_under(dir: &Path, relative: &Path) -> Vec { let Ok(entries) = fs::read_dir(dir.join(relative)) else { return Vec::new(); }; let mut files = Vec::new(); for entry in entries.flatten() { let path = relative.join(entry.file_name()); match entry.file_type() { Ok(t) if t.is_dir() => files.extend(files_under(dir, &path)), Ok(_) => files.push(path), Err(_) => {} } } files } fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { fs::create_dir_all(to)?; for entry in fs::read_dir(from)? { let entry = entry?; let target = to.join(entry.file_name()); if entry.file_type()?.is_dir() { copy_dir(&entry.path(), &target)?; } else { fs::copy(entry.path(), target)?; } } Ok(()) } /// After an install: when `tag` is not prepared but another installed version made the same /// resources, copies them (not hard links: preparing again rewrites files in place, which would /// change both). The player then needs neither their Minecraft folder nor a new preparation to /// play a release that only changed Horizon. Returns the version they came from. fn reuse_prepared(versions: &Path, tag: &str) -> Option { let target = versions.join(tag); let to = resources_at(&target); if to.join(RESOURCES_MANIFEST).exists() { return None; } let version = game_version_at(&target); for other in installed_in(versions).into_iter().filter(|t| t != tag) { let source = versions.join(&other); if game_version_at(&source) != version { continue; } let from = resources_at(&source); let Some(manifest) = read_json(&from.join(RESOURCES_MANIFEST)) else { continue; }; if !resources_compatible(&source, &target, &manifest) { continue; } // Copied beside it and renamed when complete: an interrupted copy is never "prepared". // The name is this call's own, as the window's start and an install can both copy. static COPIES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let n = COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let partial = to.with_file_name(format!(".{version}.partial-{}-{n}", std::process::id())); let _ = fs::remove_dir_all(&partial); let copied = copy_dir(&from, &partial).and_then(|_| { if to.join(RESOURCES_MANIFEST).exists() { return Ok(false); // Prepared meanwhile, by another copy or the player. } let _ = fs::remove_dir_all(&to); fs::rename(&partial, &to).map(|_| true) }); let _ = fs::remove_dir_all(&partial); match copied { Ok(true) => return Some(other), Ok(false) => return None, Err(_) => {} } } None } /// `reuse_prepared` for every installed version that is not prepared, oldest first, so a /// version prepared this way can serve the next. Launchers before 0.1.4 installed new versions /// without it; this catches those up. Returns each (version, where its resources came from). /// Prepared versions also get the run-time reports they lack (`complete_reports`). pub fn reuse_prepared_everywhere() -> Vec<(String, String)> { reuse_prepared_in(&versions_dir()) } fn reuse_prepared_in(versions: &Path) -> Vec<(String, String)> { let mut tags = installed_in(versions); tags.reverse(); let reused = tags .iter() .filter_map(|tag| reuse_prepared(versions, tag).map(|from| (tag.clone(), from))) .collect(); for tag in &tags { complete_reports(versions, tag); } reused } /// The data generator reports the game reads at run time: the built-in registries' network ids /// (without them no server can be joined or hosted) and the command tree. const RUNTIME_REPORTS: [&str; 2] = ["registries.json", "commands.json"]; /// Puts the data generator reports the game reads at run time (`RUNTIME_REPORTS`) into a prepared version's /// resources when they are missing. Preparers before they shipped there left them only in the /// scratch output of the version that ran the data generator (`.local/datagen/out/reports`), /// and resources copied from another version (`reuse_prepared`) came without them. They depend /// only on the server jar, so the version's own scratch output or any installed version pinning /// the same jar serves, and no new preparation is needed. Returns whether all are there. fn complete_reports(versions: &Path, tag: &str) -> bool { let target = versions.join(tag); let to = resources_at(&target); if !to.join(RESOURCES_MANIFEST).exists() { return false; } let missing: Vec<_> = RUNTIME_REPORTS .iter() .filter(|name| !to.join(name).is_file()) .collect(); if missing.is_empty() { return true; } let server = |dir: &Path| { read_json(&dir.join("research-lock.json")).and_then(|lock| { let pins = ["version", "server_sha1"].map(|k| lock["minecraft"][k].clone()); pins.iter().all(|v| v.is_string()).then_some(pins) }) }; let Some(pins) = server(&target) else { return false; }; let reports = |dir: &Path| dir.join(".local/datagen/out/reports"); let mut sources = vec![reports(&target)]; for other in installed_in(versions).into_iter().filter(|t| t != tag) { let dir = versions.join(&other); if server(&dir).as_ref() == Some(&pins) { sources.push(resources_at(&dir)); sources.push(reports(&dir)); } } let mut complete = true; for name in missing { let Some(from) = sources.iter().map(|s| s.join(name)).find(|p| p.is_file()) else { complete = false; continue; }; // Copied beside it and renamed: an interrupted copy never looks complete. let partial = to.join(format!(".{name}.partial-{}", std::process::id())); let copied = fs::copy(&from, &partial).and_then(|_| fs::rename(&partial, to.join(name))); if copied.is_err() { let _ = fs::remove_file(&partial); complete = false; } } complete } /// The official launcher's game directory, else the first other launcher's found /// (sources.rs); preparing looks in all of them anyway. pub fn default_minecraft_dir() -> Option { let folders = sources::Folders::current()?; sources::known_folders(sources::Os::current(), &folders) .into_iter() .map(|(_, dir)| dir) .find(|dir| dir.is_dir()) } fn found(program: &str, arg: &str) -> bool { Command::new(program) .arg(arg) .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .is_ok() } fn python() -> Option<&'static str> { let candidates: &[&'static str] = if cfg!(windows) { &["py", "python"] } else { &["python3", "python"] }; candidates.iter().copied().find(|p| found(p, "--version")) } /// How a version's resources are prepared. pub enum Preparer { /// horizon-prepare, linked into the launcher: the version ships the same preparer sources. InProcess(horizon_prepare::Options), /// The version's own preparer: its horizon-prepare binary when its sources differ from the /// launcher's (a newer or older release), or the Python script of versions made before it. Process(Command), } /// The version's horizon-prepare binary, when it ships one. fn preparer_binary(dir: &Path) -> Option { let binary = dir.join(if cfg!(windows) { "horizon-prepare.exe" } else { "horizon-prepare" }); binary.is_file().then_some(binary) } /// Downloads the pinned version from Mojang into `dir` when the signed-in account owns /// Minecraft (asked again now), else says what signing in would do, as the last line of the /// not-found error. fn download_for_owner( pins: &sources::Pins, dir: &Path, fetch: sources::Fetch, log: &dyn Fn(String), ) -> Result<(), String> { let v = &pins.version; let owner = (|| -> Result, String> { let ep = account::Endpoints::live(); let mut accounts = account::Accounts::load(); let Some((a, secrets)) = account::session_for_launch(&ep, account::store(), &mut accounts)? else { return Ok(None); }; Ok(Some((a.name, account::owns_minecraft(&ep, &secrets)?))) })(); match owner { Ok(Some((name, true))) => { log(format!( "{name} owns Minecraft: downloading {v} from Mojang" )); let os = match sources::Os::current() { sources::Os::Linux => "linux", sources::Os::MacOs => "osx", sources::Os::Windows => "windows", }; mojang::download(pins, dir, os, 8, fetch, log).map_err(|e| { format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}") }) } Ok(Some((name, false))) => Err(format!( "\n • {name}, the signed-in account, doesn't own Minecraft: Java Edition, so Horizon \ can't download it." )), Ok(None) => Err(format!( "\n • Or sign in with the Microsoft account that owns Minecraft: Horizon then \ downloads {v} from Mojang itself." )), Err(e) => Err(format!( "\n • Downloading {v} from Mojang needs your Microsoft account, which could not be \ checked: {e}" )), } } /// 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, String> { if horizon_prepare::java::find(major, &[]).is_ok() { return Ok(None); } let mut runtimes: Vec = 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, 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 /// to prepare from: `minecraft`, or the files another launcher keeps, linked into the official /// launcher's layout (sources.rs). pub fn preparer( tag: &str, minecraft: &Path, log: &dyn Fn(String), ) -> Result<(Preparer, PathBuf), String> { 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 { let pins = read_json(&dir.join("research-lock.json")) .and_then(|lock| sources::Pins::read(&lock)) .ok_or("The version's research-lock.json doesn't pin the Minecraft files")?; let own = data_dir().join("minecraft"); let mut known = vec![("Horizon's own download", own.clone())]; known.extend( sources::Folders::current() .map(|f| sources::known_folders(sources::Os::current(), &f)) .unwrap_or_default(), ); let fetch = |url: &str| -> Result, String> { let mut body = Vec::new(); get(url)? .into_reader() .read_to_end(&mut body) .map_err(|e| e.to_string())?; Ok(body) }; let linked = data_dir().join("linked-minecraft"); match sources::resolve(minecraft, &pins, &known, &linked, &fetch, log)? { sources::Resolved::Folder(dir) => dir, sources::Resolved::NotFound(checked) => { let not_found = sources::not_found(&version, &checked, minecraft); download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?; own } } }; let manifest = minecraft .join("versions") .join(&version) .join(format!("{version}.json")); let binary = preparer_binary(&dir); 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")); if !reused && !jar.exists() { let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(&manifest).map_err(|e| e.to_string())?) .map_err(|e| e.to_string())?; let url = json["downloads"]["server"]["url"] .as_str() .ok_or_else(|| format!("{} has no server download", manifest.display()))?; log(format!("Downloading the {version} server jar from Mojang")); fs::create_dir_all(jar.parent().unwrap()).map_err(|e| e.to_string())?; let mut body = Vec::new(); get(url)? .into_reader() .read_to_end(&mut body) .map_err(|e| e.to_string())?; let partial = jar.with_extension("partial"); fs::write(&partial, body) .and_then(|_| fs::rename(&partial, &jar)) .map_err(|e| e.to_string())?; } if let Some(binary) = binary { if horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref() == Some(horizon_prepare::SOURCES_SHA256) { let options = horizon_prepare::Options { root: dir, 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); } cmd.arg("--minecraft-dir").arg(&minecraft); 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 { cmd.args(["--prepare", "--server-jar"]).arg(&jar); } cmd.arg("--minecraft-dir").arg(&minecraft); Ok((Preparer::Process(cmd), minecraft)) } /// Copies the pinned version's sounds from the player's own launcher install into the version's /// resources (`horizon-prepare sounds`), each line to `log`. Sound is optional, so a launcher /// install without them is a line in the log, never a failed preparation. The version's own /// preparer does it when it is not the launcher's and knows how; versions from before it read /// the sounds where the launcher's preparer puts them. pub fn sounds(tag: &str, minecraft: &Path, log: &dyn Fn(String)) { let dir = version_dir(tag); let own = horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref() == Some(horizon_prepare::SOURCES_SHA256); let binary = preparer_binary(&dir).filter(|binary| { !own && Command::new(binary) .arg("--help") .output() .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("horizon-prepare sounds")) }); log("Copying the sounds from your Minecraft install".into()); let result = match binary { Some(binary) => Command::new(binary) .current_dir(&dir) .arg("sounds") .arg("--root") .arg(&dir) .arg("--minecraft-dir") .arg(minecraft) .output() .map_err(|e| e.to_string()) .and_then(|o| { let text = |b: &[u8]| String::from_utf8_lossy(b).trim().to_string(); for line in text(&o.stdout).lines() { log(line.to_string()); } match o.status.success() { true => Ok(()), false => Err(text(&o.stderr).trim_start_matches("error: ").to_string()), } }), None => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { horizon_prepare::sounds(&dir, Some(minecraft), &|line| log(line.to_string())) })) .unwrap_or_else(|_| Err("The sound copy stopped unexpectedly".into())) .map(|_| ()), }; if let Err(e) = result { log(format!("No sound (the game will be silent): {e}")); } } /// Runs `Preparer::InProcess` on this thread, each progress line to `log`. A panic is an /// error like any other, so the window never waits on a preparation that died. pub fn prepare_in_process( options: &horizon_prepare::Options, log: &dyn Fn(String), ) -> Result<(), String> { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { horizon_prepare::prepare(options, &|line| log(line.to_string())) })) .unwrap_or_else(|_| Err("The preparation stopped unexpectedly".into())) .map(|_| ()) } /// Where the game keeps saves and options.txt: `HORIZON_HOME`, else `horizon` in the platform's /// data folder (~/.local/share/horizon on Linux, as the release folders' horizon.sh uses). It is /// never inside a version folder, so installing, updating or removing a version keeps the saves. pub fn game_home() -> PathBuf { if let Some(home) = std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) { return PathBuf::from(home); } dirs::data_dir() .unwrap_or_else(std::env::temp_dir) .join("horizon") } /// Whether No AI is on: every AI feature hidden and off (`horizon_core::no_ai`, kept in the /// game's `horizon-extras.txt` so the game reads the same switch). pub fn no_ai() -> bool { horizon_core::no_ai::is_on(&game_home()) } /// Turns No AI on or off for the launcher and the game. pub fn set_no_ai(on: bool) -> Result<(), String> { horizon_core::no_ai::set(&game_home(), on).map_err(|e| format!("Could not save No AI: {e}")) } // ----- Logs and crash reports --------------------------------------------------------------------- /// The game's logs (`latest.log` and the day archives), as it writes them in its home. pub fn logs_dir() -> PathBuf { game_home().join("logs") } /// Where the game writes `crash-_