diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 9efaa1f37..a71df4257 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -587,7 +587,7 @@ Search for packs Horizon loads. horizon-launcher mods search [TEXT]... - `TEXT` -- `--kind` (mod, resource, modpack, shader) +- `--kind` (mod, resource, modpack, shader, datapack) - `--everything`: Also what was made for other versions or runs only partly, each marked - `--source` (modrinth, curseforge, horizon) @@ -607,11 +607,12 @@ MCP: `mods_check`. ## `horizon-launcher mods install` -Install a pack and what it needs into an instance, by its id or slug (checksums checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported as an instance of its own. +Install a pack and what it needs into an instance, by its id or slug (checksums checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported as an instance of its own; a data pack goes into the world `--world` names. horizon-launcher mods install - `PROJECT` +- `--world`: Install the project's data pack into this world of the instance (its name or folder) - `--instance`: The instance (default: the selected one) - `--everything`: Allow a version made for another Minecraft version - `--source` (modrinth, curseforge, horizon) diff --git a/docs/mod-browser.md b/docs/mod-browser.md index dac595d8e..8db26c26a 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -1,6 +1,6 @@ # The launcher's mod browser -Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks and resource packs, and Horizon's +Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks, resource packs and data packs, and Horizon's registry for Horizon's own mods, modpacks, resource packs and shader packs; see how well each one runs before installing it, and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in `launcher/src/browser.rs` and `launcher/src/browser/`. @@ -17,6 +17,7 @@ yet (Modrinth has no `horizon` loader). | Resource packs | `resourcepacks/` beside `options.txt` | **Works** when made for 26.3 ([resource-packs.md](resource-packs.md) lists what Horizon reads). Older packs are **Partly**: they load with vanilla's compatibility warning | | Modpacks (`.mrpack`, CurseForge zip) | the Modpacks page's import | **Partly**: Horizon runs the mods it can port, from the player's own downloads ([modpacks.md](modpacks.md)) | | Shader packs (`.hshader`, Horizon's registry only) | `shaderpacks/` beside `options.txt` | **Works** when made for 26.3: checked by the game's own check before install ([shaders.md](shaders.md)). The `shaders/`-format packs on Modrinth and CurseForge are not offered | +| Data packs (Modrinth) | `datapacks/` of the world picked on the **Data packs** tab (`mods install --world `); not in the Installed list: each world's list on Home has them | **Partly**: Horizon runs a data pack's functions, function tags, predicates and item modifiers, not yet its recipes, loot tables, advancements, other tags or worldgen. The install reads the zip and says what of it runs; a pack with none of those (worldgen only, such as Tectonic) is refused | Mods, resource packs and shader packs go into the game folder of the instance selected in the sidebar, and the Installed list, updates and Remove are that instance's: picking another instance reads its list. The page says which diff --git a/launcher/README.md b/launcher/README.md index ddf7e3056..0fa2a6aef 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -92,7 +92,9 @@ The opening, then Play ([clip](docs/opening.webm)): `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 …`. + datapack-list|datapack-add|datapack-remove …`. The Mods page's **Data packs** tab finds + them on Modrinth and installs one into the world picked there (`mods search --kind datapack`, + `mods install --world `), saying what of it runs in Horizon. - **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 diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs index 295ba3c08..4d8bc5be4 100644 --- a/launcher/src/browser.rs +++ b/launcher/src/browser.rs @@ -3,8 +3,9 @@ //! matches (docs/mod-browser.md). //! //! Offered: Java mods (Fabric, NeoForge, Forge), whose content Horizon ports and whose jar is -//! checked before install ([`java`]), modpacks (imported and ported) and resource packs -//! (`resourcepacks/`). Java code itself doesn't run in Horizon (docs/mods.md). +//! checked before install ([`java`]), modpacks (imported and ported), resource packs +//! (`resourcepacks/`) and data packs (into a world, [`installed::install_datapack`]). Java code +//! itself doesn't run in Horizon (docs/mods.md). pub mod curseforge; pub mod details; pub mod download; @@ -31,10 +32,18 @@ pub enum Kind { /// One of Horizon's own shader packs (`.hshader`, docs/shaders.md), from Horizon's registry /// only. Shader, + /// A data pack: it goes into one world's `datapacks/` (`crate::datapacks`). + DataPack, } impl Kind { - pub const ALL: [Kind; 4] = [Kind::Mod, Kind::Modpack, Kind::ResourcePack, Kind::Shader]; + pub const ALL: [Kind; 5] = [ + Kind::Mod, + Kind::Modpack, + Kind::ResourcePack, + Kind::Shader, + Kind::DataPack, + ]; pub fn label(self) -> &'static str { match self { @@ -42,16 +51,17 @@ impl Kind { Kind::ResourcePack => "Resource packs", Kind::Modpack => "Modpacks", Kind::Shader => "Shader packs", + Kind::DataPack => "Data packs", } } - /// The folder beside `options.txt` the file goes in; a modpack is imported and a mod - /// ported instead. + /// The folder beside `options.txt` the file goes in; a modpack is imported, a mod ported + /// and a data pack put in a world instead. pub fn folder(self) -> Option<&'static str> { match self { Kind::ResourcePack => Some("resourcepacks"), Kind::Shader => Some("shaderpacks"), - Kind::Modpack | Kind::Mod => None, + Kind::Modpack | Kind::Mod | Kind::DataPack => None, } } } @@ -132,6 +142,19 @@ impl Project { pub fn support(&self) -> Support { support(self.kind, &self.game_versions, &self.loaders) } + + /// The project as a data pack, for a search of data packs or an install into a world; + /// its page is Modrinth's data pack page. + pub fn as_datapack(self) -> Project { + Project { + page: match self.source { + SourceId::Modrinth => format!("https://modrinth.com/datapack/{}", self.slug), + _ => self.page, + }, + kind: Kind::DataPack, + ..self + } + } } /// One downloadable file of a version, with the checksums its source publishes. @@ -286,6 +309,14 @@ pub fn support(kind: Kind, game_versions: &[String], loaders: &[String]) -> Supp Support::Partial("Horizon runs the mods it can port, from your own downloads.".into()) } Kind::Shader => Support::No("Not one of Horizon's own shader packs.".into()), + Kind::DataPack => { + let made_for = match newest_release(game_versions) { + _ if game_versions.iter().any(|v| v == GAME) => String::new(), + Some(newest) => format!("Made for {newest}: the game may refuse it. "), + None => "Lists no Minecraft version. ".into(), + }; + Support::Partial(format!("{made_for}{DATAPACK_SUPPORT}")) + } Kind::Mod => { if !loaders.iter().any(|l| java::LOADERS.contains(&l.as_str())) { Support::No("Not a Fabric, NeoForge or Forge mod.".into()) @@ -303,6 +334,12 @@ pub fn support(kind: Kind, game_versions: &[String], loaders: &[String]) -> Supp } } +/// What a data pack does in Horizon today, said before install; the install says it for the +/// pack's own files (`crate::datapacks::coverage`). +pub const DATAPACK_SUPPORT: &str = "Horizon runs a data pack's functions, function tags, \ + predicates and item modifiers; not yet its recipes, loot tables, advancements, other tags \ + or worldgen."; + /// A Minecraft version whose mods port-pack carries over: 1.21 and later (the data folders /// took their current names in 1.21). pub fn portable_version(v: &str) -> bool { @@ -356,6 +393,15 @@ pub fn pick(kind: Kind, versions: &[Version], everything: bool) -> Option<&Versi .find(made_for) .or_else(|| usable.filter(java).find(|v| everything && ported(v))); } + if kind == Kind::DataPack { + // Most data packs on Modrinth ship a mod build too: only the data pack files. + let mut packs = usable.filter(|v| v.loaders.iter().any(|l| l == "datapack")); + let made_for = |v: &&Version| v.game_versions.iter().any(|g| g == GAME); + return packs + .clone() + .find(made_for) + .or_else(|| packs.find(|_| everything)); + } let runs = |v: &&Version| match support(kind, &v.game_versions, &v.loaders) { Support::Works => true, // A modpack's version is for its own Minecraft. diff --git a/launcher/src/browser/curseforge.rs b/launcher/src/browser/curseforge.rs index 56d73777a..68002c5ed 100644 --- a/launcher/src/browser/curseforge.rs +++ b/launcher/src/browser/curseforge.rs @@ -25,6 +25,7 @@ fn class(kind: Kind) -> u64 { Kind::Modpack => 4471, Kind::Mod => 6, Kind::Shader => 6552, + Kind::DataPack => 6945, } } diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs index 741fe336a..7357efc22 100644 --- a/launcher/src/browser/horizon.rs +++ b/launcher/src/browser/horizon.rs @@ -484,6 +484,7 @@ fn relative(kind: Kind, id: &str, file_name: &str) -> Result { Kind::ResourcePack => Ok(format!("resourcepacks/{file_name}")), Kind::Shader => Ok(format!("shaderpacks/{file_name}")), Kind::Modpack => Err("A modpack installs as its own profile (pack::install).".into()), + Kind::DataPack => Err("Horizon's registry has no data packs.".into()), } } diff --git a/launcher/src/browser/installed.rs b/launcher/src/browser/installed.rs index c866dd26d..c6dcfb41f 100644 --- a/launcher/src/browser/installed.rs +++ b/launcher/src/browser/installed.rs @@ -296,5 +296,67 @@ pub fn fetch_modpack( source.fetch(file, folder, progress) } +/// A data pack installed into a world. +pub struct DataPackInstall { + pub pack: crate::datapacks::DataPack, + /// Its version's number. + pub number: String, + /// What of it runs in Horizon. + pub coverage: crate::datapacks::Coverage, +} + +/// Downloads a project's data pack (checksum checked) into the world folder `world`, under a +/// free name. Refused when nothing in it runs in Horizon yet. It isn't recorded with the +/// browser's installs: the world's data pack list (Home, `worlds datapack-list`) has it. +pub fn install_datapack( + source: &dyn Source, + project: &Project, + everything: bool, + world: &Path, + progress: &dyn Fn(f32), +) -> Result { + if project.kind != Kind::DataPack && !project.loaders.iter().any(|l| l == "datapack") { + return Err(format!("{} isn't a data pack.", project.title)); + } + let versions = source.versions(project)?; + let version = pick(Kind::DataPack, &versions, everything).ok_or_else(|| { + format!( + "{} has no data pack for {}{}.", + project.title, + super::GAME, + if everything { + " or any other version" + } else { + "" + } + ) + })?; + let file = version.file().expect("pick keeps versions with a file"); + let folder = std::env::temp_dir().join(format!( + "horizon-launcher-datapack-{}-{}", + std::process::id(), + version.id + )); + let result = source.fetch(file, &folder, progress).and_then(|zip| { + let coverage = crate::datapacks::coverage(&zip)?; + if coverage.read.is_empty() { + return Err(format!( + "{} would change nothing in Horizon yet: it has no functions, predicates or item \ + modifiers, and Horizon doesn't read its {} yet.", + project.title, + coverage.not_read() + )); + } + let pack = crate::datapacks::add(world, &zip)?; + Ok(DataPackInstall { + pack, + number: version.number.clone(), + coverage, + }) + }); + let _ = fs::remove_dir_all(&folder); + result +} + #[cfg(test)] mod tests; diff --git a/launcher/src/browser/installed/tests.rs b/launcher/src/browser/installed/tests.rs index cb2814c29..152ff03c3 100644 --- a/launcher/src/browser/installed/tests.rs +++ b/launcher/src/browser/installed/tests.rs @@ -340,3 +340,91 @@ fn shader_packs_older_launchers_installed_are_left_alone() { assert!(home.join("shaderpacks/old-pack.zip").is_file()); fs::remove_dir_all(&home).unwrap(); } + +/// A data pack zip with these files. +fn datapack_zip(files: &[&str]) -> Vec { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("pack.mcmeta", options).unwrap(); + zip.write_all(br#"{"pack":{"pack_format":94,"description":"Test"}}"#) + .unwrap(); + for name in files { + zip.start_file(*name, options).unwrap(); + zip.write_all(b"{}").unwrap(); + } + zip.finish().unwrap().into_inner() +} + +#[test] +fn data_packs_go_into_a_world_when_something_in_them_runs() { + let world = home("datapack").join("saves/New World"); + fs::create_dir_all(&world).unwrap(); + let mut fake = Fake::default(); + let mut tools = project("tools", Kind::DataPack); + tools.loaders = vec!["datapack".into()]; + fake.add(tools); + let mut terrain = project("terrain", Kind::Mod); + terrain.loaders = vec!["datapack".into(), "fabric".into()]; + fake.add(terrain); + let mut jar = project("jar", Kind::Mod); + jar.loaders = vec!["fabric".into()]; + fake.add(jar); + let runs = datapack_zip(&[ + "data/t/function/a.mcfunction", + "data/t/function/b.mcfunction", + "data/minecraft/tags/function/load.json", + "data/t/recipe/r.json", + ]); + fake.release("tools", "2.0", &[], &runs, false); + fake.release( + "terrain", + "1.0", + &[], + &datapack_zip(&["data/t/worldgen/biome/b.json"]), + false, + ); + let tools = fake.project("tools").unwrap(); + let off = &|_: f32| {}; + + let done = install_datapack(&fake, &tools, false, &world, off).unwrap(); + assert_eq!(done.pack.file, "tools-2.0.zip"); + assert!(done.pack.enabled); + assert_eq!(done.number, "2.0"); + assert_eq!( + done.coverage.summary(), + "Runs its 2 functions, 1 function tag. Not read yet: 1 recipe." + ); + assert!(world.join("datapacks/tools-2.0.zip").is_file()); + // Nothing of it in the browser's own list. + assert!(Installed::load(world.parent().unwrap().parent().unwrap()) + .entries + .is_empty()); + let again = install_datapack(&fake, &tools, false, &world, off).unwrap(); + assert_eq!(again.pack.file, "tools-2.0 (2).zip"); + + let terrain = fake.project("terrain").unwrap(); + let refused = install_datapack(&fake, &terrain, false, &world, off) + .err() + .unwrap(); + assert_eq!( + refused, + "Pack terrain would change nothing in Horizon yet: it has no functions, predicates or \ + item modifiers, and Horizon doesn't read its 1 worldgen yet." + ); + let jar = fake.project("jar").unwrap(); + assert!(install_datapack(&fake, &jar, false, &world, off).is_err()); + + let mut bad = project("bad", Kind::DataPack); + bad.loaders = vec!["datapack".into()]; + fake.add(bad); + fake.release("bad", "1", &[], &runs, true); + let bad = fake.project("bad").unwrap(); + assert!(install_datapack(&fake, &bad, false, &world, off).is_err()); + let names: Vec = fs::read_dir(world.join("datapacks")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names.len(), 2, "{names:?}"); + fs::remove_dir_all(world.parent().unwrap().parent().unwrap()).unwrap(); +} diff --git a/launcher/src/browser/modrinth.rs b/launcher/src/browser/modrinth.rs index fb71d0391..7e821abaf 100644 --- a/launcher/src/browser/modrinth.rs +++ b/launcher/src/browser/modrinth.rs @@ -14,14 +14,17 @@ fn project_type(kind: Kind) -> &'static str { Kind::Modpack => "modpack", Kind::Mod => "mod", Kind::Shader => "shader", + Kind::DataPack => "datapack", } } -/// The kind of a Modrinth project; its shader packs (the shaders/ format) are not offered. +/// The kind of a Modrinth project; its shader packs (the shaders/ format) are not offered. A +/// data pack says it is a `mod` (most also ship a mod build): the search for data packs marks +/// its hits, and an install into a world asks for its data pack files. fn kind_of(project_type: &str) -> Option { Kind::ALL .into_iter() - .filter(|k| *k != Kind::Shader) + .filter(|k| !matches!(k, Kind::Shader | Kind::DataPack)) .find(|k| self::project_type(*k) == project_type) } @@ -31,7 +34,9 @@ pub(super) fn facets(query: &Query) -> String { let mut all = vec![vec![format!("project_type:{}", project_type(query.kind))]]; match &f.game_version { Some(v) => all.push(vec![format!("versions:{v}")]), - None if !query.everything && matches!(query.kind, Kind::ResourcePack | Kind::Mod) => { + None if !query.everything + && matches!(query.kind, Kind::ResourcePack | Kind::Mod | Kind::DataPack) => + { all.push(vec![format!("versions:{GAME}")]) } None => {} @@ -182,6 +187,10 @@ impl Source for Modrinth { .into_iter() .flatten() .filter_map(parse_hit) + .map(|p| match query.kind { + Kind::DataPack => p.as_datapack(), + _ => p, + }) .collect()) } @@ -222,7 +231,15 @@ impl Source for Modrinth { )); } let (c, l, v) = cached.as_ref().expect("filled above"); - Ok(details::modrinth_tags(project_type(kind), c, l, v)) + // Data packs share the mods' categories; their one loader is `datapack`. + let mut tags = match kind { + Kind::DataPack => details::modrinth_tags("mod", c, l, v), + _ => details::modrinth_tags(project_type(kind), c, l, v), + }; + if kind == Kind::DataPack { + tags.loaders.clear(); + } + Ok(tags) } } diff --git a/launcher/src/browser/tests.rs b/launcher/src/browser/tests.rs index 50bfbae40..eb22be38a 100644 --- a/launcher/src/browser/tests.rs +++ b/launcher/src/browser/tests.rs @@ -72,6 +72,51 @@ fn picks_the_newest_version_that_runs() { assert!(pick(Kind::ResourcePack, &[blocked, empty], true).is_none()); } +#[test] +fn data_packs_are_their_own_kind() { + // Most data packs on Modrinth also ship a mod build; only the data pack files are picked. + let versions = [ + version("fabric", &[GAME], &["fabric", "neoforge"]), + version("pack", &[GAME], &["datapack"]), + version("old", &["1.21.4"], &["datapack"]), + ]; + assert_eq!(pick(Kind::DataPack, &versions, false).unwrap().id, "pack"); + assert!(pick(Kind::DataPack, &versions[2..], false).is_none()); + assert_eq!( + pick(Kind::DataPack, &versions[2..], true).unwrap().id, + "old" + ); + assert!(pick(Kind::DataPack, &versions[..1], true).is_none()); + + let now = support(Kind::DataPack, &v(&[GAME]), &v(&["datapack"])); + assert_eq!(now.reason(), Some(DATAPACK_SUPPORT)); + let old = support(Kind::DataPack, &v(&["1.21.4"]), &v(&["datapack"])); + assert!( + old.reason().unwrap().starts_with("Made for 1.21.4"), + "{old:?}" + ); + assert!(old.installable()); + + assert_eq!( + modrinth::facets(&Query::new("", Kind::DataPack)), + r#"[["project_type:datapack"],["versions:26.3"]]"# + ); + // A data pack's hit says `mod`: the search for data packs marks it. + let hit = serde_json::json!({ + "project_id": "bVrj3hwG", "project_type": "mod", "slug": "terralith", + "title": "Terralith", "categories": ["datapack", "fabric", "worldgen"], + "versions": [GAME], + }); + let p = modrinth::parse_hit(&hit).unwrap(); + assert_eq!(p.kind, Kind::Mod); + let p = p.as_datapack(); + assert_eq!( + (p.kind, p.page.as_str()), + (Kind::DataPack, "https://modrinth.com/datapack/terralith") + ); + assert_eq!(Kind::DataPack.folder(), None); +} + #[test] fn file_names_must_be_plain() { for good in [ diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index f05d32ad1..739db4234 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -368,9 +368,12 @@ enum ModsCmd { }, /// Install a pack and what it needs into an instance, by its id or slug (checksums /// checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported as - /// an instance of its own + /// an instance of its own; a data pack goes into the world `--world` names Install { project: String, + /// Install the project's data pack into this world of the instance (its name or folder) + #[arg(long)] + world: Option, /// The instance (default: the selected one) #[arg(long)] instance: Option, @@ -420,6 +423,8 @@ enum KindArg { Modpack, /// Horizon's own shader packs (Horizon's registry only) Shader, + /// Data packs (Modrinth): install one into a world with `mods install --world ` + Datapack, } #[derive(Clone, Copy, clap::ValueEnum)] @@ -1424,12 +1429,14 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { KindArg::Modpack => Kind::Modpack, KindArg::Mod => Kind::Mod, KindArg::Shader => Kind::Shader, + KindArg::Datapack => Kind::DataPack, }; let query = Query { everything, ..Query::new(&text.join(" "), kind) }; let found = source.get()?.search(&query)?; + let datapack = kind == Kind::DataPack; if as_json { json(found.iter().map(|p| { let support = p.support(); @@ -1441,6 +1448,9 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { }) }).collect()); } else { + if datapack && !found.is_empty() { + println!("{}\n", horizon_launcher::browser::DATAPACK_SUPPORT); + } for p in &found { let support = p.support(); if p.source == SourceId::Horizon { @@ -1465,6 +1475,8 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { ); if unchecked { println!(" horizon-launcher mods check {}", p.slug); + } else if datapack { + println!(" horizon-launcher mods install {} --world ", p.slug); } else if let Some(why) = support.reason() { println!(" {why}"); } @@ -1515,10 +1527,44 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { project, everything, source, + world, .. } => { let source = source.get()?; let p = source.project(&project)?; + if let Some(world) = world { + let world = horizon_launcher::worlds::find(&home, &world)?; + let done = installed::install_datapack( + &*source, + &p, + everything, + &world.path, + &progress(p.title.clone()), + )?; + if as_json { + json(serde_json::json!({ + "world": world.folder, "file": done.pack.file, "version": done.number, + "runs": done.coverage.read, "not_read": done.coverage.unread, + })); + } else { + println!( + "{} {} is in {}'s data packs as {}: the game turns it on when the world \ + opens. {}", + p.title, + done.number, + world.name, + done.pack.file, + done.coverage.summary() + ); + } + return Ok(()); + } + if p.kind == Kind::DataPack { + return Err(format!( + "{} is a data pack: say which world with --world.", + p.title + )); + } if p.kind == Kind::Modpack && p.source == SourceId::Horizon { let pack = horizon::pack::install(&p.id, &line)?; if as_json { diff --git a/launcher/src/datapacks.rs b/launcher/src/datapacks.rs index 1c6a2ac46..956a1dffe 100644 --- a/launcher/src/datapacks.rs +++ b/launcher/src/datapacks.rs @@ -151,6 +151,82 @@ pub fn remove(world: &Path, pack: &DataPack) -> Result<(), String> { forget(world, &pack.file) } +/// What of a data pack the game reads today (its `DataStore`): `data///`. +pub const READ: [&str; 4] = ["function", "function tag", "predicate", "item_modifier"]; + +/// A data pack's files by kind (`function`, `worldgen`, `item tag`...), with how many each. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Coverage { + /// What Horizon runs. + pub read: Vec<(String, usize)>, + /// What it doesn't read yet. + pub unread: Vec<(String, usize)>, +} + +impl Coverage { + /// "Runs its 12 functions, 1 predicate. Not read yet: 40 worldgen, 3 recipes." + pub fn summary(&self) -> String { + let runs = match self.read.is_empty() { + true => "Nothing in it runs in Horizon yet.".to_string(), + false => format!("Runs its {}.", counts(&self.read)), + }; + match self.unread.is_empty() { + true => runs, + false => format!("{runs} Not read yet: {}.", self.not_read()), + } + } + + /// "1077 worldgen, 653 loot tables, 16 recipes": what Horizon doesn't read yet, the six + /// biggest kinds and how many other kinds. + pub fn not_read(&self) -> String { + let mut biggest = self.unread.clone(); + biggest.sort_by_key(|(_, n)| std::cmp::Reverse(*n)); + let others = biggest.len().saturating_sub(6); + biggest.truncate(6); + match others { + 0 => counts(&biggest), + 1 => format!("{} and 1 other kind", counts(&biggest)), + n => format!("{} and {n} other kinds", counts(&biggest)), + } + } +} + +fn counts(list: &[(String, usize)]) -> String { + list.iter() + .map(|(k, n)| { + let k = k.replace('_', " "); + match *n == 1 || k == "worldgen" { + true => format!("{n} {k}"), + false => format!("{n} {k}s"), + } + }) + .collect::>() + .join(", ") +} + +/// Counts a data pack zip's files by kind, and splits them into what the game reads and what +/// it doesn't yet. +pub fn coverage(file: &Path) -> Result { + let zip = fs::File::open(file) + .ok() + .and_then(|f| zip::ZipArchive::new(f).ok()) + .ok_or_else(|| format!("{} is not a zip file that can be read.", file.display()))?; + let mut kinds = std::collections::BTreeMap::::new(); + for name in zip.file_names().filter(|n| !n.ends_with('/')) { + let parts: Vec<&str> = name.split('/').collect(); + let kind = match parts.as_slice() { + ["data", _, "tags", tag, _, ..] => format!("{tag} tag"), + ["data", _, kind, _, ..] => kind.to_string(), + _ => continue, + }; + *kinds.entry(kind).or_default() += 1; + } + let (read, unread) = kinds + .into_iter() + .partition(|(k, _)| READ.contains(&k.as_str())); + Ok(Coverage { read, unread }) +} + #[cfg(test)] #[path = "datapacks/tests.rs"] mod tests; diff --git a/launcher/src/datapacks/tests.rs b/launcher/src/datapacks/tests.rs index 6fa54dd38..f5695c706 100644 --- a/launcher/src/datapacks/tests.rs +++ b/launcher/src/datapacks/tests.rs @@ -101,3 +101,38 @@ fn lists_adds_and_removes_as_the_game_reads_them() { assert_eq!(find(&world, "Trades").unwrap().file, "Trades.zip"); fs::remove_dir_all(&root).unwrap(); } + +#[test] +fn coverage_says_what_runs() { + let root = scratch("coverage"); + let file = root.join("p.zip"); + zip_file( + &file, + &[ + ("pack.mcmeta", META), + ("data/a/function/x.mcfunction", ""), + ("data/a/predicate/p.json", "{}"), + ("data/a/item_modifier/m.json", "{}"), + ("data/a/tags/item/i.json", "{}"), + ("data/a/loot_table/l.json", "{}"), + ("data/a/loot_table/k.json", "{}"), + ("data/a/worldgen/biome/b.json", "{}"), + ("assets/a/lang/en_us.json", "{}"), + ], + ); + let c = coverage(&file).unwrap(); + assert_eq!( + c.summary(), + "Runs its 1 function, 1 item modifier, 1 predicate. Not read yet: 2 loot tables, 1 item \ + tag, 1 worldgen." + ); + let many = Coverage { + read: Vec::new(), + unread: (1..=8).map(|n| (format!("kind{n}"), n)).collect(), + }; + assert_eq!( + many.not_read(), + "8 kind8s, 7 kind7s, 6 kind6s, 5 kind5s, 4 kind4s, 3 kind3s and 2 other kinds" + ); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/launcher/src/datapacks_page.rs b/launcher/src/datapacks_page.rs index 85c94a167..452e2d2d5 100644 --- a/launcher/src/datapacks_page.rs +++ b/launcher/src/datapacks_page.rs @@ -16,6 +16,15 @@ pub(super) struct WorldPacks { note: Option>, } +impl WorldPacks { + /// Reads the open world's packs again, after something else changed them. + pub(super) fn reread(&mut self) { + if let Some(world) = &self.open { + self.list = datapacks::list(world); + } + } +} + impl Launcher { /// Opens or closes the packs of `world` under its row. pub(super) fn toggle_world_packs(&mut self, world: &World) { diff --git a/launcher/src/main.rs b/launcher/src/main.rs index e0636600b..7534a000d 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -66,7 +66,7 @@ impl Page { /// `settings`) opens on that page, for screenshots; Home otherwise. fn from_env() -> Page { match std::env::var("HORIZON_LAUNCHER_PAGE").as_deref() { - Ok("mods" | "modpacks" | "shaders") => Page::Mods, + Ok("mods" | "modpacks" | "shaders" | "datapacks") => Page::Mods, Ok("servers") => Page::Servers, Ok("versions") => Page::Versions, Ok("notes") => Page::Notes, diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs index 9feed87e0..5a3e88b24 100644 --- a/launcher/src/mods_page.rs +++ b/launcher/src/mods_page.rs @@ -15,11 +15,12 @@ use std::collections::HashMap; use std::path::PathBuf; /// The kinds, as the Mods page's tabs: name and icon. -const KINDS: [(PackKind, &str, &str); 4] = [ +const KINDS: [(PackKind, &str, &str); 5] = [ (PackKind::Mod, "Mods", "box"), (PackKind::Modpack, "Modpacks", "archive"), (PackKind::ResourcePack, "Resource packs", "image"), (PackKind::Shader, "Shader packs", "zap"), + (PackKind::DataPack, "Data packs", "notes"), ]; /// Java mods checked at once. const CHECKING: usize = 2; @@ -74,6 +75,9 @@ pub(super) struct Mods { loaded: bool, /// The game folder the browser installs into and lists: the selected instance's. home: Option, + /// Its worlds (folder, name), the last played first, and the one data packs go into. + worlds: Vec<(PathBuf, String)>, + world: Option, /// The project being installed, and the line and fraction of its download. pub(super) busy: Option<(String, String, f32)>, message: Option>, @@ -101,6 +105,22 @@ impl Mods { self.home.clone().unwrap_or_else(backend::game_home) } + /// Reads the instance's worlds again; the world picked for data packs stays when it is + /// still there, else the last played. + fn read_worlds(&mut self) { + self.worlds = horizon_launcher::worlds::list(&self.home()) + .into_iter() + .map(|w| (w.path, w.name)) + .collect(); + if !self + .worlds + .iter() + .any(|(p, _)| Some(p) == self.world.as_ref()) + { + self.world = self.worlds.first().map(|(p, _)| p.clone()); + } + } + /// Whether the Modpacks tab is open (the sidebar marks the pack shown there). pub(super) fn on_modpacks(&self) -> bool { self.kind == PackKind::Modpack @@ -112,6 +132,7 @@ impl Mods { let kind = match page.as_deref() { Ok("modpacks") => PackKind::Modpack, Ok("shaders") => PackKind::Shader, + Ok("datapacks") => PackKind::DataPack, _ => PackKind::Mod, }; Self { @@ -139,6 +160,8 @@ impl Mods { installed: Vec::new(), loaded: false, home: None, + worlds: Vec::new(), + world: None, busy: None, message: None, updates: HashMap::new(), @@ -245,6 +268,7 @@ impl Launcher { let mut changed = false; let mut to_check = Vec::new(); let mut loaded = Vec::new(); + let mut done = false; while let Ok(event) = self.mods.rx.try_recv() { changed = true; let m = &mut self.mods; @@ -271,6 +295,7 @@ impl Launcher { } } Event::Done(result, modpack) => { + done = true; m.busy = None; m.message = Some(result); m.installed = installed::Installed::load(&m.home()).entries; @@ -318,6 +343,10 @@ impl Launcher { } } self.mods_check(to_check); + if done { + // A data pack put into a world shows in its list on Home. + self.world_packs.reread(); + } for l in loaded { self.mods_loaded(l); } @@ -560,6 +589,10 @@ impl Launcher { .map(|tag| backend::resources(tag)); let tx = self.mods.tx.clone(); let home = self.mods.home(); + let world = self.mods.world.clone().and_then(|path| { + let (_, name) = self.mods.worlds.iter().find(|(p, _)| *p == path)?; + Some((path, name.clone())) + }); std::thread::spawn(move || { let last = std::cell::Cell::new(-1); let progress = |line: &str, f: f32| { @@ -576,6 +609,21 @@ impl Launcher { Some(p) => p, None => source.project(&id)?, }; + if p.kind == PackKind::DataPack { + let (world, name) = + world.ok_or("Pick the world the data pack goes into first.")?; + let done = + installed::install_datapack(&*source, &p, everything, &world, &|f| { + progress(&p.title, f) + })?; + return Ok(format!( + "Put {} {} in {name}'s data packs, checksum checked: the game turns \ + it on when the world opens. {}", + p.title, + done.number, + done.coverage.summary() + )); + } modpack = p.kind == PackKind::Modpack; if modpack && p.source == SourceId::Horizon { let pack = horizon::pack::install(&p.id, &progress)?; @@ -709,6 +757,7 @@ impl Launcher { self.mods.installed_list.reset(); self.mods.updates.clear(); self.mods.confirm_remove = None; + self.mods.read_worlds(); self.mods_check_updates(); self.mods_taken_down(); if !self.mods.loaded { @@ -735,6 +784,11 @@ impl Launcher { if kind == PackKind::Shader { this.mods.source = SourceId::Horizon; } + // Data packs are on Modrinth only; a world may have been made since. + if kind == PackKind::DataPack { + this.mods.source = SourceId::Modrinth; + this.mods.read_worlds(); + } // Categories and loaders differ by kind. this.mods.browse.filters = Default::default(); this.mods.browse.open = None; @@ -764,7 +818,8 @@ impl Launcher { })); // CurseForge support is coming soon: shown, inert, never searched (like the Microsoft // account's "Coming soon"). - let source_note = div().flex().child(self.mods_source_switch(cx)); + let source_note = (self.mods.kind != PackKind::DataPack) + .then(|| div().flex().child(self.mods_source_switch(cx))); // The registry lists only what was made for Horizon: no "everything", no Modrinth filters. let registry = self.mods.source == SourceId::Horizon; let filters = (!registry).then(|| self.mods_filters(cx)); @@ -781,9 +836,9 @@ impl Launcher { .child(self.mods_field(cx)) .when(!registry, |d| d.child(toggle)), ) - .child(source_note) + .children(source_note) .children(filters) - .children(self.mods_target_line()); + .children(self.mods_target_line(cx)); // The kinds are inventory tabs on the panel that holds the open one. let body = blocks::panel(&t).flex().flex_col().gap(px(24.)).p(px(20.)); let page = |body: Div| { @@ -813,8 +868,11 @@ impl Launcher { /// Which instance installs go into, when there is more than one to pick from. A modpack /// becomes an instance of its own. - fn mods_target_line(&self) -> Option
{ + fn mods_target_line(&self, cx: &mut Context) -> Option
{ let instance = self.selected_instance()?; + if self.mods.kind == PackKind::DataPack { + return Some(self.mods_world_picker(&instance.name.clone(), cx)); + } if self.instances.list.len() < 2 || self.mods.kind == PackKind::Modpack { return None; } @@ -828,6 +886,45 @@ impl Launcher { ) } + /// The world data packs go into: one of the instance's, picked here. + fn mods_world_picker(&self, instance: &str, cx: &mut Context) -> Div { + let t = self.theme; + let caption = |s: String| text(theme::CAPTION).text_color(t.muted).child(s); + if self.mods.worlds.is_empty() { + return div().child(caption(format!( + "A data pack goes into a world, and {instance} has none yet: create one in the \ + game, then come back." + ))); + } + let mut chips = div().flex().flex_wrap().items_center().gap(px(6.)); + for (i, (path, name)) in self.mods.worlds.iter().enumerate() { + let on = self.mods.world.as_ref() == Some(path); + let path = path.clone(); + chips = chips.child( + button( + SharedString::from(format!("mods-world-{i}")), + name.clone(), + if on { Kind::Secondary } else { Kind::Ghost }, + &t, + ) + .when(on, |b| b.border_color(t.accent)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods.world = Some(path.clone()); + cx.notify(); + })), + ); + } + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(caption(format!( + "Installs into a world of {instance}; the game turns the pack on when the world \ + opens." + ))) + .child(chips) + } + /// The install under way and the last install's answer. pub(super) fn mods_busy_plate(&self) -> Vec
{ let t = self.theme;