From 587695e108d4fc21f5922ef7518613552a6649ea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 09:48:14 +0200 Subject: [PATCH] Multiplayer: vanilla's server list, with the LAN scanning header and its dots (#282) JoinMultiplayerScreen's layout: the title centred in the 33-pixel header, the ServerSelectionList between the separators (list background, 305-wide rows, white selection outline, scissored rows, the scroller sprites), the footer buttons centred in 60 pixels. The list always ends with the LAN header, "Scanning for games on your local network" over LoadingDotsText's dots, then the LAN games. Saved servers show two MOTD lines, the player count and the ping, pinging or unreachable icon; Edit and Delete need a saved server. The list scrolls with the wheel and a draggable scrollbar (ui::Scroll, after AbstractScrollArea). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/front.rs | 1 + crates/horizon-client/src/game.rs | 14 + crates/horizon-client/src/multiplayer.rs | 573 +++++++++++++++++------ crates/horizon-client/src/title.rs | 18 +- crates/horizon-client/src/ui.rs | 83 ++++ 5 files changed, 538 insertions(+), 151 deletions(-) diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 72b70a56b..828402944 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -814,6 +814,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { selected, pings, lan, + .. } => { let games = lan.games(); let sub = match servers.len() { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index fd4557137..6c456a71f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8673,6 +8673,11 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Inventory || self.creative_inventory_open() { self.inventory_drag_move(); } + if let Some(title) = &mut self.title + && !horizon_client::ui_theme::horizon() + { + title.drag(self.cursor, (b.width, b.height)); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -8748,6 +8753,15 @@ impl ApplicationHandler for Game<'_> { )?; } } + WindowEvent::MouseInput { + state: ElementState::Released, + button: MouseButton::Left, + .. + } if self.title.is_some() && self.screen != Screen::Options => { + if let Some(title) = &mut self.title { + title.release(); + } + } WindowEvent::MouseInput { state, button: MouseButton::Left, diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 1936c8ace..a13bc7063 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -34,6 +34,7 @@ pub enum Screen { pings: Pings, /// Worlds announced on the local network, listed after the servers. lan: Scanner, + scroll: crate::ui::Scroll, }, /// Add (index None) or edit a server entry. Edit { @@ -117,6 +118,60 @@ fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option } } +/// JoinMultiplayerScreen's `HeaderAndFooterLayout(33, 60)`. +const HEADER: f32 = 33.0; +const FOOTER: f32 = 60.0; +/// ServerSelectionList: rows 305 wide and 36 high. +const ROW_WIDTH: f32 = 305.0; +const ROW_HEIGHT: f32 = 36.0; +/// One row of the list: the saved servers, the LAN header, the LAN games. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Row { + Server(usize), + LanHeader, + Lan(usize), +} +/// The list's top and bottom and its rows' left edge (`getRowLeft`). +fn list_area(w: f32, h: f32) -> (f32, f32, f32) { + ( + HEADER, + h - FOOTER, + (w / 2.0).floor() - (ROW_WIDTH / 2.0).floor(), + ) +} +fn rows(servers: usize, lan: usize) -> impl Iterator { + (0..servers) + .map(Row::Server) + .chain(std::iter::once(Row::LanHeader)) + .chain((0..lan).map(Row::Lan)) +} +/// `contentHeight`: the rows and 4 pixels of padding. +fn content_height(servers: usize, lan: usize) -> f32 { + (servers + 1 + lan) as f32 * ROW_HEIGHT + 4.0 +} +/// The row under `(x, y)` (`getEntryAtPosition`), scrolled by `scroll`. +fn row_at( + servers: usize, + lan: usize, + (x, y): (f32, f32), + size: (f32, f32), + scroll: f32, +) -> Option { + let (top, bottom, left) = list_area(size.0, size.1); + if y < top || y >= bottom || x < left || x >= left + ROW_WIDTH { + return None; + } + let index = ((y - top - 2.0 + scroll.trunc()) / ROW_HEIGHT).floor(); + if index < 0.0 { + return None; + } + rows(servers, lan).nth(index as usize) +} +/// `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] +} + impl Screen { /// The address of list row `row` (saved servers, then LAN games). pub fn address_of(&self, row: usize) -> Option { @@ -134,6 +189,7 @@ impl Screen { selected: None, pings, lan: Scanner::start(), + scroll: crate::ui::Scroll::default(), } } pub fn buttons(&self, w: f32, h: f32) -> Vec { @@ -141,44 +197,75 @@ impl Screen { (x, y, bw, label.to_owned(), enabled, id) }; match self { - // JoinMultiplayerScreen's two button rows. - Self::List { selected, .. } => vec![ - b( - w / 2.0 - 154.0, - h - 52.0, - 100.0, - "Join Server", - selected.is_some(), - 40, - ), - b( - w / 2.0 - 50.0, - h - 52.0, - 100.0, - "Direct Connection", - true, - 41, - ), - b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42), - b( - w / 2.0 - 154.0, - h - 28.0, - 74.0, - "Edit", - selected.is_some(), - 43, - ), - b( - w / 2.0 - 76.0, - h - 28.0, - 74.0, - "Delete", - selected.is_some(), - 44, - ), - b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45), - b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46), - ], + // JoinMultiplayerScreen's footer: two rows of buttons, 4 apart, + // centred in the 60-pixel footer. Join needs a server or LAN game + // selected (onSelectedChange), Edit and Delete a saved server. + Self::List { + servers, selected, .. + } => { + let (w, h) = (w.ceil(), h.ceil()); + let x = ((w - 308.0) / 2.0).floor(); + let saved = selected.is_some_and(|i| i < servers.len()); + let label = |key: &str, fallback: &str| crate::lang::get_or(key, fallback); + vec![ + b( + x, + h - 52.0, + 100.0, + &label("selectServer.select", "Join Server"), + selected.is_some(), + 40, + ), + b( + x + 104.0, + h - 52.0, + 100.0, + &label("selectServer.direct", "Direct Connection"), + true, + 41, + ), + b( + x + 208.0, + h - 52.0, + 100.0, + &label("selectServer.add", "Add Server"), + true, + 42, + ), + b( + x, + h - 28.0, + 74.0, + &label("selectServer.edit", "Edit"), + saved, + 43, + ), + b( + x + 78.0, + h - 28.0, + 74.0, + &label("selectServer.delete", "Delete"), + saved, + 44, + ), + b( + x + 156.0, + h - 28.0, + 74.0, + &label("selectServer.refresh", "Refresh"), + true, + 45, + ), + b( + x + 234.0, + h - 28.0, + 74.0, + &label("gui.back", "Back"), + true, + 46, + ), + ] + } Self::Edit { address, .. } => vec![ b( w / 2.0 - 100.0, @@ -325,121 +412,205 @@ impl Screen { selected, pings, lan, + scroll, } => { - centered(batch, "Play Multiplayer", 8.0, u32::MAX); - batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); + let (w, h) = (w.ceil(), h.ceil()); + let title = crate::lang::get_or("multiplayer.title", "Play Multiplayer"); + // The header's StringWidget, centred in its 33 pixels. + let tw = HudBatch::text_width(atlas, &title); + let tx = ((w - tw.ceil()) / 2.0).floor(); + batch.text( + atlas, + &title, + tx, + ((HEADER - 9.0) / 2.0).floor(), + u32::MAX, + true, + ); + let games = lan.games(); + let (top, bottom, left) = list_area(w, h); + let content = content_height(servers.len(), games.len()); + let mut scroll = *scroll; + scroll.clamp(top, bottom, content); + // AbstractSelectionList.extractWidgetRenderState: background, + // the rows clipped to the list, separators, scrollbar. + crate::ui::list_background(batch, atlas, top, bottom, false); + let first = batch.vertices.len(); let pings = pings.lock().unwrap(); - for (i, server) in servers.iter().enumerate() { - let y = 36.0 + i as f32 * 36.0; - if y + 36.0 > h - 64.0 { - break; + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis()); + let gray = rgba(128, 128, 128, 255); + for (i, row) in rows(servers.len(), games.len()).enumerate() { + let y = top + 2.0 - scroll.amount.trunc() + i as f32 * ROW_HEIGHT; + if y + ROW_HEIGHT < top || y > bottom { + continue; } - let x = w / 2.0 - 152.0; - crate::widgets::target_as( - [x - 2.0, y - 2.0, 306.0, 36.0], - crate::widgets::Kind::Row, - ); - if *selected == Some(i) { - batch.fill( - atlas, - x - 2.0, - y - 2.0, - 306.0, - 36.0, - rgba(128, 128, 128, 255), - ); - batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); - } - batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); - batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false); - let (line, right, color) = match pings.get(&server.ip) { - Some(Ping::Ok { - motd, players, ms, .. - }) => ( - motd.lines().next().unwrap_or("").to_owned(), - format!("{players} {ms} ms"), - rgba(128, 128, 128, 255), - ), - Some(Ping::Failed(_)) => ( - "Can't connect to server".to_owned(), - String::new(), - rgba(170, 0, 0, 255), - ), - _ => ( - "Pinging...".to_owned(), - String::new(), - rgba(128, 128, 128, 255), - ), + let index = match row { + Row::Server(k) => Some(k), + Row::Lan(k) => Some(servers.len() + k), + Row::LanHeader => None, }; - batch.text(atlas, &line, x + 35.0, y + 12.0, color, false); - batch.text( - atlas, - &server.ip, - x + 35.0, - y + 22.0, - rgba(96, 96, 96, 255), - false, - ); - if !right.is_empty() { - let tw = HudBatch::text_width(atlas, &right); - batch.text( - atlas, - &right, - x + 300.0 - tw, - y + 1.0, - rgba(128, 128, 128, 255), - false, + if index.is_some() + && y + ROW_HEIGHT / 2.0 > top + && y + ROW_HEIGHT / 2.0 < bottom + { + crate::widgets::target_as( + [left, y, ROW_WIDTH, ROW_HEIGHT], + crate::widgets::Kind::Row, ); } - } - for (k, game) in lan.games().iter().enumerate() { - let i = servers.len() + k; - let y = 36.0 + i as f32 * 36.0; - if y + 36.0 > h - 64.0 { - break; - } - let x = w / 2.0 - 152.0; - crate::widgets::target_as( - [x - 2.0, y - 2.0, 306.0, 36.0], - crate::widgets::Kind::Row, - ); - if *selected == Some(i) { + // extractSelection: a white outline round black (the list + // has focus once a row is clicked). + if index.is_some() && *selected == index { + batch.fill(atlas, left, y, ROW_WIDTH, ROW_HEIGHT, u32::MAX); batch.fill( atlas, - x - 2.0, - y - 2.0, - 306.0, - 36.0, - rgba(128, 128, 128, 255), + left + 1.0, + y + 1.0, + ROW_WIDTH - 2.0, + ROW_HEIGHT - 2.0, + rgba(0, 0, 0, 255), ); - batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); } - batch.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false); - batch.text( - atlas, - &game.motd, - x + 35.0, - y + 12.0, - rgba(128, 128, 128, 255), - false, - ); - batch.text( - atlas, - &game.address, - x + 35.0, - y + 22.0, - rgba(96, 96, 96, 255), - false, - ); - } - if servers.is_empty() { - centered( - batch, - "No servers yet: add one or use Direct Connection", - h / 2.0 - 20.0, - rgba(160, 160, 160, 255), - ); + // Entry content: 2 pixels in from the row. + let (cx, cy) = (left + 2.0, y + 2.0); + 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); + // 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) { + Some(Ping::Ok { + motd, players, ms, .. + }) => ( + motd.clone(), + players.clone(), + gray, + format!( + "server_list/ping_{}", + match ms { + 0..150 => 5, + 150..300 => 4, + 300..600 => 3, + 600..1000 => 2, + _ => 1, + } + ), + ), + Some(Ping::Failed(_)) => ( + crate::lang::get_or( + "multiplayer.status.cannot_connect", + "Can't connect to server", + ), + String::new(), + rgba(255, 0, 0, 255), + "server_list/unreachable".to_owned(), + ), + _ => { + // The pinging bars bounce, offset by the row. + 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, + format!("server_list/pinging_{}", frame + 1), + ) + } + }; + for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas) + .iter() + .take(2) + .enumerate() + { + batch.text( + atlas, + line, + cx + 35.0, + cy + 12.0 + 9.0 * n as f32, + motd_color, + false, + ); + } + let icon_x = cx + ROW_WIDTH - 4.0 - 15.0; + batch.sprite_scaled( + atlas, + &format!("gui/sprites/{icon}"), + 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, + ); + } + } + Row::LanHeader => { + // LANHeader's LoadingDotsWidget: the label, then + // the dots on its last line, both centred. + let label = crate::lang::get_or( + "lanServer.scanning", + "Scanning for games on your local network", + ); + let middle = cx + ((ROW_WIDTH - 4.0) / 2.0).floor(); + let lw = HudBatch::text_width(atlas, &label).ceil(); + let lx = middle - (lw / 2.0).floor(); + let centre = lx + (lw / 2.0).floor(); + batch.text(atlas, &label, lx, cy + 2.0, u32::MAX, false); + let dots = loading_dots(millis); + let dw = HudBatch::text_width(atlas, dots).ceil(); + batch.text( + atlas, + dots, + centre - (dw / 2.0).floor(), + cy + 28.0 - 9.0 - 2.0, + gray, + false, + ); + } + Row::Lan(k) => { + let game = &games[k]; + let header = crate::lang::get_or("lanServer.title", "LAN World"); + batch.text(atlas, &header, cx + 35.0, cy + 1.0, u32::MAX, false); + batch.text(atlas, &game.motd, cx + 35.0, cy + 12.0, gray, false); + batch.text(atlas, &game.address, cx + 35.0, cy + 23.0, gray, false); + } + } } + batch.clip_since(first, 0.0, top, w, bottom); + crate::ui::separators(batch, atlas, top, bottom, false); + crate::ui::scrollbar( + batch, + atlas, + left + ROW_WIDTH + 8.0, + top, + bottom, + content, + scroll.amount, + ); } Self::Edit { index, @@ -583,19 +754,36 @@ impl Screen { servers, selected, lan, + scroll, .. }, None, ) => { - let index = ((y - 36.0) / 36.0).floor(); - if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 { - let index = index as usize; - if let Some(address) = entry_address(servers, lan, index) { - if *selected == Some(index) { - return Outcome::Connect(address); - } - *selected = Some(index); + let (w, h) = (w.ceil(), h.ceil()); + let games = lan.games().len(); + let (top, bottom, left) = list_area(w, h); + let content = content_height(servers.len(), games); + if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) { + 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) { + Some(Row::Server(k)) => Some(k), + Some(Row::Lan(k)) => Some(servers.len() + k), + Some(Row::LanHeader) => { + *selected = None; + None } + None => None, + }; + if let Some(index) = index + && let Some(address) = entry_address(servers, lan, index) + { + if *selected == Some(index) { + return Outcome::Connect(address); + } + *selected = Some(index); } } ( @@ -648,6 +836,45 @@ impl Screen { } Outcome::None } + /// The mouse wheel over the server list (`scrollRate`: half a row). + pub fn wheel(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Self::List { + servers, + lan, + scroll, + .. + } = self + { + let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil()); + if cursor.1 >= top && cursor.1 < bottom { + let content = content_height(servers.len(), lan.games().len()); + scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content); + } + } + } + /// The pointer moved: a held scrollbar follows it. + pub fn drag(&mut self, y: f32, size: (f32, f32)) { + if let Self::List { + servers, + lan, + scroll, + .. + } = self + { + let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil()); + scroll.drag( + y, + top, + bottom, + content_height(servers.len(), lan.games().len()), + ); + } + } + pub fn release(&mut self) { + if let Self::List { scroll, .. } = self { + scroll.release(); + } + } fn focused_field(&mut self) -> Option<&mut String> { match self { Self::Edit { @@ -756,3 +983,49 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { } lines } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_lan_header_follows_the_saved_servers() { + let all: Vec = rows(2, 1).collect(); + assert_eq!( + all, + [Row::Server(0), Row::Server(1), Row::LanHeader, Row::Lan(0)] + ); + // No saved servers: the list is the scanning header alone. + assert_eq!(rows(0, 0).collect::>(), [Row::LanHeader]); + assert_eq!(content_height(0, 0), 40.0); + } + + #[test] + fn rows_sit_two_pixels_under_the_header_and_scroll_with_the_list() { + // 427x240 GUI: the list spans 33..180, rows 305 wide from x 61. + let size = (427.0, 240.0); + assert_eq!(list_area(size.0, size.1), (33.0, 180.0, 61.0)); + assert_eq!(row_at(3, 0, (100.0, 35.0), size, 0.0), Some(Row::Server(0))); + assert_eq!(row_at(3, 0, (100.0, 70.9), size, 0.0), Some(Row::Server(0))); + assert_eq!(row_at(3, 0, (100.0, 71.0), size, 0.0), Some(Row::Server(1))); + assert_eq!( + row_at(3, 0, (100.0, 35.0), size, 36.0), + Some(Row::Server(1)) + ); + assert_eq!( + row_at(3, 0, (100.0, 143.0), size, 0.0), + Some(Row::LanHeader) + ); + assert_eq!(row_at(3, 0, (60.0, 40.0), size, 0.0), None); + assert_eq!(row_at(3, 0, (100.0, 32.0), size, 0.0), None); + } + + #[test] + fn loading_dots_step_every_300_ms() { + let frames: Vec<&str> = [0, 299, 300, 600, 900, 1200].map(loading_dots).to_vec(); + assert_eq!( + frames, + ["O o o", "O o o", "o O o", "o o O", "o O o", "O o o"] + ); + } +} diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 1cd57f00d..97f460fba 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -324,8 +324,24 @@ impl Title { .collect::>() .into_iter() } - /// Mouse wheel over the classic world list. + /// The pointer moved with the button held (`mouseDragged`). + pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.drag(cursor.1, size); + } + } + /// The button was released (`onRelease`). + pub fn release(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.release(); + } + } + /// Mouse wheel over the classic world and server lists. pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.wheel(delta, cursor, size); + return; + } let Mode::Select { worlds, .. } = &self.mode else { return; }; diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index e5740616e..44d208a69 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -430,6 +430,67 @@ pub(crate) fn scrollbar_thumb( Some((y, bar)) } +/// `AbstractScrollArea`'s scrolling of a list `top..bottom` holding `content` +/// pixels: the amount, the mouse wheel and the held scrollbar. +#[derive(Clone, Copy, Debug, Default)] +pub struct Scroll { + pub amount: f32, + /// The pointer's last y while the scrollbar is held (`scrolling`). + held: Option, +} +impl Scroll { + fn max(top: f32, bottom: f32, content: f32) -> f32 { + (content - (bottom - top)).max(0.0) + } + /// `setScrollAmount`: kept within the content. + pub fn clamp(&mut self, top: f32, bottom: f32, content: f32) { + self.amount = self.amount.clamp(0.0, Self::max(top, bottom, content)); + } + /// `mouseScrolled`: `rate` pixels per wheel step. + pub fn wheel(&mut self, delta: f32, rate: f32, top: f32, bottom: f32, content: f32) { + self.amount -= delta * rate; + self.clamp(top, bottom, content); + } + /// `updateScrolling`: a press on the scrollbar column at `bar_x` (when + /// there is something to scroll) holds it. + pub fn press( + &mut self, + (x, y): (f32, f32), + bar_x: f32, + top: f32, + bottom: f32, + content: f32, + ) -> bool { + let over = x >= bar_x && x <= bar_x + 6.0 && y >= top && y < bottom; + self.held = (over && Self::max(top, bottom, content) > 0.0).then_some(y); + self.held.is_some() + } + pub fn held(&self) -> bool { + self.held.is_some() + } + /// `mouseDragged` while held: above or below the list jumps to an end, + /// otherwise the thumb follows the pointer. + pub fn drag(&mut self, y: f32, top: f32, bottom: f32, content: f32) { + let Some(last) = self.held else { return }; + let max = Self::max(top, bottom, content); + if y < top { + self.amount = 0.0; + } else if y > bottom { + self.amount = max; + } else { + let height = bottom - top; + let bar = ((height * height / content).trunc()).clamp(32.0, height - 8.0); + self.amount += (y - last) * (max.max(1.0) / (height - bar)).max(1.0); + } + self.clamp(top, bottom, content); + self.held = Some(y); + } + /// `onRelease`. + pub fn release(&mut self) { + self.held = None; + } +} + /// Vertical scroll bar (AbstractScrollArea): background and scroller sprites. pub fn scrollbar( batch: &mut HudBatch, @@ -874,6 +935,28 @@ impl EditBox { mod tests { use super::*; #[test] + fn held_scrollbars_follow_the_pointer_and_stop_at_the_ends() { + // A 100-pixel list holding 400: the thumb is 25 -> 32 high, so a + // pixel of drag scrolls 300 / 68 pixels (AbstractScrollArea.mouseDragged). + let (top, bottom, content) = (0.0, 100.0, 400.0); + let mut s = Scroll::default(); + assert!(!s.press((50.0, 10.0), 100.0, top, bottom, content)); + assert!(s.press((103.0, 10.0), 100.0, top, bottom, content)); + s.drag(20.0, top, bottom, content); + assert!((s.amount - 10.0 * 300.0 / 68.0).abs() < 1e-3); + s.drag(150.0, top, bottom, content); + assert_eq!(s.amount, 300.0); + s.drag(-5.0, top, bottom, content); + assert_eq!(s.amount, 0.0); + s.release(); + s.drag(50.0, top, bottom, content); + assert_eq!(s.amount, 0.0); + // Nothing to scroll: the column doesn't take the press. + assert!(!s.press((103.0, 10.0), 100.0, top, bottom, 90.0)); + s.wheel(-2.0, 18.0, top, bottom, content); + assert_eq!(s.amount, 36.0); + } + #[test] fn edit_box_editing() { let mut e = EditBox::new(0.0, 0.0, 100.0, 20.0); e.max_length = 10;