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 <devin@cognition.ai>
This commit is contained in:
socksprox
2026-10-24 21:22:42 +02:00
parent fe128948ba
commit a5f5d8df34
4 changed files with 204 additions and 19 deletions
+1
View File
@@ -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);
+137 -2
View File
@@ -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<packs::Pack>,
/// `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<PackToast>,
toast_rx: Option<Receiver<download::Progress>>,
}
/// 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<u64>,
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::<Vec<_>>())
.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 {
@@ -34,7 +34,19 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> {
]
}
type Job = (Vec<Request>, 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<u64>),
/// `downloadedBytes`: the bytes this request has written so far.
Bytes(u64),
/// `downloadFinished`: the batch ran, whatever it downloaded.
Finished,
}
type Job = (Vec<Request>, Vec<(&'static str, String)>, Sender<Progress>);
/// `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<Request>, headers: Vec<(&'static str, String)>) {
let _ = self.jobs.send((requests, headers));
pub fn download(
&self,
requests: Vec<Request>,
headers: Vec<(&'static str, String)>,
progress: Sender<Progress>,
) {
let _ = self.jobs.send((requests, headers, progress));
}
/// The batches finished since the last call.
pub fn finished(&self) -> Vec<Batch> {
@@ -68,11 +88,16 @@ impl Queue {
}
/// `DownloadQueue.runDownload`: each pack into `<dir>/<id>/`, logged.
fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Batch {
fn run(
dir: &Path,
requests: &[Request],
headers: &[(&'static str, String)],
progress: &Sender<Progress>,
) -> 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<Progress>,
) -> Result<PathBuf, String> {
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<String> {
fn save_hashed(
input: &mut dyn Read,
path: &Path,
max_size: u64,
progress: &mut dyn FnMut(u64),
) -> io::Result<String> {
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<S
break;
}
read_so_far += n as u64;
progress(read_so_far);
if read_so_far > 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() {
+1 -1
View File
@@ -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;
};