diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 2cea1ae78..af0228a97 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2565,7 +2565,7 @@ dependencies = [ [[package]] name = "horizon-launcher" -version = "0.1.3" +version = "0.1.4" dependencies = [ "clap", "dirs 5.0.1", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index b1e664c0f..f10d1ae50 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "horizon-launcher" -version = "0.1.3" +version = "0.1.4" edition = "2021" license = "MIT" description = "Downloads, prepares and starts Horizon builds" diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 2932a4685..f83716966 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -50,9 +50,17 @@ pub const LAUNCHER_ASSET: Option<&str> = Some("horizon-launcher-windows-x64.zip" )))] pub const LAUNCHER_ASSET: Option<&str> = None; -const LAUNCHER_BINARY: &str = if cfg!(windows) { "horizon-launcher.exe" } else { "horizon-launcher" }; +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" }; +const CLIENT: &str = if cfg!(windows) { + "horizon-client.exe" +} else { + "horizon-client" +}; fn agent() -> ureq::Agent { ureq::AgentBuilder::new().user_agent(AGENT).build() @@ -61,13 +69,18 @@ fn agent() -> ureq::Agent { 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 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(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}"), }) @@ -75,19 +88,28 @@ fn get(url: &str) -> Result { /// 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())) + tag.strip_prefix('v') + .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) } /// The launcher version in a `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).filter(|v| v.starts_with(|c: char| c.is_ascii_digit())) + tag.strip_prefix(LAUNCHER_TAG_PREFIX) + .filter(|v| v.starts_with(|c: char| c.is_ascii_digit())) } /// The numeric parts of a version or tag: `v2026.10.13` and `2026.10.13` give [2026, 10, 13]. /// Anything after a `-` (a pre-release) is ignored. fn version_parts(v: &str) -> Vec { - let v = v.trim_start_matches(LAUNCHER_TAG_PREFIX).trim_start_matches('v'); - v.split('-').next().unwrap_or("").split('.').map(|p| p.parse().unwrap_or(0)).collect() + let v = v + .trim_start_matches(LAUNCHER_TAG_PREFIX) + .trim_start_matches('v'); + v.split('-') + .next() + .unwrap_or("") + .split('.') + .map(|p| p.parse().unwrap_or(0)) + .collect() } /// Compares two versions part by part, missing parts counting as zero (1.2 == 1.2.0). @@ -106,7 +128,11 @@ fn release_list() -> Result { } /// 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 { +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(); @@ -114,14 +140,23 @@ fn parse_releases(list: &serde_json::Value, asset: Option<&str>, keep: fn(&str) 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()?)))? + (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(), + date: r["published_at"] + .as_str() + .unwrap_or_default() + .chars() + .take(10) + .collect(), asset: found, }); } @@ -141,7 +176,11 @@ pub fn releases() -> Result, String> { /// Published launcher releases (`launcher-v…`), newest first, with this platform's archive. pub fn launcher_releases() -> Result, String> { - Ok(parse_releases(&release_list()?, LAUNCHER_ASSET, is_launcher_tag)) + Ok(parse_releases( + &release_list()?, + LAUNCHER_ASSET, + is_launcher_tag, + )) } /// The newest Horizon release that has a build for this platform. @@ -156,7 +195,10 @@ pub fn roadmap() -> Result { let level = |l: &str| l.chars().take_while(|c| *c == '#').count(); for title in ["Roadmap", "Project status"] { let lines: Vec<&str> = readme.lines().collect(); - if let Some(start) = lines.iter().position(|l| level(l) > 0 && l.trim_start_matches('#').trim() == title) { + if let Some(start) = lines + .iter() + .position(|l| level(l) > 0 && l.trim_start_matches('#').trim() == title) + { let depth = level(lines[start]); let section: Vec<&str> = lines[start + 1..] .iter() @@ -181,7 +223,11 @@ pub struct Links { 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() } + Self { + discord: "https://discord.gg/HcTeMZxe5E".into(), + sponsor: "https://github.com/sponsors/ludovic111".into(), + website: "https://playhorizon.dev".into(), + } } } @@ -191,7 +237,11 @@ impl Links { 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)] { + 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(); } @@ -204,7 +254,10 @@ impl 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)) + 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). @@ -212,7 +265,9 @@ 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") + dirs::data_dir() + .unwrap_or_else(std::env::temp_dir) + .join("horizon-launcher") } fn versions_dir() -> PathBuf { @@ -227,7 +282,11 @@ const COMPLETE: &str = ".installed"; /// Installed versions, newest tag first. pub fn installed() -> Vec { - let mut tags: Vec = fs::read_dir(versions_dir()) + installed_in(&versions_dir()) +} + +fn installed_in(versions: &Path) -> Vec { + let mut tags: Vec = fs::read_dir(versions) .into_iter() .flatten() .flatten() @@ -243,7 +302,9 @@ fn download(url: &str, size: u64, to: &Path, progress: &impl Fn(f32)) -> Result< let mut file = fs::File::create(to).map_err(|e| e.to_string())?; let (mut done, mut buf) = (0u64, vec![0u8; 1 << 16]); loop { - let n = reader.read(&mut buf).map_err(|e| format!("Download interrupted: {e}"))?; + let n = reader + .read(&mut buf) + .map_err(|e| format!("Download interrupted: {e}"))?; if n == 0 { return Ok(()); } @@ -256,9 +317,13 @@ fn download(url: &str, size: u64, to: &Path, progress: &impl Fn(f32)) -> Result< 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()) + 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()) + zip::ZipArchive::new(file) + .and_then(|mut z| z.extract(to)) + .map_err(|e| e.to_string()) } } @@ -277,7 +342,10 @@ pub fn install(tag: &str, url: &str, size: u64, progress: impl Fn(f32)) -> Resul 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 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(), @@ -295,6 +363,7 @@ pub fn install(tag: &str, url: &str, size: u64, progress: impl Fn(f32)) -> Resul 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(()) } @@ -305,19 +374,153 @@ pub fn remove(tag: &str) -> Result<(), String> { /// The Minecraft version a Horizon build targets, from its research-lock.json. pub fn game_version(tag: &str) -> String { - fs::read_to_string(version_dir(tag).join("research-lock.json")) - .ok() - .and_then(|s| serde_json::from_str::(&s).ok()) + 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(|| "26.3".into()) } pub fn resources(tag: &str) -> PathBuf { - version_dir(tag).join(".local/horizon-client").join(game_version(tag)) + 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("horizon-resources.json").exists() + resources(tag).join(RESOURCES_MANIFEST).exists() +} + +/// 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 +/// prepare_native_client.py writes every file and the manifest's `schema`. So both need the +/// same pinned Minecraft jars (research-lock.json), the same prepare_native_client.py and the +/// same exporter sources. The helpers it imports (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 sources = vec![ + "tools/prepare_native_client.py".to_string(), + "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)) +} + +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). +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(); + tags.into_iter() + .filter_map(|tag| reuse_prepared(versions, &tag).map(|from| (tag, from))) + .collect() } /// The official launcher's game directory, where prepare_native_client.py looks by default. @@ -334,19 +537,35 @@ pub fn default_minecraft_dir() -> Option { } fn found(program: &str, arg: &str) -> bool { - Command::new(program).arg(arg).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok() + 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"] }; + let candidates: &[&'static str] = if cfg!(windows) { + &["py", "python"] + } else { + &["python3", "python"] + }; candidates.iter().copied().find(|p| found(p, "--version")) } /// Checks what the preparation needs and builds its command. PLAY.txt describes the same steps: /// the player's own launcher install, the server jar from that version's own json, Java and Python. -pub fn prepare_command(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result { +pub fn prepare_command( + tag: &str, + minecraft: &Path, + log: &dyn Fn(String), +) -> Result { let version = game_version(tag); - let manifest = minecraft.join("versions").join(&version).join(format!("{version}.json")); + let manifest = minecraft + .join("versions") + .join(&version) + .join(format!("{version}.json")); if !manifest.exists() { return Err(format!( "Minecraft {version} is not in {}. Play {version} once from the official launcher, or choose another folder.", @@ -355,25 +574,40 @@ pub fn prepare_command(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Res } let python = python().ok_or("Python 3.10 or newer is needed. Install it and try again.")?; if !found("java", "-version") { - return Err("Java 25 is needed (a JDK, e.g. Eclipse Temurin 25). Install it and try again.".into()); + return Err( + "Java 25 is needed (a JDK, e.g. Eclipse Temurin 25). Install it and try again.".into(), + ); } - let jar = data_dir().join("server-jars").join(format!("{version}.jar")); + let jar = data_dir() + .join("server-jars") + .join(format!("{version}.jar")); if !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 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())?; + 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())?; + fs::write(&partial, body) + .and_then(|_| fs::rename(&partial, &jar)) + .map_err(|e| e.to_string())?; } let mut cmd = Command::new(python); cmd.current_dir(version_dir(tag)) - .args(["-u", "tools/prepare_native_client.py", "--prepare", "--server-jar"]) + .args([ + "-u", + "tools/prepare_native_client.py", + "--prepare", + "--server-jar", + ]) .arg(&jar) .arg("--minecraft-dir") .arg(minecraft); @@ -387,7 +621,9 @@ 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") + dirs::data_dir() + .unwrap_or_else(std::env::temp_dir) + .join("horizon") } /// Which drawing the game's menus use. Classic is vanilla's own screens, which have no way to @@ -426,7 +662,11 @@ impl MenuStyle { /// `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 = text.lines().filter(|l| !l.trim().starts_with("menuStyle:")).map(String::from).collect(); + let mut out: Vec = text + .lines() + .filter(|l| !l.trim().starts_with("menuStyle:")) + .map(String::from) + .collect(); out.insert(0, format!("menuStyle:{}", self.name())); out.join("\n") + "\n" } @@ -454,19 +694,26 @@ pub fn client_command(tag: &str) -> Command { // "PipeWire ALSA [horizon-client]", shared with development and test runs, where // muting it once left every later game silent: played from here it is "Horizon". if std::env::var_os("PIPEWIRE_PROPS").is_none() { - cmd.env("PIPEWIRE_PROPS", "{ application.name = \"Horizon\" media.role = \"Game\" }"); + cmd.env( + "PIPEWIRE_PROPS", + "{ application.name = \"Horizon\" media.role = \"Game\" }", + ); } cmd } pub fn server_command(tag: &str, folder: &Path) -> Command { let mut cmd = Command::new(version_dir(tag).join(CLIENT)); - cmd.current_dir(folder).arg("--resources").arg(resources(tag)).args(["--dedicated", "--nogui"]); + cmd.current_dir(folder) + .arg("--resources") + .arg(resources(tag)) + .args(["--dedicated", "--nogui"]); cmd } pub fn eula_agreed(folder: &Path) -> bool { - fs::read_to_string(folder.join("eula.txt")).is_ok_and(|s| s.lines().any(|l| l.trim() == "eula=true")) + fs::read_to_string(folder.join("eula.txt")) + .is_ok_and(|s| s.lines().any(|l| l.trim() == "eula=true")) } /// Writes eula.txt as vanilla's server expects it, once the player agreed in the launcher. @@ -482,10 +729,16 @@ pub fn agree_eula(folder: &Path) -> Result<(), String> { pub fn resolve_version(requested: Option<&str>) -> Result { let installed = installed(); if let Some(tag) = requested { - return installed.iter().find(|t| *t == tag).cloned().ok_or_else(|| format!("{tag} is not installed.")); + return installed + .iter() + .find(|t| *t == tag) + .cloned() + .ok_or_else(|| format!("{tag} is not installed.")); } let selected = Settings::load().selected.filter(|s| installed.contains(s)); - selected.or_else(|| installed.first().cloned()).ok_or_else(|| "No version is installed yet.".into()) + selected + .or_else(|| installed.first().cloned()) + .ok_or_else(|| "No version is installed yet.".into()) } /// Removes an installed version and moves the selection to the newest one left if needed. @@ -508,19 +761,26 @@ pub fn minecraft_dir(requested: Option) -> Result { requested .or(Settings::load().minecraft_dir) .or_else(default_minecraft_dir) - .ok_or_else(|| "No Minecraft folder found. Pass the official launcher's game folder.".into()) + .ok_or_else(|| { + "No Minecraft folder found. Pass the official launcher's game folder.".into() + }) } /// The server folder: the one given, the one chosen in the launcher, or `server/` in the data folder. pub fn server_dir(requested: Option) -> PathBuf { - requested.or(Settings::load().server_dir).unwrap_or_else(|| data_dir().join("server")) + requested + .or(Settings::load().server_dir) + .unwrap_or_else(|| data_dir().join("server")) } fn need_prepared(tag: &str) -> Result<(), String> { if is_prepared(tag) { Ok(()) } else { - Err(format!("{tag} is not prepared yet. Prepare it first (it needs your own Minecraft {}).", game_version(tag))) + Err(format!( + "{tag} is not prepared yet. Prepare it first (it needs your own Minecraft {}).", + game_version(tag) + )) } } @@ -547,8 +807,14 @@ pub fn server(tag: &str, folder: &Path, accept_eula: bool) -> Result) -> Result { let releases = releases()?; match tag { - Some(tag) => releases.into_iter().find(|r| r.tag == tag).ok_or_else(|| format!("No Horizon release is tagged {tag}.")), - None => releases.into_iter().next().ok_or_else(|| "No release is published yet.".into()), + Some(tag) => releases + .into_iter() + .find(|r| r.tag == tag) + .ok_or_else(|| format!("No Horizon release is tagged {tag}.")), + None => releases + .into_iter() + .next() + .ok_or_else(|| "No release is published yet.".into()), } } @@ -592,7 +858,10 @@ impl Logged { pub fn tail(&self, lines: usize) -> Vec { let log = self.log.lock().unwrap(); - log.iter().skip(log.len().saturating_sub(lines)).cloned().collect() + log.iter() + .skip(log.len().saturating_sub(lines)) + .cloned() + .collect() } pub fn wait(&self) -> Result<(), String> { @@ -629,7 +898,9 @@ pub struct Updates { /// The newest Horizon release with a build here, if it is newer than every installed version. pub fn horizon_update(releases: &[Release], installed: &[String]) -> Option { let newest = latest(releases)?; - let newer = installed.iter().all(|t| compare_versions(&newest.tag, t).is_gt()); + let newer = installed + .iter() + .all(|t| compare_versions(&newest.tag, t).is_gt()); newer.then(|| newest.clone()) } @@ -667,9 +938,15 @@ pub fn install_tag(tag: &str, as_update: bool, progress: impl Fn(f32)) -> Result let release = if tag == "latest" { latest(&releases).ok_or("No release has a build for this platform yet.")? } else { - releases.iter().find(|r| r.tag == tag).ok_or_else(|| format!("No Horizon release is tagged {tag}."))? + releases + .iter() + .find(|r| r.tag == tag) + .ok_or_else(|| format!("No Horizon release is tagged {tag}."))? }; - let (url, size) = release.asset.clone().ok_or_else(|| format!("{} has no build for this platform.", release.tag))?; + let (url, size) = release + .asset + .clone() + .ok_or_else(|| format!("{} has no build for this platform.", release.tag))?; let before = installed(); install(&release.tag, &url, size, progress)?; let mut settings = Settings::load(); @@ -694,7 +971,10 @@ pub fn self_update_allowed() -> bool { /// Downloads a launcher release and puts its binary in place of this one. The running process /// keeps working; `restart` starts the new one. pub fn self_update(release: &Release, progress: impl Fn(f32)) -> Result<(), String> { - let (url, size) = release.asset.clone().ok_or("This launcher release has no build for this platform.")?; + let (url, size) = release + .asset + .clone() + .ok_or("This launcher release has no build for this platform.")?; let work = data_dir().join(".launcher-update"); let _ = fs::remove_dir_all(&work); fs::create_dir_all(&work).map_err(|e| e.to_string())?; @@ -702,13 +982,15 @@ pub fn self_update(release: &Release, progress: impl Fn(f32)) -> Result<(), Stri download(&url, size, &archive, &progress)?; let unpacked = work.join("unpacked"); unpack(&archive, &url, &unpacked)?; - let binary = find_file(&unpacked, LAUNCHER_BINARY).ok_or("The download has no launcher binary.")?; + let binary = + find_file(&unpacked, LAUNCHER_BINARY).ok_or("The download has no launcher binary.")?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)); } - self_replace::self_replace(&binary).map_err(|e| format!("Could not replace the launcher: {e}"))?; + self_replace::self_replace(&binary) + .map_err(|e| format!("Could not replace the launcher: {e}"))?; let _ = fs::remove_dir_all(&work); progress(1.0); Ok(()) @@ -730,7 +1012,9 @@ fn find_file(dir: &Path, name: &str) -> Option { /// Starts the launcher again (the updated binary) with the same arguments, and exits. pub fn restart() -> ! { - let _ = Command::new(exe_path()).args(std::env::args_os().skip(1)).spawn(); + let _ = Command::new(exe_path()) + .args(std::env::args_os().skip(1)) + .spawn(); std::process::exit(0) } @@ -773,7 +1057,9 @@ pub fn markdown_to_text(md: &str) -> String { } } Event::End(TagEnd::Heading(_)) => out.push_str("\n\n"), - Event::End(TagEnd::Paragraph) => out.push_str(if lists.is_empty() { "\n\n" } else { "\n" }), + Event::End(TagEnd::Paragraph) => { + out.push_str(if lists.is_empty() { "\n\n" } else { "\n" }) + } Event::End(TagEnd::Item) if !out.ends_with('\n') => out.push('\n'), Event::End(TagEnd::CodeBlock) => out.push('\n'), Event::Text(t) | Event::Code(t) => out.push_str(&t), @@ -788,7 +1074,10 @@ pub fn markdown_to_text(md: &str) -> String { /// The first sentence-like line of a release's notes, for a one-line summary. pub fn notes_summary(body: &str) -> Option { let text = markdown_to_text(body); - let line = text.lines().map(str::trim).find(|l| l.len() > 24 && !l.starts_with("---"))?; + let line = text + .lines() + .map(str::trim) + .find(|l| l.len() > 24 && !l.starts_with("---"))?; let line = line.trim_start_matches("- "); Some(match line.char_indices().nth(140) { Some((i, _)) => format!("{}…", line[..i].trim_end()), @@ -814,6 +1103,8 @@ pub enum Msg { Updates(Result), LauncherProgress(f32), LauncherUpdated(Result<(), String>), + /// `reuse_prepared_everywhere` prepared these versions. + Reused(Vec<(String, String)>), } /// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`. @@ -843,8 +1134,14 @@ pub fn spawn(job: Job, mut cmd: Command, tx: Sender) -> Result); - let err = child.stderr.take().map(|o| Box::new(o) as Box); + let out = child + .stdout + .take() + .map(|o| Box::new(o) as Box); + let err = child + .stderr + .take() + .map(|o| Box::new(o) as Box); for stream in [out, err].into_iter().flatten() { let tx = tx.clone(); readers.push(std::thread::spawn(move || { @@ -902,7 +1199,10 @@ impl Settings { } pub fn save(&self) { let _ = fs::create_dir_all(data_dir()); - let _ = fs::write(data_dir().join("settings.json"), serde_json::to_string_pretty(self).unwrap()); + let _ = fs::write( + data_dir().join("settings.json"), + serde_json::to_string_pretty(self).unwrap(), + ); } } @@ -917,8 +1217,13 @@ mod tests { return; } let cmd = client_command("v2026.10.13"); - let props = cmd.get_envs().find(|(k, _)| *k == "PIPEWIRE_PROPS").and_then(|(_, v)| v); - assert!(props.is_some_and(|v| v.to_string_lossy().contains("application.name = \"Horizon\""))); + let props = cmd + .get_envs() + .find(|(k, _)| *k == "PIPEWIRE_PROPS") + .and_then(|(_, v)| v); + assert!(props.is_some_and(|v| v + .to_string_lossy() + .contains("application.name = \"Horizon\""))); } #[test] @@ -935,9 +1240,15 @@ mod tests { {"tag_name": "v2026.10.13", "assets": []}, {"tag_name": "launcher-v0.0.1", "draft": true, "assets": []}, ]); - let game: Vec<_> = parse_releases(&list, ASSET, is_game_tag).into_iter().map(|r| r.tag).collect(); + let game: Vec<_> = parse_releases(&list, ASSET, is_game_tag) + .into_iter() + .map(|r| r.tag) + .collect(); assert_eq!(game, ["v2026.10.13", "v2026.10.12"]); - let launcher: Vec<_> = parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag).into_iter().map(|r| r.tag).collect(); + let launcher: Vec<_> = parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag) + .into_iter() + .map(|r| r.tag) + .collect(); assert_eq!(launcher, ["launcher-v9.0.0"]); } @@ -953,9 +1264,18 @@ mod tests { #[test] fn updates() { - let r = |tag: &str| Release { tag: tag.into(), name: String::new(), body: String::new(), date: String::new(), asset: Some(("u".into(), 1)) }; + let r = |tag: &str| Release { + tag: tag.into(), + name: String::new(), + body: String::new(), + date: String::new(), + asset: Some(("u".into(), 1)), + }; let releases = [r("v2026.10.13"), r("v2026.10.12")]; - assert_eq!(horizon_update(&releases, &["v2026.10.12".into()]).map(|r| r.tag), Some("v2026.10.13".into())); + assert_eq!( + horizon_update(&releases, &["v2026.10.12".into()]).map(|r| r.tag), + Some("v2026.10.13".into()) + ); assert!(horizon_update(&releases, &["v2026.10.13".into()]).is_none()); assert!(launcher_update(&[r("launcher-v0.0.1")]).is_none()); assert!(launcher_update(&[r("launcher-v99.0.0")]).is_some()); @@ -970,11 +1290,16 @@ mod tests { // No settings file, an old one that never mentioned it, and 0.1.1's default `false`. assert!(Settings::parse("").auto_install()); assert!(Settings::parse("{}").auto_install()); - assert!(Settings::parse(r#"{"selected": "v2026.10.13", "auto_install": false}"#).auto_install()); + assert!( + Settings::parse(r#"{"selected": "v2026.10.13", "auto_install": false}"#).auto_install() + ); assert!(Settings::parse(r#"{"install_new_versions": true}"#).auto_install()); assert!(!Settings::parse(r#"{"install_new_versions": false}"#).auto_install()); // Saving after the player turned it off keeps it off. - let off = Settings { install_new_versions: Some(false), ..Settings::default() }; + let off = Settings { + install_new_versions: Some(false), + ..Settings::default() + }; assert!(!Settings::parse(&serde_json::to_string(&off).unwrap()).auto_install()); // The selection rule is unchanged: the new version is selected only from the newest. let installed = ["v2026.10.12".to_string(), "v2026.10.1".to_string()]; @@ -989,7 +1314,9 @@ mod tests { assert_eq!(defaults.sponsor, "https://github.com/sponsors/ludovic111"); assert_eq!(defaults.website, "https://playhorizon.dev"); // The file on main says the same thing as the defaults. - let file = Links::parse(r#"{"discord": "https://discord.gg/HcTeMZxe5E", "sponsor": "https://github.com/sponsors/ludovic111", "website": "https://playhorizon.dev"}"#); + let file = Links::parse( + r#"{"discord": "https://discord.gg/HcTeMZxe5E", "sponsor": "https://github.com/sponsors/ludovic111", "website": "https://playhorizon.dev"}"#, + ); assert_eq!(file, defaults); // Unreadable or missing, offline included: the defaults. assert_eq!(Links::parse(""), defaults); @@ -997,8 +1324,21 @@ mod tests { assert_eq!(Links::parse("[1]"), defaults); assert_eq!(Links::parse(r#"{"discord": 5}"#), defaults); // A key that is missing keeps its default; a new address replaces it; empty hides it. - assert_eq!(Links::parse(r#"{"discord": "https://x.y/z"}"#), Links { discord: "https://x.y/z".into(), ..defaults.clone() }); - assert_eq!(Links::parse(r#"{"discord": "", "sponsor": " "}"#), Links { discord: String::new(), sponsor: String::new(), ..defaults.clone() }); + assert_eq!( + Links::parse(r#"{"discord": "https://x.y/z"}"#), + Links { + discord: "https://x.y/z".into(), + ..defaults.clone() + } + ); + assert_eq!( + Links::parse(r#"{"discord": "", "sponsor": " "}"#), + Links { + discord: String::new(), + sponsor: String::new(), + ..defaults.clone() + } + ); // A key this launcher does not know is ignored. assert_eq!(Links::parse(r#"{"mastodon": "https://x.y/z"}"#), defaults); } @@ -1006,18 +1346,125 @@ mod tests { #[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::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::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 = + std::env::temp_dir().join(format!("horizon-launcher-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&versions); + let oracle = "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java"; + let camera = "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java"; + let collision = + "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java"; + let write = |tag: &str, path: &str, text: &str| { + let path = versions.join(tag).join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + }; + let release = |tag: &str, minecraft: &str| { + write(tag, COMPLETE, ""); + let lock = serde_json::json!({"minecraft": {"version": minecraft, "client_sha1": "c", "server_sha1": "s"}}); + write(tag, "research-lock.json", &lock.to_string()); + write(tag, "tools/prepare_native_client.py", "schema 7"); + write(tag, oracle, "heightmap"); + write(tag, collision, "collision"); + write(tag, camera, tag); // Not an exporter: it may change freely. + }; + let prepared = |tag: &str, minecraft: &str| { + let manifest = + serde_json::json!({"schema": 7, "collision_exporters_sha256": {collision: "x"}}); + write( + tag, + &format!(".local/horizon-client/{minecraft}/{RESOURCES_MANIFEST}"), + &manifest.to_string(), + ); + write( + tag, + &format!(".local/horizon-client/{minecraft}/worldgen/biomes.json"), + "{}", + ); + }; + let is_prepared = |tag: &str| { + resources_at(&versions.join(tag)) + .join(RESOURCES_MANIFEST) + .exists() + }; + + release("v2026.10.13", "26.3"); + prepared("v2026.10.13", "26.3"); + release("v2026.10.12", "26.2"); + prepared("v2026.10.12", "26.2"); + release("v2026.10.13.1", "26.3"); + assert_eq!( + reuse_prepared(&versions, "v2026.10.13.1"), + Some("v2026.10.13".into()) + ); + assert!(is_prepared("v2026.10.13.1")); + assert!(resources_at(&versions.join("v2026.10.13.1")) + .join("worldgen/biomes.json") + .exists()); + let left: Vec<_> = fs::read_dir(versions.join("v2026.10.13.1/.local/horizon-client")) + .unwrap() + .flatten() + .map(|e| e.file_name()) + .collect(); + assert_eq!(left, ["26.3"]); + // Already prepared: nothing to do. + assert_eq!(reuse_prepared(&versions, "v2026.10.13.1"), None); + + // Another Minecraft version, a changed exporter or a changed prepare script: prepare again. + release("v2026.10.14", "26.4"); + assert_eq!(reuse_prepared(&versions, "v2026.10.14"), None); + release("v2026.10.15", "26.3"); + write("v2026.10.15", collision, "collision, fixed"); + assert_eq!(reuse_prepared(&versions, "v2026.10.15"), None); + release("v2026.10.16", "26.3"); + write("v2026.10.16", "tools/prepare_native_client.py", "schema 8"); + assert_eq!(reuse_prepared(&versions, "v2026.10.16"), None); + assert!(!is_prepared("v2026.10.15") && !is_prepared("v2026.10.16")); + + // A version an older launcher installed without preparing it is caught up by the sweep + // that starting the window, `versions` and `update` run; the incompatible ones stay as + // they are, and a second sweep has nothing to do. + release("v2026.10.17", "26.3"); + assert_eq!( + reuse_prepared_in(&versions), + [("v2026.10.17".to_string(), "v2026.10.13.1".to_string())] + ); + assert!(is_prepared("v2026.10.17")); + assert!(!is_prepared("v2026.10.15") && !is_prepared("v2026.10.16")); + assert!(reuse_prepared_in(&versions).is_empty()); + let _ = fs::remove_dir_all(&versions); + } + #[test] fn plain_notes() { - let text = markdown_to_text("# Title\n\nSome *words* and [a link](https://x.y).\n\n- one\n- two\n"); - assert_eq!(text, "Title\n\nSome words and a link (https://x.y).\n\n- one\n- two\n"); + let text = markdown_to_text( + "# Title\n\nSome *words* and [a link](https://x.y).\n\n- one\n- two\n", + ); + assert_eq!( + text, + "Title\n\nSome words and a link (https://x.y).\n\n- one\n- two\n" + ); } } diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 83557b4fc..67ace9a82 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -7,7 +7,11 @@ use std::path::PathBuf; use std::process::Command; #[derive(Parser)] -#[command(name = "horizon-launcher", version, about = "Installs, prepares and starts Horizon. Without a subcommand, opens the window.")] +#[command( + name = "horizon-launcher", + version, + about = "Installs, prepares and starts Horizon. Without a subcommand, opens the window." +)] struct Cli { /// Print JSON instead of text, where a command has something to report #[arg(long, global = true)] @@ -115,7 +119,9 @@ fn json(value: serde_json::Value) { /// Runs a game process in this terminal and reports how it ended. fn attached(mut cmd: Command) -> Result<(), String> { - let status = cmd.status().map_err(|e| format!("Could not start {:?}: {e}", cmd.get_program()))?; + let status = cmd + .status() + .map_err(|e| format!("Could not start {:?}: {e}", cmd.get_program()))?; if status.success() { Ok(()) } else { @@ -131,6 +137,13 @@ fn release_json(r: &Release) -> serde_json::Value { } fn execute(command: Cmd, as_json: bool) -> Result<(), String> { + if matches!(command, Cmd::Versions { .. } | Cmd::Update { .. }) { + for (tag, from) in backend::reuse_prepared_everywhere() { + if !as_json { + eprintln!("Prepared {tag} with the resources of {from}."); + } + } + } match command { Cmd::Versions { installed: true } => { let installed = backend::installed(); @@ -141,8 +154,16 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("No version is installed."); } for tag in installed.iter().filter(|_| !as_json) { - let mark = if selected.as_ref() == Some(tag) { "*" } else { " " }; - let state = if backend::is_prepared(tag) { "prepared" } else { "not prepared" }; + let mark = if selected.as_ref() == Some(tag) { + "*" + } else { + " " + }; + let state = if backend::is_prepared(tag) { + "prepared" + } else { + "not prepared" + }; println!("{mark} {tag} {state}"); } } @@ -166,9 +187,17 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { let label = format!("Installing {tag}"); let tag = backend::install_tag(&tag, false, progress(label))?; if as_json { - json(serde_json::json!({ "installed": tag })); + json( + serde_json::json!({ "installed": tag, "prepared": backend::is_prepared(&tag) }), + ); + } else if backend::is_prepared(&tag) { + println!( + "Installed {tag}. It is prepared already, from another installed version." + ); } else { - println!("Installed {tag}. Prepare it next: horizon-launcher prepare --version {tag}"); + println!( + "Installed {tag}. Prepare it next: horizon-launcher prepare --version {tag}" + ); } } Cmd::Remove { tag } => { @@ -182,8 +211,14 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { attached(cmd)?; println!("{tag} is prepared."); } - Cmd::Play { version } => attached(backend::client(&backend::resolve_version(version.as_deref())?)?)?, - Cmd::Server { dir, version, accept_eula } => { + Cmd::Play { version } => attached(backend::client(&backend::resolve_version( + version.as_deref(), + )?)?)?, + Cmd::Server { + dir, + version, + accept_eula, + } => { let tag = backend::resolve_version(version.as_deref())?; let dir = backend::server_dir(dir); // The server inherits this terminal, so typed lines reach its console. @@ -192,10 +227,17 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { Cmd::Notes { tag } => { let r = backend::release_notes(tag.as_deref())?; if as_json { - json(serde_json::json!({ "tag": r.tag, "name": r.name, "date": r.date, "notes": r.body })); + json( + serde_json::json!({ "tag": r.tag, "name": r.name, "date": r.date, "notes": r.body }), + ); } else { let title = if r.name.is_empty() { &r.tag } else { &r.name }; - println!("{title}\n{} {}\n\n{}", r.tag, r.date, backend::markdown_to_text(&r.body)); + println!( + "{title}\n{} {}\n\n{}", + r.tag, + r.date, + backend::markdown_to_text(&r.body) + ); } } Cmd::Next => { @@ -211,7 +253,11 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { if as_json { json(serde_json::to_value(&links).unwrap()); } else { - for (name, url) in [("Discord", &links.discord), ("Sponsor", &links.sponsor), ("Website", &links.website)] { + for (name, url) in [ + ("Discord", &links.discord), + ("Sponsor", &links.sponsor), + ("Website", &links.website), + ] { println!("{name:<8} {}", if url.is_empty() { "(none)" } else { url }); } } @@ -247,7 +293,8 @@ fn update(check: bool, as_json: bool) -> Result<(), String> { None => println!("Horizon: up to date."), Some(r) if check => println!("Horizon: {} is available.", r.tag), Some(r) => { - let tag = backend::install_tag(&r.tag, true, progress(format!("Installing {}", r.tag)))?; + let tag = + backend::install_tag(&r.tag, true, progress(format!("Installing {}", r.tag)))?; println!("Horizon: installed {tag}."); } } @@ -256,7 +303,10 @@ fn update(check: bool, as_json: bool) -> Result<(), String> { Some(r) => { let version = backend::launcher_version(&r.tag).unwrap_or_default(); if check { - println!("Launcher: {version} is available (this is {}).", backend::VERSION); + println!( + "Launcher: {version} is available (this is {}).", + backend::VERSION + ); } else if !backend::self_update_allowed() { println!("Launcher: {version} is available; this build does not replace itself."); } else { diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 402fc3989..3a46184a5 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -6,13 +6,14 @@ mod markdown; mod mcp; mod theme; -use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; use gpui::{ - div, ease_out_quint, img, linear_color_stop, linear_gradient, prelude::*, px, relative, size, Animation, AnimationExt, AnyElement, App, Application, Bounds, - ClickEvent, Context, Div, ElementId, FocusHandle, FontWeight, Hsla, KeyDownEvent, RenderImage, - ObjectFit, PathPromptOptions, ScrollHandle, SharedString, Stateful, Subscription, TitlebarOptions, Window, + div, ease_out_quint, img, linear_color_stop, linear_gradient, prelude::*, px, relative, size, + Animation, AnimationExt, AnyElement, App, Application, Bounds, ClickEvent, Context, Div, + ElementId, FocusHandle, FontWeight, Hsla, KeyDownEvent, ObjectFit, PathPromptOptions, + RenderImage, ScrollHandle, SharedString, Stateful, Subscription, TitlebarOptions, Window, WindowBounds, WindowOptions, }; +use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; use std::borrow::Cow; use std::collections::VecDeque; use std::sync::mpsc::{channel, Receiver, Sender}; @@ -67,9 +68,12 @@ struct Opening { /// The background, decoded before the first frame so the opening never shows without it. fn background_image() -> Arc { - let mut rgba = image::load_from_memory_with_format(include_bytes!("../assets/background.jpg"), image::ImageFormat::Jpeg) - .expect("bundled background") - .into_rgba8(); + let mut rgba = image::load_from_memory_with_format( + include_bytes!("../assets/background.jpg"), + image::ImageFormat::Jpeg, + ) + .expect("bundled background") + .into_rgba8(); // GPUI draws BGRA. for px in rgba.pixels_mut() { px.0.swap(0, 2); @@ -152,7 +156,9 @@ impl Launcher { cx.notify(); }); cx.spawn(async move |this, cx| loop { - cx.background_executor().timer(Duration::from_millis(80)).await; + cx.background_executor() + .timer(Duration::from_millis(80)) + .await; if this.update(cx, |this, cx| this.drain(cx)).is_err() { break; } @@ -166,7 +172,11 @@ impl Launcher { settings.server_dir = Some(backend::data_dir().join("server")); } let installed = backend::installed(); - if settings.selected.as_ref().is_none_or(|s| !installed.contains(s)) { + if settings + .selected + .as_ref() + .is_none_or(|s| !installed.contains(s)) + { settings.selected = installed.first().cloned(); } let mut this = Self { @@ -177,7 +187,11 @@ impl Launcher { opening: (!settings.skip_opening).then(|| { let focus = cx.focus_handle(); window.focus(&focus); - Opening { started: None, reveal: None, focus } + Opening { + started: None, + reveal: None, + focus, + } }), background: background_image(), updates: Updates::default(), @@ -213,6 +227,13 @@ impl Launcher { rx, _appearance: appearance, }; + let tx = this.tx.clone(); + std::thread::spawn(move || { + let reused = backend::reuse_prepared_everywhere(); + if !reused.is_empty() { + let _ = tx.send(Msg::Reused(reused)); + } + }); this.fetch_releases(); this.fetch_roadmap(); this.fetch_links(); @@ -232,32 +253,46 @@ impl Launcher { fn check_updates(&mut self) { self.checked = Some(Instant::now()); let tx = self.tx.clone(); - std::thread::spawn(move || tx.send(Msg::Updates(backend::check_updates()))); + std::thread::spawn(move || { + let _ = tx.send(Msg::Updates(backend::check_updates())); + }); } fn update_launcher(&mut self, release: Release) { - if !backend::self_update_allowed() || matches!(self.self_update, SelfUpdate::Downloading(..) | SelfUpdate::Ready(_)) { + if !backend::self_update_allowed() + || matches!( + self.self_update, + SelfUpdate::Downloading(..) | SelfUpdate::Ready(_) + ) + { return; } - let version = backend::launcher_version(&release.tag).unwrap_or_default().to_string(); + let version = backend::launcher_version(&release.tag) + .unwrap_or_default() + .to_string(); self.self_update = SelfUpdate::Downloading(version, 0.); let tx = self.tx.clone(); std::thread::spawn(move || { let progress = |p| { let _ = tx.send(Msg::LauncherProgress(p)); }; - let _ = tx.send(Msg::LauncherUpdated(backend::self_update(&release, progress))); + let _ = tx.send(Msg::LauncherUpdated(backend::self_update( + &release, progress, + ))); }); } /// Installs the Horizon version the last check found, keeping the player's choice of /// version unless they were on the newest one. fn install_update(&mut self) { - let Some(release) = self.updates.horizon.clone() else { return }; + let Some(release) = self.updates.horizon.clone() else { + return; + }; if self.installing.is_some() { return; } - let select = backend::select_after_update(self.settings.selected.as_deref(), &self.installed); + let select = + backend::select_after_update(self.settings.selected.as_deref(), &self.installed); self.update_install = Some((release.tag.clone(), select)); self.install(&release); } @@ -265,18 +300,24 @@ impl Launcher { fn fetch_releases(&mut self) { self.releases = Load::Loading; let tx = self.tx.clone(); - std::thread::spawn(move || tx.send(Msg::Releases(backend::releases()))); + std::thread::spawn(move || { + let _ = tx.send(Msg::Releases(backend::releases())); + }); } fn fetch_links(&self) { let tx = self.tx.clone(); - std::thread::spawn(move || tx.send(Msg::Links(backend::links()))); + std::thread::spawn(move || { + let _ = tx.send(Msg::Links(backend::links())); + }); } fn fetch_roadmap(&mut self) { self.roadmap = Load::Loading; let tx = self.tx.clone(); - std::thread::spawn(move || tx.send(Msg::Roadmap(backend::roadmap()))); + std::thread::spawn(move || { + let _ = tx.send(Msg::Roadmap(backend::roadmap())); + }); } fn drain(&mut self, cx: &mut Context) { @@ -287,6 +328,8 @@ impl Launcher { Msg::Releases(r) => self.releases = r.map_or_else(Load::Failed, Load::Ready), Msg::Roadmap(r) => self.roadmap = r.map_or_else(Load::Failed, Load::Ready), Msg::Links(links) => self.links = links, + // The page reads is_prepared when drawn; `changed` redraws it. + Msg::Reused(_) => self.installed = backend::installed(), Msg::Progress(tag, p) => { self.bar = (self.bar.1, p); self.installing = Some((tag, p)); @@ -336,7 +379,11 @@ impl Launcher { }; } Msg::Line(job, line) => { - let log = if job == Job::Server { &mut self.server_log } else { &mut self.prepare_log }; + let log = if job == Job::Server { + &mut self.server_log + } else { + &mut self.prepare_log + }; log.push_back(line); if log.len() > LOG_LINES { log.pop_front(); @@ -351,25 +398,32 @@ impl Launcher { Job::Prepare => { self.preparing = false; self.prepare_error = error.map(|e| { - let tail = self.prepare_log.iter().rev().find(|l| !l.trim().is_empty()); + let tail = + self.prepare_log.iter().rev().find(|l| !l.trim().is_empty()); tail.map_or(e.clone(), |t| format!("{e}: {t}")) }); } Job::Client => { self.client = None; self.client_error = error.map(|e| { - let tail = self.prepare_log.iter().rev().find(|l| !l.trim().is_empty()); + let tail = + self.prepare_log.iter().rev().find(|l| !l.trim().is_empty()); tail.map_or(e.clone(), |t| format!("{e}: {t}")) }); } Job::Server => { self.server = None; - let old = self.server_log.iter().any(|l| l.contains("unknown option --dedicated")); + let old = self + .server_log + .iter() + .any(|l| l.contains("unknown option --dedicated")); self.server_error = error.map(|e| { if old { - "This version has no dedicated server. Pick a newer one.".to_string() + "This version has no dedicated server. Pick a newer one." + .to_string() } else { - let tail = self.server_log.iter().rev().find(|l| !l.trim().is_empty()); + let tail = + self.server_log.iter().rev().find(|l| !l.trim().is_empty()); tail.map_or(e.clone(), |t| format!("{e}: {t}")) } }); @@ -387,11 +441,16 @@ impl Launcher { } fn selected(&self) -> Option<&String> { - self.settings.selected.as_ref().filter(|s| self.installed.contains(s)) + self.settings + .selected + .as_ref() + .filter(|s| self.installed.contains(s)) } fn install(&mut self, release: &Release) { - let Some((url, size)) = release.asset.clone() else { return }; + let Some((url, size)) = release.asset.clone() else { + return; + }; let (tag, tx) = (release.tag.clone(), self.tx.clone()); self.installing = Some((tag.clone(), 0.0)); self.bar = (0., 0.); @@ -411,18 +470,23 @@ impl Launcher { } self.confirm_remove = None; self.installed = backend::installed(); - self.settings.selected = Settings::load().selected.or_else(|| self.installed.first().cloned()); + self.settings.selected = Settings::load() + .selected + .or_else(|| self.installed.first().cloned()); } fn prepare(&mut self) { - let Some(tag) = self.selected().cloned() else { return }; + let Some(tag) = self.selected().cloned() else { + return; + }; let Some(minecraft) = self.settings.minecraft_dir.clone() else { self.prepare_error = Some("Choose your Minecraft folder first.".into()); return; }; self.prepare_log.clear(); self.prepare_error = None; - self.prepare_log.push_back("Checking Java, Python and your Minecraft install".into()); + self.prepare_log + .push_back("Checking Java, Python and your Minecraft install".into()); let tx = self.tx.clone(); // The checks may download the server jar, so they run on the thread too. std::thread::spawn(move || { @@ -442,7 +506,9 @@ impl Launcher { } fn play(&mut self) { - let Some(tag) = self.selected().cloned() else { return }; + let Some(tag) = self.selected().cloned() else { + return; + }; match self.mode { Mode::Client => { if self.client.is_some() { @@ -460,14 +526,20 @@ impl Launcher { server.send("stop"); return; } - let Some(folder) = self.settings.server_dir.clone() else { return }; + let Some(folder) = self.settings.server_dir.clone() else { + return; + }; if let Err(e) = std::fs::create_dir_all(&folder) { self.server_error = Some(e.to_string()); return; } self.server_error = None; self.server_log.clear(); - match backend::spawn(Job::Server, backend::server_command(&tag, &folder), self.tx.clone()) { + match backend::spawn( + Job::Server, + backend::server_command(&tag, &folder), + self.tx.clone(), + ) { Ok(r) => self.server = Some(r), Err(e) => self.server_error = Some(e), } @@ -529,7 +601,10 @@ struct HoverState { off: Option<(SharedString, Instant)>, } -static HOVER: Mutex = Mutex::new(HoverState { on: None, off: None }); +static HOVER: Mutex = Mutex::new(HoverState { + on: None, + off: None, +}); fn track_hover(el: Stateful
, id: SharedString) -> Stateful
{ el.on_hover(move |hovered, window, _| { @@ -548,27 +623,47 @@ fn track_hover(el: Stateful
, id: SharedString) -> Stateful
{ /// A layer under an element's content that fades `color` in while it is hovered. fn hover_layer(id: &SharedString, color: Hsla, radius: f32) -> AnyElement { - let layer = div().absolute().top_0().left_0().size_full().rounded(px(radius)); + let layer = div() + .absolute() + .top_0() + .left_0() + .size_full() + .rounded(px(radius)); let state = HOVER.lock().unwrap(); // Each transition gets its own animation id, from when it started, so it plays once. static START: std::sync::OnceLock = std::sync::OnceLock::new(); let start = *START.get_or_init(Instant::now); - let key = |dir: &str, at: Instant| ElementId::named_usize(format!("{id}-{dir}"), (at - start).as_micros() as usize); + let key = |dir: &str, at: Instant| { + ElementId::named_usize(format!("{id}-{dir}"), (at - start).as_micros() as usize) + }; let ease = || Animation::new(theme::QUICK).with_easing(ease_out_quint()); if let Some((_, at)) = state.on.as_ref().filter(|(h, _)| h == id) { return layer - .with_animation(key("in", *at), ease(), move |d, t| d.bg(color.opacity(color.a * t))) + .with_animation(key("in", *at), ease(), move |d, t| { + d.bg(color.opacity(color.a * t)) + }) .into_any_element(); } - if let Some((_, at)) = state.off.as_ref().filter(|(h, at)| h == id && at.elapsed() < theme::QUICK) { + if let Some((_, at)) = state + .off + .as_ref() + .filter(|(h, at)| h == id && at.elapsed() < theme::QUICK) + { return layer - .with_animation(key("out", *at), ease(), move |d, t| d.bg(color.opacity(color.a * (1. - t)))) + .with_animation(key("out", *at), ease(), move |d, t| { + d.bg(color.opacity(color.a * (1. - t))) + }) .into_any_element(); } layer.into_any_element() } -fn button(id: impl Into, label: impl Into, kind: Kind, t: &Theme) -> Stateful
{ +fn button( + id: impl Into, + label: impl Into, + kind: Kind, + t: &Theme, +) -> Stateful
{ let id: SharedString = id.into(); let t = *t; let hover = match kind { @@ -592,9 +687,20 @@ fn button(id: impl Into, label: impl Into, kind: Kin .child(div().relative().child(label.into())); let base = track_hover(base, id); match kind { - Kind::Primary => base.bg(t.accent).text_color(t.on_accent).active(|s| s.opacity(theme::PRESSED)), - Kind::Secondary => base.border_1().border_color(t.border).bg(t.raised).text_color(t.text).active(|s| s.opacity(theme::PRESSED_SOFT)), - Kind::Ghost => base.text_color(t.muted).hover(move |s| s.text_color(t.text)).active(|s| s.opacity(theme::PRESSED_SOFT)), + Kind::Primary => base + .bg(t.accent) + .text_color(t.on_accent) + .active(|s| s.opacity(theme::PRESSED)), + Kind::Secondary => base + .border_1() + .border_color(t.border) + .bg(t.raised) + .text_color(t.text) + .active(|s| s.opacity(theme::PRESSED_SOFT)), + Kind::Ghost => base + .text_color(t.muted) + .hover(move |s| s.text_color(t.text)) + .active(|s| s.opacity(theme::PRESSED_SOFT)), } } @@ -610,11 +716,17 @@ fn switch(id: &'static str, on: bool, t: &Theme) -> Stateful
{ .cursor_pointer() .bg(if on { t.accent } else { t.border }) .child( - div().absolute().top(px(2.)).size(px(16.)).rounded_full().bg(gpui::white()).with_animation( - ElementId::named_usize(id, on as usize), - Animation::new(theme::QUICK).with_easing(ease_out_quint()), - move |d, p| d.left(px(if on { 2. + 14. * p } else { 16. - 14. * p })), - ), + div() + .absolute() + .top(px(2.)) + .size(px(16.)) + .rounded_full() + .bg(gpui::white()) + .with_animation( + ElementId::named_usize(id, on as usize), + Animation::new(theme::QUICK).with_easing(ease_out_quint()), + move |d, p| d.left(px(if on { 2. + 14. * p } else { 16. - 14. * p })), + ), ) } @@ -635,7 +747,12 @@ fn page_header(title: &str, description: &str, t: &Theme) -> Div { .text_color(t.text) .child(title.to_string()), ) - .child(div().text_size(px(theme::BODY)).text_color(t.muted).child(description.to_string())) + .child( + div() + .text_size(px(theme::BODY)) + .text_color(t.muted) + .child(description.to_string()), + ) } fn divider(t: &Theme) -> Div { @@ -649,8 +766,22 @@ fn row(label: &str, value: impl IntoElement, action: Option>, t: & .items_center() .gap(px(16.)) .py(px(12.)) - .child(div().w(px(theme::ROW_LABEL)).flex_none().text_size(px(13.)).text_color(t.muted).child(label.to_string())) - .child(div().flex_1().min_w_0().text_size(px(13.)).text_color(t.text).child(value)) + .child( + div() + .w(px(theme::ROW_LABEL)) + .flex_none() + .text_size(px(13.)) + .text_color(t.muted) + .child(label.to_string()), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(13.)) + .text_color(t.text) + .child(value), + ) .children(action) } @@ -665,7 +796,14 @@ fn notice(text: String, t: &Theme) -> Div { .text_size(px(13.)) .line_height(px(19.)) .text_color(t.text) - .child(div().flex_none().mt(px(6.)).size(px(6.)).rounded_full().bg(t.danger)) + .child( + div() + .flex_none() + .mt(px(6.)) + .size(px(6.)) + .rounded_full() + .bg(t.danger), + ) .child(div().flex_1().min_w_0().child(text)) } @@ -702,7 +840,10 @@ impl Launcher { const STEP: f32 = theme::CONTROL + 2.; let mut nav = div().relative().flex().flex_col().gap(px(2.)); // The selection is one pill that slides to the chosen item. - let (from, to) = (self.previous_page.index() as f32 * STEP, self.page.index() as f32 * STEP); + let (from, to) = ( + self.previous_page.index() as f32 * STEP, + self.page.index() as f32 * STEP, + ); nav = nav.child( div() .absolute() @@ -732,11 +873,15 @@ impl Launcher { .rounded(px(theme::RADIUS)) .text_size(px(theme::BODY)) .cursor_pointer() - .when(!active, |d| d.child(hover_layer(&id, t.hover.opacity(0.7), theme::RADIUS))) + .when(!active, |d| { + d.child(hover_layer(&id, t.hover.opacity(0.7), theme::RADIUS)) + }) .child( div() .relative() - .when(active, |d| d.text_color(t.text).font_weight(FontWeight::MEDIUM)) + .when(active, |d| { + d.text_color(t.text).font_weight(FontWeight::MEDIUM) + }) .when(!active, |d| d.text_color(t.muted)) .child(label), ) @@ -808,7 +953,15 @@ impl Launcher { ) .child(nav) .child(div().flex_1()) - .child(div().px(px(10.)).text_size(px(theme::SMALL)).text_color(t.faint).children(discord).children(website).child(footer)) + .child( + div() + .px(px(10.)) + .text_size(px(theme::SMALL)) + .text_color(t.faint) + .children(discord) + .children(website) + .child(footer), + ) } fn segmented(&self, cx: &mut Context) -> Div { @@ -825,9 +978,15 @@ impl Launcher { .text_size(px(13.)) .cursor_pointer() .when(active, |d| { - d.bg(t.bg).border_1().border_color(t.border).text_color(t.text).font_weight(FontWeight::MEDIUM) + d.bg(t.bg) + .border_1() + .border_color(t.border) + .text_color(t.text) + .font_weight(FontWeight::MEDIUM) + }) + .when(!active, |d| { + d.text_color(t.muted).hover(move |s| s.text_color(t.text)) }) - .when(!active, |d| d.text_color(t.muted).hover(move |s| s.text_color(t.text))) .child(label) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { this.mode = mode; @@ -848,7 +1007,10 @@ impl Launcher { fn picker(&self, cx: &mut Context) -> Div { let t = self.theme; - let label = self.selected().cloned().unwrap_or_else(|| "No version".into()); + let label = self + .selected() + .cloned() + .unwrap_or_else(|| "No version".into()); let mut wrap = div().relative().child( div() .id("picker") @@ -902,7 +1064,9 @@ impl Launcher { .cursor_pointer() .hover(move |s| s.bg(t.hover)) .child(tag.clone()) - .when(selected, |d| d.child(div().size(px(6.)).rounded_full().bg(t.accent))) + .when(selected, |d| { + d.child(div().size(px(6.)).rounded_full().bg(t.accent)) + }) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { this.settings.selected = Some(tag.clone()); this.settings.save(); @@ -937,16 +1101,20 @@ impl Launcher { fn play_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; - let header = page_header("Play", "Start the game, or run a server for others to join.", &t); + let header = page_header( + "Play", + "Start the game, or run a server for others to join.", + &t, + ); let Some(tag) = self.selected().cloned() else { return div().flex().flex_col().gap(px(24.)).child(header).child( centered("No version installed yet.", &t).child( - button("go-versions", "Choose a version", Kind::Secondary, &t).on_click(cx.listener( - |this, _: &ClickEvent, _, cx| { + button("go-versions", "Choose a version", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { this.go(Page::Versions); cx.notify(); - }, - )), + }), + ), ), ); }; @@ -963,11 +1131,26 @@ impl Launcher { (Mode::Server, false) => "Start server", (Mode::Server, true) => "Stop server", }; - let kind = if self.mode == Mode::Server && running { Kind::Secondary } else { Kind::Primary }; - let mut play = - button("play", play_label, kind, &t).min_w(px(120.)).h(px(40.)).px(px(24.)).text_size(px(theme::LARGE)); - let eula = self.settings.server_dir.as_ref().is_some_and(|d| backend::eula_agreed(d)); - if !prepared || self.preparing || (self.mode == Mode::Client && running) || (self.mode == Mode::Server && !eula) { + let kind = if self.mode == Mode::Server && running { + Kind::Secondary + } else { + Kind::Primary + }; + let mut play = button("play", play_label, kind, &t) + .min_w(px(120.)) + .h(px(40.)) + .px(px(24.)) + .text_size(px(theme::LARGE)); + let eula = self + .settings + .server_dir + .as_ref() + .is_some_and(|d| backend::eula_agreed(d)); + if !prepared + || self.preparing + || (self.mode == Mode::Client && running) + || (self.mode == Mode::Server && !eula) + { play = disabled(play); } else { play = play.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { @@ -981,17 +1164,34 @@ impl Launcher { .items_center() .justify_between() .child(self.segmented(cx)) - .child(div().flex().items_center().gap(px(8.)).child(self.picker(cx)).child(play)); + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.picker(cx)) + .child(play), + ); let resources_value = if self.preparing { div().text_color(t.muted).child("Preparing…") } else if prepared { div().child(format!("Prepared for Minecraft {version}")) } else { - div().text_color(t.muted).child(format!("Not prepared. Horizon needs the files of your own Minecraft {version}.")) + div().text_color(t.muted).child(format!( + "Not prepared. Horizon needs the files of your own Minecraft {version}." + )) }; - let mut prepare = button("prepare", if prepared { "Prepare again" } else { "Prepare" }, - if prepared { Kind::Ghost } else { Kind::Secondary }, &t); + let mut prepare = button( + "prepare", + if prepared { "Prepare again" } else { "Prepare" }, + if prepared { + Kind::Ghost + } else { + Kind::Secondary + }, + &t, + ); if self.preparing { prepare = disabled(prepare); } else { @@ -1000,11 +1200,14 @@ impl Launcher { cx.notify(); })); } - let minecraft = self - .settings - .minecraft_dir - .as_deref() - .map_or_else(|| div().text_color(t.muted).child("Not found. Choose the official launcher's game folder."), |p| div().child(short(p))); + let minecraft = self.settings.minecraft_dir.as_deref().map_or_else( + || { + div() + .text_color(t.muted) + .child("Not found. Choose the official launcher's game folder.") + }, + |p| div().child(short(p)), + ); let mut rows = div() .flex() .flex_col() @@ -1014,41 +1217,52 @@ impl Launcher { .child(row( "Minecraft folder", minecraft, - Some(button("choose-mc", "Choose…", Kind::Ghost, &t).on_click(cx.listener( - |this, _: &ClickEvent, _, cx| this.choose_folder(false, cx), - ))), + Some(button("choose-mc", "Choose…", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| this.choose_folder(false, cx)), + )), &t, )); if self.mode == Mode::Server { - let folder = self.settings.server_dir.as_deref().map(short).unwrap_or_default(); + let folder = self + .settings + .server_dir + .as_deref() + .map(short) + .unwrap_or_default(); rows = rows.child(divider(&t)).child(row( "Server folder", div().child(folder), - Some(button("choose-server", "Choose…", Kind::Ghost, &t).on_click(cx.listener( - |this, _: &ClickEvent, _, cx| this.choose_folder(true, cx), - ))), + Some( + button("choose-server", "Choose…", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| this.choose_folder(true, cx)), + ), + ), &t, )); let value = if eula { div().child("Agreed") } else { - div().text_color(t.muted).child("Running a server needs your agreement to the Minecraft EULA.") + div() + .text_color(t.muted) + .child("Running a server needs your agreement to the Minecraft EULA.") }; let mut actions = div().flex().gap(px(4.)).child( - button("eula-read", "Read", Kind::Ghost, &t) - .on_click(cx.listener(|_, _: &ClickEvent, _, cx| cx.open_url("https://aka.ms/MinecraftEULA"))), + button("eula-read", "Read", Kind::Ghost, &t).on_click(cx.listener( + |_, _: &ClickEvent, _, cx| cx.open_url("https://aka.ms/MinecraftEULA"), + )), ); if !eula { - actions = actions.child(button("eula-agree", "Agree", Kind::Secondary, &t).on_click(cx.listener( - |this, _: &ClickEvent, _, cx| { - if let Some(dir) = &this.settings.server_dir { - if let Err(e) = backend::agree_eula(dir) { - this.server_error = Some(e); + actions = + actions.child(button("eula-agree", "Agree", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some(dir) = &this.settings.server_dir { + if let Err(e) = backend::agree_eula(dir) { + this.server_error = Some(e); + } } - } - cx.notify(); - }, - ))); + cx.notify(); + }), + )); } rows = rows.child(divider(&t)).child( div() @@ -1056,15 +1270,35 @@ impl Launcher { .items_center() .gap(px(16.)) .py(px(12.)) - .child(div().w(px(150.)).flex_none().text_size(px(13.)).text_color(t.muted).child("Minecraft EULA")) - .child(div().flex_1().min_w_0().text_size(px(13.)).text_color(t.text).child(value)) + .child( + div() + .w(px(150.)) + .flex_none() + .text_size(px(13.)) + .text_color(t.muted) + .child("Minecraft EULA"), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(13.)) + .text_color(t.text) + .child(value), + ) .child(actions), ); } rows = rows.child(divider(&t)); let _ = header; - let mut page = div().flex().flex_col().gap(px(24.)).child(hero).child(actions).child(rows); + let mut page = div() + .flex() + .flex_col() + .gap(px(24.)) + .child(hero) + .child(actions) + .child(rows); if self.preparing { let last = self.prepare_log.back().cloned().unwrap_or_default(); page = page.child( @@ -1073,7 +1307,13 @@ impl Launcher { .flex_col() .gap(px(10.)) .child(progress_bar(None, &t)) - .child(div().text_size(px(12.)).text_color(t.faint).truncate().child(last)) + .child( + div() + .text_size(px(12.)) + .text_color(t.faint) + .truncate() + .child(last), + ) .child( div() .text_size(px(12.)) @@ -1102,21 +1342,34 @@ impl Launcher { fn hero(&self, tag: &str, version: &str, prepared: bool, cx: &mut Context) -> Div { let t = self.theme; let summary = match &self.releases { - Load::Ready(list) => list.iter().find(|r| r.tag == tag).and_then(|r| backend::notes_summary(&r.body)), + Load::Ready(list) => list + .iter() + .find(|r| r.tag == tag) + .and_then(|r| backend::notes_summary(&r.body)), _ => None, }; let status = format!( "Minecraft {version} · {}", if prepared { "Ready" } else { "Needs preparing" } ); - let title = if self.mode == Mode::Server { "Horizon server" } else { "Horizon" }; + let title = if self.mode == Mode::Server { + "Horizon server" + } else { + "Horizon" + }; let mut hero = div() .flex() .flex_col() .gap(px(12.)) .pt(px(28.)) .pb(px(4.)) - .child(div().text_size(px(theme::SMALL)).font_weight(FontWeight::MEDIUM).text_color(t.faint).child(status)) + .child( + div() + .text_size(px(theme::SMALL)) + .font_weight(FontWeight::MEDIUM) + .text_color(t.faint) + .child(status), + ) .child( div() .font_family(theme::DISPLAY) @@ -1147,7 +1400,14 @@ impl Launcher { .child(div().size(px(6.)).rounded_full().bg(t.accent)) .child(format!("{} available", release.tag)); hero = hero.child(match installing { - Some((_, p)) => line.child(div().w(px(120.)).flex().child(progress_bar(Some(self.bar), &t))).child(format!("{:.0}%", p * 100.)), + Some((_, p)) => line + .child( + div() + .w(px(120.)) + .flex() + .child(progress_bar(Some(self.bar), &t)), + ) + .child(format!("{:.0}%", p * 100.)), None => line.child( div() .id("install-update") @@ -1168,16 +1428,16 @@ impl Launcher { fn settings_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; - let toggle = switch("auto-install", self.settings.auto_install(), &t).on_click(cx.listener( - |this, _: &ClickEvent, _, cx| { + let toggle = switch("auto-install", self.settings.auto_install(), &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { this.settings.install_new_versions = Some(!this.settings.auto_install()); this.settings.save(); if this.settings.auto_install() { this.install_update(); } cx.notify(); - }, - )); + }), + ); let opening = switch("opening", !self.settings.skip_opening, &t).on_click(cx.listener( |this, _: &ClickEvent, _, cx| { this.settings.skip_opening = !this.settings.skip_opening; @@ -1195,8 +1455,12 @@ impl Launcher { .bg(t.raised) .border_1() .border_color(t.border) - .children([(backend::MenuStyle::Horizon, "Horizon"), (backend::MenuStyle::Classic, "Classic")].map( - |(style, label)| { + .children( + [ + (backend::MenuStyle::Horizon, "Horizon"), + (backend::MenuStyle::Classic, "Classic"), + ] + .map(|(style, label)| { let active = self.menu_style == style; div() .id(label) @@ -1208,9 +1472,15 @@ impl Launcher { .text_size(px(13.)) .cursor_pointer() .when(active, |d| { - d.bg(t.bg).border_1().border_color(t.border).text_color(t.text).font_weight(FontWeight::MEDIUM) + d.bg(t.bg) + .border_1() + .border_color(t.border) + .text_color(t.text) + .font_weight(FontWeight::MEDIUM) + }) + .when(!active, |d| { + d.text_color(t.muted).hover(move |s| s.text_color(t.text)) }) - .when(!active, |d| d.text_color(t.muted).hover(move |s| s.text_color(t.text))) .child(label) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { if backend::set_menu_style(style).is_ok() { @@ -1218,52 +1488,75 @@ impl Launcher { } cx.notify(); })) - }, - )); + }), + ); let menu_note = div().flex().flex_col().gap(px(2.)).child("Menu style").child( div().text_size(px(theme::SMALL)).text_color(t.muted).child( "Classic is vanilla's own screens, with no way back inside the game: switch back here. Applies the next time the game starts.", ), ); - let auto = div() - .flex() - .flex_col() - .gap(px(2.)) - .child("Install new versions automatically") - .child(div().text_size(px(theme::SMALL)).text_color(t.muted).child( - "Your selected version only changes if you were playing the newest one.", - )); + let auto = + div() + .flex() + .flex_col() + .gap(px(2.)) + .child("Install new versions automatically") + .child(div().text_size(px(theme::SMALL)).text_color(t.muted).child( + "Your selected version only changes if you were playing the newest one.", + )); let horizon = match (&self.updates.horizon, &self.update_error) { (Some(r), _) => div().child(format!("{} available", r.tag)), (None, Some(e)) => div().text_color(t.muted).child(e.clone()), (None, None) if self.checked.is_some() => div().child("Up to date"), _ => div().text_color(t.muted).child("Checking…"), }; - let horizon_action = self.updates.horizon.as_ref().filter(|_| self.installing.is_none()).map(|_| { - button("settings-install", "Install", Kind::Secondary, &t).on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.install_update(); - cx.notify(); - })) - }); + let horizon_action = self + .updates + .horizon + .as_ref() + .filter(|_| self.installing.is_none()) + .map(|_| { + button("settings-install", "Install", Kind::Secondary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.install_update(); + cx.notify(); + }, + )) + }); let launcher = match &self.self_update { - SelfUpdate::Downloading(v, p) => format!("{} · downloading {v}, {:.0}%", backend::VERSION, p * 100.), - SelfUpdate::Ready(v) => format!("{} · {v} is ready, restart to use it", backend::VERSION), + SelfUpdate::Downloading(v, p) => { + format!("{} · downloading {v}, {:.0}%", backend::VERSION, p * 100.) + } + SelfUpdate::Ready(v) => { + format!("{} · {v} is ready, restart to use it", backend::VERSION) + } SelfUpdate::Failed(e) => format!("{} · the update failed: {e}", backend::VERSION), SelfUpdate::Idle => match &self.updates.launcher { - Some(r) => format!("{} · {} available", backend::VERSION, backend::launcher_version(&r.tag).unwrap_or_default()), - None if self.checked.is_some() && self.update_error.is_none() => format!("{} · up to date", backend::VERSION), + Some(r) => format!( + "{} · {} available", + backend::VERSION, + backend::launcher_version(&r.tag).unwrap_or_default() + ), + None if self.checked.is_some() && self.update_error.is_none() => { + format!("{} · up to date", backend::VERSION) + } None => backend::VERSION.to_string(), }, }; let launcher_action = match &self.self_update { SelfUpdate::Ready(_) => Some( - button("restart-settings", "Restart", Kind::Secondary, &t).on_click(|_, _, _| backend::restart()), + button("restart-settings", "Restart", Kind::Secondary, &t) + .on_click(|_, _, _| backend::restart()), ), SelfUpdate::Downloading(..) => None, - _ => Some(button("check", "Check now", Kind::Ghost, &t).on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.check_updates(); - cx.notify(); - }))), + _ => Some( + button("check", "Check now", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.check_updates(); + cx.notify(); + }, + )), + ), }; let agents = div() .flex() @@ -1299,7 +1592,11 @@ impl Launcher { .flex() .flex_col() .gap(px(24.)) - .child(page_header("Settings", "Updates, menus, and the launcher itself.", &t)) + .child(page_header( + "Settings", + "Updates, menus, and the launcher itself.", + &t, + )) .child( div() .flex() @@ -1307,7 +1604,12 @@ impl Launcher { .child(divider(&t)) .child(row("Updates", auto, Some(toggle), &t)) .child(divider(&t)) - .child(row("Opening", div().child("Show opening animation"), Some(opening), &t)) + .child(row( + "Opening", + div().child("Show opening animation"), + Some(opening), + &t, + )) .child(divider(&t)) .child(row("Game menus", menu_note, Some(menus), &t)) .child(divider(&t)) @@ -1315,7 +1617,12 @@ impl Launcher { .child(divider(&t)) .child(row("Launcher", div().child(launcher), launcher_action, &t)) .child(divider(&t)) - .child(row("Data folder", div().child(short(&backend::data_dir())), None, &t)) + .child(row( + "Data folder", + div().child(short(&backend::data_dir())), + None, + &t, + )) .child(divider(&t)), ) .child(agents) @@ -1337,7 +1644,11 @@ impl Launcher { .line_height(px(18.)) .text_color(t.muted) .when(self.server_log.is_empty(), |d| { - d.child(div().text_color(t.faint).child(if running { "Starting…" } else { "The server's output shows here." })) + d.child(div().text_color(t.faint).child(if running { + "Starting…" + } else { + "The server's output shows here." + })) }) .children(lines); let input = div() @@ -1354,7 +1665,11 @@ impl Launcher { .cursor_text() .child(div().text_color(t.faint).mr(px(8.)).child(">")) .child(if self.input.is_empty() && !focused { - div().text_color(t.faint).child(if running { "Type a command, e.g. list" } else { "Start the server to send commands" }) + div().text_color(t.faint).child(if running { + "Type a command, e.g. list" + } else { + "Start the server to send commands" + }) } else { div().text_color(t.text).child(self.input.clone()) }) @@ -1403,18 +1718,26 @@ impl Launcher { .items_center() .gap(px(8.)) .text_color(t.muted) - .child(div().size(px(6.)).rounded_full().bg(if running { t.accent } else { t.faint })) + .child(div().size(px(6.)).rounded_full().bg(if running { + t.accent + } else { + t.faint + })) .child(if running { "Running" } else { "Stopped" }), ) .when(running, |d| { - d.child(button("kill", "Force stop", Kind::Ghost, &t).h(px(24.)).px(px(8.)).text_size(px(12.)).on_click( - cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some(s) = &this.server { - s.kill(); - } - cx.notify(); - }), - )) + d.child( + button("kill", "Force stop", Kind::Ghost, &t) + .h(px(24.)) + .px(px(8.)) + .text_size(px(12.)) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some(s) = &this.server { + s.kill(); + } + cx.notify(); + })), + ) }), ) .child(log) @@ -1423,16 +1746,22 @@ impl Launcher { fn versions_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; - let header = page_header("Versions", "Builds from GitHub. Each one installs into its own folder.", &t); + let header = page_header( + "Versions", + "Builds from GitHub. Each one installs into its own folder.", + &t, + ); let page = div().flex().flex_col().gap(px(24.)).child(header); let releases = match &self.releases { Load::Loading => return page.child(centered("Loading releases…", &t)), Load::Failed(e) => { return page.child(centered(&format!("Couldn't load releases. {e}"), &t).child( - button("retry", "Try again", Kind::Secondary, &t).on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.fetch_releases(); - cx.notify(); - })), + button("retry", "Try again", Kind::Secondary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.fetch_releases(); + cx.notify(); + }, + )), )) } Load::Ready(r) if r.is_empty() => return page.child(centered("No releases yet.", &t)), @@ -1447,68 +1776,105 @@ impl Launcher { if let Some((_, size)) = release.asset { meta.push(megabytes(size)); } - let title = if release.name.is_empty() { tag.clone() } else { release.name.clone() }; - let right: gpui::AnyElement = if let Some((_, p)) = self.installing.as_ref().filter(|(t, _)| *t == tag) { - div() - .flex() - .items_center() - .gap(px(10.)) - .w(px(180.)) - .child(progress_bar(Some(self.bar), &t)) - .child(div().w(px(36.)).text_size(px(12.)).text_color(t.muted).child(format!("{:.0}%", p * 100.))) - .into_any_element() - } else if installed { - let confirming = self.confirm_remove.as_ref() == Some(&tag); - let (t1, t2) = (tag.clone(), tag.clone()); - div() - .flex() - .items_center() - .gap(px(4.)) - .when(!selected && !confirming, |d| { - d.child(button(format!("use-{tag}"), "Use", Kind::Ghost, &t).on_click(cx.listener( - move |this, _: &ClickEvent, _, cx| { - this.settings.selected = Some(t1.clone()); - this.settings.save(); - cx.notify(); - }, - ))) - }) - .when(selected && !confirming, |d| { - d.child(div().px(px(12.)).text_size(px(13.)).text_color(t.faint).child("In use")) - }) - .child( - button( - format!("remove-{tag}"), - if confirming { "Remove for good" } else { "Remove" }, - if confirming { Kind::Secondary } else { Kind::Ghost }, - &t, - ) - .when(confirming, |b| b.text_color(t.danger)) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - if this.confirm_remove.as_ref() == Some(&t2) { - this.remove(&t2); - } else { - this.confirm_remove = Some(t2.clone()); - } - cx.notify(); - })), - ) - .into_any_element() - } else if release.asset.is_none() { - div().text_size(px(13.)).text_color(t.faint).child("No build for this platform").into_any_element() + let title = if release.name.is_empty() { + tag.clone() } else { - let mut b = button(format!("install-{tag}"), "Install", Kind::Secondary, &t); - if self.installing.is_some() { - b = disabled(b); - } else { - b = b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.install(&release); - cx.notify(); - })); - } - b.into_any_element() + release.name.clone() }; - let error = self.install_error.as_ref().filter(|(t, _)| *t == tag).map(|(_, e)| e.clone()); + let right: gpui::AnyElement = + if let Some((_, p)) = self.installing.as_ref().filter(|(t, _)| *t == tag) { + div() + .flex() + .items_center() + .gap(px(10.)) + .w(px(180.)) + .child(progress_bar(Some(self.bar), &t)) + .child( + div() + .w(px(36.)) + .text_size(px(12.)) + .text_color(t.muted) + .child(format!("{:.0}%", p * 100.)), + ) + .into_any_element() + } else if installed { + let confirming = self.confirm_remove.as_ref() == Some(&tag); + let (t1, t2) = (tag.clone(), tag.clone()); + div() + .flex() + .items_center() + .gap(px(4.)) + .when(!selected && !confirming, |d| { + d.child( + button(format!("use-{tag}"), "Use", Kind::Ghost, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.settings.selected = Some(t1.clone()); + this.settings.save(); + cx.notify(); + }), + ), + ) + }) + .when(selected && !confirming, |d| { + d.child( + div() + .px(px(12.)) + .text_size(px(13.)) + .text_color(t.faint) + .child("In use"), + ) + }) + .child( + button( + format!("remove-{tag}"), + if confirming { + "Remove for good" + } else { + "Remove" + }, + if confirming { + Kind::Secondary + } else { + Kind::Ghost + }, + &t, + ) + .when(confirming, |b| b.text_color(t.danger)) + .on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + if this.confirm_remove.as_ref() == Some(&t2) { + this.remove(&t2); + } else { + this.confirm_remove = Some(t2.clone()); + } + cx.notify(); + }, + )), + ) + .into_any_element() + } else if release.asset.is_none() { + div() + .text_size(px(13.)) + .text_color(t.faint) + .child("No build for this platform") + .into_any_element() + } else { + let mut b = button(format!("install-{tag}"), "Install", Kind::Secondary, &t); + if self.installing.is_some() { + b = disabled(b); + } else { + b = b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.install(&release); + cx.notify(); + })); + } + b.into_any_element() + }; + let error = self + .install_error + .as_ref() + .filter(|(t, _)| *t == tag) + .map(|(_, e)| e.clone()); list = list .child( div() @@ -1533,7 +1899,13 @@ impl Launcher { .flex() .items_center() .gap(px(8.)) - .child(div().text_size(px(13.5)).text_color(t.text).truncate().child(title)) + .child( + div() + .text_size(px(13.5)) + .text_color(t.text) + .truncate() + .child(title), + ) .when(installed, |d| { d.child( div() @@ -1547,7 +1919,12 @@ impl Launcher { ) }), ) - .child(div().text_size(px(12.)).text_color(t.faint).child(meta.join(" · "))), + .child( + div() + .text_size(px(12.)) + .text_color(t.faint) + .child(meta.join(" · ")), + ), ) .child(right), ) @@ -1560,49 +1937,61 @@ impl Launcher { fn notes_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; - let sponsor = (!self.links.sponsor.is_empty()).then(|| div() - .flex() - .items_center() - .justify_between() - .gap(px(16.)) - .p(px(16.)) - .rounded(px(8.)) - .border_1() - .border_color(t.border) - .child( - div() - .flex() - .flex_col() - .gap(px(2.)) - .child(div().text_size(px(13.)).text_color(t.text).child("Support the work below")) - .child( - div() - .text_size(px(12.5)) - .text_color(t.muted) - .child("Horizon is built in the open. Sponsors fund the next release."), - ), - ) - .child(button("sponsor", "Sponsor on GitHub", Kind::Secondary, &t).on_click({ - let url = self.links.sponsor.clone(); - move |_: &ClickEvent, _, cx| cx.open_url(&url) - }))); + let sponsor = (!self.links.sponsor.is_empty()).then(|| { + div() + .flex() + .items_center() + .justify_between() + .gap(px(16.)) + .p(px(16.)) + .rounded(px(8.)) + .border_1() + .border_color(t.border) + .child( + div() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .text_size(px(13.)) + .text_color(t.text) + .child("Support the work below"), + ) + .child(div().text_size(px(12.5)).text_color(t.muted).child( + "Horizon is built in the open. Sponsors fund the next release.", + )), + ) + .child( + button("sponsor", "Sponsor on GitHub", Kind::Secondary, &t).on_click({ + let url = self.links.sponsor.clone(); + move |_: &ClickEvent, _, cx| cx.open_url(&url) + }), + ) + }); let page = div() .flex() .flex_col() .gap(px(24.)) - .child(page_header("Patch notes", "What changed in each release, newest first.", &t)) + .child(page_header( + "Patch notes", + "What changed in each release, newest first.", + &t, + )) .children(sponsor); let releases = match &self.releases { Load::Loading => return page.child(centered("Loading patch notes…", &t)), Load::Failed(e) => { - return page.child(centered(&format!("Couldn't load patch notes. {e}"), &t).child( - button("retry-notes", "Try again", Kind::Secondary, &t).on_click(cx.listener( - |this, _: &ClickEvent, _, cx| { - this.fetch_releases(); - cx.notify(); - }, - )), - )) + return page.child( + centered(&format!("Couldn't load patch notes. {e}"), &t).child( + button("retry-notes", "Try again", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.fetch_releases(); + cx.notify(); + }), + ), + ), + ) } Load::Ready(r) => r.clone(), }; @@ -1628,12 +2017,26 @@ impl Launcher { .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .text_color(t.text) - .child(if release.name.is_empty() { release.tag.clone() } else { release.name.clone() }), + .child(if release.name.is_empty() { + release.tag.clone() + } else { + release.name.clone() + }), ) - .child(div().flex_none().text_size(px(12.)).text_color(t.faint).child(release.date.clone())), + .child( + div() + .flex_none() + .text_size(px(12.)) + .text_color(t.faint) + .child(release.date.clone()), + ), ) .child(if release.body.trim().is_empty() { - div().text_size(px(13.)).text_color(t.faint).child("No notes for this release.").into_any_element() + div() + .text_size(px(13.)) + .text_color(t.faint) + .child("No notes for this release.") + .into_any_element() } else { markdown::render(&release.body, &t) }), @@ -1644,11 +2047,11 @@ impl Launcher { fn next_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; - let page = div() - .flex() - .flex_col() - .gap(px(24.)) - .child(page_header("What's next", "The roadmap, from the README on GitHub.", &t)); + let page = div().flex().flex_col().gap(px(24.)).child(page_header( + "What's next", + "The roadmap, from the README on GitHub.", + &t, + )); match &self.roadmap { Load::Loading => page.child(centered("Loading the roadmap…", &t)), Load::Failed(e) => page.child(centered(e, &t).child( @@ -1666,8 +2069,19 @@ impl Launcher { /// A thin bar. A known fraction eases from its previous value; an unknown one shuttles slowly. fn progress_bar(fraction: Option<(f32, f32)>, t: &Theme) -> Div { - let bar = div().absolute().top_0().h(px(4.)).rounded_full().bg(t.accent); - let track = div().relative().flex_1().h(px(4.)).rounded_full().bg(t.border).overflow_hidden(); + let bar = div() + .absolute() + .top_0() + .h(px(4.)) + .rounded_full() + .bg(t.accent); + let track = div() + .relative() + .flex_1() + .h(px(4.)) + .rounded_full() + .bg(t.border) + .overflow_hidden(); match fraction { Some((from, to)) => { let (from, to) = (from.clamp(0.02, 1.), to.clamp(0.02, 1.)); @@ -1677,11 +2091,15 @@ fn progress_bar(fraction: Option<(f32, f32)>, t: &Theme) -> Div { move |d, p| d.w(relative(from + (to - from) * p)), )) } - None => track.child(bar.w(relative(0.3)).with_animation( - "shuttle", - Animation::new(Duration::from_millis(1600)).repeat().with_easing(gpui::ease_in_out), - |d, p| d.left(relative(-0.3 + 1.3 * p)), - )), + None => track.child( + bar.w(relative(0.3)).with_animation( + "shuttle", + Animation::new(Duration::from_millis(1600)) + .repeat() + .with_easing(gpui::ease_in_out), + |d, p| d.left(relative(-0.3 + 1.3 * p)), + ), + ), } } @@ -1697,11 +2115,16 @@ impl Render for Launcher { Page::Settings => self.settings_page(cx), }; // The new page fades in and rises a few pixels. - let content = div().relative().w_full().max_w(px(760.)).child(content).with_animation( - ElementId::named_usize("page", self.switches), - Animation::new(theme::MOVE).with_easing(ease_out_quint()), - |d, p| d.opacity(p).top(px(8. * (1. - p))), - ); + let content = div() + .relative() + .w_full() + .max_w(px(760.)) + .child(content) + .with_animation( + ElementId::named_usize("page", self.switches), + Animation::new(theme::MOVE).with_easing(ease_out_quint()), + |d, p| d.opacity(p).top(px(8. * (1. - p))), + ); // The opening: the image at full strength under the wordmark, then the launcher. let (reveal, hold) = self.opening_phase(window); let side = ease_out_cubic((reveal - 0.2) / 0.7); @@ -1731,16 +2154,28 @@ impl Render for Launcher { ) .when(t.dark, |d| { d.child(div().absolute().size_full().bg(t.bg.opacity(veil))) - .child(div().absolute().size_full().opacity(shade).bg(linear_gradient( - 90., - linear_color_stop(t.bg.opacity(0.9), 0.), - linear_color_stop(t.bg.opacity(0.), 0.7), - ))) - .child(div().absolute().size_full().opacity(shade).bg(linear_gradient( - 180., - linear_color_stop(t.bg.opacity(0.), 0.25), - linear_color_stop(t.bg.opacity(0.75), 1.), - ))) + .child( + div() + .absolute() + .size_full() + .opacity(shade) + .bg(linear_gradient( + 90., + linear_color_stop(t.bg.opacity(0.9), 0.), + linear_color_stop(t.bg.opacity(0.), 0.7), + )), + ) + .child( + div() + .absolute() + .size_full() + .opacity(shade) + .bg(linear_gradient( + 180., + linear_color_stop(t.bg.opacity(0.), 0.25), + linear_color_stop(t.bg.opacity(0.75), 1.), + )), + ) }) }); let mut root = div() @@ -1801,10 +2236,12 @@ impl Render for Launcher { this.skip_opening(); cx.notify(); })) - .on_key_down(cx.listener(|this, _: &KeyDownEvent, _, cx| { - this.skip_opening(); - cx.notify(); - })) + .on_key_down(cx.listener( + |this, _: &KeyDownEvent, _, cx| { + this.skip_opening(); + cx.notify(); + }, + )) }), ); } @@ -1816,13 +2253,17 @@ impl Launcher { /// Where the opening is: the reveal's progress (1 when there is no opening) and the hold's. fn opening_phase(&mut self, window: &mut Window) -> (f32, f32) { let loaded = !matches!(self.releases, Load::Loading); - let Some(opening) = &mut self.opening else { return (1., 0.) }; + let Some(opening) = &mut self.opening else { + return (1., 0.); + }; let held = opening.started.get_or_insert_with(Instant::now).elapsed(); if opening.reveal.is_none() && ((held >= OPENING_HOLD && loaded) || held >= OPENING_MAX) { opening.reveal = Some(Instant::now()); } let hold = held.as_secs_f32() / OPENING_MAX.as_secs_f32(); - let reveal = opening.reveal.map_or(0., |at| at.elapsed().as_secs_f32() / OPENING_REVEAL.as_secs_f32()); + let reveal = opening.reveal.map_or(0., |at| { + at.elapsed().as_secs_f32() / OPENING_REVEAL.as_secs_f32() + }); if reveal >= 1. { self.opening = None; return (1., 0.); @@ -1858,7 +2299,10 @@ fn main() { WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), window_min_size: Some(size(px(820.), px(560.))), - titlebar: Some(TitlebarOptions { title: Some("Horizon".into()), ..Default::default() }), + titlebar: Some(TitlebarOptions { + title: Some("Horizon".into()), + ..Default::default() + }), app_id: Some("horizon-launcher".into()), ..Default::default() }, diff --git a/launcher/src/markdown.rs b/launcher/src/markdown.rs index 8978b7e5e..ee50f6470 100644 --- a/launcher/src/markdown.rs +++ b/launcher/src/markdown.rs @@ -1,16 +1,24 @@ //! Release notes and the roadmap: pulldown-cmark events into gpui elements. use crate::theme::Theme; -use gpui::{div, prelude::*, px, AnyElement, FontStyle, FontWeight, HighlightStyle, SharedString, StyledText}; +use gpui::{ + div, prelude::*, px, AnyElement, FontStyle, FontWeight, HighlightStyle, SharedString, + StyledText, +}; use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd}; use std::ops::Range; +/// A run of text's styled ranges. +type Spans = Vec<(Range, Span)>; +/// A table row: each cell's text and its spans. +type Row = Vec<(String, Spans)>; + enum Block { - Heading(u8, String, Vec<(Range, Span)>), - Paragraph(String, Vec<(Range, Span)>), - Item(usize, Option, String, Vec<(Range, Span)>), + Heading(u8, String, Spans), + Paragraph(String, Spans), + Item(usize, Option, String, Spans), Code(String), Rule, - Table(Vec, Span)>)>>), + Table(Vec), } #[derive(Clone, Copy)] @@ -29,8 +37,12 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { let mut item: Option<(usize, Option)> = None; let mut heading = None; let mut code: Option = None; - let mut table: Option, Span)>)>>> = None; - let flush = |blocks: &mut Vec, text: &mut String, spans: &mut Vec<_>, item: &mut Option<(usize, Option)>, heading: Option| { + let mut table: Option> = None; + let flush = |blocks: &mut Vec, + text: &mut String, + spans: &mut Vec<_>, + item: &mut Option<(usize, Option)>, + heading: Option| { if text.trim().is_empty() { text.clear(); spans.clear(); @@ -43,7 +55,10 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { _ => Block::Paragraph(t, s), }); }; - for event in Parser::new_ext(source, Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES) { + for event in Parser::new_ext( + source, + Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES, + ) { match event { Event::Start(Tag::Heading { level, .. }) => { heading = Some(match level { @@ -56,7 +71,9 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { flush(&mut blocks, &mut text, &mut spans, &mut item, heading); heading = None; } - Event::End(TagEnd::Paragraph) => flush(&mut blocks, &mut text, &mut spans, &mut item, None), + Event::End(TagEnd::Paragraph) => { + flush(&mut blocks, &mut text, &mut spans, &mut item, None) + } Event::Start(Tag::List(start)) => { flush(&mut blocks, &mut text, &mut spans, &mut item, None); lists.push(start) @@ -67,15 +84,19 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { Event::Start(Tag::Item) => { flush(&mut blocks, &mut text, &mut spans, &mut item, None); let depth = lists.len().saturating_sub(1); - let number = lists.last_mut().and_then(|n| n.as_mut().map(|n| { - *n += 1; - *n - 1 - })); + let number = lists.last_mut().and_then(|n| { + n.as_mut().map(|n| { + *n += 1; + *n - 1 + }) + }); item = Some((depth, number)); } Event::End(TagEnd::Item) => flush(&mut blocks, &mut text, &mut spans, &mut item, None), Event::Start(Tag::CodeBlock(_)) => code = Some(String::new()), - Event::End(TagEnd::CodeBlock) => blocks.push(Block::Code(code.take().unwrap_or_default())), + Event::End(TagEnd::CodeBlock) => { + blocks.push(Block::Code(code.take().unwrap_or_default())) + } Event::Start(Tag::Strong) => open.push((Span::Strong, text.len())), Event::Start(Tag::Emphasis) => open.push((Span::Emphasis, text.len())), Event::Start(Tag::Link { .. }) => open.push((Span::Link, text.len())), @@ -110,25 +131,47 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { row.push((std::mem::take(&mut text), std::mem::take(&mut spans))); } } - Event::End(TagEnd::Table) => blocks.push(Block::Table(table.take().unwrap_or_default())), + Event::End(TagEnd::Table) => { + blocks.push(Block::Table(table.take().unwrap_or_default())) + } _ => {} } } flush(&mut blocks, &mut text, &mut spans, &mut item, None); - let styled = |text: String, spans: Vec<(Range, Span)>| { + let styled = |text: String, spans: Spans| { let highlights = spans.into_iter().map(|(range, span)| { let style = match span { - Span::Strong => HighlightStyle { font_weight: Some(FontWeight::SEMIBOLD), color: Some(t.text), ..Default::default() }, - Span::Emphasis => HighlightStyle { font_style: Some(FontStyle::Italic), ..Default::default() }, - Span::Code => HighlightStyle { background_color: Some(t.raised), color: Some(t.text), ..Default::default() }, - Span::Link => HighlightStyle { color: Some(t.text), ..Default::default() }, + Span::Strong => HighlightStyle { + font_weight: Some(FontWeight::SEMIBOLD), + color: Some(t.text), + ..Default::default() + }, + Span::Emphasis => HighlightStyle { + font_style: Some(FontStyle::Italic), + ..Default::default() + }, + Span::Code => HighlightStyle { + background_color: Some(t.raised), + color: Some(t.text), + ..Default::default() + }, + Span::Link => HighlightStyle { + color: Some(t.text), + ..Default::default() + }, }; (range, style) }); StyledText::new(SharedString::from(text)).with_highlights(highlights.collect::>()) }; - let mut column = div().flex().flex_col().gap(px(8.)).text_size(px(13.5)).line_height(px(21.)).text_color(t.muted); + let mut column = div() + .flex() + .flex_col() + .gap(px(8.)) + .text_size(px(13.5)) + .line_height(px(21.)) + .text_color(t.muted); for block in blocks { column = column.child(match block { Block::Heading(level, text, spans) => div() @@ -144,11 +187,11 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { .gap(px(8.)) .pl(px(depth as f32 * 16.)) .child( - div() - .flex_none() - .w(px(16.)) - .text_color(t.faint) - .child(number.map(|n| format!("{n}.")).unwrap_or_else(|| "–".into())), + div().flex_none().w(px(16.)).text_color(t.faint).child( + number + .map(|n| format!("{n}.")) + .unwrap_or_else(|| "–".into()), + ), ) .child(div().flex_1().min_w_0().child(styled(text, spans))) .into_any_element(), @@ -166,14 +209,37 @@ pub fn render(source: &str, t: &Theme) -> AnyElement { .into_any_element(), Block::Rule => div().h(px(1.)).bg(t.border).my(px(8.)).into_any_element(), Block::Table(rows) => { - let mut grid = div().flex().flex_col().my(px(4.)).border_t_1().border_color(t.border); + let mut grid = div() + .flex() + .flex_col() + .my(px(4.)) + .border_t_1() + .border_color(t.border); for (i, row) in rows.into_iter().enumerate() { - let mut line = div().flex().gap(px(16.)).py(px(8.)).border_b_1().border_color(t.border); + let mut line = div() + .flex() + .gap(px(16.)) + .py(px(8.)) + .border_b_1() + .border_color(t.border); let columns = row.len(); for (j, (text, spans)) in row.into_iter().enumerate() { // Two-column tables keep a narrow first column; wider ones share the width. - let cell = if j == 0 && columns > 1 { div().w(px(180.)).flex_none() } else if j + 1 < columns && columns > 2 { div().w(px(56.)).flex_none() } else { div().flex_1().min_w_0() }; - line = line.child(cell.when(i == 0, |d| d.text_color(t.text).font_weight(FontWeight::MEDIUM).text_size(px(12.5))).child(styled(text, spans))); + let cell = if j == 0 && columns > 1 { + div().w(px(180.)).flex_none() + } else if j + 1 < columns && columns > 2 { + div().w(px(56.)).flex_none() + } else { + div().flex_1().min_w_0() + }; + line = line.child( + cell.when(i == 0, |d| { + d.text_color(t.text) + .font_weight(FontWeight::MEDIUM) + .text_size(px(12.5)) + }) + .child(styled(text, spans)), + ); } grid = grid.child(line); } diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index b712812a6..af9f901bc 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -46,11 +46,16 @@ fn tools() -> Value { } fn arg_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> { - args.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()) + args.get(key) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) } impl Session { fn call(&mut self, name: &str, args: &Value) -> Result { + if matches!(name, "list_versions" | "check_updates") { + backend::reuse_prepared_everywhere(); + } match name { "list_versions" => { let installed = backend::installed(); @@ -58,7 +63,11 @@ impl Session { "installed": installed.iter().map(|t| json!({ "tag": t, "prepared": backend::is_prepared(t) })).collect::>(), "selected": backend::resolve_version(None).ok(), }); - if !args.get("installed_only").and_then(Value::as_bool).unwrap_or(false) { + if !args + .get("installed_only") + .and_then(Value::as_bool) + .unwrap_or(false) + { out["releases"] = backend::releases()? .iter() .map(|r| json!({ "tag": r.tag, "name": r.name, "date": r.date, "available_here": r.asset.is_some() })) @@ -67,8 +76,16 @@ impl Session { Ok(serde_json::to_string_pretty(&out).unwrap()) } "install_version" => { - let tag = backend::install_tag(arg_str(args, "tag").ok_or("tag is required")?, false, |_| {})?; - Ok(format!("Installed {tag}. It is now the selected version; prepare it before playing.")) + let tag = backend::install_tag( + arg_str(args, "tag").ok_or("tag is required")?, + false, + |_| {}, + )?; + Ok(if backend::is_prepared(&tag) { + format!("Installed {tag}. It is now the selected version, prepared already from another installed version.") + } else { + format!("Installed {tag}. It is now the selected version; prepare it before playing.") + }) } "remove_version" => { let tag = arg_str(args, "tag").ok_or("tag is required")?; @@ -77,12 +94,15 @@ impl Session { } "prepare_resources" => { let tag = backend::resolve_version(arg_str(args, "version"))?; - let minecraft = backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?; + let minecraft = + backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?; let cmd = backend::prepare_command(&tag, &minecraft, &|_| {})?; let run = Logged::start(Job::Prepare, cmd)?; let result = run.wait(); let tail = run.tail(20).join("\n"); - result.map(|_| format!("{tag} is prepared.\n{tail}")).map_err(|e| format!("{e}\n{tail}")) + result + .map(|_| format!("{tag} is prepared.\n{tail}")) + .map_err(|e| format!("{e}\n{tail}")) } "launch_client" => { if self.client.as_ref().is_some_and(|c| c.finished().is_none()) { @@ -103,15 +123,24 @@ impl Session { } let tag = backend::resolve_version(arg_str(args, "version"))?; let dir = backend::server_dir(arg_str(args, "dir").map(PathBuf::from)); - let accept = args.get("accept_eula").and_then(Value::as_bool).unwrap_or(false); + let accept = args + .get("accept_eula") + .and_then(Value::as_bool) + .unwrap_or(false); let server = Logged::start(Job::Server, backend::server(&tag, &dir, accept)?)?; std::thread::sleep(Duration::from_secs(3)); let tail = server.tail(15).join("\n"); if let Some(result) = server.finished() { - return Err(format!("The server stopped: {}\n{tail}", result.err().unwrap_or_default())); + return Err(format!( + "The server stopped: {}\n{tail}", + result.err().unwrap_or_default() + )); } self.server = Some(server); - Ok(format!("Started the {tag} server in {}.\n{tail}", dir.display())) + Ok(format!( + "Started the {tag} server in {}.\n{tail}", + dir.display() + )) } "server_command" => { let server = self.running_server()?; @@ -121,28 +150,55 @@ impl Session { std::thread::sleep(Duration::from_millis(700)); let log = server.log.lock().unwrap(); let reply: Vec<_> = log.iter().skip(before.min(log.len())).cloned().collect(); - Ok(if reply.is_empty() { "(no output yet)".into() } else { reply.join("\n") }) + Ok(if reply.is_empty() { + "(no output yet)".into() + } else { + reply.join("\n") + }) } "server_log" => { - let server = self.server.as_ref().ok_or("No server was started in this session.")?; + let server = self + .server + .as_ref() + .ok_or("No server was started in this session.")?; let lines = args.get("lines").and_then(Value::as_u64).unwrap_or(50) as usize; - let state = if server.finished().is_some() { "stopped" } else { "running" }; - Ok(format!("[server {state}]\n{}", server.tail(lines).join("\n"))) + let state = if server.finished().is_some() { + "stopped" + } else { + "running" + }; + Ok(format!( + "[server {state}]\n{}", + server.tail(lines).join("\n") + )) } "stop_server" => { - let mut server = self.server.take().ok_or("No server was started in this session.")?; + let mut server = self + .server + .take() + .ok_or("No server was started in this session.")?; server.stop(Duration::from_secs(30)); - Ok(format!("The server stopped.\n{}", server.tail(5).join("\n"))) + Ok(format!( + "The server stopped.\n{}", + server.tail(5).join("\n") + )) } "patch_notes" => { let r = backend::release_notes(arg_str(args, "tag"))?; - Ok(format!("# {} ({}, {})\n\n{}", if r.name.is_empty() { &r.tag } else { &r.name }, r.tag, r.date, r.body)) + Ok(format!( + "# {} ({}, {})\n\n{}", + if r.name.is_empty() { &r.tag } else { &r.name }, + r.tag, + r.date, + r.body + )) } "roadmap" => backend::roadmap(), "links" => Ok(serde_json::to_string_pretty(&backend::links()).unwrap()), "menu_style" => { if let Some(name) = arg_str(args, "style") { - let style = backend::MenuStyle::parse(name).ok_or("style is \"horizon\" or \"classic\"")?; + 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())) @@ -179,8 +235,16 @@ impl Session { "ping" => Ok(json!({})), "tools/list" => Ok(json!({ "tools": tools() })), "tools/call" => { - let name = params.get("name").and_then(Value::as_str).ok_or((-32602, "name is required".to_string()))?; - if !tools().as_array().unwrap().iter().any(|t| t["name"] == name) { + let name = params + .get("name") + .and_then(Value::as_str) + .ok_or((-32602, "name is required".to_string()))?; + if !tools() + .as_array() + .unwrap() + .iter() + .any(|t| t["name"] == name) + { return Err((-32602, format!("Unknown tool {name}"))); } let args = params.get("arguments").cloned().unwrap_or(json!({})); @@ -196,7 +260,10 @@ impl Session { } pub fn serve() -> Result<(), String> { - let mut session = Session { server: None, client: None }; + let mut session = Session { + server: None, + client: None, + }; let stdin = std::io::stdin(); let mut stdout = std::io::stdout(); for line in stdin.lock().lines() { @@ -205,9 +272,14 @@ pub fn serve() -> Result<(), String> { continue; } let reply = match serde_json::from_str::(&line) { - Err(e) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": e.to_string() } })), + Err(e) => Some( + json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": e.to_string() } }), + ), Ok(msg) => { - let method = msg.get("method").and_then(Value::as_str).unwrap_or_default(); + let method = msg + .get("method") + .and_then(Value::as_str) + .unwrap_or_default(); let params = msg.get("params").cloned().unwrap_or(json!({})); // Notifications (no id) get no reply. msg.get("id").cloned().map(|id| match session.handle(method, ¶ms) { @@ -217,7 +289,9 @@ pub fn serve() -> Result<(), String> { } }; if let Some(reply) = reply { - writeln!(stdout, "{reply}").and_then(|_| stdout.flush()).map_err(|e| e.to_string())?; + writeln!(stdout, "{reply}") + .and_then(|_| stdout.flush()) + .map_err(|e| e.to_string())?; } } // The session is over: the server it started goes with it. diff --git a/launcher/src/theme.rs b/launcher/src/theme.rs index 8d7e5b825..08f8741d7 100644 --- a/launcher/src/theme.rs +++ b/launcher/src/theme.rs @@ -17,8 +17,8 @@ pub const HERO: f32 = tokens::HERO; /// Shapes and controls, shared with the game's menus. pub use tokens::{ - CONTROL, CONTROL_LARGE, DISABLED, PRESSED, PRESSED_SOFT, PRIMARY_HOVER, RADIUS, RADIUS_CARD, RADIUS_GROUP, - RADIUS_SEGMENT, ROW_LABEL, SEGMENT, SIDEBAR, + CONTROL, DISABLED, PRESSED, PRESSED_SOFT, PRIMARY_HOVER, RADIUS, RADIUS_GROUP, RADIUS_SEGMENT, + ROW_LABEL, SEGMENT, SIDEBAR, }; /// Motion: short and eased out, never bouncy.