Merge pull request #1588 from socksprox/feat/server-resource-packs
This commit is contained in:
@@ -4820,11 +4820,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
|
||||
@@ -5036,6 +5040,7 @@ impl Game<'_> {
|
||||
Screen::Playing | Screen::Options | Screen::Win => {}
|
||||
}
|
||||
self.draw_toasts(&mut batch);
|
||||
self.draw_pack_toasts(&mut batch);
|
||||
self.remote_hud(&mut batch);
|
||||
self.draw_sign_editor(&mut batch);
|
||||
self.draw_book(&mut batch);
|
||||
|
||||
@@ -8,14 +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::SystemToast,
|
||||
ui,
|
||||
};
|
||||
use horizon_core::jmath;
|
||||
use horizon_protocol::{packets::configuration::ResourcePackPush, servers};
|
||||
use std::path::PathBuf;
|
||||
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.
|
||||
@@ -75,6 +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<packs::Pack>,
|
||||
/// The download batches' notifiers, oldest first.
|
||||
notifiers: Vec<PackNotifier>,
|
||||
}
|
||||
/// `DownloadedPackSource.createDownloadNotifier`: one batch's progress in its
|
||||
/// own `SystemToast`.
|
||||
struct PackNotifier {
|
||||
progress: Receiver<download::Progress>,
|
||||
total: usize,
|
||||
/// `count`: the requests started.
|
||||
count: usize,
|
||||
/// `failCount`.
|
||||
failed: usize,
|
||||
/// `totalBytes`: the Content-Length of the request in flight.
|
||||
size: Option<u64>,
|
||||
/// The bytes it has written so far: none before the first response.
|
||||
bytes: Option<u64>,
|
||||
/// The last request has finished.
|
||||
done: bool,
|
||||
toast: Option<SystemToast>,
|
||||
}
|
||||
impl PackNotifier {
|
||||
fn new(progress: Receiver<download::Progress>, total: usize) -> Self {
|
||||
Self {
|
||||
progress,
|
||||
total,
|
||||
count: 0,
|
||||
failed: 0,
|
||||
size: None,
|
||||
bytes: None,
|
||||
done: false,
|
||||
toast: None,
|
||||
}
|
||||
}
|
||||
/// 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<Text>) {
|
||||
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 {
|
||||
@@ -89,6 +199,7 @@ impl Game<'_> {
|
||||
let state = &mut self.server_packs;
|
||||
state.user = user;
|
||||
state.prompt = None;
|
||||
state.notifiers.clear();
|
||||
let Some(address) = address else {
|
||||
state.address = None;
|
||||
state.packs.local_world();
|
||||
@@ -103,6 +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.notifiers.clear();
|
||||
self.server_packs.packs.disconnect();
|
||||
self.tick_server_packs();
|
||||
}
|
||||
@@ -197,6 +309,7 @@ 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) {
|
||||
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;
|
||||
@@ -238,6 +351,15 @@ impl Game<'_> {
|
||||
Ok(queue) => state.queue = Some(queue),
|
||||
Err(e) => {
|
||||
log::error!("Horizon: failed to open the download queue: {e}");
|
||||
// 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(),
|
||||
@@ -248,8 +370,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
let headers = download::headers(&state.user.0, state.user.1);
|
||||
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);
|
||||
queue.download(requests, headers, progress);
|
||||
}
|
||||
}
|
||||
/// `DownloadedPackSource.startReload`: the packs on top of the player's
|
||||
@@ -297,6 +423,29 @@ impl Game<'_> {
|
||||
.layout(atlas, (w, h))
|
||||
.draw(batch, atlas, self.cursor, [&yes, &no]);
|
||||
}
|
||||
/// 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);
|
||||
}
|
||||
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.
|
||||
pub(super) fn pack_prompt_click(&mut self) -> Result<()> {
|
||||
let Some(prompt) = &self.server_packs.prompt else {
|
||||
@@ -314,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<serde_json::Value>) {
|
||||
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::<download::Progress>();
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,21 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> {
|
||||
]
|
||||
}
|
||||
|
||||
type Job = (Vec<Request>, Vec<(&'static str, String)>);
|
||||
/// `HttpUtil.DownloadProgressListener`, on the channel a batch was given.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Progress {
|
||||
/// `requestStart`: the batch's next request begins.
|
||||
RequestStart,
|
||||
/// `downloadStart`: the response came, with its Content-Length if it
|
||||
/// said one.
|
||||
DownloadStart(Option<u64>),
|
||||
/// `downloadedBytes`: what this request has written so far.
|
||||
Bytes(u64),
|
||||
/// `requestFinished`: whether it succeeded.
|
||||
RequestFinished(bool),
|
||||
}
|
||||
|
||||
type Job = (Vec<Request>, Vec<(&'static str, String)>, Sender<Progress>);
|
||||
|
||||
/// `DownloadQueue`: batches download in order, on one thread.
|
||||
pub struct Queue {
|
||||
@@ -50,16 +64,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 +90,18 @@ 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 _ = 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)),
|
||||
@@ -165,6 +194,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) {
|
||||
@@ -198,6 +228,7 @@ pub fn download_file(
|
||||
.header("Content-Length")
|
||||
.and_then(|v| v.trim().parse::<u64>().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
|
||||
{
|
||||
@@ -206,9 +237,13 @@ pub fn download_file(
|
||||
));
|
||||
}
|
||||
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 +253,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 +272,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 +288,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 +407,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 +425,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 +441,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 +449,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 +457,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 +466,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();
|
||||
}
|
||||
@@ -425,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 {
|
||||
@@ -433,6 +485,7 @@ mod tests {
|
||||
sha1: None,
|
||||
}],
|
||||
Vec::new(),
|
||||
progress,
|
||||
);
|
||||
let batch = loop {
|
||||
if let Some(b) = queue.finished().pop() {
|
||||
@@ -445,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::<Vec<_>>(),
|
||||
[
|
||||
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");
|
||||
|
||||
@@ -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.
|
||||
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,
|
||||
|
||||
@@ -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<String>,
|
||||
/// `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<String>) -> 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<String>) {
|
||||
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>, 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user