Launcher: play straight into a world or server, and the Multiplayer list

Each world on Home gets Play (the game starts with --world <folder>), and
Home lists the selected instance's servers from the game's own servers.dat:
Join starts the game with --server <address>, Add server and Remove change
the file. server_list reads and writes it as vanilla's ServerList does
(uncompressed NBT, a new file then servers.dat_old) and writes every entry
back with all its fields, the hidden Direct Connection ones too.

CLI: `multiplayer [list|add|remove] [--instance]`, `play --server`;
MCP: play takes `server`; `multiplayer remove` needs confirm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 01:56:41 +01:00
parent c70e2fae74
commit 4b761abcb2
14 changed files with 744 additions and 2 deletions
+34
View File
@@ -54,6 +54,7 @@ Start the client.
- `--world`: Open or create this world (a folder under saves) at once
- `--creative`: Creative mode for a new world
- `--join`: Join a friend's world with its invite code
- `--server`: Join this server at once: an address, or a server of the list by name or position
- `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --server-thread
MCP: `play`, then the `game_*` tools.
@@ -373,6 +374,39 @@ Move a world to the system's trash.
MCP: `worlds_delete`, needs `confirm: true`.
## `horizon-launcher multiplayer list`
The servers of the game's Multiplayer screen (the default).
horizon-launcher multiplayer list
- `--instance`: The instance (default: the selected one)
MCP: `multiplayer_list`.
## `horizon-launcher multiplayer add`
Add a server to the list.
horizon-launcher multiplayer add <ADDRESS>
- `ADDRESS`: Its address, as in the game's Add Server (host or host:port)
- `--name`: Its name in the list (default: Minecraft Server)
- `--instance`
MCP: `multiplayer_add`.
## `horizon-launcher multiplayer remove`
Remove a server from the list: its position from 1, name or address.
horizon-launcher multiplayer remove <SERVER>
- `SERVER`
- `--instance`
MCP: `multiplayer_remove`, needs `confirm: true`.
## `horizon-launcher modpack list`
The imported packs and their coverage (the default).
+1
View File
@@ -2734,6 +2734,7 @@ dependencies = [
name = "horizon-launcher"
version = "0.2.0"
dependencies = [
"base64",
"chrono",
"clap",
"dirs 5.0.1",
+1
View File
@@ -42,6 +42,7 @@ horizon-world = { path = "../crates/horizon-world" }
# Deleting a world moves it to the system's trash
trash = "5"
# Backup names carry the local time, as vanilla's do
base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["clock"] }
# The session file's random name.
getrandom = "0.3"
+9
View File
@@ -86,6 +86,13 @@ The opening, then Play ([clip](docs/opening.webm)):
(`<date>_<time>_<folder>.zip`); **Copy** puts "<name> (1)" beside it; **Delete** moves it to the
system's trash after a confirmation; **Open folder**. The same from the command line:
`horizon-launcher worlds [list|backup|copy|delete] [--instance <name>]`.
**Play** on a world starts the game straight into it.
- **Multiplayer**: Home lists the selected instance's servers, the game's own Multiplayer list
(`servers.dat`, each with the picture the game last saw). **Join** starts the game straight into
one; **Add server** and **Remove** (after a confirmation) change the file the game reads,
keeping every field the launcher doesn't show and the servers joined with Direct Connection. The
same from the command line: `horizon-launcher multiplayer [list|add|remove] [--instance <name>]`
and `horizon-launcher play --server <address or name>`.
- **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer.
Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux,
@@ -188,6 +195,8 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher instance version <instance> <tag|latest> keep it on one installed version, or follow updates
horizon-launcher worlds [list] [--instance <name>] an instance's worlds
horizon-launcher worlds backup|copy|delete <world> [--instance <name>] delete moves it to the trash
horizon-launcher multiplayer [list] [--instance <name>] the servers in an instance's Multiplayer list
horizon-launcher multiplayer add <address> [--name <name>] | remove <server>
horizon-launcher modpack [list] the imported packs and their coverage
horizon-launcher modpack import <pack> a .mrpack, CurseForge zip or instance folder
horizon-launcher modpack port <pack> [--from <dir>] [--version <tag>] get the jars and carry them over
+93
View File
@@ -4,6 +4,7 @@ use clap::{Parser, Subcommand};
use horizon_launcher::account::{self, Accounts};
use horizon_launcher::backend::{self, Release};
use horizon_launcher::instances;
use horizon_launcher::server_list;
use std::io::{IsTerminal, Write};
use std::path::PathBuf;
use std::process::Command;
@@ -213,6 +214,32 @@ enum WorldsCmd {
},
}
#[derive(Subcommand)]
enum MultiplayerCmd {
/// The servers of the game's Multiplayer screen (the default)
List {
/// The instance (default: the selected one)
#[arg(long)]
instance: Option<String>,
},
/// Add a server to the list
Add {
/// Its address, as in the game's Add Server (host or host:port)
address: String,
/// Its name in the list (default: Minecraft Server)
#[arg(long)]
name: Option<String>,
#[arg(long)]
instance: Option<String>,
},
/// Remove a server from the list: its position from 1, name or address
Remove {
server: String,
#[arg(long)]
instance: Option<String>,
},
}
#[derive(Subcommand)]
enum ModsCmd {
/// What the browser installed (the default)
@@ -331,6 +358,9 @@ enum Cmd {
/// Join a friend's world with its invite code
#[arg(long)]
join: Option<String>,
/// Join this server at once: an address, or a server of the list by name or position
#[arg(long, conflicts_with_all = ["world", "join"])]
server: Option<String>,
/// An extra argument for the game, passed through as-is (repeatable), for example
/// --server-thread
#[arg(long = "arg", value_name = "ARG", allow_hyphen_values = true)]
@@ -412,6 +442,11 @@ enum Cmd {
#[command(subcommand)]
action: Option<WorldsCmd>,
},
/// The servers in an instance's Multiplayer list (servers.dat): list, add, remove
Multiplayer {
#[command(subcommand)]
action: Option<MultiplayerCmd>,
},
/// Modpacks: import a Java pack, see its coverage report, port what this computer can and
/// play it as its own profile (docs/modpacks.md)
Modpack {
@@ -681,6 +716,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
world,
creative,
join,
server,
arg,
} => {
let instance = match instance {
@@ -695,6 +731,11 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
if let Some(world) = world {
cmd.arg("--world").arg(world);
}
if let Some(server) = server {
let list = server_list::List::load(&instance.home);
let ip = server_list::find(&list, &server).map_or(server, |(_, s)| s.ip);
cmd.arg("--server").arg(ip);
}
if creative {
cmd.arg("--creative");
}
@@ -865,6 +906,10 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
action.unwrap_or(WorldsCmd::List { instance: None }),
as_json,
)?,
Cmd::Multiplayer { action } => multiplayer(
action.unwrap_or(MultiplayerCmd::List { instance: None }),
as_json,
)?,
Cmd::Instance { action } => instance(action.unwrap_or(InstanceCmd::List), as_json)?,
Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?,
Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?,
@@ -1487,6 +1532,54 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
Ok(())
}
fn multiplayer(action: MultiplayerCmd, as_json: bool) -> Result<(), String> {
let home = |instance: Option<String>| -> Result<PathBuf, String> {
Ok(match instance {
Some(name) => instances::find(&name)?.home,
None => instances::selected().home,
})
};
match action {
MultiplayerCmd::List { instance } => {
let home = home(instance)?;
let servers = server_list::List::load(&home).servers();
if as_json {
json(
servers
.iter()
.map(|s| serde_json::json!({ "name": s.name, "address": s.ip, "icon": s.icon.is_some() }))
.collect(),
);
} else if servers.is_empty() {
println!("No servers in {}", home.join("servers.dat").display());
}
for (i, s) in servers.iter().enumerate().filter(|_| !as_json) {
println!("{}. {} ({})", i + 1, s.name, s.ip);
}
}
MultiplayerCmd::Add {
address,
name,
instance,
} => {
let home = home(instance)?;
let mut list = server_list::List::load(&home);
list.add(name.as_deref().unwrap_or(""), &address)?;
list.save(&home)?;
println!("Added {}.", address.trim());
}
MultiplayerCmd::Remove { server, instance } => {
let home = home(instance)?;
let mut list = server_list::List::load(&home);
let (i, _) = server_list::find(&list, &server)?;
let gone = list.remove(i)?;
list.save(&home)?;
println!("Removed {} ({}).", gone.name, gone.ip);
}
}
Ok(())
}
fn worlds(action: WorldsCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::worlds::{self, World};
let home = |instance: Option<String>| -> Result<PathBuf, String> {
+1
View File
@@ -27,6 +27,7 @@ pub const DESTRUCTIVE: &[&str] = &[
"account sign-out",
"data delete",
"worlds delete",
"multiplayer remove",
];
/// Commands that send something or reach other people: only when the player asks.
+1
View File
@@ -12,6 +12,7 @@ pub mod modpacks;
pub mod mojang;
pub mod process;
pub mod proxy;
pub mod server_list;
pub mod servers;
pub mod signed;
pub mod sources;
+23
View File
@@ -19,6 +19,7 @@ mod mcp;
mod modpacks_page;
mod mods_page;
mod mods_project;
mod multiplayer_page;
mod partner;
mod perf;
mod scrollbar;
@@ -186,6 +187,8 @@ struct Launcher {
friend_focused: bool,
friend_focus: FocusHandle,
joining: Option<String>,
/// Where the next start goes at once: `--world <folder>` or `--server <address>`.
quick_play: Option<(&'static str, String)>,
/// Settings' Game arguments field: the line, whether it has focus, and its focus handle.
args_input: String,
args_focused: bool,
@@ -229,6 +232,7 @@ struct Launcher {
instances: instances_page::Instances,
/// Home's Worlds section, of the selected instance (`worlds_page.rs`).
worlds: worlds_page::Worlds,
multiplayer: multiplayer_page::Multiplayer,
/// The name the game made up for an offline player (`horizon-player.txt`), for the top bar.
offline_name: Option<String>,
/// The player's servers, for the sidebar until the Servers page has read them.
@@ -364,6 +368,7 @@ impl Launcher {
friend_focused: false,
friend_focus: cx.focus_handle(),
joining: None,
quick_play: None,
collection: collection::Collection::load(),
agents: agents_page::AgentsUi::default(),
playing: None,
@@ -387,6 +392,7 @@ impl Launcher {
mods: mods_page::Mods::new(cx),
instances: instances_page::Instances::default(),
worlds: worlds_page::Worlds::default(),
multiplayer: multiplayer_page::Multiplayer::default(),
offline_name: offline_name(),
side_servers: horizon_launcher::servers::list(),
art: art::Art::default(),
@@ -561,6 +567,9 @@ impl Launcher {
self.client_error = Some(e);
}
}
if let Some((flag, value)) = self.quick_play.take() {
cmd.arg(flag).arg(value);
}
backend::append_game_args(&mut cmd);
self.client_home = cmd.get_current_dir().map(|d| d.to_path_buf());
match backend::spawn(Job::Client, cmd, self.tx.clone()) {
@@ -683,6 +692,7 @@ impl Launcher {
self.client = None;
// The game saved: last played, sizes and pictures changed.
self.worlds.stale();
self.multiplayer.stale();
// The run's own game folder: an instance's or a pack's keeps its reports.
let home = self.client_home.clone().unwrap_or_else(backend::game_home);
let report = self
@@ -2166,6 +2176,9 @@ impl Launcher {
if let Some(worlds) = self.worlds_section(cx) {
page = page.child(worlds);
}
if let Some(servers) = self.multiplayer_section(cx) {
page = page.child(servers);
}
if let Some(e) = self.client_error.clone() {
page = page.child(notice(e, &t));
}
@@ -3063,6 +3076,16 @@ impl Launcher {
)
}
/// Plays the selected instance straight into a world (`--world`) or a server (`--server`):
/// flags every Horizon release takes.
pub(crate) fn quick_play(&mut self, flag: &'static str, value: String) {
self.quick_play = Some((flag, value));
self.play();
if self.starting_client.is_none() {
self.quick_play = None;
}
}
fn join_friend(&mut self) {
if horizon_friends::invite::parse(&self.friend_code).is_none() {
return;
+7
View File
@@ -34,6 +34,7 @@ fn session_tools() -> Value {
"world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." },
"creative": { "type": "boolean", "description": "Creative mode for a new world." },
"join": { "type": "string", "description": "Join a friend's world with its invite code. Only when the player asks." },
"server": { "type": "string", "description": "Join this server at once: an address, or a server of the instance's list (multiplayer_list) by name or position. Only when the player asks." },
"offscreen": { "type": "boolean", "description": "Render without showing a window (game_screenshot still works)." },
"arg": { "type": "array", "items": { "type": "string" }, "description": "Extra game arguments, passed through as-is (for example \"--server-thread\")." } } } },
{ "name": "server", "description": "Start a Horizon dedicated server. It runs until server_stop or the end of this MCP session. Requires agreeing to the Minecraft EULA. CLI: horizon-launcher server",
@@ -87,6 +88,12 @@ impl Session {
if let Some(code) = arg_str(args, "join") {
backend::join_friend(&mut cmd, code)?;
}
if let Some(server) = arg_str(args, "server") {
let list = horizon_launcher::server_list::List::load(&instance.home);
let ip = horizon_launcher::server_list::find(&list, server)
.map_or_else(|_| server.to_string(), |(_, s)| s.ip);
cmd.arg("--server").arg(ip);
}
if let Some(extra) = args.get("arg").and_then(Value::as_array) {
cmd.args(extra.iter().filter_map(Value::as_str));
}
+251
View File
@@ -0,0 +1,251 @@
//! The selected instance's server list on Home (`horizon_launcher::server_list`, the game's own
//! `servers.dat`): each server with the picture the game last saw, Join (the game starts straight
//! into it), Remove after a confirmation, and a line to add one.
use super::*;
use gpui::{Image, ImageFormat};
use horizon_launcher::server_list::{self, Server};
use servers_page::Field;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Default)]
pub(super) struct Multiplayer {
/// The game folder the list is of, and the list as last read with each picture decoded.
home: Option<PathBuf>,
list: Vec<(Server, Option<Arc<Image>>)>,
fresh: bool,
adding: bool,
confirm_remove: Option<usize>,
error: Option<String>,
}
impl Multiplayer {
/// Read again on the next frame: the game may have changed its list.
pub(super) fn stale(&mut self) {
self.fresh = false;
}
}
impl Launcher {
fn load_servers(&mut self, home: PathBuf) {
if self.multiplayer.home.as_ref() != Some(&home) {
self.multiplayer = Multiplayer {
home: Some(home.clone()),
..Multiplayer::default()
};
}
if self.multiplayer.fresh {
return;
}
// A few servers and their 64×64 pictures: small enough to read while drawing.
self.multiplayer.list = server_list::List::load(&home)
.servers()
.into_iter()
.map(|s| {
let icon = s
.icon
.clone()
.map(|png| Arc::new(Image::from_bytes(ImageFormat::Png, png)));
(s, icon)
})
.collect();
self.multiplayer.fresh = true;
}
fn edit_servers(&mut self, edit: impl FnOnce(&mut server_list::List) -> Result<(), String>) {
let Some(home) = self.multiplayer.home.clone() else {
return;
};
let mut list = server_list::List::load(&home);
self.multiplayer.error = edit(&mut list).and_then(|()| list.save(&home)).err();
self.multiplayer.confirm_remove = None;
self.multiplayer.stale();
}
/// Enter in the address field, or Add.
pub(super) fn add_server(&mut self) {
let name = self.servers.value(Field::ServerName).to_string();
let address = self.servers.value(Field::ServerAddress).to_string();
self.edit_servers(|list| list.add(&name, &address));
if self.multiplayer.error.is_none() {
self.servers.text(Field::ServerName).clear();
self.servers.text(Field::ServerAddress).clear();
self.multiplayer.adding = false;
}
}
/// Home's Multiplayer section, for the selected instance.
pub(super) fn multiplayer_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let home = self.selected_instance()?.home.clone();
self.load_servers(home);
let header = div()
.flex()
.items_center()
.justify_between()
.mb(px(4.))
.child(section_title("Multiplayer", "server", &t))
.child(
button("server-add", "Add server", Kind::Ghost, &t).on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.multiplayer.adding = !this.multiplayer.adding;
this.multiplayer.error = None;
if this.multiplayer.adding {
this.servers.focus_soon = Some(Field::ServerAddress);
}
cx.notify();
},
)),
);
let mut section = div().flex().flex_col().gap(px(8.)).child(header);
if let Some(e) = self.multiplayer.error.clone() {
section = section.child(notice(e, &t));
}
if self.multiplayer.adding {
section = section.child(
plate(&t)
.flex()
.items_center()
.gap(px(8.))
.px(px(14.))
.py(px(10.))
.child(self.field(Field::ServerName, "Minecraft Server", 220., cx))
.child(self.field(Field::ServerAddress, "play.example.com", 300., cx))
.child(button("server-save", "Add", Kind::Secondary, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.add_server();
cx.notify();
}),
)),
);
}
let list = self.multiplayer.list.clone();
if list.is_empty() && !self.multiplayer.adding {
section = section.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("No servers yet: add one here or in the game's Multiplayer screen."),
);
}
for (i, (server, icon)) in list.into_iter().enumerate() {
section = section.child(self.server_row(i, server, icon, cx));
}
Some(section)
}
fn server_row(
&mut self,
i: usize,
server: Server,
icon: Option<Arc<Image>>,
cx: &mut Context<Self>,
) -> Div {
let t = self.theme;
let picture = div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(48.))
.border_2()
.border_color(t.outline)
.bg(t.well);
let picture = match icon {
Some(image) => picture.child(gpui::img(image).size(px(44.))),
None => picture.child(blocks::icon("server", 22., t.muted)),
};
let mut actions = div().flex().items_center().gap(px(6.));
if self.multiplayer.confirm_remove == Some(i) {
actions = actions
.child(
text(theme::CAPTION)
.text_color(t.danger)
.child("Remove it from the list?"),
)
.child(
button(
SharedString::from(format!("server-keep-{i}")),
"Keep",
Kind::Ghost,
&t,
)
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.multiplayer.confirm_remove = None;
cx.notify();
})),
)
.child(
button(
SharedString::from(format!("server-remove-{i}")),
"Remove",
Kind::Secondary,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.edit_servers(|list| list.remove(i).map(|_| ()));
cx.notify();
},
)),
);
} else {
let ip = server.ip.clone();
let busy = self.client.is_some() || self.starting_client.is_some();
let join = button(
SharedString::from(format!("server-join-{i}")),
"Join",
Kind::Secondary,
&t,
);
let join = if busy { disabled(join) } else { join };
actions = actions
.child(
join.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.quick_play("--server", ip.clone());
cx.notify();
})),
)
.child(
button(
SharedString::from(format!("server-delete-{i}")),
"Remove",
Kind::Ghost,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.multiplayer.confirm_remove = Some(i);
cx.notify();
},
)),
);
}
plate(&t)
.flex()
.items_center()
.gap(px(14.))
.px(px(14.))
.py(px(10.))
.child(picture)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.child(
blocks::pixel(15., FontWeight::MEDIUM)
.text_color(t.ink)
.truncate()
.child(server.name.clone()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(server.ip.clone()),
),
)
.child(actions)
}
}
+159
View File
@@ -0,0 +1,159 @@
//! The player's server list, `servers.dat` in an instance's game folder: the game's Multiplayer
//! screen reads and writes the same file. Its format is vanilla's (`ServerList.load`/`save`,
//! `ServerData.read`/`write`): uncompressed NBT, `servers` a list of compounds with `name`, `ip`,
//! an optional `icon` (a PNG in base64), `acceptTextures`, `acceptedCodeOfConduct` and `hidden`.
//! The launcher only adds and removes entries: every other field of every entry is written back
//! as it was read.
use base64::Engine;
use horizon_world::nbt::{self, Compound, JavaString, Limits, NamedTag, Tag};
use std::fs;
use std::path::Path;
const FILE: &str = "servers.dat";
#[derive(Clone, Debug, PartialEq)]
pub struct Server {
pub name: String,
pub ip: String,
/// The server's picture, as the game last saw it (PNG).
pub icon: Option<Vec<u8>>,
}
/// The entries as they are in the file, the hidden ones (servers joined with Direct
/// Connection) too.
pub struct List {
entries: Vec<Compound>,
}
fn key(k: &str) -> JavaString {
JavaString::from(k)
}
fn text(entry: &Compound, k: &str) -> String {
match entry.get(&key(k)) {
Some(Tag::String(s)) => s.to_string_lossy(),
_ => String::new(),
}
}
fn hidden(entry: &Compound) -> bool {
matches!(entry.get(&key("hidden")), Some(Tag::Byte(b)) if *b != 0)
}
impl List {
/// The list in `home`; empty when there is none or it can't be read, as the game does.
pub fn load(home: &Path) -> List {
let entries = fs::read(home.join(FILE))
.ok()
.and_then(|bytes| nbt::read_named(&bytes, Limits::default()).ok())
.and_then(|(root, _)| match root.tag.get("servers") {
Some(Tag::List(list)) => Some(
list.iter()
.filter_map(|t| match t {
Tag::Compound(c) => Some(c.clone()),
_ => None,
})
.collect(),
),
_ => None,
})
.unwrap_or_default();
List { entries }
}
/// The servers the Multiplayer screen shows, in its order.
pub fn servers(&self) -> Vec<Server> {
self.entries
.iter()
.filter(|e| !hidden(e))
.map(|e| Server {
name: text(e, "name"),
ip: text(e, "ip"),
icon: Some(text(e, "icon"))
.filter(|s| !s.is_empty())
.and_then(|s| base64::engine::general_purpose::STANDARD.decode(s).ok()),
})
.collect()
}
/// Adds a server at the end of the shown ones, as the game's Add Server does.
pub fn add(&mut self, name: &str, ip: &str) -> Result<(), String> {
let (name, ip) = (name.trim(), ip.trim());
if ip.is_empty() {
return Err("A server needs an address.".into());
}
let name = if name.is_empty() {
"Minecraft Server"
} else {
name
};
let at = self
.entries
.iter()
.rposition(|e| !hidden(e))
.map_or(0, |i| i + 1);
let entry: Compound = [
(key("name"), Tag::String(name.into())),
(key("ip"), Tag::String(ip.into())),
(key("hidden"), Tag::Byte(0)),
]
.into_iter()
.collect();
self.entries.insert(at, entry);
Ok(())
}
/// Removes the `index`th shown server.
pub fn remove(&mut self, index: usize) -> Result<Server, String> {
let server = self
.servers()
.into_iter()
.nth(index)
.ok_or_else(|| format!("There is no server {}.", index + 1))?;
let at = (0..self.entries.len())
.filter(|&i| !hidden(&self.entries[i]))
.nth(index)
.unwrap();
self.entries.remove(at);
Ok(server)
}
/// Writes the list as the game does: a new file first, the old one kept as `servers.dat_old`.
pub fn save(&self, home: &Path) -> Result<(), String> {
let root = NamedTag {
name: "".into(),
tag: Tag::compound([(
"servers",
Tag::List(self.entries.iter().cloned().map(Tag::Compound).collect()),
)]),
};
let bytes = nbt::write_named(&root, Limits::default()).map_err(|e| e.to_string())?;
let (new, current) = (home.join("servers.dat_new"), home.join(FILE));
let written = fs::create_dir_all(home)
.and_then(|()| fs::write(&new, bytes))
.and_then(|()| match current.exists() {
true => fs::copy(&current, home.join("servers.dat_old")).map(|_| ()),
false => Ok(()),
})
.and_then(|()| fs::rename(&new, &current));
written.map_err(|e| format!("Could not save the server list: {e}"))
}
}
/// The shown server a command names: its position from 1, its name (any case) or its address.
pub fn find(list: &List, query: &str) -> Result<(usize, Server), String> {
let servers = list.servers();
let q = query.trim();
q.parse::<usize>()
.ok()
.filter(|n| (1..=servers.len()).contains(n))
.map(|n| n - 1)
.or_else(|| servers.iter().position(|s| s.name.eq_ignore_ascii_case(q)))
.or_else(|| servers.iter().position(|s| s.ip.eq_ignore_ascii_case(q)))
.map(|i| (i, servers[i].clone()))
.ok_or_else(|| format!("No server {q} in the list"))
}
#[cfg(test)]
#[path = "server_list/tests.rs"]
mod tests;
+143
View File
@@ -0,0 +1,143 @@
use super::*;
use std::path::PathBuf;
fn scratch(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"horizon-launcher-servers-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
root
}
fn s(v: &str) -> Tag {
Tag::String(v.into())
}
/// A servers.dat as the game writes it: one shown server with a picture and the fields the
/// launcher doesn't use, then one joined through Direct Connection.
fn vanilla_file(home: &Path) -> Vec<u8> {
let png = [0x89, b'P', b'N', b'G', 1, 2, 3];
let icon = base64::engine::general_purpose::STANDARD.encode(png);
let root = NamedTag {
name: "".into(),
tag: Tag::compound([(
"servers",
Tag::List(vec![
Tag::compound([
("name", s("Friends")),
("ip", s("friends.example:25570")),
("icon", s(&icon)),
("acceptTextures", Tag::Byte(1)),
("acceptedCodeOfConduct", Tag::Int(-12345)),
("hidden", Tag::Byte(0)),
]),
Tag::compound([
("name", s("Minecraft Server")),
("ip", s("direct.example")),
("hidden", Tag::Byte(1)),
]),
]),
)]),
};
let bytes = nbt::write_named(&root, Limits::default()).unwrap();
fs::write(home.join(FILE), &bytes).unwrap();
bytes
}
fn entries(home: &Path) -> Vec<Tag> {
let bytes = fs::read(home.join(FILE)).unwrap();
match nbt::read_named(&bytes, Limits::default())
.unwrap()
.0
.tag
.get("servers")
{
Some(Tag::List(list)) => list.clone(),
other => panic!("no servers list: {other:?}"),
}
}
#[test]
fn reads_the_shown_servers_with_their_pictures() {
let home = scratch("reads");
vanilla_file(home.as_path());
let list = List::load(home.as_path());
assert_eq!(
list.servers(),
vec![Server {
name: "Friends".into(),
ip: "friends.example:25570".into(),
icon: Some(vec![0x89, b'P', b'N', b'G', 1, 2, 3]),
}]
);
// No file, or one that isn't NBT: an empty list, as in the game.
assert!(List::load(&home.as_path().join("none"))
.servers()
.is_empty());
fs::write(home.as_path().join(FILE), b"not nbt").unwrap();
assert!(List::load(home.as_path()).servers().is_empty());
}
#[test]
fn adding_and_removing_keeps_every_other_field_and_the_hidden_servers() {
let home = scratch("keeps");
let original = vanilla_file(home.as_path());
let before = entries(home.as_path());
let mut list = List::load(home.as_path());
list.add(" Hub ", " hub.example ").unwrap();
assert!(list.add("x", " ").is_err());
list.save(home.as_path()).unwrap();
// The game's own backup of what was there.
assert_eq!(
fs::read(home.as_path().join("servers.dat_old")).unwrap(),
original
);
assert!(!home.as_path().join("servers.dat_new").exists());
let after = entries(home.as_path());
assert_eq!(after.len(), 3);
assert_eq!(
after[0], before[0],
"the first server is written back untouched"
);
assert_eq!(
after[1],
Tag::compound([
("name", s("Hub")),
("ip", s("hub.example")),
("hidden", Tag::Byte(0)),
]),
"a new server goes after the shown ones, before the hidden ones"
);
assert_eq!(after[2], before[1], "the hidden server stays");
let mut list = List::load(home.as_path());
let (i, found) = find(&list, "friends").unwrap();
assert_eq!((i, found.ip.as_str()), (0, "friends.example:25570"));
assert_eq!(find(&list, "2").unwrap().1.name, "Hub");
assert_eq!(find(&list, "HUB.example").unwrap().0, 1);
assert!(find(&list, "3").is_err(), "the hidden one can't be named");
assert_eq!(list.remove(0).unwrap().name, "Friends");
assert!(list.remove(5).is_err());
list.save(home.as_path()).unwrap();
assert_eq!(
entries(home.as_path()),
vec![after[1].clone(), before[1].clone()]
);
}
#[test]
fn a_server_without_a_name_gets_the_games_default() {
let home = scratch("default");
let mut list = List::load(home.as_path());
list.add("", "play.example").unwrap();
list.save(home.as_path()).unwrap();
assert!(!home.as_path().join("servers.dat_old").exists());
assert_eq!(
List::load(home.as_path()).servers()[0].name,
"Minecraft Server"
);
}
+7 -1
View File
@@ -35,10 +35,13 @@ pub(super) enum Field {
/// The instance dialog's (`instances_page.rs`).
InstanceName,
InstanceGroup,
/// Home's Multiplayer section's (`multiplayer_page.rs`).
ServerName,
ServerAddress,
}
impl Field {
const ALL: [Field; 11] = [
const ALL: [Field; 13] = [
Field::Name,
Field::Seed,
Field::Players,
@@ -50,6 +53,8 @@ impl Field {
Field::Email,
Field::InstanceName,
Field::InstanceGroup,
Field::ServerName,
Field::ServerAddress,
];
}
@@ -1027,6 +1032,7 @@ impl Launcher {
Field::Token => self.save_token(),
Field::Email => self.invite_friend(),
Field::InstanceName | Field::InstanceGroup => {}
Field::ServerName | Field::ServerAddress => self.add_server(),
}
}
+14 -1
View File
@@ -235,8 +235,21 @@ impl Launcher {
actions = actions.child(text(theme::CAPTION).text_color(t.muted).child("Working…"));
} else {
let (backup, copy, folder) = (w.clone(), w.clone(), w.path.clone());
let delete = w.folder.clone();
let (delete, play) = (w.folder.clone(), w.folder.clone());
let running = self.client.is_some() || self.starting_client.is_some();
let play_button = act("world-play", "Play", Kind::Secondary);
let play_button = if running {
disabled(play_button)
} else {
play_button
};
actions = actions
.child(
play_button.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.quick_play("--world", play.clone());
cx.notify();
})),
)
.child(
act("world-backup", "Back up", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {