Launcher: worlds of an instance, with backup, copy and delete

Home lists the selected instance's worlds from their level.dat (name, mode,
version, last played) with their size and picture. Back up zips one into
backups/ as vanilla's Make Backup does; Copy makes "<name> (1)" with that
name in its level.dat; Delete moves it to the system's trash after a
confirmation (the file manager call on macOS, no Finder permission);
Open folder. `horizon-launcher worlds list|backup|copy|delete`, and their
MCP tools (delete needs confirm). level.dat is read with horizon-world's NBT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 01:37:31 +01:00
parent 90f2755245
commit c70e2fae74
11 changed files with 1111 additions and 6 deletions
+43
View File
@@ -330,6 +330,49 @@ Keep an instance on one installed Horizon version, or "latest" to follow updates
MCP: `instance_version`.
## `horizon-launcher worlds list`
The worlds: name, mode, version, last played and size (the default).
horizon-launcher worlds list
- `--instance`: The instance (default: the selected one)
MCP: `worlds_list`.
## `horizon-launcher worlds backup`
Zip a world into the instance's backups/ folder, as the game's Make Backup does.
horizon-launcher worlds backup <WORLD>
- `WORLD`: Its folder or name
- `--instance`
MCP: `worlds_backup`.
## `horizon-launcher worlds copy`
Copy a world beside it, as "<name> (1)".
horizon-launcher worlds copy <WORLD>
- `WORLD`
- `--instance`
MCP: `worlds_copy`.
## `horizon-launcher worlds delete`
Move a world to the system's trash.
horizon-launcher worlds delete <WORLD>
- `WORLD`
- `--instance`
MCP: `worlds_delete`, needs `confirm: true`.
## `horizon-launcher modpack list`
The imported packs and their coverage (the default).
+219 -6
View File
@@ -70,6 +70,15 @@ dependencies = [
"equator",
]
[[package]]
name = "android_system_properties"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
dependencies = [
"libc",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -919,6 +928,17 @@ dependencies = [
"zeroize",
]
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"iana-time-zone",
"num-traits",
"windows-link 0.2.1",
]
[[package]]
name = "cipher"
version = "0.4.4"
@@ -981,6 +1001,15 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "cobs"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "cocoa"
version = "0.25.0"
@@ -1635,6 +1664,18 @@ dependencies = [
"winreg",
]
[[package]]
name = "embedded-io"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
[[package]]
name = "embedded-io"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]]
name = "encoding_rs"
version = "0.8.42"
@@ -2354,7 +2395,7 @@ dependencies = [
"wayland-protocols-plasma",
"windows 0.61.3",
"windows-core 0.61.2",
"windows-numerics",
"windows-numerics 0.2.0",
"windows-registry 0.5.3",
"x11-clipboard",
"x11rb",
@@ -2693,6 +2734,7 @@ dependencies = [
name = "horizon-launcher"
version = "0.2.0"
dependencies = [
"chrono",
"clap",
"dirs 5.0.1",
"flate2",
@@ -2708,6 +2750,7 @@ dependencies = [
"horizon-release-sign",
"horizon-telemetry",
"horizon-theme",
"horizon-world",
"image",
"keyring",
"objc2-app-kit",
@@ -2720,6 +2763,7 @@ dependencies = [
"sha1",
"sha2 0.10.9",
"tar",
"trash",
"ureq",
"winresource",
"zip",
@@ -2801,6 +2845,21 @@ dependencies = [
name = "horizon-theme"
version = "0.1.0"
[[package]]
name = "horizon-world"
version = "0.1.0"
dependencies = [
"flate2",
"horizon-core",
"libm",
"lz4_flex",
"postcard",
"serde",
"serde_json",
"sha2 0.10.9",
"xxhash-rust",
]
[[package]]
name = "http"
version = "1.5.0"
@@ -2907,6 +2966,30 @@ dependencies = [
"tracing",
]
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.61.2",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.3.0"
@@ -3425,6 +3508,12 @@ dependencies = [
"num-traits",
]
[[package]]
name = "lz4_flex"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226"
[[package]]
name = "mac"
version = "0.1.1"
@@ -4263,6 +4352,18 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "postcard"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
dependencies = [
"cobs",
"embedded-io 0.4.0",
"embedded-io 0.6.1",
"serde",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -6187,6 +6288,24 @@ dependencies = [
"once_cell",
]
[[package]]
name = "trash"
version = "5.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317"
dependencies = [
"chrono",
"libc",
"log",
"objc2",
"objc2-foundation",
"once_cell",
"percent-encoding",
"scopeguard",
"urlencoding",
"windows 0.62.2",
]
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -6367,6 +6486,12 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "usvg"
version = "0.45.1"
@@ -6820,11 +6945,23 @@ version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-collections 0.2.0",
"windows-core 0.61.2",
"windows-future",
"windows-future 0.2.1",
"windows-link 0.1.3",
"windows-numerics",
"windows-numerics 0.2.0",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
@@ -6837,7 +6974,7 @@ dependencies = [
"rayon",
"thiserror 2.0.21",
"windows 0.61.3",
"windows-future",
"windows-future 0.2.1",
]
[[package]]
@@ -6849,6 +6986,15 @@ dependencies = [
"windows-core 0.61.2",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.57.0"
@@ -6874,6 +7020,19 @@ dependencies = [
"windows-strings 0.4.2",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-future"
version = "0.2.1"
@@ -6882,7 +7041,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
"windows-threading",
"windows-threading 0.1.0",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
@@ -6951,6 +7121,16 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-registry"
version = "0.4.0"
@@ -6991,6 +7171,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.3.1"
@@ -7009,6 +7198,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
@@ -7111,6 +7309,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
@@ -7423,6 +7630,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xxhash-rust"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
[[package]]
name = "y4m"
version = "0.8.0"
+6
View File
@@ -37,6 +37,12 @@ horizon-mods = { path = "../crates/horizon-mods", features = ["index"] }
horizon-release-sign = { path = "../crates/horizon-release-sign" }
# Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md).
horizon-telemetry = { path = "../crates/horizon-telemetry" }
# level.dat and servers.dat (the worlds and server lists of instances)
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
chrono = { version = "0.4", default-features = false, features = ["clock"] }
# 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
+7
View File
@@ -81,6 +81,11 @@ The opening, then Play ([clip](docs/opening.webm)):
Open folder. Each instance plays the launcher's version, which follows updates, unless the Play
page's version picker keeps it on another installed one (to keep an old world on the version
it was made with); picking the version marked "follows updates" lets it follow again.
- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played,
size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does
(`<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>]`.
- **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,
@@ -181,6 +186,8 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher instance rename|icon|group <instance> <value> icon: a block or item name, #rrggbb or none
horizon-launcher instance select <instance> make Play start it
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 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
+100
View File
@@ -184,6 +184,35 @@ enum InstanceCmd {
Version { instance: String, version: String },
}
#[derive(Subcommand)]
enum WorldsCmd {
/// The worlds: name, mode, version, last played and size (the default)
List {
/// The instance (default: the selected one)
#[arg(long)]
instance: Option<String>,
},
/// Zip a world into the instance's backups/ folder, as the game's Make Backup does
Backup {
/// Its folder or name
world: String,
#[arg(long)]
instance: Option<String>,
},
/// Copy a world beside it, as "<name> (1)"
Copy {
world: String,
#[arg(long)]
instance: Option<String>,
},
/// Move a world to the system's trash
Delete {
world: String,
#[arg(long)]
instance: Option<String>,
},
}
#[derive(Subcommand)]
enum ModsCmd {
/// What the browser installed (the default)
@@ -378,6 +407,11 @@ enum Cmd {
#[command(subcommand)]
action: Option<InstanceCmd>,
},
/// An instance's single-player worlds: list them, back one up, copy or delete it
Worlds {
#[command(subcommand)]
action: Option<WorldsCmd>,
},
/// 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 {
@@ -827,6 +861,10 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
println!("Horizon is in the applications menu.");
}
}
Cmd::Worlds { action } => worlds(
action.unwrap_or(WorldsCmd::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)?,
@@ -1449,6 +1487,68 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
Ok(())
}
fn worlds(action: WorldsCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::worlds::{self, World};
let home = |instance: Option<String>| -> Result<PathBuf, String> {
Ok(match instance {
Some(name) => instances::find(&name)?.home,
None => instances::selected().home,
})
};
let value = |w: &World| {
let millis = w
.last_played
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64);
serde_json::json!({
"folder": w.folder, "name": w.name, "mode": w.mode, "version": w.version,
"last_played_ms": millis, "size": w.size, "path": w.path, "icon": w.icon,
})
};
match action {
WorldsCmd::List { instance } => {
let home = home(instance)?;
let all = worlds::list(&home);
if as_json {
json(all.iter().map(value).collect());
} else if all.is_empty() {
println!("No worlds in {}", home.join("saves").display());
}
for w in all.iter().filter(|_| !as_json) {
let version = w.version.as_deref().unwrap_or("unknown version");
let mb = w.size as f64 / 1_000_000.0;
println!(
"{} ({})\n {}, {version}, {mb:.1} MB",
w.name, w.folder, w.mode
);
}
}
WorldsCmd::Backup { world, instance } => {
let home = home(instance)?;
let zip = worlds::backup(&home, &worlds::find(&home, &world)?)?;
match as_json {
true => json(serde_json::json!({ "backup": zip })),
false => println!("{}", zip.display()),
}
}
WorldsCmd::Copy { world, instance } => {
let home = home(instance)?;
let copy = worlds::copy(&worlds::find(&home, &world)?)?;
match as_json {
true => json(value(&copy)),
false => println!("Copied to {} ({})", copy.name, copy.folder),
}
}
WorldsCmd::Delete { world, instance } => {
let home = home(instance)?;
let w = worlds::find(&home, &world)?;
worlds::delete(&w)?;
println!("{} is in the trash.", w.name);
}
}
Ok(())
}
fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::browser::horizon;
use horizon_launcher::modpacks::{self, Imported};
+1
View File
@@ -26,6 +26,7 @@ pub const DESTRUCTIVE: &[&str] = &[
"servers forget",
"account sign-out",
"data delete",
"worlds delete",
];
/// Commands that send something or reach other people: only when the player asks.
+1
View File
@@ -17,3 +17,4 @@ pub mod signed;
pub mod sources;
pub mod tailscale;
pub mod telemetry;
pub mod worlds;
+9
View File
@@ -25,6 +25,7 @@ mod scrollbar;
mod servers_page;
mod theme;
mod titlebar;
mod worlds_page;
use gpui::{
actions, div, ease_out_quint, prelude::*, px, relative, size, Animation, AnimationExt,
@@ -226,6 +227,8 @@ struct Launcher {
mods: mods_page::Mods,
/// The instances, for the sidebar and Play, and their dialog (`instances_page.rs`).
instances: instances_page::Instances,
/// Home's Worlds section, of the selected instance (`worlds_page.rs`).
worlds: worlds_page::Worlds,
/// 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.
@@ -383,6 +386,7 @@ impl Launcher {
starting_pack: None,
mods: mods_page::Mods::new(cx),
instances: instances_page::Instances::default(),
worlds: worlds_page::Worlds::default(),
offline_name: offline_name(),
side_servers: horizon_launcher::servers::list(),
art: art::Art::default(),
@@ -677,6 +681,8 @@ impl Launcher {
}
Job::Client => {
self.client = None;
// The game saved: last played, sizes and pictures changed.
self.worlds.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
@@ -2157,6 +2163,9 @@ impl Launcher {
page = page.child(notice(e, &t));
}
page = page.child(rows);
if let Some(worlds) = self.worlds_section(cx) {
page = page.child(worlds);
}
if let Some(e) = self.client_error.clone() {
page = page.child(notice(e, &t));
}
+270
View File
@@ -0,0 +1,270 @@
//! An instance's single-player worlds (`saves/` in its game folder): what each is, and backing
//! up, copying and deleting them. Backups are made as vanilla's Make Backup makes them
//! (`LevelStorageAccess.makeWorldBackup`): `backups/<yyyy-MM-dd_HH-mm-ss>_<folder>.zip` in the
//! game folder, every file under `<folder>/` but the world's `session.lock`.
use horizon_world::nbt::{self, Limits, Tag};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// The lock a running game holds on a world; vanilla's backups leave it out.
const LOCK: &str = "session.lock";
#[derive(Clone, Debug, PartialEq)]
pub struct World {
/// Its folder's name under `saves/`, the id commands take.
pub folder: String,
pub path: PathBuf,
/// `LevelName`, else the folder's name.
pub name: String,
/// Survival, Creative, Adventure, Spectator or Hardcore.
pub mode: &'static str,
/// `LastPlayed`, else when level.dat changed.
pub last_played: SystemTime,
/// The version that last saved it (`Version.Name`).
pub version: Option<String>,
/// Bytes on disk, every file in its folder.
pub size: u64,
/// `icon.png`, the picture the game took of it.
pub icon: Option<PathBuf>,
}
/// The worlds in a game folder's `saves/`, the last played first.
pub fn list(home: &Path) -> Vec<World> {
let mut worlds: Vec<World> = fs::read_dir(home.join("saves"))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| read(&e.path()))
.collect();
worlds.sort_by_key(|w| std::cmp::Reverse(w.last_played));
worlds
}
/// level.dat: gzip, as vanilla writes it, or plain.
fn level_dat(path: &Path) -> Option<Tag> {
let bytes = fs::read(path).ok()?;
let mut raw = Vec::new();
let raw = match flate2::read::GzDecoder::new(&bytes[..])
.take(64 << 20)
.read_to_end(&mut raw)
{
Ok(_) => raw,
Err(_) => bytes,
};
Some(nbt::read_named(&raw, Limits::default()).ok()?.0.tag)
}
fn read(path: &Path) -> Option<World> {
let dat = path.join("level.dat");
let changed = fs::metadata(&dat).and_then(|m| m.modified()).ok()?;
let folder = path.file_name()?.to_string_lossy().into_owned();
let root = level_dat(&dat);
let data = root.as_ref().and_then(|r| r.get("Data"));
let field = |key: &str| data.and_then(|d| d.get(key));
let number = |tag: Option<&Tag>| match tag {
Some(Tag::Byte(v)) => i64::from(*v),
Some(Tag::Int(v)) => i64::from(*v),
Some(Tag::Long(v)) => *v,
_ => 0,
};
let text = |tag: Option<&Tag>| match tag {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
// 26.3 keeps hardcore with the difficulty; older saves at the top of Data.
let hardcore = number(field("difficulty_settings").and_then(|d| d.get("hardcore"))) != 0
|| number(field("hardcore")) != 0;
let mode = match (hardcore, number(field("GameType"))) {
(true, _) => "Hardcore",
(_, 1) => "Creative",
(_, 2) => "Adventure",
(_, 3) => "Spectator",
_ => "Survival",
};
let last_played = match number(field("LastPlayed")) {
millis if millis > 0 => UNIX_EPOCH + Duration::from_millis(millis as u64),
_ => changed,
};
let icon = path.join("icon.png");
Some(World {
name: text(field("LevelName"))
.filter(|n| !n.trim().is_empty())
.unwrap_or_else(|| folder.clone()),
folder,
path: path.to_path_buf(),
mode,
last_played,
version: text(field("Version").and_then(|v| v.get("Name"))),
size: size(path),
icon: icon.is_file().then_some(icon),
})
}
fn size(dir: &Path) -> u64 {
fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| match e.file_type() {
Ok(t) if t.is_dir() => size(&e.path()),
Ok(_) => e.metadata().map_or(0, |m| m.len()),
Err(_) => 0,
})
.sum()
}
/// The world in `home` a command names: its folder, or its name (any case).
pub fn find(home: &Path, query: &str) -> Result<World, String> {
let all = list(home);
all.iter()
.find(|w| w.folder == query)
.or_else(|| all.iter().find(|w| w.name.eq_ignore_ascii_case(query)))
.cloned()
.ok_or_else(|| format!("No world {query} in {}", home.join("saves").display()))
}
/// `base`, else `base (1)`, `base (2)`... from the `first` count: the first name free in `dir`
/// (vanilla's `FileUtil.findAvailableName`, after making the name safe for every file system).
fn free_name(dir: &Path, base: &str, suffix: &str, first: u32) -> String {
let safe: String = base
.chars()
.map(|c| match c {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
c if c.is_control() => '_',
c => c,
})
.collect();
let safe = safe.trim_matches(|c: char| c == '.' || c.is_whitespace());
let safe = if safe.is_empty() { "World" } else { safe };
(first..)
.map(|n| match n {
0 => format!("{safe}{suffix}"),
n => format!("{safe} ({n}){suffix}"),
})
.find(|name| !dir.join(name).exists())
.unwrap()
}
/// Zips the world into the game folder's `backups/`, as vanilla's Make Backup does. Returns the
/// zip's path.
pub fn backup(home: &Path, world: &World) -> Result<PathBuf, String> {
backup_at(home, world, chrono::Local::now())
}
fn backup_at(
home: &Path,
world: &World,
now: chrono::DateTime<chrono::Local>,
) -> Result<PathBuf, String> {
let dir = home.join("backups");
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let prefix = format!("{}_{}", now.format("%Y-%m-%d_%H-%M-%S"), world.folder);
let zip_path = dir.join(free_name(&dir, &prefix, ".zip", 0));
let made = (|| -> std::io::Result<()> {
let mut zip = zip::ZipWriter::new(std::io::BufWriter::new(fs::File::create(&zip_path)?));
let options = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.large_file(true);
let mut stack = vec![world.path.clone()];
while let Some(dir) = stack.pop() {
let mut entries: Vec<_> = fs::read_dir(&dir)?.collect::<Result<_, _>>()?;
entries.sort_by_key(|e| e.file_name());
for e in entries {
let path = e.path();
if e.file_type()?.is_dir() {
stack.push(path);
continue;
}
if path.file_name() == Some(LOCK.as_ref()) {
continue;
}
let relative = path.strip_prefix(&world.path).unwrap_or(&path);
let mut entry = world.folder.clone();
for part in relative.components() {
entry.push('/');
entry.push_str(&part.as_os_str().to_string_lossy());
}
zip.start_file(entry, options)?;
std::io::copy(&mut fs::File::open(&path)?, &mut zip)?;
}
}
zip.finish()?.flush()
})();
made.map(|()| zip_path.clone()).map_err(|e| {
let _ = fs::remove_file(&zip_path);
format!("Could not back up {}: {e}", world.name)
})
}
/// Copies the world into a new folder of the same `saves/`, named "<name> (1)", "<name> (2)"...
/// and gives the copy that name in its level.dat so the game's list tells them apart.
pub fn copy(world: &World) -> Result<World, String> {
let saves = world.path.parent().ok_or("A world folder has a parent")?;
let folder = free_name(saves, &world.name, "", 1);
let to = saves.join(&folder);
let made = copy_dir(&world.path, &to).and_then(|()| rename_level(&to, &folder));
if let Err(e) = made {
let _ = fs::remove_dir_all(&to);
return Err(format!("Could not copy {}: {e}", world.name));
}
read(&to).ok_or_else(|| format!("{} has no level.dat", to.display()))
}
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
fs::create_dir_all(to)?;
for e in fs::read_dir(from)? {
let e = e?;
let target = to.join(e.file_name());
if e.file_type()?.is_dir() {
copy_dir(&e.path(), &target)?;
} else if e.file_name() != LOCK {
fs::copy(e.path(), target)?;
}
}
Ok(())
}
/// Sets `Data.LevelName`; a level.dat that can't be read is left as it is.
fn rename_level(world: &Path, name: &str) -> std::io::Result<()> {
let dat = world.join("level.dat");
let Some(mut root) = level_dat(&dat) else {
return Ok(());
};
let Some(Tag::Compound(data)) = root.get_mut("Data") else {
return Ok(());
};
data.insert("LevelName".into(), Tag::String(name.into()));
let bytes = nbt::write_named(
&nbt::NamedTag {
name: "".into(),
tag: root,
},
Limits::default(),
)
.map_err(std::io::Error::other)?;
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&bytes)?;
fs::write(dat, gz.finish()?)
}
/// Moves the world to the system's trash, where the player can still get it back.
pub fn delete(world: &World) -> Result<(), String> {
#[allow(unused_mut)]
let mut trash = trash::TrashContext::default();
// The crate's default on macOS asks Finder through AppleScript, which needs the player to
// allow the launcher to control Finder first; the file manager call needs nothing.
#[cfg(target_os = "macos")]
trash::macos::TrashContextExtMacos::set_delete_method(
&mut trash,
trash::macos::DeleteMethod::NsFileManager,
);
trash
.delete(&world.path)
.map_err(|e| format!("Could not move {} to the trash: {e}", world.name))
}
#[cfg(test)]
#[path = "worlds/tests.rs"]
mod tests;
+157
View File
@@ -0,0 +1,157 @@
use super::*;
use chrono::TimeZone;
fn scratch(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"horizon-launcher-worlds-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
root
}
/// A world as the game saves it: a gzip level.dat with `data`'s fields under `Data`.
fn world(home: &Path, folder: &str, data: Vec<(&str, Tag)>) -> PathBuf {
let dir = home.join("saves").join(folder);
fs::create_dir_all(dir.join("region")).unwrap();
let root = Tag::compound([("Data", Tag::compound(data))]);
let bytes = nbt::write_named(
&nbt::NamedTag {
name: "".into(),
tag: root,
},
Limits::default(),
)
.unwrap();
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&bytes).unwrap();
fs::write(dir.join("level.dat"), gz.finish().unwrap()).unwrap();
fs::write(dir.join("region/r.0.0.mca"), [7u8; 1000]).unwrap();
fs::write(dir.join(LOCK), "lock").unwrap();
dir
}
fn name(n: &str) -> Tag {
Tag::String(n.into())
}
#[test]
fn lists_what_each_world_is() {
let home = scratch("list");
let survival = world(
&home,
"Survival",
vec![
("LevelName", name("My survival")),
("GameType", Tag::Int(0)),
("LastPlayed", Tag::Long(1_700_000_000_000)),
("Version", Tag::compound([("Name", name("26.3"))])),
],
);
fs::write(survival.join("icon.png"), "png").unwrap();
world(
&home,
"Hard",
vec![
("LevelName", name("Hard")),
("GameType", Tag::Int(0)),
("LastPlayed", Tag::Long(1_800_000_000_000)),
(
"difficulty_settings",
Tag::compound([("hardcore", Tag::Byte(1))]),
),
],
);
world(
&home,
"Old",
vec![
("GameType", Tag::Int(1)),
("hardcore", Tag::Byte(0)),
("LastPlayed", Tag::Long(1_600_000_000_000)),
],
);
fs::create_dir_all(home.join("saves/not a world")).unwrap();
let all = list(&home);
let names: Vec<&str> = all.iter().map(|w| w.name.as_str()).collect();
assert_eq!(names, ["Hard", "My survival", "Old"]);
assert_eq!(all[0].mode, "Hardcore");
assert_eq!(all[1].mode, "Survival");
assert_eq!(all[1].folder, "Survival");
assert_eq!(all[1].version.as_deref(), Some("26.3"));
assert_eq!(all[1].icon, Some(survival.join("icon.png")));
assert_eq!(
all[1].last_played,
UNIX_EPOCH + Duration::from_millis(1_700_000_000_000)
);
assert!(all[1].size >= 1000);
// No LevelName: the folder's name.
assert_eq!(all[2].mode, "Creative");
assert_eq!(find(&home, "my SURVIVAL").unwrap().folder, "Survival");
assert!(find(&home, "nope").is_err());
fs::remove_dir_all(&home).unwrap();
}
#[test]
fn a_backup_is_named_and_laid_out_as_vanillas() {
let home = scratch("backup");
world(&home, "World", vec![("LevelName", name("World"))]);
let w = find(&home, "World").unwrap();
let at = chrono::Local
.with_ymd_and_hms(2026, 10, 27, 1, 2, 3)
.unwrap();
let first = backup_at(&home, &w, at).unwrap();
assert_eq!(first, home.join("backups/2026-10-27_01-02-03_World.zip"));
// The same second again: the next free name.
let second = backup_at(&home, &w, at).unwrap();
assert_eq!(
second,
home.join("backups/2026-10-27_01-02-03_World (1).zip")
);
let mut zip = zip::ZipArchive::new(fs::File::open(&first).unwrap()).unwrap();
let mut entries: Vec<String> = zip.file_names().map(str::to_string).collect();
entries.sort();
assert_eq!(entries, ["World/level.dat", "World/region/r.0.0.mca"]);
let mut region = Vec::new();
zip.by_name("World/region/r.0.0.mca")
.unwrap()
.read_to_end(&mut region)
.unwrap();
assert_eq!(region, [7u8; 1000]);
fs::remove_dir_all(&home).unwrap();
}
#[test]
fn a_copy_gets_the_next_free_name_in_its_folder_and_level_dat() {
let home = scratch("copy");
world(
&home,
"Base",
vec![("LevelName", name("Base")), ("GameType", Tag::Int(1))],
);
let base = find(&home, "Base").unwrap();
let copy1 = copy(&base).unwrap();
assert_eq!(copy1.folder, "Base (1)");
assert_eq!(copy1.name, "Base (1)");
assert_eq!(copy1.mode, "Creative");
assert!(!copy1.path.join(LOCK).exists());
assert_eq!(
fs::read(copy1.path.join("region/r.0.0.mca")).unwrap(),
[7u8; 1000]
);
assert_eq!(copy(&base).unwrap().folder, "Base (2)");
// The original is untouched.
assert_eq!(find(&home, "Base").unwrap(), base);
// A name that can't be a folder name is made safe.
assert_eq!(free_name(&home, "a/b: c?", "", 0), "a_b_ c_");
// A world whose folder isn't its name: the copy still gets a new name.
world(&home, "f", vec![("LevelName", name("Named"))]);
let named = copy(&find(&home, "f").unwrap()).unwrap();
assert_eq!(
(named.folder.as_str(), named.name.as_str()),
("Named (1)", "Named (1)")
);
fs::remove_dir_all(&home).unwrap();
}
+298
View File
@@ -0,0 +1,298 @@
//! The selected instance's worlds on Home (`horizon_launcher::worlds`): each with its picture,
//! mode, version, when it was last played and its size, and Back up, Copy, Delete (to the
//! trash, after a confirmation) and Open folder. Reading sizes and copying run in the background.
use super::*;
use horizon_launcher::worlds::{self, World};
use std::path::{Path, PathBuf};
#[derive(Default)]
pub(super) struct Worlds {
/// The game folder the list is of, and the list as last read: kept on screen while it is
/// read again, so the page doesn't jump.
home: Option<PathBuf>,
list: Vec<World>,
fresh: bool,
reading: bool,
/// The world being backed up, copied or deleted now.
busy: Option<String>,
confirm_delete: Option<String>,
/// What the last action did (a backup's zip), or why it failed.
done: Option<Result<(String, Option<PathBuf>), String>>,
}
impl Worlds {
/// Read again on the next frame: the game may have saved, or an action changed the list.
pub(super) fn stale(&mut self) {
self.fresh = false;
}
}
/// "today", "yesterday", "3 days ago", else the date.
fn ago(when: std::time::SystemTime) -> String {
let when: chrono::DateTime<chrono::Local> = when.into();
let days = (chrono::Local::now().date_naive() - when.date_naive()).num_days();
match days {
..=0 => "today".into(),
1 => "yesterday".into(),
2..=13 => format!("{days} days ago"),
_ => when.format("%Y-%m-%d").to_string(),
}
}
enum Action {
Backup,
Copy,
Delete,
}
impl Launcher {
/// Reads the worlds of `home` in the background when the list is missing or of another
/// instance.
fn load_worlds(&mut self, home: PathBuf, cx: &mut Context<Self>) {
if self.worlds.home.as_ref() != Some(&home) {
self.worlds = Worlds {
home: Some(home.clone()),
..Worlds::default()
};
}
if self.worlds.fresh || self.worlds.reading {
return;
}
self.worlds.reading = true;
let read = home.clone();
let task = cx
.background_executor()
.spawn(async move { worlds::list(&read) });
cx.spawn(async move |this, cx| {
let list = task.await;
let _ = this.update(cx, |this, cx| {
// Another instance may have been picked meanwhile.
if this.worlds.home.as_ref() == Some(&home) {
this.worlds.list = list;
this.worlds.fresh = true;
this.worlds.reading = false;
}
cx.notify();
});
})
.detach();
}
fn world_action(&mut self, action: Action, world: World, cx: &mut Context<Self>) {
let Some(home) = self.worlds.home.clone() else {
return;
};
if self.worlds.busy.is_some() {
return;
}
self.worlds.busy = Some(world.folder.clone());
self.worlds.confirm_delete = None;
self.worlds.done = None;
let task = cx.background_executor().spawn(async move {
match action {
Action::Backup => worlds::backup(&home, &world)
.map(|zip| (format!("{} backed up.", world.name), Some(zip))),
Action::Copy => {
worlds::copy(&world).map(|c| (format!("Copied to {}.", c.name), None))
}
Action::Delete => worlds::delete(&world)
.map(|()| (format!("{} moved to the trash.", world.name), None)),
}
});
cx.spawn(async move |this, cx| {
let done = task.await;
let _ = this.update(cx, |this, cx| {
this.worlds.busy = None;
this.worlds.done = Some(done);
this.worlds.stale();
cx.notify();
});
})
.detach();
}
/// Home's Worlds section, for the selected instance.
pub(super) fn worlds_section(&mut self, cx: &mut Context<Self>) -> Option<Div> {
let t = self.theme;
let home = self.selected_instance()?.home.clone();
self.load_worlds(home.clone(), cx);
let list = self.worlds.list.clone();
let mut section = div()
.flex()
.flex_col()
.gap(px(8.))
.child(section_title("Worlds", "globe", &t).mb(px(4.)));
match &self.worlds.done {
Some(Ok((message, zip))) => {
let mut line = div().flex().items_center().gap(px(12.)).child(
text(theme::CAPTION)
.text_color(t.muted)
.child(message.clone()),
);
if let Some(zip) = zip.clone() {
let dir = zip.parent().map(Path::to_path_buf).unwrap_or(zip);
line = line.child(
button("world-backups", "Open backups", Kind::Ghost, &t)
.on_click(move |_, _, cx| cx.open_with_system(&dir)),
);
}
section = section.child(line);
}
Some(Err(e)) => section = section.child(notice(e.clone(), &t)),
None => {}
}
if list.is_empty() {
let saves = home.join("saves");
return Some(
section.child(
div()
.flex()
.items_center()
.justify_between()
.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("No worlds yet: they appear here once you play one."),
)
.child(
button("worlds-folder", "Open folder", Kind::Ghost, &t).on_click(
move |_, _, cx| {
let _ = std::fs::create_dir_all(&saves);
cx.open_with_system(&saves);
},
),
),
),
);
}
for (i, w) in list.into_iter().enumerate() {
section = section.child(self.world_row(i, w, cx));
}
Some(section)
}
fn world_row(&mut self, i: usize, w: World, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let busy = self.worlds.busy.is_some();
let this_busy = self.worlds.busy.as_ref() == Some(&w.folder);
let confirming = self.worlds.confirm_delete.as_ref() == Some(&w.folder);
let picture = match &w.icon {
Some(icon) => div()
.flex_none()
.size(px(48.))
.border_2()
.border_color(t.outline)
.child(gpui::img(icon.clone()).size(px(44.)))
.into_any_element(),
None => div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(48.))
.border_2()
.border_color(t.outline)
.bg(t.well)
.child(blocks::icon("image", 22., t.muted))
.into_any_element(),
};
let mut facts = vec![w.mode.to_string()];
facts.extend(w.version.clone());
facts.push(ago(w.last_played));
facts.push(megabytes(w.size));
let act = |id: &str, label: &'static str, kind: Kind| {
let b = button(SharedString::from(format!("{id}-{i}")), label, kind, &t);
if busy {
disabled(b)
} else {
b
}
};
let mut actions = div().flex().items_center().gap(px(6.));
if confirming {
let gone = w.clone();
actions = actions
.child(
text(theme::CAPTION)
.text_color(t.danger)
.child("Move it to the trash?"),
)
.child(act("world-keep", "Keep", Kind::Ghost).on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.worlds.confirm_delete = None;
cx.notify();
},
)))
.child(
act("world-trash", "Move to trash", Kind::Secondary).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_action(Action::Delete, gone.clone(), cx);
cx.notify();
},
)),
);
} else if this_busy {
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();
actions = actions
.child(
act("world-backup", "Back up", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_action(Action::Backup, backup.clone(), cx);
cx.notify();
},
)),
)
.child(act("world-copy", "Copy", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_action(Action::Copy, copy.clone(), cx);
cx.notify();
},
)))
.child(
act("world-delete", "Delete", Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
// Buttons look disabled while something runs, but still click.
if this.worlds.busy.is_none() {
this.worlds.confirm_delete = Some(delete.clone());
}
cx.notify();
},
)),
)
.child(
act("world-folder", "Open folder", Kind::Ghost)
.on_click(move |_, _, cx| cx.open_with_system(&folder)),
);
}
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(w.name.clone()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(facts.join(" · ")),
),
)
.child(actions)
}
}