From a5f5d8df34293f561e0bb102d1e74f1ae1fce55d Mon Sep 17 00:00:00 2001 From: socksprox Date: Sat, 24 Oct 2026 21:22:42 +0200 Subject: [PATCH 1/3] Server packs: the download progress toast #1570 landed the client pack manager without vanilla's PackDownloadNotificationComponent: the SystemToast that follows a download with download.pack.progress.percent or .bytes and stays as download.pack.failed when a batch fails. The download queue reports requestStart/downloadedBytes/downloadFinished on a channel (vanilla's DownloadProgressListener), the game ticks them into a toast it slides in for the vanilla 5 seconds with the toast in/out sounds. Co-Authored-By: Devin --- crates/horizon-client/src/game.rs | 1 + .../horizon-client/src/game/server_packs.rs | 139 +++++++++++++++++- .../src/server_packs/download.rs | 81 ++++++++-- crates/horizon-client/src/title.rs | 2 +- 4 files changed, 204 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index bf8327cc1..e162c9e0f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5034,6 +5034,7 @@ impl Game<'_> { Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_toasts(&mut batch); + self.draw_pack_toast(&mut batch); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 6c891a831..6fdec751e 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -12,10 +12,11 @@ use horizon_client::{ scoreboard::{comp_text, tag_to_json}, server_packs::{Prompt, ServerPacks, action, download, parse_sha1, valid_url}, text::{Text, named_color}, + toasts::Slide, ui, }; use horizon_protocol::{packets::configuration::ResourcePackPush, servers}; -use std::path::PathBuf; +use std::{path::PathBuf, sync::mpsc::Receiver}; /// `ClientCommonPacketListenerImpl.PackConfirmScreen`: the packs it asks /// about, whether the last one is required, and the server's message. @@ -75,6 +76,32 @@ pub(super) struct ServerPackState { user: (String, u128), /// The packs loaded on top of the player's own, bottom first. pub(super) active: Vec, + /// `packDownloadNotifier` (`PackDownloadNotificationComponent`): the + /// toast while packs download; `downloadFinished` hides it, a failed + /// batch turns it into `download.pack.failed` until it slides out. + toast: Option, + toast_rx: Option>, +} +/// The download toast: vanilla's `SystemToast` `download.pack.title` with the +/// running progress, `download.pack.failed` when a batch fails. +#[derive(Default)] +struct PackToast { + slide: Slide, + /// `downloadedBytes`: the bytes the request in flight has written. + bytes: u64, + /// Its Content-Length — the progress is a percent, else a byte count. + size: Option, + failed: bool, +} +/// `Unit.humanReadable`, for `download.pack.progress.bytes`. +fn human_readable(bytes: u64) -> String { + const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; + let (mut value, mut unit) = (bytes as f64, 0); + while value >= 1024.0 && unit < UNITS.len() - 1 { + value /= 1024.0; + unit += 1; + } + format!("{value:.1} {}", UNITS[unit]) } fn saves() -> PathBuf { @@ -89,6 +116,8 @@ impl Game<'_> { let state = &mut self.server_packs; state.user = user; state.prompt = None; + state.toast = None; + state.toast_rx = None; let Some(address) = address else { state.address = None; state.packs.local_world(); @@ -103,6 +132,8 @@ impl Game<'_> { /// `Minecraft.clearDownloadedResourcePacks`: every server pack goes at once. pub(super) fn server_packs_disconnect(&mut self) { self.server_packs.prompt = None; + self.server_packs.toast = None; + self.server_packs.toast_rx = None; self.server_packs.packs.disconnect(); self.tick_server_packs(); } @@ -197,10 +228,56 @@ impl Game<'_> { /// that finished, the ones to start, a resource reload when the active /// packs change, and the statuses for the server. pub(super) fn tick_server_packs(&mut self) { + // SystemToast.update: the toast slides for 5000 ms fully shown. + if let Some(toast) = &mut self.server_packs.toast { + let (sound, finished) = toast.slide.update_now(|fully| fully < 5000); + if let Some(sound) = sound { + self.audio.play( + if sound { + "minecraft:ui.toast.in" + } else { + "minecraft:ui.toast.out" + }, + None, + 1.0, + 1.0, + ); + } + if finished { + self.server_packs.toast = None; + } + } // A reload waits for the world's resources (`reload_packs`). if self.rest_loader.is_some() || self.world_loader.is_some() { return; } + let progress = self + .server_packs + .toast_rx + .as_ref() + .map(|rx| rx.try_iter().collect::>()) + .unwrap_or_default(); + for p in progress { + let toast = &mut self.server_packs.toast; + match p { + download::Progress::RequestStart(size) => { + if let Some(t) = toast { + t.bytes = 0; + t.size = size; + } + } + download::Progress::Bytes(done) => { + if let Some(t) = toast { + t.bytes = done; + } + } + download::Progress::Finished => { + if toast.as_ref().is_some_and(|t| !t.failed) { + self.server_packs.toast = None; + } + } + } + } let finished = self .server_packs .queue @@ -208,7 +285,16 @@ impl Game<'_> { .map(download::Queue::finished) .unwrap_or_default(); for batch in finished { + let failed = !batch.failed.is_empty(); self.server_packs.packs.downloaded(batch); + if failed { + // PackDownloadNotificationComponent.onFailure: the failure + // toast replaces the progress one and stays its 5 seconds. + self.server_packs.toast = Some(PackToast { + failed: true, + ..PackToast::default() + }); + } } while self.server_packs.packs.wants_tick() { let tick = self.server_packs.packs.tick(); @@ -238,6 +324,10 @@ impl Game<'_> { Ok(queue) => state.queue = Some(queue), Err(e) => { log::error!("Horizon: failed to open the download queue: {e}"); + state.toast = Some(PackToast { + failed: true, + ..PackToast::default() + }); let failed = requests.iter().map(|r| r.id).collect(); state.packs.downloaded(horizon_client::server_packs::Batch { downloaded: Vec::new(), @@ -248,8 +338,12 @@ impl Game<'_> { } } let headers = download::headers(&state.user.0, state.user.1); + // PackDownloadNotificationComponent: a toast follows the download. + let (progress, rx) = std::sync::mpsc::channel(); + state.toast = Some(PackToast::default()); + state.toast_rx = Some(rx); if let Some(queue) = &state.queue { - queue.download(requests, headers); + queue.download(requests, headers, progress); } } /// `DownloadedPackSource.startReload`: the packs on top of the player's @@ -297,6 +391,47 @@ impl Game<'_> { .layout(atlas, (w, h)) .draw(batch, atlas, self.cursor, [&yes, &no]); } + /// `PackDownloadNotificationComponent`'s toast: `download.pack.title` + /// with the running progress, or `download.pack.failed` alone. + pub(super) fn draw_pack_toast(&self, batch: &mut HudBatch) { + let Some(toast) = &self.server_packs.toast else { + return; + }; + let atlas = &self.gui.atlas; + let t = |key: &str| Text::translate(key, &[]).plain(); + let title = if toast.failed { + t("download.pack.failed") + } else { + t("download.pack.title") + }; + let body = (!toast.failed).then(|| { + if let Some(size) = toast.size.filter(|s| *s > 0) { + Text::tr( + "download.pack.progress.percent", + &[&(toast.bytes * 100 / size)], + ) + .plain() + } else { + Text::tr( + "download.pack.progress.bytes", + &[&human_readable(toast.bytes)], + ) + .plain() + } + }); + let width = body.as_ref().map_or_else( + || HudBatch::text_width(atlas, &title), + |body| HudBatch::text_width(atlas, &title).max(HudBatch::text_width(atlas, body)), + ); + let width = width.ceil().max(160.0) + 30.0; + // Toast.xPos: in from the right edge by the visible portion. + let x = batch.width - width * toast.slide.portion; + horizon_client::title::toast_background(atlas, batch, x, width); + batch.text(atlas, &title, x + 18.0, 7.0, u32::MAX, false); + if let Some(body) = &body { + batch.text(atlas, body, x + 18.0, 19.0, u32::MAX, false); + } + } /// A left click on the prompt: its answer when it hit a button. pub(super) fn pack_prompt_click(&mut self) -> Result<()> { let Some(prompt) = &self.server_packs.prompt else { diff --git a/crates/horizon-client/src/server_packs/download.rs b/crates/horizon-client/src/server_packs/download.rs index 595612df8..c299db9b9 100644 --- a/crates/horizon-client/src/server_packs/download.rs +++ b/crates/horizon-client/src/server_packs/download.rs @@ -34,7 +34,19 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> { ] } -type Job = (Vec, Vec<(&'static str, String)>); +/// `DownloadProgressListener`, on the channel a download was given. +#[derive(Clone, Copy, Debug)] +pub enum Progress { + /// `requestStart`: a request began; its Content-Length when the + /// response said one. + RequestStart(Option), + /// `downloadedBytes`: the bytes this request has written so far. + Bytes(u64), + /// `downloadFinished`: the batch ran, whatever it downloaded. + Finished, +} + +type Job = (Vec, Vec<(&'static str, String)>, Sender); /// `DownloadQueue`: batches download in order, on one thread. pub struct Queue { @@ -50,16 +62,24 @@ impl Queue { std::thread::Builder::new() .name("download-queue".into()) .spawn(move || { - for (requests, headers) in todo { - if finished.send(run(&dir, &requests, &headers)).is_err() { + for (requests, headers, progress) in todo { + if finished + .send(run(&dir, &requests, &headers, &progress)) + .is_err() + { break; } } })?; Ok(Self { jobs, done }) } - pub fn download(&self, requests: Vec, headers: Vec<(&'static str, String)>) { - let _ = self.jobs.send((requests, headers)); + pub fn download( + &self, + requests: Vec, + headers: Vec<(&'static str, String)>, + progress: Sender, + ) { + let _ = self.jobs.send((requests, headers, progress)); } /// The batches finished since the last call. pub fn finished(&self) -> Vec { @@ -68,11 +88,16 @@ impl Queue { } /// `DownloadQueue.runDownload`: each pack into `//`, logged. -fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Batch { +fn run( + dir: &Path, + requests: &[Request], + headers: &[(&'static str, String)], + progress: &Sender, +) -> Batch { let mut batch = Batch::default(); for request in requests { let id = horizon_protocol::crypto::uuid_string(request.id); - let result = download_file(&dir.join(&id), request, headers, MAX_SIZE); + let result = download_file(&dir.join(&id), request, headers, MAX_SIZE, progress); // DownloadQueue.LogEntry, its fields in the codec's order. let mut entry = vec![ ("id", serde_json::Value::from(id)), @@ -112,6 +137,7 @@ fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Err(_) => batch.failed.push(request.id), } } + let _ = progress.send(Progress::Finished); batch } @@ -165,6 +191,7 @@ pub fn download_file( request: &Request, headers: &[(&'static str, String)], max_size: u64, + progress: &Sender, ) -> Result { let target = request.sha1.as_ref().map(|sha1| dir.join(sha1)); if let (Some(target), Some(sha1)) = (&target, &request.sha1) { @@ -205,10 +232,15 @@ pub fn download_file( "Filesize is bigger than maximum allowed (file is {size}, limit is {max_size})" )); } + let _ = progress.send(Progress::RequestStart(size)); let mut input = response.into_reader(); + let mut report = |written: u64| { + let _ = progress.send(Progress::Bytes(written)); + }; match (&target, &request.sha1) { (Some(target), Some(sha1)) => { - let actual = save_hashed(&mut input, target, max_size).map_err(|e| e.to_string())?; + let actual = save_hashed(&mut input, target, max_size, &mut report) + .map_err(|e| e.to_string())?; if &actual != sha1 { return Err(format!( "Hash of downloaded file ({actual}) did not match requested ({sha1})" @@ -218,7 +250,7 @@ pub fn download_file( } _ => { let tmp = dir.join(format!("download{:016x}.tmp", rand_suffix())); - let result = save_hashed(&mut input, &tmp, max_size).and_then(|actual| { + let result = save_hashed(&mut input, &tmp, max_size, &mut report).and_then(|actual| { let path = dir.join(&actual); if matches(&path, &actual) { touch(&path); @@ -237,7 +269,12 @@ fn rand_suffix() -> u64 { RandomState::new().hash_one(std::time::Instant::now()) } /// `downloadAndHash`: write what comes, at most `max_size` bytes. -fn save_hashed(input: &mut dyn Read, path: &Path, max_size: u64) -> io::Result { +fn save_hashed( + input: &mut dyn Read, + path: &Path, + max_size: u64, + progress: &mut dyn FnMut(u64), +) -> io::Result { let mut out = fs::File::create(path)?; let mut hasher = Sha1::new(); let mut buffer = [0u8; 8196]; @@ -248,6 +285,7 @@ fn save_hashed(input: &mut dyn Read, path: &Path, max_size: u64) -> io::Result max_size { return Err(io::Error::other(format!( "Filesize was bigger than maximum allowed (got >= {read_so_far}, limit was {max_size})" @@ -366,7 +404,14 @@ mod tests { url, sha1: Some(sha1(&body)), }; - let path = download_file(&dir, &request, &headers("Alex", 0xab), MAX_SIZE).unwrap(); + let path = download_file( + &dir, + &request, + &headers("Alex", 0xab), + MAX_SIZE, + &channel().0, + ) + .unwrap(); assert_eq!(path, dir.join(sha1(&body))); assert_eq!(fs::read(&path).unwrap(), body); let sent = server.join().unwrap(); @@ -377,7 +422,10 @@ mod tests { url: "http://127.0.0.1:9/gone.zip".into(), ..request }; - assert_eq!(download_file(&dir, &cached, &[], MAX_SIZE).unwrap(), path); + assert_eq!( + download_file(&dir, &cached, &[], MAX_SIZE, &channel().0).unwrap(), + path + ); fs::remove_dir_all(dir).unwrap(); } @@ -390,7 +438,7 @@ mod tests { url, sha1: Some("0".repeat(40)), }; - let err = download_file(&dir, &wrong, &[], MAX_SIZE).unwrap_err(); + let err = download_file(&dir, &wrong, &[], MAX_SIZE, &channel().0).unwrap_err(); assert!(err.contains("did not match requested"), "{err}"); server.join().unwrap(); let dead = Request { @@ -398,7 +446,7 @@ mod tests { url: "http://127.0.0.1:9/pack.zip".into(), sha1: None, }; - assert!(download_file(&dir.join("dead"), &dead, &[], MAX_SIZE).is_err()); + assert!(download_file(&dir.join("dead"), &dead, &[], MAX_SIZE, &channel().0).is_err()); assert!(!dir.join("dead").exists()); let (url, server) = serve("200 OK", vec![0; 100]); let large = Request { @@ -406,7 +454,7 @@ mod tests { url, sha1: None, }; - let err = download_file(&dir, &large, &[], 10).unwrap_err(); + let err = download_file(&dir, &large, &[], 10, &channel().0).unwrap_err(); assert!(err.contains("bigger than maximum"), "{err}"); let _ = server.join(); let (url, server) = serve("404 Not Found", Vec::new()); @@ -415,7 +463,7 @@ mod tests { url, sha1: None, }; - assert!(download_file(&dir, &missing, &[], MAX_SIZE).is_err()); + assert!(download_file(&dir, &missing, &[], MAX_SIZE, &channel().0).is_err()); server.join().unwrap(); fs::remove_dir_all(dir).unwrap(); } @@ -433,6 +481,7 @@ mod tests { sha1: None, }], Vec::new(), + channel().0, ); let batch = loop { if let Some(b) = queue.finished().pop() { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index f77ac93eb..94b1ba2e8 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1554,7 +1554,7 @@ impl Title { } } /// SystemToast's 32-pixel background keeps the notice icon and borders intact. -fn toast_background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, width: f32) { +pub fn toast_background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, width: f32) { let Some(rect) = atlas.sprites.get("gui/sprites/toast/system").copied() else { return; }; From 6d735c26d31f060623fb2b7835925555e0105158 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:40:53 +0200 Subject: [PATCH 2/3] Server packs: the download toast follows DownloadedPackSource's notifier What the toast showed differed from vanilla 26.3 in several ways: - the title and the failure line had no arguments: download.pack.title takes the request number and the batch size, download.pack.failed the failures and the batch size; - sizes read "1.3 KiB" style; com.mojang.realmsclient.Unit.humanReadable gives "1.3 KB" ("512 B" below 1 KiB, half-up rounding), checked against the jar; - each update didn't restart SystemToast's 5 s display time, so a download longer than 5 s lost its toast, and the Notification Time option was ignored; - a finished batch removed the toast at once instead of forceHide's slide out; - the failure title sat at y 7 in white; SystemToast draws titles yellow, and a title without a message at y 12; - a second batch replaced the first one's channel and lost its events. The download thread now reports HttpUtil's listener calls (requestStart, downloadStart with the Content-Length, downloadedBytes, requestFinished), and each batch gets a PackNotifier (createDownloadNotifier) with its own toast. The toast is a shared toasts::SystemToast; the system background moved to toasts.rs with a y, so the pack toasts stack under an advancement toast. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 +- .../horizon-client/src/game/server_packs.rs | 368 +++++++++++------- .../src/server_packs/download.rs | 36 +- crates/horizon-client/src/title.rs | 32 +- crates/horizon-client/src/toasts.rs | 102 +++++ 5 files changed, 367 insertions(+), 173 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e162c9e0f..3b9aee231 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5034,7 +5034,7 @@ impl Game<'_> { Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_toasts(&mut batch); - self.draw_pack_toast(&mut batch); + self.draw_pack_toasts(&mut batch); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 6fdec751e..58d25de0e 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -8,15 +8,19 @@ use horizon_client::{ Result, confirm_screen::Confirm, hud::{HudAtlas, HudBatch}, - multiplayer, packs, + java_text, multiplayer, packs, scoreboard::{comp_text, tag_to_json}, server_packs::{Prompt, ServerPacks, action, download, parse_sha1, valid_url}, text::{Text, named_color}, - toasts::Slide, + toasts::SystemToast, ui, }; +use horizon_core::jmath; use horizon_protocol::{packets::configuration::ResourcePackPush, servers}; -use std::{path::PathBuf, sync::mpsc::Receiver}; +use std::{ + path::PathBuf, + sync::mpsc::{Receiver, TryRecvError}, +}; /// `ClientCommonPacketListenerImpl.PackConfirmScreen`: the packs it asks /// about, whether the last one is required, and the server's message. @@ -76,32 +80,111 @@ pub(super) struct ServerPackState { user: (String, u128), /// The packs loaded on top of the player's own, bottom first. pub(super) active: Vec, - /// `packDownloadNotifier` (`PackDownloadNotificationComponent`): the - /// toast while packs download; `downloadFinished` hides it, a failed - /// batch turns it into `download.pack.failed` until it slides out. - toast: Option, - toast_rx: Option>, + /// The download batches' notifiers, oldest first. + notifiers: Vec, } -/// The download toast: vanilla's `SystemToast` `download.pack.title` with the -/// running progress, `download.pack.failed` when a batch fails. -#[derive(Default)] -struct PackToast { - slide: Slide, - /// `downloadedBytes`: the bytes the request in flight has written. - bytes: u64, - /// Its Content-Length — the progress is a percent, else a byte count. +/// `DownloadedPackSource.createDownloadNotifier`: one batch's progress in its +/// own `SystemToast`. +struct PackNotifier { + progress: Receiver, + total: usize, + /// `count`: the requests started. + count: usize, + /// `failCount`. + failed: usize, + /// `totalBytes`: the Content-Length of the request in flight. size: Option, - failed: bool, + /// The bytes it has written so far: none before the first response. + bytes: Option, + /// The last request has finished. + done: bool, + toast: Option, } -/// `Unit.humanReadable`, for `download.pack.progress.bytes`. -fn human_readable(bytes: u64) -> String { - const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; - let (mut value, mut unit) = (bytes as f64, 0); - while value >= 1024.0 && unit < UNITS.len() - 1 { - value /= 1024.0; - unit += 1; +impl PackNotifier { + fn new(progress: Receiver, total: usize) -> Self { + Self { + progress, + total, + count: 0, + failed: 0, + size: None, + bytes: None, + done: false, + toast: None, + } } - format!("{value:.1} {}", UNITS[unit]) + /// The batch's events since the last call, with the toast updated once + /// for all of them. False once the batch has ended and its toast is gone. + fn poll(&mut self) -> bool { + let (mut changed, mut hide) = (false, false); + let ended = loop { + let event = match self.progress.try_recv() { + Ok(event) => event, + Err(e) => break e == TryRecvError::Disconnected, + }; + changed |= match event { + download::Progress::RequestStart => { + self.count += 1; + true + } + download::Progress::DownloadStart(size) => { + self.size = size; + self.bytes = Some(0); + true + } + download::Progress::Bytes(bytes) => { + self.bytes = Some(bytes); + true + } + download::Progress::RequestFinished(ok) => { + self.failed += usize::from(!ok); + self.done = self.count == self.total; + // Every pack came: forceHide; else the failure title. + hide |= self.done && self.failed == 0; + self.done && self.failed > 0 + } + }; + }; + if changed { + let (title, message) = self.text(); + let (title, message) = (title.plain(), message.map(|m| m.plain())); + // SystemToast.addOrUpdate. + match &mut self.toast { + Some(toast) => toast.reset(title, message), + None => self.toast = Some(SystemToast::new(title, message)), + } + } + if hide && let Some(toast) = &mut self.toast { + toast.force_hide(); + } + !ended || self.toast.is_some() + } + /// The toast's title and message. + fn text(&self) -> (Text, Option) { + if self.done && self.failed > 0 { + let failed = Text::tr("download.pack.failed", &[&self.failed, &self.total]); + return (failed, None); + } + let title = Text::tr("download.pack.title", &[&self.count, &self.total]); + let message = self.bytes.map(|bytes| match self.size { + Some(size) if size > 0 => { + Text::tr("download.pack.progress.percent", &[&(bytes * 100 / size)]) + } + _ => Text::tr("download.pack.progress.bytes", &[&human_readable(bytes)]), + }); + (title, message) + } +} +/// `com.mojang.realmsclient.Unit.humanReadable`, for +/// `download.pack.progress.bytes`. +fn human_readable(bytes: u64) -> String { + if bytes < 1024 { + return format!("{bytes} B"); + } + let exp = (jmath::log(bytes as f64) / jmath::log(1024.0)) as i32; + let prefix = &"KMGTPE"[exp as usize - 1..exp as usize]; + let value = bytes as f64 / 1024f64.powi(exp); + format!("{} {prefix}B", java_text::format_fixed(value, 1)) } fn saves() -> PathBuf { @@ -116,8 +199,7 @@ impl Game<'_> { let state = &mut self.server_packs; state.user = user; state.prompt = None; - state.toast = None; - state.toast_rx = None; + state.notifiers.clear(); let Some(address) = address else { state.address = None; state.packs.local_world(); @@ -132,8 +214,7 @@ impl Game<'_> { /// `Minecraft.clearDownloadedResourcePacks`: every server pack goes at once. pub(super) fn server_packs_disconnect(&mut self) { self.server_packs.prompt = None; - self.server_packs.toast = None; - self.server_packs.toast_rx = None; + self.server_packs.notifiers.clear(); self.server_packs.packs.disconnect(); self.tick_server_packs(); } @@ -228,56 +309,11 @@ impl Game<'_> { /// that finished, the ones to start, a resource reload when the active /// packs change, and the statuses for the server. pub(super) fn tick_server_packs(&mut self) { - // SystemToast.update: the toast slides for 5000 ms fully shown. - if let Some(toast) = &mut self.server_packs.toast { - let (sound, finished) = toast.slide.update_now(|fully| fully < 5000); - if let Some(sound) = sound { - self.audio.play( - if sound { - "minecraft:ui.toast.in" - } else { - "minecraft:ui.toast.out" - }, - None, - 1.0, - 1.0, - ); - } - if finished { - self.server_packs.toast = None; - } - } + self.server_packs.notifiers.retain_mut(PackNotifier::poll); // A reload waits for the world's resources (`reload_packs`). if self.rest_loader.is_some() || self.world_loader.is_some() { return; } - let progress = self - .server_packs - .toast_rx - .as_ref() - .map(|rx| rx.try_iter().collect::>()) - .unwrap_or_default(); - for p in progress { - let toast = &mut self.server_packs.toast; - match p { - download::Progress::RequestStart(size) => { - if let Some(t) = toast { - t.bytes = 0; - t.size = size; - } - } - download::Progress::Bytes(done) => { - if let Some(t) = toast { - t.bytes = done; - } - } - download::Progress::Finished => { - if toast.as_ref().is_some_and(|t| !t.failed) { - self.server_packs.toast = None; - } - } - } - } let finished = self .server_packs .queue @@ -285,16 +321,7 @@ impl Game<'_> { .map(download::Queue::finished) .unwrap_or_default(); for batch in finished { - let failed = !batch.failed.is_empty(); self.server_packs.packs.downloaded(batch); - if failed { - // PackDownloadNotificationComponent.onFailure: the failure - // toast replaces the progress one and stays its 5 seconds. - self.server_packs.toast = Some(PackToast { - failed: true, - ..PackToast::default() - }); - } } while self.server_packs.packs.wants_tick() { let tick = self.server_packs.packs.tick(); @@ -324,10 +351,15 @@ impl Game<'_> { Ok(queue) => state.queue = Some(queue), Err(e) => { log::error!("Horizon: failed to open the download queue: {e}"); - state.toast = Some(PackToast { - failed: true, - ..PackToast::default() - }); + // Every request failed, as the notifier would hear it. + let (progress, events) = std::sync::mpsc::channel(); + for _ in &requests { + let _ = progress.send(download::Progress::RequestStart); + let _ = progress.send(download::Progress::RequestFinished(false)); + } + state + .notifiers + .push(PackNotifier::new(events, requests.len())); let failed = requests.iter().map(|r| r.id).collect(); state.packs.downloaded(horizon_client::server_packs::Batch { downloaded: Vec::new(), @@ -338,10 +370,10 @@ impl Game<'_> { } } let headers = download::headers(&state.user.0, state.user.1); - // PackDownloadNotificationComponent: a toast follows the download. - let (progress, rx) = std::sync::mpsc::channel(); - state.toast = Some(PackToast::default()); - state.toast_rx = Some(rx); + let (progress, events) = std::sync::mpsc::channel(); + state + .notifiers + .push(PackNotifier::new(events, requests.len())); if let Some(queue) = &state.queue { queue.download(requests, headers, progress); } @@ -391,45 +423,27 @@ impl Game<'_> { .layout(atlas, (w, h)) .draw(batch, atlas, self.cursor, [&yes, &no]); } - /// `PackDownloadNotificationComponent`'s toast: `download.pack.title` - /// with the running progress, or `download.pack.failed` alone. - pub(super) fn draw_pack_toast(&self, batch: &mut HudBatch) { - let Some(toast) = &self.server_packs.toast else { - return; - }; - let atlas = &self.gui.atlas; - let t = |key: &str| Text::translate(key, &[]).plain(); - let title = if toast.failed { - t("download.pack.failed") - } else { - t("download.pack.title") - }; - let body = (!toast.failed).then(|| { - if let Some(size) = toast.size.filter(|s| *s > 0) { - Text::tr( - "download.pack.progress.percent", - &[&(toast.bytes * 100 / size)], - ) - .plain() - } else { - Text::tr( - "download.pack.progress.bytes", - &[&human_readable(toast.bytes)], - ) - .plain() + /// The download notifiers' toasts, each in the next 32-pixel slot + /// below an advancement or recipe toast (`ToastManager`). + pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch) { + let multiplier = f64::from(self.settings.notification_display_time); + let mut slot = usize::from(!self.adv.toasts.is_empty()); + for notifier in &mut self.server_packs.notifiers { + let Some(toast) = &mut notifier.toast else { + continue; + }; + let (sound, finished) = toast.update(multiplier); + if let Some(show) = sound { + let event = if show { "ui.toast.in" } else { "ui.toast.out" }; + self.audio + .play(&format!("minecraft:{event}"), None, 1.0, 1.0); } - }); - let width = body.as_ref().map_or_else( - || HudBatch::text_width(atlas, &title), - |body| HudBatch::text_width(atlas, &title).max(HudBatch::text_width(atlas, body)), - ); - let width = width.ceil().max(160.0) + 30.0; - // Toast.xPos: in from the right edge by the visible portion. - let x = batch.width - width * toast.slide.portion; - horizon_client::title::toast_background(atlas, batch, x, width); - batch.text(atlas, &title, x + 18.0, 7.0, u32::MAX, false); - if let Some(body) = &body { - batch.text(atlas, body, x + 18.0, 19.0, u32::MAX, false); + if finished { + notifier.toast = None; + continue; + } + toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32); + slot += 1; } } /// A left click on the prompt: its answer when it hit a button. @@ -449,3 +463,97 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + use download::Progress::*; + + fn notifier(total: usize, events: &[download::Progress]) -> PackNotifier { + let (send, receive) = std::sync::mpsc::channel(); + for event in events { + send.send(*event).unwrap(); + } + let mut notifier = PackNotifier::new(receive, total); + assert!(notifier.poll()); + notifier + } + fn texts(n: &PackNotifier) -> (serde_json::Value, Option) { + let (title, message) = n.text(); + (title.component(), message.map(|m| m.component())) + } + + #[test] + fn the_toast_counts_requests_and_shows_progress() { + let n = notifier(2, &[RequestStart]); + let (title, message) = texts(&n); + assert_eq!(title["translate"], "download.pack.title"); + assert_eq!(title["with"], serde_json::json!([1, 2])); + assert_eq!(message, None); + let n = notifier(2, &[RequestStart, DownloadStart(Some(400)), Bytes(100)]); + assert_eq!( + texts(&n).1.unwrap(), + serde_json::json!({"translate": "download.pack.progress.percent", "with": [25]}) + ); + let n = notifier(1, &[RequestStart, DownloadStart(None), Bytes(1280)]); + assert_eq!( + texts(&n).1.unwrap()["with"], + serde_json::json!([{"text": "1.3 KB"}]) + ); + } + + #[test] + fn a_failed_pack_turns_the_toast_into_the_failure_count() { + let events = [ + RequestStart, + RequestFinished(false), + RequestStart, + DownloadStart(Some(3)), + Bytes(3), + ]; + let (send, receive) = std::sync::mpsc::channel(); + for event in events { + send.send(event).unwrap(); + } + let mut n = PackNotifier::new(receive, 2); + assert!(n.poll()); + // Not the last request yet: still downloading. + assert_eq!(texts(&n).0["translate"], "download.pack.title"); + send.send(RequestFinished(true)).unwrap(); + drop(send); + assert!(n.poll(), "the failure toast stays until it slides out"); + let (title, message) = texts(&n); + assert_eq!( + title, + serde_json::json!({"translate": "download.pack.failed", "with": [1, 2]}) + ); + assert_eq!(message, None); + } + + #[test] + fn a_finished_batch_without_a_toast_is_dropped() { + let (send, receive) = std::sync::mpsc::channel::(); + drop(send); + assert!(!PackNotifier::new(receive, 1).poll()); + } + + #[test] + fn sizes_read_as_realms_unit_human_readable() { + // com.mojang.realmsclient.Unit.humanReadable, run on the 26.3 jar. + for (bytes, text) in [ + (0, "0 B"), + (1023, "1023 B"), + (1024, "1.0 KB"), + (1280, "1.3 KB"), + (1535, "1.5 KB"), + (10_000, "9.8 KB"), + (1_048_575, "1024.0 KB"), + (1_048_576, "1.0 MB"), + (52_428_800, "50.0 MB"), + (262_144_000, "250.0 MB"), + (1_073_741_824, "1.0 GB"), + ] { + assert_eq!(human_readable(bytes), text, "{bytes}"); + } + } +} diff --git a/crates/horizon-client/src/server_packs/download.rs b/crates/horizon-client/src/server_packs/download.rs index c299db9b9..4b075962f 100644 --- a/crates/horizon-client/src/server_packs/download.rs +++ b/crates/horizon-client/src/server_packs/download.rs @@ -34,16 +34,18 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> { ] } -/// `DownloadProgressListener`, on the channel a download was given. -#[derive(Clone, Copy, Debug)] +/// `HttpUtil.DownloadProgressListener`, on the channel a batch was given. +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Progress { - /// `requestStart`: a request began; its Content-Length when the - /// response said one. - RequestStart(Option), - /// `downloadedBytes`: the bytes this request has written so far. + /// `requestStart`: the batch's next request begins. + RequestStart, + /// `downloadStart`: the response came, with its Content-Length if it + /// said one. + DownloadStart(Option), + /// `downloadedBytes`: what this request has written so far. Bytes(u64), - /// `downloadFinished`: the batch ran, whatever it downloaded. - Finished, + /// `requestFinished`: whether it succeeded. + RequestFinished(bool), } type Job = (Vec, Vec<(&'static str, String)>, Sender); @@ -97,7 +99,9 @@ fn run( let mut batch = Batch::default(); for request in requests { let id = horizon_protocol::crypto::uuid_string(request.id); + let _ = progress.send(Progress::RequestStart); let result = download_file(&dir.join(&id), request, headers, MAX_SIZE, progress); + let _ = progress.send(Progress::RequestFinished(result.is_ok())); // DownloadQueue.LogEntry, its fields in the codec's order. let mut entry = vec![ ("id", serde_json::Value::from(id)), @@ -137,7 +141,6 @@ fn run( Err(_) => batch.failed.push(request.id), } } - let _ = progress.send(Progress::Finished); batch } @@ -225,6 +228,7 @@ pub fn download_file( .header("Content-Length") .and_then(|v| v.trim().parse::().ok()); fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let _ = progress.send(Progress::DownloadStart(size)); if let Some(size) = size && size > max_size { @@ -232,7 +236,6 @@ pub fn download_file( "Filesize is bigger than maximum allowed (file is {size}, limit is {max_size})" )); } - let _ = progress.send(Progress::RequestStart(size)); let mut input = response.into_reader(); let mut report = |written: u64| { let _ = progress.send(Progress::Bytes(written)); @@ -473,6 +476,7 @@ mod tests { let dir = scratch(); let (url, server) = serve("200 OK", b"zip".to_vec()); let queue = Queue::open(dir.clone()).unwrap(); + let (progress, events) = channel(); let id = 0x5b2c_7a4e_1f3d_4c8b_9a6e_2d4f_8b1c_3e5a; queue.download( vec![Request { @@ -481,7 +485,7 @@ mod tests { sha1: None, }], Vec::new(), - channel().0, + progress, ); let batch = loop { if let Some(b) = queue.finished().pop() { @@ -494,6 +498,16 @@ mod tests { .join("5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a") .join(sha1(b"zip")); assert_eq!(batch.downloaded, [(id, file)]); + // HttpUtil.downloadFile's listener calls, in order. + assert_eq!( + events.iter().collect::>(), + [ + Progress::RequestStart, + Progress::DownloadStart(Some(3)), + Progress::Bytes(3), + Progress::RequestFinished(true), + ] + ); let log = fs::read_to_string(dir.join("log.json")).unwrap(); let entry: serde_json::Value = serde_json::from_str(log.trim()).unwrap(); assert_eq!(entry["id"], "5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a"); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 94b1ba2e8..ce1c8abf8 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1150,7 +1150,7 @@ impl Title { + 30.0; // Toast.xPos: in from the right edge by the visible portion. let x = w - width * slide.portion; - toast_background(atlas, batch, x, width); + crate::toasts::background(atlas, batch, x, 0.0, width); batch.text(atlas, &title, x + 18.0, 7.0, rgba(255, 255, 0, 255), false); batch.text(atlas, &message, x + 18.0, 19.0, u32::MAX, false); } @@ -1553,36 +1553,6 @@ impl Title { } } } -/// SystemToast's 32-pixel background keeps the notice icon and borders intact. -pub fn toast_background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, width: f32) { - let Some(rect) = atlas.sprites.get("gui/sprites/toast/system").copied() else { - return; - }; - let source_x = [0.0, 17.0, rect.w as f32 - 4.0, rect.w as f32]; - let target_x = [x, x + 17.0, x + width - 4.0, x + width]; - for col in 0..3 { - for (sy, sh, y, h) in [ - (0.0, 28.0, 0.0, 28.0), - (rect.h as f32 - 4.0, 4.0, 28.0, 4.0), - ] { - let mut piece = rect; - let du = (rect.u1 - rect.u0) / rect.w as f32; - let dv = (rect.v1 - rect.v0) / rect.h as f32; - piece.u0 = rect.u0 + source_x[col] * du; - piece.u1 = rect.u0 + source_x[col + 1] * du; - piece.v0 = rect.v0 + sy * dv; - piece.v1 = rect.v0 + (sy + sh) * dv; - batch.rect_uv( - target_x[col], - y, - target_x[col + 1] - target_x[col], - h, - piece, - u32::MAX, - ); - } - } -} fn centered(atlas: &HudAtlas, batch: &mut HudBatch, text: &str, y: f32, color: u32) { batch.text( atlas, diff --git a/crates/horizon-client/src/toasts.rs b/crates/horizon-client/src/toasts.rs index 26807100a..b70a37036 100644 --- a/crates/horizon-client/src/toasts.rs +++ b/crates/horizon-client/src/toasts.rs @@ -1,5 +1,6 @@ //! `ToastManager`'s slide, shared by the game's toasts and the title //! screens' system toasts. +use crate::hud::{HudAtlas, HudBatch}; use std::time::Instant; /// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms, @@ -56,3 +57,104 @@ impl Slide { self.update(origin.elapsed().as_millis() as i64, wants_show) } } + +/// `SystemToast`: a yellow title over a white message (or the title alone, +/// lower down) on the system background. It stays until its display time +/// has passed since its last change, or until it is hidden. +pub struct SystemToast { + pub slide: Slide, + title: String, + message: Option, + /// `changed`: the next update takes its time as `lastChanged`. + changed: bool, + last_changed: i64, + force_hide: bool, +} +impl SystemToast { + /// `SystemToastId.displayTime`'s default, in milliseconds. + const DISPLAY_TIME: f64 = 5000.0; + pub fn new(title: String, message: Option) -> Self { + Self { + slide: Slide::default(), + title, + message, + changed: false, + last_changed: 0, + force_hide: false, + } + } + /// `reset`: new text, and the display time starts again. + pub fn reset(&mut self, title: String, message: Option) { + self.title = title; + self.message = message; + self.changed = true; + } + pub fn force_hide(&mut self) { + self.force_hide = true; + } + /// `ToastInstance.update` with `SystemToast.update`, the display time + /// scaled by the Notification Time option: the visibility it switched + /// to (the sound to play), and whether it has slid out. + pub fn update(&mut self, multiplier: f64) -> (Option, bool) { + self.slide.update_now(|fully| { + if std::mem::take(&mut self.changed) { + self.last_changed = fully; + } + !self.force_hide + && ((fully - self.last_changed) as f64) < Self::DISPLAY_TIME * multiplier + }) + } + /// `extractRenderState` at `y`, in from the right edge by the visible + /// portion (`Toast.xPos`). + pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, y: f32) { + let width = std::iter::once(&self.title) + .chain(&self.message) + .map(|line| HudBatch::text_width(atlas, line)) + .fold(0.0, f32::max) + .ceil() + .max(160.0) + + 30.0; + let x = batch.width - width * self.slide.portion; + background(atlas, batch, x, y, width); + let yellow = crate::hud::rgba(255, 255, 0, 255); + match &self.message { + Some(message) => { + batch.text(atlas, &self.title, x + 18.0, y + 7.0, yellow, false); + batch.text(atlas, message, x + 18.0, y + 19.0, u32::MAX, false); + } + None => { + batch.text(atlas, &self.title, x + 18.0, y + 12.0, yellow, false); + } + } + } +} +/// SystemToast's 32-pixel background keeps the notice icon and borders intact. +pub fn background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, y: f32, width: f32) { + let Some(rect) = atlas.sprites.get("gui/sprites/toast/system").copied() else { + return; + }; + let source_x = [0.0, 17.0, rect.w as f32 - 4.0, rect.w as f32]; + let target_x = [x, x + 17.0, x + width - 4.0, x + width]; + for col in 0..3 { + for (sy, sh, y, h) in [ + (0.0, 28.0, y, 28.0), + (rect.h as f32 - 4.0, 4.0, y + 28.0, 4.0), + ] { + let mut piece = rect; + let du = (rect.u1 - rect.u0) / rect.w as f32; + let dv = (rect.v1 - rect.v0) / rect.h as f32; + piece.u0 = rect.u0 + source_x[col] * du; + piece.u1 = rect.u0 + source_x[col + 1] * du; + piece.v0 = rect.v0 + sy * dv; + piece.v1 = rect.v0 + (sy + sh) * dv; + batch.rect_uv( + target_x[col], + y, + target_x[col + 1] - target_x[col], + h, + piece, + u32::MAX, + ); + } + } +} From 42afd721e7497b63c1195f64012816e24b3318ff Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:04:39 +0200 Subject: [PATCH 3/3] Server packs: the download toast shows over the connection screen A server sends its packs in the configuration phase, while the joining screen covers the frame; vanilla's ToastManager draws over every screen. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3b9aee231..ee86ba3cf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4818,11 +4818,15 @@ impl Game<'_> { } let atlas_ptr: *const HudAtlas = &self.gui.atlas; let _ = atlas_ptr; + // The ToastManager draws over every screen: a server's packs + // download while the connection screen shows. if self.remote_overlay(&mut batch) { + self.draw_pack_toasts(&mut batch); return batch; } if let Some(reason) = self.loading_reason() { self.draw_level_loading(&mut batch, reason); + self.draw_pack_toasts(&mut batch); return batch; } // Hud.extractRenderState: F1 (keyToggleGui) hides camera overlays, the