Launcher: data packs into a world

datapacks.rs lists a world's datapacks/ (zips and folders with
pack.mcmeta, as the game discovers them; off when datapacks.json lists them
disabled), adds a data pack zip under a free name (refusing resource packs:
no data/ folder) and removes one to the trash, forgetting it in
datapacks.json. The game turns a new pack on when the world opens.

Home: each world gets "Data packs", which opens its packs under the row
with Add data pack… and Remove; a zip dropped on a world goes into it.
CLI: `worlds datapack-list|datapack-add|datapack-remove <world>`;
datapack-remove needs confirm over MCP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 02:49:42 +01:00
parent cac63dedca
commit aa6fdac501
11 changed files with 640 additions and 4 deletions
+35
View File
@@ -374,6 +374,41 @@ Move a world to the system's trash.
MCP: `worlds_delete`, needs `confirm: true`.
## `horizon-launcher worlds datapack-list`
A world's data packs, and which are on.
horizon-launcher worlds datapack-list <WORLD>
- `WORLD`
- `--instance`
MCP: `worlds_datapack_list`.
## `horizon-launcher worlds datapack-add`
Copy a data pack zip into a world (the game turns it on when the world opens).
horizon-launcher worlds datapack-add <WORLD> <FILE>
- `WORLD`
- `FILE`
- `--instance`
MCP: `worlds_datapack_add`.
## `horizon-launcher worlds datapack-remove`
Move a world's data pack to the system's trash.
horizon-launcher worlds datapack-remove <WORLD> <PACK>
- `WORLD`
- `PACK`: Its file name, with or without .zip
- `--instance`
MCP: `worlds_datapack_remove`, needs `confirm: true`.
## `horizon-launcher packs list`
The resource and shader packs, and which are on (the default).
+5 -1
View File
@@ -88,7 +88,11 @@ 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.
**Play** on a world starts the game straight into it. **Data packs** opens the world's
`datapacks/` under its row: what is there (and which the game has turned off), **Add data pack…**,
and **Remove** (to the trash); a data pack `.zip` dropped on a world goes into it. The game turns
a new one on when the world opens. From the command line: `horizon-launcher worlds
datapack-list|datapack-add|datapack-remove <world> …`.
- **Packs**: Home lists the selected instance's resource packs and shader packs, each with a switch.
The choice is the game's own: `resourcePacks` in options.txt (a pack turned on goes on top, as
the game's Resource Packs screen does) and `pickedShaderPack` in `horizon-graphics.txt` (one shader
+62
View File
@@ -212,6 +212,27 @@ enum WorldsCmd {
#[arg(long)]
instance: Option<String>,
},
/// A world's data packs, and which are on
DatapackList {
world: String,
#[arg(long)]
instance: Option<String>,
},
/// Copy a data pack zip into a world (the game turns it on when the world opens)
DatapackAdd {
world: String,
file: PathBuf,
#[arg(long)]
instance: Option<String>,
},
/// Move a world's data pack to the system's trash
DatapackRemove {
world: String,
/// Its file name, with or without .zip
pack: String,
#[arg(long)]
instance: Option<String>,
},
}
#[derive(Clone, Copy, clap::ValueEnum)]
@@ -1816,6 +1837,7 @@ fn multiplayer(action: MultiplayerCmd, as_json: bool) -> Result<(), String> {
}
fn worlds(action: WorldsCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::datapacks;
use horizon_launcher::worlds::{self, World};
let home = |instance: Option<String>| -> Result<PathBuf, String> {
Ok(match instance {
@@ -1873,6 +1895,46 @@ fn worlds(action: WorldsCmd, as_json: bool) -> Result<(), String> {
worlds::delete(&w)?;
println!("{} is in the trash.", w.name);
}
WorldsCmd::DatapackList { world, instance } => {
let w = worlds::find(&home(instance)?, &world)?;
let packs = datapacks::list(&w.path);
if as_json {
json(
packs
.iter()
.map(|p| serde_json::json!({ "file": p.file, "description": p.description, "enabled": p.enabled, "path": p.path }))
.collect(),
);
} else if packs.is_empty() {
println!("No data packs in {}", w.name);
}
for p in packs.iter().filter(|_| !as_json) {
let on = if p.enabled { "on " } else { "off" };
println!(" {on} {} {}", p.file, p.description);
}
}
WorldsCmd::DatapackAdd {
world,
file,
instance,
} => {
let w = worlds::find(&home(instance)?, &world)?;
let p = datapacks::add(&w.path, &file)?;
println!(
"Added {} to {}: the game turns it on when the world opens.",
p.file, w.name
);
}
WorldsCmd::DatapackRemove {
world,
pack,
instance,
} => {
let w = worlds::find(&home(instance)?, &world)?;
let p = datapacks::find(&w.path, &pack)?;
datapacks::remove(&w.path, &p)?;
println!("{} is in the trash.", p.file);
}
}
Ok(())
}
+1
View File
@@ -30,6 +30,7 @@ pub const DESTRUCTIVE: &[&str] = &[
"multiplayer remove",
"screenshots delete",
"packs remove",
"worlds datapack-remove",
];
/// Commands that send something or reach other people: only when the player asks.
+156
View File
@@ -0,0 +1,156 @@
//! A world's data packs: `<world>/datapacks/`, each a `.zip` or a folder with a `pack.mcmeta`, as
//! the game discovers them (`datapack::discover`). The game turns on every pack it finds there
//! that `<world>/datapacks.json` doesn't list as disabled, when the world opens or on `/reload`,
//! so adding one is copying it in.
use crate::packs::{entry, plain};
use std::fs;
use std::path::{Path, PathBuf};
const SETTINGS: &str = "datapacks.json";
#[derive(Clone, Debug, PartialEq)]
pub struct DataPack {
/// Its file or folder name in `datapacks/`; the game's id is `file/<name>`.
pub file: String,
pub path: PathBuf,
/// `pack.mcmeta`'s description as plain text.
pub description: String,
/// Off when `datapacks.json` lists it as disabled (the game's `/datapack disable`).
pub enabled: bool,
}
fn settings(world: &Path) -> serde_json::Value {
fs::read(world.join(SETTINGS))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_else(|| serde_json::json!({}))
}
fn disabled(settings: &serde_json::Value) -> Vec<String> {
settings["disabled"]
.as_array()
.into_iter()
.flatten()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
}
/// The data packs of the world folder `world`, by name.
pub fn list(world: &Path) -> Vec<DataPack> {
let off = disabled(&settings(world));
let mut packs: Vec<DataPack> = fs::read_dir(world.join("datapacks"))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| {
let path = e.path();
let file = e.file_name().to_str()?.to_string();
let zip = path.is_file() && file.to_ascii_lowercase().ends_with(".zip");
if !(zip || path.is_dir()) {
return None;
}
let meta: serde_json::Value =
serde_json::from_slice(&entry(&path, "pack.mcmeta")?).ok()?;
Some(DataPack {
enabled: !off.contains(&format!("file/{file}")),
description: plain(&meta["pack"]["description"]),
file,
path,
})
})
.collect();
packs.sort_by_key(|p| p.file.to_lowercase());
packs
}
/// Whether a zip is a data pack: a `pack.mcmeta` and a `data/` folder.
fn check(file: &Path) -> Result<(), String> {
let name = file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let zip = fs::File::open(file)
.ok()
.and_then(|f| zip::ZipArchive::new(f).ok())
.ok_or_else(|| format!("{name} is not a zip file that can be read."))?;
if zip.index_for_name("pack.mcmeta").is_none() {
return Err(format!("{name} is not a pack: it has no pack.mcmeta."));
}
if !zip.file_names().any(|n| n.starts_with("data/")) {
return Err(format!(
"{name} has no data folder: it is a resource pack, not a data pack."
));
}
Ok(())
}
/// Copies a data pack zip into the world's `datapacks/` under a free name. The game turns it on
/// the next time the world opens (or on `/reload`).
pub fn add(world: &Path, file: &Path) -> Result<DataPack, String> {
check(file)?;
let dir = world.join("datapacks");
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let name = file.file_name().ok_or("A pack file has a name")?;
let stem = Path::new(name)
.file_stem()
.unwrap_or(name)
.to_string_lossy();
let target = (1..)
.map(|n| match n {
1 => dir.join(name),
n => dir.join(format!("{stem} ({n}).zip")),
})
.find(|p| !p.exists())
.unwrap();
fs::copy(file, &target).map_err(|e| format!("Could not copy {}: {e}", file.display()))?;
let file_name = target.file_name().unwrap().to_string_lossy().into_owned();
// A pack of the same name removed while it was disabled would stay off.
forget(world, &file_name)?;
list(world)
.into_iter()
.find(|p| p.file == file_name)
.ok_or_else(|| format!("{} is not a data pack the game reads", target.display()))
}
/// Drops `file/<name>` from both lists of `datapacks.json`, when it is there.
fn forget(world: &Path, file: &str) -> Result<(), String> {
let mut s = settings(world);
let id = format!("file/{file}");
let mut changed = false;
for key in ["enabled", "disabled"] {
if let Some(list) = s[key].as_array_mut() {
let before = list.len();
list.retain(|v| v.as_str() != Some(id.as_str()));
changed |= list.len() != before;
}
}
if !changed {
return Ok(());
}
let text = serde_json::to_string_pretty(&s).unwrap();
fs::write(world.join(SETTINGS), text).map_err(|e| format!("{SETTINGS}: {e}"))
}
/// The data pack a command names: its file name, with or without `.zip`.
pub fn find(world: &Path, query: &str) -> Result<DataPack, String> {
list(world)
.into_iter()
.find(|p| p.file == query || p.file.strip_suffix(".zip") == Some(query))
.ok_or_else(|| {
format!(
"No data pack {query} in {}",
world.join("datapacks").display()
)
})
}
/// Moves the data pack to the system's trash and forgets it in `datapacks.json`.
pub fn remove(world: &Path, pack: &DataPack) -> Result<(), String> {
crate::desktop_seams::to_trash(&pack.path)
.map_err(|e| format!("Could not move {} to the trash: {e}", pack.file))?;
forget(world, &pack.file)
}
#[cfg(test)]
#[path = "datapacks/tests.rs"]
mod tests;
+103
View File
@@ -0,0 +1,103 @@
use super::*;
use std::io::Write;
fn scratch(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"horizon-launcher-datapacks-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
root
}
fn zip_file(path: &Path, files: &[(&str, &str)]) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut zip = zip::ZipWriter::new(fs::File::create(path).unwrap());
for (name, text) in files {
zip.start_file(*name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(text.as_bytes()).unwrap();
}
zip.finish().unwrap();
}
const META: &str = r#"{"pack":{"pack_format":88,"description":"More trades"}}"#;
#[test]
fn lists_adds_and_removes_as_the_game_reads_them() {
let root = scratch("all");
let world = root.join("saves/My World");
zip_file(
&world.join("datapacks/Trades.zip"),
&[
("pack.mcmeta", META),
("data/t/function/a.mcfunction", "say hi"),
],
);
fs::create_dir_all(world.join("datapacks/folder pack")).unwrap();
fs::write(
world.join("datapacks/folder pack/pack.mcmeta"),
r#"{"pack":{"description":{"text":"Mine"}}}"#,
)
.unwrap();
fs::write(world.join("datapacks/readme.txt"), "").unwrap();
fs::write(
world.join("datapacks.json"),
r#"{"enabled":[],"disabled":["file/folder pack","file/Gone.zip"]}"#,
)
.unwrap();
let packs = list(&world);
let seen: Vec<(&str, &str, bool)> = packs
.iter()
.map(|p| (p.file.as_str(), p.description.as_str(), p.enabled))
.collect();
assert_eq!(
seen,
[
("folder pack", "Mine", false),
("Trades.zip", "More trades", true)
]
);
let drops = root.join("drops");
zip_file(
&drops.join("Gone.zip"),
&[("pack.mcmeta", META), ("data/g/tags/x.json", "{}")],
);
zip_file(
&drops.join("Trades.zip"),
&[("pack.mcmeta", META), ("data/t/function/b.mcfunction", "")],
);
zip_file(
&drops.join("Textures.zip"),
&[
("pack.mcmeta", META),
("assets/minecraft/textures/a.png", ""),
],
);
// A pack disabled before it was taken out comes back on.
let gone = add(&world, &drops.join("Gone.zip")).unwrap();
assert!(gone.enabled);
assert!(!fs::read_to_string(world.join("datapacks.json"))
.unwrap()
.contains("Gone.zip"));
assert_eq!(
add(&world, &drops.join("Trades.zip")).unwrap().file,
"Trades (2).zip"
);
let refused = add(&world, &drops.join("Textures.zip")).unwrap_err();
assert!(refused.contains("resource pack"), "{refused}");
let folder = find(&world, "folder pack").unwrap();
let trash = root.join("trash");
std::env::set_var(crate::desktop_seams::TRASH_ENV, &trash);
remove(&world, &folder).unwrap();
std::env::remove_var(crate::desktop_seams::TRASH_ENV);
assert!(trash.join("folder pack/pack.mcmeta").is_file());
assert!(!fs::read_to_string(world.join("datapacks.json"))
.unwrap()
.contains("folder pack"));
assert_eq!(find(&world, "Trades").unwrap().file, "Trades.zip");
fs::remove_dir_all(&root).unwrap();
}
+255
View File
@@ -0,0 +1,255 @@
//! A world's data packs, opened under its row on Home (`horizon_launcher::datapacks`): what is
//! in `datapacks/`, Add (a file picker) or a zip dropped on the world, and Remove (to the trash,
//! after a confirmation).
use super::*;
use gpui::ExternalPaths;
use horizon_launcher::datapacks::{self, DataPack};
use horizon_launcher::worlds::World;
use std::path::PathBuf;
#[derive(Default)]
pub(super) struct WorldPacks {
/// The world whose packs are open, and its packs as last read.
open: Option<PathBuf>,
list: Vec<DataPack>,
confirm_remove: Option<String>,
note: Option<Result<String, String>>,
}
impl Launcher {
/// Opens or closes the packs of `world` under its row.
pub(super) fn toggle_world_packs(&mut self, world: &World) {
if self.world_packs.open.as_ref() == Some(&world.path) {
self.world_packs = WorldPacks::default();
} else {
self.world_packs = WorldPacks {
open: Some(world.path.clone()),
list: datapacks::list(&world.path),
..WorldPacks::default()
};
}
}
pub(super) fn world_packs_open(&self, world: &World) -> bool {
self.world_packs.open.as_ref() == Some(&world.path)
}
/// Copies dropped or picked zips into `world`, and opens its packs to show them.
pub(super) fn add_world_packs(&mut self, world: PathBuf, files: Vec<PathBuf>) {
let added: Result<Vec<String>, String> = files
.iter()
.map(|f| datapacks::add(&world, f).map(|p| p.file))
.collect();
self.world_packs = WorldPacks {
list: datapacks::list(&world),
note: Some(added.map(|names| {
format!(
"Added {}: the game turns it on when the world opens.",
names.join(", ")
)
})),
open: Some(world),
confirm_remove: None,
};
}
fn choose_world_packs(&mut self, world: PathBuf, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: true,
prompt: Some("Add".into()),
});
cx.spawn(async move |this, cx| {
if let Ok(Ok(Some(paths))) = paths.await {
let _ = this.update(cx, |this, cx| {
this.add_world_packs(world, paths);
cx.notify();
});
}
})
.detach();
}
/// A world row that takes dropped data packs.
pub(super) fn world_drop_target(
&self,
i: usize,
world: &World,
row: Div,
cx: &mut Context<Self>,
) -> Stateful<Div> {
let t = self.theme;
let path = world.path.clone();
div()
.id(SharedString::from(format!("world-drop-{i}")))
.border_2()
.mx(px(-4.))
.p(px(2.))
.border_color(gpui::transparent_black())
.drag_over::<ExternalPaths>(move |s, _, _, _| s.border_color(t.accent))
.on_drop(cx.listener(move |this, paths: &ExternalPaths, _, cx| {
this.add_world_packs(path.clone(), paths.paths().to_vec());
cx.notify();
}))
.child(row)
}
/// The open world's packs, under its row.
pub(super) fn world_packs_panel(
&mut self,
world: &World,
cx: &mut Context<Self>,
) -> Option<Div> {
if !self.world_packs_open(world) {
return None;
}
let t = self.theme;
let path = world.path.clone();
let mut panel = div()
.flex()
.flex_col()
.gap(px(6.))
.ml(px(62.))
.mb(px(6.))
.child(
div()
.flex()
.items_center()
.justify_between()
.child(caps("Data packs").text_color(t.muted))
.child(
div()
.flex()
.gap(px(6.))
.child(
button("world-packs-add", "Add data pack…", Kind::Ghost, &t)
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.choose_world_packs(path.clone(), cx);
cx.notify();
})),
)
.child({
let dir = world.path.join("datapacks");
button("world-packs-folder", "Open folder", Kind::Ghost, &t)
.on_click(move |_, _, cx| {
let _ = std::fs::create_dir_all(&dir);
cx.open_with_system(&dir);
})
}),
),
);
match &self.world_packs.note {
Some(Ok(m)) => {
panel = panel.child(text(theme::CAPTION).text_color(t.muted).child(m.clone()))
}
Some(Err(e)) => panel = panel.child(notice(e.clone(), &t)),
None => {}
}
if self.world_packs.list.is_empty() {
panel = panel.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("None yet: drop a data pack .zip on the world, or use Add data pack…"),
);
}
for (i, pack) in self.world_packs.list.clone().into_iter().enumerate() {
let confirming = self.world_packs.confirm_remove.as_ref() == Some(&pack.file);
let mut actions = div().flex().items_center().gap(px(6.));
if confirming {
let (world, gone) = (world.path.clone(), pack.clone());
actions = actions
.child(
text(theme::CAPTION)
.text_color(t.danger)
.child("Move it to the trash?"),
)
.child(
button(
SharedString::from(format!("world-pack-keep-{i}")),
"Keep",
Kind::Ghost,
&t,
)
.on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.world_packs.confirm_remove = None;
cx.notify();
},
)),
)
.child(
button(
SharedString::from(format!("world-pack-trash-{i}")),
"Move to trash",
Kind::Secondary,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
let note = datapacks::remove(&world, &gone)
.map(|()| format!("{} moved to the trash.", gone.file));
this.world_packs.list = datapacks::list(&world);
this.world_packs.note = Some(note);
this.world_packs.confirm_remove = None;
cx.notify();
},
)),
);
} else {
let file = pack.file.clone();
if !pack.enabled {
actions = actions.child(
text(theme::CAPTION)
.text_color(t.muted)
.child("Off in the game"),
);
}
actions = actions.child(
button(
SharedString::from(format!("world-pack-remove-{i}")),
"Remove",
Kind::Ghost,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.world_packs.confirm_remove = Some(file.clone());
cx.notify();
},
)),
);
}
panel = panel.child(
plate(&t)
.flex()
.items_center()
.gap(px(12.))
.px(px(12.))
.py(px(6.))
.child(blocks::icon("package", 16., t.muted))
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.child(
text(theme::LABEL)
.text_color(t.ink)
.truncate()
.child(pack.file.clone()),
)
.child(
text(theme::CAPTION)
.text_color(t.muted)
.truncate()
.child(pack.description.clone()),
),
)
.child(actions),
);
}
Some(panel)
}
}
+1
View File
@@ -3,6 +3,7 @@ pub mod account;
pub mod agents;
pub mod backend;
pub mod browser;
pub mod datapacks;
pub mod desktop;
pub mod desktop_seams;
#[cfg(unix)]
+3
View File
@@ -11,6 +11,7 @@ mod cli_tools;
mod collection;
mod console;
mod cull;
mod datapacks_page;
mod game_tools;
mod instances_page;
mod internet;
@@ -239,6 +240,7 @@ struct Launcher {
multiplayer: multiplayer_page::Multiplayer,
screenshots: screenshots_page::Screenshots,
game_packs: packs_page::Packs,
world_packs: datapacks_page::WorldPacks,
/// 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.
@@ -402,6 +404,7 @@ impl Launcher {
multiplayer: multiplayer_page::Multiplayer::default(),
screenshots: screenshots_page::Screenshots::default(),
game_packs: packs_page::Packs::default(),
world_packs: datapacks_page::WorldPacks::default(),
offline_name: offline_name(),
side_servers: horizon_launcher::servers::list(),
art: art::Art::default(),
+2 -2
View File
@@ -124,7 +124,7 @@ fn read(path: &Path, kind: Kind, on: &[String]) -> Option<Pack> {
}
/// A file at the root of a pack folder or zip, at most 4 MB.
fn entry(path: &Path, name: &str) -> Option<Vec<u8>> {
pub(crate) fn entry(path: &Path, name: &str) -> Option<Vec<u8>> {
let mut out = Vec::new();
if path.is_dir() {
fs::File::open(path.join(name))
@@ -141,7 +141,7 @@ fn entry(path: &Path, name: &str) -> Option<Vec<u8>> {
}
/// A text component as plain text: its strings, without `§` formatting codes.
fn plain(component: &serde_json::Value) -> String {
pub(crate) fn plain(component: &serde_json::Value) -> String {
fn walk(v: &serde_json::Value, out: &mut String) {
match v {
serde_json::Value::String(s) => out.push_str(s),
+17 -1
View File
@@ -166,7 +166,10 @@ impl Launcher {
);
}
for (i, w) in list.into_iter().enumerate() {
section = section.child(self.world_row(i, w, cx));
let row = self.world_row(i, w.clone(), cx);
section = section
.child(self.world_drop_target(i, &w, row, cx))
.children(self.world_packs_panel(&w, cx));
}
Some(section)
}
@@ -275,6 +278,19 @@ impl Launcher {
},
)),
)
.child({
let world = w.clone();
let label = match self.world_packs_open(&w) {
true => "Hide data packs",
false => "Data packs",
};
act("world-packs", label, Kind::Ghost).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.toggle_world_packs(&world);
cx.notify();
},
))
})
.child(
act("world-folder", "Open folder", Kind::Ghost)
.on_click(move |_, _, cx| cx.open_with_system(&folder)),