From 4768d3f65b9cc04ebc3f6639676c43c06ac2c2f9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:09:09 +0200 Subject: [PATCH] launcher: a Servers page that creates, runs and manages horizon-server servers (WIP) Co-Authored-By: Claude Opus 5.5 --- launcher/Cargo.lock | 1 + launcher/Cargo.toml | 3 + launcher/src/heads.rs | 98 ++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 496 ++---- launcher/src/servers.rs | 14 + launcher/src/servers_page.rs | 2803 ++++++++++++++++++++++++++++++++++ 7 files changed, 3046 insertions(+), 370 deletions(-) create mode 100644 launcher/src/heads.rs create mode 100644 launcher/src/servers_page.rs diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index bde1037b3..5503e0471 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2668,6 +2668,7 @@ dependencies = [ "horizon-prepare", "horizon-telemetry", "horizon-theme", + "image", "keyring", "oo7", "pulldown-cmark", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 34af6e2a1..09458b766 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -32,6 +32,9 @@ horizon-port-pack = { path = "../crates/horizon-port-pack" } horizon-telemetry = { path = "../crates/horizon-telemetry" } # The session file's random name. getrandom = "0.3" +# Players' heads on the Servers page, from the default skins in the player's own game files (already +# in the lockfile through gpui). +image = { version = "0.25", default-features = false, features = ["png"] } # Microsoft account secrets in the OS keychain: the Secret Service on Linux through oo7 (the same # build gpui uses), Keychain and Credential Manager through keyring. diff --git a/launcher/src/heads.rs b/launcher/src/heads.rs new file mode 100644 index 000000000..540cdd1e5 --- /dev/null +++ b/launcher/src/heads.rs @@ -0,0 +1,98 @@ +//! Players' heads for the Servers page: the face of the skin the game shows for them. Without the skin +//! service a player has vanilla's default skin for their UUID (`DefaultPlayerSkin.get`), read from the +//! player's own prepared game files. +use std::path::Path; + +/// `DefaultPlayerSkin.get(UUID)`: the default skin by `UUID.hashCode` (as the game's tab list picks it). +pub fn default_skin(uuid: u128) -> &'static str { + const SKINS: [&str; 18] = [ + "slim/alex", + "slim/ari", + "slim/efe", + "slim/kai", + "slim/makena", + "slim/noor", + "slim/steve", + "slim/sunny", + "slim/zuri", + "wide/alex", + "wide/ari", + "wide/efe", + "wide/kai", + "wide/makena", + "wide/noor", + "wide/steve", + "wide/sunny", + "wide/zuri", + ]; + let hilo = ((uuid >> 64) as u64) ^ (uuid as u64); + let hash = ((hilo >> 32) as i32) ^ (hilo as i32); + SKINS[hash.rem_euclid(SKINS.len() as i32) as usize] +} + +/// A UUID written with or without dashes. +pub fn parse_uuid(text: &str) -> Option { + let hex: String = text.chars().filter(|c| *c != '-').collect(); + (hex.len() == 32).then(|| u128::from_str_radix(&hex, 16).ok())? +} + +/// The 8 by 8 face, row by row as RGBA, with the hat layer over it: what the tab list draws. +pub fn face(skin_png: &[u8]) -> Option> { + let skin = image::load_from_memory_with_format(skin_png, image::ImageFormat::Png) + .ok()? + .to_rgba8(); + if skin.width() < 64 || skin.height() < 32 { + return None; + } + let mut out = Vec::with_capacity(64); + for y in 0..8 { + for x in 0..8 { + let base = skin.get_pixel(8 + x, 8 + y).0; + let hat = skin.get_pixel(40 + x, 8 + y).0; + out.push(if hat[3] > 0 { hat } else { base }); + } + } + Some(out) +} + +/// The face of a player with a default skin, from the prepared game files in `resources`. +pub fn default_face(resources: &Path, uuid: &str) -> Option> { + let skin = default_skin(parse_uuid(uuid)?); + let path = resources + .join("assets/minecraft/textures/entity/player") + .join(format!("{skin}.png")); + face(&std::fs::read(path).ok()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_skins_follow_the_uuid_hash() { + // OfflinePlayer:Alex and OfflinePlayer:Steve, as vanilla's server makes them. + assert_eq!( + parse_uuid("36532b5e-c442-3dbb-a24c-c7e55d0f979a"), + Some(0x36532b5ec4423dbba24cc7e55d0f979a) + ); + assert_eq!(default_skin(0), "slim/alex"); + assert_eq!(default_skin(1), "slim/ari"); + assert_eq!(default_skin(u128::MAX), "slim/alex"); + assert!(parse_uuid("not-a-uuid").is_none()); + } + + #[test] + fn the_face_wears_its_hat() { + let mut skin = image::RgbaImage::new(64, 64); + skin.put_pixel(8, 8, image::Rgba([1, 2, 3, 255])); + skin.put_pixel(9, 8, image::Rgba([4, 5, 6, 255])); + skin.put_pixel(41, 8, image::Rgba([7, 8, 9, 255])); + let mut png = Vec::new(); + skin.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let face = face(&png).unwrap(); + assert_eq!(face.len(), 64); + assert_eq!(face[0], [1, 2, 3, 255]); + assert_eq!(face[1], [7, 8, 9, 255]); + } +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 9e164d9fb..f9dccee61 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -2,6 +2,7 @@ pub mod account; pub mod backend; pub mod desktop; +pub mod heads; pub mod modpacks; pub mod mojang; pub mod servers; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index ca86b5b08..ad99bee8d 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -8,6 +8,7 @@ mod markdown; mod mcp; mod modpacks_page; mod perf; +mod servers_page; mod theme; use gpui::{ @@ -21,6 +22,7 @@ use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Upda use horizon_launcher::telemetry; use std::borrow::Cow; use std::collections::VecDeque; +use std::sync::atomic::Ordering; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -31,15 +33,17 @@ enum Page { Play, Versions, Modpacks, + Servers, Notes, Settings, } impl Page { - const ALL: [(Page, &'static str); 5] = [ + const ALL: [(Page, &'static str); 6] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), (Page::Modpacks, "Modpacks"), + (Page::Servers, "Servers"), (Page::Notes, "Patch notes"), (Page::Settings, "Settings"), ]; @@ -85,12 +89,6 @@ fn ease_out_cubic(x: f32) -> f32 { /// How often the launcher looks for new releases while it is open. const CHECK_EVERY: Duration = Duration::from_secs(4 * 3600); -#[derive(Clone, Copy, PartialEq)] -enum Mode { - Client, - Server, -} - enum Load { Loading, Ready(T), @@ -113,7 +111,6 @@ struct Launcher { update_install: Option<(String, bool)>, /// The install bar's previous and current fraction, so it moves rather than jumps. bar: (f32, f32), - mode: Mode, releases: Load>, installed: Vec, installing: Option<(String, f32)>, @@ -134,7 +131,10 @@ struct Launcher { /// The folder the running game keeps its settings in: the game home, or a modpack's. client_home: Option, crash: Option, - server: Option, + /// The Servers page (`servers_page.rs`). + servers: servers_page::Servers, + /// The window's own focus, so Tab reaches the controls when nothing else has the keyboard. + root_focus: FocusHandle, /// Microsoft accounts (accounts.json), the sign-in under way and what it last showed. accounts: Accounts, sign_in: Option, @@ -142,11 +142,6 @@ struct Launcher { keychain: bool, /// The game is waiting for its session (a token renewal) before it starts. starting_client: Option, - server_log: VecDeque, - server_error: Option, - input: String, - input_focused: bool, - focus: FocusHandle, /// Join a friend: the code typed on the Play page, and the one the game /// starting now joins. friend_code: String, @@ -157,7 +152,6 @@ struct Launcher { args_input: String, args_focused: bool, args_focus: FocusHandle, - console_scroll: ScrollHandle, /// Opt-in data collection: the player's answer and Settings' section (`collection`). collection: collection::Collection, tx: Sender, @@ -203,9 +197,6 @@ impl Launcher { if settings.minecraft_dir.is_none() { settings.minecraft_dir = backend::default_minecraft_dir(); } - if settings.server_dir.is_none() { - settings.server_dir = Some(backend::data_dir().join("server")); - } // Release builds on Linux keep their entry in the applications menu up to date (a moved // binary changes it); `HORIZON_LAUNCHER_DESKTOP_ENTRY=1` does it in a development build. if cfg!(target_os = "linux") @@ -244,7 +235,6 @@ impl Launcher { self_update: SelfUpdate::Idle, update_install: None, bar: (0., 0.), - mode: Mode::Client, releases: Load::Loading, installed, installing: None, @@ -265,22 +255,17 @@ impl Launcher { client_started: None, client_home: None, crash: None, - server: None, + servers: servers_page::Servers::new(), + root_focus: cx.focus_handle(), accounts: Accounts::load(), sign_in: None, sign_in_state: None, keychain: true, starting_client: None, - server_log: VecDeque::new(), - server_error: None, - input: String::new(), - input_focused: false, - focus: cx.focus_handle(), friend_code: String::new(), friend_focused: false, friend_focus: cx.focus_handle(), joining: None, - console_scroll: ScrollHandle::new(), collection: collection::Collection::load(), tx, rx, @@ -529,17 +514,13 @@ impl Launcher { .record_since("launcher.play_to_game_frame_ms", pressed); } } - let log = if job == Job::Server { - &mut self.server_log - } else { - &mut self.prepare_log - }; - log.push_back(line); - if log.len() > LOG_LINES { - log.pop_front(); - } - if job == Job::Server { - self.console_scroll.scroll_to_bottom(); + // The MCP server keeps its own server's log; the launcher's are the preparer's + // and the game's. + if job != Job::Server { + self.prepare_log.push_back(line); + if self.prepare_log.len() > LOG_LINES { + self.prepare_log.pop_front(); + } } } Msg::Exit(job, result) => { @@ -599,27 +580,12 @@ impl Launcher { }); } } - Job::Server => { - self.server = None; - let old = self - .server_log - .iter() - .any(|l| l.contains("unknown option --dedicated")); - self.server_error = error.map(|e| { - if old { - "This version has no dedicated server. Pick a newer one." - .to_string() - } else { - let tail = - self.server_log.iter().rev().find(|l| !l.trim().is_empty()); - tail.map_or(e.clone(), |t| format!("{e}: {t}")) - } - }); - } + Job::Server => {} } } } } + changed |= self.servers_tick(); if let Some(sign_in) = &self.sign_in { let state = sign_in.state(); let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); @@ -744,38 +710,11 @@ impl Launcher { let Some(tag) = self.selected().cloned() else { return; }; - match self.mode { - Mode::Client => { - if self.client.is_some() || self.starting_client.is_some() { - return; - } - self.starting_pack = None; - self.start_client(tag); - } - Mode::Server => { - if let Some(server) = &mut self.server { - server.send("stop"); - return; - } - let Some(folder) = self.settings.server_dir.clone() else { - return; - }; - if let Err(e) = std::fs::create_dir_all(&folder) { - self.server_error = Some(e.to_string()); - return; - } - self.server_error = None; - self.server_log.clear(); - match backend::spawn( - Job::Server, - backend::server_command(&tag, &folder), - self.tx.clone(), - ) { - Ok(r) => self.server = Some(r), - Err(e) => self.server_error = Some(e), - } - } + if self.client.is_some() || self.starting_client.is_some() { + return; } + self.starting_pack = None; + self.start_client(tag); } /// Starts the game: the session first (a network round trip when the token needs @@ -810,7 +749,7 @@ impl Launcher { }); } - fn choose_folder(&mut self, server: bool, cx: &mut Context) { + fn choose_folder(&mut self, cx: &mut Context) { let paths = cx.prompt_for_paths(PathPromptOptions { files: false, directories: true, @@ -821,11 +760,7 @@ impl Launcher { if let Ok(Ok(Some(mut paths))) = paths.await { if let Some(path) = paths.pop() { let _ = this.update(cx, |this, cx| { - if server { - this.settings.server_dir = Some(path); - } else { - this.settings.minecraft_dir = Some(path); - } + this.settings.minecraft_dir = Some(path); this.settings.save(); cx.notify(); }); @@ -834,18 +769,6 @@ impl Launcher { }) .detach(); } - - fn submit_command(&mut self) { - let line = std::mem::take(&mut self.input); - if line.trim().is_empty() { - return; - } - if let Some(server) = &mut self.server { - server.send(line.trim_start_matches('/')); - self.server_log.push_back(format!("> {line}")); - self.console_scroll.scroll_to_bottom(); - } - } } // ----- Building blocks --------------------------------------------------------------------------- @@ -978,6 +901,28 @@ fn mark(size: f32, t: &Theme) -> Div { ) } +/// The last thing the player did was press Tab: focused controls show a ring (a click focuses them +/// too, without one). +static KEYBOARD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Makes a control reachable with Tab, pressed with Enter or Space, with a ring when the keyboard +/// put it in focus. +fn keyboard(el: Stateful
, t: &Theme) -> Stateful
{ + let ring = t.accent; + el.tab_index(0).focus(move |s| { + if KEYBOARD.load(Ordering::Relaxed) { + s.shadow(vec![gpui::BoxShadow { + color: ring, + offset: gpui::point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(2.), + }]) + } else { + s + } + }) +} + fn button( id: impl Into, label: impl Into, @@ -1006,7 +951,7 @@ fn button( .cursor_pointer() .child(hover_layer(&id, hover, theme::RADIUS_PILL, 0.)) .child(div().relative().child(label.into())); - let base = track_hover(base, id); + let base = keyboard(track_hover(base, id), &t); match kind { Kind::Primary => base .bg(t.accent) @@ -1025,8 +970,7 @@ fn button( /// An on/off switch whose knob slides. fn switch(id: &'static str, on: bool, t: &Theme) -> Stateful
{ - div() - .id(id) + keyboard(div().id(id), t) .relative() .flex_none() .w(px(36.)) @@ -1069,8 +1013,7 @@ fn segments( .children(options.iter().map(|&(value, label)| { let active = current == value; let pick = on_pick.clone(); - div() - .id(SharedString::from(format!("{id}-{label}"))) + keyboard(div().id(SharedString::from(format!("{id}-{label}"))), &t) .flex() .items_center() .h(px(theme::SEGMENT)) @@ -1089,7 +1032,7 @@ fn segments( } fn disabled(b: Stateful
) -> Stateful
{ - b.opacity(theme::DISABLED).cursor_default() + b.opacity(theme::DISABLED).cursor_default().tab_stop(false) } /// A page's title in display type and one line on what it is for. @@ -1309,22 +1252,6 @@ impl Launcher { .child(links) } - fn segmented(&self, cx: &mut Context) -> Stateful
{ - let this = cx.entity().downgrade(); - segments( - "mode", - &[(Mode::Client, "Client"), (Mode::Server, "Server")], - self.mode, - &self.theme, - move |mode, _, cx| { - let _ = this.update(cx, |this, cx| { - this.mode = mode; - cx.notify(); - }); - }, - ) - } - fn picker(&self, cx: &mut Context) -> Div { let t = self.theme; let label = self @@ -1443,36 +1370,14 @@ impl Launcher { let prepared = backend::is_prepared(&tag); let version = backend::game_version(&tag); let hero = self.hero(&tag, &version, prepared, cx); - let running = match self.mode { - Mode::Client => self.client.is_some() || self.starting_client.is_some(), - Mode::Server => self.server.is_some(), - }; - let play_label = match (self.mode, running) { - (Mode::Client, false) => "Play", - (Mode::Client, true) => "Running", - (Mode::Server, false) => "Start server", - (Mode::Server, true) => "Stop server", - }; - let kind = if self.mode == Mode::Server && running { - Kind::Secondary - } else { - Kind::Primary - }; - let mut play = button("play", play_label, kind, &t) + let running = self.client.is_some() || self.starting_client.is_some(); + let play_label = if running { "Running" } else { "Play" }; + let mut play = button("play", play_label, Kind::Primary, &t) .min_w(px(132.)) .h(px(theme::CONTROL_LARGE)) .px(px(28.)) .text_size(px(theme::UI.px)); - let eula = self - .settings - .server_dir - .as_ref() - .is_some_and(|d| backend::eula_agreed(d)); - if !prepared - || self.preparing - || (self.mode == Mode::Client && running) - || (self.mode == Mode::Server && !eula) - { + if !prepared || self.preparing || running { play = disabled(play); } else { play = play.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { @@ -1485,7 +1390,14 @@ impl Launcher { .flex() .items_center() .justify_between() - .child(self.segmented(cx)) + .child( + button("host", "Host a server", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.go(Page::Servers); + cx.notify(); + }, + )), + ) .child( div() .flex() @@ -1533,33 +1445,30 @@ impl Launcher { .into_any_element() }, ); - let mut rows = - div() - .flex() - .flex_col() - .border_t_1() - .border_color(t.rule) - .child(index_row( - 1, - "Resources", - Some(div().child(resources_value).into_any_element()), - Some(prepare.into_any_element()), - &t, - )) - .child(index_row( - 2, - "Minecraft folder", - Some(minecraft), - Some( - button("choose-mc", "Choose…", Kind::Ghost, &t) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.choose_folder(false, cx) - })) - .into_any_element(), - ), - &t, - )); - if self.mode == Mode::Client { + let mut rows = div() + .flex() + .flex_col() + .border_t_1() + .border_color(t.rule) + .child(index_row( + 1, + "Resources", + Some(div().child(resources_value).into_any_element()), + Some(prepare.into_any_element()), + &t, + )) + .child(index_row( + 2, + "Minecraft folder", + Some(minecraft), + Some( + button("choose-mc", "Choose…", Kind::Ghost, &t) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.choose_folder(cx))) + .into_any_element(), + ), + &t, + )); + { let who = match self.accounts.selected() { Some(a) => format!("{} (Microsoft account)", a.name), None => "Offline: online servers need a Microsoft account.".to_string(), @@ -1580,62 +1489,6 @@ impl Launcher { &t, )); } - if self.mode == Mode::Server { - let folder = self - .settings - .server_dir - .as_deref() - .map(short) - .unwrap_or_default(); - rows = rows.child(index_row( - 3, - "Server folder", - Some( - div() - .font_family(theme::MONO) - .child(folder) - .into_any_element(), - ), - Some( - button("choose-server", "Choose…", Kind::Ghost, &t) - .on_click( - cx.listener(|this, _: &ClickEvent, _, cx| this.choose_folder(true, cx)), - ) - .into_any_element(), - ), - &t, - )); - let value = if eula { - "Agreed" - } else { - "Running a server needs your agreement to the Minecraft EULA." - }; - let mut actions = div().flex().gap(px(4.)).child( - button("eula-read", "Read", Kind::Ghost, &t).on_click(cx.listener( - |_, _: &ClickEvent, _, cx| cx.open_url("https://aka.ms/MinecraftEULA"), - )), - ); - if !eula { - actions = - actions.child(button("eula-agree", "Agree", Kind::Secondary, &t).on_click( - cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some(dir) = &this.settings.server_dir { - if let Err(e) = backend::agree_eula(dir) { - this.server_error = Some(e); - } - } - cx.notify(); - }), - )); - } - rows = rows.child(index_row( - 4, - "Minecraft EULA", - Some(div().child(value).into_any_element()), - Some(actions.into_any_element()), - &t, - )); - } let mut page = div() .flex() @@ -1668,18 +1521,11 @@ impl Launcher { if let Some(e) = self.prepare_error.clone() { page = page.child(notice(e, &t)); } - if self.mode == Mode::Client { - if let Some(e) = self.client_error.clone() { - page = page.child(notice(e, &t)); - } - if let Some(crash) = self.crash.clone() { - page = page.child(self.crash_notice(crash, cx)); - } - } else { - if let Some(e) = self.server_error.clone() { - page = page.child(notice(e, &t)); - } - page = page.child(self.console(cx)); + if let Some(e) = self.client_error.clone() { + page = page.child(notice(e, &t)); + } + if let Some(crash) = self.crash.clone() { + page = page.child(self.crash_notice(crash, cx)); } // The signature: the name, huge and faint, at the foot of the page. page.child( @@ -1819,11 +1665,7 @@ impl Launcher { .and_then(|r| backend::notes_summary(&r.body)), _ => None, }; - let title = if self.mode == Mode::Server { - "Horizon server" - } else { - "Horizon" - }; + let title = "Horizon"; let mut hero = div() .flex() @@ -2449,8 +2291,7 @@ impl Launcher { } fn join_friend(&mut self) { - if self.mode != Mode::Client || horizon_friends::invite::parse(&self.friend_code).is_none() - { + if horizon_friends::invite::parse(&self.friend_code).is_none() { return; } self.joining = Some(self.friend_code.clone()); @@ -2460,121 +2301,6 @@ impl Launcher { } } - fn console(&self, cx: &mut Context) -> Div { - let t = self.theme; - let running = self.server.is_some(); - let focused = self.input_focused; - let lines = self.server_log.iter().map(|l| div().child(l.clone())); - let log = div() - .id("console") - .h(px(260.)) - .px(px(20.)) - .py(px(12.)) - .overflow_y_scroll() - .track_scroll(&self.console_scroll) - .font_family(theme::MONO) - .text_size(px(theme::CAPTION.px)) - .line_height(px(19.)) - .text_color(t.ink_soft) - .when(self.server_log.is_empty(), |d| { - d.child(div().text_color(t.muted).child(if running { - "Starting…" - } else { - "The server's output shows here." - })) - }) - .children(lines); - let input = div() - .id("command") - .track_focus(&self.focus) - .flex() - .items_center() - .h(px(theme::FIELD + 8.)) - .px(px(20.)) - .border_t_1() - .border_color(t.rule) - .font_family(theme::MONO) - .text_size(px(theme::CAPTION.px)) - .cursor_text() - .child(div().text_color(t.accent).mr(px(10.)).child("›")) - .child(if self.input.is_empty() && !focused { - div().text_color(t.muted).child(if running { - "Type a command, e.g. list" - } else { - "Start the server to send commands" - }) - } else { - div().text_color(t.ink).child(self.input.clone()) - }) - .when(focused, |d| d.child(div().w(px(1.)).h(px(14.)).bg(t.ink))) - .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { - window.focus(&this.focus); - cx.notify(); - })) - .on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| { - let k = &ev.keystroke; - match k.key.as_str() { - "enter" => this.submit_command(), - "backspace" => { - this.input.pop(); - } - _ if !k.modifiers.control && !k.modifiers.platform => { - if let Some(ch) = &k.key_char { - this.input.push_str(ch); - } - } - _ => return, - } - cx.stop_propagation(); - cx.notify(); - })); - plate(&t) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex() - .items_center() - .justify_between() - .h(px(44.)) - .px(px(20.)) - .border_b_1() - .border_color(t.rule) - .child( - div() - .flex() - .items_center() - .gap(px(10.)) - .child(div().size(px(6.)).rounded_full().bg(if running { - t.success - } else { - t.muted - })) - .child( - caps(if running { "Running" } else { "Stopped" }) - .text_color(t.muted), - ), - ) - .when(running, |d| { - d.child( - button("kill", "Force stop", Kind::Ghost, &t) - .h(px(26.)) - .px(px(10.)) - .text_size(px(theme::CAPTION.px)) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some(s) = &this.server { - s.kill(); - } - cx.notify(); - })), - ) - }), - ) - .child(log) - .child(input) - } - fn versions_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; let header = page_header( @@ -2925,13 +2651,14 @@ impl Render for Launcher { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = self.theme; self.perf.frame(); - self.input_focused = self.focus.is_focused(window); + self.servers.note_focus(window); self.friend_focused = self.friend_focus.is_focused(window); self.args_focused = self.args_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), Page::Modpacks => self.modpacks_page(cx), + Page::Servers => self.servers_page(cx), Page::Notes => self.notes_page(cx), Page::Settings => self.settings_page(cx), }; @@ -2950,7 +2677,30 @@ impl Render for Launcher { ); let (reveal, held) = self.opening_phase(window); let ui = ease_out_cubic((reveal - 0.3) / 0.7); + if self.opening.is_none() && window.focused(cx).is_none() { + window.focus(&self.root_focus); + } let mut root = div() + .id("root") + .track_focus(&self.root_focus) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + match k.key.as_str() { + "tab" => { + KEYBOARD.store(true, Ordering::Relaxed); + if k.modifiers.shift { + window.focus_prev(); + } else { + window.focus_next(); + } + } + "escape" if this.servers_escape() => {} + _ => return, + } + cx.stop_propagation(); + cx.notify(); + })) + .capture_any_mouse_down(|_, _, _| KEYBOARD.store(false, Ordering::Relaxed)) .relative() .flex() .flex_col() @@ -2986,6 +2736,11 @@ impl Render for Launcher { ) .child(self.footer(cx)), ); + if self.page == Page::Servers { + if let Some(dialog) = self.create_dialog(cx) { + root = root.child(dialog); + } + } if self.asking_consent() { root = root.child(self.consent_screen(cx)); } @@ -3107,6 +2862,7 @@ fn main() { ) .expect("window"); cx.on_window_closed(|cx| { + servers_page::stop_on_quit(); telemetry::send_before_exit(); cx.quit() }) diff --git a/launcher/src/servers.rs b/launcher/src/servers.rs index fc72924e1..87dccbf35 100644 --- a/launcher/src/servers.rs +++ b/launcher/src/servers.rs @@ -710,6 +710,20 @@ pub fn names(dir: &Path, file: &str) -> Vec { .collect() } +/// A list file's names with their UUIDs (empty when the file has none). +pub fn entries(dir: &Path, file: &str) -> Vec<(String, String)> { + fs::read_to_string(dir.join(file)) + .ok() + .and_then(|t| serde_json::from_str::>(&t).ok()) + .unwrap_or_default() + .iter() + .filter_map(|e| { + let name = e["name"].as_str()?.to_string(); + Some((name, e["uuid"].as_str().unwrap_or_default().to_string())) + }) + .collect() +} + /// A backup, as `horizon-server backups --json` lists it. #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct Backup { diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs new file mode 100644 index 000000000..a83df527d --- /dev/null +++ b/launcher/src/servers_page.rs @@ -0,0 +1,2803 @@ +//! The Servers page: create a server in one dialog, then start, stop and watch it, give friends its +//! address, manage who may join, change its settings, back it up and update it, all with buttons. Every +//! action runs `horizon-server` or calls the running server's control API (`horizon_launcher::servers`). +use super::*; +use horizon_launcher::heads; +use horizon_launcher::servers::{ + self, Applied, Backup, Entry, Fix, NewServer, Problem, Status, World, +}; +use serde_json::Value; +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; + +/// The servers this launcher started in this session, stopped when it closes unless they run as a +/// service (`stop_on_quit`). +static STARTED_HERE: Mutex> = Mutex::new(Vec::new()); + +/// How often the open server's status and log are read, and the list's. +const POLL_OPEN: Duration = Duration::from_millis(1000); +const POLL_LIST: Duration = Duration::from_secs(3); + +/// Lines of the server's log kept on the page. +const CONSOLE_KEEP: usize = 1000; + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Field { + Name, + Seed, + Players, + Command, + AddPlayer, + Motd, + Port, +} + +impl Field { + const ALL: [Field; 7] = [ + Field::Name, + Field::Seed, + Field::Players, + Field::Command, + Field::AddPlayer, + Field::Motd, + Field::Port, + ]; +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Tab { + Overview, + Players, + Settings, + Backups, +} + +const TABS: [(Tab, &str); 4] = [ + (Tab::Overview, "Overview"), + (Tab::Players, "Players"), + (Tab::Settings, "Settings"), + (Tab::Backups, "Backups"), +]; + +const MODES: [(&str, &str); 3] = [ + ("survival", "Survival"), + ("creative", "Creative"), + ("adventure", "Adventure"), +]; + +const DIFFICULTIES: [(&str, &str); 4] = [ + ("peaceful", "Peaceful"), + ("easy", "Easy"), + ("normal", "Normal"), + ("hard", "Hard"), +]; + +/// What the background work reports. +pub(super) enum Event { + Polled { + dir: PathBuf, + status: Status, + logs: Option<(u64, Vec)>, + }, + Statuses(Vec<(PathBuf, Status)>), + Line(String), + Done(Result), + Created(Result), + Details { + dir: PathBuf, + config: Option, + backups: Vec, + service: bool, + }, + Applied(Result), + Pvp(Option), + UpdateCheck(Result), + Failed(String), +} + +/// The Create dialog's answers. +pub(super) struct Create { + new_world: bool, + copy: Option, + worlds: Vec<(String, PathBuf)>, + mode: &'static str, + difficulty: &'static str, + max_players: u32, + friends_only: bool, + check_accounts: bool, + eula: bool, + /// Create was pressed without the EULA ticked. + eula_missing: bool, +} + +pub(super) struct Servers { + list: Vec, + loaded: bool, + pub(super) open: Option, + tab: Tab, + statuses: HashMap, + polling: bool, + polled: Option, + log: VecDeque, + log_next: u64, + log_dir: Option, + console_scroll: ScrollHandle, + /// The action under way, and what it printed. + busy: Option, + job_log: VecDeque, + problem: Option, + note: Option, + pub(super) create: Option, + creating: bool, + config: Option, + /// Settings waiting for `config set`, and whether one runs. + queued: Vec<(String, String)>, + applying: bool, + /// Settings saved while the server ran that wait for its next start. + restart_needed: BTreeSet, + backups: Vec, + confirm_restore: Option, + service: Option, + update: Option, + pvp: Option, + texts: HashMap, + focus: HashMap, + focused: Option, + /// The field to put the keyboard in on the next frame. + focus_soon: Option, + copied: Option, + faces: HashMap>>, + tx: Sender, + rx: Receiver, +} + +impl Servers { + pub(super) fn new() -> Self { + let (tx, rx) = channel(); + Self { + list: Vec::new(), + loaded: false, + open: None, + tab: Tab::Overview, + statuses: HashMap::new(), + polling: false, + polled: None, + log: VecDeque::new(), + log_next: 0, + log_dir: None, + console_scroll: ScrollHandle::new(), + busy: None, + job_log: VecDeque::new(), + problem: None, + note: None, + create: None, + creating: false, + config: None, + queued: Vec::new(), + applying: false, + restart_needed: BTreeSet::new(), + backups: Vec::new(), + confirm_restore: None, + service: None, + update: None, + pvp: None, + texts: HashMap::new(), + focus: HashMap::new(), + focused: None, + focus_soon: None, + copied: None, + faces: HashMap::new(), + tx, + rx, + } + } + + fn text(&mut self, f: Field) -> &mut String { + self.texts.entry(f).or_default() + } + + fn value(&self, f: Field) -> &str { + self.texts.get(&f).map_or("", String::as_str) + } + + /// Which field has the keyboard, read every frame. + pub(super) fn note_focus(&mut self, window: &mut Window) { + if let Some(h) = self.focus_soon.take().and_then(|f| self.focus.get(&f)) { + window.focus(h); + } + self.focused = Field::ALL + .into_iter() + .find(|f| self.focus.get(f).is_some_and(|h| h.is_focused(window))); + } + + fn status(&self) -> Status { + self.open + .as_ref() + .and_then(|d| self.statuses.get(d).cloned()) + .unwrap_or_else(Status::stopped) + } + + /// A setting from server.toml (as `config --json` gave it). + fn setting(&self, section: &str, key: &str) -> Option<&Value> { + self.config + .as_ref() + .map(|c| &c[section][key]) + .filter(|v| !v.is_null()) + } + + /// A setting as shown: what was just asked for, else what server.toml holds. + fn shown(&self, section: &str, key: &str) -> String { + let full = format!("{section}.{key}"); + if let Some((_, v)) = self.queued.iter().rev().find(|(k, _)| *k == full) { + return v.clone(); + } + match self.setting(section, key) { + Some(Value::String(s)) => s.clone(), + None => String::new(), + Some(v) => v.to_string(), + } + } +} + +/// Stops the servers this launcher started, unless they run in the background as a service. +pub(super) fn stop_on_quit() { + for dir in STARTED_HERE.lock().unwrap().drain(..) { + if servers::service_installed(&dir) { + continue; + } + if let Some(api) = servers::Api::open(&dir) { + let _ = api.call("POST", "/api/v1/stop", None); + } + } +} + +/// The player's own name, to let them in on a friends-only server: the Microsoft account that plays, +/// else the name the game made up for them (`horizon-player.txt`). +fn own_name(accounts: &Accounts) -> Option { + accounts.selected().map(|a| a.name.clone()).or_else(|| { + std::fs::read_to_string(backend::game_home().join("horizon-player.txt")) + .ok() + .map(|n| n.trim().to_string()) + .filter(|n| !n.is_empty()) + }) +} + +fn bytes(n: u64) -> String { + match n { + 0..1_000_000 => format!("{} kB", n.div_ceil(1000)), + 1_000_000..1_000_000_000 => format!("{:.1} MB", n as f64 / 1e6), + _ => format!("{:.2} GB", n as f64 / 1e9), + } +} + +/// A backup's date and kind from its name (`2026-10-19_11-28-57-manual.zip`, UTC), for people. +fn backup_label(b: &Backup) -> (String, String) { + let stem = b.name.trim_end_matches(".zip"); + let (when, kind) = match stem.get(..19) { + Some(when) if stem.len() > 20 => (when, &stem[20..]), + _ => return (stem.to_string(), String::new()), + }; + let (date, time) = when.split_once('_').unwrap_or((when, "")); + let label = format!("{date} {} UTC", time.replace('-', ":")); + let kind = match kind { + "auto" => "Automatic".to_string(), + "manual" => "Made by hand".to_string(), + k if k.starts_with("before-") => format!("Before updating to {}", &k[7..]), + k => k.to_string(), + }; + (label, kind) +} + +fn uptime(secs: u64) -> String { + match secs { + 0..60 => format!("{secs} s"), + 60..3600 => format!("{} min", secs / 60), + 3600..86_400 => format!("{} h {:02} min", secs / 3600, secs / 60 % 60), + _ => format!("{} d {} h", secs / 86_400, secs / 3600 % 24), + } +} + +/// Keeps a field's text to 256 characters. +fn clip(text: &mut String) { + if let Some((at, _)) = text.char_indices().nth(256) { + text.truncate(at); + } +} + +impl Launcher { + // ----- Background work ------------------------------------------------------------------ + + /// Runs `job` on a thread with the page busy; its lines and result arrive as events. + fn server_job( + &mut self, + label: impl Into, + job: impl FnOnce(&dyn Fn(String)) -> Result + Send + 'static, + ) { + if self.servers.busy.is_some() { + return; + } + self.servers.busy = Some(label.into()); + self.servers.job_log.clear(); + self.servers.problem = None; + self.servers.note = None; + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let lines = tx.clone(); + let log = move |l: String| { + let _ = lines.send(Event::Line(l)); + }; + let _ = tx.send(Event::Done(job(&log))); + }); + } + + /// `horizon-server ` on the open server, as a job. + fn server_command(&mut self, label: &str, args: Vec) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + self.server_job(label.to_string(), move |log| { + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + servers::run_streamed(&dir, &args, log).map(|_| String::new()) + }); + } + + /// Reads the open server's settings, backups and service state again. + fn load_details(&self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let config = servers::config(&dir); + let backups = servers::backups(&dir).unwrap_or_default(); + let service = servers::service_installed(&dir); + let _ = tx.send(Event::Details { + dir, + config, + backups, + service, + }); + }); + } + + fn open_server(&mut self, dir: PathBuf) { + if self.servers.open.as_ref() == Some(&dir) { + return; + } + let s = &mut self.servers; + s.open = Some(dir); + s.tab = Tab::Overview; + s.config = None; + s.backups.clear(); + s.service = None; + s.update = None; + s.pvp = None; + s.problem = None; + s.note = None; + s.confirm_restore = None; + s.restart_needed.clear(); + s.texts.remove(&Field::Motd); + s.texts.remove(&Field::Port); + s.polled = None; + self.load_details(); + } + + /// Called with the launcher's other work: what the background sent, and the next status poll. + pub(super) fn servers_tick(&mut self) -> bool { + let mut changed = false; + while let Ok(event) = self.servers.rx.try_recv() { + changed = true; + self.servers_event(event); + } + if self.page != Page::Servers || self.servers.polling || !self.servers.loaded { + return changed; + } + let every = if self.servers.open.is_some() { + POLL_OPEN + } else { + POLL_LIST + }; + if self.servers.polled.is_some_and(|at| at.elapsed() < every) { + return changed; + } + self.servers.polled = Some(Instant::now()); + self.servers.polling = true; + let tx = self.servers.tx.clone(); + match self.servers.open.clone() { + Some(dir) => { + let since = if self.servers.log_dir.as_ref() == Some(&dir) { + self.servers.log_next + } else { + 0 + }; + std::thread::spawn(move || { + let api = servers::Api::open(&dir); + let status = api + .as_ref() + .and_then(|a| a.status()) + .unwrap_or_else(Status::stopped); + let logs = api.and_then(|a| a.logs(since)); + let _ = tx.send(Event::Polled { dir, status, logs }); + }); + } + None => { + let dirs: Vec = self.servers.list.iter().map(|e| e.dir.clone()).collect(); + std::thread::spawn(move || { + let all = dirs + .into_iter() + .map(|d| { + let s = servers::status(&d); + (d, s) + }) + .collect(); + let _ = tx.send(Event::Statuses(all)); + }); + } + } + changed + } + + fn servers_event(&mut self, event: Event) { + let s = &mut self.servers; + match event { + Event::Polled { dir, status, logs } => { + s.polling = false; + let was = s.statuses.get(&dir).map(|st| st.phase.clone()); + if was.as_deref() != Some("running") && status.phase == "running" { + // A fresh start took every saved setting. + s.restart_needed.clear(); + s.pvp = None; + } + if let Some((next, lines)) = logs { + if s.log_dir.as_ref() != Some(&dir) { + s.log.clear(); + s.log_dir = Some(dir.clone()); + } + if !lines.is_empty() { + s.log.extend(lines); + while s.log.len() > CONSOLE_KEEP { + s.log.pop_front(); + } + s.console_scroll.scroll_to_bottom(); + } + s.log_next = next; + } + let read_pvp = status.phase == "running" && s.pvp.is_none(); + s.statuses.insert(dir, status); + if read_pvp { + self.read_pvp(); + } + } + Event::Statuses(all) => { + s.polling = false; + s.statuses.extend(all); + } + Event::Line(line) => { + s.job_log.push_back(line); + while s.job_log.len() > 6 { + s.job_log.pop_front(); + } + } + Event::Done(result) => { + s.busy = None; + s.polled = None; + match result { + Ok(note) if !note.is_empty() => s.note = Some(note), + Ok(_) => {} + Err(p) => s.problem = Some(p), + } + self.load_details(); + } + Event::Created(result) => { + s.creating = false; + match result { + Ok(entry) => { + s.create = None; + s.list = servers::list(); + self.open_server(entry.dir.clone()); + self.servers.note = Some(format!( + "{} is ready. Press Start, then give your friends the address below.", + entry.name + )); + } + Err(p) => s.problem = Some(p), + } + } + Event::Details { + dir, + config, + backups, + service, + } => { + if s.open.as_ref() == Some(&dir) { + s.config = config; + s.backups = backups; + s.service = Some(service); + } + } + Event::Applied(result) => { + s.applying = false; + match result { + Ok(applied) if applied.running => s.restart_needed.extend(applied.restart), + Ok(_) => {} + Err(p) => s.problem = Some(p), + } + if s.queued.is_empty() { + self.load_details(); + } else { + self.apply_settings(); + } + } + Event::Pvp(on) => s.pvp = on, + Event::UpdateCheck(result) => match result { + Ok(v) => s.update = Some(v), + Err(p) => s.problem = Some(p), + }, + Event::Failed(e) => s.problem = Some(Problem::plain(e)), + } + } + + /// The `pvp` game rule, asked of the running game (it's a rule of the world, not a setting). + fn read_pvp(&self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let on = servers::Api::open(&dir) + .and_then(|a| a.command("gamerule pvp").ok()) + .and_then(|out| { + let text = out.join(" "); + let text = text.trim_end(); + if text.ends_with("true") { + Some(true) + } else if text.ends_with("false") { + Some(false) + } else { + None + } + }); + let _ = tx.send(Event::Pvp(on)); + }); + } + + /// Queues a setting for `horizon-server config set`; they go one batch at a time. + fn set_setting(&mut self, key: &str, value: String) { + self.servers.queued.retain(|(k, _)| k != key); + self.servers.queued.push((key.to_string(), value)); + self.servers.note = None; + if !self.servers.applying { + self.apply_settings(); + } + } + + fn apply_settings(&mut self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let batch = std::mem::take(&mut self.servers.queued); + if batch.is_empty() { + return; + } + self.servers.applying = true; + // Shown as asked until the file is read back. + if let Some(config) = &mut self.servers.config { + for (key, value) in &batch { + if let Some((section, field)) = key.split_once('.') { + let new = match &config[section][field] { + Value::Bool(_) => Value::Bool(value == "true"), + Value::Number(_) => value.parse::().map_or(Value::Null, Value::from), + _ => Value::String(value.clone()), + }; + config[section][field] = new; + } + } + } + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let pairs: Vec<(&str, String)> = + batch.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); + let _ = tx.send(Event::Applied(servers::set_config(&dir, &pairs))); + }); + } + + /// A command for the running game, through the control API; its answer shows in the console. + fn api_command(&mut self, line: String) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let tx = self.servers.tx.clone(); + self.servers.log.push_back(format!("> {line}")); + self.servers.console_scroll.scroll_to_bottom(); + std::thread::spawn(move || { + let result = servers::Api::open(&dir) + .ok_or_else(|| "The server isn't running.".to_string()) + .and_then(|a| a.command(&line)); + if let Err(e) = result { + let _ = tx.send(Event::Failed(e)); + } + }); + } + + fn start_server(&mut self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + STARTED_HERE.lock().unwrap().push(dir.clone()); + self.servers.restart_needed.clear(); + self.server_job("Starting", move |log| { + log("A new world takes a minute the first time".into()); + servers::run_streamed(&dir, &["start"], log).map(|_| String::new()) + }); + } + + fn fix(&mut self, fix: Fix, cx: &mut Context) { + self.servers.problem = None; + match fix { + Fix::UsePort(port) => { + self.set_setting("server.port", port.to_string()); + self.servers.texts.remove(&Field::Port); + self.servers.note = Some(format!( + "The server now uses port {port}. Press Start again." + )); + } + Fix::Prepare => match self.selected().cloned() { + Some(tag) if backend::is_prepared(&tag) => { + self.server_job("Copying the game files", move |log| { + log(format!("Copying the game files prepared for Horizon {tag}")); + servers::set_up(&tag) + .map(|_| "The game files are ready. Press Start again.".to_string()) + .map_err(Problem::plain) + }); + } + _ => { + self.servers.create = None; + self.go(Page::Play); + if !self.preparing { + self.prepare(); + } + } + }, + Fix::AgreeEula => { + if let Some(c) = &mut self.servers.create { + c.eula = true; + c.eula_missing = false; + } else if let Some(dir) = &self.servers.open { + if let Err(e) = backend::agree_eula(dir) { + self.servers.problem = Some(Problem::plain(e)); + } + } + } + Fix::ShowLog => { + self.servers.tab = Tab::Overview; + if let Some(dir) = &self.servers.open { + cx.open_with_system(&dir.join("logs")); + } + } + } + } + + // ----- Creating ------------------------------------------------------------------------- + + fn open_create(&mut self, cx: &mut Context) { + self.focus_handle(Field::Name, cx); + self.servers.focus_soon = Some(Field::Name); + let worlds = servers::player_worlds(); + let name = if self.servers.list.is_empty() { + "My server".to_string() + } else { + format!("Server {}", self.servers.list.len() + 1) + }; + *self.servers.text(Field::Name) = name; + self.servers.text(Field::Seed).clear(); + *self.servers.text(Field::Players) = own_name(&self.accounts).unwrap_or_default(); + self.servers.problem = None; + self.servers.create = Some(Create { + new_world: true, + copy: worlds.first().map(|w| w.1.clone()), + worlds, + mode: "survival", + difficulty: "normal", + max_players: 10, + friends_only: true, + check_accounts: false, + eula: false, + eula_missing: false, + }); + } + + fn create_server(&mut self) { + if self.servers.creating { + return; + } + let Some(c) = &mut self.servers.create else { + return; + }; + if !c.eula { + c.eula_missing = true; + return; + } + let Some(c) = self.servers.create.as_ref() else { + return; + }; + let world = match (&c.copy, c.new_world) { + (Some(dir), false) => World::Copy(dir.clone()), + _ => World::New { + seed: self.servers.value(Field::Seed).to_string(), + }, + }; + let players: Vec = self + .servers + .value(Field::Players) + .split([',', ' ']) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(); + let name = self.servers.value(Field::Name).trim().to_string(); + let spec = NewServer { + name: if name.is_empty() { + "My server".into() + } else { + name + }, + world, + game_mode: c.mode.into(), + difficulty: c.difficulty.into(), + max_players: c.max_players, + friends_only: c.friends_only, + check_accounts: c.check_accounts, + players, + eula: c.eula, + }; + let tag = self.selected().cloned(); + let tx = self.servers.tx.clone(); + self.servers.creating = true; + self.servers.problem = None; + self.servers.job_log.clear(); + std::thread::spawn(move || { + let lines = tx.clone(); + let log = move |l: String| { + let _ = lines.send(Event::Line(l)); + }; + let _ = tx.send(Event::Created(servers::create(&spec, tag.as_deref(), &log))); + }); + } + + // ----- Building blocks ------------------------------------------------------------------ + + fn focus_handle(&mut self, f: Field, cx: &mut Context) -> FocusHandle { + self.servers + .focus + .entry(f) + .or_insert_with(|| cx.focus_handle().tab_index(0).tab_stop(true)) + .clone() + } + + /// A one-line text field: typing, paste, Backspace, Enter to confirm, Escape, Tab to the next. + fn field( + &mut self, + f: Field, + placeholder: &'static str, + width: f32, + cx: &mut Context, + ) -> Stateful
{ + let t = self.theme; + let handle = self.focus_handle(f, cx); + let focused = self.servers.focused == Some(f); + let value = self.servers.value(f).to_string(); + let shown: String = { + let chars: Vec = value.chars().collect(); + chars[chars.len().saturating_sub(60)..].iter().collect() + }; + div() + .id(SharedString::from(format!("field-{f:?}"))) + .track_focus(&handle) + .flex() + .items_center() + .w(px(width)) + .h(px(theme::FIELD)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(theme::RADIUS)) + .border_1() + .border_color(if focused { t.accent } else { t.rule }) + .bg(t.surface) + .text_size(px(theme::UI.px)) + .cursor_text() + .child(if value.is_empty() && !focused { + div().text_color(t.muted).child(placeholder) + } else { + div().text_color(t.ink).child(shown) + }) + .when(focused, |d| { + d.child(div().flex_none().w(px(1.)).h(px(16.)).bg(t.ink)) + }) + .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| { + if let Some(h) = this.servers.focus.get(&f) { + window.focus(h); + } + cx.notify(); + })) + .on_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + let command = k.modifiers.control || k.modifiers.platform; + match k.key.as_str() { + "enter" => this.field_enter(f), + "escape" => { + if this.servers.create.is_some() && !this.servers.creating { + this.servers.create = None; + } + window.blur(); + } + "backspace" => { + this.servers.text(f).pop(); + } + "v" if command => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + let line = text.lines().next().unwrap_or_default().trim().to_string(); + this.servers.text(f).push_str(&line); + } + } + _ if !command => match &k.key_char { + Some(ch) if !ch.chars().any(char::is_control) => { + this.servers.text(f).push_str(ch) + } + _ => return, + }, + _ => return, + } + clip(this.servers.text(f)); + cx.stop_propagation(); + cx.notify(); + })) + } + + /// Escape closes the Create dialog. Whether it did. + pub(super) fn servers_escape(&mut self) -> bool { + if self.page != Page::Servers || self.servers.create.is_none() || self.servers.creating { + return false; + } + self.servers.create = None; + self.servers.problem = None; + true + } + + fn field_enter(&mut self, f: Field) { + match f { + Field::Name | Field::Seed | Field::Players => self.create_server(), + Field::Command => { + let line = std::mem::take(self.servers.text(Field::Command)); + let line = line.trim().trim_start_matches('/').to_string(); + if !line.is_empty() { + self.api_command(line); + } + } + Field::AddPlayer => self.add_player(), + Field::Motd => { + let motd = self.servers.value(Field::Motd).trim().to_string(); + if motd.is_empty() { + self.servers.problem = + Some(Problem::plain("Type the line players see under the name.")); + } else { + self.set_setting("server.motd", motd); + } + } + Field::Port => self.save_port(), + } + } + + fn save_port(&mut self) { + match self.servers.value(Field::Port).trim().parse::() { + Ok(port) if port >= 1024 => self.set_setting("server.port", port.to_string()), + _ => { + self.servers.problem = Some(Problem::plain( + "Use a port number from 1024 to 65535 (25565 is Minecraft's own).", + )) + } + } + } + + fn add_player(&mut self) { + let name = self.servers.value(Field::AddPlayer).trim().to_string(); + let valid = (3..=16).contains(&name.len()) + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + if !valid { + self.servers.problem = Some(Problem::plain( + "A Minecraft name has 3 to 16 letters, digits or underscores.", + )); + return; + } + self.servers.text(Field::AddPlayer).clear(); + self.server_command( + &format!("Letting {name} in"), + vec!["whitelist".into(), "add".into(), name], + ); + } + + /// A player's face, from the default skin their UUID picks (the server knows no other). + fn head(&mut self, uuid: &str, size: f32) -> Div { + let resources = servers::game_files(&servers::runtime_root(), "26.3"); + let face = self + .servers + .faces + .entry(uuid.to_string()) + .or_insert_with(|| heads::default_face(&resources, uuid)) + .clone(); + let cell = size / 8.; + let mut d = div() + .flex_none() + .flex() + .flex_col() + .size(px(size)) + .rounded(px(3.)) + .overflow_hidden() + .bg(self.theme.plate); + if let Some(pixels) = face { + for row in pixels.chunks(8) { + d = d.child(div().flex().children(row.iter().map(|p| { + div().size(px(cell)).bg(Hsla::from(gpui::Rgba { + r: p[0] as f32 / 255., + g: p[1] as f32 / 255., + b: p[2] as f32 / 255., + a: 1., + })) + }))); + } + } + d + } + + /// A row's small button. + fn small( + &self, + id: impl Into, + label: &'static str, + enabled: bool, + cx: &mut Context, + action: impl Fn(&mut Self) + 'static, + ) -> Stateful
{ + let b = button(id, label, Kind::Ghost, &self.theme) + .h(px(28.)) + .px(px(10.)) + .text_size(px(theme::CAPTION.px)); + if enabled { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + action(this); + cx.notify(); + })) + } else { + disabled(b) + } + } + + // ----- The page ------------------------------------------------------------------------- + + pub(super) fn servers_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if !self.servers.loaded { + self.servers.list = servers::list(); + self.servers.loaded = true; + if self.servers.open.is_none() && self.servers.list.len() == 1 { + let dir = self.servers.list[0].dir.clone(); + self.open_server(dir); + } + } + if let Some(dir) = self.servers.open.clone() { + if self.servers.list.iter().any(|e| e.dir == dir) { + return self.server_dashboard(&dir, cx); + } + self.servers.open = None; + } + let header = page_header( + "Servers", + "Host a world for your friends on this computer. Create one, press Start, and give them \ + the address.", + &t, + ); + let actions = div() + .flex() + .items_center() + .gap(px(8.)) + .child( + button("server-create", "Create a server", Kind::Primary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.open_create(cx); + cx.notify(); + }), + ), + ) + .child({ + let b = button("server-add", "Add a server folder…", Kind::Ghost, &t); + if self.servers.creating { + disabled(b) + } else { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_server_folder(cx); + cx.notify(); + })) + } + }); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(actions); + if let Some(p) = self + .servers + .problem + .clone() + .filter(|_| self.servers.create.is_none()) + { + page = page.child(self.problem_notice(p, cx)); + } + if self.servers.list.is_empty() { + return page.child(centered( + "No server yet. Create one: it takes a few seconds, and Create alone gives a \ + friends-only survival world.", + &t, + )); + } + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, e) in self.servers.list.clone().into_iter().enumerate() { + let status = self + .servers + .statuses + .get(&e.dir) + .cloned() + .unwrap_or_else(Status::stopped); + let detail = if status.running() { + format!( + "{} · {} of {} players", + phase_label(&status), + status.players.len(), + status.max_players.unwrap_or(0) + ) + } else { + format!("{} · {}", phase_label(&status), short(&e.dir)) + }; + let dir = e.dir.clone(); + list = list.child(index_row( + i + 1, + e.name.clone(), + Some(detail.into_any_element()), + Some( + button( + SharedString::from(format!("server-open-{i}")), + "Open", + Kind::Secondary, + &t, + ) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.open_server(dir.clone()); + cx.notify(); + })) + .into_any_element(), + ), + &t, + )); + } + page.child(list) + } + + fn add_server_folder(&mut self, cx: &mut Context) { + let paths = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Add".into()), + }); + cx.spawn(async move |this, cx| { + if let Ok(Ok(Some(mut paths))) = paths.await { + if let Some(dir) = paths.pop() { + let _ = this.update(cx, |this, cx| { + this.add_existing(dir); + cx.notify(); + }); + } + } + }) + .detach(); + } + + /// A folder with a server.toml joins the list; a vanilla server folder is set up first (its + /// server.properties becomes server.toml; its world, lists and EULA stay). + fn add_existing(&mut self, dir: PathBuf) { + let name = dir + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "Server".into()); + let tag = self.selected().cloned(); + let tx = self.servers.tx.clone(); + self.servers.creating = true; + self.servers.problem = None; + std::thread::spawn(move || { + let result = (|| { + if servers::program().is_none() { + let tag = + tag.ok_or_else(|| Problem::plain("Install a Horizon version first."))?; + servers::set_up(&tag).map_err(Problem::plain)?; + } + if !dir.join("server.toml").is_file() { + servers::run(&dir, &["init", "--yes"])?; + } + let entry = Entry { name, dir }; + servers::add(entry.clone()).map_err(Problem::plain)?; + Ok(entry) + })(); + let _ = tx.send(Event::Created(result)); + }); + } + + fn problem_notice(&self, p: Problem, cx: &mut Context) -> Div { + let t = self.theme; + let mut n = notice(p.message.clone(), &t).items_center(); + if let Some(fix) = p.fix { + let label = match &fix { + Fix::UsePort(port) => format!("Use port {port}"), + Fix::Prepare => "Prepare the game files".into(), + Fix::AgreeEula => "I agree to the EULA".into(), + Fix::ShowLog => "Open the logs".into(), + }; + n = n.child( + button("problem-fix", label, Kind::Secondary, &t) + .bg(t.plate) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.fix(fix.clone(), cx); + cx.notify(); + })), + ); + } + n.child( + button("problem-dismiss", "Dismiss", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.servers.problem = None; + cx.notify(); + }, + )), + ) + } + + fn server_dashboard(&mut self, dir: &Path, cx: &mut Context) -> Div { + let t = self.theme; + let status = self.servers.status(); + let name = self + .servers + .list + .iter() + .find(|e| e.dir == dir) + .map(|e| e.name.clone()) + .unwrap_or_default(); + let running = status.running(); + let busy = self.servers.busy.clone(); + let mut top = div().flex().flex_col().gap(px(10.)); + if self.servers.list.len() > 1 || self.servers.create.is_none() { + top = top.child( + div().flex().child( + caps("← All servers") + .id("servers-back") + .text_color(t.muted) + .cursor_pointer() + .hover(move |s| s.text_color(t.ink)) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.open = None; + this.servers.polled = None; + this.servers.problem = None; + this.servers.note = None; + cx.notify(); + })), + ), + ); + } + let dot = match status.phase.as_str() { + "running" if status.crashes > 0 => t.accent, + "running" => t.success, + "stopped" => t.muted, + _ => t.accent, + }; + top = top + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child(div().size(px(8.)).rounded_full().bg(dot)) + .child(caps(phase_label(&status)).text_color(t.muted)) + .when_some(status.uptime.filter(|_| running), |d, up| { + d.child(caps(format!("· up {}", uptime(up))).text_color(t.muted)) + }), + ) + .child(text(theme::DISPLAY).text_color(t.ink).child(name)); + if status.crashes > 0 { + top = top.child(text(theme::CAPTION).text_color(t.muted).child(format!( + "The game crashed {} time{} and was restarted by itself{}.", + status.crashes, + if status.crashes == 1 { "" } else { "s" }, + status + .last_crash + .as_ref() + .map(|c| format!(" (last: {c})")) + .unwrap_or_default() + ))); + } + + // The big buttons. + let big = |b: Stateful
| { + b.min_w(px(132.)) + .h(px(theme::CONTROL_LARGE)) + .px(px(28.)) + .text_size(px(theme::UI.px)) + }; + let idle = busy.is_none(); + let start = big(button( + "server-start", + if running { "Stop" } else { "Start" }, + if running { + Kind::Secondary + } else { + Kind::Primary + }, + &t, + )); + let start = if !idle { + disabled(start) + } else if running { + start.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.server_command("Stopping", vec!["stop".into()]); + cx.notify(); + })) + } else { + start.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.start_server(); + cx.notify(); + })) + }; + let restart = big(button("server-restart", "Restart", Kind::Secondary, &t)); + let restart = if idle && running { + restart.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.restart_needed.clear(); + this.server_command("Restarting", vec!["restart".into()]); + cx.notify(); + })) + } else { + disabled(restart) + }; + let panel = button("server-panel", "Open the web panel", Kind::Ghost, &t); + let panel = if running { + let d = dir.to_path_buf(); + panel.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + match servers::Api::open(&d).map(|a| a.panel_link()) { + Some(Ok(url)) => cx.open_url(&url), + Some(Err(e)) => this.servers.problem = Some(Problem::plain(e)), + None => {} + } + cx.notify(); + })) + } else { + disabled(panel) + }; + let folder = dir.to_path_buf(); + let buttons = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .child(start) + .child(restart) + .child(panel) + .child( + button("server-folder", "Open the folder", Kind::Ghost, &t) + .on_click(move |_, _, cx| cx.open_with_system(&folder)), + ); + + let mut page = div() + .flex() + .flex_col() + .gap(px(24.)) + .child(top) + .child(buttons); + if let Some(label) = &busy { + let last = self.servers.job_log.back().cloned().unwrap_or_default(); + page = page.child( + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(progress_bar(None, &t)) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .truncate() + .child(format!("{label}… {last}")), + ), + ); + } + if let Some(p) = self.servers.problem.clone() { + page = page.child(self.problem_notice(p, cx)); + } + if let Some(n) = self.servers.note.clone() { + page = page.child( + plate(&t) + .flex() + .items_center() + .gap(px(12.)) + .p(px(16.)) + .child(div().flex_none().size(px(6.)).rounded_full().bg(t.success)) + .child( + div() + .flex_1() + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(n), + ), + ); + } + if running && !self.servers.restart_needed.is_empty() { + let names: Vec<&str> = self + .servers + .restart_needed + .iter() + .map(|k| setting_name(k)) + .collect(); + page = page.child( + plate(&t) + .flex() + .items_center() + .gap(px(12.)) + .p(px(16.)) + .child(div().flex_none().size(px(6.)).rounded_full().bg(t.accent)) + .child( + div() + .flex_1() + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(format!("Saved. Restart to apply: {}.", names.join(", "))), + ) + .child({ + let b = + button("restart-apply", "Restart now", Kind::Secondary, &t).bg(t.plate); + if idle { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.restart_needed.clear(); + this.server_command("Restarting", vec!["restart".into()]); + cx.notify(); + })) + } else { + disabled(b) + } + }), + ); + } + page = page.child(self.stats(&status)); + let this = cx.entity().downgrade(); + page = page.child(div().flex().child(segments( + "server-tabs", + &TABS, + self.servers.tab, + &t, + move |tab, _, cx| { + let _ = this.update(cx, |this, cx| { + this.servers.tab = tab; + this.servers.confirm_restore = None; + cx.notify(); + }); + }, + ))); + let body = match self.servers.tab { + Tab::Overview => self.overview_tab(&status, cx), + Tab::Players => self.players_tab(dir, &status, cx), + Tab::Settings => self.settings_tab(&status, cx), + Tab::Backups => self.backups_tab(&status, cx), + }; + page.child(body) + } + + fn stats(&self, status: &Status) -> Div { + let t = self.theme; + let tile = |value: String, label: &'static str| { + plate(&t) + .flex() + .flex_col() + .flex_1() + .gap(px(4.)) + .p(px(16.)) + .child(text(theme::TITLE).text_color(t.ink).child(value)) + .child(caps(label).text_color(t.muted)) + }; + let dash = || "–".to_string(); + let on = status.running(); + div() + .flex() + .gap(px(12.)) + .child(tile( + if on { + format!( + "{} / {}", + status.players.len(), + status.max_players.unwrap_or(0) + ) + } else { + dash() + }, + "Players online", + )) + .child(tile( + status + .tps + .filter(|_| on) + .map_or_else(dash, |v| format!("{v:.1}")), + "TPS · 20 is full speed", + )) + .child(tile( + status + .mspt + .filter(|_| on) + .map_or_else(dash, |v| format!("{v:.1} ms")), + "MSPT · tick time", + )) + .child(tile( + status + .ram_bytes + .filter(|_| on) + .map_or_else(dash, |b| format!("{:.2} GB", b as f64 / 1e9)), + "RAM", + )) + } + + fn overview_tab(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let port = self + .servers + .setting("server", "port") + .and_then(Value::as_u64) + .unwrap_or(25565); + let lan = servers::lan_address(); + let address = match lan { + Some(ip) if port == 25565 => ip.to_string(), + Some(ip) => format!("{ip}:{port}"), + None => format!("localhost:{port}"), + }; + let copied = self + .servers + .copied + .is_some_and(|at| at.elapsed() < Duration::from_secs(2)); + let copy_text = address.clone(); + let address_plate = plate(&t) + .flex() + .flex_col() + .gap(px(10.)) + .p(px(20.)) + .child(caps("Address on this network").text_color(t.muted)) + .child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child( + text(theme::TITLE) + .font_family(theme::MONO) + .text_color(t.ink) + .child(address), + ) + .child( + button( + "address-copy", + if copied { "Copied" } else { "Copy" }, + Kind::Secondary, + &t, + ) + .bg(t.plate) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string( + copy_text.clone(), + )); + this.servers.copied = Some(Instant::now()); + cx.notify(); + })), + ), + ) + .child(text(theme::CAPTION).text_color(t.ink_soft).child( + "Friends on the same Wi-Fi: Multiplayer, Add Server, then paste this address.", + )) + .child(text(theme::CAPTION).text_color(t.muted).child(format!( + "Friends elsewhere can't reach it as it is: use Tailscale (free, nothing to change \ + on your router, only people you invite), or forward TCP port {port} on your router \ + to this computer." + ))); + let mut tab = div().flex().flex_col().gap(px(20.)).child(address_plate); + if !status.players.is_empty() { + let mut row = div().flex().flex_wrap().gap(px(16.)); + for p in status.players.clone() { + row = row.child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.head(&p.uuid, 20.)) + .child(text(theme::UI).text_color(t.ink).child(p.name.clone())), + ); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(caps("Online now").text_color(t.muted)) + .child(row), + ); + } + tab.child(self.server_console(status.running(), cx)) + } + + fn server_console(&mut self, running: bool, cx: &mut Context) -> Div { + let t = self.theme; + let lines: Vec
= self + .servers + .log + .iter() + .map(|l| { + div() + .when(l.starts_with("> "), |d| d.text_color(t.accent)) + .child(l.clone()) + }) + .collect(); + let empty = self.servers.log.is_empty(); + let log = div() + .id("server-console") + .h(px(240.)) + .px(px(20.)) + .py(px(12.)) + .overflow_y_scroll() + .track_scroll(&self.servers.console_scroll) + .font_family(theme::MONO) + .text_size(px(theme::CAPTION.px)) + .line_height(px(19.)) + .text_color(t.ink_soft) + .when(empty, |d| { + d.child(div().text_color(t.muted).child(if running { + "Waiting for the server's log…" + } else { + "The server's log shows here while it runs." + })) + }) + .children(lines); + let input = if running { + self.field( + Field::Command, + "Type a command: say Hello, time set day, gamemode creative Alex…", + 520., + cx, + ) + .flex_1() + .border_0() + .bg(t.plate_soft) + .font_family(theme::MONO) + .text_size(px(theme::CAPTION.px)) + .into_any_element() + } else { + div() + .px(px(12.)) + .h(px(theme::FIELD)) + .flex() + .items_center() + .text_size(px(theme::CAPTION.px)) + .text_color(t.muted) + .child("Start the server to type commands") + .into_any_element() + }; + plate(&t) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex() + .items_center() + .h(px(40.)) + .px(px(20.)) + .border_b_1() + .border_color(t.rule) + .child(caps("Console").text_color(t.muted)), + ) + .child(log) + .child( + div() + .flex() + .items_center() + .px(px(8.)) + .py(px(4.)) + .border_t_1() + .border_color(t.rule) + .child(div().text_color(t.accent).ml(px(12.)).child("›")) + .child(input), + ) + } + + fn players_tab(&mut self, dir: &Path, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let running = status.running(); + let idle = self.servers.busy.is_none(); + let ops = servers::names(dir, "ops.json"); + let whitelist = servers::entries(dir, "whitelist.json"); + let banned = servers::names(dir, "banned-players.json"); + let is_op = |n: &str| ops.iter().any(|o| o.eq_ignore_ascii_case(n)); + let mut tab = div().flex().flex_col().gap(px(28.)); + + // Online now. + let mut online = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in status.players.clone().into_iter().enumerate() { + let op = is_op(&p.name); + let (n1, n2, n3) = (p.name.clone(), p.name.clone(), p.name.clone()); + let actions = div() + .flex() + .gap(px(2.)) + .child(self.small( + SharedString::from(format!("online-op-{i}")), + if op { + "Remove operator" + } else { + "Make operator" + }, + idle, + cx, + move |this| { + let verb = if op { "deop" } else { "op" }; + this.server_command("Changing operators", vec![verb.into(), n1.clone()]); + }, + )) + .child(self.small( + SharedString::from(format!("online-kick-{i}")), + "Kick", + running, + cx, + move |this| this.api_command(format!("kick {n2}")), + )) + .child(self.small( + SharedString::from(format!("online-ban-{i}")), + "Ban", + running, + cx, + move |this| this.api_command(format!("ban {n3}")), + )); + let ping = p.ping.map(|ms| format!("{ms} ms ping")).unwrap_or_default(); + online = online.child( + div() + .flex() + .items_center() + .gap(px(14.)) + .min_h(px(theme::ROW)) + .py(px(8.)) + .border_b_1() + .border_color(t.rule) + .child(self.head(&p.uuid, 24.)) + .child( + div() + .flex() + .flex_col() + .flex_1() + .child(text(theme::UI).text_color(t.ink).child(p.name.clone())) + .child(text(theme::CAPTION).text_color(t.muted).child(if op { + format!("Operator · {ping}") + } else { + ping + })), + ) + .child(actions), + ); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(10.)) + .child( + text(theme::HEADING) + .text_color(t.ink) + .child(format!("Online now ({})", status.players.len())), + ) + .child(if status.players.is_empty() { + text(theme::UI) + .text_color(t.muted) + .child(if running { + "Nobody is playing right now." + } else { + "The server is stopped." + }) + .into_any_element() + } else { + online.into_any_element() + }), + ); + + // Who may join. + let friends_only = self + .servers + .setting("server", "whitelist") + .and_then(Value::as_bool) + .unwrap_or(true); + let toggle = switch("friends-only", friends_only, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.set_setting("server.whitelist", (!friends_only).to_string()); + cx.notify(); + }, + )); + let add = div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.field(Field::AddPlayer, "A player's name", 240., cx)) + .child({ + let b = button("player-add", "Let in", Kind::Secondary, &t); + if idle { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_player(); + cx.notify(); + })) + } else { + disabled(b) + } + }); + let mut people: Vec<(String, String)> = whitelist.clone(); + for op in &ops { + if !people.iter().any(|(n, _)| n.eq_ignore_ascii_case(op)) { + people.push((op.clone(), String::new())); + } + } + let mut allowed = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, (name, uuid)) in people.into_iter().enumerate() { + let op = is_op(&name); + let listed = whitelist.iter().any(|(n, _)| n == &name); + let (n1, n2) = (name.clone(), name.clone()); + let mut actions = div().flex().gap(px(2.)).child(self.small( + SharedString::from(format!("allowed-op-{i}")), + if op { + "Remove operator" + } else { + "Make operator" + }, + idle, + cx, + move |this| { + let verb = if op { "deop" } else { "op" }; + this.server_command("Changing operators", vec![verb.into(), n1.clone()]); + }, + )); + if listed { + actions = actions.child(self.small( + SharedString::from(format!("allowed-remove-{i}")), + "Remove", + idle, + cx, + move |this| { + this.server_command( + "Updating the list", + vec!["whitelist".into(), "remove".into(), n2.clone()], + ); + }, + )); + } + let head = if uuid.is_empty() { + div().size(px(24.)).flex_none() + } else { + self.head(&uuid, 24.) + }; + let about = match (op, listed) { + (true, true) => Some("Operator: can run every command"), + (true, false) => Some("Operator (not on the list: can join anyway)"), + _ => None, + }; + allowed = allowed.child( + div() + .flex() + .items_center() + .gap(px(14.)) + .min_h(px(theme::ROW)) + .py(px(8.)) + .border_b_1() + .border_color(t.rule) + .child(head) + .child( + div() + .flex() + .flex_col() + .flex_1() + .child(text(theme::UI).text_color(t.ink).child(name.clone())) + .when_some(about, |d, a| { + d.child(text(theme::CAPTION).text_color(t.muted).child(a)) + }), + ) + .child(actions), + ); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(14.)) + .child(text(theme::HEADING).text_color(t.ink).child("Who may join")) + .child( + div() + .flex() + .items_center() + .gap(px(14.)) + .child(toggle) + .child( + div() + .flex() + .flex_col() + .child(text(theme::UI).text_color(t.ink).child("Friends only")) + .child(text(theme::CAPTION).text_color(t.muted).child( + if friends_only { + "On: only the players below can join." + } else { + "Off: anyone who has the address can join." + }, + )), + ), + ) + .child(add) + .child(allowed), + ); + + // Banned. + if !banned.is_empty() { + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, name) in banned.into_iter().enumerate() { + let n = name.clone(); + list = list.child(index_row( + i + 1, + name, + None, + Some( + self.small( + SharedString::from(format!("unban-{i}")), + "Unban", + running, + cx, + move |this| this.api_command(format!("pardon {n}")), + ) + .into_any_element(), + ), + &t, + )); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(text(theme::HEADING).text_color(t.ink).child("Banned")) + .when(!running, |d| { + d.child( + text(theme::CAPTION) + .text_color(t.muted) + .child("Start the server to unban someone."), + ) + }) + .child(list), + ); + } + tab + } + + /// A row of the settings form: a name, one line on it, and its control. + fn setting_row(&self, name: &str, about: String, control: AnyElement) -> Div { + let t = self.theme; + div() + .flex() + .items_center() + .gap(px(16.)) + .min_h(px(theme::ROW)) + .py(px(12.)) + .border_b_1() + .border_color(t.rule) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(2.)) + .child(text(theme::UI).text_color(t.ink).child(name.to_string())) + .child(text(theme::CAPTION).text_color(t.muted).child(about)), + ) + .child(control) + } + + /// − value + for a number setting within `range`. + fn stepper( + &self, + key: &'static str, + range: std::ops::RangeInclusive, + cx: &mut Context, + ) -> AnyElement { + let t = self.theme; + let (section, field) = key.split_once('.').unwrap_or_default(); + let value: i64 = self.servers.shown(section, field).parse().unwrap_or(0); + let make = |id: &'static str, label: &'static str, to: i64, cx: &mut Context| { + let b = button( + SharedString::from(format!("{key}-{id}")), + label, + Kind::Secondary, + &t, + ) + .w(px(36.)) + .px(px(0.)); + if range.contains(&to) && to != value { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_setting(key, to.to_string()); + cx.notify(); + })) + } else { + disabled(b) + } + }; + div() + .flex() + .items_center() + .gap(px(8.)) + .child(make("less", "−", value - 1, cx)) + .child( + text(theme::UI) + .w(px(44.)) + .flex() + .justify_center() + .text_color(t.ink) + .child(value.to_string()), + ) + .child(make("more", "+", value + 1, cx)) + .into_any_element() + } + + fn choice( + &self, + id: &'static str, + key: &'static str, + options: &[(&'static str, &'static str)], + cx: &mut Context, + ) -> AnyElement { + let (section, field) = key.split_once('.').unwrap_or_default(); + let current = self.servers.shown(section, field); + let current: &'static str = options + .iter() + .find(|(v, _)| *v == current) + .map_or("", |(v, _)| v); + let this = cx.entity().downgrade(); + segments(id, options, current, &self.theme, move |value, _, cx| { + let _ = this.update(cx, |this, cx| { + this.set_setting(key, value.to_string()); + cx.notify(); + }); + }) + .into_any_element() + } + + fn settings_tab(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let running = status.running(); + if self.servers.config.is_none() { + return div().child(centered( + "Reading the settings… A server set up by an older Horizon shows them here once \ + it's updated (Backups and updates, below).", + &t, + )); + } + if self.servers.focused != Some(Field::Motd) + && !self.servers.texts.contains_key(&Field::Motd) + { + *self.servers.text(Field::Motd) = self.servers.shown("server", "motd"); + } + if self.servers.focused != Some(Field::Port) + && !self.servers.texts.contains_key(&Field::Port) + { + *self.servers.text(Field::Port) = self.servers.shown("server", "port"); + } + let save = |id: &'static str, f: Field, cx: &mut Context| { + button(id, "Save", Kind::Secondary, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.field_enter(f); + cx.notify(); + }, + )) + }; + let motd = div() + .flex() + .gap(px(8.)) + .child(self.field(Field::Motd, "A Minecraft Server", 260., cx)) + .child(save("motd-save", Field::Motd, cx)) + .into_any_element(); + let port = div() + .flex() + .gap(px(8.)) + .child(self.field(Field::Port, "25565", 100., cx)) + .child(save("port-save", Field::Port, cx)) + .into_any_element(); + let pvp = match (running, self.servers.pvp) { + (true, Some(on)) => switch("pvp", on, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.servers.pvp = Some(!on); + this.api_command(format!("gamerule pvp {}", !on)); + cx.notify(); + })) + .into_any_element(), + _ => disabled(switch("pvp", true, &t)).into_any_element(), + }; + let accounts = self + .servers + .setting("server", "online_mode") + .and_then(Value::as_bool) + .unwrap_or(false); + let accounts_switch = switch("online-mode", accounts, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_setting("server.online_mode", (!accounts).to_string()); + cx.notify(); + })) + .into_any_element(); + let live = if running { + "Applies at once." + } else { + "Used from the next start." + }; + let later = if running { + "Saved now, used after a restart." + } else { + "Used from the next start." + }; + let form = div() + .flex() + .flex_col() + .border_t_1() + .border_color(t.rule) + .child(self.setting_row( + "Message in the server list", + format!("What players see under the server's name (the MOTD). {later}"), + motd, + )) + .child(self.setting_row( + "Game mode", + format!("For players who join for the first time. {live}"), + self.choice("set-mode", "world.game_mode", &MODES, cx), + )) + .child(self.setting_row( + "Difficulty", + live.into(), + self.choice("set-difficulty", "world.difficulty", &DIFFICULTIES, cx), + )) + .child(self.setting_row( + "Players can hurt each other (PvP)", + if running { + "A rule of the world. Applies at once.".into() + } else { + "A rule of the world: start the server to change it.".into() + }, + pvp, + )) + .child(self.setting_row( + "Most players at once", + format!("Operators can always join. {later}"), + self.stepper("server.max_players", 1..=100, cx), + )) + .child(self.setting_row( + "View distance", + format!("How far players see, in chunks (2 to 32). Lower is lighter. {later}"), + self.stepper("server.view_distance", 2..=32, cx), + )) + .child(self.setting_row( + "Simulation distance", + format!("How far from players crops grow and mobs move, in chunks. {later}"), + self.stepper("server.simulation_distance", 2..=32, cx), + )) + .child(self.setting_row( + "Port", + format!( + "1024 to 65535. Friends type it after the address unless it's 25565. {later}" + ), + port, + )) + .child(self.setting_row( + "Check Minecraft accounts", + if accounts { + format!("On: players must own Minecraft and sign in with Microsoft. {later}") + } else { + format!("Off: anyone can play under any name, so keep Friends only on. {later}") + }, + accounts_switch, + )) + .child(self.background_row(cx)); + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(text(theme::CAPTION).text_color(t.muted).child( + "Changes save as you make them. Those the game can't take while it runs wait for \ + a restart, and the page says so.", + )) + .child(form) + } + + fn background_row(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + let on = self.servers.service.unwrap_or(false); + let idle = self.servers.busy.is_none() && self.servers.service.is_some(); + let toggle = switch("background", on, &t); + let toggle = if idle { + toggle.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.server_command( + if on { + "Turning off running in the background" + } else { + "Setting it to run in the background" + }, + vec![ + "service".into(), + if on { "uninstall" } else { "install" }.into(), + ], + ); + cx.notify(); + })) + } else { + disabled(toggle) + }; + self.setting_row( + "Run in the background and at login", + if on { + "On: starts when you log in to this computer, keeps running when the launcher \ + closes, and comes back by itself if the computer restarts." + .into() + } else { + "Off: the server stops when you close the launcher.".into() + }, + toggle.into_any_element(), + ) + } + + fn updates_section(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let idle = self.servers.busy.is_none(); + let check = self.servers.update.clone(); + let release = status + .release + .clone() + .or_else(|| { + check + .as_ref() + .and_then(|u| u["installed"].as_str().map(str::to_string)) + }) + .or_else(servers::runtime_release) + .unwrap_or_else(|| "?".into()); + let available = status.update_available.clone().or_else(|| { + check + .as_ref() + .filter(|u| u["available"] == true) + .and_then(|u| u["newest"].as_str().map(str::to_string)) + }); + let about = match (&available, &check, &status.update_last) { + (Some(tag), _, _) => format!( + "Update available: Horizon {tag} (this server runs {release}). Updating backs up \ + the world first, and goes back by itself if the new version doesn't start." + ), + (None, Some(_), _) => format!("Up to date: Horizon {release}."), + (None, None, Some((last, _))) => format!("Horizon {release}. {last}"), + (None, None, None) => format!("Horizon {release}."), + }; + let control = match available { + Some(tag) => { + let b = button("update-now", "Update now", Kind::Primary, &t); + if idle { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.servers.update = None; + this.server_command(&format!("Updating to {tag}"), vec!["update".into()]); + cx.notify(); + })) + } else { + disabled(b) + } + } + None => button("update-check", "Check for updates", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some(dir) = this.servers.open.clone() { + let tx = this.servers.tx.clone(); + std::thread::spawn(move || { + let result = servers::run(&dir, &["update", "--check", "--json"]) + .and_then(|out| { + serde_json::from_str(out.trim()) + .map_err(|e| Problem::plain(e.to_string())) + }); + let _ = tx.send(Event::UpdateCheck(result)); + }); + } + cx.notify(); + }), + ), + }; + let mut rows = div() + .flex() + .flex_col() + .border_t_1() + .border_color(t.rule) + .child(self.setting_row("This server's Horizon", about, control.into_any_element())); + if self.servers.setting("updates", "keep").is_some() { + rows = rows.child(self.setting_row( + "Older versions kept", + "Downloaded versions kept besides the one in use and the one an update can go back \ + to." + .into(), + self.stepper("updates.keep", 0..=5, cx), + )); + } + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(text(theme::HEADING).text_color(t.ink).child("Updates")) + .child(rows) + } + + fn backups_tab(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let idle = self.servers.busy.is_none(); + let every = self.servers.shown("backups", "every"); + let auto = !every.is_empty() && every != "0"; + let keep = self.servers.shown("backups", "keep"); + let now = { + let b = button("backup-now", "Back up now", Kind::Primary, &t); + if idle { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.server_command("Backing up", vec!["backup".into()]); + cx.notify(); + })) + } else { + disabled(b) + } + }; + let toggle = switch("auto-backup", auto, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.set_setting("backups.every", if auto { "0".into() } else { "6h".into() }); + cx.notify(); + }, + )); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, b) in self.servers.backups.clone().into_iter().enumerate() { + let (when, kind) = backup_label(&b); + let confirming = self.servers.confirm_restore.as_deref() == Some(b.name.as_str()); + let name = b.name.clone(); + let restore = button( + SharedString::from(format!("restore-{i}")), + if confirming { + "Replace the world" + } else { + "Restore" + }, + if confirming { + Kind::Primary + } else { + Kind::Ghost + }, + &t, + ); + let restore = if idle { + restore.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if this.servers.confirm_restore.as_ref() == Some(&name) { + this.servers.confirm_restore = None; + this.server_command( + "Restoring", + vec!["restore".into(), name.clone(), "--yes".into()], + ); + } else { + this.servers.confirm_restore = Some(name.clone()); + } + cx.notify(); + })) + } else { + disabled(restore) + }; + let mut right = div().flex().items_center().gap(px(8.)); + if confirming { + right = right.child( + button("restore-cancel", "Cancel", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.servers.confirm_restore = None; + cx.notify(); + }, + )), + ); + } + right = right.child(restore); + let detail = if kind.is_empty() { + bytes(b.bytes) + } else { + format!("{kind} · {}", bytes(b.bytes)) + }; + list = list.child(index_row( + i + 1, + when, + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + let mut tab = div() + .flex() + .flex_col() + .gap(px(20.)) + .child( + div().flex().items_center().gap(px(16.)).child(now).child( + text(theme::CAPTION) + .text_color(t.muted) + .child(if status.running() { + "Players stay online: the world is saved, then zipped." + } else { + "Zips the world and the server's settings into its backups folder." + }), + ), + ) + .child( + div() + .flex() + .items_center() + .gap(px(14.)) + .child(toggle) + .child( + div() + .flex() + .flex_col() + .child( + text(theme::UI) + .text_color(t.ink) + .child("Back up automatically"), + ) + .child(text(theme::CAPTION).text_color(t.muted).child(if auto { + format!( + "On: every {every} while the server runs, keeping the last \ + {keep}. Backups you make yourself are never deleted." + ) + } else { + "Off: only the backups you make.".to_string() + })), + ), + ); + if self.servers.confirm_restore.is_some() { + tab = tab.child(notice( + "Restoring replaces the world with this backup. The world as it is now isn't \ + deleted: it's moved into the backups folder. A running server stops and starts \ + again with the restored world." + .into(), + &t, + )); + } + tab = if self.servers.backups.is_empty() { + tab.child(text(theme::UI).text_color(t.muted).child("No backup yet.")) + } else { + tab.child(list) + }; + tab.child(self.updates_section(status, cx)) + } + + // ----- The Create dialog ---------------------------------------------------------------- + + pub(super) fn create_dialog(&mut self, cx: &mut Context) -> Option> { + let t = self.theme; + let c = self.servers.create.as_ref()?; + let (new_world, copy, worlds) = (c.new_world, c.copy.clone(), c.worlds.clone()); + let (mode, difficulty, max_players) = (c.mode, c.difficulty, c.max_players); + let (friends_only, check_accounts, eula, eula_missing) = + (c.friends_only, c.check_accounts, c.eula, c.eula_missing); + let creating = self.servers.creating; + let row = |label: &'static str, control: AnyElement| { + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(caps(label).text_color(t.muted)) + .child(control) + }; + let weak = cx.entity().downgrade(); + let pick = move |f: fn(&mut Create, &'static str)| { + let weak = weak.clone(); + move |value: &'static str, _: &mut Window, cx: &mut App| { + let _ = weak.update(cx, |this, cx| { + if let Some(c) = &mut this.servers.create { + f(c, value); + } + cx.notify(); + }); + } + }; + let world_kind = segments( + "create-world", + &[("new", "New world"), ("copy", "Copy one of my worlds")], + if new_world { "new" } else { "copy" }, + &t, + pick(|c, v| c.new_world = v == "new"), + ); + let world_detail = if new_world { + self.field( + Field::Seed, + "Seed (optional: leave empty for a random world)", + 400., + cx, + ) + .into_any_element() + } else if worlds.is_empty() { + text(theme::CAPTION) + .text_color(t.muted) + .child("You have no single-player world yet: play one first, or choose New world.") + .into_any_element() + } else { + let mut list = div().flex().flex_col().gap(px(2.)); + for (i, (name, path)) in worlds.into_iter().take(8).enumerate() { + let chosen = copy.as_ref() == Some(&path); + list = list.child( + div() + .id(SharedString::from(format!("create-copy-{i}"))) + .flex() + .items_center() + .gap(px(10.)) + .h(px(32.)) + .px(px(10.)) + .rounded(px(theme::RADIUS)) + .cursor_pointer() + .when(chosen, |d| d.bg(t.plate_soft)) + .hover(move |s| s.bg(t.plate_soft)) + .child( + div() + .size(px(12.)) + .rounded_full() + .border_1() + .border_color(if chosen { t.accent } else { t.muted }) + .when(chosen, |d| d.bg(t.accent)), + ) + .child(text(theme::UI).text_color(t.ink).child(name)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.copy = Some(path.clone()); + } + cx.notify(); + })), + ); + } + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(list) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .child("The server gets a copy: your single-player world stays as it is."), + ) + .into_any_element() + }; + let modes = segments("create-mode", &MODES, mode, &t, pick(|c, v| c.mode = v)); + let difficulties = segments( + "create-difficulty", + &DIFFICULTIES, + difficulty, + &t, + pick(|c, v| c.difficulty = v), + ); + let who = segments( + "create-who", + &[ + ("friends", "Friends only"), + ("anyone", "Anyone with the address"), + ], + if friends_only { "friends" } else { "anyone" }, + &t, + pick(|c, v| c.friends_only = v == "friends"), + ); + let step = |id: &'static str, label: &'static str, delta: i32, cx: &mut Context| { + button(id, label, Kind::Secondary, &t) + .w(px(36.)) + .px(px(0.)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.max_players = (c.max_players as i32 + delta).clamp(1, 100) as u32; + } + cx.notify(); + })) + }; + let players = div() + .flex() + .items_center() + .gap(px(8.)) + .child(step("create-fewer", "−", -1, cx)) + .child( + text(theme::UI) + .w(px(44.)) + .flex() + .justify_center() + .text_color(t.ink) + .child(max_players.to_string()), + ) + .child(step("create-more", "+", 1, cx)); + let checkbox = |id: &'static str, on: bool| { + div() + .id(id) + .flex_none() + .size(px(18.)) + .rounded(px(4.)) + .border_1() + .border_color(if on { t.accent } else { t.muted }) + .bg(if on { t.accent } else { t.surface }) + .flex() + .items_center() + .justify_center() + .text_color(t.on_accent) + .text_size(px(12.)) + .cursor_pointer() + .when(on, |d| d.child("✓")) + }; + let accounts = div() + .flex() + .items_start() + .gap(px(10.)) + .child( + checkbox("create-accounts", check_accounts).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.check_accounts = !c.check_accounts; + } + cx.notify(); + }, + )), + ) + .child( + div() + .flex() + .flex_col() + .child( + text(theme::UI) + .text_color(t.ink) + .child("Check Minecraft accounts"), + ) + .child(text(theme::CAPTION).text_color(t.muted).child( + "Only if every player signs in with Microsoft. Leave it off for Horizon \ + players without an account: Friends only keeps strangers out.", + )), + ); + let eula_line = div() + .flex() + .items_center() + .gap(px(10.)) + .child(checkbox("create-eula", eula).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.eula = !c.eula; + c.eula_missing = false; + } + cx.notify(); + }, + ))) + .child( + text(theme::UI) + .text_color(if eula_missing { t.danger } else { t.ink }) + .child("I agree to the Minecraft EULA"), + ) + .child( + div() + .id("create-eula-read") + .text_size(px(theme::UI.px)) + .text_color(t.accent) + .cursor_pointer() + .hover(|s| s.opacity(0.8)) + .child("Read it") + .on_click(|_, _, cx| cx.open_url(servers::EULA_URL)), + ); + let body = div() + .id("create-body") + .flex() + .flex_col() + .min_h_0() + .gap(px(20.)) + .px(px(28.)) + .pt(px(28.)) + .pb(px(20.)) + .overflow_y_scroll() + .child(caps("New server").text_color(t.muted)) + .child( + text(theme::HEADING) + .text_color(t.ink) + .child("Create a server"), + ) + .child(text(theme::CAPTION).text_color(t.muted).child( + "Everything has a default: tick the EULA and Create makes a friends-only survival \ + world. You can change all of it later.", + )) + .child(row( + "Name", + self.field(Field::Name, "My server", 400., cx) + .into_any_element(), + )) + .child(row( + "World", + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(div().flex().child(world_kind)) + .child(world_detail) + .into_any_element(), + )) + .child(row( + "Game mode", + div().flex().child(modes).into_any_element(), + )) + .child(row( + "Difficulty", + div().flex().child(difficulties).into_any_element(), + )) + .child(row("Most players at once", players.into_any_element())) + .child(row( + "Who can join", + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(div().flex().child(who)) + .when(friends_only, |d| { + d.child(self.field( + Field::Players, + "Players allowed in, separated by commas (you first)", + 480., + cx, + )) + .child(text(theme::CAPTION).text_color(t.muted).child( + "The first one becomes an operator. Add more later on the Players tab.", + )) + }) + .child(accounts) + .into_any_element(), + )) + .child(eula_line); + let mut foot = div() + .flex() + .flex_none() + .items_center() + .justify_end() + .gap(px(12.)) + .px(px(28.)) + .pt(px(8.)) + .pb(px(28.)); + if creating { + let last = self.servers.job_log.back().cloned().unwrap_or_default(); + foot = foot.child( + text(theme::CAPTION) + .flex_1() + .min_w_0() + .text_color(t.muted) + .truncate() + .child(format!("Creating… {last}")), + ); + } else if let Some(p) = &self.servers.problem { + foot = foot.child( + text(theme::CAPTION) + .flex_1() + .min_w_0() + .text_color(t.danger) + .child(p.message.clone()), + ); + if let Some(fix @ Fix::Prepare) = p.fix.clone() { + foot = foot.child( + button("create-fix", "Prepare the game files", Kind::Secondary, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.fix(fix.clone(), cx); + cx.notify(); + }), + ), + ); + } + } else if eula_missing { + foot = foot.child( + text(theme::CAPTION) + .flex_1() + .text_color(t.danger) + .child("Tick the EULA box to create the server."), + ); + } + let cancel = button("create-cancel", "Cancel", Kind::Secondary, &t); + let create = button("create-go", "Create", Kind::Primary, &t); + foot = if creating { + foot.child(disabled(cancel)).child(disabled(create)) + } else { + foot.child(cancel.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.create = None; + this.servers.problem = None; + cx.notify(); + }))) + .child(create.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.create_server(); + cx.notify(); + }))) + }; + let card = plate(&t) + .flex() + .flex_col() + .w_full() + .max_w(px(640.)) + .max_h_full() + .bg(t.page) + .border_1() + .border_color(t.rule) + .child(body) + .child(foot); + Some( + div() + .id("create-dialog") + .absolute() + .top_0() + .left_0() + .size_full() + .flex() + .flex_col() + .items_center() + .px(px(32.)) + .py(px(24.)) + .bg(t.page.opacity(0.92)) + .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) + .occlude() + .child(card), + ) + } +} + +/// The state, in a few words. +fn phase_label(status: &Status) -> String { + if let Some(busy) = &status.update_busy { + return format!("Updating: {busy}"); + } + match status.phase.as_str() { + "running" if status.crashes > 0 => "Running · restarted after a crash".into(), + "running" if status.paused => "Running · paused while nobody plays".into(), + "running" => "Running".into(), + "starting" => "Starting".into(), + "restarting" => "Restarting".into(), + "stopping" => "Stopping".into(), + _ => "Stopped".into(), + } +} + +/// A setting's name for people. +fn setting_name(key: &str) -> &str { + match key { + "server.motd" => "the message in the server list", + "server.port" => "the port", + "server.max_players" => "most players", + "server.view_distance" => "view distance", + "server.simulation_distance" => "simulation distance", + "server.online_mode" => "account checks", + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backups_read_for_people() { + let b = |name: &str| Backup { + name: name.into(), + bytes: 1, + modified: None, + }; + assert_eq!( + backup_label(&b("2026-10-19_11-28-57-manual.zip")), + ("2026-10-19 11:28:57 UTC".into(), "Made by hand".into()) + ); + assert_eq!( + backup_label(&b("2026-10-19_11-28-57-before-v2026.10.20.zip")).1, + "Before updating to v2026.10.20" + ); + assert_eq!( + backup_label(&b("2026-10-19_11-28-57-auto.zip")).1, + "Automatic" + ); + assert_eq!(backup_label(&b("odd.zip")), ("odd".into(), String::new())); + assert_eq!(bytes(5_292_542), "5.3 MB"); + assert_eq!(uptime(3725), "1 h 02 min"); + let mut long = "é".repeat(300); + clip(&mut long); + assert_eq!(long.chars().count(), 256); + } +}