diff --git a/.github/releases/v2026.11.0.md b/.github/releases/v2026.11.0.md
new file mode 100644
index 0000000..9d77a7a
--- /dev/null
+++ b/.github/releases/v2026.11.0.md
@@ -0,0 +1,40 @@
+
Bring your instances from another launcher, take them anywhere as a modpack, and give each world the datapacks it needs.
+
+
+
+The first finished version of Cubby, after two alphas and two betas. Thank you to everyone who tried them and told me what broke. If something still does, [open an issue](https://github.com/benjaminbrtrd/Cubby/issues/new) with the crash report from the app.
+
+## ✨ What's new
+
+**Bring your instances with you.** *New instance, then Import* finds the instances of MultiMC, PolyMC, CurseForge, ATLauncher, GDLauncher, the Modrinth App and the Minecraft Launcher on your PC. Pick the ones you want: Cubby copies their mods, worlds, screenshots and settings, and leaves the other launcher as it was.
+
+**Export a modpack.** *Export as a modpack file* saves any instance as a Modrinth `.mrpack` or a CurseForge `.zip`, ready to share or to open in another launcher.
+
+**Memory that fits.** With *Set memory automatically*, on by default, each instance gets the memory its mods need: 2 GB for Vanilla, up to 8 GB for big modpacks, and never more than half of your computer's. An instance with its own value keeps it.
+
+**Datapacks for each world.** In the Worlds tab, turn a world's datapacks on and off, or add them from a file. *Discover > Datapacks* searches Modrinth and installs into the world you pick.
+
+**Update mods without fear.** Read each mod's changelog before *Update all*. Cubby keeps the old files, so *Undo last update* puts them back if something breaks.
+
+**Copy settings from another instance.** Key bindings, game options or the server list, in one go, with *Copy from another instance*.
+
+**Desktop shortcuts.** Put an instance on your desktop and double-click it to play, even when Cubby isn't open.
+
+**A map of your world.** See the land around the spawn from above, from the world's panel. It works with Minecraft 26.1 worlds too.
+
+**Server messages like in the game.** The message of the day shows the game's colours and styles, and the server list lines up status, players and ping in neat columns.
+
+**Tidier side panels.** Every side panel now follows the same order: what it is, what state it's in, the main action, then the rest, with deleting at the bottom.
+
+**Cubby remembers its window.** It opens where you left it, at the size you left it.
+
+## 🐛 Fixes
+
+- World icons and screenshots show up on macOS.
+- When Fabric refuses two mods that don't work together, like Sodium and Iris, the crash screen names both.
+- Buttons no longer stick out of the side panels, and the big map fits its window.
+
+## ⚠️ Good to know
+
+- **Coming from a beta?** Cubby updates itself. You stay on the preview channel and will get the next test builds too: switch Settings > Updates > *Version channel* to *Stable* if you only want finished versions.
+- Back up the worlds you care about before you import, export or update a lot at once.
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 08011f4..8bb4ad7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -106,6 +106,7 @@ jobs:
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
# Optional: without them, CurseForge search is off and only the demo can be played.
CUBBY_CURSEFORGE_API_KEY: ${{ secrets.CUBBY_CURSEFORGE_API_KEY }}
+ CUBBY_DISCORD_CLIENT_ID: ${{ vars.CUBBY_DISCORD_CLIENT_ID }}
CUBBY_MSA_CLIENT_ID: ${{ vars.CUBBY_MSA_CLIENT_ID }}
with:
tauriScript: npm run tauri
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 24f7243..735e9f0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -20,7 +20,7 @@ Open an issue with:
cargo fmt --all
cargo clippy --workspace --all-targets
cargo test --workspace
- cd ui && npm run check
+ cd ui && npm run check && npm test
```
## Code
@@ -39,6 +39,12 @@ The interface is in English for now. Write it the way the app already speaks:
- An error says what happened and what to do about it.
- Use the game's words: *instance*, *loader*, *mods*, *resource packs*, *shader packs*, *worlds*.
+## Releasing
+
+1. Set the version in `Cargo.toml`, `src-tauri/tauri.conf.json` and `ui/package.json`.
+2. Write the notes in `.github/releases/v.md`, with a screenshot of what's new.
+3. Push a tag such as `v2026.11.0`. GitHub Actions builds a draft release.
+
## License
By contributing, you agree that your work is released under the [GPL-3.0](LICENSE), like the rest of Cubby.
diff --git a/Cargo.lock b/Cargo.lock
index 2648e6e..eae13a7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -734,13 +734,14 @@ checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
[[package]]
name = "cubby"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"chrono",
"cubby-atlauncher",
"cubby-auth",
"cubby-common",
"cubby-curseforge",
+ "cubby-discord",
"cubby-ftb",
"cubby-instance",
"cubby-java",
@@ -766,6 +767,7 @@ dependencies = [
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
+ "tauri-plugin-window-state",
"tempfile",
"tokio",
"tracing",
@@ -774,7 +776,7 @@ dependencies = [
[[package]]
name = "cubby-atlauncher"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"cubby-common",
"futures",
@@ -790,7 +792,7 @@ dependencies = [
[[package]]
name = "cubby-auth"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -805,7 +807,7 @@ dependencies = [
[[package]]
name = "cubby-common"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -817,11 +819,12 @@ dependencies = [
"thiserror 2.0.21",
"tokio",
"tracing",
+ "zip 2.6.1",
]
[[package]]
name = "cubby-curseforge"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"cubby-common",
"reqwest 0.12.28",
@@ -832,9 +835,18 @@ dependencies = [
"zip 2.6.1",
]
+[[package]]
+name = "cubby-discord"
+version = "2026.11.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "tracing",
+]
+
[[package]]
name = "cubby-ftb"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"chrono",
"cubby-common",
@@ -848,11 +860,12 @@ dependencies = [
[[package]]
name = "cubby-instance"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"chrono",
"cubby-common",
"flate2",
+ "png",
"serde",
"serde_json",
"tokio",
@@ -863,7 +876,7 @@ dependencies = [
[[package]]
name = "cubby-java"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"cubby-common",
"futures",
@@ -876,7 +889,7 @@ dependencies = [
[[package]]
name = "cubby-launch"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"chrono",
"cubby-common",
@@ -890,7 +903,7 @@ dependencies = [
[[package]]
name = "cubby-meta"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"cubby-common",
"cubby-launch",
@@ -903,7 +916,7 @@ dependencies = [
[[package]]
name = "cubby-modrinth"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"chrono",
"cubby-common",
@@ -918,7 +931,7 @@ dependencies = [
[[package]]
name = "cubby-packinstall"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"cubby-common",
"cubby-ftb",
@@ -936,7 +949,7 @@ dependencies = [
[[package]]
name = "cubby-technic"
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
dependencies = [
"cubby-common",
"reqwest 0.12.28",
@@ -4621,6 +4634,21 @@ dependencies = [
"zip 9.3.0",
]
+[[package]]
+name = "tauri-plugin-window-state"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d6815cab7b212f9cfe16a9d79d8d22f9e14159e4a9460f7dec1467167a008e3"
+dependencies = [
+ "bitflags 2.13.2",
+ "log",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "tauri-runtime"
version = "2.12.2"
diff --git a/Cargo.toml b/Cargo.toml
index 6670a97..40163be 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*", "src-tauri"]
[workspace.package]
-version = "2026.11.0-beta.2"
+version = "2026.11.0"
edition = "2021"
license = "GPL-3.0-only"
repository = "https://github.com/benjaminbrtrd/Cubby"
@@ -21,6 +21,7 @@ cubby-ftb = { path = "crates/cubby-ftb" }
cubby-technic = { path = "crates/cubby-technic" }
cubby-atlauncher = { path = "crates/cubby-atlauncher" }
cubby-curseforge = { path = "crates/cubby-curseforge" }
+cubby-discord = { path = "crates/cubby-discord" }
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "gzip", "multipart"] }
serde = { version = "1", features = ["derive"] }
diff --git a/README.md b/README.md
index 4881cba..e13e72f 100644
--- a/README.md
+++ b/README.md
@@ -1,64 +1,68 @@
-
+
+
+
+
-
Cubby
+
A lightweight Minecraft launcher for Windows, macOS and Linux.
-
The lightweight Minecraft launcher.
-
-
-
-Cubby keeps each of your worlds in its own instance, with its own version, loader, mods and settings. You pick one and press Play: Cubby downloads the game, the loader and the right Java, then gets out of the way.
-
-It's a native app built with Rust and Tauri, so there's no bundled browser and no Java just to open the launcher. The installer is about 11 MB.
-
-## What it does
-
-- **Instances.** Any release, snapshot or old version, with Fabric, Quilt, Forge or NeoForge. Give each one an emblem and a colour so you can spot it at a glance.
-- **Mods, resource packs and shaders** from Modrinth and CurseForge, searched from inside the launcher. Cubby only shows what works with the instance you're installing into, adds the dependencies, and finds updates for what you already have.
-- **Modpacks** from Modrinth, CurseForge, FTB, ATLauncher and Technic, or from a `.mrpack` or `.zip` you downloaded.
-- **Crash diagnosis.** When the game crashes, Cubby reads the log, tells you what most likely went wrong and offers a fix, like turning off a mod made for another version of the game.
-- **While you play:** the live game log, your screenshots as you take them, and the status of the server you joined.
-- **Also:** world backups, import from Prism Launcher, several accounts, and night, day and high-contrast themes.
-
-| Find mods | Mod pages | When it crashes |
-| --- | --- | --- |
-|  |  |  |
-
-## Download
+
-Cubby runs on Windows 10 and 11, on macOS 11 or later (Apple Silicon and Intel) and on 64-bit Linux. Get it from the [releases page](https://github.com/benjaminbrtrd/Cubby/releases).
+
+
+
+
+
+
-The full game needs a signed-in Microsoft account that owns Minecraft: Java Edition. Without one, Cubby only starts the Minecraft demo.
+
-## Versions
+## Features
-Cubby uses calendar versions: `2026.11.0` is the first release of November 2026, `2026.11.1` the next one that month. Test builds add `-alpha.N` or `-beta.N`. The full year keeps them apart from Minecraft's own version numbers.
+- Instances for any Minecraft version, with Fabric, Quilt, Forge or NeoForge
+- Mods, shader packs, resource packs and datapacks from Modrinth and CurseForge
+- Modpacks from Modrinth, CurseForge, FTB, ATLauncher and Technic
+- Mod updates with changelogs, and undo
+- World backups and maps
+- Import from Prism Launcher, MultiMC, CurseForge, ATLauncher, GDLauncher, the Modrinth App and the Minecraft Launcher
+- Export to `.mrpack` or CurseForge `.zip`
+- Native app built with Rust and Tauri
-To publish a release, push a tag such as `v2026.11.0`: GitHub Actions builds the installer and attaches it to a draft release.
+
+
+
+
+
+
-## Building from source
+## Building
-You need [Rust](https://rustup.rs) 1.90 or newer and [Node.js](https://nodejs.org) 20 or newer. On Windows, the WebView2 runtime (already there on Windows 11). On Linux, WebKitGTK 4.1 and its development files (`libwebkit2gtk-4.1-dev` on Debian and Ubuntu).
+Requires [Rust](https://rustup.rs) 1.90+ and [Node.js](https://nodejs.org) 20+. On Linux, `libwebkit2gtk-4.1-dev`.
```sh
git clone https://github.com/benjaminbrtrd/Cubby cubby
-cd cubby/ui
-npm install
-cd ..
+cd cubby/ui && npm install && cd ..
npm run tauri dev
```
-`npm run tauri build` makes the installer in `target/release/bundle/`.
+`npm run dev` in `ui/` runs the interface in a browser with sample data.
-Two values can be set at build time:
+
+Build-time variables
-- `CUBBY_CURSEFORGE_API_KEY`: a [CurseForge API key](https://console.curseforge.com). Without it, CurseForge search is turned off, and everything else works.
-- `CUBBY_MSA_CLIENT_ID`: optional. Cubby already has its own Azure application id, approved by Mojang; set this only to sign in through another one.
+- `CUBBY_CURSEFORGE_API_KEY`: [CurseForge API key](https://console.curseforge.com). Without it, CurseForge is turned off.
+- `CUBBY_DISCORD_CLIENT_ID`: optional, for Discord Rich Presence.
+- `CUBBY_MSA_CLIENT_ID`: optional, to sign in through another Azure application.
-The interface also runs in a plain browser with sample data, which is handy for working on screens: `npm run dev` in `ui/`.
+
-## How the code is laid out
+
+Code layout
```
crates/
@@ -66,26 +70,25 @@ crates/
cubby-meta Mojang versions, Fabric, Quilt, Forge and NeoForge installs
cubby-java finding, picking and downloading Java
cubby-auth Microsoft sign-in
- cubby-instance instances, their content, backups, settings
+ cubby-instance instances, their content, worlds, backups, settings
cubby-launch building the command line and running the game
- cubby-modrinth Modrinth search, installs and updates
+ cubby-modrinth Modrinth
cubby-curseforge CurseForge
cubby-ftb Feed The Beast
cubby-atlauncher ATLauncher
cubby-technic Technic
cubby-packinstall installing a modpack plan
-src-tauri/ the desktop app: window, commands, events
+ cubby-discord Discord Rich Presence
+src-tauri/ the desktop app
ui/ the interface, in Svelte
```
-Each crate builds and tests on its own. `cargo test --workspace` runs the offline tests; the ones that call real services are marked `#[ignore]` and run with `cargo test -- --ignored`.
-
-## Contributing
+
-Bug reports and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
+See [CONTRIBUTING.md](CONTRIBUTING.md) to contribute.
## License
-Cubby is free software under the [GNU General Public License v3.0](LICENSE).
+[GPL-3.0](LICENSE). Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.
-**Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.** Made by Benjamin · contact@cubbylauncher.com
+Made by Benjamin · contact@cubbylauncher.com
diff --git a/crates/cubby-common/Cargo.toml b/crates/cubby-common/Cargo.toml
index 54ee291..189d0f1 100644
--- a/crates/cubby-common/Cargo.toml
+++ b/crates/cubby-common/Cargo.toml
@@ -17,3 +17,4 @@ sha1.workspace = true
hex.workspace = true
dirs.workspace = true
tracing.workspace = true
+zip.workspace = true
diff --git a/crates/cubby-common/src/export.rs b/crates/cubby-common/src/export.rs
new file mode 100644
index 0000000..b03e734
--- /dev/null
+++ b/crates/cubby-common/src/export.rs
@@ -0,0 +1,154 @@
+//! Shared by the modpack exports (`.mrpack`, CurseForge `.zip`): what of the game directory can go into a
+//! pack, and writing the archive.
+
+use std::fs;
+use std::io::Write;
+use std::path::{Component, Path, PathBuf};
+
+use serde::Serialize;
+use zip::write::SimpleFileOptions;
+
+use crate::{Error, Result};
+
+/// Folders the export handles on its own (content files) or that never belong in a pack.
+const NEVER: [&str; 14] = [
+ "mods", "resourcepacks", "shaderpacks", "logs", "crash-reports", "screenshots", ".trash", "natives", ".fabric", ".mixin.out",
+ "downloads", "cache", ".cache", "debug",
+];
+/// Ticked by default: what modpack authors usually ship.
+const SUGGESTED: [&str; 6] = ["config", "defaultconfigs", "kubejs", "scripts", "options.txt", "global_packs"];
+
+/// A top-level entry of the game directory that can go into the pack's overrides.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExportCandidate {
+ pub name: String,
+ pub is_dir: bool,
+ pub size: u64,
+ /// Usually shipped with a pack (config, options.txt...).
+ pub suggested: bool,
+}
+
+fn tree_size(path: &Path) -> u64 {
+ let Ok(meta) = fs::symlink_metadata(path) else { return 0 };
+ if meta.is_file() {
+ return meta.len();
+ }
+ if !meta.is_dir() {
+ return 0;
+ }
+ fs::read_dir(path).map(|rd| rd.flatten().map(|e| tree_size(&e.path())).sum()).unwrap_or(0)
+}
+
+/// Top-level files and folders of the game directory that an export can include, sorted by name.
+pub fn export_candidates(game_dir: &Path) -> Vec {
+ let Ok(rd) = fs::read_dir(game_dir) else { return Vec::new() };
+ let mut out: Vec = rd
+ .flatten()
+ .filter_map(|e| {
+ let name = e.file_name().to_string_lossy().into_owned();
+ let ty = e.file_type().ok()?;
+ if NEVER.contains(&name.as_str()) || ty.is_symlink() || name.starts_with('.') && name != ".minecraft" {
+ return None;
+ }
+ Some(ExportCandidate { suggested: SUGGESTED.contains(&name.as_str()), size: tree_size(&e.path()), is_dir: ty.is_dir(), name })
+ })
+ .collect();
+ out.sort_by_key(|c| c.name.to_lowercase());
+ out
+}
+
+/// Every file under the chosen top-level entries, as (`/`-separated path relative to the game directory,
+/// absolute path). Symbolic links are skipped. An entry that isn't a plain name is an error.
+pub fn collect_files(game_dir: &Path, include: &[String]) -> Result> {
+ let mut out = Vec::new();
+ for name in include {
+ let plain = !name.is_empty() && Path::new(name).components().all(|c| matches!(c, Component::Normal(_))) && !name.contains(['/', '\\']);
+ if !plain || NEVER.contains(&name.as_str()) {
+ return Err(Error::Other(format!("\"{name}\" can't go into a pack.")));
+ }
+ let mut stack = vec![(name.clone(), game_dir.join(name))];
+ while let Some((rel, path)) = stack.pop() {
+ let Ok(meta) = fs::symlink_metadata(&path) else { continue };
+ if meta.is_file() {
+ out.push((rel, path));
+ } else if meta.is_dir() {
+ for entry in fs::read_dir(&path).map_err(|e| Error::io(&path, e))?.flatten() {
+ stack.push((format!("{rel}/{}", entry.file_name().to_string_lossy()), entry.path()));
+ }
+ }
+ }
+ }
+ out.sort();
+ Ok(out)
+}
+
+/// Writes a pack: `index_name` (the manifest) at the root, then each file under `prefix` (`overrides/`).
+/// The archive is written next to `dest` and renamed at the end, so a failed export leaves nothing behind.
+pub fn write_pack(dest: &Path, index_name: &str, index: &[u8], prefix: &str, files: &[(String, PathBuf)]) -> Result<()> {
+ let tmp = dest.with_extension("part");
+ let result = (|| {
+ let file = fs::File::create(&tmp).map_err(|e| Error::io(&tmp, e))?;
+ let mut zip = zip::ZipWriter::new(file);
+ let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
+ let zip_err = |e: zip::result::ZipError| Error::Other(format!("Couldn't write {} ({e}).", dest.display()));
+ zip.start_file(index_name, options).map_err(zip_err)?;
+ zip.write_all(index).map_err(|e| Error::io(&tmp, e))?;
+ for (rel, src) in files {
+ zip.start_file(format!("{prefix}{rel}"), options).map_err(zip_err)?;
+ let mut input = fs::File::open(src).map_err(|e| Error::io(src, e))?;
+ std::io::copy(&mut input, &mut zip).map_err(|e| Error::io(src, e))?;
+ }
+ zip.finish().map_err(zip_err)?;
+ Ok(())
+ })();
+ if let Err(e) = result {
+ let _ = fs::remove_file(&tmp);
+ return Err(e);
+ }
+ let _ = fs::remove_file(dest);
+ fs::rename(&tmp, dest).map_err(|e| Error::io(dest, e))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Read;
+
+ fn temp(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("cubby-export-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn candidates_collect_and_write() {
+ let game = temp("game");
+ for dir in ["config/sub", "mods", "saves/World", "logs"] {
+ fs::create_dir_all(game.join(dir)).unwrap();
+ }
+ fs::write(game.join("config/a.toml"), "a").unwrap();
+ fs::write(game.join("config/sub/b.json"), "bb").unwrap();
+ fs::write(game.join("options.txt"), "fov:1").unwrap();
+ fs::write(game.join("saves/World/level.dat"), "x").unwrap();
+
+ let names: Vec<_> = export_candidates(&game).into_iter().map(|c| (c.name, c.suggested)).collect();
+ assert_eq!(names, [("config".to_string(), true), ("options.txt".to_string(), true), ("saves".to_string(), false)]);
+
+ let files = collect_files(&game, &["config".into(), "options.txt".into()]).unwrap();
+ let rels: Vec<_> = files.iter().map(|(r, _)| r.as_str()).collect();
+ assert_eq!(rels, ["config/a.toml", "config/sub/b.json", "options.txt"]);
+ assert!(collect_files(&game, &["../x".into()]).is_err());
+ assert!(collect_files(&game, &["mods".into()]).is_err());
+
+ let dest = game.join("pack.mrpack");
+ write_pack(&dest, "modrinth.index.json", b"{}", "overrides/", &files).unwrap();
+ let mut zip = zip::ZipArchive::new(fs::File::open(&dest).unwrap()).unwrap();
+ let mut text = String::new();
+ zip.by_name("overrides/config/sub/b.json").unwrap().read_to_string(&mut text).unwrap();
+ assert_eq!(text, "bb");
+ assert!(zip.by_name("modrinth.index.json").is_ok());
+ assert!(!dest.with_extension("part").exists());
+ }
+}
diff --git a/crates/cubby-common/src/lib.rs b/crates/cubby-common/src/lib.rs
index c783fdc..730cf37 100644
--- a/crates/cubby-common/src/lib.rs
+++ b/crates/cubby-common/src/lib.rs
@@ -3,6 +3,7 @@
pub mod contracts;
pub mod error;
pub mod events;
+pub mod export;
pub mod net;
pub mod packs;
pub mod paths;
diff --git a/crates/cubby-curseforge/src/export.rs b/crates/cubby-curseforge/src/export.rs
new file mode 100644
index 0000000..1e6073a
--- /dev/null
+++ b/crates/cubby-curseforge/src/export.rs
@@ -0,0 +1,244 @@
+//! Exporting an instance as a CurseForge modpack `.zip`: `manifest.json` lists the files CurseForge knows
+//! (found by fingerprint), everything else goes into `overrides/`.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use cubby_common::export::{collect_files, write_pack};
+use cubby_common::{Error, Result};
+use serde::{Deserialize, Serialize};
+
+use crate::client::CurseForgeClient;
+
+const CONTENT_FOLDERS: [&str; 3] = ["mods", "resourcepacks", "shaderpacks"];
+
+/// CurseForge's file fingerprint: MurmurHash2 (seed 1) of the file without its whitespace bytes.
+pub fn fingerprint(bytes: &[u8]) -> u32 {
+ const M: u32 = 0x5bd1_e995;
+ let data: Vec = bytes.iter().copied().filter(|b| !matches!(b, 9 | 10 | 13 | 32)).collect();
+ let mut h: u32 = 1 ^ data.len() as u32;
+ let (chunks, rest) = data.as_chunks::<4>();
+ for chunk in chunks {
+ let mut k = u32::from_le_bytes(*chunk);
+ k = k.wrapping_mul(M);
+ k ^= k >> 24;
+ k = k.wrapping_mul(M);
+ h = h.wrapping_mul(M) ^ k;
+ }
+ if !rest.is_empty() {
+ for (i, b) in rest.iter().enumerate() {
+ h ^= (*b as u32) << (8 * i);
+ }
+ h = h.wrapping_mul(M);
+ }
+ h ^= h >> 13;
+ h = h.wrapping_mul(M);
+ h ^ (h >> 15)
+}
+
+/// What goes into the pack besides the content files.
+#[derive(Debug, Clone)]
+pub struct CfExportSpec {
+ pub name: String,
+ pub version: String,
+ pub author: String,
+ pub minecraft: String,
+ /// "fabric-0.16.5", "forge-47.2.0", "neoforge-21.1.5", "quilt-0.27.1"; `None` for Vanilla.
+ pub loader_id: Option,
+ /// Top-level entries of the game directory to copy into `overrides/`.
+ pub include: Vec,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Manifest<'a> {
+ minecraft: MinecraftOut<'a>,
+ manifest_type: &'static str,
+ manifest_version: u32,
+ name: &'a str,
+ version: &'a str,
+ author: &'a str,
+ files: Vec,
+ overrides: &'static str,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MinecraftOut<'a> {
+ version: &'a str,
+ mod_loaders: Vec>,
+}
+
+#[derive(Serialize)]
+struct LoaderOut<'a> {
+ id: &'a str,
+ primary: bool,
+}
+
+#[derive(Serialize)]
+struct FileOut {
+ #[serde(rename = "projectID")]
+ project_id: u64,
+ #[serde(rename = "fileID")]
+ file_id: u64,
+ required: bool,
+}
+
+#[derive(Deserialize)]
+struct MatchResponse {
+ data: MatchData,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct MatchData {
+ #[serde(default)]
+ exact_matches: Vec,
+}
+
+#[derive(Deserialize)]
+struct Match {
+ file: MatchFile,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct MatchFile {
+ id: u64,
+ mod_id: u64,
+ file_fingerprint: u32,
+}
+
+/// Content files of a game directory that the game loads (turned-off mods are left out), as
+/// (`/`-separated path, absolute path).
+fn content_files(game_dir: &Path) -> Vec<(String, PathBuf)> {
+ let mut out = Vec::new();
+ for folder in CONTENT_FOLDERS {
+ let Ok(rd) = std::fs::read_dir(game_dir.join(folder)) else { continue };
+ for entry in rd.flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ let lower = name.to_lowercase();
+ if !entry.path().is_file() || name.starts_with('.') || lower.ends_with(".disabled") || !(lower.ends_with(".jar") || lower.ends_with(".zip")) {
+ continue;
+ }
+ out.push((format!("{folder}/{name}"), entry.path()));
+ }
+ }
+ out.sort();
+ out
+}
+
+impl CurseForgeClient {
+ /// Project and file ids of the fingerprints CurseForge knows exactly.
+ pub async fn match_fingerprints(&self, fingerprints: &[u32]) -> Result> {
+ #[derive(Serialize)]
+ struct Body<'a> {
+ fingerprints: &'a [u32],
+ }
+ let mut out = HashMap::new();
+ for chunk in fingerprints.chunks(500) {
+ let response: MatchResponse = self.post("/v1/fingerprints/432", &Body { fingerprints: chunk }, "CurseForge fingerprints").await?;
+ out.extend(response.data.exact_matches.into_iter().map(|m| (m.file.file_fingerprint, (m.file.mod_id, m.file.id))));
+ }
+ Ok(out)
+ }
+}
+
+/// Writes the instance whose game directory is `game_dir` to `dest` as a CurseForge `.zip`. With a client,
+/// files CurseForge knows are listed in the manifest; without one (no API key) every file goes into the zip.
+/// Returns (files listed, files stored).
+pub async fn export_curseforge(client: Option<&CurseForgeClient>, game_dir: &Path, dest: &Path, spec: &CfExportSpec) -> Result<(usize, usize)> {
+ if spec.name.trim().is_empty() {
+ return Err(Error::Other("Give the pack a name.".into()));
+ }
+ let dir = game_dir.to_path_buf();
+ let include = spec.include.clone();
+ let (content, extra) = tokio::task::spawn_blocking(move || -> Result<_> {
+ let mut content = Vec::new();
+ for (rel, path) in content_files(&dir) {
+ let bytes = std::fs::read(&path).map_err(|e| Error::io(&path, e))?;
+ content.push((rel, path, fingerprint(&bytes)));
+ }
+ Ok((content, collect_files(&dir, &include)?))
+ })
+ .await
+ .map_err(|e| Error::Other(format!("The export stopped unexpectedly ({e}).")))??;
+
+ let matches = match client {
+ Some(client) if !content.is_empty() => client.match_fingerprints(&content.iter().map(|(_, _, f)| *f).collect::>()).await?,
+ _ => HashMap::new(),
+ };
+ let mut files = Vec::new();
+ let mut overrides = Vec::new();
+ for (rel, path, fp) in content {
+ match matches.get(&fp) {
+ Some(&(project_id, file_id)) => files.push(FileOut { project_id, file_id, required: true }),
+ None => overrides.push((rel, path)),
+ }
+ }
+ overrides.extend(extra);
+ let listed = files.len();
+ let stored = overrides.len();
+ let manifest = Manifest {
+ minecraft: MinecraftOut {
+ version: &spec.minecraft,
+ mod_loaders: spec.loader_id.as_deref().map(|id| LoaderOut { id, primary: true }).into_iter().collect(),
+ },
+ manifest_type: "minecraftModpack",
+ manifest_version: 1,
+ name: spec.name.trim(),
+ version: spec.version.trim(),
+ author: spec.author.trim(),
+ files,
+ overrides: "overrides",
+ };
+ let json = serde_json::to_vec_pretty(&manifest).map_err(|e| Error::Other(e.to_string()))?;
+ let dest = dest.to_path_buf();
+ tokio::task::spawn_blocking(move || write_pack(&dest, "manifest.json", &json, "overrides/", &overrides))
+ .await
+ .map_err(|e| Error::Other(format!("The export stopped unexpectedly ({e}).")))??;
+ Ok((listed, stored))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn fingerprint_skips_whitespace() {
+ assert_eq!(fingerprint(b"a b\tc\r\n"), fingerprint(b"abc"));
+ assert_ne!(fingerprint(b"abc"), fingerprint(b"abd"));
+ // Known value: the empty input hashes to the seed mixed alone.
+ assert_eq!(fingerprint(b""), {
+ let m: u32 = 0x5bd1_e995;
+ let mut h: u32 = 1;
+ h ^= h >> 13;
+ h = h.wrapping_mul(m);
+ h ^ (h >> 15)
+ });
+ }
+
+ #[tokio::test]
+ async fn export_without_key_stores_everything() {
+ let dir = std::env::temp_dir().join(format!("cubby-cf-export-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("mods")).unwrap();
+ std::fs::create_dir_all(dir.join("config")).unwrap();
+ std::fs::write(dir.join("mods/a.jar"), "jar").unwrap();
+ std::fs::write(dir.join("mods/b.jar.disabled"), "off").unwrap();
+ std::fs::write(dir.join("config/a.toml"), "x").unwrap();
+ let spec = CfExportSpec {
+ name: "Pack".into(),
+ version: "1.0".into(),
+ author: "Me".into(),
+ minecraft: "1.20.1".into(),
+ loader_id: Some("forge-47.2.0".into()),
+ include: vec!["config".into()],
+ };
+ let dest = dir.join("pack.zip");
+ assert_eq!(export_curseforge(None, &dir, &dest, &spec).await.unwrap(), (0, 2));
+ let manifest = crate::read_manifest(&dest).unwrap();
+ assert_eq!(manifest.minecraft.version, "1.20.1");
+ assert_eq!(manifest.minecraft.mod_loaders[0].id, "forge-47.2.0");
+ }
+}
diff --git a/crates/cubby-curseforge/src/lib.rs b/crates/cubby-curseforge/src/lib.rs
index a6fe5b2..6521035 100644
--- a/crates/cubby-curseforge/src/lib.rs
+++ b/crates/cubby-curseforge/src/lib.rs
@@ -5,9 +5,11 @@
mod api;
mod browse;
mod client;
+mod export;
mod manifest;
mod plan;
pub use browse::{CfLinks, CfProject, CfScreenshot, ResourceCategory, ResourceKind, ResourceQuery};
pub use client::{api_key_from_env, api_key_with_source, ApiKeySource, CurseForgeClient, API_BASE, GAME_ID, MODPACK_CLASS_ID, MOD_CLASS_ID, RESOURCE_PACK_CLASS_ID, SHADER_CLASS_ID};
+pub use export::{export_curseforge, fingerprint, CfExportSpec};
pub use manifest::{parse_manifest, read_manifest, CfManifest, CfManifestFile, CfMinecraft, CfModLoader};
diff --git a/crates/cubby-discord/Cargo.toml b/crates/cubby-discord/Cargo.toml
new file mode 100644
index 0000000..cad0747
--- /dev/null
+++ b/crates/cubby-discord/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "cubby-discord"
+description = "Discord Rich Presence: what the player is playing, on their Discord profile"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+repository.workspace = true
+
+[dependencies]
+serde.workspace = true
+serde_json.workspace = true
+tracing.workspace = true
diff --git a/crates/cubby-discord/src/lib.rs b/crates/cubby-discord/src/lib.rs
new file mode 100644
index 0000000..316d980
--- /dev/null
+++ b/crates/cubby-discord/src/lib.rs
@@ -0,0 +1,265 @@
+//! Discord Rich Presence: shows "Playing Minecraft · " on the player's Discord profile.
+//!
+//! Talks to the Discord app running on the same computer through its local IPC socket (a named pipe on
+//! Windows), like the official SDK: a handshake with the application id, then `SET_ACTIVITY`. Nothing goes
+//! over the network from Cubby. When Discord isn't running, updates are dropped and retried on the next one.
+//!
+//! The application id comes from a Discord application whose Rich Presence art has an asset named `cubby`.
+
+use std::io::{Read, Write};
+use std::sync::mpsc::{self, Receiver, Sender};
+
+use serde_json::{json, Value};
+
+const OP_HANDSHAKE: u32 = 0;
+const OP_FRAME: u32 = 1;
+const OP_CLOSE: u32 = 2;
+const MAX_FRAME: usize = 64 * 1024;
+
+/// What the player is doing.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Activity {
+ /// First line: "Playing All the Mods 9".
+ pub details: String,
+ /// Second line: "Minecraft 1.20.1 · Forge".
+ pub state: String,
+ /// Unix time the game started, in seconds: Discord shows the elapsed time.
+ pub started: i64,
+}
+
+/// The JSON of a `SET_ACTIVITY` command. `None` clears the activity.
+pub fn set_activity_payload(pid: u32, activity: Option<&Activity>, nonce: u64) -> Value {
+ let activity = activity.map(|a| {
+ json!({
+ "details": clip(&a.details),
+ "state": clip(&a.state),
+ "timestamps": { "start": a.started },
+ "assets": { "large_image": "cubby", "large_text": "Cubby" },
+ })
+ });
+ json!({ "cmd": "SET_ACTIVITY", "args": { "pid": pid, "activity": activity }, "nonce": nonce.to_string() })
+}
+
+/// Discord refuses texts longer than 128 characters (and shorter than 2).
+fn clip(text: &str) -> String {
+ let mut out: String = text.chars().take(128).collect();
+ while out.chars().count() < 2 {
+ out.push(' ');
+ }
+ out
+}
+
+/// A frame: operation code and length (little endian), then the JSON.
+pub fn encode_frame(op: u32, payload: &Value) -> Vec {
+ let body = payload.to_string();
+ let mut out = Vec::with_capacity(8 + body.len());
+ out.extend(op.to_le_bytes());
+ out.extend((body.len() as u32).to_le_bytes());
+ out.extend(body.as_bytes());
+ out
+}
+
+trait Pipe: Read + Write + Send {}
+impl Pipe for T {}
+
+#[cfg(unix)]
+fn connect() -> Option> {
+ use std::os::unix::net::UnixStream;
+ use std::time::Duration;
+ let mut bases: Vec = ["XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"].iter().filter_map(std::env::var_os).map(Into::into).collect();
+ bases.push("/tmp".into());
+ // Flatpak and Snap builds of Discord put the socket in their own folder.
+ let subs = ["", "app/com.discordapp.Discord", "app/com.discordapp.DiscordCanary", "snap.discord", ".flatpak/com.discordapp.Discord/xdg-run"];
+ for base in &bases {
+ for sub in subs {
+ for n in 0..10 {
+ let path = base.join(sub).join(format!("discord-ipc-{n}"));
+ if let Ok(stream) = UnixStream::connect(&path) {
+ let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
+ let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
+ return Some(Box::new(stream));
+ }
+ }
+ }
+ }
+ None
+}
+
+#[cfg(windows)]
+fn connect() -> Option> {
+ for n in 0..10 {
+ let path = format!(r"\\.\pipe\discord-ipc-{n}");
+ if let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&path) {
+ return Some(Box::new(file));
+ }
+ }
+ None
+}
+
+#[cfg(not(any(unix, windows)))]
+fn connect() -> Option> {
+ None
+}
+
+fn read_frame(pipe: &mut dyn Pipe) -> std::io::Result<(u32, Value)> {
+ let mut head = [0u8; 8];
+ pipe.read_exact(&mut head)?;
+ let op = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
+ let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
+ if len > MAX_FRAME {
+ return Err(std::io::Error::other("Discord sent a frame that is too big"));
+ }
+ let mut body = vec![0u8; len];
+ pipe.read_exact(&mut body)?;
+ Ok((op, serde_json::from_slice(&body).unwrap_or(Value::Null)))
+}
+
+struct Connection {
+ pipe: Box,
+}
+
+impl Connection {
+ fn open(client_id: &str) -> Option {
+ let mut pipe = connect()?;
+ pipe.write_all(&encode_frame(OP_HANDSHAKE, &json!({ "v": 1, "client_id": client_id }))).ok()?;
+ match read_frame(pipe.as_mut()) {
+ Ok((OP_FRAME, v)) if v.get("evt").and_then(Value::as_str) == Some("READY") => Some(Self { pipe }),
+ Ok((op, v)) => {
+ tracing::debug!("Discord refused the handshake (op {op}): {v}");
+ None
+ }
+ Err(e) => {
+ tracing::debug!("no answer from Discord: {e}");
+ None
+ }
+ }
+ }
+
+ fn send(&mut self, payload: &Value) -> std::io::Result<()> {
+ self.pipe.write_all(&encode_frame(OP_FRAME, payload))?;
+ let (op, answer) = read_frame(self.pipe.as_mut())?;
+ if op == OP_CLOSE {
+ return Err(std::io::Error::other("Discord closed the connection"));
+ }
+ if answer.get("evt").and_then(Value::as_str) == Some("ERROR") {
+ tracing::debug!("Discord didn't take the activity: {answer}");
+ }
+ Ok(())
+ }
+}
+
+enum Message {
+ Set(Option),
+ Stop,
+}
+
+/// Sends activities to Discord from a thread of its own, so a slow or missing Discord never holds up Cubby.
+/// Dropping it clears the activity.
+pub struct Presence {
+ tx: Sender,
+}
+
+impl Presence {
+ /// Starts the worker for this Discord application id.
+ pub fn new(client_id: String) -> Self {
+ let (tx, rx) = mpsc::channel();
+ std::thread::Builder::new()
+ .name("discord-presence".into())
+ .spawn(move || worker(client_id, rx))
+ .map_err(|e| tracing::warn!("couldn't start the Discord thread: {e}"))
+ .ok();
+ Self { tx }
+ }
+
+ /// Shows this activity, or clears it with `None`. Only the newest one counts.
+ pub fn set(&self, activity: Option) {
+ let _ = self.tx.send(Message::Set(activity));
+ }
+}
+
+impl Drop for Presence {
+ fn drop(&mut self) {
+ let _ = self.tx.send(Message::Set(None));
+ let _ = self.tx.send(Message::Stop);
+ }
+}
+
+fn worker(client_id: String, rx: Receiver) {
+ let mut conn: Option = None;
+ let mut nonce = 0u64;
+ let pid = std::process::id();
+ while let Ok(first) = rx.recv() {
+ // Skip to the newest update: a game that started and stopped while Discord was slow shows nothing.
+ let mut msg = first;
+ while let Ok(next) = rx.try_recv() {
+ msg = next;
+ }
+ let activity = match msg {
+ Message::Stop => break,
+ Message::Set(a) => a,
+ };
+ if conn.is_none() {
+ if activity.is_none() {
+ continue;
+ }
+ conn = Connection::open(&client_id);
+ }
+ let Some(c) = conn.as_mut() else { continue };
+ nonce += 1;
+ if let Err(e) = c.send(&set_activity_payload(pid, activity.as_ref(), nonce)) {
+ tracing::debug!("lost Discord: {e}");
+ conn = None;
+ // Discord may have restarted: try once more with a new connection.
+ if let Some(mut fresh) = activity.as_ref().and_then(|_| Connection::open(&client_id)) {
+ if fresh.send(&set_activity_payload(pid, activity.as_ref(), nonce)).is_ok() {
+ conn = Some(fresh);
+ }
+ }
+ }
+ }
+}
+
+/// The Discord application id: `CUBBY_DISCORD_CLIENT_ID` when Cubby runs, else the one it was built with.
+pub fn client_id() -> Option {
+ let clean = |s: &str| {
+ let s = s.trim();
+ (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.to_string())
+ };
+ std::env::var("CUBBY_DISCORD_CLIENT_ID")
+ .ok()
+ .as_deref()
+ .and_then(clean)
+ .or_else(|| option_env!("CUBBY_DISCORD_CLIENT_ID").and_then(clean))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn frames_and_payloads() {
+ let frame = encode_frame(OP_HANDSHAKE, &json!({"v": 1}));
+ assert_eq!(&frame[..4], &[0, 0, 0, 0]);
+ assert_eq!(u32::from_le_bytes(frame[4..8].try_into().unwrap()) as usize, frame.len() - 8);
+
+ let a = Activity { details: "Playing All the Mods 9".into(), state: "Minecraft 1.20.1 · Forge".into(), started: 1_700_000_000 };
+ let p = set_activity_payload(42, Some(&a), 7);
+ assert_eq!(p["cmd"], "SET_ACTIVITY");
+ assert_eq!(p["args"]["pid"], 42);
+ assert_eq!(p["args"]["activity"]["timestamps"]["start"], 1_700_000_000);
+ assert_eq!(p["args"]["activity"]["assets"]["large_image"], "cubby");
+ assert_eq!(p["nonce"], "7");
+ assert!(set_activity_payload(42, None, 8)["args"]["activity"].is_null());
+ assert_eq!(clip("x"), "x ");
+ assert_eq!(clip(&"é".repeat(200)).chars().count(), 128);
+ }
+
+ #[test]
+ fn no_discord_is_fine() {
+ // Without Discord running, updates are dropped quietly.
+ let presence = Presence::new("1".into());
+ presence.set(Some(Activity { details: "Playing".into(), state: "Minecraft".into(), started: 0 }));
+ presence.set(None);
+ drop(presence);
+ }
+}
diff --git a/crates/cubby-instance/Cargo.toml b/crates/cubby-instance/Cargo.toml
index 72f69a0..f389357 100644
--- a/crates/cubby-instance/Cargo.toml
+++ b/crates/cubby-instance/Cargo.toml
@@ -16,3 +16,4 @@ toml.workspace = true
chrono.workspace = true
zip.workspace = true
flate2 = "1"
+png = "0.18"
diff --git a/crates/cubby-instance/src/datapacks.rs b/crates/cubby-instance/src/datapacks.rs
new file mode 100644
index 0000000..b2c23c0
--- /dev/null
+++ b/crates/cubby-instance/src/datapacks.rs
@@ -0,0 +1,262 @@
+//! The datapacks of a world: `saves//datapacks`.
+//!
+//! The game loads every `.zip` and every folder with a `pack.mcmeta` it finds there. A datapack turned off in
+//! Cubby moves to `saves//datapacks.disabled`, which the game never reads, and comes back when turned on.
+//! Removed ones go to `/.trash/datapacks/`.
+
+use std::fs;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+
+use chrono::{DateTime, Utc};
+use cubby_common::{Error, Result};
+use serde::Serialize;
+
+use crate::util::{check_plain_name, copy_dir_all, move_to_trash, tree_size};
+
+const ON: &str = "datapacks";
+const OFF: &str = "datapacks.disabled";
+const MAX_MCMETA_BYTES: u64 = 256 * 1024;
+
+/// A datapack of a world.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DatapackFile {
+ /// File or folder name on disk.
+ pub file_name: String,
+ /// The file name without `.zip`.
+ pub name: String,
+ pub is_dir: bool,
+ pub enabled: bool,
+ pub size: u64,
+ pub modified: Option>,
+ /// `pack.description` from `pack.mcmeta`, as plain text.
+ pub description: Option,
+}
+
+fn world_dir(game_dir: &Path, world: &str) -> Result {
+ check_plain_name(world)?;
+ let dir = game_dir.join("saves").join(world);
+ if !dir.is_dir() {
+ return Err(Error::NotFound(format!("world {world}")));
+ }
+ Ok(dir)
+}
+
+fn is_pack(path: &Path, file_name: &str) -> bool {
+ !file_name.starts_with('.') && (file_name.to_lowercase().ends_with(".zip") && path.is_file() || path.join("pack.mcmeta").is_file())
+}
+
+/// The text of a chat component: a string, `{"text": ..., "extra": [...]}` or a list of them.
+fn component_text(value: &serde_json::Value, out: &mut String) {
+ match value {
+ serde_json::Value::String(s) => out.push_str(s),
+ serde_json::Value::Array(items) => items.iter().for_each(|v| component_text(v, out)),
+ serde_json::Value::Object(map) => {
+ if let Some(text) = map.get("text").or_else(|| map.get("translate")) {
+ component_text(text, out);
+ }
+ if let Some(extra) = map.get("extra") {
+ component_text(extra, out);
+ }
+ }
+ serde_json::Value::Number(n) => out.push_str(&n.to_string()),
+ _ => {}
+ }
+}
+
+/// Removes `§x` formatting codes.
+fn strip_codes(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut chars = text.chars();
+ while let Some(c) = chars.next() {
+ if c == '§' {
+ chars.next();
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+fn read_mcmeta(path: &Path, is_dir: bool) -> Option {
+ if is_dir {
+ let file = path.join("pack.mcmeta");
+ if fs::metadata(&file).ok()?.len() > MAX_MCMETA_BYTES {
+ return None;
+ }
+ return fs::read_to_string(file).ok();
+ }
+ let mut zip = zip::ZipArchive::new(fs::File::open(path).ok()?).ok()?;
+ let entry = zip.by_name("pack.mcmeta").ok()?;
+ if entry.size() > MAX_MCMETA_BYTES {
+ return None;
+ }
+ let mut text = String::new();
+ entry.take(MAX_MCMETA_BYTES).read_to_string(&mut text).ok()?;
+ Some(text)
+}
+
+fn description(path: &Path, is_dir: bool) -> Option {
+ let text = read_mcmeta(path, is_dir)?;
+ let json: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).ok()?;
+ let mut out = String::new();
+ component_text(json.get("pack")?.get("description")?, &mut out);
+ let out = strip_codes(&out).trim().to_string();
+ (!out.is_empty()).then_some(out)
+}
+
+fn list_folder(dir: &Path, enabled: bool, out: &mut Vec) {
+ let Ok(rd) = fs::read_dir(dir) else { return };
+ for entry in rd.flatten() {
+ let path = entry.path();
+ let file_name = entry.file_name().to_string_lossy().into_owned();
+ if !is_pack(&path, &file_name) {
+ continue;
+ }
+ let Ok(meta) = entry.metadata() else { continue };
+ let is_dir = meta.is_dir();
+ let name = if is_dir { file_name.clone() } else { file_name[..file_name.len() - 4].to_string() };
+ out.push(DatapackFile {
+ description: description(&path, is_dir),
+ size: if is_dir { tree_size(&path) } else { meta.len() },
+ modified: meta.modified().ok().map(DateTime::::from),
+ file_name,
+ name,
+ is_dir,
+ enabled,
+ });
+ }
+}
+
+/// The datapacks of a world, turned on and off, sorted by name.
+pub fn list_datapacks(game_dir: &Path, world: &str) -> Result> {
+ let dir = world_dir(game_dir, world)?;
+ let mut out = Vec::new();
+ list_folder(&dir.join(ON), true, &mut out);
+ list_folder(&dir.join(OFF), false, &mut out);
+ out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| b.enabled.cmp(&a.enabled)));
+ Ok(out)
+}
+
+/// Turns a datapack on (moves it into `datapacks/`) or off (into `datapacks.disabled/`).
+pub fn set_datapack_enabled(game_dir: &Path, world: &str, file_name: &str, enabled: bool) -> Result<()> {
+ check_plain_name(file_name)?;
+ let dir = world_dir(game_dir, world)?;
+ let (from, to) = if enabled { (OFF, ON) } else { (ON, OFF) };
+ let src = dir.join(from).join(file_name);
+ if !src.exists() {
+ // Already where it should be: nothing to do.
+ return if dir.join(to).join(file_name).exists() { Ok(()) } else { Err(Error::NotFound(format!("datapack {file_name}"))) };
+ }
+ let dest_dir = dir.join(to);
+ fs::create_dir_all(&dest_dir).map_err(|e| Error::io(&dest_dir, e))?;
+ let dest = dest_dir.join(file_name);
+ if dest.exists() {
+ return Err(Error::Other(format!("{file_name} is in this world twice. Remove one of them.")));
+ }
+ fs::rename(&src, &dest).map_err(|e| Error::io(src, e))
+}
+
+/// Moves a datapack to `/.trash/datapacks/`. Returns its new location.
+pub fn remove_datapack(game_dir: &Path, world: &str, file_name: &str) -> Result {
+ check_plain_name(file_name)?;
+ let dir = world_dir(game_dir, world)?;
+ let src = [ON, OFF].iter().map(|f| dir.join(f).join(file_name)).find(|p| p.exists()).ok_or_else(|| Error::NotFound(format!("datapack {file_name}")))?;
+ move_to_trash(&src, &game_dir.join(".trash").join("datapacks"), &format!("{world}-{file_name}"))
+}
+
+/// Where a datapack named `file_name` would be downloaded or copied in a world, turned on.
+pub fn datapack_path(game_dir: &Path, world: &str, file_name: &str) -> Result {
+ check_plain_name(file_name)?;
+ Ok(world_dir(game_dir, world)?.join(ON).join(file_name))
+}
+
+/// Copies `.zip` files and datapack folders into a world, turned on. A datapack of the same name is replaced.
+/// Returns the names added; anything that isn't a datapack is an error, and nothing after it is copied.
+pub fn import_datapacks(game_dir: &Path, world: &str, sources: &[PathBuf]) -> Result> {
+ let dir = world_dir(game_dir, world)?.join(ON);
+ fs::create_dir_all(&dir).map_err(|e| Error::io(&dir, e))?;
+ let mut added = Vec::new();
+ for src in sources {
+ let file_name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ if !is_pack(src, &file_name) {
+ return Err(Error::Other(format!("{file_name} isn't a datapack: pick a .zip file or a folder with a pack.mcmeta.")));
+ }
+ let dest = dir.join(&file_name);
+ let off = dir.with_file_name(OFF).join(&file_name);
+ for old in [&dest, &off] {
+ if old.is_dir() {
+ fs::remove_dir_all(old).map_err(|e| Error::io(old, e))?;
+ } else if old.exists() {
+ fs::remove_file(old).map_err(|e| Error::io(old, e))?;
+ }
+ }
+ if src.is_dir() {
+ copy_dir_all(src, &dest)?;
+ } else {
+ fs::copy(src, &dest).map_err(|e| Error::io(src, e))?;
+ }
+ added.push(file_name);
+ }
+ Ok(added)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::{temp_dir, write_zip};
+
+ fn world(name: &str) -> PathBuf {
+ let game = temp_dir(name);
+ fs::create_dir_all(game.join("saves/World/datapacks")).unwrap();
+ game
+ }
+
+ #[test]
+ fn lists_toggles_and_removes() {
+ let game = world("datapacks-list");
+ let packs = game.join("saves/World/datapacks");
+ write_zip(&packs.join("Terralith.zip"), &[("pack.mcmeta", r#"{"pack":{"pack_format":48,"description":[{"text":"§aNew "},{"text":"biomes"}]}}"#)]);
+ fs::create_dir_all(packs.join("my pack")).unwrap();
+ fs::write(packs.join("my pack/pack.mcmeta"), r#"{"pack":{"description":"Mine"}}"#).unwrap();
+ fs::create_dir_all(packs.join("not a pack")).unwrap();
+ fs::write(packs.join("notes.txt"), "x").unwrap();
+
+ let list = list_datapacks(&game, "World").unwrap();
+ let names: Vec<_> = list.iter().map(|p| (p.name.as_str(), p.enabled, p.description.as_deref())).collect();
+ assert_eq!(names, [("my pack", true, Some("Mine")), ("Terralith", true, Some("New biomes"))]);
+
+ set_datapack_enabled(&game, "World", "Terralith.zip", false).unwrap();
+ assert!(game.join("saves/World/datapacks.disabled/Terralith.zip").is_file());
+ assert!(!list_datapacks(&game, "World").unwrap().iter().find(|p| p.name == "Terralith").unwrap().enabled);
+ set_datapack_enabled(&game, "World", "Terralith.zip", false).unwrap();
+ set_datapack_enabled(&game, "World", "Terralith.zip", true).unwrap();
+ assert!(packs.join("Terralith.zip").is_file());
+
+ let trashed = remove_datapack(&game, "World", "my pack").unwrap();
+ assert!(trashed.join("pack.mcmeta").is_file());
+ assert_eq!(list_datapacks(&game, "World").unwrap().len(), 1);
+ assert!(list_datapacks(&game, "../x").is_err());
+ assert!(list_datapacks(&game, "Nope").is_err());
+ }
+
+ #[test]
+ fn imports_zips_and_folders() {
+ let game = world("datapacks-import");
+ let src = temp_dir("datapacks-import-src");
+ write_zip(&src.join("a.zip"), &[("pack.mcmeta", "{}")]);
+ fs::create_dir_all(src.join("b")).unwrap();
+ fs::write(src.join("b/pack.mcmeta"), "{}").unwrap();
+ fs::write(src.join("c.txt"), "x").unwrap();
+ let added = import_datapacks(&game, "World", &[src.join("a.zip"), src.join("b")]).unwrap();
+ assert_eq!(added, ["a.zip", "b"]);
+ assert!(game.join("saves/World/datapacks/b/pack.mcmeta").is_file());
+ assert!(import_datapacks(&game, "World", &[src.join("c.txt")]).is_err());
+ // Importing again replaces, also a copy that was turned off.
+ set_datapack_enabled(&game, "World", "a.zip", false).unwrap();
+ import_datapacks(&game, "World", &[src.join("a.zip")]).unwrap();
+ assert_eq!(list_datapacks(&game, "World").unwrap().iter().filter(|p| p.enabled).count(), 2);
+ assert!(!game.join("saves/World/datapacks.disabled/a.zip").exists());
+ }
+}
diff --git a/crates/cubby-instance/src/launchers.rs b/crates/cubby-instance/src/launchers.rs
new file mode 100644
index 0000000..b443670
--- /dev/null
+++ b/crates/cubby-instance/src/launchers.rs
@@ -0,0 +1,540 @@
+//! Importing instances from other launchers: MultiMC and PolyMC (Prism's format), the CurseForge app,
+//! ATLauncher, GDLauncher, the Modrinth App and the official launcher's installations.
+//!
+//! Their folders are only read. Each instance's game folder is copied into a new Cubby instance.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use chrono::{DateTime, Utc};
+use cubby_common::{Error, Result};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::model::{Instance, JavaOverrides, Loader};
+use crate::prism;
+use crate::store::InstanceStore;
+use crate::util::copy_dir_all;
+
+/// A launcher Cubby can import from.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Launcher {
+ Prism,
+ MultiMc,
+ PolyMc,
+ CurseForge,
+ AtLauncher,
+ GdLauncher,
+ ModrinthApp,
+ Official,
+}
+
+impl Launcher {
+ pub fn title(self) -> &'static str {
+ match self {
+ Launcher::Prism => "Prism Launcher",
+ Launcher::MultiMc => "MultiMC",
+ Launcher::PolyMc => "PolyMC",
+ Launcher::CurseForge => "CurseForge",
+ Launcher::AtLauncher => "ATLauncher",
+ Launcher::GdLauncher => "GDLauncher",
+ Launcher::ModrinthApp => "Modrinth App",
+ Launcher::Official => "Minecraft Launcher",
+ }
+ }
+}
+
+/// The usual folders, from the system's data folder (`%APPDATA%`, `~/Library/Application Support`,
+/// `~/.local/share`), the home folder and the documents folder.
+#[derive(Debug, Clone)]
+pub struct SystemDirs {
+ pub data: PathBuf,
+ pub home: PathBuf,
+ pub documents: Option,
+}
+
+/// Where each launcher keeps its data, most likely first. Folders that don't exist are left in: callers skip them.
+pub fn known_locations(dirs: &SystemDirs) -> Vec<(Launcher, PathBuf)> {
+ let d = &dirs.data;
+ let mut out = vec![
+ (Launcher::Prism, d.join("PrismLauncher")),
+ (Launcher::MultiMc, d.join("multimc")),
+ (Launcher::MultiMc, d.join("MultiMC")),
+ (Launcher::MultiMc, dirs.home.join("MultiMC")),
+ (Launcher::PolyMc, d.join("PolyMC")),
+ (Launcher::CurseForge, dirs.home.join("curseforge").join("minecraft").join("Instances")),
+ (Launcher::AtLauncher, d.join("ATLauncher")),
+ (Launcher::AtLauncher, d.join("atlauncher")),
+ (Launcher::GdLauncher, d.join("gdlauncher_next")),
+ (Launcher::GdLauncher, d.join("gdlauncher_carbon").join("data")),
+ (Launcher::ModrinthApp, d.join("ModrinthApp")),
+ (Launcher::ModrinthApp, d.join("com.modrinth.theseus")),
+ (Launcher::Official, d.join("minecraft")),
+ (Launcher::Official, d.join(".minecraft")),
+ (Launcher::Official, dirs.home.join(".minecraft")),
+ ];
+ if let Some(docs) = &dirs.documents {
+ out.insert(6, (Launcher::CurseForge, docs.join("curseforge").join("minecraft").join("Instances")));
+ }
+ out
+}
+
+/// An instance of another launcher.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ForeignInstance {
+ pub launcher: Launcher,
+ /// What identifies it for [`import_foreign`]: the instance folder, or for the official launcher
+ /// `launcher_profiles.json#`.
+ pub path: String,
+ pub name: String,
+ /// `None` when the launcher doesn't say (newer Modrinth App versions keep it in a database).
+ pub minecraft: Option,
+ pub loader: Loader,
+ pub group: Option,
+ pub last_played: Option>,
+ pub total_played_secs: u64,
+ /// The folder copied into the new instance.
+ pub game_dir: PathBuf,
+}
+
+fn read_json(path: &Path) -> Option {
+ let text = fs::read_to_string(path).ok()?;
+ serde_json::from_str(text.trim_start_matches('\u{feff}')).ok()
+}
+
+fn str_at<'a>(v: &'a Value, path: &[&str]) -> Option<&'a str> {
+ let mut cur = v;
+ for key in path {
+ cur = cur.get(key)?;
+ }
+ cur.as_str().map(str::trim).filter(|s| !s.is_empty())
+}
+
+fn folder_name(path: &Path) -> String {
+ path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
+}
+
+/// A loader from a kind word ("fabric", "Forge", "neoforge"...) and a version.
+fn loader_of(kind: &str, version: &str) -> Loader {
+ let version = version.trim().to_string();
+ if version.is_empty() {
+ return Loader::Vanilla;
+ }
+ match kind.trim().to_lowercase().replace(['-', '_'], "").as_str() {
+ "fabric" | "fabricloader" => Loader::Fabric { version },
+ "quilt" | "quiltloader" => Loader::Quilt { version },
+ "forge" | "minecraftforge" => Loader::Forge { version },
+ "neoforge" | "neoforged" => Loader::NeoForge { version },
+ _ => Loader::Vanilla,
+ }
+}
+
+fn iso_time(s: Option<&str>) -> Option> {
+ s.and_then(|s| DateTime::parse_from_rfc3339(s).ok()).map(|d| d.with_timezone(&Utc)).filter(|d| d.timestamp() > 0)
+}
+
+fn sub_dirs(dir: &Path) -> Vec {
+ let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
+ let mut out: Vec = rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
+ out.sort();
+ out
+}
+
+// CurseForge app: //minecraftinstance.json, the game folder is the instance folder.
+
+/// "forge-47.2.0", "fabric-0.15.11-1.20.1", "neoforge-21.1.5" → a loader.
+fn curseforge_loader(id: &str, minecraft: &str) -> Loader {
+ let Some((kind, rest)) = id.split_once('-') else { return Loader::Vanilla };
+ let version = rest.strip_suffix(&format!("-{minecraft}")).unwrap_or(rest);
+ loader_of(kind, version)
+}
+
+fn read_curseforge(dir: &Path) -> Option {
+ let v = read_json(&dir.join("minecraftinstance.json"))?;
+ let minecraft = str_at(&v, &["gameVersion"]).map(String::from);
+ let loader = str_at(&v, &["baseModLoader", "name"]).map(|id| curseforge_loader(id, minecraft.as_deref().unwrap_or(""))).unwrap_or(Loader::Vanilla);
+ Some(ForeignInstance {
+ launcher: Launcher::CurseForge,
+ path: dir.to_string_lossy().into_owned(),
+ name: str_at(&v, &["name"]).map(String::from).unwrap_or_else(|| folder_name(dir)),
+ minecraft,
+ loader,
+ group: None,
+ last_played: iso_time(str_at(&v, &["lastPlayed"])),
+ total_played_secs: 0,
+ game_dir: dir.to_path_buf(),
+ })
+}
+
+// ATLauncher: /instances//instance.json.
+
+fn read_atlauncher(dir: &Path) -> Option {
+ let v = read_json(&dir.join("instance.json"))?;
+ let launcher = v.get("launcher").unwrap_or(&Value::Null);
+ let loader = match (str_at(launcher, &["loaderVersion", "type"]), str_at(launcher, &["loaderVersion", "version"])) {
+ (Some(kind), Some(version)) => loader_of(kind, version),
+ _ => Loader::Vanilla,
+ };
+ Some(ForeignInstance {
+ launcher: Launcher::AtLauncher,
+ path: dir.to_string_lossy().into_owned(),
+ name: str_at(launcher, &["name"]).map(String::from).unwrap_or_else(|| folder_name(dir)),
+ minecraft: str_at(&v, &["id"]).map(String::from),
+ loader,
+ group: None,
+ last_played: iso_time(str_at(launcher, &["lastPlayed"])),
+ total_played_secs: launcher.get("totalPlayTime").and_then(Value::as_u64).map(|ms| ms / 1000).unwrap_or(0),
+ game_dir: dir.to_path_buf(),
+ })
+}
+
+// GDLauncher: the old one keeps /instances//config.json, GDLauncher Carbon (2.0)
+// /instances//instance.json with the game in instance/.
+
+fn read_gdlauncher(dir: &Path) -> Option {
+ if let Some(v) = read_json(&dir.join("config.json")).filter(|v| v.get("loader").is_some()) {
+ let l = &v["loader"];
+ return Some(ForeignInstance {
+ launcher: Launcher::GdLauncher,
+ path: dir.to_string_lossy().into_owned(),
+ name: folder_name(dir),
+ minecraft: str_at(l, &["mcVersion"]).map(String::from),
+ loader: loader_of(str_at(l, &["loaderType"]).unwrap_or(""), str_at(l, &["loaderVersion"]).unwrap_or("")),
+ group: None,
+ last_played: v.get("lastPlayed").and_then(Value::as_i64).filter(|ms| *ms > 0).and_then(DateTime::::from_timestamp_millis),
+ total_played_secs: v.get("timePlayed").and_then(Value::as_u64).unwrap_or(0),
+ game_dir: dir.to_path_buf(),
+ });
+ }
+ let v = read_json(&dir.join("instance.json"))?;
+ let version = v.get("game_configuration").and_then(|g| g.get("version")).or_else(|| v.get("version")).unwrap_or(&Value::Null);
+ let minecraft = str_at(version, &["release"]).or_else(|| str_at(version, &["Standard", "release"])).map(String::from);
+ let modloaders = version.get("modloaders").or_else(|| version.get("Standard").and_then(|s| s.get("modloaders")));
+ let loader = modloaders
+ .and_then(Value::as_array)
+ .and_then(|l| l.first())
+ .map(|m| loader_of(str_at(m, &["type_"]).or_else(|| str_at(m, &["type"])).unwrap_or(""), str_at(m, &["version"]).unwrap_or("")))
+ .unwrap_or(Loader::Vanilla);
+ let game = dir.join("instance");
+ Some(ForeignInstance {
+ launcher: Launcher::GdLauncher,
+ path: dir.to_string_lossy().into_owned(),
+ name: str_at(&v, &["name"]).map(String::from).unwrap_or_else(|| folder_name(dir)),
+ minecraft,
+ loader,
+ group: None,
+ last_played: iso_time(str_at(&v, &["last_played"])),
+ total_played_secs: v.get("seconds_played").and_then(Value::as_u64).unwrap_or(0),
+ game_dir: if game.is_dir() { game } else { dir.to_path_buf() },
+ })
+}
+
+// Modrinth App: /profiles//, with profile.json in versions before 0.8. Newer versions keep the
+// version in a database, so those profiles come without a Minecraft version.
+
+fn read_modrinth_app(dir: &Path) -> Option {
+ let v = read_json(&dir.join("profile.json"));
+ let meta = v.as_ref().and_then(|v| v.get("metadata"));
+ let (minecraft, loader, name) = match meta {
+ Some(m) => {
+ let version = str_at(m, &["loader_version", "id"]).unwrap_or("");
+ let mc = str_at(m, &["game_version"]).map(String::from);
+ let version = version.strip_prefix(&format!("{}-", mc.as_deref().unwrap_or("-"))).unwrap_or(version);
+ (mc, loader_of(str_at(m, &["loader"]).unwrap_or(""), version), str_at(m, &["name"]).map(String::from))
+ }
+ None => (None, Loader::Vanilla, None),
+ };
+ // A profile is a folder with game content in it.
+ if meta.is_none() && !["mods", "saves", "options.txt"].iter().any(|n| dir.join(n).exists()) {
+ return None;
+ }
+ Some(ForeignInstance {
+ launcher: Launcher::ModrinthApp,
+ path: dir.to_string_lossy().into_owned(),
+ name: name.unwrap_or_else(|| folder_name(dir)),
+ minecraft,
+ loader,
+ group: None,
+ last_played: None,
+ total_played_secs: 0,
+ game_dir: dir.to_path_buf(),
+ })
+}
+
+// The official launcher: installations in launcher_profiles.json.
+
+/// "fabric-loader-0.15.11-1.20.1", "quilt-loader-0.26.0-1.20.1", "1.20.1-forge-47.2.0", "neoforge-21.1.5",
+/// "1.21.1" → (Minecraft version, loader). `None` for "latest-release" and the like.
+pub(crate) fn official_version(id: &str) -> Option<(String, Loader)> {
+ let id = id.trim();
+ for (prefix, kind) in [("fabric-loader-", "fabric"), ("quilt-loader-", "quilt")] {
+ if let Some(rest) = id.strip_prefix(prefix) {
+ let (version, mc) = rest.split_once('-')?;
+ return Some((mc.to_string(), loader_of(kind, version)));
+ }
+ }
+ if let Some((mc, version)) = id.split_once("-forge-") {
+ return Some((mc.to_string(), loader_of("forge", version)));
+ }
+ if let Some(version) = id.strip_prefix("neoforge-") {
+ // NeoForge 21.1.x is for 1.21.1, 20.4.x for 1.20.4; a .0 minor is the plain release.
+ let mut parts = version.split('.');
+ let (major, minor) = (parts.next()?, parts.next()?);
+ let mc = if minor == "0" { format!("1.{major}") } else { format!("1.{major}.{minor}") };
+ return Some((mc, loader_of("neoforge", version)));
+ }
+ if id.is_empty() || id.starts_with("latest-") || id.contains("optifine") || id.contains("OptiFine") {
+ return None;
+ }
+ Some((id.to_string(), Loader::Vanilla))
+}
+
+/// Game content worth copying from a shared `.minecraft` (not the launcher's versions, libraries and assets).
+const OFFICIAL_CONTENT: [&str; 9] = ["mods", "saves", "resourcepacks", "shaderpacks", "config", "screenshots", "options.txt", "servers.dat", "optionsshaders.txt"];
+
+fn read_official(root: &Path) -> Vec {
+ let file = root.join("launcher_profiles.json");
+ let Some(v) = read_json(&file) else { return Vec::new() };
+ let Some(profiles) = v.get("profiles").and_then(Value::as_object) else { return Vec::new() };
+ let mut out = Vec::new();
+ for (key, p) in profiles {
+ let Some((minecraft, loader)) = str_at(p, &["lastVersionId"]).and_then(official_version) else { continue };
+ let game_dir = str_at(p, &["gameDir"]).map(PathBuf::from).unwrap_or_else(|| root.to_path_buf());
+ let name = str_at(p, &["name"]).map(String::from).unwrap_or_else(|| format!("Minecraft {minecraft}"));
+ out.push(ForeignInstance {
+ launcher: Launcher::Official,
+ path: format!("{}#{key}", file.to_string_lossy()),
+ name,
+ minecraft: Some(minecraft),
+ loader,
+ group: None,
+ last_played: iso_time(str_at(p, &["lastUsed"])),
+ total_played_secs: 0,
+ game_dir,
+ });
+ }
+ out
+}
+
+/// The instances of one launcher folder (see [`known_locations`]).
+pub fn list_foreign(launcher: Launcher, root: &Path) -> Vec {
+ let mut out: Vec = match launcher {
+ Launcher::Prism | Launcher::MultiMc | Launcher::PolyMc => prism::list_prism_instances(root)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|p| ForeignInstance {
+ launcher,
+ game_dir: ["minecraft", ".minecraft"].iter().map(|n| p.path.join(n)).find(|d| d.is_dir()).unwrap_or_else(|| p.path.clone()),
+ path: p.path.to_string_lossy().into_owned(),
+ name: p.name,
+ minecraft: p.minecraft,
+ loader: p.loader,
+ group: p.group,
+ last_played: p.last_played,
+ total_played_secs: p.total_played_secs,
+ })
+ .collect(),
+ Launcher::CurseForge => sub_dirs(root).iter().filter_map(|d| read_curseforge(d)).collect(),
+ Launcher::AtLauncher => sub_dirs(&root.join("instances")).iter().filter_map(|d| read_atlauncher(d)).collect(),
+ Launcher::GdLauncher => sub_dirs(&root.join("instances")).iter().filter_map(|d| read_gdlauncher(d)).collect(),
+ Launcher::ModrinthApp => sub_dirs(&root.join("profiles")).iter().filter_map(|d| read_modrinth_app(d)).collect(),
+ Launcher::Official => read_official(root),
+ };
+ out.sort_by_key(|i| i.name.to_lowercase());
+ out
+}
+
+/// Every instance of every launcher found in the usual folders. Two locations of the same folder are listed once.
+pub fn list_all_foreign(dirs: &SystemDirs) -> Vec {
+ let mut seen = std::collections::HashSet::new();
+ let mut out = Vec::new();
+ for (launcher, root) in known_locations(dirs) {
+ let Ok(real) = fs::canonicalize(&root) else { continue };
+ if !seen.insert(real) {
+ continue;
+ }
+ out.extend(list_foreign(launcher, &root));
+ }
+ out
+}
+
+fn copy_selected(src: &Path, dest: &Path, names: &[&str]) -> Result<()> {
+ fs::create_dir_all(dest).map_err(|e| Error::io(dest, e))?;
+ for name in names {
+ let from = src.join(name);
+ if from.is_dir() {
+ copy_dir_all(&from, &dest.join(name))?;
+ } else if from.is_file() {
+ fs::copy(&from, dest.join(name)).map_err(|e| Error::io(&from, e))?;
+ }
+ }
+ Ok(())
+}
+
+/// Things other launchers keep in the instance folder that aren't game content.
+const SKIPPED: [&str; 9] = ["minecraftinstance.json", "instance.json", "config.json", "profile.json", "natives", "logs", "crash-reports", ".fabric", "instance.cfg"];
+
+/// Copies a game folder, leaving out the other launcher's own files.
+fn copy_game(src: &Path, dest: &Path) -> Result<()> {
+ fs::create_dir_all(dest).map_err(|e| Error::io(dest, e))?;
+ for entry in fs::read_dir(src).map_err(|e| Error::io(src, e))?.flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if SKIPPED.contains(&name.as_str()) {
+ continue;
+ }
+ let path = entry.path();
+ let Ok(ty) = entry.file_type() else { continue };
+ if ty.is_dir() {
+ copy_dir_all(&path, &dest.join(&name))?;
+ } else if ty.is_file() {
+ fs::copy(&path, dest.join(&name)).map_err(|e| Error::io(&path, e))?;
+ }
+ }
+ Ok(())
+}
+
+/// Imports an instance listed by [`list_foreign`] into `store`, copying its game folder.
+pub fn import_foreign(store: &InstanceStore, found: &ForeignInstance) -> Result {
+ if matches!(found.launcher, Launcher::Prism | Launcher::MultiMc | Launcher::PolyMc) {
+ return prism::import_prism(store, Path::new(&found.path), true);
+ }
+ let minecraft = found.minecraft.clone().ok_or_else(|| {
+ Error::Other(format!("{} doesn't say which Minecraft version {} uses. Export it as a .mrpack from {0}, then import that file.", found.launcher.title(), found.name))
+ })?;
+ if !found.game_dir.is_dir() {
+ return Err(Error::NotFound(format!("the game folder of {}", found.name)));
+ }
+ let id = store.reserve_id(&found.name)?;
+ let inst = Instance {
+ id,
+ name: found.name.clone(),
+ group: found.group.clone(),
+ icon: None,
+ minecraft,
+ loader: found.loader.clone(),
+ created: Utc::now(),
+ last_played: found.last_played,
+ total_played_secs: found.total_played_secs,
+ java: JavaOverrides::default(),
+ window: None,
+ notes: Some(format!("Imported from {}.", found.launcher.title())),
+ modpack: None,
+ };
+ let dest = store.game_dir(&inst);
+ // The official launcher's default installation is the shared .minecraft: only its game content is copied.
+ let shared = found.launcher == Launcher::Official && found.game_dir.join("versions").is_dir();
+ let copied = if shared { copy_selected(&found.game_dir, &dest, &OFFICIAL_CONTENT) } else { copy_game(&found.game_dir, &dest) };
+ if let Err(e) = copied {
+ let _ = fs::remove_dir_all(store.paths().instance(&inst.id));
+ return Err(e);
+ }
+ store.insert(inst)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::temp_dir;
+ use cubby_common::paths::Paths;
+
+ fn write(path: &Path, text: &str) {
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, text).unwrap();
+ }
+
+ #[test]
+ fn official_version_ids() {
+ assert_eq!(official_version("fabric-loader-0.15.11-1.20.1"), Some(("1.20.1".into(), Loader::Fabric { version: "0.15.11".into() })));
+ assert_eq!(official_version("1.20.1-forge-47.2.0"), Some(("1.20.1".into(), Loader::Forge { version: "47.2.0".into() })));
+ assert_eq!(official_version("neoforge-21.1.5"), Some(("1.21.1".into(), Loader::NeoForge { version: "21.1.5".into() })));
+ assert_eq!(official_version("neoforge-21.0.10"), Some(("1.21".into(), Loader::NeoForge { version: "21.0.10".into() })));
+ assert_eq!(official_version("1.21.1"), Some(("1.21.1".into(), Loader::Vanilla)));
+ assert_eq!(official_version("latest-release"), None);
+ }
+
+ #[test]
+ fn curseforge_loader_ids() {
+ assert_eq!(curseforge_loader("forge-47.2.0", "1.20.1"), Loader::Forge { version: "47.2.0".into() });
+ assert_eq!(curseforge_loader("fabric-0.15.11-1.20.1", "1.20.1"), Loader::Fabric { version: "0.15.11".into() });
+ assert_eq!(curseforge_loader("neoforge-21.1.5", "1.21.1"), Loader::NeoForge { version: "21.1.5".into() });
+ }
+
+ #[test]
+ fn lists_each_launcher() {
+ let root = temp_dir("launchers");
+ write(
+ &root.join("cf/All the Mods/minecraftinstance.json"),
+ r#"{"name":"All the Mods","gameVersion":"1.20.1","baseModLoader":{"name":"forge-47.2.0"},"lastPlayed":"2026-10-01T10:00:00Z"}"#,
+ );
+ write(&root.join("cf/All the Mods/mods/a.jar"), "x");
+ write(
+ &root.join("atl/instances/Vanilla Plus/instance.json"),
+ r#"{"id":"1.21.1","launcher":{"name":"Vanilla Plus","loaderVersion":{"type":"Fabric","version":"0.16.5"},"totalPlayTime":7200000}}"#,
+ );
+ write(&root.join("gd/instances/Old/config.json"), r#"{"loader":{"loaderType":"forge","loaderVersion":"47.2.0","mcVersion":"1.20.1"},"timePlayed":60}"#);
+ write(
+ &root.join("gd/instances/New/instance.json"),
+ r#"{"name":"New One","game_configuration":{"version":{"Standard":{"release":"1.21.1","modloaders":[{"type_":"Neoforge","version":"21.1.5"}]}}}}"#,
+ );
+ write(&root.join("gd/instances/New/instance/mods/b.jar"), "x");
+ write(&root.join("mr/profiles/Fabulous/profile.json"), r#"{"metadata":{"name":"Fabulous","game_version":"1.21.1","loader":"fabric","loader_version":{"id":"0.16.5"}}}"#);
+ write(&root.join("mr/profiles/Newer/mods/c.jar"), "x");
+ write(&root.join("mr/profiles/caches/x"), "x");
+ write(
+ &root.join("official/launcher_profiles.json"),
+ r#"{"profiles":{"a":{"name":"Fabric","lastVersionId":"fabric-loader-0.16.5-1.21.1","gameDir":"/x"},"b":{"type":"latest-release","lastVersionId":"latest-release"}}}"#,
+ );
+
+ let cf = list_foreign(Launcher::CurseForge, &root.join("cf"));
+ assert_eq!((cf[0].name.as_str(), cf[0].minecraft.as_deref(), &cf[0].loader), ("All the Mods", Some("1.20.1"), &Loader::Forge { version: "47.2.0".into() }));
+ assert!(cf[0].last_played.is_some());
+
+ let atl = list_foreign(Launcher::AtLauncher, &root.join("atl"));
+ assert_eq!((atl[0].loader.clone(), atl[0].total_played_secs), (Loader::Fabric { version: "0.16.5".into() }, 7200));
+
+ let gd = list_foreign(Launcher::GdLauncher, &root.join("gd"));
+ let names: Vec<_> = gd.iter().map(|i| (i.name.as_str(), i.minecraft.as_deref())).collect();
+ assert_eq!(names, [("New One", Some("1.21.1")), ("Old", Some("1.20.1"))]);
+ assert_eq!(gd[0].loader, Loader::NeoForge { version: "21.1.5".into() });
+ assert!(gd[0].game_dir.ends_with("instance"));
+
+ let mr = list_foreign(Launcher::ModrinthApp, &root.join("mr"));
+ let names: Vec<_> = mr.iter().map(|i| (i.name.as_str(), i.minecraft.as_deref())).collect();
+ assert_eq!(names, [("Fabulous", Some("1.21.1")), ("Newer", None)]);
+
+ let official = list_foreign(Launcher::Official, &root.join("official"));
+ assert_eq!(official.len(), 1);
+ assert_eq!(official[0].game_dir, PathBuf::from("/x"));
+ }
+
+ #[test]
+ fn imports_and_skips_launcher_files() {
+ let root = temp_dir("launchers-import");
+ write(&root.join("cf/Pack/minecraftinstance.json"), r#"{"name":"Pack","gameVersion":"1.20.1","baseModLoader":{"name":"forge-47.2.0"}}"#);
+ write(&root.join("cf/Pack/mods/a.jar"), "x");
+ write(&root.join("cf/Pack/saves/W/level.dat"), "x");
+ let store = InstanceStore::new(Paths::new(root.join("cubby")));
+ let found = list_foreign(Launcher::CurseForge, &root.join("cf")).remove(0);
+ let inst = import_foreign(&store, &found).unwrap();
+ let game = store.game_dir(&inst);
+ assert!(game.join("mods/a.jar").is_file());
+ assert!(game.join("saves/W/level.dat").is_file());
+ assert!(!game.join("minecraftinstance.json").exists());
+ assert_eq!(inst.loader, Loader::Forge { version: "47.2.0".into() });
+
+ // The shared .minecraft of the official launcher: only game content comes over.
+ let mc = root.join("official");
+ write(&mc.join("launcher_profiles.json"), r#"{"profiles":{"a":{"name":"Release","lastVersionId":"1.21.1"}}}"#);
+ write(&mc.join("versions/1.21.1/1.21.1.json"), "{}");
+ write(&mc.join("saves/S/level.dat"), "x");
+ let found = list_foreign(Launcher::Official, &mc).remove(0);
+ let inst = import_foreign(&store, &found).unwrap();
+ assert!(store.game_dir(&inst).join("saves/S/level.dat").is_file());
+ assert!(!store.game_dir(&inst).join("versions").exists());
+
+ let unknown = ForeignInstance { minecraft: None, ..found };
+ assert!(import_foreign(&store, &unknown).is_err());
+ }
+}
diff --git a/crates/cubby-instance/src/lib.rs b/crates/cubby-instance/src/lib.rs
index 9d68bbf..fada5cb 100644
--- a/crates/cubby-instance/src/lib.rs
+++ b/crates/cubby-instance/src/lib.rs
@@ -1,14 +1,21 @@
//! Instances and their content, world backups, Prism Launcher import and launcher settings.
mod backups;
+pub mod datapacks;
+pub mod memory;
pub mod content;
+pub mod launchers;
+pub mod map;
mod model;
mod nbt;
+pub mod options;
pub mod prism;
mod servers;
pub mod skins;
mod settings;
+pub mod shortcut;
mod store;
+pub mod update_backups;
mod util;
pub use content::{
@@ -17,6 +24,12 @@ pub use content::{
};
pub use servers::{read_servers, write_servers, ServerEntry};
pub use backups::{backup_stamp, WorldBackup};
+pub use datapacks::{datapack_path, import_datapacks, list_datapacks, remove_datapack, set_datapack_enabled, DatapackFile};
+pub use update_backups::{record_update, UpdateBackup, UpdatedFile};
+pub use launchers::{import_foreign, known_locations, list_all_foreign, list_foreign, ForeignInstance, Launcher, SystemDirs};
+pub use options::{copy_options, OptionsCopy};
+pub use map::{render_map, WorldMap};
+pub use memory::{count_enabled_mods, recommended_memory_mb};
pub use model::{Instance, JavaOverrides, Loader, ModpackInfo, NewInstance, WindowSize};
pub use prism::{import_prism, list_prism_instances, PrismInstanceInfo};
pub use settings::{FrameMode, GameSettings, JavaSettings, OnLaunch, ProxyMode, ProxySettings, Settings, UpdateChannel, UpdateMode, UpdateSettings};
diff --git a/crates/cubby-instance/src/map.rs b/crates/cubby-instance/src/map.rs
new file mode 100644
index 0000000..44ac414
--- /dev/null
+++ b/crates/cubby-instance/src/map.rs
@@ -0,0 +1,541 @@
+//! A top-down map of a world around its spawn, read from the region files (`region/r.X.Z.mca`), as a PNG.
+//!
+//! Each pixel is the top block of a column (from the chunk's `WORLD_SURFACE` heightmap), coloured by block name
+//! and shaded by height like the game's own maps. Worlds from Minecraft 1.13 on are read (block palettes);
+//! older ones have numeric block ids and give an error. Ungenerated chunks stay transparent.
+
+use std::collections::HashMap;
+use std::fs;
+use std::io::{Read, Seek, SeekFrom};
+use std::path::{Path, PathBuf};
+use std::time::SystemTime;
+
+use cubby_common::{Error, Result};
+use serde::Serialize;
+
+use crate::nbt::{self, Tag};
+use crate::util::check_plain_name;
+
+/// Blocks on each side of the spawn: the map is twice this wide.
+pub const MAP_RADIUS: i32 = 384;
+/// The chunk format with sections at the root and `block_states` (1.18).
+const DATA_VERSION_1_18: i64 = 2844;
+/// Heightmaps and block states stopped spanning two longs (1.16).
+const DATA_VERSION_1_16: i64 = 2526;
+const MAX_CHUNK_BYTES: usize = 8 * 1024 * 1024;
+
+/// A rendered map.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorldMap {
+ pub path: PathBuf,
+ /// Block coordinates of the top-left pixel.
+ pub min_x: i32,
+ pub min_z: i32,
+ pub size: u32,
+ /// Chunks drawn (the others aren't generated yet).
+ pub chunks: u32,
+}
+
+/// RGB of a block, by its name without `minecraft:`.
+fn block_color(name: &str) -> [u8; 3] {
+ let n = name.strip_prefix("minecraft:").unwrap_or(name);
+ let exact: Option<[u8; 3]> = match n {
+ "grass_block" => Some([118, 168, 70]),
+ "water" | "bubble_column" => Some([52, 92, 196]),
+ "lava" => Some([220, 100, 20]),
+ "sand" | "sandstone" | "cut_sandstone" | "smooth_sandstone" => Some([219, 207, 163]),
+ "red_sand" | "red_sandstone" => Some([190, 102, 33]),
+ "gravel" => Some([136, 126, 126]),
+ "dirt" | "coarse_dirt" | "rooted_dirt" | "dirt_path" | "farmland" => Some([134, 96, 67]),
+ "podzol" => Some([91, 63, 24]),
+ "mycelium" => Some([111, 99, 105]),
+ "snow" | "snow_block" | "powder_snow" => Some([248, 254, 254]),
+ "ice" | "packed_ice" | "blue_ice" | "frosted_ice" => Some([160, 188, 255]),
+ "clay" => Some([160, 166, 179]),
+ "mud" | "mangrove_roots" | "muddy_mangrove_roots" => Some([60, 57, 61]),
+ "moss_block" | "moss_carpet" => Some([89, 109, 45]),
+ "terracotta" => Some([152, 94, 67]),
+ "netherrack" => Some([111, 54, 52]),
+ "end_stone" => Some([219, 222, 158]),
+ "obsidian" | "crying_obsidian" => Some([20, 18, 29]),
+ "bedrock" => Some([85, 85, 85]),
+ "pumpkin" | "carved_pumpkin" => Some([198, 118, 24]),
+ "melon" => Some([111, 145, 30]),
+ "cactus" => Some([87, 130, 41]),
+ "sugar_cane" | "bamboo" | "kelp" | "kelp_plant" | "seagrass" | "tall_seagrass" => Some([96, 150, 60]),
+ "lily_pad" => Some([32, 128, 48]),
+ _ => None,
+ };
+ if let Some(c) = exact {
+ return c;
+ }
+ let has = |s: &str| n.contains(s);
+ if has("leaves") || has("vine") || has("azalea") {
+ return [55, 110, 35];
+ }
+ if has("short_grass") || n == "grass" || has("tall_grass") || has("fern") || has("bush") || has("sapling") {
+ return [100, 155, 60];
+ }
+ if has("flower") || has("tulip") || has("poppy") || has("dandelion") || has("orchid") || has("allium") || has("daisy") || has("rose") {
+ return [180, 160, 70];
+ }
+ if has("cherry") {
+ return [228, 170, 190];
+ }
+ if has("birch") {
+ return [216, 202, 145];
+ }
+ if has("spruce") || has("dark_oak") || has("mangrove") {
+ return [102, 76, 50];
+ }
+ if has("log") || has("wood") || has("planks") || has("stairs") && has("oak") || has("fence") || has("door") {
+ return [143, 119, 72];
+ }
+ if has("deepslate") || has("blackstone") || has("basalt") {
+ return [72, 72, 78];
+ }
+ if has("stone") || has("cobble") || has("andesite") || has("tuff") || has("ore") {
+ return [125, 125, 125];
+ }
+ if has("granite") {
+ return [149, 103, 85];
+ }
+ if has("diorite") || has("calcite") || has("quartz") {
+ return [222, 222, 214];
+ }
+ if has("brick") {
+ return [150, 74, 60];
+ }
+ if has("glass") {
+ return [200, 220, 230];
+ }
+ if has("wool") || has("carpet") || has("concrete") || has("terracotta") {
+ return [200, 200, 200];
+ }
+ if has("snow") {
+ return [248, 254, 254];
+ }
+ if has("nylium") || has("wart") {
+ return [130, 30, 40];
+ }
+ if has("coral") {
+ return [200, 80, 140];
+ }
+ [140, 140, 120]
+}
+
+/// Values of `count` entries of `bits` bits packed in longs: spanning two longs (before 1.16) or not.
+fn unpack(longs: &[i64], bits: usize, count: usize, spanning: bool) -> Option> {
+ if bits == 0 || bits > 32 {
+ return None;
+ }
+ let mask = (1u64 << bits) - 1;
+ let mut out = Vec::with_capacity(count);
+ if spanning {
+ for i in 0..count {
+ let bit = i * bits;
+ let (idx, off) = (bit / 64, bit % 64);
+ let mut v = (*longs.get(idx)? as u64) >> off;
+ if off + bits > 64 {
+ v |= (*longs.get(idx + 1)? as u64) << (64 - off);
+ }
+ out.push((v & mask) as u32);
+ }
+ } else {
+ let per = 64 / bits;
+ for i in 0..count {
+ let long = *longs.get(i / per)? as u64;
+ out.push(((long >> ((i % per) * bits)) & mask) as u32);
+ }
+ }
+ Some(out)
+}
+
+/// The top blocks of one chunk: 256 (name, y), x fastest, `None` where nothing is there.
+fn chunk_surface(chunk: &Tag) -> Result>> {
+ let version = chunk.get("DataVersion").and_then(Tag::as_i64).unwrap_or(0);
+ if version < 1451 {
+ return Err(Error::Other("This world is from before Minecraft 1.13: its map can't be drawn yet.".into()));
+ }
+ let level = if version >= DATA_VERSION_1_18 { chunk } else { chunk.get("Level").unwrap_or(chunk) };
+ let spanning = version < DATA_VERSION_1_16;
+ let min_y = if version >= DATA_VERSION_1_18 { -64 } else { 0 };
+ let none = || vec![None; 256];
+ let Some(heights) = level.get("Heightmaps").and_then(|h| h.get("WORLD_SURFACE").or_else(|| h.get("MOTION_BLOCKING"))).and_then(Tag::as_longs) else {
+ return Ok(none());
+ };
+ // 9 bits since 1.18 (384 blocks), 9 before too (256 + 1 values).
+ let Some(heights) = unpack(heights, 9, 256, spanning) else { return Ok(none()) };
+
+ // Sections by Y: (palette names, block indices), decoded when a column needs them.
+ let sections_tag = level.get("sections").or_else(|| level.get("Sections")).and_then(Tag::as_list).unwrap_or(&[]);
+ let mut sections: HashMap>)> = HashMap::new();
+ for s in sections_tag {
+ let Some(y) = s.get("Y").and_then(Tag::as_i64) else { continue };
+ sections.insert(y as i32, (s, None));
+ }
+ let mut out = Vec::with_capacity(256);
+ for (i, h) in heights.iter().enumerate() {
+ if *h == 0 {
+ out.push(None);
+ continue;
+ }
+ let y = min_y + *h as i32 - 1;
+ let sy = y.div_euclid(16);
+ let Some((section, decoded)) = sections.get_mut(&sy) else {
+ out.push(None);
+ continue;
+ };
+ let (palette, data) = if version >= DATA_VERSION_1_18 {
+ let states = section.get("block_states");
+ (states.and_then(|s| s.get("palette")).and_then(Tag::as_list), states.and_then(|s| s.get("data")).and_then(Tag::as_longs))
+ } else {
+ (section.get("Palette").and_then(Tag::as_list), section.get("BlockStates").and_then(Tag::as_longs))
+ };
+ let Some(palette) = palette.filter(|p| !p.is_empty()) else {
+ out.push(None);
+ continue;
+ };
+ let index = if palette.len() == 1 {
+ 0
+ } else {
+ if decoded.is_none() {
+ let bits = (usize::BITS - (palette.len() - 1).leading_zeros()).max(4) as usize;
+ *decoded = data.and_then(|d| unpack(d, bits, 4096, spanning));
+ }
+ let (x, z, ly) = (i % 16, i / 16, y.rem_euclid(16) as usize);
+ decoded.as_ref().and_then(|d| d.get(ly * 256 + z * 16 + x)).copied().unwrap_or(0) as usize
+ };
+ // A palette entry is `{Name, Properties}`, or since Minecraft 26.1 just the name when the block has no properties.
+ let name = palette.get(index).and_then(|p| p.as_str().or_else(|| p.get("Name").and_then(Tag::as_str))).unwrap_or("minecraft:air");
+ out.push((!name.ends_with(":air") && !name.ends_with("cave_air")).then(|| (name.to_string(), y)));
+ }
+ Ok(out)
+}
+
+/// The NBT of the chunk at (`cx`, `cz`) inside a region file (coordinates within the region, 0..32).
+fn read_chunk(file: &mut fs::File, cx: usize, cz: usize) -> Option {
+ let mut header = [0u8; 4];
+ file.seek(SeekFrom::Start(((cx + cz * 32) * 4) as u64)).ok()?;
+ file.read_exact(&mut header).ok()?;
+ let offset = u32::from_be_bytes([0, header[0], header[1], header[2]]) as u64 * 4096;
+ if offset == 0 {
+ return None;
+ }
+ let mut head = [0u8; 5];
+ file.seek(SeekFrom::Start(offset)).ok()?;
+ file.read_exact(&mut head).ok()?;
+ let len = (u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize).checked_sub(1)?;
+ if len > MAX_CHUNK_BYTES {
+ return None;
+ }
+ let mut raw = vec![0u8; len];
+ file.read_exact(&mut raw).ok()?;
+ let mut data = Vec::new();
+ match head[4] {
+ 1 => flate2::read::GzDecoder::new(&raw[..]).take(32 * 1024 * 1024).read_to_end(&mut data).ok()?,
+ 2 => flate2::read::ZlibDecoder::new(&raw[..]).take(32 * 1024 * 1024).read_to_end(&mut data).ok()?,
+ 3 => {
+ data = raw;
+ data.len()
+ }
+ _ => return None,
+ };
+ nbt::parse_root(&data)
+}
+
+/// The spawn point of a world, from `level.dat` (0, 0 when it can't be read): `Data.spawn.pos` since Minecraft 26.1,
+/// `Data.SpawnX` / `SpawnZ` before.
+fn spawn_of(world: &Path) -> (i32, i32) {
+ let data = nbt::read_file(&world.join("level.dat")).and_then(|r| r.get("Data").cloned());
+ if let Some([x, _, z]) = data.as_ref().and_then(|d| d.get("spawn")?.get("pos")?.as_ints()).and_then(|p| <&[i32; 3]>::try_from(p).ok()) {
+ return (*x, *z);
+ }
+ let get = |k: &str| data.as_ref().and_then(|d| d.get(k)).and_then(Tag::as_i64).unwrap_or(0) as i32;
+ (get("SpawnX"), get("SpawnZ"))
+}
+
+/// The overworld's region folder: `dimensions/minecraft/overworld/region` since Minecraft 26.1, `region` before.
+fn region_dir(world: &Path) -> PathBuf {
+ let new = world.join("dimensions").join("minecraft").join("overworld").join("region");
+ if new.is_dir() { new } else { world.join("region") }
+}
+
+fn region_files(world: &Path, min: (i32, i32), max: (i32, i32)) -> Vec<(i32, i32, PathBuf)> {
+ let mut out = Vec::new();
+ let dir = region_dir(world);
+ for rz in min.1.div_euclid(512)..=max.1.div_euclid(512) {
+ for rx in min.0.div_euclid(512)..=max.0.div_euclid(512) {
+ let path = dir.join(format!("r.{rx}.{rz}.mca"));
+ if path.is_file() {
+ out.push((rx, rz, path));
+ }
+ }
+ }
+ out
+}
+
+fn newest_change(files: &[(i32, i32, PathBuf)]) -> Option {
+ files.iter().filter_map(|(_, _, p)| fs::metadata(p).and_then(|m| m.modified()).ok()).max()
+}
+
+/// Draws the map of `saves/` around its spawn into `cache_dir/.png`, unless that file is newer than
+/// the region files. `on_progress(done, total)` counts region files.
+pub fn render_map(game_dir: &Path, world: &str, cache_dir: &Path, mut on_progress: impl FnMut(u64, u64)) -> Result {
+ check_plain_name(world)?;
+ let dir = game_dir.join("saves").join(world);
+ if !dir.is_dir() {
+ return Err(Error::NotFound(format!("world {world}")));
+ }
+ let (sx, sz) = spawn_of(&dir);
+ // Snap to chunks, so the map lines up with them.
+ let (min_x, min_z) = ((sx - MAP_RADIUS).div_euclid(16) * 16, (sz - MAP_RADIUS).div_euclid(16) * 16);
+ let size = (MAP_RADIUS * 2) as u32;
+ let (max_x, max_z) = (min_x + size as i32 - 1, min_z + size as i32 - 1);
+ let regions = region_files(&dir, (min_x, min_z), (max_x, max_z));
+ if regions.is_empty() {
+ return Err(Error::Other("This world has no map yet: play in it once, then draw it.".into()));
+ }
+ fs::create_dir_all(cache_dir).map_err(|e| Error::io(cache_dir, e))?;
+ let out_path = cache_dir.join(format!("{world}.png"));
+ let fresh = match (fs::metadata(&out_path).and_then(|m| m.modified()).ok(), newest_change(®ions)) {
+ (Some(png), Some(regions)) => png >= regions,
+ _ => false,
+ };
+ let meta_path = cache_dir.join(format!("{world}.json"));
+ if fresh {
+ if let Some(map) = fs::read(&meta_path).ok().and_then(|b| serde_json::from_slice::(&b).ok()).and_then(|v| v.get("chunks")?.as_u64()) {
+ return Ok(WorldMap { path: out_path, min_x, min_z, size, chunks: map as u32 });
+ }
+ }
+
+ let (w, h) = (size as usize, size as usize);
+ let mut heights = vec![i32::MIN; w * h];
+ let mut colors = vec![[0u8; 3]; w * h];
+ let mut chunks = 0u32;
+ let total = regions.len() as u64;
+ let mut error = None;
+ for (n, (rx, rz, path)) in regions.iter().enumerate() {
+ on_progress(n as u64, total);
+ let Ok(mut file) = fs::File::open(path) else { continue };
+ for cz in 0..32 {
+ for cx in 0..32 {
+ let (bx, bz) = (rx * 512 + cx as i32 * 16, rz * 512 + cz as i32 * 16);
+ if bx + 15 < min_x || bz + 15 < min_z || bx > max_x || bz > max_z {
+ continue;
+ }
+ let Some(chunk) = read_chunk(&mut file, cx, cz) else { continue };
+ let surface = match chunk_surface(&chunk) {
+ Ok(s) => s,
+ Err(e) => {
+ error.get_or_insert(e);
+ continue;
+ }
+ };
+ chunks += 1;
+ for (i, top) in surface.into_iter().enumerate() {
+ let Some((name, y)) = top else { continue };
+ let (px, pz) = (bx + (i % 16) as i32 - min_x, bz + (i / 16) as i32 - min_z);
+ if px < 0 || pz < 0 || px >= w as i32 || pz >= h as i32 {
+ continue;
+ }
+ let at = pz as usize * w + px as usize;
+ heights[at] = y;
+ colors[at] = block_color(&name);
+ }
+ }
+ }
+ }
+ on_progress(total, total);
+ if chunks == 0 {
+ return Err(error.unwrap_or_else(|| Error::Other("This world has no map yet: play in it once, then draw it.".into())));
+ }
+
+ // Shade by the height difference with the block to the north, like the game's maps.
+ let mut rgba = vec![0u8; w * h * 4];
+ for z in 0..h {
+ for x in 0..w {
+ let at = z * w + x;
+ if heights[at] == i32::MIN {
+ continue;
+ }
+ let north = if z > 0 && heights[at - w] != i32::MIN { heights[at - w] } else { heights[at] };
+ let shade = match heights[at].cmp(&north) {
+ std::cmp::Ordering::Greater => 1.12,
+ std::cmp::Ordering::Less => 0.82,
+ std::cmp::Ordering::Equal => 1.0,
+ };
+ let c = colors[at];
+ for k in 0..3 {
+ rgba[at * 4 + k] = (c[k] as f32 * shade).min(255.0) as u8;
+ }
+ rgba[at * 4 + 3] = 255;
+ }
+ }
+ let tmp = out_path.with_extension("part");
+ {
+ let file = fs::File::create(&tmp).map_err(|e| Error::io(&tmp, e))?;
+ let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), size, size);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ let png_err = |e: png::EncodingError| Error::Other(format!("Couldn't write the map ({e})."));
+ let mut writer = encoder.write_header().map_err(png_err)?;
+ writer.write_image_data(&rgba).map_err(png_err)?;
+ writer.finish().map_err(png_err)?;
+ }
+ fs::rename(&tmp, &out_path).map_err(|e| Error::io(&out_path, e))?;
+ let _ = fs::write(&meta_path, format!("{{\"chunks\":{chunks}}}"));
+ Ok(WorldMap { path: out_path, min_x, min_z, size, chunks })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::temp_dir;
+ use std::io::Write;
+
+ fn pack(values: &[u32], bits: usize) -> Vec {
+ let per = 64 / bits;
+ let mut out = vec![0u64; values.len().div_ceil(per)];
+ for (i, v) in values.iter().enumerate() {
+ out[i / per] |= (*v as u64) << ((i % per) * bits);
+ }
+ out.into_iter().map(|v| v as i64).collect()
+ }
+
+ fn compound(items: Vec<(&str, Tag)>) -> Tag {
+ Tag::Compound(items.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
+ }
+
+ /// A 1.21 chunk: grass at y=64 everywhere but one column of water at y=62.
+ fn chunk() -> Tag {
+ let mut heights = vec![64 + 64 + 1; 256];
+ heights[17] = 62 + 64 + 1;
+ // Section 4 holds y 64..79: index 0 grass on its bottom layer, 1 air elsewhere.
+ let mut grass_layer = vec![1u32; 4096];
+ grass_layer[..256].iter_mut().for_each(|v| *v = 0);
+ let palette = |names: &[&str]| Tag::List(names.iter().map(|n| compound(vec![("Name", Tag::String(n.to_string()))])).collect());
+ let mut water_layer = vec![0u32; 4096];
+ water_layer[14 * 256 + 17] = 1;
+ compound(vec![
+ ("DataVersion", Tag::Int(3955)),
+ ("Heightmaps", compound(vec![("WORLD_SURFACE", Tag::LongArray(pack(&heights, 9)))])),
+ (
+ "sections",
+ Tag::List(vec![
+ compound(vec![
+ ("Y", Tag::Byte(4)),
+ ("block_states", compound(vec![("palette", palette(&["minecraft:grass_block", "minecraft:air"])), ("data", Tag::LongArray(pack(&grass_layer, 4)))])),
+ ]),
+ compound(vec![
+ ("Y", Tag::Byte(3)),
+ ("block_states", compound(vec![("palette", palette(&["minecraft:stone", "minecraft:water"])), ("data", Tag::LongArray(pack(&water_layer, 4)))])),
+ ]),
+ ]),
+ ),
+ ])
+ }
+
+ #[test]
+ fn surface_of_a_chunk() {
+ let surface = chunk_surface(&chunk()).unwrap();
+ assert_eq!(surface[0], Some(("minecraft:grass_block".to_string(), 64)));
+ assert_eq!(surface[17], Some(("minecraft:water".to_string(), 62)));
+ assert!(chunk_surface(&compound(vec![("DataVersion", Tag::Int(100))])).is_err());
+ }
+
+ #[test]
+ fn palette_of_plain_names() {
+ // Minecraft 26.1 writes a block without properties as its bare name.
+ fn names_only(tag: &mut Tag) {
+ match tag {
+ Tag::Compound(items) => items.iter_mut().for_each(|(k, v)| {
+ if k == "palette" {
+ if let Tag::List(entries) = v {
+ entries.iter_mut().for_each(|e| *e = Tag::String(e.get("Name").and_then(Tag::as_str).unwrap_or_default().to_string()));
+ }
+ } else {
+ names_only(v);
+ }
+ }),
+ Tag::List(items) => items.iter_mut().for_each(names_only),
+ _ => {}
+ }
+ }
+ let mut c = chunk();
+ names_only(&mut c);
+ let surface = chunk_surface(&c).unwrap();
+ assert_eq!(surface[0], Some(("minecraft:grass_block".to_string(), 64)));
+ assert_eq!(surface[17], Some(("minecraft:water".to_string(), 62)));
+ }
+
+ #[test]
+ fn unpacks_both_ways() {
+ let values: Vec = (0..256).map(|i| i % 300).collect();
+ assert_eq!(unpack(&pack(&values, 9), 9, 256, false).unwrap(), values);
+ // Spanning: 9-bit values laid end to end.
+ let mut longs = vec![0u64; (256 * 9usize).div_ceil(64)];
+ for (i, v) in values.iter().enumerate() {
+ let bit = i * 9;
+ longs[bit / 64] |= (*v as u64) << (bit % 64);
+ if bit % 64 + 9 > 64 {
+ longs[bit / 64 + 1] |= (*v as u64) >> (64 - bit % 64);
+ }
+ }
+ let longs: Vec = longs.into_iter().map(|v| v as i64).collect();
+ assert_eq!(unpack(&longs, 9, 256, true).unwrap(), values);
+ }
+
+ #[test]
+ fn reads_the_26_1_layout() {
+ let world = temp_dir("map-layout");
+ let new = world.join("dimensions/minecraft/overworld/region");
+ assert_eq!(region_dir(&world), world.join("region"));
+ fs::create_dir_all(&new).unwrap();
+ assert_eq!(region_dir(&world), new);
+ let level = Tag::Compound(vec![(
+ "Data".into(),
+ Tag::Compound(vec![("spawn".into(), Tag::Compound(vec![("pos".into(), Tag::IntArray(vec![-128, 64, 96]))]))]),
+ )]);
+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
+ gz.write_all(&nbt::write_root(&level)).unwrap();
+ fs::write(world.join("level.dat"), gz.finish().unwrap()).unwrap();
+ assert_eq!(spawn_of(&world), (-128, 96));
+ }
+
+ #[test]
+ fn renders_a_region() {
+ let game = temp_dir("map-render");
+ let world = game.join("saves/World");
+ fs::create_dir_all(world.join("region")).unwrap();
+ // One chunk at (0, 0) in r.0.0.mca, zlib-compressed.
+ let nbt = nbt::write_root(&chunk());
+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
+ z.write_all(&nbt).unwrap();
+ let body = z.finish().unwrap();
+ let mut region = vec![0u8; 8192];
+ region[0..4].copy_from_slice(&[0, 0, 2, 1]);
+ region.extend(((body.len() + 1) as u32).to_be_bytes());
+ region.push(2);
+ region.extend(&body);
+ region.resize(region.len().div_ceil(4096) * 4096, 0);
+ fs::write(world.join("region/r.0.0.mca"), region).unwrap();
+
+ let cache = game.join("maps");
+ let map = render_map(&game, "World", &cache, |_, _| {}).unwrap();
+ assert_eq!((map.chunks, map.size), (1, 768));
+ assert_eq!((map.min_x, map.min_z), (-384, -384));
+ let decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(&map.path).unwrap()));
+ let mut reader = decoder.read_info().unwrap();
+ let mut buf = vec![0; reader.output_buffer_size().unwrap()];
+ reader.next_frame(&mut buf).unwrap();
+ let px = |x: usize, z: usize| &buf[(z * 768 + x) * 4..(z * 768 + x) * 4 + 4];
+ assert_eq!(px(384, 384)[3], 255, "block (0, 0) is drawn");
+ assert_eq!(px(0, 0)[3], 0, "ungenerated chunks stay transparent");
+ // The second call reads the cache.
+ assert_eq!(render_map(&game, "World", &cache, |_, _| {}).unwrap().chunks, 1);
+ assert!(render_map(&game, "Nope", &cache, |_, _| {}).is_err());
+ }
+}
+
diff --git a/crates/cubby-instance/src/memory.rs b/crates/cubby-instance/src/memory.rs
new file mode 100644
index 0000000..9c0d41d
--- /dev/null
+++ b/crates/cubby-instance/src/memory.rs
@@ -0,0 +1,73 @@
+//! How much memory to give the game when the player lets Cubby choose.
+
+use std::path::Path;
+
+const STEP_MB: u32 = 512;
+
+/// Number of mods the game will load: `.jar` files in `/mods` (turned-off `.jar.disabled` don't count).
+pub fn count_enabled_mods(game_dir: &Path) -> usize {
+ let Ok(rd) = std::fs::read_dir(game_dir.join("mods")) else {
+ return 0;
+ };
+ rd.flatten()
+ .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
+ .filter(|e| {
+ e.file_name()
+ .to_string_lossy()
+ .to_lowercase()
+ .ends_with(".jar")
+ })
+ .count()
+}
+
+/// Maximum heap for an instance with `mods` mods on a computer with `total_mb` of memory.
+///
+/// The steps follow what modpack authors usually ask for: Vanilla runs well in 2 GB, a few dozen mods
+/// in 3 to 4 GB, a big pack in 6 to 8 GB. More than that only makes garbage collection pauses longer.
+/// The game never gets more than half of the computer's memory, so the system and Cubby keep enough.
+pub fn recommended_memory_mb(total_mb: u64, mods: usize) -> u32 {
+ let wanted: u32 = match mods {
+ 0 => 2048,
+ 1..=30 => 3072,
+ 31..=100 => 4096,
+ 101..=200 => 6144,
+ _ => 8192,
+ };
+ if total_mb == 0 {
+ return wanted;
+ }
+ let half = u32::try_from(total_mb / 2).unwrap_or(u32::MAX);
+ let cap = (half / STEP_MB * STEP_MB).max(1024);
+ wanted.min(cap)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::temp_dir;
+
+ #[test]
+ fn grows_with_mods_and_stays_under_half() {
+ assert_eq!(recommended_memory_mb(16_384, 0), 2048);
+ assert_eq!(recommended_memory_mb(16_384, 12), 3072);
+ assert_eq!(recommended_memory_mb(16_384, 80), 4096);
+ assert_eq!(recommended_memory_mb(16_384, 150), 6144);
+ assert_eq!(recommended_memory_mb(32_768, 400), 8192);
+ assert_eq!(recommended_memory_mb(8_192, 400), 4096);
+ assert_eq!(recommended_memory_mb(6_000, 400), 2560);
+ assert_eq!(recommended_memory_mb(1_500, 0), 1024);
+ assert_eq!(recommended_memory_mb(0, 150), 6144);
+ }
+
+ #[test]
+ fn counts_enabled_jars_only() {
+ let dir = temp_dir("memory-mods");
+ let mods = dir.join("mods");
+ std::fs::create_dir_all(mods.join("sub.jar")).unwrap();
+ for name in ["a.jar", "B.JAR", "c.jar.disabled", "readme.txt"] {
+ std::fs::write(mods.join(name), "x").unwrap();
+ }
+ assert_eq!(count_enabled_mods(&dir), 2);
+ assert_eq!(count_enabled_mods(&dir.join("nope")), 0);
+ }
+}
diff --git a/crates/cubby-instance/src/nbt.rs b/crates/cubby-instance/src/nbt.rs
index 4878253..06d3a31 100644
--- a/crates/cubby-instance/src/nbt.rs
+++ b/crates/cubby-instance/src/nbt.rs
@@ -18,8 +18,12 @@ pub(crate) enum Tag {
String(String),
List(Vec),
Compound(Vec<(String, Tag)>),
- /// Byte, int or long array.
+ /// Byte array (its payload is skipped).
Array,
+ /// Int array: kept, `level.dat` stores the spawn point in one since Minecraft 26.1.
+ IntArray(Vec),
+ /// Long array: kept, the world map reads block states and heightmaps from them.
+ LongArray(Vec),
}
impl Tag {
@@ -37,6 +41,27 @@ impl Tag {
}
}
+ pub(crate) fn as_list(&self) -> Option<&[Tag]> {
+ match self {
+ Tag::List(items) => Some(items),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn as_longs(&self) -> Option<&[i64]> {
+ match self {
+ Tag::LongArray(values) => Some(values),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn as_ints(&self) -> Option<&[i32]> {
+ match self {
+ Tag::IntArray(values) => Some(values),
+ _ => None,
+ }
+ }
+
pub(crate) fn as_i64(&self) -> Option {
match self {
Tag::Byte(v) => Some(*v as i64),
@@ -77,7 +102,7 @@ pub(crate) fn parse_root(data: &[u8]) -> Option {
///
/// Strings are written as plain UTF-8, which equals Java's modified UTF-8 for text without NUL or
/// supplementary characters; longer strings are truncated to the 65535-byte limit on a char boundary.
-/// Arrays (which the reader does not keep) cannot be written and are emitted as empty arrays.
+/// Byte arrays (which the reader does not keep) cannot be written and are emitted as empty arrays.
pub(crate) fn write_root(root: &Tag) -> Vec {
let mut out = vec![10];
write_name(&mut out, "");
@@ -94,6 +119,8 @@ fn tag_id(tag: &Tag) -> u8 {
Tag::Float(_) => 5,
Tag::Double(_) => 6,
Tag::Array => 7,
+ Tag::IntArray(_) => 11,
+ Tag::LongArray(_) => 12,
Tag::String(_) => 8,
Tag::List(_) => 9,
Tag::Compound(_) => 10,
@@ -118,6 +145,18 @@ fn write_payload(out: &mut Vec, tag: &Tag) {
Tag::Float(v) => out.extend(v.to_be_bytes()),
Tag::Double(v) => out.extend(v.to_be_bytes()),
Tag::Array => out.extend(0i32.to_be_bytes()),
+ Tag::IntArray(values) => {
+ out.extend((values.len() as i32).to_be_bytes());
+ for v in values {
+ out.extend(v.to_be_bytes());
+ }
+ }
+ Tag::LongArray(values) => {
+ out.extend((values.len() as i32).to_be_bytes());
+ for v in values {
+ out.extend(v.to_be_bytes());
+ }
+ }
Tag::String(s) => write_name(out, s),
Tag::List(items) => {
out.push(items.first().map(tag_id).unwrap_or(0));
@@ -212,10 +251,15 @@ impl Reader<'_> {
}
Tag::Compound(items)
}
- 11 | 12 => {
+ 11 => {
let n = self.len()?;
- self.take(n.checked_mul(if ty == 11 { 4 } else { 8 })?)?;
- Tag::Array
+ let bytes = self.take(n.checked_mul(4)?)?;
+ Tag::IntArray(bytes.as_chunks::<4>().0.iter().map(|c| i32::from_be_bytes(*c)).collect())
+ }
+ 12 => {
+ let n = self.len()?;
+ let bytes = self.take(n.checked_mul(8)?)?;
+ Tag::LongArray(bytes.as_chunks::<8>().0.iter().map(|c| i64::from_be_bytes(*c)).collect())
}
_ => return None,
})
diff --git a/crates/cubby-instance/src/options.rs b/crates/cubby-instance/src/options.rs
new file mode 100644
index 0000000..e8b46bb
--- /dev/null
+++ b/crates/cubby-instance/src/options.rs
@@ -0,0 +1,124 @@
+//! Sharing the game's options between instances: video and sound options, key bindings and the server list.
+
+use std::fs;
+use std::path::Path;
+
+use cubby_common::{Error, Result};
+use serde::Deserialize;
+
+use crate::util::atomic_write;
+
+/// What to copy from one instance to another.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct OptionsCopy {
+ /// Everything in `options.txt` but the key bindings (video, sound, language, resource packs...).
+ pub options: bool,
+ /// The `key_*` lines of `options.txt`.
+ pub keys: bool,
+ /// `servers.dat`.
+ pub servers: bool,
+}
+
+/// Lines that belong to the target: the format version (the game upgrades old options from it) and the
+/// resource packs, which name files only the source has.
+fn kept_by_target(key: &str) -> bool {
+ matches!(key, "version" | "resourcePacks" | "incompatibleResourcePacks")
+}
+
+fn is_key(key: &str) -> bool {
+ key.starts_with("key_")
+}
+
+fn parse(text: &str) -> Vec<(String, String)> {
+ text.lines()
+ .filter_map(|l| l.split_once(':').map(|(k, v)| (k.to_string(), v.to_string())))
+ .collect()
+}
+
+/// `target`'s options with the chosen part of `source` laid over them. Keys `source` doesn't have stay as
+/// they are; keys only `source` has are added at the end.
+pub fn merge_options(target: &str, source: &str, options: bool, keys: bool) -> String {
+ let wanted = |k: &str| !kept_by_target(k) && if is_key(k) { keys } else { options };
+ let from: Vec<(String, String)> = parse(source).into_iter().filter(|(k, _)| wanted(k)).collect();
+ let mut out: Vec<(String, String)> = parse(target);
+ for (k, v) in from {
+ match out.iter_mut().find(|(ok, _)| *ok == k) {
+ Some(slot) => slot.1 = v,
+ None => out.push((k, v)),
+ }
+ }
+ let mut text: String = out.into_iter().map(|(k, v)| format!("{k}:{v}\n")).collect();
+ if text.is_empty() {
+ text.push('\n');
+ }
+ text
+}
+
+/// Copies options, key bindings and/or the server list from one game folder to another.
+/// Returns what was copied, so the caller can say when the source had nothing.
+pub fn copy_options(source_game: &Path, target_game: &Path, what: OptionsCopy) -> Result {
+ let mut done = OptionsCopy::default();
+ if what.options || what.keys {
+ let src = source_game.join("options.txt");
+ if let Ok(source) = fs::read_to_string(&src) {
+ let dest = target_game.join("options.txt");
+ let target = fs::read_to_string(&dest).unwrap_or_default();
+ fs::create_dir_all(target_game).map_err(|e| Error::io(target_game, e))?;
+ atomic_write(&dest, merge_options(&target, &source, what.options, what.keys).as_bytes())?;
+ done.options = what.options;
+ done.keys = what.keys;
+ }
+ }
+ if what.servers {
+ let src = source_game.join("servers.dat");
+ if src.is_file() {
+ fs::create_dir_all(target_game).map_err(|e| Error::io(target_game, e))?;
+ let data = fs::read(&src).map_err(|e| Error::io(&src, e))?;
+ atomic_write(&target_game.join("servers.dat"), &data)?;
+ done.servers = true;
+ }
+ }
+ Ok(done)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::temp_dir;
+
+ const SOURCE: &str = "version:3955\nfov:1.0\nguiScale:3\nresourcePacks:[\"file/Faithful.zip\"]\nkey_key.jump:key.keyboard.space\nkey_key.sprint:key.keyboard.left.control\nkey_key.zoom:key.keyboard.c\n";
+ const TARGET: &str = "version:3700\nfov:0.0\nresourcePacks:[\"vanilla\"]\nkey_key.jump:key.keyboard.j\nrenderDistance:8\n";
+
+ #[test]
+ fn only_keys() {
+ let out = merge_options(TARGET, SOURCE, false, true);
+ assert_eq!(
+ out,
+ "version:3700\nfov:0.0\nresourcePacks:[\"vanilla\"]\nkey_key.jump:key.keyboard.space\nrenderDistance:8\nkey_key.sprint:key.keyboard.left.control\nkey_key.zoom:key.keyboard.c\n"
+ );
+ }
+
+ #[test]
+ fn only_options_keeps_version_and_packs() {
+ let out = merge_options(TARGET, SOURCE, true, false);
+ assert!(out.starts_with("version:3700\nfov:1.0\nresourcePacks:[\"vanilla\"]\nkey_key.jump:key.keyboard.j\n"), "{out}");
+ assert!(out.contains("guiScale:3\n"));
+ assert!(!out.contains("key.keyboard.space"));
+ }
+
+ #[test]
+ fn copies_files() {
+ let dir = temp_dir("options-copy");
+ let (a, b) = (dir.join("a"), dir.join("b"));
+ fs::create_dir_all(&a).unwrap();
+ fs::write(a.join("options.txt"), SOURCE).unwrap();
+ fs::write(a.join("servers.dat"), [10u8, 0, 0, 0]).unwrap();
+ let all = OptionsCopy { options: true, keys: true, servers: true };
+ assert_eq!(copy_options(&a, &b, all).unwrap(), all);
+ assert!(fs::read_to_string(b.join("options.txt")).unwrap().contains("key_key.zoom"));
+ assert_eq!(fs::read(b.join("servers.dat")).unwrap(), [10, 0, 0, 0]);
+ // A source without options copies nothing.
+ assert_eq!(copy_options(&dir.join("empty"), &b, all).unwrap(), OptionsCopy::default());
+ }
+}
diff --git a/crates/cubby-instance/src/settings.rs b/crates/cubby-instance/src/settings.rs
index 8b3ff2c..fdaf77b 100644
--- a/crates/cubby-instance/src/settings.rs
+++ b/crates/cubby-instance/src/settings.rs
@@ -33,6 +33,8 @@ pub enum OnLaunch {
pub struct JavaSettings {
/// Pick or download a suitable runtime automatically.
pub auto: bool,
+ /// Give each instance the memory its mods need (see [`crate::recommended_memory_mb`]) instead of `max_memory_mb`.
+ pub auto_memory: bool,
pub min_memory_mb: u32,
pub max_memory_mb: u32,
pub jvm_args: String,
@@ -40,7 +42,7 @@ pub struct JavaSettings {
impl Default for JavaSettings {
fn default() -> Self {
- Self { auto: true, min_memory_mb: 1024, max_memory_mb: 4096, jvm_args: String::new() }
+ Self { auto: true, auto_memory: true, min_memory_mb: 1024, max_memory_mb: 4096, jvm_args: String::new() }
}
}
@@ -156,6 +158,8 @@ pub struct Settings {
pub curseforge_api_key: Option,
/// The first-run onboarding has been completed.
pub onboarded: bool,
+ /// Show the instance being played on the player's Discord profile.
+ pub discord_presence: bool,
}
impl Default for Settings {
@@ -180,6 +184,7 @@ impl Default for Settings {
updates: UpdateSettings::default(),
curseforge_api_key: None,
onboarded: false,
+ discord_presence: true,
}
}
}
diff --git a/crates/cubby-instance/src/shortcut.rs b/crates/cubby-instance/src/shortcut.rs
new file mode 100644
index 0000000..c0a08bb
--- /dev/null
+++ b/crates/cubby-instance/src/shortcut.rs
@@ -0,0 +1,149 @@
+//! Desktop shortcuts that start an instance: they open `cubby://play/`, which Cubby handles by
+//! starting the game (and Cubby itself, when it isn't running).
+//!
+//! Windows gets an Internet shortcut (`.url`), Linux a `.desktop` file, macOS a tiny app bundle whose
+//! script opens the link (a `.webloc` would open the browser first).
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use cubby_common::{Error, Result};
+
+/// The link a shortcut opens.
+pub fn play_link(id: &str) -> String {
+ format!("cubby://play/{id}")
+}
+
+/// A name usable as a file name on every system.
+pub fn shortcut_file_stem(name: &str) -> String {
+ let cleaned: String = name
+ .trim()
+ .chars()
+ .map(|c| if c.is_control() || "\\/:*?\"<>|".contains(c) { ' ' } else { c })
+ .collect();
+ let cleaned = cleaned.split_whitespace().collect::>().join(" ");
+ let cleaned = cleaned.trim_matches('.').to_string();
+ if cleaned.is_empty() { "Minecraft".into() } else { cleaned }
+}
+
+/// Contents of a Windows `.url` file. `icon` is an `.exe` or `.ico` to show.
+pub fn windows_url_file(id: &str, icon: Option<&Path>) -> String {
+ let mut text = format!("[InternetShortcut]\r\nURL={}\r\n", play_link(id));
+ if let Some(icon) = icon {
+ text.push_str(&format!("IconFile={}\r\nIconIndex=0\r\n", icon.display()));
+ }
+ text
+}
+
+/// Contents of a Linux `.desktop` file.
+pub fn desktop_entry(id: &str, name: &str, icon: Option<&Path>) -> String {
+ let mut text = format!(
+ "[Desktop Entry]\nType=Application\nName={}\nComment=Play {} with Cubby\nExec=xdg-open {}\nTerminal=false\nCategories=Game;\n",
+ name.replace('\n', " "),
+ name.replace('\n', " "),
+ play_link(id)
+ );
+ if let Some(icon) = icon {
+ text.push_str(&format!("Icon={}\n", icon.display()));
+ }
+ text
+}
+
+fn xml_escape(s: &str) -> String {
+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
+}
+
+/// `Info.plist` of the macOS shortcut app.
+pub fn macos_info_plist(id: &str, name: &str, has_icon: bool) -> String {
+ let icon = if has_icon { "\tCFBundleIconFile\n\tAppIcon\n" } else { "" };
+ format!(
+ "\n\n\
+\n\n\tCFBundleExecutable\n\tplay\n{icon}\
+\tCFBundleIdentifier\n\tcom.cubbylauncher.shortcut.{}\n\tCFBundleName\n\t{}\n\
+\tCFBundlePackageType\n\tAPPL\n\tLSUIElement\n\t\n\n\n",
+ xml_escape(&id.replace(|c: char| !c.is_ascii_alphanumeric() && c != '-', "-")),
+ xml_escape(name)
+ )
+}
+
+/// A path in `dir` named `stem` + `ext` that doesn't exist yet ("Pack 2.url" when "Pack.url" does).
+fn free_path(dir: &Path, stem: &str, ext: &str) -> PathBuf {
+ let mut path = dir.join(format!("{stem}{ext}"));
+ let mut n = 2;
+ while path.exists() {
+ path = dir.join(format!("{stem} {n}{ext}"));
+ n += 1;
+ }
+ path
+}
+
+/// Writes a shortcut for the current system into `dir` (the Desktop). `icon`: Cubby's icon file when
+/// known (`.exe` or `.ico` on Windows, `.icns` on macOS, `.png` on Linux). Returns the shortcut's path.
+pub fn create_shortcut(dir: &Path, id: &str, name: &str, icon: Option<&Path>) -> Result {
+ fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
+ let stem = shortcut_file_stem(name);
+ if cfg!(target_os = "windows") {
+ let path = free_path(dir, &stem, ".url");
+ fs::write(&path, windows_url_file(id, icon)).map_err(|e| Error::io(&path, e))?;
+ Ok(path)
+ } else if cfg!(target_os = "macos") {
+ let app = free_path(dir, &stem, ".app");
+ let contents = app.join("Contents");
+ let macos = contents.join("MacOS");
+ fs::create_dir_all(&macos).map_err(|e| Error::io(&macos, e))?;
+ let has_icon = match icon {
+ Some(icon) if icon.is_file() => {
+ let resources = contents.join("Resources");
+ fs::create_dir_all(&resources).map_err(|e| Error::io(&resources, e))?;
+ fs::copy(icon, resources.join("AppIcon.icns")).is_ok()
+ }
+ _ => false,
+ };
+ fs::write(contents.join("Info.plist"), macos_info_plist(id, name, has_icon)).map_err(|e| Error::io(&contents, e))?;
+ let script = macos.join("play");
+ fs::write(&script, format!("#!/bin/sh\nexec /usr/bin/open '{}'\n", play_link(id).replace('\'', ""))).map_err(|e| Error::io(&script, e))?;
+ set_executable(&script)?;
+ Ok(app)
+ } else {
+ let path = free_path(dir, &stem, ".desktop");
+ fs::write(&path, desktop_entry(id, name, icon)).map_err(|e| Error::io(&path, e))?;
+ set_executable(&path)?;
+ Ok(path)
+ }
+}
+
+#[cfg(unix)]
+fn set_executable(path: &Path) -> Result<()> {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(path, fs::Permissions::from_mode(0o755)).map_err(|e| Error::io(path, e))
+}
+
+#[cfg(not(unix))]
+fn set_executable(_path: &Path) -> Result<()> {
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::temp_dir;
+
+ #[test]
+ fn file_names_and_contents() {
+ assert_eq!(shortcut_file_stem(" All: the / Mods? "), "All the Mods");
+ assert_eq!(shortcut_file_stem("..."), "Minecraft");
+ assert!(windows_url_file("my-pack", Some(Path::new("C:/Cubby/cubby.exe"))).contains("URL=cubby://play/my-pack\r\nIconFile=C:/Cubby/cubby.exe"));
+ assert!(desktop_entry("my-pack", "My Pack", None).contains("Exec=xdg-open cubby://play/my-pack\n"));
+ let plist = macos_info_plist("my-pack", "Tom & Jerry", true);
+ assert!(plist.contains("Tom & Jerry") && plist.contains("AppIcon"));
+ }
+
+ #[test]
+ fn writes_one_per_call() {
+ let dir = temp_dir("shortcut");
+ let a = create_shortcut(&dir, "my-pack", "My Pack", None).unwrap();
+ let b = create_shortcut(&dir, "my-pack", "My Pack", None).unwrap();
+ assert_ne!(a, b);
+ assert!(a.exists() && b.exists());
+ }
+}
diff --git a/crates/cubby-instance/src/update_backups.rs b/crates/cubby-instance/src/update_backups.rs
new file mode 100644
index 0000000..ce70932
--- /dev/null
+++ b/crates/cubby-instance/src/update_backups.rs
@@ -0,0 +1,210 @@
+//! Undoing a content update.
+//!
+//! Before an update replaces files, the old ones are copied to `/backups/content-//`.
+//! Once it is done, [`record_update`] writes `cubby-update.json` there: which old file became which new one.
+//! [`InstanceStore::undo_update`] puts the old files back, moves the new ones to `/.trash//`
+//! and renames the backup `content--undone`, so it isn't offered again.
+
+use std::fs;
+use std::path::Path;
+
+use chrono::{DateTime, Utc};
+use cubby_common::{Error, Result};
+use serde::{Deserialize, Serialize};
+
+use crate::store::InstanceStore;
+use crate::util::{atomic_write, check_plain_name, move_to_trash};
+
+const MANIFEST: &str = "cubby-update.json";
+const PREFIX: &str = "content-";
+const UNDONE: &str = "-undone";
+const FOLDERS: [&str; 3] = ["mods", "resourcepacks", "shaderpacks"];
+
+/// One file an update replaced.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdatedFile {
+ /// "mods", "resourcepacks" or "shaderpacks".
+ pub folder: String,
+ /// The file before the update (kept in the backup).
+ pub old: String,
+ /// The file the update put in its place.
+ pub new: String,
+}
+
+/// An update that can be undone.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateBackup {
+ /// Folder name in `/backups/`.
+ pub name: String,
+ pub created: DateTime,
+ pub files: Vec,
+}
+
+/// Writes the manifest of an update whose old files were copied to `backup_dir`. `renamed` lists the files
+/// replaced by a file with another name as `(folder, old, new)`; the others kept their name. Does nothing when
+/// the update backed up nothing.
+pub fn record_update(backup_dir: &Path, renamed: &[(String, String, String)]) -> Result<()> {
+ let mut files = Vec::new();
+ for folder in FOLDERS {
+ let Ok(rd) = fs::read_dir(backup_dir.join(folder)) else { continue };
+ let mut names: Vec = rd.flatten().filter(|e| e.path().is_file()).map(|e| e.file_name().to_string_lossy().into_owned()).collect();
+ names.sort();
+ for old in names {
+ let new = renamed.iter().find(|(f, o, _)| f == folder && *o == old).map(|(_, _, n)| n.clone()).unwrap_or_else(|| old.clone());
+ files.push(UpdatedFile { folder: folder.to_string(), old, new });
+ }
+ }
+ if files.is_empty() {
+ return Ok(());
+ }
+ let manifest = UpdateBackup { name: dir_name(backup_dir), created: Utc::now(), files };
+ let text = serde_json::to_string_pretty(&manifest).map_err(|e| Error::Other(e.to_string()))?;
+ atomic_write(&backup_dir.join(MANIFEST), text.as_bytes())
+}
+
+fn dir_name(dir: &Path) -> String {
+ dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
+}
+
+fn read_manifest(dir: &Path) -> Option {
+ let text = fs::read_to_string(dir.join(MANIFEST)).ok()?;
+ let mut backup: UpdateBackup = serde_json::from_str(&text).ok()?;
+ backup.name = dir_name(dir);
+ Some(backup)
+}
+
+/// Updates of a backups folder that can be undone, newest first.
+pub fn list_update_backups(backups: &Path) -> Vec {
+ let Ok(rd) = fs::read_dir(backups) else { return Vec::new() };
+ let mut out: Vec = rd
+ .flatten()
+ .filter(|e| {
+ let name = e.file_name().to_string_lossy().into_owned();
+ name.starts_with(PREFIX) && !name.ends_with(UNDONE) && e.path().is_dir()
+ })
+ .filter_map(|e| read_manifest(&e.path()))
+ .collect();
+ out.sort_by(|a, b| b.created.cmp(&a.created).then_with(|| b.name.cmp(&a.name)));
+ out
+}
+
+/// Puts back the files an update replaced. Returns how many files came back.
+pub fn undo_update(game_dir: &Path, backups: &Path, name: &str) -> Result {
+ check_plain_name(name)?;
+ if !name.starts_with(PREFIX) || name.ends_with(UNDONE) {
+ return Err(Error::NotFound(format!("update backup {name}")));
+ }
+ let dir = backups.join(name);
+ let backup = read_manifest(&dir).ok_or_else(|| Error::NotFound(format!("update backup {name}")))?;
+ // Check everything first, so a missing backup file doesn't leave the instance half undone.
+ for f in &backup.files {
+ check_plain_name(&f.old)?;
+ check_plain_name(&f.new)?;
+ if !FOLDERS.contains(&f.folder.as_str()) {
+ return Err(Error::Other(format!("{} isn't a content folder.", f.folder)));
+ }
+ if !dir.join(&f.folder).join(&f.old).is_file() {
+ return Err(Error::Other(format!("The backup of {} is missing, so this update can't be undone.", f.old)));
+ }
+ }
+ for f in &backup.files {
+ let folder = game_dir.join(&f.folder);
+ fs::create_dir_all(&folder).map_err(|e| Error::io(&folder, e))?;
+ // The new file may have been turned off or on since: look for both names.
+ let new_names = [f.new.clone(), toggled(&f.new)];
+ for new in &new_names {
+ let path = folder.join(new);
+ if path.is_file() && *new != f.old {
+ move_to_trash(&path, &game_dir.join(".trash").join(&f.folder), new)?;
+ }
+ }
+ let src = dir.join(&f.folder).join(&f.old);
+ fs::copy(&src, folder.join(&f.old)).map_err(|e| Error::io(&src, e))?;
+ }
+ let done = backups.join(format!("{name}{UNDONE}"));
+ fs::rename(&dir, &done).map_err(|e| Error::io(&dir, e))?;
+ Ok(backup.files.len())
+}
+
+/// `a.jar` ↔ `a.jar.disabled`.
+fn toggled(name: &str) -> String {
+ match name.strip_suffix(".disabled") {
+ Some(base) => base.to_string(),
+ None => format!("{name}.disabled"),
+ }
+}
+
+impl InstanceStore {
+ /// Updates of an instance that can be undone, newest first.
+ pub fn list_update_backups(&self, id: &str) -> Result> {
+ self.get(id)?;
+ Ok(list_update_backups(&self.backups_dir(id)?))
+ }
+
+ /// Puts back the files replaced by the update backed up in `name`. Returns how many came back.
+ pub fn undo_update(&self, id: &str, name: &str) -> Result {
+ let inst = self.get(id)?;
+ undo_update(&self.game_dir(&inst), &self.backups_dir(id)?, name)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::temp_dir;
+
+ #[test]
+ fn records_lists_and_undoes() {
+ let root = temp_dir("update-undo");
+ let game = root.join(".minecraft");
+ let backups = root.join("backups");
+ let backup = backups.join("content-20261108-101500");
+ fs::create_dir_all(game.join("mods")).unwrap();
+ fs::create_dir_all(backup.join("mods")).unwrap();
+ fs::create_dir_all(backup.join("resourcepacks")).unwrap();
+ // sodium was renamed by the update, the pack kept its name, lithium was turned off after.
+ fs::write(backup.join("mods/sodium-0.5.jar"), "old sodium").unwrap();
+ fs::write(backup.join("mods/lithium-1.jar"), "old lithium").unwrap();
+ fs::write(backup.join("resourcepacks/Faithful.zip"), "old pack").unwrap();
+ fs::write(game.join("mods/sodium-0.6.jar"), "new sodium").unwrap();
+ fs::write(game.join("mods/lithium-2.jar.disabled"), "new lithium").unwrap();
+ fs::create_dir_all(game.join("resourcepacks")).unwrap();
+ fs::write(game.join("resourcepacks/Faithful.zip"), "new pack").unwrap();
+
+ let renamed = vec![
+ ("mods".to_string(), "sodium-0.5.jar".to_string(), "sodium-0.6.jar".to_string()),
+ ("mods".to_string(), "lithium-1.jar".to_string(), "lithium-2.jar".to_string()),
+ ];
+ record_update(&backup, &renamed).unwrap();
+ record_update(&backups.join("content-empty"), &[]).unwrap();
+ let list = list_update_backups(&backups);
+ assert_eq!(list.len(), 1);
+ assert_eq!(list[0].name, "content-20261108-101500");
+ assert_eq!(list[0].files.len(), 3);
+
+ assert_eq!(undo_update(&game, &backups, "content-20261108-101500").unwrap(), 3);
+ assert_eq!(fs::read_to_string(game.join("mods/sodium-0.5.jar")).unwrap(), "old sodium");
+ assert_eq!(fs::read_to_string(game.join("mods/lithium-1.jar")).unwrap(), "old lithium");
+ assert_eq!(fs::read_to_string(game.join("resourcepacks/Faithful.zip")).unwrap(), "old pack");
+ assert!(!game.join("mods/sodium-0.6.jar").exists());
+ assert!(!game.join("mods/lithium-2.jar.disabled").exists());
+ assert!(game.join(".trash/mods").read_dir().unwrap().count() >= 2);
+ assert!(list_update_backups(&backups).is_empty());
+ assert!(undo_update(&game, &backups, "content-20261108-101500").is_err());
+ assert!(undo_update(&game, &backups, "../x").is_err());
+ }
+
+ #[test]
+ fn refuses_when_a_backup_file_is_missing() {
+ let root = temp_dir("update-undo-missing");
+ let backups = root.join("backups");
+ let backup = backups.join("content-1");
+ fs::create_dir_all(backup.join("mods")).unwrap();
+ fs::write(backup.join("mods/a.jar"), "a").unwrap();
+ record_update(&backup, &[]).unwrap();
+ fs::remove_file(backup.join("mods/a.jar")).unwrap();
+ assert!(undo_update(&root.join(".minecraft"), &backups, "content-1").is_err());
+ }
+}
diff --git a/crates/cubby-launch/src/ping.rs b/crates/cubby-launch/src/ping.rs
index 3eb4726..c89760c 100644
--- a/crates/cubby-launch/src/ping.rs
+++ b/crates/cubby-launch/src/ping.rs
@@ -22,6 +22,10 @@ pub struct ServerStatus {
pub online: bool,
/// Message of the day as plain text (formatting codes stripped, newlines kept).
pub motd: String,
+ /// Message of the day with its colours and styles as `§` codes, the way the game draws it: `§0`–`§f` colours,
+ /// `§l` bold, `§o` italic, `§n` underlined, `§m` struck, `§k` obfuscated, `§r` reset, and `§#rrggbb` for a
+ /// hex colour from a JSON component.
+ pub motd_formatted: String,
pub players_online: u32,
pub players_max: u32,
pub version: Option,
@@ -38,7 +42,7 @@ pub struct ServerStatus {
impl ServerStatus {
fn offline() -> Self {
- Self { online: false, motd: String::new(), players_online: 0, players_max: 0, version: None, protocol: None, asked_protocol: PROTOCOL_VERSION, ping_ms: None, favicon: None }
+ Self { online: false, motd: String::new(), motd_formatted: String::new(), players_online: 0, players_max: 0, version: None, protocol: None, asked_protocol: PROTOCOL_VERSION, ping_ms: None, favicon: None }
}
}
@@ -143,6 +147,7 @@ fn parse_status(value: &Value) -> ServerStatus {
ServerStatus {
online: true,
motd: value.get("description").map(flatten_motd).unwrap_or_default(),
+ motd_formatted: value.get("description").map(formatted_motd).unwrap_or_default(),
players_online: players["online"].as_u64().unwrap_or(0) as u32,
players_max: players["max"].as_u64().unwrap_or(0) as u32,
version: value["version"]["name"].as_str().map(str::to_string),
@@ -179,6 +184,91 @@ fn push_component(value: &Value, out: &mut String) {
}
}
+/// Colours and styles a chat component sets, inherited by its `extra` children.
+#[derive(Debug, Clone, Default)]
+struct Style {
+ color: Option,
+ bold: bool,
+ italic: bool,
+ underlined: bool,
+ strikethrough: bool,
+ obfuscated: bool,
+}
+
+impl Style {
+ fn with(&self, map: &serde_json::Map) -> Style {
+ let flag = |key: &str, current: bool| map.get(key).and_then(Value::as_bool).unwrap_or(current);
+ Style {
+ color: map.get("color").and_then(Value::as_str).and_then(color_code).or_else(|| self.color.clone()),
+ bold: flag("bold", self.bold),
+ italic: flag("italic", self.italic),
+ underlined: flag("underlined", self.underlined),
+ strikethrough: flag("strikethrough", self.strikethrough),
+ obfuscated: flag("obfuscated", self.obfuscated),
+ }
+ }
+
+ /// `§r`, then the colour, then the styles: what puts the text in this style whatever came before.
+ fn codes(&self) -> String {
+ let mut out = String::from("§r");
+ if let Some(color) = &self.color {
+ out.push_str(color);
+ }
+ for (on, code) in [(self.obfuscated, 'k'), (self.bold, 'l'), (self.strikethrough, 'm'), (self.underlined, 'n'), (self.italic, 'o')] {
+ if on {
+ out.push('§');
+ out.push(code);
+ }
+ }
+ out
+ }
+}
+
+/// `§` code of a JSON colour: a name (`gold`) or `#rrggbb`.
+fn color_code(name: &str) -> Option {
+ const NAMES: [&str; 16] = [
+ "black", "dark_blue", "dark_green", "dark_aqua", "dark_red", "dark_purple", "gold", "gray",
+ "dark_gray", "blue", "green", "aqua", "red", "light_purple", "yellow", "white",
+ ];
+ if let Some(i) = NAMES.iter().position(|n| *n == name) {
+ return Some(format!("§{:x}", i));
+ }
+ let hex = name.strip_prefix('#')?;
+ (hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit())).then(|| format!("§#{}", hex.to_ascii_lowercase()))
+}
+
+/// The message of the day with `§` codes for its colours and styles (see [`ServerStatus::motd_formatted`]).
+fn formatted_motd(value: &Value) -> String {
+ let mut out = String::new();
+ push_formatted(value, &Style::default(), &mut out);
+ out
+}
+
+fn push_formatted(value: &Value, style: &Style, out: &mut String) {
+ match value {
+ Value::String(s) => {
+ if !s.is_empty() {
+ out.push_str(&style.codes());
+ out.push_str(s);
+ }
+ }
+ Value::Array(items) => items.iter().for_each(|item| push_formatted(item, style, out)),
+ Value::Object(map) => {
+ let style = style.with(map);
+ if let Some(text) = map.get("text").or_else(|| map.get("translate")).and_then(Value::as_str) {
+ if !text.is_empty() {
+ out.push_str(&style.codes());
+ out.push_str(text);
+ }
+ }
+ if let Some(extra) = map.get("extra") {
+ push_formatted(extra, &style, out);
+ }
+ }
+ _ => {}
+ }
+}
+
fn strip_formatting(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars();
@@ -281,6 +371,15 @@ mod tests {
assert!(read_varint_slice(&mut &[0x80u8, 0x80][..]).is_err());
}
+ #[test]
+ fn motd_formatting() {
+ assert_eq!(formatted_motd(&json!("§aHello §lworld")), "§r§aHello §lworld");
+ let component = json!({"text": "Cubby ", "color": "gold", "bold": true, "extra": [{"text": "test", "bold": false, "color": "#4CC9D6"}, "!"]});
+ assert_eq!(formatted_motd(&component), "§r§6§lCubby §r§#4cc9d6test§r§6§l!");
+ assert_eq!(formatted_motd(&json!({"text": "", "extra": [{"text": "x", "italic": true}]})), "§r§ox");
+ assert_eq!(color_code("pink"), None);
+ }
+
#[test]
fn motd_flattening() {
assert_eq!(flatten_motd(&json!("§aHello §lworld")), "Hello world");
diff --git a/crates/cubby-modrinth/src/browse.rs b/crates/cubby-modrinth/src/browse.rs
index 1dd2092..b601642 100644
--- a/crates/cubby-modrinth/src/browse.rs
+++ b/crates/cubby-modrinth/src/browse.rs
@@ -197,7 +197,18 @@ impl Modrinth {
pub async fn search(&self, query: &SearchQuery) -> Result {
let response = self.search_raw(&search_params(query)).await?;
Ok(SearchResults {
- hits: response.hits.into_iter().map(hit_from_search).collect(),
+ // Modrinth calls most datapacks "mod" projects (many are mods too): keep the kind that was searched.
+ hits: response
+ .hits
+ .into_iter()
+ .map(hit_from_search)
+ .map(|mut h| {
+ if query.kind == ProjectKind::Datapack {
+ h.kind = ProjectKind::Datapack;
+ }
+ h
+ })
+ .collect(),
total: response.total_hits,
offset: response.offset,
limit: response.limit,
@@ -377,7 +388,7 @@ mod tests {
assert_eq!(hits[0].loaders, ["fabric", "quilt"]);
assert_eq!(hits[0].featured_image.as_deref(), Some("https://cdn/g.png"));
assert_eq!((hits[0].client_side, hits[0].server_side), (Side::Required, Side::Unsupported));
- assert_eq!((hits[1].slug.as_str(), hits[1].kind, hits[1].client_side), ("x", ProjectKind::Mod, Side::Unknown));
+ assert_eq!((hits[1].slug.as_str(), hits[1].kind, hits[1].client_side), ("x", ProjectKind::Datapack, Side::Unknown));
let project: api::Project = serde_json::from_str(
r##"{"id":"P1","slug":"pack","project_type":"modpack","title":"Pack","description":"d","body":"# Hi",
diff --git a/crates/cubby-modrinth/src/datapacks.rs b/crates/cubby-modrinth/src/datapacks.rs
new file mode 100644
index 0000000..1551657
--- /dev/null
+++ b/crates/cubby-modrinth/src/datapacks.rs
@@ -0,0 +1,36 @@
+//! Datapacks: they go into a world (`saves//datapacks`), not into the instance, so they have their
+//! own download instead of the install plans of mods and packs. Discover searches them like other projects.
+
+use cubby_common::{Error, Result};
+
+use crate::client::Modrinth;
+use crate::model::FileInfo;
+
+impl Modrinth {
+ /// The `.zip` of a datapack version: `version_id`, else the newest version of the project for `game_version`.
+ pub async fn datapack_file(&self, id_or_slug: &str, version_id: Option<&str>, game_version: &str) -> Result {
+ let newest = match version_id {
+ Some(id) => self.version_raw(id).await?,
+ None => self
+ .project_versions_raw(id_or_slug, &["datapack".to_string()], &[game_version.to_string()])
+ .await?
+ .into_iter()
+ .filter(|v| v.loaders.iter().any(|l| l == "datapack"))
+ .max_by_key(|v| v.published_millis())
+ .ok_or_else(|| Error::NotFound(format!("a datapack version of {id_or_slug} for Minecraft {game_version}")))?,
+ };
+ let file = newest
+ .files
+ .iter()
+ .find(|f| f.primary && f.filename.to_lowercase().ends_with(".zip"))
+ .or_else(|| newest.files.iter().find(|f| f.filename.to_lowercase().ends_with(".zip")))
+ .ok_or_else(|| Error::Other(format!("{} has no datapack .zip to download.", newest.name)))?;
+ Ok(FileInfo {
+ url: file.url.clone(),
+ file_name: file.filename.clone(),
+ size: file.size,
+ primary: file.primary,
+ sha1: file.hashes.get("sha1").cloned().unwrap_or_default().to_lowercase(),
+ })
+ }
+}
diff --git a/crates/cubby-modrinth/src/export.rs b/crates/cubby-modrinth/src/export.rs
new file mode 100644
index 0000000..169b9f6
--- /dev/null
+++ b/crates/cubby-modrinth/src/export.rs
@@ -0,0 +1,155 @@
+//! Exporting an instance as a `.mrpack`: the mods, resource packs and shader packs Modrinth knows become
+//! downloads, everything else goes into `overrides/`.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use cubby_common::export::{collect_files, write_pack};
+use cubby_common::{Error, Result};
+use serde::Serialize;
+
+use crate::client::Modrinth;
+use crate::mrpack::{PackLoader, INDEX_FILE};
+
+/// What goes into the pack besides the content files.
+#[derive(Debug, Clone)]
+pub struct ExportSpec {
+ pub name: String,
+ /// The pack's own version ("1.0.0").
+ pub version: String,
+ pub summary: Option,
+ pub minecraft: String,
+ /// `None` for Vanilla.
+ pub loader: Option<(PackLoader, String)>,
+ /// Top-level entries of the game directory to copy into `overrides/` (`config`, `options.txt`...).
+ pub include: Vec,
+}
+
+/// What an export wrote.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExportSummary {
+ /// Files players download from Modrinth when they install the pack.
+ pub downloads: usize,
+ /// Files stored inside the pack.
+ pub included: usize,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Index<'a> {
+ format_version: u32,
+ game: &'static str,
+ version_id: &'a str,
+ name: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ summary: Option<&'a str>,
+ files: Vec,
+ dependencies: BTreeMap<&'static str, String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct IndexFile {
+ path: String,
+ hashes: BTreeMap<&'static str, String>,
+ downloads: Vec,
+ file_size: u64,
+}
+
+/// The `dependencies` of the index: the game and the loader.
+pub fn pack_dependencies(minecraft: &str, loader: Option<&(PackLoader, String)>) -> BTreeMap<&'static str, String> {
+ let mut deps = BTreeMap::from([("minecraft", minecraft.to_string())]);
+ if let Some((kind, version)) = loader {
+ let key = match kind {
+ PackLoader::Fabric => "fabric-loader",
+ PackLoader::Quilt => "quilt-loader",
+ PackLoader::Forge => "forge",
+ PackLoader::NeoForge => "neoforge",
+ };
+ deps.insert(key, version.clone());
+ }
+ deps
+}
+
+impl Modrinth {
+ /// Writes the instance whose game directory is `game_dir` to `dest` as a `.mrpack`. Turned-off mods are
+ /// left out.
+ pub async fn export_mrpack(&self, game_dir: &Path, dest: &Path, spec: &ExportSpec) -> Result {
+ if spec.name.trim().is_empty() {
+ return Err(Error::Other("Give the pack a name.".into()));
+ }
+ let files: Vec<_> = self.local_files(game_dir).await.into_iter().filter(|f| f.enabled && !f.sha1.is_empty()).collect();
+ let known = self.identify(&files).await?;
+ let mut index_files = Vec::new();
+ let mut overrides: Vec<(String, PathBuf)> = Vec::new();
+ for f in &files {
+ let rel = format!("{}/{}", f.folder.as_str(), f.file_name);
+ let remote = known.get(&f.sha1).and_then(|v| v.files.iter().find(|vf| vf.hashes.get("sha1").is_some_and(|h| h.eq_ignore_ascii_case(&f.sha1))));
+ match remote {
+ Some(vf) if vf.url.starts_with("https://") && vf.hashes.contains_key("sha512") => index_files.push(IndexFile {
+ path: rel,
+ hashes: BTreeMap::from([("sha1", f.sha1.clone()), ("sha512", vf.hashes["sha512"].to_lowercase())]),
+ downloads: vec![vf.url.clone()],
+ file_size: f.size,
+ }),
+ _ => overrides.push((rel, f.path.clone())),
+ }
+ }
+ let dir = game_dir.to_path_buf();
+ let include = spec.include.clone();
+ let extra = tokio::task::spawn_blocking(move || collect_files(&dir, &include))
+ .await
+ .map_err(|e| Error::Other(format!("The export stopped unexpectedly ({e}).")))??;
+ overrides.extend(extra);
+
+ let summary = ExportSummary { downloads: index_files.len(), included: overrides.len() };
+ let index = Index {
+ format_version: 1,
+ game: "minecraft",
+ version_id: spec.version.trim(),
+ name: spec.name.trim(),
+ summary: spec.summary.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ files: index_files,
+ dependencies: pack_dependencies(&spec.minecraft, spec.loader.as_ref()),
+ };
+ let json = serde_json::to_vec_pretty(&index).map_err(|e| Error::Other(e.to_string()))?;
+ let dest = dest.to_path_buf();
+ tokio::task::spawn_blocking(move || write_pack(&dest, INDEX_FILE, &json, "overrides/", &overrides))
+ .await
+ .map_err(|e| Error::Other(format!("The export stopped unexpectedly ({e}).")))??;
+ Ok(summary)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mrpack::MrpackIndex;
+
+ #[test]
+ fn dependencies_use_mrpack_keys() {
+ let deps = pack_dependencies("1.21.1", Some(&(PackLoader::Fabric, "0.16.5".into())));
+ assert_eq!(deps.get("fabric-loader").map(String::as_str), Some("0.16.5"));
+ assert_eq!(pack_dependencies("1.20.1", None).len(), 1);
+ // What we write, Cubby (and the Modrinth format) reads back.
+ let index = Index {
+ format_version: 1,
+ game: "minecraft",
+ version_id: "1.0.0",
+ name: "Pack",
+ summary: None,
+ files: vec![IndexFile {
+ path: "mods/a.jar".into(),
+ hashes: BTreeMap::from([("sha1", "a".repeat(40)), ("sha512", "b".repeat(128))]),
+ downloads: vec!["https://cdn.modrinth.com/data/x/a.jar".into()],
+ file_size: 3,
+ }],
+ dependencies: pack_dependencies("1.21.1", Some(&(PackLoader::NeoForge, "21.1.5".into()))),
+ };
+ let parsed = MrpackIndex::parse(&serde_json::to_vec(&index).unwrap()).unwrap();
+ assert_eq!(parsed.minecraft(), Some("1.21.1"));
+ assert_eq!(parsed.loader(), Some((PackLoader::NeoForge, "21.1.5".into())));
+ assert_eq!(parsed.client_downloads().unwrap().len(), 1);
+ }
+}
diff --git a/crates/cubby-modrinth/src/lib.rs b/crates/cubby-modrinth/src/lib.rs
index aac42a7..5e09cc9 100644
--- a/crates/cubby-modrinth/src/lib.rs
+++ b/crates/cubby-modrinth/src/lib.rs
@@ -4,6 +4,8 @@
pub mod api;
mod browse;
mod client;
+mod datapacks;
+mod export;
mod install;
mod local;
mod model;
@@ -11,6 +13,7 @@ pub mod mrpack;
mod resolve;
pub use browse::{facets, search_params};
+pub use export::{pack_dependencies, ExportSpec, ExportSummary};
pub use client::{Modrinth, API_BASE, USER_AGENT};
pub use model::*;
pub use mrpack::{sanitize_path, MrpackIndex, PackLoader};
diff --git a/crates/cubby-modrinth/src/model.rs b/crates/cubby-modrinth/src/model.rs
index 83f1d97..512aa36 100644
--- a/crates/cubby-modrinth/src/model.rs
+++ b/crates/cubby-modrinth/src/model.rs
@@ -9,6 +9,8 @@ pub enum ProjectKind {
Modpack,
Shader,
ResourcePack,
+ /// Goes into a world (`saves//datapacks`), not into the instance: see `install_datapack`.
+ Datapack,
}
impl ProjectKind {
@@ -19,6 +21,7 @@ impl ProjectKind {
ProjectKind::Modpack => "modpack",
ProjectKind::Shader => "shader",
ProjectKind::ResourcePack => "resourcepack",
+ ProjectKind::Datapack => "datapack",
}
}
@@ -27,6 +30,7 @@ impl ProjectKind {
"modpack" => ProjectKind::Modpack,
"shader" => ProjectKind::Shader,
"resourcepack" => ProjectKind::ResourcePack,
+ "datapack" => ProjectKind::Datapack,
_ => ProjectKind::Mod,
}
}
@@ -37,7 +41,7 @@ impl ProjectKind {
ProjectKind::Mod => Some(Folder::Mods),
ProjectKind::ResourcePack => Some(Folder::ResourcePacks),
ProjectKind::Shader => Some(Folder::ShaderPacks),
- ProjectKind::Modpack => None,
+ ProjectKind::Modpack | ProjectKind::Datapack => None,
}
}
}
diff --git a/crates/cubby-modrinth/src/resolve.rs b/crates/cubby-modrinth/src/resolve.rs
index 832467a..4d0e1ab 100644
--- a/crates/cubby-modrinth/src/resolve.rs
+++ b/crates/cubby-modrinth/src/resolve.rs
@@ -54,6 +54,7 @@ pub(crate) fn compatible(version: &api::Version, target: &Target, kind: ProjectK
version.loaders.iter().any(|l| allowed.contains(l))
}
ProjectKind::ResourcePack | ProjectKind::Shader => matches_loaders(version, &[]),
+ ProjectKind::Datapack => version.loaders.iter().any(|l| l == "datapack"),
}
}
diff --git a/docs/screenshots/discover.png b/docs/screenshots/discover.png
index b767e93..6e696ea 100644
Binary files a/docs/screenshots/discover.png and b/docs/screenshots/discover.png differ
diff --git a/docs/screenshots/library.png b/docs/screenshots/library.png
index 9c2715c..ffa5414 100644
Binary files a/docs/screenshots/library.png and b/docs/screenshots/library.png differ
diff --git a/docs/screenshots/mods.png b/docs/screenshots/mods.png
new file mode 100644
index 0000000..4b72e25
Binary files /dev/null and b/docs/screenshots/mods.png differ
diff --git a/docs/screenshots/project.png b/docs/screenshots/project.png
index 4154273..3d0ad65 100644
Binary files a/docs/screenshots/project.png and b/docs/screenshots/project.png differ
diff --git a/docs/screenshots/worlds.png b/docs/screenshots/worlds.png
new file mode 100644
index 0000000..8cc68b1
Binary files /dev/null and b/docs/screenshots/worlds.png differ
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 607cd5a..e22d05a 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -38,6 +38,7 @@ cubby-ftb.workspace = true
cubby-technic.workspace = true
cubby-atlauncher.workspace = true
cubby-curseforge.workspace = true
+cubby-discord.workspace = true
dirs.workspace = true
futures.workspace = true
uuid.workspace = true
@@ -54,6 +55,7 @@ tauri-plugin-dialog = "2"
sysinfo = { version = "0.39", default-features = false, features = ["system"] }
tauri-plugin-updater = "2"
tauri-plugin-deep-link = "2"
+tauri-plugin-window-state = "2"
[target.'cfg(any(target_os = "windows", target_os = "linux"))'.dependencies]
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
diff --git a/src-tauri/src/commands/app.rs b/src-tauri/src/commands/app.rs
index 294979a..9f4dad1 100644
--- a/src-tauri/src/commands/app.rs
+++ b/src-tauri/src/commands/app.rs
@@ -6,16 +6,15 @@ use super::*;
#[tauri::command]
pub fn app_info(core: State<'_, Core>) -> AppInfoDto {
- let mut sys = sysinfo::System::new();
- sys.refresh_memory();
AppInfoDto {
version: env!("CARGO_PKG_VERSION"),
data_dir: core.paths.root().to_string_lossy().into_owned(),
msa_configured: core.msa_client_id().is_some(),
msa_source: core.msa_client_id_with_source().map(|(_, source)| source),
curseforge_key: core.curseforge_key_with_source().map(|(_, source)| source),
- total_memory_mb: sys.total_memory() / (1024 * 1024),
+ total_memory_mb: core.total_memory_mb,
dev_build: cfg!(debug_assertions),
+ discord: core.discord.is_some(),
}
}
diff --git a/src-tauri/src/commands/content.rs b/src-tauri/src/commands/content.rs
index 03ad2dc..796575c 100644
--- a/src-tauri/src/commands/content.rs
+++ b/src-tauri/src/commands/content.rs
@@ -254,3 +254,28 @@ pub fn delete_world(core: State<'_, Core>, instance_id: String, folder: String)
core.store.delete_world(&instance_id, &folder).msg()?;
Ok(())
}
+
+/// Copies options, key bindings and/or the server list from another instance into this one.
+/// Returns what was copied (a part the other instance doesn't have is left out).
+#[tauri::command]
+pub fn copy_options(
+ core: State<'_, Core>,
+ id: String,
+ from: String,
+ what: cubby_instance::OptionsCopy,
+) -> CmdResult {
+ if id == from {
+ return Err("Pick another instance to copy from.".into());
+ }
+ ensure_stopped(&core, &id)?;
+ let done = cubby_instance::copy_options(&game_dir(&core, &from)?, &game_dir(&core, &id)?, what).msg()?;
+ Ok(CopiedOptionsDto { options: done.options, keys: done.keys, servers: done.servers })
+}
+
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CopiedOptionsDto {
+ pub options: bool,
+ pub keys: bool,
+ pub servers: bool,
+}
diff --git a/src-tauri/src/commands/datapacks.rs b/src-tauri/src/commands/datapacks.rs
new file mode 100644
index 0000000..61b96f1
--- /dev/null
+++ b/src-tauri/src/commands/datapacks.rs
@@ -0,0 +1,144 @@
+//! The datapacks of a world: listing, turning on and off, adding from files or from Modrinth.
+
+use cubby_common::net::Download;
+use cubby_instance::DatapackFile;
+use tauri_plugin_dialog::DialogExt;
+
+use super::content::game_dir;
+use super::*;
+
+#[tauri::command]
+pub async fn list_datapacks(
+ core: State<'_, Core>,
+ id: String,
+ world: String,
+) -> CmdResult> {
+ let dir = game_dir(&core, &id)?;
+ blocking(move || cubby_instance::list_datapacks(&dir, &world).msg()).await
+}
+
+#[tauri::command]
+pub fn set_datapack_enabled(
+ core: State<'_, Core>,
+ id: String,
+ world: String,
+ file_name: String,
+ enabled: bool,
+) -> CmdResult<()> {
+ cubby_instance::set_datapack_enabled(&game_dir(&core, &id)?, &world, &file_name, enabled).msg()
+}
+
+#[tauri::command]
+pub fn remove_datapack(
+ core: State<'_, Core>,
+ id: String,
+ world: String,
+ file_name: String,
+) -> CmdResult<()> {
+ cubby_instance::remove_datapack(&game_dir(&core, &id)?, &world, &file_name).msg()?;
+ Ok(())
+}
+
+/// Asks for datapack .zip files and copies them into the world. Returns the names added (empty when cancelled).
+#[tauri::command]
+pub async fn add_datapack_files(
+ app: AppHandle,
+ core: State<'_, Core>,
+ id: String,
+ world: String,
+) -> CmdResult> {
+ let dir = game_dir(&core, &id)?;
+ let picked = tauri::async_runtime::spawn_blocking(move || {
+ app.dialog()
+ .file()
+ .add_filter("Datapacks", &["zip"])
+ .blocking_pick_files()
+ })
+ .await
+ .map_err(|e| format!("The file dialog stopped unexpectedly ({e})."))?;
+ let Some(files) = picked else {
+ return Ok(Vec::new());
+ };
+ let paths = files
+ .into_iter()
+ .map(|f| f.into_path().map_err(|e| format!("Couldn't use the chosen file: {e}")))
+ .collect::>>()?;
+ blocking(move || cubby_instance::import_datapacks(&dir, &world, &paths).msg()).await
+}
+
+/// Downloads a version of a Modrinth datapack into the world: `version_id`, else the newest one for the
+/// instance's Minecraft version.
+/// Returns the file name.
+#[tauri::command]
+pub async fn install_datapack(
+ core: State<'_, Core>,
+ id: String,
+ world: String,
+ project_id: String,
+ version_id: Option,
+) -> CmdResult {
+ let inst = core.store.get(&id).msg()?;
+ let game = core.store.game_dir(&inst);
+ let file = core
+ .modrinth
+ .datapack_file(project_id.trim(), version_id.as_deref().map(str::trim).filter(|v| !v.is_empty()), &inst.minecraft)
+ .await
+ .msg()?;
+ let path = cubby_instance::datapack_path(&game, &world, &file.file_name).msg()?;
+ let mut job = Download::new(file.url, &path).with_size(file.size);
+ if file.sha1.len() == 40 {
+ job = job.with_sha1(file.sha1);
+ }
+ cubby_common::net::ensure_file(&core.http, &job).await.msg()?;
+ Ok(file.file_name)
+}
+
+// World map
+
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorldMapDto {
+ /// The PNG, as an asset URL (with a version, so a new drawing isn't hidden by the cache).
+ pub url: String,
+ pub min_x: i32,
+ pub min_z: i32,
+ pub size: u32,
+ pub chunks: u32,
+}
+
+/// Draws the map around the world's spawn (task `map:`), or returns the one drawn since the world last changed.
+#[tauri::command]
+pub async fn render_world_map(
+ app: AppHandle,
+ core: State<'_, Core>,
+ id: String,
+ world: String,
+) -> CmdResult {
+ let inst = core.store.get(&id).msg()?;
+ let game = core.store.game_dir(&inst);
+ let cache = core.paths.instance(&inst.id).join("maps");
+ run_task(&app, format!("map:{id}"), move |app, task| async move {
+ let sink = app.state::().sink.clone();
+ let map = blocking(move || {
+ cubby_instance::render_map(&game, &world, &cache, |done, total| {
+ sink.progress(&task, "Drawing the map", done, total)
+ })
+ .msg()
+ })
+ .await?;
+ let stamp = std::fs::metadata(&map.path)
+ .and_then(|m| m.modified())
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ Ok(WorldMapDto {
+ url: format!("{}?v={stamp}", dto::asset_url(&map.path)),
+ min_x: map.min_x,
+ min_z: map.min_z,
+ size: map.size,
+ chunks: map.chunks,
+ })
+ })
+ .await
+}
diff --git a/src-tauri/src/commands/discover.rs b/src-tauri/src/commands/discover.rs
index f3b810b..51cd57b 100644
--- a/src-tauri/src/commands/discover.rs
+++ b/src-tauri/src/commands/discover.rs
@@ -435,8 +435,35 @@ pub async fn apply_updates(
.await
.msg()?;
selection.follow(&game_dir, &applied.renamed);
+ let renamed: Vec<(String, String, String)> = applied
+ .renamed
+ .iter()
+ .map(|r| (r.folder.as_str().to_string(), r.old.clone(), r.new.clone()))
+ .collect();
+ if let Err(e) = cubby_instance::record_update(&backup_dir, &renamed) {
+ log::warn!("couldn't record the update in {}: {e}", backup_dir.display());
+ }
applied.into_result().msg().map(|_| ())
},
)
.await
}
+
+/// Updates of the instance that can be undone, newest first.
+#[tauri::command]
+pub fn list_update_backups(
+ core: State<'_, Core>,
+ instance_id: String,
+) -> CmdResult> {
+ core.store.list_update_backups(&instance_id).msg()
+}
+
+/// Puts back the files an update replaced; returns how many came back.
+#[tauri::command]
+pub fn undo_update(core: State<'_, Core>, instance_id: String, name: String) -> CmdResult {
+ ensure_stopped(&core, &instance_id)?;
+ if core.tasks.lock().expect("tasks lock").contains(&format!("update:{instance_id}")) {
+ return Err("Wait for the update to finish.".into());
+ }
+ core.store.undo_update(&instance_id, &name).msg()
+}
diff --git a/src-tauri/src/commands/export.rs b/src-tauri/src/commands/export.rs
new file mode 100644
index 0000000..4ce077c
--- /dev/null
+++ b/src-tauri/src/commands/export.rs
@@ -0,0 +1,153 @@
+//! Exporting an instance as a modpack file: `.mrpack` (Modrinth) or `.zip` (CurseForge).
+
+use cubby_common::export::ExportCandidate;
+use cubby_modrinth::{ExportSpec, PackLoader as MrLoader};
+use serde::{Deserialize, Serialize};
+use tauri_plugin_dialog::DialogExt;
+
+use super::*;
+
+/// What can go into the pack besides mods, resource packs and shader packs.
+#[tauri::command]
+pub async fn export_candidates(core: State<'_, Core>, id: String) -> CmdResult> {
+ let dir = content::game_dir(&core, &id)?;
+ blocking(move || Ok(cubby_common::export::export_candidates(&dir))).await
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExportRequest {
+ /// "mrpack" or "curseforge".
+ pub format: String,
+ pub name: String,
+ pub version: String,
+ /// Summary (Modrinth) or author (CurseForge).
+ #[serde(default)]
+ pub note: String,
+ #[serde(default)]
+ pub include: Vec,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExportResultDto {
+ pub path: String,
+ /// Files listed for download from Modrinth or CurseForge.
+ pub listed: usize,
+ /// Files stored inside the pack.
+ pub stored: usize,
+ /// CurseForge without an API key: every mod is stored in the zip.
+ pub without_key: bool,
+}
+
+fn safe_file_name(name: &str) -> String {
+ let cleaned: String = name
+ .trim()
+ .chars()
+ .map(|c| if c.is_control() || "\\/:*?\"<>|".contains(c) { '-' } else { c })
+ .collect();
+ if cleaned.trim().is_empty() { "modpack".into() } else { cleaned }
+}
+
+/// Asks where to save, then writes the pack (task `export:`). `None` when the dialog was cancelled.
+#[tauri::command]
+pub async fn export_instance(
+ app: AppHandle,
+ core: State<'_, Core>,
+ id: String,
+ request: ExportRequest,
+) -> CmdResult