From 329334723d673c281b8641f62147547012dda158 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:11:23 +0100 Subject: [PATCH 1/6] Fix classic singleplayer world management UI parity --- Cargo.lock | 1 + crates/horizon-client/Cargo.toml | 1 + crates/horizon-client/src/front.rs | 22 +- crates/horizon-client/src/game.rs | 19 + crates/horizon-client/src/game/agent.rs | 25 +- crates/horizon-client/src/game/clipboard.rs | 8 +- crates/horizon-client/src/hud.rs | 10 + crates/horizon-client/src/title.rs | 879 +++++++++++++++--- crates/horizon-client/src/title/tests.rs | 360 +++++++ .../src/title/world_management.rs | 137 +++ 10 files changed, 1351 insertions(+), 111 deletions(-) create mode 100644 crates/horizon-client/src/title/tests.rs create mode 100644 crates/horizon-client/src/title/world_management.rs diff --git a/Cargo.lock b/Cargo.lock index 4694fb718..7836e5b29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -923,6 +923,7 @@ dependencies = [ "ureq", "wgpu", "winit", + "zip", ] [[package]] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 42841eecb..e0b3d3189 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -28,6 +28,7 @@ chrono = { version = "0.4.42", default-features = false, features = ["clock", "s flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } horizon-theme = { path = "../horizon-theme" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } +zip = { version = "2", default-features = false, features = ["deflate"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). gilrs = "0.11" # HTTPS to the Minecraft services (online-mode session join). diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 52bd977aa..fef4f7220 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -81,7 +81,12 @@ impl Default for Opening { fn page(mode: &Mode) -> usize { match mode { Mode::Main => 0, - Mode::Select { .. } | Mode::Create { .. } => 1, + Mode::Select { .. } + | Mode::Create { .. } + | Mode::Edit { .. } + | Mode::Backup { .. } + | Mode::Delete { .. } + | Mode::Error { .. } => 1, Mode::Multiplayer(_) => 2, } } @@ -91,6 +96,13 @@ impl Title { /// Horizon's layout for every title mode. `backdrop` is how much of the /// live backdrop is visible (0 shows the plain cold background). pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) { + if matches!( + self.mode, + Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } + ) { + self.draw(ui.atlas, ui.batch, ui.cursor); + return; + } let reveal = self.opening_phase(backdrop >= 1.0); if backdrop < 1.0 { ui.cold_background(1.0 - backdrop); @@ -135,6 +147,7 @@ impl Title { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); multiplayer_page(ui, x, w, screen, caret); } + _ => unreachable!("World-management screens use the classic layout"), } } ui.opacity = 1.0; @@ -306,6 +319,12 @@ impl Title { if self.skip_opening() { return Action::None; } + if matches!( + self.mode, + Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } + ) { + return self.click(x, y, (batch.width, batch.height)); + } let hit = { let mut ui = Ui::dry(atlas, batch, (x, y)); self.draw_horizon(&mut ui, 1.0); @@ -391,6 +410,7 @@ impl Title { MAKE => return self.create_action(), _ => {} }, + Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } => {} Mode::Multiplayer(screen) => { let id = match hit { JOIN => Some(40), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ed70ddc65..ce193c976 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3261,6 +3261,9 @@ impl Game<'_> { self.draw_options(&mut batch); return batch; } + if let Some(title) = &mut self.title { + title.poll_backup(); + } if let Some(title) = &self.title { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); @@ -8333,6 +8336,17 @@ impl ApplicationHandler for Game<'_> { }) * wheel_sensitivity }; let d = scaled(raw_y) as f32; + if let Some(title) = &mut self.title + && !horizon_client::ui_theme::horizon() + { + let size = self + .window + .as_ref() + .map(|w| w.inner_size()) + .unwrap_or_default(); + let batch = HudBatch::new([size.width, size.height]); + title.scroll_worlds(d, self.cursor, (batch.width, batch.height)); + } if self.screen == Screen::Playing && self.player.is_some() && !self.extras_scroll(d) @@ -8590,6 +8604,11 @@ impl ApplicationHandler for Game<'_> { return Ok(()); } match event.physical_key { + PhysicalKey::Code(KeyCode::Enter | KeyCode::NumpadEnter) => { + if let Some(t) = self.title.as_mut() { + t.confirm_edit(); + } + } PhysicalKey::Code(KeyCode::Backspace) => self.title_edit(None, true), PhysicalKey::Code(KeyCode::Tab) => { if let Some(t) = self.title.as_mut() { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 8b1b8071e..e2b02d199 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -490,6 +490,22 @@ impl Game<'_> { "focus": match focus { 0 => "name", 1 => "seed", _ => "none" }, "creative": creative, }), + Mode::Edit { + world, + name, + focused, + } => { + json!({ "mode": "edit-world", "folder": world.folder, "fields": { "name": name }, "focus": if *focused { "name" } else { "none" } }) + } + Mode::Backup { world, .. } => { + json!({ "mode": "creating-backup", "folder": world.folder }) + } + Mode::Delete { world } => { + json!({ "mode": "delete-world", "folder": world.folder, "name": world.name }) + } + Mode::Error { message, .. } => { + json!({ "mode": "world-operation-error", "message": message }) + } Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }), } } @@ -1312,7 +1328,14 @@ impl Game<'_> { } } } - _ => return Err("--field works on the create-world screen".into()), + horizon_client::title::Mode::Edit { focused, .. } if field == "name" => { + *focused = true + } + _ => { + return Err( + "--field works on the create-world or edit-world screen".into() + ); + } } } if replace { diff --git a/crates/horizon-client/src/game/clipboard.rs b/crates/horizon-client/src/game/clipboard.rs index 6b6b338ab..c28aa900c 100644 --- a/crates/horizon-client/src/game/clipboard.rs +++ b/crates/horizon-client/src/game/clipboard.rs @@ -47,7 +47,7 @@ impl Game<'_> { return; }; if let Some((id, value, max)) = title.focused_field() { - Self::append_shortcut( + let changed = Self::append_shortcut( &mut self.text_selection, &mut self.clipboard, id, @@ -55,6 +55,9 @@ impl Game<'_> { shortcut, max, ); + if changed { + title.search_changed(); + } } } /// Typing or a backspace in an append-only field of the title screens: @@ -66,6 +69,9 @@ impl Game<'_> { let cleared = title .focused_field() .is_some_and(|(id, value, _)| self.text_selection.take(id, value)); + if cleared { + title.search_changed(); + } if backspace { if !cleared { title.backspace(); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 71db32199..46c727b6c 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -35,6 +35,8 @@ pub const MAP_SLOTS: usize = 16; pub const MINIMAP_SPRITE: &str = "horizon/minimap"; /// Atlas slots for downloaded player skins (`skins/`), 64x64 each. pub const SKIN_SLOTS: usize = 32; +/// Reused by the visible rows of the classic world selector. +pub const WORLD_ICON_SLOTS: usize = 32; pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { decode_bytes(&fs::read(path)?) } @@ -213,6 +215,14 @@ impl HudAtlas { for i in 0..SKIN_SLOTS { images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4])); } + for i in 0..WORLD_ICON_SLOTS { + images.push(( + format!("horizon/world-icon{i}"), + 64, + 64, + vec![0; 64 * 64 * 4], + )); + } // Horizon-style menu text and corner masks (ui_theme), rasterized at run time. images.push(( "horizon/ui-text".into(), diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index ed47dff15..256516d63 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -5,6 +5,26 @@ use crate::{ save::Level, }; use std::path::{Path, PathBuf}; +use std::{ + cell::{Cell, RefCell}, + sync::mpsc, +}; + +#[cfg(test)] +mod tests; +mod world_management; + +const LIST_TOP: f32 = 48.0; +const LIST_BOTTOM: f32 = 58.0; +const ROW_HEIGHT: f32 = 36.0; +const ROW_WIDTH: f32 = 270.0; + +fn edit_top(h: f32) -> f32 { + ((h.ceil() - 234.0) / 2.0).floor() +} +fn confirm_top(h: f32, lines: usize) -> f32 { + ((h.ceil() - 61.0 - lines as f32 * 9.0) / 2.0).floor() +} #[derive(Clone, Debug)] pub struct WorldEntry { @@ -12,6 +32,8 @@ pub struct WorldEntry { pub name: String, pub creative: bool, pub modified: std::time::SystemTime, + pub commands: bool, + pub version: String, } #[derive(Clone, Debug)] pub enum Mode { @@ -26,6 +48,22 @@ pub enum Mode { creative: bool, focus: u8, }, + Edit { + world: WorldEntry, + name: String, + focused: bool, + }, + Backup { + world: WorldEntry, + name: String, + }, + Delete { + world: WorldEntry, + }, + Error { + message: String, + return_to: Box, + }, Multiplayer(crate::multiplayer::Screen), } #[derive(Clone, Debug, PartialEq)] @@ -50,6 +88,15 @@ pub struct Title { pub mode: Mode, pub saves: PathBuf, pub started: std::time::Instant, + search: String, + search_focused: bool, + scroll: Cell, + create_return_to_main: bool, + message_lines: Cell, + backup: Option>>, + backup_shown: Cell, + toast: Option<(std::time::Instant, String, u64)>, + icons: RefCell>)>>, /// The mode last drawn and when it appeared (Horizon's screen fades). shown: std::cell::Cell<(std::mem::Discriminant, std::time::Instant)>, /// The launcher-style opening (Horizon style, first title of the session). @@ -89,11 +136,21 @@ pub fn list_worlds(saves: &Path) -> Vec { let modified = std::fs::metadata(path.join("level.dat")) .and_then(|m| m.modified()) .ok()?; + let data = crate::save::read_dat(&path.join("level.dat"))?; + let data = data.get("Data")?; + let modified = match data.get("LastPlayed") { + Some(horizon_world::nbt::Tag::Long(millis)) if *millis >= 0 => std::time::UNIX_EPOCH + std::time::Duration::from_millis(*millis as u64), + _ => modified, + }; Some(WorldEntry { folder: e.file_name().to_string_lossy().into_owned(), name: level.name, creative: level.creative, modified, + commands: matches!(data.get("allowCommands"), Some(horizon_world::nbt::Tag::Byte(v)) if *v != 0), + version: data.get("Version").and_then(|v| v.get("Name")) + .and_then(|v| match v { horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()), _ => None }) + .unwrap_or_else(|| "Unknown".into()), }) }) .collect(); @@ -109,10 +166,179 @@ impl Title { mode, saves, started: now, + search: String::new(), + search_focused: false, + scroll: Cell::new(0.0), + create_return_to_main: false, + message_lines: Cell::new(1), + backup: None, + backup_shown: Cell::new(false), + toast: None, + icons: RefCell::new(std::collections::HashMap::new()), opening: std::cell::Cell::new(None), recent: std::cell::RefCell::new(None), } } + /// Vanilla bypasses the selector when there are no saves. + pub fn enter_singleplayer(&mut self) { + self.search.clear(); + self.search_focused = true; + self.scroll.set(0.0); + let worlds = list_worlds(&self.saves); + self.create_return_to_main = worlds.is_empty(); + self.mode = if worlds.is_empty() { + Self::new_world() + } else { + Mode::Select { + worlds, + selected: None, + } + }; + } + fn new_world() -> Mode { + Mode::Create { + name: "New World".into(), + seed: String::new(), + creative: false, + focus: 0, + } + } + fn return_to_list(&mut self, folder: Option<&str>) { + let worlds = list_worlds(&self.saves); + let selected = folder.and_then(|folder| { + worlds + .iter() + .position(|w| w.folder == folder && self.matches_search(w)) + }); + self.mode = Mode::Select { worlds, selected }; + *self.recent.borrow_mut() = None; + } + fn cancel_create(&mut self) { + if self.create_return_to_main { + self.mode = Mode::Main; + } else { + self.return_to_list(None); + } + } + fn matches_search(&self, world: &WorldEntry) -> bool { + let filter = self.search.to_lowercase(); + world.name.to_lowercase().contains(&filter) || world.folder.to_lowercase().contains(&filter) + } + fn visible_worlds<'a>( + &self, + worlds: &'a [WorldEntry], + ) -> impl Iterator { + worlds + .iter() + .enumerate() + .filter(|(_, w)| self.matches_search(w)) + .collect::>() + .into_iter() + } + /// Mouse wheel over the classic world list. + pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + let Mode::Select { worlds, .. } = &self.mode else { + return; + }; + if cursor.1 < LIST_TOP || cursor.1 >= size.1 - LIST_BOTTOM { + return; + } + let max = (self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0 + - (size.1 - LIST_TOP - LIST_BOTTOM)) + .max(0.0); + self.scroll + .set((self.scroll.get() - delta * ROW_HEIGHT / 2.0).clamp(0.0, max)); + } + fn failed(&mut self, error: impl std::fmt::Display) { + let return_to = Box::new(self.mode.clone()); + self.mode = Mode::Error { + message: error.to_string(), + return_to, + }; + } + /// Polling is done once per rendered frame so filesystem work never blocks drawing. + pub fn poll_backup(&mut self) { + if !self.backup_shown.get() { + return; + } + let Some(receiver) = &self.backup else { + return; + }; + let result = match receiver.try_recv() { + Ok(result) => result, + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => Err("Backup worker stopped".into()), + }; + self.backup = None; + if let Mode::Backup { world, name } = &self.mode { + let world = world.clone(); + let name = name.clone(); + self.mode = Mode::Edit { + world: world.clone(), + name, + focused: false, + }; + match result { + Ok(bytes) => self.toast = Some((std::time::Instant::now(), world.folder, bytes)), + Err(error) => self.failed(error), + } + } + } + fn start_backup(&mut self, world: WorldEntry, name: String) { + let (send, receive) = mpsc::channel(); + let saves = self.saves.clone(); + let folder = world.folder.clone(); + std::thread::spawn(move || { + let _ = send.send(world_management::backup(&saves, &folder).map_err(|e| e.to_string())); + }); + self.backup_shown.set(false); + self.backup = Some(receive); + self.mode = Mode::Backup { world, name }; + } + fn icon( + &self, + atlas: &HudAtlas, + batch: &mut HudBatch, + world: &WorldEntry, + slot: usize, + x: f32, + y: f32, + ) { + let path = self.saves.join(&world.folder).join("icon.png"); + let mut icons = self.icons.borrow_mut(); + let pixels = if let Ok(modified) = std::fs::metadata(&path).and_then(|m| m.modified()) { + let cached = icons + .entry(path.clone()) + .or_insert_with(|| (std::time::UNIX_EPOCH, None)); + if cached.0 != modified { + *cached = ( + modified, + crate::hud::decode(&path) + .ok() + .filter(|(w, h, _)| *w == 64 && *h == 64) + .map(|(_, _, p)| p), + ); + } + cached.1.as_ref() + } else { + None + }; + let sprite = format!("horizon/world-icon{slot}"); + 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.clone(), + }); + 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); + } + } /// The worlds, newest first, cached for two seconds (drawn every frame). pub fn recent_worlds(&self) -> Vec { let mut recent = self.recent.borrow_mut(); @@ -177,6 +403,7 @@ impl Title { } } fn buttons(&self, w: f32, h: f32) -> Vec