Merge pull request #421 from ludovic111/fix/server-list-entries

Server list rows: favicons, styled MOTDs, player count colours, icon arrows
This commit is contained in:
Ludovic Marie
2026-10-16 03:46:02 +02:00
committed by GitHub
3 changed files with 333 additions and 62 deletions
+8 -2
View File
@@ -840,8 +840,14 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
Some(Ping::Ok {
motd, players, ms, ..
}) => (
motd.lines().next().unwrap_or("").trim().to_owned(),
format!("{players} · {ms} ms"),
motd.resolve_legacy()
.plain()
.lines()
.next()
.unwrap_or("")
.trim()
.to_owned(),
format!("{} · {ms} ms", Ping::player_count(*players).plain()),
color::ACCENT,
),
Some(Ping::Failed(_)) => (
+324 -60
View File
@@ -4,7 +4,7 @@
//! ServerStatusPinger to show the MOTD, player count and latency.
use crate::hud::{HudAtlas, HudBatch, rgba};
use crate::lan::discovery::Scanner;
use crate::text::{Text, format_translation};
use crate::text::{DARK_GRAY, GRAY, Text, format_translation};
use horizon_protocol::servers::{self, ServerEntry};
use std::{
collections::HashMap,
@@ -18,14 +18,36 @@ use std::{
pub enum Ping {
Pinging,
Ok {
motd: String,
players: String,
/// The description component, styled (`sanitizeDescription`).
motd: Text,
/// Online and max players; None when the status has no `players`.
players: Option<(i64, i64)>,
ms: u128,
version: String,
},
Failed(String),
}
impl Ping {
/// ServerStatusPinger.formatPlayerCount: dark grey with grey numbers,
/// or `multiplayer.status.unknown` without a player count.
pub fn player_count(players: Option<(i64, i64)>) -> Text {
match players {
Some((online, max)) => Text::translate(
"multiplayer.status.player_count",
&[
Text::colored(online.to_string(), GRAY),
Text::colored(max.to_string(), GRAY),
],
),
None => Text::translate("multiplayer.status.unknown", &[]),
}
.with_color(DARK_GRAY)
}
}
type Pings = Arc<Mutex<HashMap<String, Ping>>>;
/// Server icons by address as 64x64 RGBA (FaviconTexture), from servers.dat
/// and then from each ping's favicon.
type Icons = Arc<Mutex<HashMap<String, Arc<Vec<u8>>>>>;
#[derive(Clone, Debug)]
pub enum Screen {
@@ -33,6 +55,7 @@ pub enum Screen {
servers: Vec<ServerEntry>,
selected: Option<usize>,
pings: Pings,
icons: Icons,
/// Worlds announced on the local network, listed after the servers.
lan: Scanner,
scroll: crate::ui::Scroll,
@@ -75,24 +98,63 @@ pub fn servers_file(saves: &Path) -> PathBuf {
.parent()
.map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat"))
}
fn ping_all(servers: &[ServerEntry], pings: &Pings) {
/// `FaviconTexture.upload`: a PNG of exactly 64x64 pixels, else no icon.
fn icon_pixels(png: &[u8]) -> Option<Arc<Vec<u8>>> {
crate::hud::decode_bytes(png)
.ok()
.filter(|(w, h, _)| *w == 64 && *h == 64)
.map(|(_, _, p)| Arc::new(p))
}
/// `ServerStatus.Favicon.CODEC`: a base64 PNG behind the data URL prefix.
fn favicon_bytes(json: &serde_json::Value) -> Option<Vec<u8>> {
let url = json["favicon"].as_str()?;
let base64 = url
.strip_prefix("data:image/png;base64,")?
.replace('\n', "");
crate::skins::base64_decode(&base64)
}
fn ping_all(servers: &[ServerEntry], pings: &Pings, icons: &Icons, file: &Path) {
for s in servers {
let address = s.ip.clone();
pings.lock().unwrap().insert(address.clone(), Ping::Pinging);
let pings = pings.clone();
let saved = s.icon.clone();
if let Some(pixels) = saved
.as_deref()
.and_then(crate::skins::base64_decode)
.and_then(|png| icon_pixels(&png))
{
icons.lock().unwrap().insert(address.clone(), pixels);
}
let (pings, icons, file) = (pings.clone(), icons.clone(), file.to_owned());
let _ = std::thread::Builder::new()
.name("horizon-ping".into())
.spawn(move || {
let result = match crate::net::ping(&address, Duration::from_secs(5)) {
Ok((json, ms)) => {
let lang = Default::default();
let motd = crate::net::json_text(&json["description"], &lang);
let players = format!(
"{}/{}",
json["players"]["online"].as_i64().unwrap_or(0),
json["players"]["max"].as_i64().unwrap_or(0)
);
let motd = crate::component::to_text(&json["description"], &mut |s| {
Text::literal(s)
});
let players = json["players"].as_object().map(|p| {
(
p.get("online").and_then(|n| n.as_i64()).unwrap_or(0),
p.get("max").and_then(|n| n.as_i64()).unwrap_or(0),
)
});
let version = json["version"]["name"].as_str().unwrap_or("?").to_owned();
// A new favicon replaces the saved one (an invalid one
// clears it) and servers.dat is saved again.
if let Some(png) = favicon_bytes(&json) {
let encoded = crate::lan::base64(&png);
let pixels = icon_pixels(&png);
match &pixels {
Some(p) => icons.lock().unwrap().insert(address.clone(), p.clone()),
None => icons.lock().unwrap().remove(&address),
};
let icon = pixels.map(|_| encoded);
if icon != saved {
save_icon(&file, &address, icon);
}
}
Ping::Ok {
motd,
players,
@@ -106,6 +168,33 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) {
});
}
}
/// Save the list after a move or delete, keeping the icons pings stored in
/// servers.dat since it was loaded.
fn save_servers(file: &Path, servers: &mut [ServerEntry]) {
let _guard = SAVING.lock();
let saved = servers::load(file);
for entry in servers.iter_mut() {
if let Some(s) = saved.iter().find(|s| s.ip == entry.ip) {
entry.icon = s.icon.clone();
}
}
let _ = servers::save(file, servers);
}
/// Held while servers.dat is read and written back.
static SAVING: Mutex<()> = Mutex::new(());
/// Store `icon` on the entries for `address` (OnlineServerEntry.updateServerList).
fn save_icon(file: &Path, address: &str, icon: Option<String>) {
let _guard = SAVING.lock();
let mut list = servers::load(file);
let mut changed = false;
for entry in list.iter_mut().filter(|e| e.ip == address) {
changed |= entry.icon != icon;
entry.icon = icon.clone();
}
if changed {
let _ = servers::save(file, &list);
}
}
/// The address of list row `index`: the saved servers, then the LAN games.
fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option<String> {
@@ -168,6 +257,41 @@ fn row_at(
}
rows(servers, lan).nth(index as usize)
}
/// SelectableEntry's hover areas over the 32-pixel icon, relative to it.
fn over_right_half(x: f32, y: f32) -> bool {
(16.0..32.0).contains(&x) && (0.0..32.0).contains(&y)
}
fn over_top_left(x: f32, y: f32) -> bool {
(0.0..16.0).contains(&x) && (0.0..16.0).contains(&y)
}
fn over_bottom_left(x: f32, y: f32) -> bool {
(0.0..16.0).contains(&x) && (16.0..32.0).contains(&y)
}
/// The server's favicon in icon slot `slot`, else `misc/unknown_server`.
fn draw_server_icon(
atlas: &HudAtlas,
batch: &mut HudBatch,
pixels: Option<&[u8]>,
slot: usize,
x: f32,
y: f32,
) {
let sprite = format!("horizon/world-icon{}", slot % crate::hud::WORLD_ICON_SLOTS);
if let Some(pixels) = pixels
&& let Some(rect) = atlas.sprites.get(&sprite)
{
batch.patches.push(crate::font::Patch {
x: (rect.u0 * atlas.width as f32).round() as u32,
y: (rect.v0 * atlas.height as f32).round() as u32,
width: 64,
height: 64,
rgba: pixels.to_vec(),
});
batch.sprite_scaled(atlas, &sprite, x, y, 32.0, 32.0, u32::MAX);
} else {
batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX);
}
}
/// `LoadingDotsText.get`.
fn loading_dots(millis: u128) -> &'static str {
["O o o", "o O o", "o o O", "o O o"][(millis / 300 % 4) as usize]
@@ -243,11 +367,13 @@ impl Screen {
pub fn list(saves: &Path) -> Self {
let servers = servers::load(&servers_file(saves));
let pings: Pings = Arc::default();
ping_all(&servers, &pings);
let icons: Icons = Arc::default();
ping_all(&servers, &pings, &icons, &servers_file(saves));
Self::List {
servers,
selected: None,
pings,
icons,
lan: Scanner::start(),
scroll: crate::ui::Scroll::default(),
}
@@ -459,7 +585,7 @@ impl Screen {
true,
);
}
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) {
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool, cursor: (f32, f32)) {
let (w, h) = (batch.width, batch.height);
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| {
@@ -471,6 +597,7 @@ impl Screen {
servers,
selected,
pings,
icons,
lan,
scroll,
} => {
@@ -497,6 +624,9 @@ impl Screen {
crate::ui::list_background(batch, atlas, top, bottom, false);
let first = batch.vertices.len();
let pings = pings.lock().unwrap();
let icons = icons.lock().unwrap();
// The row under the pointer (`isHovered`).
let hovered = row_at(servers.len(), games.len(), cursor, (w, h), scroll.amount);
let millis = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis());
@@ -543,25 +673,18 @@ impl Screen {
match row {
Row::Server(k) => {
let server = &servers[k];
batch.sprite_scaled(
atlas,
"misc/unknown_server",
cx,
cy,
32.0,
32.0,
u32::MAX,
);
batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, false);
let icon = icons.get(&server.ip);
draw_server_icon(atlas, batch, icon.map(|p| p.as_slice()), i, cx, cy);
batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, true);
// OnlineServerEntry: up to two lines of MOTD, the
// player count left of the status icon.
let (motd, status, motd_color, icon) = match pings.get(&server.ip) {
// player count left of the status icon, all with
// GuiGraphics.text's shadow.
let (motd, status, sprite) = match pings.get(&server.ip) {
Some(Ping::Ok {
motd, players, ms, ..
}) => (
motd.clone(),
players.clone(),
gray,
motd.resolve_legacy(),
Ping::player_count(*players),
format!(
"server_list/ping_{}",
match ms {
@@ -574,12 +697,9 @@ impl Screen {
),
),
Some(Ping::Failed(_)) => (
crate::lang::get_or(
"multiplayer.status.cannot_connect",
"Can't connect to server",
),
String::new(),
rgba(255, 0, 0, 255),
Text::translate("multiplayer.status.cannot_connect", &[])
.with_color(0xFF0000),
Text::empty(),
"server_list/unreachable".to_owned(),
),
_ => {
@@ -587,50 +707,71 @@ impl Screen {
let frame = (millis / 100 + i as u128 * 2) & 7;
let frame = if frame > 4 { 8 - frame } else { frame };
(
crate::lang::get_or(
"multiplayer.status.pinging",
"Pinging...",
),
String::new(),
gray,
Text::translate("multiplayer.status.pinging", &[]),
Text::empty(),
format!("server_list/pinging_{}", frame + 1),
)
}
};
for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas)
for (n, line) in atlas
.font
.split(&motd, ROW_WIDTH - 4.0 - 32.0 - 2.0)
.iter()
.take(2)
.enumerate()
{
batch.text(
batch.text_styled(
atlas,
line,
cx + 35.0,
cy + 12.0 + 9.0 * n as f32,
motd_color,
false,
gray,
true,
);
}
let icon_x = cx + ROW_WIDTH - 4.0 - 15.0;
batch.sprite_scaled(
atlas,
&format!("gui/sprites/{icon}"),
&format!("gui/sprites/{sprite}"),
icon_x,
cy,
10.0,
8.0,
u32::MAX,
);
if !status.is_empty() {
let sw = HudBatch::text_width(atlas, &status).ceil();
batch.text(
atlas,
&status,
icon_x - sw - 5.0,
cy + 1.0,
gray,
false,
);
let sw = atlas.font.width_text(&status).ceil();
batch.text_styled(
atlas,
&status,
icon_x - sw - 5.0,
cy + 1.0,
gray,
true,
);
// Hovering the row: the join arrow over the icon
// and the move arrows, each highlighted under
// the pointer.
if hovered == Some(row) {
let (rx, ry) = (cursor.0 - cx, cursor.1 - cy);
batch.fill(atlas, cx, cy, 32.0, 32.0, 0xA0909090);
for (sprite, shown, over) in [
("join", true, over_right_half(rx, ry)),
("move_up", k > 0, over_top_left(rx, ry)),
("move_down", k + 1 < servers.len(), over_bottom_left(rx, ry)),
] {
if shown {
let lit = if over { "_highlighted" } else { "" };
batch.sprite_scaled(
atlas,
&format!("gui/sprites/server_list/{sprite}{lit}"),
cx,
cy,
32.0,
32.0,
u32::MAX,
);
}
}
}
}
Row::LanHeader => {
@@ -809,7 +950,7 @@ impl Screen {
&& i < servers.len()
{
servers.remove(i);
let _ = servers::save(&servers_file(saves), servers);
save_servers(&servers_file(saves), servers);
}
}
(Self::List { .. }, Some(45)) => *self = Self::list(saves),
@@ -831,9 +972,34 @@ impl Screen {
if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) {
return Outcome::None;
}
let row = row_at(servers.len(), games, (x, y), (w, h), scroll.amount);
// OnlineServerEntry.mouseClicked: the icon's right half joins,
// its left quarters move the server up or down (and keep it
// selected).
if let Some(Row::Server(k)) = row {
let row_top = top + 2.0 - scroll.amount.trunc() + k as f32 * ROW_HEIGHT;
let (rx, ry) = ((x - left - 2.0).floor(), (y - row_top - 2.0).floor());
if over_right_half(rx, ry) {
*selected = Some(k);
return Outcome::Connect(servers[k].ip.clone());
}
let to = if k > 0 && over_top_left(rx, ry) {
Some(k - 1)
} else if k + 1 < servers.len() && over_bottom_left(rx, ry) {
Some(k + 1)
} else {
None
};
if let Some(to) = to {
servers.swap(k, to);
save_servers(&servers_file(saves), servers);
*selected = Some(to);
return Outcome::None;
}
}
// Clicking a selected row again joins it; the LAN header
// takes the click without anything to join.
let index = match row_at(servers.len(), games, (x, y), (w, h), scroll.amount) {
let index = match row {
Some(Row::Server(k)) => Some(k),
Some(Row::Lan(k)) => Some(servers.len() + k),
Some(Row::LanHeader) => {
@@ -1071,8 +1237,8 @@ mod tests {
pings.insert(
"server0".into(),
Ping::Ok {
motd: String::new(),
players: String::new(),
motd: Text::empty(),
players: None,
ms: 42,
version: String::new(),
},
@@ -1149,4 +1315,102 @@ mod tests {
["O o o", "O o o", "o O o", "o o O", "o O o", "O o o"]
);
}
#[test]
fn player_count_is_dark_gray_with_gray_numbers() {
assert_eq!(
Ping::player_count(Some((3, 20))).component(),
serde_json::json!({
"translate": "multiplayer.status.player_count",
"with": [{"text": "3", "color": "gray"}, {"text": "20", "color": "gray"}],
"color": "dark_gray",
})
);
assert_eq!(
Ping::player_count(None).component(),
serde_json::json!({"translate": "multiplayer.status.unknown", "color": "dark_gray"})
);
}
fn png(size: u32) -> Vec<u8> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, size, size);
encoder.set_color(png::ColorType::Rgba);
let mut writer = encoder.write_header().unwrap();
writer
.write_image_data(&vec![200; (size * size * 4) as usize])
.unwrap();
writer.finish().unwrap();
out
}
#[test]
fn favicons_are_64_pixel_pngs_behind_the_data_url() {
let icon = png(64);
let encoded = crate::lan::base64(&icon);
let (a, b) = encoded.split_at(10);
let json = serde_json::json!({ "favicon": format!("data:image/png;base64,{a}\n{b}") });
let bytes = favicon_bytes(&json).unwrap();
assert_eq!(bytes, icon);
assert_eq!(icon_pixels(&bytes).unwrap().len(), 64 * 64 * 4);
// FaviconTexture refuses other sizes; other formats are not icons.
assert!(icon_pixels(&png(32)).is_none());
assert!(favicon_bytes(&serde_json::json!({ "favicon": encoded })).is_none());
}
#[test]
fn icon_arrows_join_and_move_servers() {
let dir = std::env::temp_dir().join(format!("horizon-mp-arrows-{}", std::process::id()));
let saves = dir.join("saves");
std::fs::create_dir_all(&saves).unwrap();
let file = servers_file(&saves);
let names = ["a", "b", "c"];
let list: Vec<ServerEntry> = names
.iter()
.map(|n| ServerEntry::new(n, &format!("127.0.0.1:{}", 1 + n.len())))
.collect();
servers::save(&file, &list).unwrap();
let mut screen = Screen::list(&saves);
let size = (427.0, 240.0);
let order = |screen: &Screen| match screen {
Screen::List {
servers, selected, ..
} => (
servers.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
*selected,
),
_ => unreachable!(),
};
// 427x240: rows start at x 61, the first icon at (63, 37).
let (ix, iy) = (63.0, 37.0);
// The first server has no up arrow: its top-left quarter selects it.
assert!(matches!(
screen.click(None, ix + 4.0, iy + 4.0, size, &saves),
Outcome::None
));
assert_eq!(
order(&screen),
(vec!["a".into(), "b".into(), "c".into()], Some(0))
);
// Bottom-left quarter: down, saved, and still selected.
screen.click(None, ix + 4.0, iy + 20.0, size, &saves);
assert_eq!(
order(&screen),
(vec!["b".into(), "a".into(), "c".into()], Some(1))
);
let saved: Vec<String> = servers::load(&file).into_iter().map(|s| s.name).collect();
assert_eq!(saved, ["b", "a", "c"]);
// Top-left quarter of the second row: back up.
screen.click(None, ix + 4.0, iy + ROW_HEIGHT + 4.0, size, &saves);
assert_eq!(
order(&screen),
(vec!["a".into(), "b".into(), "c".into()], Some(0))
);
// The right half joins at once.
match screen.click(None, ix + 20.0, iy + 2.0 * ROW_HEIGHT + 10.0, size, &saves) {
Outcome::Connect(address) => assert_eq!(address, list[2].ip),
_ => panic!("the join arrow connects"),
}
let _ = std::fs::remove_dir_all(&dir);
}
}
+1
View File
@@ -1020,6 +1020,7 @@ impl Title {
atlas,
batch,
(self.started.elapsed().as_millis() / 300).is_multiple_of(2),
cursor,
),
}
for b in self.buttons(w, h) {