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.

+ +![A world in Cubby: its map around the spawn and its datapacks](https://raw.githubusercontent.com/benjaminbrtrd/Cubby/main/docs/screenshots/worlds.png) + +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 +

-

Cubby

+

A lightweight Minecraft launcher for Windows, macOS and Linux.

-

The lightweight Minecraft launcher.

- -![The Cubby library](docs/screenshots/library.png) - -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 | -| --- | --- | --- | -| ![Discover](docs/screenshots/discover.png) | ![A mod page](docs/screenshots/project.png) | ![The crash screen](docs/screenshots/crash.png) | - -## Download +

+ Download +  ·  + Website +

-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). +

+ Latest version + Windows, macOS and Linux + GPL-3.0 + Build +

-The full game needs a signed-in Microsoft account that owns Minecraft: Java Edition. Without one, Cubby only starts the Minecraft demo. +![Cubby](docs/screenshots/discover.png) -## 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. +

+ The mods of an instance + A world, its map and its datapacks + A mod page + The library +

-## 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> { + let inst = core.store.get(&id).msg()?; + let mrpack = match request.format.as_str() { + "mrpack" => true, + "curseforge" => false, + other => return Err(format!("Unknown pack format: {other}.")), + }; + let ext = if mrpack { "mrpack" } else { "zip" }; + let version = request.version.trim(); + let default_name = if version.is_empty() { + format!("{}.{ext}", safe_file_name(&request.name)) + } else { + format!("{} {}.{ext}", safe_file_name(&request.name), safe_file_name(version)) + }; + let dialog = app.clone(); + let picked = tauri::async_runtime::spawn_blocking(move || { + dialog + .dialog() + .file() + .set_file_name(default_name) + .add_filter(if mrpack { "Modrinth modpack" } else { "CurseForge modpack" }, &[ext]) + .blocking_save_file() + }) + .await + .map_err(|e| format!("The file dialog stopped unexpectedly ({e})."))?; + let Some(picked) = picked else { + return Ok(None); + }; + let mut dest = picked + .into_path() + .map_err(|e| format!("Couldn't use the chosen file: {e}"))?; + if dest.extension().is_none_or(|e| !e.eq_ignore_ascii_case(ext)) { + dest.set_extension(ext); + } + + let game_dir = core.store.game_dir(&inst); + let loader = dto::LoaderDto::from(&inst.loader); + run_task(&app, format!("export:{id}"), move |app, task| async move { + let core = app.state::(); + core.sink.progress(&task, "Writing the pack", 0, 1); + let (listed, stored, without_key) = if mrpack { + let kind = match loader.kind.as_str() { + "fabric" => Some(MrLoader::Fabric), + "quilt" => Some(MrLoader::Quilt), + "forge" => Some(MrLoader::Forge), + "neoforge" => Some(MrLoader::NeoForge), + _ => None, + }; + let spec = ExportSpec { + name: request.name.clone(), + version: request.version.clone(), + summary: Some(request.note.clone()), + minecraft: inst.minecraft.clone(), + loader: kind.zip(loader.version.clone()), + include: request.include.clone(), + }; + let s = core.modrinth.export_mrpack(&game_dir, &dest, &spec).await.msg()?; + (s.downloads, s.included, false) + } else { + let client = core.curseforge(); + let spec = cubby_curseforge::CfExportSpec { + name: request.name.clone(), + version: request.version.clone(), + author: request.note.clone(), + minecraft: inst.minecraft.clone(), + loader_id: loader + .version + .clone() + .filter(|_| loader.kind != "vanilla") + .map(|v| format!("{}-{v}", loader.kind)), + include: request.include.clone(), + }; + let (listed, stored) = cubby_curseforge::export_curseforge(client.as_ref(), &game_dir, &dest, &spec) + .await + .msg()?; + (listed, stored, client.is_none()) + }; + core.sink.progress(&task, "Writing the pack", 1, 1); + Ok(Some(ExportResultDto { + path: dest.to_string_lossy().into_owned(), + listed, + stored, + without_key, + })) + }) + .await +} + +/// Shows an exported file in Finder or Explorer. +#[tauri::command] +pub fn reveal_file(app: AppHandle, path: String) -> CmdResult<()> { + app.opener() + .reveal_item_in_dir(&path) + .map_err(|e| e.to_string()) +} diff --git a/src-tauri/src/commands/instances.rs b/src-tauri/src/commands/instances.rs index 3bd46e4..b9b4875 100644 --- a/src-tauri/src/commands/instances.rs +++ b/src-tauri/src/commands/instances.rs @@ -23,7 +23,40 @@ pub(crate) fn to_dto(core: &Core, inst: &Instance) -> InstanceDto { let installed = std::fs::read_to_string(dir.join(INSTALLED_MARKER)) .is_ok_and(|k| k.trim() == version_key(inst)); let blocked = cubby_packinstall::install::count_missing(&dir, &core.store.game_dir(inst)); - InstanceDto::new(inst, &dir, installed, blocked) + let mut dto = InstanceDto::new(inst, &dir, installed, blocked); + dto.recommended_memory_mb = recommended_memory(core, inst); + dto +} + +/// The computer's memory in MB (0 when it can't be read). +pub(crate) fn total_memory_mb() -> u64 { + let mut sys = sysinfo::System::new(); + sys.refresh_memory(); + sys.total_memory() / (1024 * 1024) +} + +/// What "Set memory automatically" gives this instance, from its mods and the computer's memory. +pub(crate) fn recommended_memory(core: &Core, inst: &Instance) -> u32 { + let mods = cubby_instance::count_enabled_mods(&core.store.game_dir(inst)); + cubby_instance::recommended_memory_mb(core.total_memory_mb, mods) +} + +/// Minimum and maximum heap for a launch: the instance's own values, else the automatic amount when the +/// global settings ask for it, else the global values. +pub(crate) fn memory_for(core: &Core, inst: &Instance, settings: &Settings) -> (u32, u32) { + let max = inst.java.max_memory_mb.unwrap_or_else(|| { + if settings.java.auto_memory { + recommended_memory(core, inst) + } else { + settings.java.max_memory_mb + } + }); + let min = inst + .java + .min_memory_mb + .unwrap_or(settings.java.min_memory_mb) + .min(max); + (min, max) } #[tauri::command] @@ -166,3 +199,38 @@ pub async fn list_loader_versions( .await .msg() } + +/// Cubby's own icon, for a desktop shortcut: the app executable on Windows (it holds the icon), the bundle's +/// `.icns` on macOS, an installed PNG on Linux. `None` in development builds without a bundle. +fn app_icon() -> Option { + let exe = std::env::current_exe().ok()?; + if cfg!(target_os = "windows") { + return Some(exe); + } + if cfg!(target_os = "macos") { + let resources = exe.parent()?.parent()?.join("Resources"); + return std::fs::read_dir(resources) + .ok()? + .flatten() + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "icns")); + } + ["/usr/share/icons/hicolor/128x128/apps/cubby.png", "/usr/share/pixmaps/cubby.png"] + .iter() + .map(PathBuf::from) + .find(|p| p.is_file()) +} + +/// Puts a shortcut on the Desktop that starts this instance. Returns its path. +#[tauri::command] +pub fn create_desktop_shortcut( + app: AppHandle, + core: State<'_, Core>, + id: String, +) -> CmdResult { + let inst = core.store.get(&id).msg()?; + let desktop = app.path().desktop_dir().map_err(|e| e.to_string())?; + let path = cubby_instance::shortcut::create_shortcut(&desktop, &inst.id, &inst.name, app_icon().as_deref()) + .msg()?; + Ok(path.to_string_lossy().into_owned()) +} diff --git a/src-tauri/src/commands/launch.rs b/src-tauri/src/commands/launch.rs index 448cb54..7dfb1ed 100644 --- a/src-tauri/src/commands/launch.rs +++ b/src-tauri/src/commands/launch.rs @@ -153,18 +153,13 @@ pub async fn launch_instance( .window .map(|w| (w.width, w.height)) .unwrap_or((settings.game.width, settings.game.height)); + let (min_memory_mb, max_memory_mb) = memory_for(&core, &inst, &settings); let opts = LaunchOptions { instance_id: inst.id.clone(), game_dir, java, - min_memory_mb: inst - .java - .min_memory_mb - .unwrap_or(settings.java.min_memory_mb), - max_memory_mb: inst - .java - .max_memory_mb - .unwrap_or(settings.java.max_memory_mb), + min_memory_mb, + max_memory_mb, extra_jvm_args: jvm_args.split_whitespace().map(str::to_owned).collect(), window: Some(window), fullscreen: settings.game.fullscreen, @@ -180,6 +175,19 @@ pub async fn launch_instance( .msg()?; core.sink.finished(&task, None); + let loader = dto::LoaderDto::from(&inst.loader); + let activity = cubby_discord::Activity { + details: format!("Playing {}", inst.name), + state: if loader.kind == "vanilla" { + format!("Minecraft {}", inst.minecraft) + } else { + format!("Minecraft {} · {}", inst.minecraft, loader_title(&loader.kind)) + }, + started: chrono::Utc::now().timestamp(), + }; + core.playing.lock().expect("playing lock").push((inst.id.clone(), activity)); + core.update_presence(); + let window = app.get_webview_window("main"); if let Some(w) = &window { let _ = match settings.on_launch { @@ -193,6 +201,8 @@ pub async fn launch_instance( tauri::async_runtime::spawn(async move { let exit = handle.wait().await; let core = app.state::(); + core.playing.lock().expect("playing lock").retain(|(i, _)| *i != id); + core.update_presence(); // Keep the log of this session, so it can still be read after Cubby restarts. let (path, lines) = (session_log_path(&core, &id), core.games.log_lines(&id)); if !lines.is_empty() @@ -321,3 +331,14 @@ pub(super) async fn java_for( let installs = cubby_java::detect(&core.paths).await; cubby_java::pick(&installs, major).ok_or_else(|| format!("Java {major} is required but wasn't found. Turn on \"Choose Java automatically\" in Settings.")) } + +/// "Fabric", "NeoForge"... for Discord. +fn loader_title(kind: &str) -> &'static str { + match kind { + "fabric" => "Fabric", + "quilt" => "Quilt", + "forge" => "Forge", + "neoforge" => "NeoForge", + _ => "Vanilla", + } +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 48a5c3a..e216234 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -20,7 +20,9 @@ use crate::state::{Core, PendingLogin}; pub(crate) mod accounts; pub(crate) mod app; pub(crate) mod content; +pub(crate) mod datapacks; pub(crate) mod discover; +pub(crate) mod export; pub(crate) mod instances; pub(crate) mod launch; pub(crate) mod prism; diff --git a/src-tauri/src/commands/prism.rs b/src-tauri/src/commands/prism.rs index 6d9d71f..3fbef3a 100644 --- a/src-tauri/src/commands/prism.rs +++ b/src-tauri/src/commands/prism.rs @@ -93,3 +93,104 @@ pub(super) fn prism_icon( } None } + +// Other launchers + +/// An instance of another launcher, for the import dialog. +#[derive(Debug, Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ForeignInstanceDto { + /// "prism", "multiMc", "polyMc", "curseForge", "atLauncher", "gdLauncher", "modrinthApp", "official". + pub launcher: cubby_instance::Launcher, + pub launcher_name: &'static str, + pub path: String, + pub name: String, + /// `None` when the launcher doesn't say: such an instance can't be imported. + pub minecraft: Option, + pub loader: LoaderDto, + pub group: Option, + pub game_dir: String, +} + +impl From for ForeignInstanceDto { + fn from(f: cubby_instance::ForeignInstance) -> Self { + Self { + launcher: f.launcher, + launcher_name: f.launcher.title(), + path: f.path, + name: f.name, + minecraft: f.minecraft, + loader: (&f.loader).into(), + group: f.group, + game_dir: f.game_dir.to_string_lossy().into_owned(), + } + } +} + +fn system_dirs(app: &AppHandle) -> CmdResult { + let path = app.path(); + Ok(cubby_instance::SystemDirs { + data: path.data_dir().map_err(|e| e.to_string())?, + home: path.home_dir().map_err(|e| e.to_string())?, + documents: path.document_dir().ok(), + }) +} + +/// Instances of every launcher Cubby knows, found in their usual folders. +#[tauri::command] +pub async fn list_launcher_instances(app: AppHandle) -> CmdResult> { + let dirs = system_dirs(&app)?; + blocking(move || { + Ok(cubby_instance::list_all_foreign(&dirs) + .into_iter() + .map(Into::into) + .collect()) + }) + .await +} + +/// Imports instances of other launchers (by the `path` the listing gave), copying their game folders. +/// Their files are only read. +#[tauri::command] +pub async fn import_launcher_instances( + app: AppHandle, + paths: Vec, +) -> CmdResult> { + let dirs = system_dirs(&app)?; + let app2 = app.clone(); + let imported = blocking(move || { + let core = app2.state::(); + let found = cubby_instance::list_all_foreign(&dirs); + let mut out = Vec::new(); + for path in paths { + let f = found + .iter() + .find(|f| f.path == path) + .ok_or_else(|| format!("{path} isn't there anymore."))?; + let mut inst = cubby_instance::import_foreign(&core.store, f).msg()?; + if matches!( + f.launcher, + cubby_instance::Launcher::Prism + | cubby_instance::Launcher::MultiMc + | cubby_instance::Launcher::PolyMc + ) { + // Their icons live in /icons, next to instances/. + let root = Path::new(&f.path) + .parent() + .and_then(Path::parent) + .map(Path::to_path_buf) + .unwrap_or_default(); + inst.icon = inst + .icon + .take() + .and_then(|key| prism_icon(&core, &inst, &root, &key)); + core.store.save(&inst).msg()?; + } + out.push(inst); + } + Ok(out) + }) + .await?; + let core = app.state::(); + Ok(imported.iter().map(|i| to_dto(&core, i)).collect()) +} diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs index b97407c..d4aa9cb 100644 --- a/src-tauri/src/commands/settings.rs +++ b/src-tauri/src/commands/settings.rs @@ -13,6 +13,7 @@ pub fn get_settings(core: State<'_, Core>) -> Settings { pub fn save_settings(core: State<'_, Core>, settings: Settings) -> CmdResult { settings.save(&core.paths).msg()?; *core.settings.lock().expect("settings lock") = settings.clone(); + core.update_presence(); Ok(settings) } diff --git a/src-tauri/src/dto.rs b/src-tauri/src/dto.rs index f37d324..a6393ff 100644 --- a/src-tauri/src/dto.rs +++ b/src-tauri/src/dto.rs @@ -171,6 +171,9 @@ pub struct InstanceDto { /// Files of the modpack the player still has to download by hand (0 normally). #[serde(default)] pub blocked_files: u32, + /// The memory Cubby would pick for this instance (MB), from its mods and the computer's memory. + #[serde(default)] + pub recommended_memory_mb: u32, } impl InstanceDto { @@ -198,6 +201,7 @@ impl InstanceDto { notes: inst.notes.clone(), modpack: inst.modpack.as_ref().map(Into::into), blocked_files, + recommended_memory_mb: 0, } } } @@ -430,6 +434,8 @@ pub struct AppInfoDto { pub total_memory_mb: u64, /// Development build: without an account the full game starts offline instead of the demo. pub dev_build: bool, + /// This build can show the game on Discord (it has a Discord application id). + pub discord: bool, } #[derive(Debug, Clone, Serialize)] @@ -446,6 +452,8 @@ pub struct DataFolderDto { pub struct ServerStatusDto { pub online: bool, pub motd: String, + /// The message of the day with its `§` colour and style codes. + pub motd_formatted: String, pub players_online: u32, pub players_max: u32, pub version: Option, @@ -460,6 +468,7 @@ impl From for ServerStatusDto { Self { online: s.online, motd: s.motd, + motd_formatted: s.motd_formatted, players_online: s.players_online, players_max: s.players_max, version: s.version, @@ -541,6 +550,7 @@ fn project_kind(kind: &str) -> Result { "modpack" => Ok(modrinth::ProjectKind::Modpack), "shader" => Ok(modrinth::ProjectKind::Shader), "resourcepack" => Ok(modrinth::ProjectKind::ResourcePack), + "datapack" => Ok(modrinth::ProjectKind::Datapack), other => Err(format!("Unknown project type: {other}.")), } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6b6bd71..e235a6a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -23,6 +23,8 @@ pub fn run() { })); builder .plugin(tauri_plugin_deep_link::init()) + // Reopens the window at the size and place it had when Cubby closed. + .plugin(tauri_plugin_window_state::Builder::default().build()) .plugin( tauri_plugin_log::Builder::default() .level(if cfg!(debug_assertions) { @@ -55,6 +57,7 @@ pub fn run() { commands::instances::duplicate_instance, commands::instances::delete_instance, commands::instances::open_folder, + commands::instances::create_desktop_shortcut, commands::instances::list_versions, commands::instances::list_loader_versions, commands::content::list_mods, @@ -82,6 +85,8 @@ pub fn run() { commands::settings::list_java, commands::prism::list_prism_instances, commands::prism::import_prism, + commands::prism::list_launcher_instances, + commands::prism::import_launcher_instances, commands::launch::repair_instance, commands::content::delete_screenshot, commands::content::list_packs, @@ -89,6 +94,7 @@ pub fn run() { commands::content::set_shader_pack, commands::content::list_servers, commands::content::save_servers, + commands::content::copy_options, commands::content::ping_server, commands::settings::data_folders, commands::settings::open_data_folder, @@ -126,6 +132,17 @@ pub fn run() { packs::import_pack_url, packs::blocked_files, packs::find_blocked_files, + commands::discover::list_update_backups, + commands::discover::undo_update, + commands::export::export_candidates, + commands::export::export_instance, + commands::export::reveal_file, + commands::datapacks::list_datapacks, + commands::datapacks::set_datapack_enabled, + commands::datapacks::remove_datapack, + commands::datapacks::add_datapack_files, + commands::datapacks::install_datapack, + commands::datapacks::render_world_map, ]) .build(tauri::generate_context!()) .expect("error while building Cubby") diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index b9739c7..1f21e97 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -37,6 +37,12 @@ pub struct Core { pub atlauncher: AtLauncherClient, /// Ids of the background tasks running (`install:`, `modpack:`...), one of each at a time. pub tasks: Mutex>, + /// The computer's memory in MB, read once at start (0 when unknown). + pub total_memory_mb: u64, + /// Discord Rich Presence, when this build has a Discord application id. + pub discord: Option, + /// Games running, oldest first, with what Discord shows for each: the newest one is shown. + pub playing: Mutex>, } impl Core { @@ -69,6 +75,9 @@ impl Core { games: GameManager::new(), login: Mutex::new(None), tasks: Mutex::new(HashSet::new()), + total_memory_mb: crate::commands::total_memory_mb(), + discord: cubby_discord::client_id().map(cubby_discord::Presence::new), + playing: Mutex::new(Vec::new()), paths, }) } @@ -112,6 +121,15 @@ impl Core { }) } + /// Tells Discord what is being played now (the newest game), or clears it when nothing is or the player + /// turned it off. + pub fn update_presence(&self) { + let Some(discord) = &self.discord else { return }; + let on = self.settings().discord_presence; + let current = self.playing.lock().expect("playing lock").last().map(|(_, a)| a.clone()); + discord.set(current.filter(|_| on)); + } + /// A CurseForge client with the current key (cheap, so built per call: a key saved in the settings /// applies right away), `None` without a key. pub fn curseforge(&self) -> Option { diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 07e16ae..93e4baf 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "Cubby", "mainBinaryName": "Cubby", - "version": "2026.11.0-beta.2", + "version": "2026.11.0", "identifier": "io.github.benjaminbrtrd.cubby", "build": { "frontendDist": "../ui/dist", @@ -47,9 +47,10 @@ "devCsp": null, "assetProtocol": { "enable": true, - "scope": [ - "$DATA/Cubby/instances/**" - ] + "scope": { + "allow": ["$DATA/Cubby/instances/**"], + "requireLiteralLeadingDot": false + } } } }, diff --git a/ui/package-lock.json b/ui/package-lock.json index de0f8b5..87149ee 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -1,12 +1,12 @@ { "name": "ui", - "version": "2026.11.0-beta.2", + "version": "2026.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ui", - "version": "2026.11.0-beta.2", + "version": "2026.11.0", "dependencies": { "@fontsource/atkinson-hyperlegible-mono": "^5.3.0", "@fontsource/atkinson-hyperlegible-next": "^5.3.0", diff --git a/ui/package.json b/ui/package.json index 835254b..ed2ef21 100644 --- a/ui/package.json +++ b/ui/package.json @@ -1,13 +1,14 @@ { "name": "ui", "private": true, - "version": "2026.11.0-beta.2", + "version": "2026.11.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview", - "check": "svelte-check --tsconfig ./tsconfig.app.json && tsc -p tsconfig.node.json" + "check": "svelte-check --tsconfig ./tsconfig.app.json && tsc -p tsconfig.node.json", + "test": "vite build --ssr src/lib/views/play/crash.test.ts --outDir node_modules/.tmp/test-build --emptyOutDir --logLevel warn && node --disable-warning=ExperimentalWarning node_modules/.tmp/test-build/crash.test.js" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.3.1", diff --git a/ui/src/app.css b/ui/src/app.css index 3a23c1c..1803ded 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -49,24 +49,3 @@ a { scroll-behavior: auto !important; } -/* Side panels: their buttons line up on the right. A row made only of buttons ends on the right edge, a lone - button in a column panel does too, and two buttons side by side share the width, half each. Full-width buttons - (class "wide") are not touched. */ -aside :where(div, span, p):has(> :is(.cb-btn, .cb-iconbtn)):not(:has(> :not(.cb-btn, .cb-iconbtn))) { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; -} -aside :where(div, span, p):has(> .cb-btn:first-child:nth-last-child(2)):not(:has(> :not(.cb-btn))) { - display: grid; - grid-template-columns: 1fr 1fr; - gap: var(--space-2); -} -aside :where(div, span, p):has(> .cb-btn:first-child:nth-last-child(2)):not(:has(> :not(.cb-btn))) > .cb-btn { - width: 100%; - justify-content: center; - white-space: nowrap; -} -aside > :is(.cb-btn, .cb-iconbtn):not(.wide) { - align-self: flex-end; -} diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 9d4a502..8be5dc0 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -8,6 +8,14 @@ import type { BlockedFile, ContentUpdate, DataFolder, + WorldMapImage, + OptionsCopy, + ForeignInstance, + ExportCandidate, + ExportRequest, + ExportResult, + UpdateBackup, + Datapack, InstallPlan, SkinProfile, DefaultSkin, @@ -79,6 +87,8 @@ export const api = { killInstance: (id: string) => call('kill_instance', { id }), runningGames: () => call('running_games'), gameLog: (id: string) => call('game_log', { id }), + /** Puts a shortcut on the Desktop that starts the instance (cubby://play/); returns its path. */ + createDesktopShortcut: (id: string) => call('create_desktop_shortcut', { id }), openFolder: (id: string, sub?: string) => call('open_folder', { id, sub: sub ?? null }), listVersions: () => call('list_versions'), @@ -103,6 +113,8 @@ export const api = { /** Replaces the whole servers.dat list, in this order. */ saveServers: (id: string, servers: Server[]) => call('save_servers', { id, servers }), /** `instanceId`: ask with that instance's Minecraft protocol, so `compatible` says whether the server takes it. */ + /** Copies options, key bindings and/or the server list from instance `from`; returns what it copied. */ + copyOptions: (id: string, from: string, what: OptionsCopy) => call('copy_options', { id, from, what }), pingServer: (address: string, instanceId?: string) => call('ping_server', { address, instanceId: instanceId ?? null }), dataFolders: () => call('data_folders'), @@ -164,6 +176,11 @@ export const api = { /** Replaces each file by its latest compatible version (task `update:`). Backs up the old files into /backups/content-/. */ applyUpdates: (instanceId: string, fileNames: string[]) => call('apply_updates', { instanceId, fileNames }), + /** Updates that can be undone, newest first. */ + listUpdateBackups: (instanceId: string) => call('list_update_backups', { instanceId }), + /** Puts back the files an update replaced; returns how many came back. */ + undoUpdate: (instanceId: string, name: string) => call('undo_update', { instanceId, name }), + // Worlds backupWorld: (instanceId: string, folder: string) => call('backup_world', { instanceId, folder }), listBackups: (instanceId: string) => call('list_backups', { instanceId }), @@ -194,8 +211,31 @@ export const api = { /** Looks in the Downloads folder, moves matches into place and returns the updated list. */ findBlockedFiles: (instanceId: string) => call('find_blocked_files', { instanceId }), + /** Draws the map around a world's spawn (task `map:`), or returns the one already drawn since it last changed. */ + renderWorldMap: (id: string, world: string) => call('render_world_map', { id, world }), + + // Exports + exportCandidates: (id: string) => call('export_candidates', { id }), + /** Asks where to save, then writes the pack (task `export:`); null when cancelled. */ + exportInstance: (id: string, request: ExportRequest) => call('export_instance', { id, request }), + revealFile: (path: string) => call('reveal_file', { path }), + + // Datapacks of a world + listDatapacks: (id: string, world: string) => call('list_datapacks', { id, world }), + setDatapackEnabled: (id: string, world: string, fileName: string, enabled: boolean) => call('set_datapack_enabled', { id, world, fileName, enabled }), + /** Moves the datapack to the instance's trash folder. */ + removeDatapack: (id: string, world: string, fileName: string) => call('remove_datapack', { id, world, fileName }), + /** Asks for .zip files and copies them into the world; returns the names added (empty when cancelled). */ + addDatapackFiles: (id: string, world: string) => call('add_datapack_files', { id, world }), + /** Downloads a version (else the newest for the instance's Minecraft version) into the world; returns its file name. */ + installDatapack: (id: string, world: string, projectId: string, versionId: string | null = null) => call('install_datapack', { id, world, projectId, versionId }), + listPrismInstances: () => call('list_prism_instances'), importPrism: (paths: string[]) => call('import_prism', { paths }), + /** Instances of every launcher Cubby knows, from their usual folders. */ + listLauncherInstances: () => call('list_launcher_instances'), + /** Copies them into new instances (by the `path` the listing gave). */ + importLauncherInstances: (paths: string[]) => call('import_launcher_instances', { paths }), openUrl: (url: string) => call('open_url', { url }), } diff --git a/ui/src/lib/cubby/Inspector.svelte b/ui/src/lib/cubby/Inspector.svelte new file mode 100644 index 0000000..b03c16e --- /dev/null +++ b/ui/src/lib/cubby/Inspector.svelte @@ -0,0 +1,20 @@ + + + +
+ {@render children()} + {#if danger} +
+ + {#if danger.hint}

{danger.hint}

{/if} +
+ {/if} +
diff --git a/ui/src/lib/cubby/InspectorHead.svelte b/ui/src/lib/cubby/InspectorHead.svelte new file mode 100644 index 0000000..2119c72 --- /dev/null +++ b/ui/src/lib/cubby/InspectorHead.svelte @@ -0,0 +1,42 @@ + + + +
+

{eyebrow}

+ {#if wide && media}{@render media()}{/if} +
+ {#if !wide && media}{@render media()}{/if} +
+

{title}

+ {#if sub}

{sub}

{/if} +
+
+ {#if meta}
{@render meta()}
{/if} +
diff --git a/ui/src/lib/cubby/InspectorNotice.svelte b/ui/src/lib/cubby/InspectorNotice.svelte new file mode 100644 index 0000000..797aceb --- /dev/null +++ b/ui/src/lib/cubby/InspectorNotice.svelte @@ -0,0 +1,16 @@ + + + +
+ +
+ {@render children()} + {#if action}{@render action()}{/if} +
+
diff --git a/ui/src/lib/cubby/InspectorPath.svelte b/ui/src/lib/cubby/InspectorPath.svelte new file mode 100644 index 0000000..85e9d89 --- /dev/null +++ b/ui/src/lib/cubby/InspectorPath.svelte @@ -0,0 +1,12 @@ + + + +
+ {path} + {#if oncopy}{/if} + {#if onopen}{/if} +
diff --git a/ui/src/lib/cubby/InspectorSection.svelte b/ui/src/lib/cubby/InspectorSection.svelte new file mode 100644 index 0000000..35590c0 --- /dev/null +++ b/ui/src/lib/cubby/InspectorSection.svelte @@ -0,0 +1,15 @@ + + + +
+
+

{title}{#if count != null && count !== ''} · {count}{/if}

+ {#if action}{@render action()}{/if} +
+ {@render children()} +
diff --git a/ui/src/lib/cubby/InspectorStatus.svelte b/ui/src/lib/cubby/InspectorStatus.svelte new file mode 100644 index 0000000..f5363be --- /dev/null +++ b/ui/src/lib/cubby/InspectorStatus.svelte @@ -0,0 +1,8 @@ + + + +{@render children()} diff --git a/ui/src/lib/cubby/Motd.svelte b/ui/src/lib/cubby/Motd.svelte new file mode 100644 index 0000000..cb1e2fe --- /dev/null +++ b/ui/src/lib/cubby/Motd.svelte @@ -0,0 +1,91 @@ + + + + + +
+ {#each lines as line, i (i)} +
{#each line.runs as run, j (j)}{run.text}{/each}
+ {/each} +
diff --git a/ui/src/lib/cubby/ServerRow.svelte b/ui/src/lib/cubby/ServerRow.svelte index 21b5eed..bc5166d 100644 --- a/ui/src/lib/cubby/ServerRow.svelte +++ b/ui/src/lib/cubby/ServerRow.svelte @@ -3,6 +3,7 @@ import Button from './Button.svelte'; import Icon from './Icon.svelte'; import StatusTag from './StatusTag.svelte'; + import Motd from './Motd.svelte'; import type { ServerRowProps } from './types'; let { @@ -10,6 +11,7 @@ address, iconSrc, motd, + motdFormatted, online: onlineProp, offlineText, players, @@ -35,28 +37,35 @@ {name} {address} -

{online ? motd : offlineText || t('Can’t reach server')}

+ {#if online && motdFormatted} + + {:else} +

{online ? motd : offlineText || t('Can’t reach server')}

+ {/if} +
- - {#if online && players} - + + + {#if online && players} - {players.online + '/' + players.max} + {players.online.toLocaleString() + ' / ' + players.max.toLocaleString()} {playersLabel || t('players online')} - - {/if} - {#if online} - - + + {#if online} + + + {ping == null ? '—' : pingText || ping + t(' ms')} - {ping == null ? '—' : pingText || ping + t(' ms')} - - {/if} + {/if} +
- {#if instance}{instance}{/if} + {#if instance}{instance}{/if}
diff --git a/ui/src/lib/cubby/index.ts b/ui/src/lib/cubby/index.ts index 703e5d0..17ba3de 100644 --- a/ui/src/lib/cubby/index.ts +++ b/ui/src/lib/cubby/index.ts @@ -31,11 +31,19 @@ export { default as InstanceRow } from './InstanceRow.svelte'; /* Content */ export { default as ModRow } from './ModRow.svelte'; export { default as ServerRow } from './ServerRow.svelte'; +export { default as Motd } from './Motd.svelte'; export { default as LogViewer } from './LogViewer.svelte'; /* Feedback */ export { default as Banner } from './Banner.svelte'; export { default as Dialog } from './Dialog.svelte'; export { default as Tooltips } from './Tooltips.svelte'; +/* Side panels */ +export { default as Inspector } from './Inspector.svelte'; +export { default as InspectorHead } from './InspectorHead.svelte'; +export { default as InspectorSection } from './InspectorSection.svelte'; +export { default as InspectorStatus } from './InspectorStatus.svelte'; +export { default as InspectorNotice } from './InspectorNotice.svelte'; +export { default as InspectorPath } from './InspectorPath.svelte'; /* Data and helpers */ export { diff --git a/ui/src/lib/cubby/types.ts b/ui/src/lib/cubby/types.ts index 790a2eb..f2d27ab 100644 --- a/ui/src/lib/cubby/types.ts +++ b/ui/src/lib/cubby/types.ts @@ -250,6 +250,8 @@ export interface ServerRowProps { address: string; iconSrc?: string; motd?: string; + /** The message of the day with its `§` codes: drawn in the game's colours when given. */ + motdFormatted?: string; online?: boolean; offlineText?: string; players?: { online: number; max: number }; diff --git a/ui/src/lib/dev/mock.ts b/ui/src/lib/dev/mock.ts index 6e25f50..652d08e 100644 --- a/ui/src/lib/dev/mock.ts +++ b/ui/src/lib/dev/mock.ts @@ -3,6 +3,7 @@ // that appear as installed. Add `?onboarding` to the URL to see the first-launch assistant. import { pixelArt, svgUrl } from './pixelart' +import { handleDatapackProject, handleExtra, NOT_HANDLED } from './mockExtra' import { OPTIONAL_MODS, PACKS, PACK_DESCRIPTION, PACK_MARKDOWN, PROVIDERS, SORTERS, morePacks, type MockPackDef } from './mockPacks' import type { Account, @@ -118,6 +119,7 @@ const inst = (p: Partial & Pick): Promise { + const datapack = handleDatapackProject(command, args) + if (datapack !== NOT_HANDLED) return datapack await sleep(60) switch (command) { case 'app_info': - return { version: '0.1.0', dataDir: 'C:\\Users\\Nyx\\AppData\\Roaming\\Cubby', msaConfigured: true, msaSource: 'builtIn', curseforgeKey: settings.curseforgeApiKey ? 'settings' : null, totalMemoryMb: 32768, devBuild: true } + return { version: '0.1.0', dataDir: 'C:\\Users\\Nyx\\AppData\\Roaming\\Cubby', msaConfigured: true, msaSource: 'builtIn', curseforgeKey: settings.curseforgeApiKey ? 'settings' : null, totalMemoryMb: 32768, devBuild: true, discord: true } case 'list_instances': return structuredClone(instances) case 'create_instance': { @@ -640,7 +645,7 @@ export async function handle(command: string, args: Record): Promis const host = String(args.address) if (host.startsWith('192.168.1.42') || host.startsWith('localhost')) return { online: false, motd: '', playersOnline: 0, playersMax: 0, version: null, pingMs: null, iconUrl: null } - if (host.startsWith('crew')) return { online: true, motd: 'Season 4 · back on Saturday', playersOnline: 5, playersMax: 20, version: '1.21.1', pingMs: 24, iconUrl: SERVER_ICONS.crew } + if (host.startsWith('crew')) return { online: true, motd: 'Season 4 · back on Saturday', motdFormatted: '§r§6§l The Crew §r§7· §aSeason 4\n§r§7 back on §bSaturday §r§8[1.21]', playersOnline: 5, playersMax: 20, version: '1.21.1', pingMs: 24, iconUrl: SERVER_ICONS.crew } if (host.includes('createfactory')) return { online: true, motd: 'Create Factory · 24/7 · whitelist on Discord', playersOnline: 87, playersMax: 100, version: '1.20.1', pingMs: 212, iconUrl: SERVER_ICONS.factory } return { online: true, motd: 'A Minecraft Server', playersOnline: host.length % 9, playersMax: 20, version: '1.21.1', pingMs: 40 + host.length, iconUrl: null } } @@ -740,9 +745,10 @@ export async function handle(command: string, args: Record): Promis { path: 'C:\\Users\\Nyx\\AppData\\Roaming\\PrismLauncher\\instances\\Vanilla 1.21', name: 'Vanilla 1.21', minecraft: '1.21', loader: { kind: 'vanilla' }, group: null }, { path: 'C:\\Users\\Nyx\\AppData\\Roaming\\PrismLauncher\\instances\\Fabulously Optimized', name: 'Fabulously Optimized', minecraft: '1.21.1', loader: { kind: 'fabric', version: '0.16.5' }, group: null }, ] - case 'import_prism': { + case 'import_prism': + case 'import_launcher_instances': { const imported = (args.paths as string[]).map((p) => { - const name = p.split('\\').pop()! + const name = p.split(/[\\/#]/).pop()! return inst({ id: slug(name), name, icon: null, minecraft: '1.21.1', loader: { kind: 'fabric', version: '0.16.5' } }) }) instances = [...instances, ...imported.filter((n) => !instances.some((i) => i.id === n.id))] @@ -1044,8 +1050,11 @@ export async function handle(command: string, args: Record): Promis return case 'delete_world': return - default: + default: { + const extra = await handleExtra(command, args) + if (extra !== NOT_HANDLED) return extra throw `Unknown command: ${command}` + } } } diff --git a/ui/src/lib/dev/mockExtra.ts b/ui/src/lib/dev/mockExtra.ts new file mode 100644 index 0000000..cf58c53 --- /dev/null +++ b/ui/src/lib/dev/mockExtra.ts @@ -0,0 +1,175 @@ +// Browser dev mode: sample answers for the commands added with datapacks, update undo, exports, launcher +// imports, shared options, shortcuts, world maps and Discord. See mock.ts. +import type { Datapack, Project, ProjectHit, ProjectVersion, UpdateBackup } from '../types' + +export const NOT_HANDLED = Symbol('not handled') + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) + +const datapacks = new Map([ + [ + 'friends-smp/Lake Village', + [ + { fileName: 'Terralith_1.21_v2.5.5.zip', name: 'Terralith_1.21_v2.5.5', isDir: false, enabled: true, size: 2_310_000, modified: '2026-10-02T18:00:00Z', description: 'Explore almost 100 new biomes' }, + { fileName: 'coordinates hud', name: 'coordinates hud', isDir: true, enabled: false, size: 12_400, modified: '2026-09-12T10:00:00Z', description: 'Shows your coordinates' }, + ], + ], +]) + +const DATAPACK_HITS: ProjectHit[] = [ + ['terralith', 'Terralith', 'Stardust Labs', 'Explore almost 100 new biomes consisting of both realism and light fantasy.', 9_800_000], + ['incendium', 'Incendium', 'Stardust Labs', 'A Nether overhaul with new biomes, structures and items.', 4_100_000], + ['dungeons-and-taverns', 'Dungeons and Taverns', 'nova_wostra', 'New structures to find on your travels.', 6_300_000], + ['veinminer', 'Veinminer', 'MiraculixxT', 'Mine a whole vein of ore at once.', 2_900_000], +].map(([slug, title, author, summary, downloads]) => ({ + id: `dp-${slug}`, + slug: slug as string, + title: title as string, + author: author as string, + summary: summary as string, + iconUrl: null, + categories: ['datapack'], + downloads: downloads as number, + follows: Math.round((downloads as number) / 300), + updated: '2026-10-20T10:00:00Z', + published: '2023-05-01T10:00:00Z', + gameVersions: ['1.21.1'], + loaders: ['datapack'], + kind: 'datapack', + clientSide: 'unsupported', + serverSide: 'required', + license: 'MIT', + featuredImage: null, +})) as unknown as ProjectHit[] + +const datapackHit = (idOrSlug: string) => DATAPACK_HITS.find((h) => h.id === idOrSlug || h.slug === idOrSlug) + +function datapackVersions(h: ProjectHit): ProjectVersion[] { + return ['1.21.1', '1.20.1'].map((mc, i) => ({ + id: `${h.id}-v${i}`, + projectId: h.id, + name: `${h.title} ${mc}`, + versionNumber: `2.${5 - i}.0`, + channel: 'release', + gameVersions: [mc], + loaders: ['datapack'], + published: new Date(Date.now() - (i + 1) * 9 * 86400e3).toISOString(), + downloads: 1000, + changelog: '- New structures\n- Fixes', + files: [{ url: 'https://cdn.example/x.zip', fileName: `${h.slug}-${mc}.zip`, size: 2_100_000, primary: true, sha1: 'a'.repeat(40) }], + dependencies: [], + })) +} + +/** Discover › Datapacks in the browser: searches, project pages and versions of the sample datapacks. */ +export function handleDatapackProject(command: string, args: Record): unknown { + if (command === 'search_projects' && args.query?.kind === 'datapack') { + const q = String(args.query.query ?? '').trim().toLowerCase() + const hits = DATAPACK_HITS.filter((h) => !q || `${h.title} ${h.summary}`.toLowerCase().includes(q)) + return Promise.resolve({ hits: structuredClone(hits), total: hits.length, offset: 0, limit: 20 }) + } + const hit = (command === 'get_project' || command === 'list_project_versions') && datapackHit(args.idOrSlug) + if (!hit) return NOT_HANDLED + if (command === 'list_project_versions') return Promise.resolve(datapackVersions(hit)) + const project: Project = { ...structuredClone(hit), body: hit.summary, gallery: [], links: { source: null, issues: null, wiki: null, discord: null, donation: [] }, versionCount: 2 } + return Promise.resolve(project) +} + +let updateBackups: UpdateBackup[] = [ + { + name: 'content-20261106-201500', + created: '2026-11-06T19:15:00Z', + files: [ + { folder: 'mods', old: 'sodium-fabric-0.5.11+mc1.21.jar', new: 'sodium-fabric-0.6.0+mc1.21.1.jar' }, + { folder: 'mods', old: 'lithium-fabric-0.13.0.jar', new: 'lithium-fabric-0.14.3.jar' }, + ], + }, +] + +export async function handleExtra(command: string, args: Record): Promise { + switch (command) { + case 'list_datapacks': + await sleep(150) + return structuredClone(datapacks.get(`${args.id}/${args.world}`) ?? []) + case 'set_datapack_enabled': { + const p = datapacks.get(`${args.id}/${args.world}`)?.find((d) => d.fileName === args.fileName) + if (p) p.enabled = args.enabled + return + } + case 'remove_datapack': { + const key = `${args.id}/${args.world}` + datapacks.set(key, (datapacks.get(key) ?? []).filter((d) => d.fileName !== args.fileName)) + return + } + case 'add_datapack_files': + return [] + case 'install_datapack': { + await sleep(800) + const hit = DATAPACK_HITS.find((h) => h.id === args.projectId) + const fileName = `${hit?.title ?? 'Datapack'}.zip` + const key = `${args.id}/${args.world}` + const list = (datapacks.get(key) ?? []).filter((d) => d.fileName !== fileName) + list.push({ fileName, name: fileName.slice(0, -4), isDir: false, enabled: true, size: 1_200_000, modified: new Date().toISOString(), description: hit?.summary ?? null }) + datapacks.set(key, list) + return fileName + } + case 'list_update_backups': + return args.instanceId === 'friends-smp' ? structuredClone(updateBackups) : [] + case 'undo_update': { + await sleep(700) + const b = updateBackups.find((x) => x.name === args.name) + updateBackups = updateBackups.filter((x) => x.name !== args.name) + return b?.files.length ?? 0 + } + case 'export_candidates': + return [ + { name: 'config', isDir: true, size: 1_840_000, suggested: true }, + { name: 'options.txt', isDir: false, size: 5_600, suggested: true }, + { name: 'saves', isDir: true, size: 412_000_000, suggested: false }, + { name: 'servers.dat', isDir: false, size: 420, suggested: false }, + ] + case 'export_instance': + await sleep(1200) + return { path: `/Users/you/Downloads/${args.request.name} ${args.request.version}.${args.request.format === 'mrpack' ? 'mrpack' : 'zip'}`, listed: 34, stored: 6, withoutKey: false } + case 'reveal_file': + return + case 'list_launcher_instances': { + await sleep(400) + const prism = 'C:\\Users\\Nyx\\AppData\\Roaming\\PrismLauncher\\instances\\' + return [ + { launcher: 'prism', launcherName: 'Prism Launcher', path: `${prism}Skyfactory`, name: 'Skyfactory', minecraft: '1.16.5', loader: { kind: 'forge', version: '36.2.39' }, group: 'Modpacks', gameDir: `${prism}Skyfactory\\minecraft` }, + { launcher: 'prism', launcherName: 'Prism Launcher', path: `${prism}Vanilla 1.21`, name: 'Vanilla 1.21', minecraft: '1.21', loader: { kind: 'vanilla' }, group: null, gameDir: `${prism}Vanilla 1.21\\minecraft` }, + { launcher: 'curseForge', launcherName: 'CurseForge', path: 'C:\\Users\\Nyx\\curseforge\\minecraft\\Instances\\All the Mods 9', name: 'All the Mods 9', minecraft: '1.20.1', loader: { kind: 'forge', version: '47.3.0' }, group: null, gameDir: 'C:\\Users\\Nyx\\curseforge\\minecraft\\Instances\\All the Mods 9' }, + { launcher: 'modrinthApp', launcherName: 'Modrinth App', path: 'C:\\Users\\Nyx\\AppData\\Roaming\\ModrinthApp\\profiles\\Fabulously Optimized', name: 'Fabulously Optimized', minecraft: null, loader: { kind: 'vanilla' }, group: null, gameDir: 'C:\\Users\\Nyx\\AppData\\Roaming\\ModrinthApp\\profiles\\Fabulously Optimized' }, + { launcher: 'official', launcherName: 'Minecraft Launcher', path: 'C:\\Users\\Nyx\\AppData\\Roaming\\.minecraft\\launcher_profiles.json#a1', name: 'Fabric 1.21.1', minecraft: '1.21.1', loader: { kind: 'fabric', version: '0.16.5' }, group: null, gameDir: 'C:\\Users\\Nyx\\AppData\\Roaming\\.minecraft' }, + ] + } + case 'copy_options': + await sleep(300) + return { ...args.what } + case 'create_desktop_shortcut': + return `/Users/you/Desktop/${args.id}.app` + case 'render_world_map': { + await sleep(900) + return { url: mockMap(), minX: -384, minZ: -384, size: 768, chunks: 1840 } + } + default: + return NOT_HANDLED + } +} + +/** A made-up landscape: water, sand, grass and forest from a few waves. */ +function mockMap(): string { + const size = 96 + const canvas = document.createElement('canvas') + canvas.width = canvas.height = size + const ctx = canvas.getContext('2d')! + for (let z = 0; z < size; z++) { + for (let x = 0; x < size; x++) { + const h = Math.sin(x / 9) + Math.cos(z / 11) + Math.sin((x + z) / 17) * 0.8 + ctx.fillStyle = h < -0.6 ? '#345cc4' : h < -0.35 ? '#dbcfa3' : h < 1 ? (Math.random() < 0.06 ? '#376e23' : '#76a846') : h < 1.6 ? '#376e23' : '#7d7d7d' + ctx.fillRect(x, z, 1, 1) + } + } + return canvas.toDataURL() +} diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts new file mode 100644 index 0000000..6d8a37c --- /dev/null +++ b/ui/src/lib/i18n/fr-10.ts @@ -0,0 +1,249 @@ +// French: automatic memory, world datapacks, undoing updates, exports, imports from other launchers, +// shared game options, desktop shortcuts, world maps and Discord. See fr.ts. +import type { Entry } from '../i18n.svelte' + +export const FR_10: Record = { + // Automatic memory + 'Set memory automatically': 'Régler la mémoire automatiquement', + 'Each instance gets what its mods need: 2 GB for Vanilla, up to 8 GB for big modpacks, never more than half of your {total}.': + 'Chaque instance reçoit ce dont ses mods ont besoin : 2 Go pour Vanilla, jusqu’à 8 Go pour les gros modpacks, jamais plus de la moitié de vos {total}.', + memory: 'mémoire', + 'Every instance that doesn’t set its own gets the memory below.': 'Les instances qui n’ont pas leur propre réglage reçoivent la mémoire ci-dessous.', + '{n}, set from its mods': '{n}, selon ses mods', + ' (automatic)': ' (automatique)', + + // Datapacks + 'Datapacks · {length}': 'Datapacks · {length}', + 'Reading datapacks…': 'Lecture des datapacks…', + 'No datapacks in this world. They add structures, biomes or rules to one world, without mods.': + 'Aucun datapack dans ce monde. Ils ajoutent des structures, des biomes ou des règles à un monde, sans mods.', + Folder: 'Dossier', + 'Load {name} in this world': 'Charger {name} dans ce monde', + 'Remove {name}': 'Retirer {name}', + 'Find on Modrinth': 'Chercher sur Modrinth', + 'Add from file': 'Ajouter un fichier', + 'Close the game to change datapacks. They load when the world opens.': 'Fermez le jeu pour changer les datapacks. Ils se chargent à l’ouverture du monde.', + datapack: ['datapack', 'datapacks'], + 'Added {n} to {world}.': '{n} ajouté(s) à {world}.', + 'Datapacks for {world}': 'Datapacks pour {world}', + 'Search datapacks': 'Chercher des datapacks', + 'Search datapacks for {minecraft}': 'Chercher des datapacks pour {minecraft}', + 'Searching Modrinth…': 'Recherche sur Modrinth…', + 'No datapacks for Minecraft {minecraft} match.': 'Aucun datapack pour Minecraft {minecraft} ne correspond.', + '{author} · {downloads} downloads': '{author} · {downloads} téléchargements', + Added: 'Ajouté', + Add: 'Ajouter', + '{title} is in {world}.': '{title} est dans {world}.', + '{name} moved to the instance’s trash folder.': '{name} a été déplacé dans la corbeille de l’instance.', + + // Reviewing and undoing updates + 'Undo last update': 'Annuler la dernière mise à jour', + 'Update {n}': 'Mettre à jour {n}', + file: ['fichier', 'fichiers'], + 'What’s new': 'Nouveautés', + 'Cubby keeps the old files, so you can undo the update if something breaks.': 'Cubby garde les anciens fichiers : vous pourrez annuler la mise à jour si quelque chose casse.', + 'No changelog for this version.': 'Pas de notes de version pour cette version.', + 'Undo update': 'Annuler la mise à jour', + 'Undo the update from {when}?': 'Annuler la mise à jour du {when} ?', + 'These files go back to the version you had before. The newer files move to the instance’s trash folder.': + 'Ces fichiers reviennent à la version d’avant. Les plus récents vont dans la corbeille de l’instance.', + 'Put back {n} from before the update.': '{n} remis comme avant la mise à jour.', + + // Export + 'Export as a modpack file': 'Exporter en fichier modpack', + 'Export {name}': 'Exporter {name}', + Export: 'Exporter', + 'Show in folder': 'Afficher dans le dossier', + 'Saved to': 'Enregistré dans', + '{listed} downloaded by the launcher that opens it, {stored} stored in the file.': '{listed} téléchargés par le launcher qui l’ouvre, {stored} stockés dans le fichier.', + 'Without a CurseForge API key, Cubby can’t tell which mods CurseForge has, so they are all stored in the file. It works, but the file is bigger.': + 'Sans clé d’API CurseForge, Cubby ne sait pas quels mods CurseForge propose : ils sont tous stockés dans le fichier. Ça marche, mais le fichier est plus lourd.', + Format: 'Format', + 'Opens in Cubby, the Modrinth App, Prism Launcher and most launchers. Mods from Modrinth are downloaded from there, the others are stored in the file.': + 'S’ouvre dans Cubby, la Modrinth App, Prism Launcher et la plupart des launchers. Les mods de Modrinth sont téléchargés depuis Modrinth, les autres sont stockés dans le fichier.', + 'Opens in the CurseForge app, Cubby and Prism Launcher. Mods CurseForge has are downloaded from there, the others are stored in the file.': + 'S’ouvre dans l’app CurseForge, Cubby et Prism Launcher. Les mods présents sur CurseForge en sont téléchargés, les autres sont stockés dans le fichier.', + 'No CurseForge API key': 'Pas de clé d’API CurseForge', + 'Every mod will be stored in the file.': 'Tous les mods seront stockés dans le fichier.', + 'Pack name': 'Nom du pack', + Version: 'Version', + Summary: 'Résumé', + Author: 'Auteur', + 'Also include': 'Inclure aussi', + 'Mods, resource packs and shader packs are always in. Turned-off mods are left out.': 'Les mods, resource packs et shader packs sont toujours inclus. Les mods désactivés sont exclus.', + 'Reading the instance…': 'Lecture de l’instance…', + 'Nothing else in this instance yet.': 'Rien d’autre dans cette instance pour l’instant.', + 'Writing the pack': 'Écriture du pack', + + // Importing from other launchers + 'Import from another launcher': 'Importer depuis un autre launcher', + 'Copies instances, the other launcher stays as it is': 'Copie les instances, l’autre launcher reste tel quel', + 'Imported {n}.': '{n} importée(s).', + 'Looking for other launchers…': 'Recherche des autres launchers…', + 'Couldn’t read the other launchers’ instances': 'Impossible de lire les instances des autres launchers', + 'No other launcher found': 'Aucun autre launcher trouvé', + 'Cubby looks for Prism Launcher, MultiMC, PolyMC, CurseForge, ATLauncher, GDLauncher, the Modrinth App and the Minecraft Launcher in their usual folders.': + 'Cubby cherche Prism Launcher, MultiMC, PolyMC, CurseForge, ATLauncher, GDLauncher, la Modrinth App et le Minecraft Launcher dans leurs dossiers habituels.', + '{launcher} instances': 'Instances de {launcher}', + 'Version unknown: export it as a .mrpack from {launcher}, then import the file.': 'Version inconnue : exportez-la en .mrpack depuis {launcher}, puis importez le fichier.', + 'Safe: Cubby copies the mods, worlds, screenshots and settings. The other launchers stay as they are.': + 'Sans risque : Cubby copie les mods, mondes, captures et réglages. Les autres launchers restent tels quels.', + + // Copying options + 'Game options': 'Options du jeu', + 'Copy from another instance': 'Copier depuis une autre instance', + 'Bring over your key bindings, options or server list, so a new instance feels like home.': + 'Récupérez vos touches, options ou serveurs : une nouvelle instance est tout de suite à votre goût.', + Copy: 'Copier', + 'Copy settings into {name}': 'Copier des réglages dans {name}', + 'There is no other instance to copy from yet.': 'Il n’y a pas encore d’autre instance depuis laquelle copier.', + From: 'Depuis', + 'Key bindings': 'Touches', + 'Your controls: jump, sprint, and the keys mods add.': 'Vos contrôles : sauter, sprinter, et les touches ajoutées par les mods.', + 'Video, sound and other options': 'Vidéo, son et autres options', + 'Render distance, FOV, volume, language... Resource packs stay as they are.': 'Distance d’affichage, FOV, volume, langue… Les resource packs ne changent pas.', + 'Server list': 'Liste des serveurs', + 'Replaces the Multiplayer list of this instance.': 'Remplace la liste Multijoueur de cette instance.', + 'Close the game first: it writes its options when it quits.': 'Fermez d’abord le jeu : il enregistre ses options en quittant.', + options: 'options', + 'key bindings': 'touches', + servers: 'serveurs', + 'Copied the {parts} of {name}.': '{parts} de {name} copiés.', + '{name} has nothing to copy yet. Play it once first.': '{name} n’a encore rien à copier. Lancez-la une fois d’abord.', + + // Desktop shortcuts + 'Add to desktop': 'Ajouter au bureau', + 'A shortcut to {name} is on your desktop. Double-click it to play.': 'Un raccourci vers {name} est sur votre bureau. Double-cliquez dessus pour jouer.', + 'That shortcut’s instance isn’t in Cubby anymore.': 'L’instance de ce raccourci n’est plus dans Cubby.', + + // World map + Map: 'Carte', + 'Show the map of {name} bigger': 'Agrandir la carte de {name}', + 'Map of {name} around its spawn': 'Carte de {name} autour du point d’apparition', + '{n} blocks around the spawn · {chunks} chunks explored': '{n} blocs autour du point d’apparition · {chunks} chunks explorés', + 'Drawing the map': 'Dessin de la carte', + 'See the land around the spawn from above.': 'Voyez les environs du point d’apparition vus du ciel.', + 'Draw again': 'Redessiner', + 'Draw the map': 'Dessiner la carte', + 'From {x}, {z} to {x2}, {z2}. The red dot is the spawn.': 'De {x}, {z} à {x2}, {z2}. Le point rouge est le point d’apparition.', + 'This world has no map yet: play in it once, then draw it.': 'Ce monde n’a pas encore de carte : jouez-y une fois, puis dessinez-la.', + + // Discord + 'Show on Discord': 'Afficher sur Discord', + 'Your Discord profile says which instance you’re playing, while you play. Discord has to be open on this computer.': + 'Votre profil Discord indique à quelle instance vous jouez, pendant la partie. Discord doit être ouvert sur cet ordinateur.', + + // Import footer + 'Coming from Prism, CurseForge, the Modrinth App or another launcher?': 'Vous venez de Prism, CurseForge, Modrinth App ou d’un autre launcher ?', + 'Import its instances': 'Importer ses instances', + + // Mod details + 'Show less': 'Afficher moins', + 'Show all {n} changes': 'Afficher les {n} changements', + 'Turned on': 'Activé', + 'Turned off': 'Désactivé', + + // Crash: two mods the loader says don't work together + ' says it doesn’t work with ': ' indique ne pas fonctionner avec ', + ', and you have ': ', et vous avez ', + '. The loader stopped before the game started. A newer ': '. Le loader s’est arrêté avant le lancement du jeu. Une version plus récente de ', + ' usually fixes it. Your PC is fine.': ' règle généralement le problème. Votre PC va bien.', + 'Here marks the line that names them.': 'Le repère indique la ligne qui les nomme.', + 'the other mod': 'l’autre mod', + ' needs a newer ': ' a besoin d’une version plus récente de ', + '. Opens the mods of {n}.': '. Ouvre les mods de {n}.', + 'Undo the last update': 'Annuler la dernière mise à jour', + 'Puts back the {n} the last update replaced, so you play as before.': 'Remet les {n} remplacés par la dernière mise à jour : vous jouez comme avant.', + 'Update again from Mods': 'Remettez à jour depuis Mods', + 'Back as before': 'Revenu comme avant', + + // Discover › Datapacks + Datapacks: 'Datapacks', + datapacks: 'datapacks', + 'Datapacks add structures, biomes, recipes or rules to one world, without mods: they work in Vanilla too. Cubby puts them in the world you pick.': + 'Les datapacks ajoutent des structures, des biomes, des recettes ou des règles à un monde, sans mods : ils marchent aussi en Vanilla. Cubby les met dans le monde que vous choisissez.', + 'Into world': 'Dans le monde', + 'Into {world}. Change world': 'Dans {world}. Changer de monde', + '{name} has no world yet. Play it once and create one.': '{name} n’a pas encore de monde. Lancez-la et créez-en un.', + World: 'Monde', + 'Couldn’t load the versions': 'Impossible de charger les versions', + 'Loading versions…': 'Chargement des versions…', + '{title} has no datapack version: it only comes as a mod.': '{title} n’a pas de version datapack : il n’existe qu’en mod.', + 'This version isn’t made for Minecraft {mc}. The world may not load it.': 'Cette version n’est pas faite pour Minecraft {mc}. Le monde risque de ne pas la charger.', + 'In the world': 'Dans le monde', + 'See its datapacks': 'Voir ses datapacks', + 'Install · {size}': 'Installer · {size}', + 'Close the game first: the world reads its datapacks when it opens.': 'Fermez d’abord le jeu : le monde lit ses datapacks à l’ouverture.', + 'This version has no .zip to put in a world.': 'Cette version n’a pas de .zip à mettre dans un monde.', + '{title} is in the world. It loads the next time you open it.': '{title} est dans le monde. Il se charge à la prochaine ouverture.', + 'Only the world you put it in. New chunks may look different, and its changes stay in that world. Back the world up first.': + 'Seulement le monde où vous le mettez. Les nouveaux chunks peuvent changer, et ses effets restent dans ce monde. Sauvegardez le monde avant.', + 'Does it need mods?': 'Faut-il des mods ?', + 'No. Datapacks work in Vanilla too. On a server, the server puts them in its own world.': 'Non. Les datapacks marchent aussi en Vanilla. Sur un serveur, c’est le serveur qui les met dans son monde.', + 'In the instance\'s Worlds tab, under the world. It loads the next time you open the world.': 'Dans l’onglet Mondes de l’instance, sous le monde. Il se charge à la prochaine ouverture du monde.', + + // Side panels + 'Add a server to see who’s online and join it in one click.': 'Ajoutez un serveur pour voir qui est en ligne et le rejoindre en un clic.', + 'All settings': 'Tous les réglages', + 'Backups': 'Sauvegardes', + 'Can join': 'Peut rejoindre', + 'Can’t reach it': 'Injoignable', + 'Cause found': 'Cause trouvée', + 'Cause not found': 'Cause introuvable', + 'Changes show in game and on servers within a minute.': 'Le changement apparaît en jeu et sur les serveurs en moins d’une minute.', + 'Clean': 'Nettoyer', + 'Close the game to change resource packs.': 'Fermez le jeu pour changer les resource packs.', + 'Close the game to restore a backup, change datapacks or delete this world.': 'Fermez le jeu pour restaurer une sauvegarde, changer les datapacks ou supprimer ce monde.', + 'Crash': 'Crash', + 'Cubby found what most likely went wrong': 'Cubby a trouvé la cause la plus probable', + 'Datapacks add structures, biomes or rules to one world, without mods.': 'Les datapacks ajoutent des structures, des biomes ou des règles à un monde, sans mods.', + 'Fit': 'Compatibilité', + 'Fits': 'Compatible', + 'Folders': 'Dossiers', + 'Free up space': 'Libérer de l’espace', + 'Game running': 'Jeu lancé', + 'Installed twice.': 'Installé deux fois.', + 'Known when online': 'Connue quand il est en ligne', + 'Last played {when}': 'Dernière partie {when}', + 'May not get in': 'Risque d’être refusé', + 'Minecraft {minecraft} can’t open a world from a launcher: Play starts on the title screen.': 'Minecraft {minecraft} ne peut pas ouvrir un monde depuis un launcher : Jouer démarre sur l’écran titre.', + 'Move down': 'Descendre', + 'Move up': 'Monter', + 'Moves the file to the instance’s trash.': 'Déplace le fichier dans la corbeille de l’instance.', + 'Moves the pack to the instance’s trash.': 'Déplace le pack dans la corbeille de l’instance.', + 'No backups yet. A backup is a zip of the world you can go back to.': 'Pas encore de sauvegarde. Une sauvegarde est un zip du monde auquel vous pouvez revenir.', + 'No mod selected': 'Aucun mod sélectionné', + 'No resource packs': 'Aucun resource pack', + 'No screenshot selected': 'Aucune capture sélectionnée', + 'No server selected': 'Aucun serveur sélectionné', + 'No shaders': 'Pas de shaders', + 'Not applied yet': 'Pas encore appliqué', + 'On · {n} of {n2}': 'Activé · {n} sur {n2}', + 'Owns Java Edition': 'Possède Java Edition', + 'Pick a mod in the list to see what it does, its version and its file.': 'Choisissez un mod dans la liste pour voir ce qu’il fait, sa version et son fichier.', + 'Play this world': 'Jouer à ce monde', + 'Play, then create a world in Singleplayer. It shows up here with its backups, map and datapacks.': 'Lancez le jeu, puis créez un monde en Solo. Il apparaîtra ici avec ses sauvegardes, sa carte et ses datapacks.', + 'Position': 'Position', + 'Press F2 in game to take one': 'Appuyez sur F2 en jeu pour en prendre une', + 'Removes the account from Cubby. Your Minecraft stays yours.': 'Retire le compte de Cubby. Votre Minecraft reste à vous.', + 'Resource packs change textures, sounds and fonts, without mods.': 'Les resource packs changent les textures, les sons et les polices, sans mods.', + 'Screenshot': 'Capture', + 'Screenshots you take while playing show up here.': 'Les captures que vous prenez en jouant apparaissent ici.', + 'Screenshots you take while playing show up here. Pick one to see it larger, copy it or delete it.': 'Les captures que vous prenez en jouant apparaissent ici. Choisissez-en une pour l’agrandir, la copier ou la supprimer.', + 'Select a screenshot to see it larger, copy it or delete it.': 'Sélectionnez une capture pour l’agrandir, la copier ou la supprimer.', + 'Select a server to see who’s online and join it.': 'Sélectionnez un serveur pour voir qui est en ligne et le rejoindre.', + 'Should work': 'Devrait fonctionner', + 'Taken': 'Prise', + 'Takes it off the server list.': 'Le retire de la liste des serveurs.', + 'Takes it off this instance’s server list.': 'Le retire de la liste des serveurs de cette instance.', + 'The game’s normal look': 'L’apparence normale du jeu', + 'The pack on top wins. Changes apply the next time you start the game.': 'Le pack du haut l’emporte. Les changements s’appliquent au prochain lancement du jeu.', + 'The server runs {version}, and this instance uses {minecraft}.': 'Le serveur tourne en {version}, et cette instance utilise {minecraft}.', + 'This instance uses the game’s textures': 'Cette instance utilise les textures du jeu', + 'Use none': 'Aucun', + 'Version not given': 'Version non indiquée', + 'What you wear now': 'Ce que vous portez', + 'Your player ID on every server': 'Votre identifiant de joueur sur tous les serveurs', + '{name} is running': '{name} est lancé', + '{name} may not get in.': '{name} risque d’être refusé.', +} diff --git a/ui/src/lib/i18n/fr.ts b/ui/src/lib/i18n/fr.ts index 80e255c..d56325a 100644 --- a/ui/src/lib/i18n/fr.ts +++ b/ui/src/lib/i18n/fr.ts @@ -11,11 +11,13 @@ import { FR_6 } from './fr-6' import { FR_7 } from './fr-7' import { FR_8 } from './fr-8' import { FR_9 } from './fr-9' +import { FR_10 } from './fr-10' export const FR: Record = { ...FR_7, ...FR_8, ...FR_9, + ...FR_10, ...FR_1, ...FR_2, ...FR_3, diff --git a/ui/src/lib/state.svelte.ts b/ui/src/lib/state.svelte.ts index cb34fe1..a15ab0a 100644 --- a/ui/src/lib/state.svelte.ts +++ b/ui/src/lib/state.svelte.ts @@ -200,6 +200,14 @@ class AppState { return [...counts.entries()].map(([name, count]) => ({ name, count })) } + /** The maximum memory the game gets when this instance starts (MB): its own value, else the automatic or global one. */ + memoryOf(instance: Instance): number { + const java = this.settings?.java + if (instance.javaOverrides.maxMemoryMb != null) return instance.javaOverrides.maxMemoryMb + if ((java?.autoMemory ?? true) && instance.recommendedMemoryMb) return instance.recommendedMemoryMb + return java?.maxMemoryMb ?? 4096 + } + get recent(): Instance[] { return [...this.instances].sort((a, b) => (b.lastPlayed ?? '').localeCompare(a.lastPlayed ?? '') || a.name.localeCompare(b.name)) } @@ -214,10 +222,24 @@ class AppState { } setTarget(id: string) { + if (id !== this.targetId) this.targetWorld = null this.targetId = id store('targetId', id) } + /** The world of the target instance datapacks go into (its folder in saves/); null = the most recent one. */ + targetWorld = $state(null) + + /** Discover › Datapacks, installing into this world of this instance. */ + openDatapacks(instanceId: string, world: string) { + this.setTarget(instanceId) + this.targetWorld = world + this.discover.kind = 'datapack' + this.discover.categories = [] + this.discover.page = 0 + this.navigate({ name: 'discover' }) + } + setLibraryView(view: 'grid' | 'list') { this.libraryView = view store('libraryView', view) @@ -257,10 +279,31 @@ class AppState { return unlisten } - /** cubby://pack/ links (the "Open in Cubby" button of a shared pack's page) open New instance › From a link. */ + /** cubby://pack/ links (the "Open in Cubby" button of a shared pack's page) open New instance › From a link. + * cubby://play/ links (desktop shortcuts) start that instance. */ private listenForLinks() { if (!inTauri) return - const open = (urls: string[] | null | undefined) => { + const open = (urls: string[] | null | undefined, atStart = false) => { + const play = urls?.find((u) => u.toLowerCase().startsWith('cubby://play/')) + if (play) { + // The link Cubby started with comes back on every page load (a language change reloads): play it once. + if (atStart) { + try { + if (sessionStorage.getItem('cubby.startLink') === play) return + sessionStorage.setItem('cubby.startLink', play) + } catch { + /* no storage: play it */ + } + } + const id = decodeURIComponent(play.slice('cubby://play/'.length).replace(/\/+$/, '')) + if (this.instance(id)) { + this.selected = id + void this.launch(id) + } else { + this.toast(t('That shortcut’s instance isn’t in Cubby anymore.'), 'error') + } + return + } const link = urls?.find((u) => u.toLowerCase().startsWith('cubby://pack/')) if (!link) return this.pendingPackLink = link @@ -268,7 +311,7 @@ class AppState { this.navigate({ name: 'create' }) } void import('@tauri-apps/plugin-deep-link').then(async (m) => { - open(await m.getCurrent().catch(() => null)) + open(await m.getCurrent().catch(() => null), true) await m.onOpenUrl(open) }).catch((e) => console.warn('deep links unavailable', e)) } @@ -592,4 +635,8 @@ class AppState { } } -export const app = new AppState() +// One state for the whole app. In development, a hot reload of this module (or of one it imports, like a catalog +// of texts) would otherwise make a second one: the screens it reloads would read and navigate a state the rest of +// the window doesn't show (links doing nothing, the account missing). The first one is kept across reloads. +export const app: AppState = (import.meta.hot?.data.app as AppState | undefined) ?? new AppState() +if (import.meta.hot) import.meta.hot.data.app = app diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index ecd37c4..c1028a9 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -27,6 +27,8 @@ export interface Instance { modpack: { projectId: string; versionId: string; title: string; versionNumber: string } | null /** Files of a modpack still to download by hand (0 normally). */ blockedFiles: number + /** The memory "Set memory automatically" gives this instance (MB), from its mods and the computer's memory. */ + recommendedMemoryMb: number } export interface JavaOverrides { @@ -156,7 +158,8 @@ export interface Settings { accent: string frameMode: 'instance' | 'fixed' | 'none' frameColor: string - java: { auto: boolean; minMemoryMb: number; maxMemoryMb: number; jvmArgs: string } + /** autoMemory: each instance gets `recommendedMemoryMb` instead of `maxMemoryMb`. */ + java: { auto: boolean; autoMemory: boolean; minMemoryMb: number; maxMemoryMb: number; jvmArgs: string } game: { width: number; height: number; fullscreen: boolean } onLaunch: 'minimize' | 'keep' | 'close' downloadConcurrency: number @@ -173,6 +176,8 @@ export interface Settings { curseforgeApiKey: string | null /** The first-launch assistant was completed or skipped. */ onboarded: boolean + /** Show the instance being played on the player's Discord profile. */ + discordPresence: boolean } export interface PrismInstance { @@ -199,6 +204,8 @@ export interface AppInfo { totalMemoryMb: number /** Development build: without an account the full game starts offline instead of the demo. */ devBuild: boolean + /** This build can show the game on Discord (it has a Discord application id). */ + discord: boolean } export type CubbyEvent = @@ -234,6 +241,8 @@ export interface Server { export interface ServerStatus { online: boolean motd: string + /** The message of the day with its `§` colour and style codes (draw it with Motd). */ + motdFormatted?: string playersOnline: number playersMax: number version: string | null @@ -244,7 +253,7 @@ export interface ServerStatus { } // Discover (Modrinth) -export type ProjectKind = 'mod' | 'modpack' | 'shader' | 'resourcepack' +export type ProjectKind = 'mod' | 'modpack' | 'shader' | 'resourcepack' | 'datapack' export type ProjectSort = 'relevance' | 'downloads' | 'follows' | 'newest' | 'updated' /** Where a project runs, from Modrinth's client_side / server_side. */ export type SideSupport = 'required' | 'optional' | 'unsupported' | 'unknown' @@ -522,3 +531,86 @@ export interface PackFileInfo { /** CurseForge zip and no API key: it can't be installed, and this says why. */ blockedReason: string | null } + +/** A datapack of a world (`saves//datapacks`; turned off ones wait in `datapacks.disabled`). */ +export interface Datapack { + fileName: string + /** The file name without `.zip`. */ + name: string + isDir: boolean + enabled: boolean + size: number + modified: string | null + description: string | null +} + +/** An update that can be undone: its old files are kept in /backups//. */ +export interface UpdateBackup { + name: string + created: string + /** folder: "mods", "resourcepacks" or "shaderpacks"; old: the file before, new: the file the update put in. */ + files: { folder: string; old: string; new: string }[] +} + +/** A top-level file or folder of an instance that an export can include. */ +export interface ExportCandidate { + name: string + isDir: boolean + size: number + /** Usually shipped with a pack (config, options.txt...). */ + suggested: boolean +} + +export interface ExportRequest { + format: 'mrpack' | 'curseforge' + name: string + version: string + /** Summary (Modrinth) or author (CurseForge). */ + note: string + include: string[] +} + +export interface ExportResult { + path: string + /** Files the launcher that opens it downloads. */ + listed: number + /** Files stored inside the pack. */ + stored: number + /** CurseForge without an API key: every mod is stored. */ + withoutKey: boolean +} + +/** An instance of another launcher (Prism, MultiMC, CurseForge, ATLauncher, GDLauncher, Modrinth App, Minecraft Launcher). */ +export interface ForeignInstance { + launcher: 'prism' | 'multiMc' | 'polyMc' | 'curseForge' | 'atLauncher' | 'gdLauncher' | 'modrinthApp' | 'official' + launcherName: string + /** What importLauncherInstances takes. */ + path: string + name: string + /** null when the launcher doesn't say: it can't be imported. */ + minecraft: string | null + loader: Loader + group: string | null + gameDir: string +} + +/** What copyOptions copies, and what it did copy. */ +export interface OptionsCopy { + /** options.txt without the key bindings */ + options: boolean + /** the key_* lines of options.txt */ + keys: boolean + /** servers.dat */ + servers: boolean +} + +/** A world's map around its spawn, drawn by renderWorldMap. */ +export interface WorldMapImage { + url: string + /** Block coordinates of the top-left pixel. */ + minX: number + minZ: number + /** Width and height, in blocks (one pixel per block). */ + size: number + chunks: number +} diff --git a/ui/src/lib/views/accounts/Accounts.svelte b/ui/src/lib/views/accounts/Accounts.svelte index da2015e..72c72c8 100644 --- a/ui/src/lib/views/accounts/Accounts.svelte +++ b/ui/src/lib/views/accounts/Accounts.svelte @@ -110,7 +110,7 @@ + +
+ {#if !compact}

{t('Install')}

{/if} +
+ {t('Install to')} + +
+
+ {t('Into world')} + +
+ + {#if failed} + {failed} + {:else if all === null} +

{t('Loading versions…')}

+ {:else if !ordered.length} +

{t('{title} has no datapack version: it only comes as a mod.', { title: project.title })}

+ {:else if chosen} +
+ {t('Version')} + (versionId = id)} label={t('Version')} listWidth={340}> + {#snippet trigger()} + + {chosen.versionNumber} + {CHANNEL[chosen.channel].word} · {mcRange(chosen.gameVersions)} + + {/snippet} + {#snippet option(item)} + + {item.v.versionNumber} + {CHANNEL[item.v.channel].word} · {mcRange(item.v.gameVersions)} · {relativeTime(item.v.published, '')} + + {/snippet} + +
+ {#if target && !chosenFits} +

{t('This version isn’t made for Minecraft {mc}. The world may not load it.', { mc: target.minecraft })}

+ {/if} + {#if done.includes(key)} +
+ {t('In the world')} + +
+ {:else} + + {#if running}

{t('Close the game first: the world reads its datapacks when it opens.')}

{/if} + {#if !zip}

{t('This version has no .zip to put in a world.')}

{/if} + {/if} + {/if} +
+ + diff --git a/ui/src/lib/views/discover/Discover.svelte b/ui/src/lib/views/discover/Discover.svelte index 7fceb5b..b8ebb37 100644 --- a/ui/src/lib/views/discover/Discover.svelte +++ b/ui/src/lib/views/discover/Discover.svelte @@ -22,11 +22,13 @@ import InstallPanel from './InstallPanel.svelte' import Picker from './Picker.svelte' import TargetPicker from './TargetPicker.svelte' + import WorldPicker from './WorldPicker.svelte' + import DatapackInstall from './DatapackInstall.svelte' import { CATEGORIES, KINDS, KIND_ORDER, PAGE_SIZE, categoryLabel, hitFit, type Fit } from './discover' const d = $derived(app.discover) /** Where this tab can look: every provider for modpacks, Modrinth and CurseForge for the rest, in the app's order. */ - const sources = $derived((app.providers ?? []).filter((p) => d.kind === 'modpack' || p.id === 'modrinth' || p.id === 'curseforge')) + const sources = $derived((app.providers ?? []).filter((p) => d.kind === 'modpack' || p.id === 'modrinth' || (p.id === 'curseforge' && d.kind !== 'datapack'))) /** The chosen source, or Modrinth when this tab doesn't offer it. */ const source = $derived(sources.some((p) => p.id === d.provider) ? d.provider : 'modrinth') /** Modpacks of another provider (ATLauncher, CurseForge, FTB, Technic): same grid, searched through the pack commands. */ @@ -165,7 +167,7 @@ const localFilter = $derived.by(() => { const loaders = packProvider ? packLoaders : [] const versions = packProvider ? packVersions : [] - const hideIn = d.hideInstalled && target && kind !== 'modpack' && !fromCf ? target.id : null + const hideIn = d.hideInstalled && target && kind !== 'modpack' && kind !== 'datapack' && !fromCf ? target.id : null if (!loaders.length && !versions.length && !hideIn) return null return (h: ProjectHit) => (!loaders.length || h.loaders.some((l) => loaders.includes(l))) && @@ -282,8 +284,8 @@ !results ? 1 : local ? Math.max(1, Math.ceil(matches.length / PAGE_SIZE) + (bufferDone ? 0 : 1)) : Math.max(1, Math.ceil(results.total / PAGE_SIZE)), ) /** Everything read was already installed: only Hide installed emptied the list. */ - const allInstalled = $derived(local && !!allHits.length && !matches.length && d.hideInstalled && !packLoaders.length && !packVersions.length) - const filtered = $derived(d.categories.length > 0 || d.environment !== null || d.hideInstalled || packLoaders.length > 0 || packVersions.length > 0) + const allInstalled = $derived(local && !!allHits.length && !matches.length && d.hideInstalled && kind !== 'datapack' && !packLoaders.length && !packVersions.length) + const filtered = $derived(d.categories.length > 0 || d.environment !== null || (d.hideInstalled && kind !== 'datapack') || packLoaders.length > 0 || packVersions.length > 0) const sourceName = $derived(sources.find((p) => p.id === source)?.name ?? 'Modrinth') // the last page read can turn out shorter than expected: stay on a page that exists @@ -374,7 +376,7 @@ function cardState(h: ProjectHit): CardState { if (packProvider) return { fit: hitFit(h, target), action: 'pack', version: null } if (fromCf) return { fit: hitFit(h, target), action: 'curseforge', version: null } - if (h.kind === 'modpack' || !target) return { fit: hitFit(h, target), action: 'install', version: null } + if (h.kind === 'modpack' || h.kind === 'datapack' || !target) return { fit: hitFit(h, target), action: 'install', version: null } const busy = pending[h.id] === target.id && !!app.taskFor(`install:${target.id}`) if (busy) return { fit: { tone: 'busy', icon: 'download', word: t('Installing') }, action: 'busy', version: null } const q = queue.has(h.id, target.id) @@ -469,6 +471,12 @@ {t('Install to')} + {#if kind === 'datapack'} +
+ {t('Into world')} + +
+ {/if} {:else} {/if} @@ -588,7 +596,7 @@ {/if} - {#if kind !== 'modpack' && target && !fromCf} + {#if kind !== 'modpack' && kind !== 'datapack' && target && !fromCf} (app.discover.hideInstalled = v)} @@ -797,11 +805,20 @@ {#if installing} {@const h = installing} {#snippet dialogActions()} - + {/snippet} (installing = null)} actions={dialogActions}> - (installing = null)} onInstall={(id) => (pending[h.id] = id)} onQueued={() => (installing = null)} /> + {#if h.kind === 'datapack'} + (installing = null)} /> + {:else} + (installing = null)} onInstall={(id) => (pending[h.id] = id)} onQueued={() => (installing = null)} /> + {/if} {/if} diff --git a/ui/src/lib/views/discover/InstallPanel.svelte b/ui/src/lib/views/discover/InstallPanel.svelte index bfe28f5..8a182ff 100644 --- a/ui/src/lib/views/discover/InstallPanel.svelte +++ b/ui/src/lib/views/discover/InstallPanel.svelte @@ -459,7 +459,7 @@
{#if !compact}
-

{t('Install')}

+

{t('Install')}

{/if} @@ -497,8 +497,8 @@ {#if chosen}
-

{t('Comes with the pack')}

-
+

{t('Comes with the pack')}

+
Minecraft
{packMc ?? '—'}
{t('Loader')}
@@ -515,7 +515,7 @@ {#if !compact}
-

{t('When you install')}

+

{t('When you install')}

  1. {group.trim() ? t('Cubby adds {name} to your Library, in {group}.', { name: name.trim() || project.title, group: group.trim() }) : t('Cubby adds {name} to your Library.', { name: name.trim() || project.title })}
  2. @@ -656,7 +656,7 @@ {#if !compact}
    -

    {t('When you install')}

    +

    {t('When you install')}

      {#if kind === 'mod'}
    1. {t('Cubby saves {title} in the', { title: project.title })} mods {t('folder of {name}, with the mods it needs.', { name: target.name })}
    2. @@ -702,7 +702,6 @@ gap: var(--space-1) var(--space-2); } /* .panel first: wins over the dialog body's paragraph spacing */ - .panel h2, .panel h3, .panel p, .panel ol, diff --git a/ui/src/lib/views/discover/ProjectPage.svelte b/ui/src/lib/views/discover/ProjectPage.svelte index fd80bca..6654dca 100644 --- a/ui/src/lib/views/discover/ProjectPage.svelte +++ b/ui/src/lib/views/discover/ProjectPage.svelte @@ -62,7 +62,8 @@ } }) - const kind = $derived(project?.kind ?? routeKind) + // Modrinth calls most datapacks "mod" projects: a page opened as a datapack stays one. + const kind = $derived(routeKind === 'datapack' ? 'datapack' : (project?.kind ?? routeKind)) const words = $derived(KINDS[kind]) const target = $derived(kind === 'modpack' ? undefined : app.target) @@ -202,7 +203,7 @@ width: var(--size-inspector); display: flex; flex-direction: column; - gap: var(--space-5); + gap: var(--space-6); padding: var(--space-6) var(--space-5); background: var(--bg-chrome); border-inline-start: var(--border-chrome) solid var(--edge); diff --git a/ui/src/lib/views/discover/WorldPicker.svelte b/ui/src/lib/views/discover/WorldPicker.svelte new file mode 100644 index 0000000..3fdb0b3 --- /dev/null +++ b/ui/src/lib/views/discover/WorldPicker.svelte @@ -0,0 +1,88 @@ + + + +{#if worlds && !worlds.length} +

      {t('{name} has no world yet. Play it once and create one.', { name: target?.name ?? '' })}

      +{:else if worlds && chosen} + (app.targetWorld = id)} label={t('Into world')} buttonLabel={t('Into {world}. Change world', { world: chosen.name })} {variant}> + {#snippet trigger()} + {#if chosen.iconUrl}{/if} + + {chosen.name} + {t('World')} + + {/snippet} + {#snippet option(item)} + {#if item.world.iconUrl}{/if} + + {item.world.name} + {item.world.lastPlayed ? relativeTime(item.world.lastPlayed) : t('Not played yet')} + + {/snippet} + +{/if} + + diff --git a/ui/src/lib/views/discover/discover.ts b/ui/src/lib/views/discover/discover.ts index c1112f4..ccc40ab 100644 --- a/ui/src/lib/views/discover/discover.ts +++ b/ui/src/lib/views/discover/discover.ts @@ -18,7 +18,7 @@ export interface KindText { /** Folder of the instance it goes to */ folder: string /** Instance tab where the player manages it */ - tab: 'mods' | 'shaders' | 'resourcepacks' | null + tab: 'mods' | 'shaders' | 'resourcepacks' | 'worlds' | null /** Short sentence for "New to …?" */ help: string } @@ -56,9 +56,17 @@ export const KINDS: Record = { tab: 'resourcepacks', help: t('Resource packs change how blocks, items, mobs and menus look, and sometimes how they sound. They add nothing new, so they are safe in any world.'), }, + datapack: { + label: t('Datapacks'), + one: t('datapack'), + many: t('datapacks'), + folder: 'datapacks', + tab: 'worlds', + help: t('Datapacks add structures, biomes, recipes or rules to one world, without mods: they work in Vanilla too. Cubby puts them in the world you pick.'), + }, } -export const KIND_ORDER: ProjectKind[] = ['mod', 'modpack', 'shader', 'resourcepack'] +export const KIND_ORDER: ProjectKind[] = ['mod', 'modpack', 'shader', 'resourcepack', 'datapack'] /** Path segment of a project on modrinth.com. */ export function modrinthUrl(kind: ProjectKind, slug: string): string { @@ -117,6 +125,12 @@ export const CATEGORIES: Record = { { label: t('Changes'), items: ['blocks', 'items', 'entities', 'gui', 'fonts', 'audio', 'environment', 'equipment', 'models', 'core-shaders', 'locale'] }, { label: t('Resolution'), items: ['8x-', '16x', '32x', '48x', '64x', '128x', '256x', '512x+'] }, ], + datapack: [ + { + label: t('Categories'), + items: ['adventure', 'decoration', 'equipment', 'food', 'game-mechanics', 'magic', 'mobs', 'optimization', 'technology', 'transportation', 'utility', 'worldgen'], + }, + ], } const CATEGORY_LABELS: Record = { @@ -327,6 +341,7 @@ export function fits(v: Supported, kind: ProjectKind, target: Instance | undefin if (!gameFits(v.gameVersions, target)) return false if (kind === 'mod') return loaderFits(v.loaders, target) if (kind === 'shader') return target.loader.kind !== 'vanilla' + if (kind === 'datapack') return v.loaders.length === 0 || v.loaders.includes('datapack') return true } diff --git a/ui/src/lib/views/discover/project/DescriptionTab.svelte b/ui/src/lib/views/discover/project/DescriptionTab.svelte index 5be0010..67b1a72 100644 --- a/ui/src/lib/views/discover/project/DescriptionTab.svelte +++ b/ui/src/lib/views/discover/project/DescriptionTab.svelte @@ -92,6 +92,19 @@
      {t('Where do I turn it on?')}
      {t('In the instance\'s Shaders tab, or in game: Options, Video settings, Shader packs.')}
      + {:else if kind === 'datapack'} +
      +
      {t('Does it change my worlds?')}
      +
      {t('Only the world you put it in. New chunks may look different, and its changes stay in that world. Back the world up first.')}
      +
      +
      +
      {t('Does it need mods?')}
      +
      {t('No. Datapacks work in Vanilla too. On a server, the server puts them in its own world.')}
      +
      +
      +
      {t('Where do I turn it on?')}
      +
      {t('In the instance\'s Worlds tab, under the world. It loads the next time you open the world.')}
      +
      {:else}
      {t('Does it change my worlds?')}
      diff --git a/ui/src/lib/views/discover/project/ProjectAside.svelte b/ui/src/lib/views/discover/project/ProjectAside.svelte index 374fd38..8645718 100644 --- a/ui/src/lib/views/discover/project/ProjectAside.svelte +++ b/ui/src/lib/views/discover/project/ProjectAside.svelte @@ -6,6 +6,7 @@ import { date, num } from '../../../format' import type { Project, ProjectKind, ProjectVersion } from '../../../types' import InstallPanel from '../InstallPanel.svelte' + import DatapackInstall from '../DatapackInstall.svelte' import { loaderLabel, mcRange, modLoadersOf, modrinthUrl, sideText } from '../discover' import { follow } from './shared' @@ -30,11 +31,15 @@ }) - +{#if kind === 'datapack'} + +{:else} + +{/if} {#if links.length}
      - +
      @@ -596,10 +615,6 @@ min-height: 0; overflow: auto; width: var(--size-inspector); - display: flex; - flex-direction: column; - gap: var(--space-4); - padding: var(--space-6) var(--space-5); background: var(--bg-chrome); border-inline-start: var(--border-chrome) solid var(--edge); } diff --git a/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte b/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte new file mode 100644 index 0000000..d697b06 --- /dev/null +++ b/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte @@ -0,0 +1,93 @@ + + + +{#snippet actions()} + + +{/snippet} + + + {#if !others.length} +

      {t('There is no other instance to copy from yet.')}

      + {:else} +
      + + + + + {#if running}

      {t('Close the game first: it writes its options when it quits.')}

      {/if} +
      + {/if} +
      + + diff --git a/ui/src/lib/views/instance-page/ExportDialog.svelte b/ui/src/lib/views/instance-page/ExportDialog.svelte new file mode 100644 index 0000000..ea64af4 --- /dev/null +++ b/ui/src/lib/views/instance-page/ExportDialog.svelte @@ -0,0 +1,146 @@ + + + +{#snippet actions()} + {#if result} + + + {:else} + + + {/if} +{/snippet} + + + {#if result} +

      {t('Saved to')} {result.path}

      +

      + {t('{listed} downloaded by the launcher that opens it, {stored} stored in the file.', { listed: plural(result.listed, 'file', 'files'), stored: plural(result.stored, 'file', 'files') })} +

      + {#if result.withoutKey} +

      {t('Without a CurseForge API key, Cubby can’t tell which mods CurseForge has, so they are all stored in the file. It works, but the file is bigger.')}

      + {/if} + {:else} +
      + (format = v as typeof format)} /> +

      + {format === 'mrpack' + ? t('Opens in Cubby, the Modrinth App, Prism Launcher and most launchers. Mods from Modrinth are downloaded from there, the others are stored in the file.') + : t('Opens in the CurseForge app, Cubby and Prism Launcher. Mods CurseForge has are downloaded from there, the others are stored in the file.')} +

      + {#if noKey} + {t('Every mod will be stored in the file.')} + {/if} + + + +
      +

      {t('Also include')}

      +

      {t('Mods, resource packs and shader packs are always in. Turned-off mods are left out.')}

      + {#if candidates === null} +

      {t('Reading the instance…')}

      + {:else if !candidates.length} +

      {t('Nothing else in this instance yet.')}

      + {:else} +
        + {#each candidates as c (c.name)} +
      • + toggle(c, on)} /> +
      • + {/each} +
      + {/if} +
      + {#if task} +

      {task.label}…

      + {/if} +
      + {/if} +
      + + diff --git a/ui/src/lib/views/instance-page/InstancePage.svelte b/ui/src/lib/views/instance-page/InstancePage.svelte index f901f7a..c0d2bf5 100644 --- a/ui/src/lib/views/instance-page/InstancePage.svelte +++ b/ui/src/lib/views/instance-page/InstancePage.svelte @@ -3,7 +3,7 @@ import { date, timeOfDay } from '../../format' import { t } from '../../i18n.svelte' import { app } from '../../state.svelte' - import type { ContentSource, ContentUpdate, Instance, ModFile, Pack, ProjectKind, Screenshot, Server, World, WorldBackup } from '../../types' + import type { ContentSource, ContentUpdate, Instance, ModFile, Pack, ProjectKind, Screenshot, Server, World, UpdateBackup, WorldBackup } from '../../types' // Helpers shared by the tabs of this folder (plain hoisted functions, safe to import from the tabs). @@ -51,6 +51,8 @@ screenshots = $state(null) servers = $state(null) backups = $state(null) + /** Content updates that can be undone, newest first. */ + updateBackups = $state(null) checkingUpdates = $state(false) duplicating = $state(false) @@ -186,6 +188,16 @@ } catch (e) { app.error(e) } + void this.loadUpdateBackups() + } + + async loadUpdateBackups() { + try { + this.updateBackups = await api.listUpdateBackups(this.id) + } catch (e) { + this.updateBackups ??= [] + app.error(e) + } } openFolder(sub?: string) { @@ -236,6 +248,7 @@ @@ -187,8 +229,11 @@
      ((filter = v as Filter), (limit = 60))} /> + {#if lastUpdate && !updateTask} + + {/if} {#if counts.updates} - + {:else if data.checkingUpdates} {:else if !data.updates} @@ -267,81 +312,85 @@
      {#if removing} @@ -356,7 +405,80 @@ {/if} +{#if reviewing} + {#snippet reviewActions()} + + + {/snippet} + (reviewing = false)} actions={reviewActions}> +

      {t('Cubby keeps the old files, so you can undo the update if something breaks.')}

      +
      + {#each pending as r (r.key)} + {@const u = r.update!} +
      + + {r.name} + {u.currentVersion} → {u.latestVersion} + + {#if u.changelog.trim()} +
      + {:else} +

      {t('No changelog for this version.')}

      + {/if} +
      + {/each} +
      +
      +{/if} + +{#if undoing && lastUpdate} + {@const b = lastUpdate} + {#snippet undoActions()} + + + {/snippet} + (undoing = false)} actions={undoActions}> +

      {t('These files go back to the version you had before. The newer files move to the instance’s trash folder.')}

      +
        + {#each b.files as f (f.folder + f.old)} +
      • {f.new} → {f.old}
      • + {/each} +
      +
      +{/if} + diff --git a/ui/src/lib/views/instance-page/OverviewTab.svelte b/ui/src/lib/views/instance-page/OverviewTab.svelte index ab68330..386b670 100644 --- a/ui/src/lib/views/instance-page/OverviewTab.svelte +++ b/ui/src/lib/views/instance-page/OverviewTab.svelte @@ -59,7 +59,7 @@ const sm = data.shaderMods if (shaderOn && mods && !(sm.iris?.enabled || sm.optifine?.enabled)) list.push({ ok: false, text: t('A shader pack is on, but Iris isn’t installed or is turned off.'), action: { label: t('See in Shader packs'), run: () => go('shaders') } }) - const max = instance.javaOverrides.maxMemoryMb ?? app.settings?.java.maxMemoryMb + const max = app.memoryOf(instance) const total = app.info?.totalMemoryMb if (max && total) { if (max > total * 0.75) list.push({ ok: false, text: t('Memory is set to {n}, most of your {n2}.', { n: gigabytes(max), n2: gigabytes(total) }), action: { label: t('Change'), run: () => go('settings') } }) @@ -144,7 +144,7 @@ // Details const javaPath = $derived(instance.javaOverrides.executable) - const memory = $derived(instance.javaOverrides.maxMemoryMb ?? app.settings?.java.maxMemoryMb ?? null) + const memory = $derived(app.memoryOf(instance)) const folder = $derived.by(() => { const root = app.info?.dataDir if (!root) return null @@ -234,6 +234,7 @@ address={server.address} iconSrc={status.iconUrl ?? server.iconUrl ?? undefined} motd={status.motd} + motdFormatted={status.motdFormatted} online={status.online} players={status.online ? { online: status.playersOnline, max: status.playersMax } : undefined} playersLabel={t('players online')} @@ -254,7 +255,7 @@
      {t('Picked automatically')}
      {/if}
      {t('Memory')}
      -
      {memory ? megabytes(memory) : '—'}{instance.javaOverrides.maxMemoryMb == null ? t(' (global)') : ''}
      +
      {memory ? megabytes(memory) : '—'}{instance.javaOverrides.maxMemoryMb == null ? (app.settings?.java.autoMemory ? t(' (automatic)') : t(' (global)')) : ''}
      {t('Created')}
      {date(instance.created)}
      {t('Account')}
      diff --git a/ui/src/lib/views/instance-page/ResourcePacksTab.svelte b/ui/src/lib/views/instance-page/ResourcePacksTab.svelte index 0b88986..22b94cd 100644 --- a/ui/src/lib/views/instance-page/ResourcePacksTab.svelte +++ b/ui/src/lib/views/instance-page/ResourcePacksTab.svelte @@ -2,7 +2,7 @@ import { t } from '../../i18n.svelte' import { tick } from 'svelte' import { api } from '../../api' - import { Banner, Button, Icon, IconButton, InstanceIcon, StatusTag } from '../../cubby' + import { Banner, Button, Icon, IconButton, Inspector, InspectorHead, InspectorPath, InspectorSection, InspectorStatus, InstanceIcon, MetaChip } from '../../cubby' import { bytes, num, relativeTime } from '../../format' import { projectArt } from '../../icon' import { app } from '../../state.svelte' @@ -67,6 +67,18 @@ void persist([...on.filter((x) => x.fileName !== p.fileName), { ...p, enabled: false }, ...off]) } + async function removePack(p: Pack) { + try { + await api.removePack(id, 'resource', p.fileName) + app.forgetFile(id, p.fileName) + if (selected === p.fileName) selected = null + app.toast(t('{name} moved to the instance’s trash folder.', { name: p.name }), 'success') + } catch (e) { + app.error(e) + } + await data.loadPacks() + } + const describe = (p: Pack) => `${p.isDir ? t('Folder') : t('Zip file')} · ${bytes(p.size)}` @@ -77,12 +89,12 @@ {/if} {/snippet} -{#snippet art(p: Pack, raised = false)} +{#snippet art(p: Pack, raised = false, size = 32)} {@const src = data.source(p.fileName)} {#if src?.iconUrl} - + {:else} - + {/if} {/snippet} @@ -177,46 +189,52 @@ diff --git a/ui/src/lib/views/instance-page/ScreenshotsTab.svelte b/ui/src/lib/views/instance-page/ScreenshotsTab.svelte index 8bbb730..b3f0cf5 100644 --- a/ui/src/lib/views/instance-page/ScreenshotsTab.svelte +++ b/ui/src/lib/views/instance-page/ScreenshotsTab.svelte @@ -2,7 +2,7 @@ import { t } from '../../i18n.svelte' import { tick } from 'svelte' import { api } from '../../api' - import { Button, Dialog } from '../../cubby' + import { Button, Dialog, Icon, Inspector, InspectorHead, InspectorPath, InspectorSection, MetaChip } from '../../cubby' import { locale, num, plural, timeOfDay } from '../../format' import { app } from '../../state.svelte' import type { Instance, Screenshot } from '../../types' @@ -193,39 +193,38 @@ {#if viewing} @@ -262,9 +261,6 @@ .muted { color: var(--ink-muted); } - .wrap { - overflow-wrap: anywhere; - } .toolbar { display: flex; flex-wrap: wrap; @@ -348,68 +344,6 @@ white-space: nowrap; text-overflow: ellipsis; } - - .preview { - display: block; - width: 100%; - padding: 0; - background: var(--field); - border: var(--border-block) solid var(--edge); - box-shadow: var(--shadow-block); - cursor: zoom-in; - } - .preview:focus-visible { - outline: none; - box-shadow: var(--focus-ring), var(--shadow-block); - } - .preview img { - display: block; - width: 100%; - aspect-ratio: 16 / 9; - object-fit: cover; - image-rendering: pixelated; - } - .pager { - display: flex; - align-items: center; - gap: var(--space-2); - } - .pager__pos { - flex: 1; - text-align: center; - } - .title { - display: flex; - flex-direction: column; - gap: var(--space-1); - } - .facts { - display: grid; - grid-template-columns: auto 1fr; - align-items: center; - gap: var(--space-2) var(--space-4); - padding: var(--space-3) var(--space-4); - background: var(--surface); - border: var(--border-block) solid var(--edge); - } - .row { - display: flex; - flex-wrap: wrap; - gap: var(--space-2); - } - .ip-aside__inner :global(.wide) { - width: 100%; - } - .danger { - display: flex; - flex-direction: column; - align-items: flex-end; - gap: 6px; - margin-top: auto; - padding-top: var(--space-4); - border-top: var(--border-hair) solid var(--line); - text-align: end; - } .full { display: block; width: 100%; diff --git a/ui/src/lib/views/instance-page/ServersTab.svelte b/ui/src/lib/views/instance-page/ServersTab.svelte index facf6ae..b63455b 100644 --- a/ui/src/lib/views/instance-page/ServersTab.svelte +++ b/ui/src/lib/views/instance-page/ServersTab.svelte @@ -2,7 +2,7 @@ import { t } from '../../i18n.svelte' import { tick, untrack } from 'svelte' import { api } from '../../api' - import { Button, Dialog, Icon, IconButton, MetaChip, PlayButton, SegmentedControl, ServerRow, StatusTag, TextField } from '../../cubby' + import { Button, Dialog, Icon, IconButton, Inspector, InspectorHead, InspectorNotice, InspectorSection, InspectorStatus, MetaChip, Motd, PlayButton, SegmentedControl, ServerRow, StatusTag, TextField } from '../../cubby' import { num, plural } from '../../format' import { app } from '../../state.svelte' import type { Instance, Server, ServerStatus } from '../../types' @@ -227,6 +227,7 @@ address={s.address} iconSrc={st.iconUrl ?? s.iconUrl ?? undefined} motd={st.motd} + motdFormatted={st.motdFormatted} online={st.online} players={st.online ? { online: st.playersOnline, max: st.playersMax } : undefined} playersLabel={t('{n} of {n2} players online', { n: num(st.playersOnline), n2: num(st.playersMax) })} @@ -257,102 +258,91 @@ {#if removing !== null && servers[removing]} @@ -377,16 +367,6 @@ .muted { color: var(--ink-muted); } - .warn { - color: var(--gold-text); - } - .icon { - display: inline-flex; - flex: none; - } - .wrap { - overflow-wrap: anywhere; - } .toolbar { display: flex; flex-wrap: wrap; @@ -479,19 +459,6 @@ .srow__main:hover :global(.cb-server) { background: var(--surface-hover); } - /* one line: Copy, Edit and the two move buttons stay together whatever the width of the panel */ - .row.row--actions { - flex-wrap: nowrap; - } - .row--actions > :global(.cb-btn) { - flex: 1; - } - .move { - flex: none; - display: inline-flex; - align-items: center; - gap: var(--space-1); - } .srow.is-selected .srow__main::after { content: ''; position: absolute; @@ -499,94 +466,9 @@ border: var(--border-block) solid var(--ink); pointer-events: none; } - .who { - display: flex; - align-items: center; - gap: var(--space-4); - } - .who__icon { - display: block; - flex: none; - box-sizing: border-box; - width: 64px; - height: 64px; - image-rendering: pixelated; - border: var(--border-block) solid var(--edge); - box-shadow: var(--shadow-block-sm); - } - .who__icon--empty { - display: flex; - align-items: center; - justify-content: center; - color: var(--ink-muted); - background: var(--surface); - } - .who__text { - min-width: 0; - display: flex; - flex-direction: column; - gap: var(--space-1); - } - .who__text h2 { - outline: none; - } - .ip-aside__inner :global(.wide) { - width: 100%; - } - .row { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-2); - } .edit { display: flex; flex-direction: column; gap: var(--space-3); } - .label { - margin-bottom: 6px; - } - .motd { - padding: var(--space-2) var(--space-3); - overflow-wrap: anywhere; - white-space: pre-wrap; - background: var(--field); - border: var(--border-block) solid var(--outline); - box-shadow: var(--shadow-well); - } - .facts { - display: grid; - grid-template-columns: auto 1fr; - align-items: center; - gap: var(--space-2) var(--space-4); - padding: var(--space-3) var(--space-4); - background: var(--surface); - border: var(--border-block) solid var(--edge); - } - .inline { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-2); - } - .flag { - display: flex; - align-items: flex-start; - gap: var(--space-2); - } - .part { - display: flex; - flex-direction: column; - gap: 6px; - } - .danger { - display: flex; - flex-wrap: wrap; - align-items: flex-end; - gap: var(--space-2) var(--space-3); - padding-top: var(--space-4); - border-top: var(--border-hair) solid var(--line); - text-align: end; - } diff --git a/ui/src/lib/views/instance-page/SettingsTab.svelte b/ui/src/lib/views/instance-page/SettingsTab.svelte index 42d0efe..b600ce5 100644 --- a/ui/src/lib/views/instance-page/SettingsTab.svelte +++ b/ui/src/lib/views/instance-page/SettingsTab.svelte @@ -18,6 +18,7 @@ + +{#snippet packActions()} + + +{/snippet} + + {#if packs === null} +

      {t('Reading datapacks…')}

      + {:else if !packs.length} +

      {t('Datapacks add structures, biomes or rules to one world, without mods.')}

      + {:else} +
        + {#each packs as p (p.fileName)} +
      • +
        + {p.name} + {p.description ?? (p.isDir ? t('Folder') : bytes(p.size))} +
        + toggle(p, on)} /> + remove(p)} /> +
      • + {/each} +
      + {/if} +
      + + diff --git a/ui/src/lib/views/instance-page/WorldMap.svelte b/ui/src/lib/views/instance-page/WorldMap.svelte new file mode 100644 index 0000000..f63c6b0 --- /dev/null +++ b/ui/src/lib/views/instance-page/WorldMap.svelte @@ -0,0 +1,105 @@ + + + +{#snippet drawAction()} + +{/snippet} + + {#if map} + +

      {t('{n} blocks around the spawn · {chunks} chunks explored', { n: num(map.size / 2), chunks: num(map.chunks) })}

      + {:else if task} + + {:else if failed[key]} +

      {failed[key]}

      + {:else} +

      {t('See the land around the spawn from above.')}

      + {/if} +
      + +{#if big && map} + (big = false)}> +
      + {t('Map + +
      +

      {t('From {x}, {z} to {x2}, {z2}. The red dot is the spawn.', { x: num(map.minX), z: num(map.minZ), x2: num(map.minX + map.size), z2: num(map.minZ + map.size) })}

      +
      +{/if} + + diff --git a/ui/src/lib/views/instance-page/WorldsTab.svelte b/ui/src/lib/views/instance-page/WorldsTab.svelte index 98e77a0..faca22c 100644 --- a/ui/src/lib/views/instance-page/WorldsTab.svelte +++ b/ui/src/lib/views/instance-page/WorldsTab.svelte @@ -2,12 +2,14 @@ import { t } from '../../i18n.svelte' import { tick, untrack } from 'svelte' import { api } from '../../api' - import { Button, Dialog, Icon, IconButton, PlayButton } from '../../cubby' + import { Button, Dialog, Icon, IconButton, Inspector, InspectorHead, InspectorNotice, InspectorPath, InspectorSection, InspectorStatus, MetaChip, PlayButton } from '../../cubby' import { bytes, plural, relativeTime } from '../../format' import { app } from '../../state.svelte' import type { Instance, World, WorldBackup } from '../../types' import { when, type InstanceData } from './InstancePage.svelte' import { opensWorlds } from '../library/Stage.svelte' + import WorldDatapacks from './WorldDatapacks.svelte' + import WorldMap from './WorldMap.svelte' let { instance, data }: { instance: Instance; data: InstanceData } = $props() @@ -155,51 +157,73 @@ {#if restoring} @@ -243,9 +267,6 @@ white-space: nowrap; text-overflow: ellipsis; } - .wrap { - overflow-wrap: anywhere; - } .toolbar { display: flex; flex-wrap: wrap; @@ -351,45 +372,4 @@ height: 128px; box-shadow: var(--shadow-block-sm); } - .facts { - display: grid; - grid-template-columns: auto minmax(0, 1fr); - align-items: center; - gap: var(--space-2) var(--space-4); - padding: var(--space-4); - background: var(--surface); - border: var(--border-block) solid var(--edge); - } - .facts .full { - grid-column: 1 / -1; - } - .part { - display: flex; - flex-direction: column; - gap: var(--space-2); - } - .backup { - display: flex; - align-items: center; - gap: var(--space-2); - } - .backup__text { - flex: 1; - min-width: 0; - display: flex; - flex-direction: column; - } - .danger { - display: flex; - flex-direction: column; - align-items: flex-end; - gap: 6px; - margin-top: var(--space-2); - padding-top: var(--space-4); - border-top: var(--border-hair) solid var(--line); - text-align: end; - } - h2[tabindex='-1'] { - outline: none; - } diff --git a/ui/src/lib/views/library/FirstGame.svelte b/ui/src/lib/views/library/FirstGame.svelte index 32a6b84..32b6384 100644 --- a/ui/src/lib/views/library/FirstGame.svelte +++ b/ui/src/lib/views/library/FirstGame.svelte @@ -32,7 +32,7 @@ {t('Or')} - +
    diff --git a/ui/src/lib/views/library/ImportDialog.svelte b/ui/src/lib/views/library/ImportDialog.svelte index c7e2819..b1de6e4 100644 --- a/ui/src/lib/views/library/ImportDialog.svelte +++ b/ui/src/lib/views/library/ImportDialog.svelte @@ -4,9 +4,9 @@ import { api } from '../../api' import { app } from '../../state.svelte' import { loaderFull, plural } from '../../format' - import type { PrismInstance } from '../../types' + import type { ForeignInstance } from '../../types' - let found = $state(null) + let found = $state(null) let chosen = $state>({}) let failed = $state(null) let busy = $state(false) @@ -14,11 +14,12 @@ $effect(() => { let stale = false api - .listPrismInstances() + .listLauncherInstances() .then((list) => { if (stale) return found = list - chosen = Object.fromEntries(list.map((p) => [p.path, true])) + // Prism and MultiMC instances are ticked: they are what people usually move. Others wait to be picked. + chosen = Object.fromEntries(list.map((p) => [p.path, !!p.minecraft && ['prism', 'multiMc', 'polyMc'].includes(p.launcher)])) }) .catch((e) => { if (stale) return @@ -30,8 +31,15 @@ } }) - const picked = $derived((found ?? []).filter((p) => chosen[p.path])) - const allOn = $derived(!!found?.length && picked.length === found.length) + const importable = $derived((found ?? []).filter((p) => p.minecraft)) + const picked = $derived(importable.filter((p) => chosen[p.path])) + const allOn = $derived(!!importable.length && picked.length === importable.length) + /** Instances grouped by launcher, in the order the launchers were found. */ + const groups = $derived.by(() => { + const map = new Map() + for (const p of found ?? []) map.set(p.launcherName, [...(map.get(p.launcherName) ?? []), p]) + return [...map.entries()] + }) function close() { app.prismImportOpen = false @@ -45,17 +53,17 @@ function toggleAll() { const on = !allOn - chosen = Object.fromEntries((found ?? []).map((p) => [p.path, on])) + chosen = Object.fromEntries((found ?? []).map((p) => [p.path, on && !!p.minecraft])) } async function run() { if (!picked.length) return busy = true try { - const imported = await api.importPrism(picked.map((p) => p.path)) + const imported = await api.importLauncherInstances(picked.map((p) => p.path)) await app.refreshInstances() if (imported[0]) app.selected = imported[0].id - app.toast(t('Imported {n} from Prism Launcher.', { n: plural(imported.length, 'instance', 'instances') }), 'success') + app.toast(t('Imported {n}.', { n: plural(imported.length, 'instance', 'instances') }), 'success') close() } catch (e) { app.error(e) @@ -76,15 +84,14 @@

    {t('Cubby found these on your PC.')} {t('Pick what to bring over.')}

    {#if found === null} -

    {t('Looking for Prism Launcher instances…')}

    +

    {t('Looking for other launchers…')}

    {:else if failed} - {failed} + {failed} {:else if !found.length}
    -

    Prism Launcher

    -

    {t('Nothing in its usual folder')}

    -

    %APPDATA%\PrismLauncher\instances

    +

    {t('No other launcher found')}

    +

    {t('Cubby looks for Prism Launcher, MultiMC, PolyMC, CurseForge, ATLauncher, GDLauncher, the Modrinth App and the Minecraft Launcher in their usual folders.')}

    {t('Not found')}
    @@ -92,31 +99,38 @@

    - Prism Launcher - {plural(found.length, 'instance', 'instances')} + {plural(found.length, 'instance', 'instances')} + {groups.map(([name]) => name).join(', ')}

    -
      - {#each found as p (p.path)} -
    • - -
      -

      - {p.name} - {p.minecraft} - {loaderFull(p.loader)} - {#if p.group}{p.group}{/if} -

      -

      {p.path}

      -
      -
    • - {/each} -
    + {#each groups as [launcher, list] (launcher)} +

    {launcher}

    +
      + {#each list as p (p.path)} +
    • + +
      +

      + {p.name} + {#if p.minecraft} + {p.minecraft} + {loaderFull(p.loader)} + {:else} + {t('Version unknown: export it as a .mrpack from {launcher}, then import the file.', { launcher })} + {/if} + {#if p.group}{p.group}{/if} +

      +

      {p.gameDir}

      +
      +
    • + {/each} +
    + {/each} {/if} -

    {t('Safe: Cubby copies the mods, worlds, screenshots and settings. Prism Launcher stays as it is.')}

    +

    {t('Safe: Cubby copies the mods, worlds, screenshots and settings. The other launchers stay as they are.')}

    @@ -221,6 +235,9 @@ outline: 2px solid transparent; box-shadow: var(--focus-ring); } + .group { + margin: var(--space-2) 0 var(--space-1); + } .progress { margin-top: var(--space-3); } diff --git a/ui/src/lib/views/play/Crash.svelte b/ui/src/lib/views/play/Crash.svelte index 8bac3f0..2ccb44b 100644 --- a/ui/src/lib/views/play/Crash.svelte +++ b/ui/src/lib/views/play/Crash.svelte @@ -7,7 +7,7 @@ import { Banner, Button, Dialog, Icon, LogViewer, PlayButton, Switch } from '../../cubby' import { loaderFull, plural, timeOfDay } from '../../format' import { app } from '../../state.svelte' - import type { Instance, ModFile, World } from '../../types' + import type { Instance, ModFile, UpdateBackup, World } from '../../types' import CrashAside from './CrashAside.svelte' import Rich from './Rich.svelte' import { diagnose, type Party } from './crash' @@ -53,9 +53,16 @@ (w) => (worlds = w), () => (worlds = []), ) + api.listUpdateBackups(id).then( + (b) => (lastUpdate = b[0] ?? null), + () => (lastUpdate = null), + ) }) }) + /** The newest content update that can be undone: a crash right after an update often comes from it. */ + let lastUpdate = $state(null) + const parser = new LogParser() const parsed = $derived(parser.parse(app.logs[id] ?? [])) const facts = $derived.by(() => { @@ -67,7 +74,7 @@ const lastWorld = $derived([...worlds].sort((a, b) => (b.lastPlayed ?? '').localeCompare(a.lastPlayed ?? ''))[0] ?? null) // Memory - const currentMb = $derived(instance?.javaOverrides.maxMemoryMb ?? app.settings?.java.maxMemoryMb ?? 4096) + const currentMb = $derived(instance ? app.memoryOf(instance) : (app.settings?.java.maxMemoryMb ?? 4096)) const totalMb = $derived(app.info?.totalMemoryMb ?? 0) /** 2 GB more, keeping 2 GB for Windows and the other programs. */ const raisedMb = $derived.by(() => { @@ -100,6 +107,7 @@ raisedMb, totalMb, customJava: !!instance?.javaOverrides.executable, + lastUpdate, }), ) @@ -202,6 +210,22 @@ const repairTask = $derived(app.tasks[`repair:${id}`]) + async function undoUpdate() { + const b = lastUpdate + if (!b) return + busy = 'undo-update' + try { + const n = await api.undoUpdate(id, b.name) + applied['undo-update'] = true + app.toast(t('Put back {n} from before the update.', { n: plural(n, 'file', 'files') }), 'success') + await loadMods() + } catch (e) { + app.error(e) + } finally { + busy = null + } + } + async function repair() { busy = 'repair' try { @@ -348,6 +372,12 @@ {:else} {/if} + {:else if f.id === 'undo-update'} + {#if applied['undo-update']} + {t('Back as before')} + {:else} + + {/if} {:else if f.id === 'updates'} {:else if f.id === 'settings'} diff --git a/ui/src/lib/views/play/CrashAside.svelte b/ui/src/lib/views/play/CrashAside.svelte index 6db52d3..9c8ed60 100644 --- a/ui/src/lib/views/play/CrashAside.svelte +++ b/ui/src/lib/views/play/CrashAside.svelte @@ -2,7 +2,7 @@

    diff --git a/ui/src/lib/views/play/Running.svelte b/ui/src/lib/views/play/Running.svelte index 6ab66b8..8dd65db 100644 --- a/ui/src/lib/views/play/Running.svelte +++ b/ui/src/lib/views/play/Running.svelte @@ -2,20 +2,7 @@ import { t } from '../../i18n.svelte' import { untrack } from 'svelte' import { api } from '../../api' - import { - Banner, - Button, - Icon, - IconButton, - InstanceIcon, - LogViewer, - MetaChip, - PlayButton, - SegmentedControl, - StatusTag, - TextField, - type SegmentedOption, - } from '../../cubby' + import { Banner, Button, Icon, IconButton, Inspector, InspectorNotice, InspectorSection, InstanceIcon, LogViewer, MetaChip, Motd, PlayButton, SegmentedControl, type SegmentedOption, StatusTag, TextField } from '../../cubby' import { fold, loaderFull, megabytes, num, plural, session, timeOfDay } from '../../format' import { iconOf } from '../../icon' import { app } from '../../state.svelte' @@ -342,82 +329,59 @@
  3. + + {#if status?.online && motd}{/if} + + {/if} + {/if} @@ -444,16 +408,11 @@ padding: var(--space-6); } h1, - h2, - h3, p, dl, dd { margin: 0; } - .muted { - color: var(--ink-muted); - } .head { display: flex; @@ -553,24 +512,10 @@ .aside { flex: none; width: var(--size-inspector); - display: flex; - flex-direction: column; - gap: var(--space-4); - padding: var(--space-6) var(--space-4); overflow: auto; background: var(--bg-chrome); border-inline-start: var(--border-chrome) solid var(--edge); } - .block { - display: flex; - flex-direction: column; - gap: var(--space-2); - } - .block-head { - display: flex; - align-items: baseline; - gap: var(--space-2); - } .shots { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -597,58 +542,4 @@ aspect-ratio: 16 / 9; object-fit: cover; } - - .server { - display: flex; - flex-direction: column; - align-items: flex-start; - gap: var(--space-2); - padding: var(--space-3) var(--space-4); - background: var(--surface); - border: var(--border-block) solid var(--edge); - box-shadow: var(--shadow-block-sm); - } - .server-top { - display: flex; - align-items: center; - gap: var(--space-3); - min-width: 0; - width: 100%; - } - .server-icon { - display: flex; - align-items: center; - justify-content: center; - flex: none; - width: 48px; - height: 48px; - overflow: hidden; - color: var(--ink-muted); - background: var(--bg-chrome); - border: var(--border-block) solid var(--edge); - } - .server-icon img { - width: 100%; - height: 100%; - image-rendering: pixelated; - } - .server-name { - min-width: 0; - } - .server-name p { - overflow-wrap: anywhere; - } - .server-stats { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-2) var(--space-3); - } - .motd { - overflow-wrap: anywhere; - white-space: pre-line; - } - .note { - margin-top: auto; - } diff --git a/ui/src/lib/views/play/crash.test.ts b/ui/src/lib/views/play/crash.test.ts new file mode 100644 index 0000000..2822d41 --- /dev/null +++ b/ui/src/lib/views/play/crash.test.ts @@ -0,0 +1,75 @@ +// Crash diagnosis on real game logs. Run with `npm test` (built by Vite, run by node:test). +/// +import assert from 'node:assert/strict' +import { test } from 'node:test' +import type { ModFile } from '../../types' +import { diagnose } from './crash' + +function mod(fileName: string, name: string, id: string, version: string): ModFile { + return { fileName, name, enabled: true, size: 1, modified: null, version, description: null, authors: [], loader: 'fabric', id } as unknown as ModFile +} + +const MODS = [ + mod('sodium-fabric-0.9.3-beta.4+mc26.3.jar', 'Sodium', 'sodium', '0.9.3-beta.4+mc26.3'), + mod('iris-fabric-1.11.7+mc26.3.jar', 'Iris', 'iris', '1.11.7+mc26.3'), + mod('fabric-api-0.140.0.jar', 'Fabric API', 'fabric-api', '0.140.0'), +] + +// Fabric Loader refusing to start after Sodium was updated past what Iris supports. +const SODIUM_IRIS = [ + '[12:01:02] [main/INFO]: Loading Minecraft 26.3 with Fabric Loader 0.18.4', + '[12:01:02] [main/ERROR]: Incompatible mods found!', + 'net.fabricmc.loader.impl.FormattedException: Some of your mods are incompatible with the game or each other!', + 'A potential solution has been determined, this may resolve your problem:', + '\t - Replace mod \'Iris\' (iris) 1.11.7+mc26.3 with any version that is compatible with:', + '\t - sodium 0.9.3-beta.4+mc26.3', + 'More details:', + '\t - Mod \'Sodium\' (sodium) 0.9.3-beta.4+mc26.3 is incompatible with version 1.11.7 or earlier of mod \'Iris\' (iris), yet a conflicting version is present: 1.11.7+mc26.3!', + '\tat net.fabricmc.loader.impl.FormattedException.ofLocalized(FormattedException.java:51)', + '\tat net.fabricmc.loader.impl.FabricLoaderImpl.load(FabricLoaderImpl.java:200)', + '\tat net.fabricmc.loader.impl.launch.knot.Knot.init(Knot.java:146)', + '\tat net.fabricmc.loader.impl.launch.knot.Knot.launch(Knot.java:68)', + '\tat net.fabricmc.loader.impl.launch.knot.KnotClient.main(KnotClient.java:23)', +] + +test('Fabric: a mod declared incompatible with another is a conflict naming both', () => { + const d = diagnose(SODIUM_IRIS, MODS, 1) + assert.equal(d.kind, 'conflict') + assert.equal(d.culprit?.mod?.name, 'Sodium') + assert.equal(d.other?.mod?.name, 'Iris') + assert.deepEqual(d.declared, { range: '1.11.7 or earlier', present: '1.11.7+mc26.3' }) + assert.ok(d.evidence.some((e) => e.culprit && e.text.includes('is incompatible with'))) +}) + +test('Fabric: the same error inside one multi-line log entry', () => { + // The loader's error list sometimes arrives as one entry: its lines are still read one by one. + const d = diagnose(['[12:01:02] [main/INFO]: Loading Minecraft 26.3', SODIUM_IRIS.slice(1).join('\n')], MODS, 1) + assert.equal(d.kind, 'conflict') + assert.equal(d.other?.ref, 'iris') + assert.ok(d.checkedLines >= SODIUM_IRIS.length) +}) + +test('Fabric: "any version" and a mod that isn\'t installed', () => { + const d = diagnose( + ['Incompatible mods found!', " - Mod 'Embeddium' (embeddium) 1.0 is incompatible with any version of mod 'Sodium' (sodium), yet a conflicting version is present: 0.6.0!"], + MODS, + 1, + ) + assert.equal(d.kind, 'conflict') + assert.equal(d.culprit?.mod, null) + assert.equal(d.culprit?.name, 'Embeddium') + assert.equal(d.declared?.range, 'any version') +}) + +test('Fabric: wrong and missing dependencies stay "missing"', () => { + const wrong = diagnose( + ['Incompatible mods found!', " - Mod 'Iris' (iris) 1.11.7 requires version 0.9.0 or later of mod 'Sodium' (sodium), but only the wrong version is present: 0.8.0!"], + MODS, + 1, + ) + assert.equal(wrong.kind, 'missing') + assert.equal(wrong.missing[0].wrong, true) + const absent = diagnose(["Incompatible mods found!", " - Mod 'Iris' (iris) 1.11.7 requires any version of mod 'Sodium' (sodium), which is missing!"], [], 1) + assert.equal(absent.kind, 'missing') + assert.equal(absent.missing[0].wrong, false) +}) diff --git a/ui/src/lib/views/play/crash.ts b/ui/src/lib/views/play/crash.ts index 3d189c3..eaf8c92 100644 --- a/ui/src/lib/views/play/crash.ts +++ b/ui/src/lib/views/play/crash.ts @@ -55,6 +55,9 @@ export interface Diagnosis { jvmError: string | null /** For `version` read from the loader: the game versions the mod is made for ("1.21 to 1.21.1"). */ madeFor: string | null + /** For `conflict` read from the loader: `culprit` says it doesn't work with these versions of `other` + * ("1.11.7 or earlier"), and `present` is the version installed. */ + declared: { range: string; present: string | null } | null signals: Signals /** Crash report file named by the game, if any. */ reportPath: string | null @@ -70,7 +73,7 @@ const CLASS_VERSION = /class file version (\d+)(?:\.\d+)?\), this version of the const JAVA_WRONG = /UnsupportedClassVersionError|compiled by a more recent version of the Java Runtime|requires (?:version )?[^\n]*?\bof (?:mod )?'?java'?\b|requires Java \d+|Java \d+ (?:or (?:newer|later|above)|is required)|Unsupported Java version|wrong version of Java/i const RESOLUTION = - /Mod resolution (?:failed|encountered an incompatible mod set)|Incompatible mods? (?:set|found)|Some of your mods are incompatible|which is missing|Missing or unsupported mandatory dependencies|Mod ID: '[^']+', Requested by: '[^']+'|Missing Mods:/i + /Mod resolution (?:failed|encountered an incompatible mod set)|Incompatible mods? (?:set|found)|is incompatible with .*? of (?:mod )?'|Some of your mods are incompatible|which is missing|Missing or unsupported mandatory dependencies|Mod ID: '[^']+', Requested by: '[^']+'|Missing Mods:/i const LINKAGE = /java\.lang\.(NoSuchMethodError|NoSuchFieldError|AbstractMethodError|IncompatibleClassChangeError|NoClassDefFoundError|ClassNotFoundException)\b/ const MIXIN = /MixinApplyError|InvalidMixinException|InvalidInjectionException|MixinTransformerError|Mixin apply(?:ing)? (?:for|from) mod [\w.-]+ failed|Critical injection failure|mixin\.injection\.throwables/ const JVM_START = @@ -230,7 +233,8 @@ function findFirst(tail: string[], re: RegExp, from = 0): number { * fail to load, two mods that disagree, the graphics driver or Java itself. Says `unknown` rather than guess. */ export function diagnose(lines: string[], mods: ModFile[], exitCode: number | null = null): Diagnosis { - const tail = lines.slice(-TAIL) + // A log entry can hold several lines (the loader's error list): look at them one by one. + const tail = lines.flatMap((l) => l.split(/\r?\n/)).slice(-TAIL) const text = tail.join('\n') const reportPath = /Crash report saved to:?\s*(?:#@!@#\s*)?(\S.*?\.txt)/.exec(text)?.[1]?.trim() ?? null @@ -257,6 +261,7 @@ export function diagnose(lines: string[], mods: ModFile[], exitCode: number | nu frame, jvmError: null, madeFor: null, + declared: null, signals, reportPath, jvmReportPath, @@ -272,11 +277,20 @@ export function diagnose(lines: string[], mods: ModFile[], exitCode: number | nu } // Mods the loader says are made for another version of Minecraft, with the versions they accept. const wrongGame: { mod: Party; madeFor: string | null; at: number }[] = [] + // Mods the loader says don't work together ("Mod 'Sodium' (sodium) 0.9 is incompatible with version 1.11.7 or + // earlier of mod 'Iris' (iris), yet a conflicting version is present: 1.11.7!"). + const clashes: { by: Party; with: Party; range: string; present: string | null; at: number }[] = [] let resolutionAt = -1 if (RESOLUTION.test(text)) { resolutionAt = findFirst(tail, RESOLUTION) for (let i = Math.max(0, resolutionAt - 2); i < tail.length; i++) { const msg = messageOf(tail[i]) + const clash = /Mod '([^']+)' \(([\w.-]+)\)\s*\S*\s+is incompatible with\s+(.*?)\s*\bof\s+(?:mod\s+)?(?:'([^']+)'\s*\(([\w.-]+)\)|'?([\w.-]+)'?)(?:.*?conflicting version is present:\s*([^\s!]+))?/i.exec(msg) + if (clash) { + const other = partyFromId(clash[5] ?? clash[6], clash[4] ?? null, mods) + clashes.push({ by: partyFromId(clash[2], clash[1], mods), with: other, range: clash[3].trim().replace(/^versions?\s+/i, ''), present: clash[7] ?? null, at: i }) + continue + } const fab = /Mod '([^']+)' \(([\w.-]+)\)\s*\S*\s+requires\s+(.*?)\bof\s+(?:mod\s+)?(?:'([^']+)'\s*\(([\w.-]+)\)|'?([\w.-]+)'?)/i.exec(msg) if (fab) { const req = partyFromId(fab[2], fab[1], mods) @@ -297,6 +311,7 @@ export function diagnose(lines: string[], mods: ModFile[], exitCode: number | nu } } signals.missing = missing.length + if (clashes.length) signals.conflict = true } // Two mods that disagree: a missing method or class between them. @@ -391,6 +406,19 @@ export function diagnose(lines: string[], mods: ModFile[], exitCode: number | nu } } + // Two mods the loader says don't work together. + if (clashes.length) { + const c = clashes[0] + return { + ...base, + kind: 'conflict', + culprit: c.by, + other: c.with, + declared: { range: c.range, present: c.present }, + evidence: evidence(tail, [resolutionAt, c.at - 1, c.at], c.at), + } + } + // A mod made for another game version: the loader stops before anything else can go wrong. if (wrongGame.length) { const first = wrongGame[0] diff --git a/ui/src/lib/views/play/crashText.ts b/ui/src/lib/views/play/crashText.ts index de7798f..dac8cc8 100644 --- a/ui/src/lib/views/play/crashText.ts +++ b/ui/src/lib/views/play/crashText.ts @@ -1,7 +1,7 @@ // The words of the crash screen: what happened, the ways to fix it and what Cubby checked, built from a // diagnosis. Pure functions; the screen (Crash.svelte) owns the state and the actions. import { locale, plural, playTime } from '../../format' -import type { ModFile, World } from '../../types' +import type { ModFile, UpdateBackup, World } from '../../types' import type { Diagnosis, Party } from './crash' import type { SessionFacts } from './log' import { t } from '../../i18n.svelte' @@ -115,6 +115,22 @@ export function causeOf(d: Diagnosis, ctx: { name: string; memoryMb: number; min } } case 'conflict': + if (d.declared && b) + return { + title: [lead, ...who(a, t('a mod'), true), t(' doesn’t work with '), ...who(b, t('another mod'), true)], + text: [ + ...who(a, t('A mod')), + t(' says it doesn’t work with '), + ...who(b, t('another mod')), + ' ', + { mono: d.declared.range }, + ...(d.declared.present ? [t(', and you have '), { mono: d.declared.present }] : []), + t('. The loader stopped before the game started. A newer '), + ...who(b, t('version')), + t(' usually fixes it. Your PC is fine.'), + ], + marks: [t('Here marks the line that names them.')], + } return { title: [lead, ...who(a, t('a mod'), true), t(' doesn’t work with '), ...who(b, t('this setup'), true)], text: b @@ -193,7 +209,7 @@ export function namedParts(d: Diagnosis): Part[] { // Ways to fix it -export type FixId = 'disable' | 'enable' | 'find' | 'memory' | 'java' | 'updates' | 'driver' | 'settings' | 'repair' | 'help' +export type FixId = 'disable' | 'enable' | 'find' | 'memory' | 'java' | 'updates' | 'undo-update' | 'driver' | 'settings' | 'repair' | 'help' export interface Fix { key: string @@ -218,6 +234,8 @@ export interface FixContext { totalMb: number /** The instance runs a Java the player chose. */ customJava: boolean + /** The newest content update that can be undone, if any. */ + lastUpdate: UpdateBackup | null } /** The ways to fix a crash, best first. */ @@ -360,6 +378,28 @@ export function fixesFor(d: Diagnosis, ctx: FixContext): Fix[] { case 'conflict': case 'version': case 'mixin': + if (d.kind === 'conflict' && d.declared && d.other) { + // The loader named the versions: update the mod that is too old, or undo the update that brought the clash. + out.push({ + ...updates([d.other]), + title: [t('Update '), ...who(d.other, t('the other mod'))], + text: [...who(d.culprit, t('A mod')), t(' needs a newer '), ...who(d.other, t('version')), t('. Opens the mods of {n}.', { n })], + }) + const touched = (p: Party | null) => !!p?.mod && !!ctx.lastUpdate?.files.some((f) => baseName(p.mod!) === f.new.replace(/\.disabled$/, '')) + if (ctx.lastUpdate && (touched(d.culprit) || touched(d.other))) { + out.push({ + key: 'undo-update', + id: 'undo-update', + title: [t('Undo the last update')], + text: [t('Puts back the {n} the last update replaced, so you play as before.', { n: plural(ctx.lastUpdate.files.length, 'file', 'files') })], + undoable: false, + undo: t('Update again from Mods'), + }) + } + disable(d.other) + out.push(repair(false)) + break + } disable(d.culprit) out.push(updates(d.kind === 'version' ? [d.culprit] : [d.culprit, d.other])) out.push(repair(false)) diff --git a/ui/src/lib/views/servers/Servers.svelte b/ui/src/lib/views/servers/Servers.svelte index f597686..a8a3ca5 100644 --- a/ui/src/lib/views/servers/Servers.svelte +++ b/ui/src/lib/views/servers/Servers.svelte @@ -2,7 +2,7 @@ import { t } from '../../i18n.svelte' import { tick, untrack } from 'svelte' import { api } from '../../api' - import { Button, Dialog, Icon, InstanceIcon, MetaChip, PlayButton, ServerRow, StatusTag, TextField } from '../../cubby' + import { Button, Dialog, Icon, Inspector, InspectorHead, InspectorNotice, InspectorSection, InspectorStatus, InstanceIcon, MetaChip, Motd, PlayButton, ServerRow, StatusTag, TextField } from '../../cubby' import { num } from '../../format' import { iconOf } from '../../icon' import { app } from '../../state.svelte' @@ -357,6 +357,7 @@ address={e.server.address} iconSrc={e.status?.iconUrl ?? e.server.iconUrl ?? undefined} motd={motdOf(e.status)} + motdFormatted={e.status?.motdFormatted} online={e.status ? e.status.online : false} offlineText={e.status ? t('Can’t reach server') : t('Checking the server…')} players={e.status?.online ? { online: e.status.playersOnline, max: e.status.playersMax } : undefined} @@ -375,121 +376,90 @@
+ {:else} -

{t('Server details')}

-

{entries?.length ? t('Select a server to see its details.') : t('Add a server to see its status here.')}

+ {#snippet svEmpty()}{/snippet} + +

{entries?.length ? t('Select a server to see who’s online and join it.') : t('Add a server to see its status here.')}

{/if} - + @@ -677,109 +647,11 @@ background: var(--bg-chrome); border-inline-start: var(--border-chrome) solid var(--edge); } - .aside-inner { + .aside :global(.aside-inner) { position: sticky; top: 0; max-height: calc(100vh - var(--size-titlebar)); + min-height: 0; overflow: auto; - display: flex; - flex-direction: column; - gap: var(--space-4); - padding: var(--space-6) var(--space-5); - } - .aside-inner :global(.cb-play) { - width: 100%; - } - .who { - display: flex; - align-items: center; - gap: var(--space-4); - } - .who-text { - min-width: 0; - } - .address { - margin-top: var(--space-1); - overflow-wrap: anywhere; - } - .big-icon { - display: block; - flex: none; - width: 64px; - height: 64px; - image-rendering: pixelated; - border: var(--border-block) solid var(--edge); - box-shadow: var(--shadow-block-sm); - } - .placeholder { - display: flex; - align-items: center; - justify-content: center; - color: var(--ink-muted); - background: var(--surface); - } - .actions { - display: flex; - flex-wrap: wrap; - gap: var(--space-2); - } - .label { - margin-bottom: 6px; - } - .motd { - padding: var(--space-2) var(--space-3); - white-space: pre-line; - overflow-wrap: anywhere; - background: var(--field); - border: var(--border-block) solid var(--outline); - box-shadow: var(--shadow-well); - } - .facts { - display: grid; - grid-template-columns: auto 1fr; - align-items: center; - gap: var(--space-2) var(--space-4); - padding: var(--space-3) var(--space-4); - background: var(--surface); - border: var(--border-block) solid var(--edge); - } - .dd-row { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-2); - min-width: 0; - } - .fit { - display: flex; - align-items: flex-start; - gap: 10px; - padding: 10px var(--space-3); - background: var(--surface); - border: var(--border-block) solid var(--edge); - } - .fit-icon { - display: inline-flex; - flex: none; - padding-top: 2px; - } - .fit--match .fit-icon, - .fit--range .fit-icon { - color: var(--grass-text); - } - .fit--mismatch .fit-icon { - color: var(--gold-text); - } - .fit--unknown .fit-icon { - color: var(--diamond-text); - } - .fit-text { - min-width: 0; - display: flex; - flex-direction: column; - gap: 2px; - } - .fit-action { - margin-top: var(--space-2); } diff --git a/ui/src/lib/views/settings/Settings.svelte b/ui/src/lib/views/settings/Settings.svelte index f6dfa38..77d57ef 100644 --- a/ui/src/lib/views/settings/Settings.svelte +++ b/ui/src/lib/views/settings/Settings.svelte @@ -22,7 +22,7 @@ const BLOCKS: { id: BlockId; label: string; words: string }[] = [ { id: 'language', label: t('Language'), words: 'english french français langue translation locale' }, { id: 'java', label: t('Java and memory'), words: 'java runtime automatic memory ram jvm arguments installs detected' }, - { id: 'game', label: t('Game'), words: 'window size width height fullscreen starts launch minimize keep close play time track show' }, + { id: 'game', label: t('Game'), words: 'window size width height fullscreen starts launch minimize keep close play time track show discord rich presence status' }, { id: 'downloads', label: t('Downloads'), words: 'parallel concurrency mod updates check modrinth proxy network system manual address' }, { id: 'storage', label: t('Storage'), words: 'data folder disk space size cache clean up instances libraries assets logs trash open' }, { id: 'accounts', label: t('Accounts'), words: 'microsoft application client id azure sign in curseforge api key' }, @@ -471,6 +471,16 @@ s.java.auto, (v) => saveJava({ auto: v }), )} + {@render switchRow( + 'java-memory', + t('Set memory automatically'), + s.java.autoMemory + ? t('Each instance gets what its mods need: 2 GB for Vanilla, up to 8 GB for big modpacks, never more than half of your {total}.', { total: totalMb ? gb(totalMb) : t('memory') }) + : t('Every instance that doesn’t set its own gets the memory below.'), + s.java.autoMemory, + (v) => saveJava({ autoMemory: v }), + )} + {#if !s.java.autoMemory}
+ {/if}

{ON_LAUNCH_HINT[s.onLaunch]}

+ {#if app.info?.discord} + {@render switchRow('discord', t('Show on Discord'), t('Your Discord profile says which instance you’re playing, while you play. Discord has to be open on this computer.'), s.discordPresence, (v) => save({ discordPresence: v }))} + {/if} {@render switchRow('track', t('Count play time'), t('Adds each session to the instance’s play time.'), s.trackPlayTime, (v) => save({ trackPlayTime: v }))} {@render switchRow('show', t('Show play time'), t('In the library, with each instance.'), s.showPlayTime, (v) => save({ showPlayTime: v }))}
diff --git a/ui/src/lib/views/shell/Palette.svelte b/ui/src/lib/views/shell/Palette.svelte index fc5a83f..5bc3f7d 100644 --- a/ui/src/lib/views/shell/Palette.svelte +++ b/ui/src/lib/views/shell/Palette.svelte @@ -76,10 +76,10 @@ { id: 'a:new', label: t('New instance'), detail: t('Pick a version and a loader'), icon: 'plus', words: 'create add', run: () => app.navigate({ name: 'create' }) }, { id: 'a:import', - label: t('Import from Prism Launcher'), - detail: t('Copies instances, Prism stays as it is'), + label: t('Import from another launcher'), + detail: t('Copies instances, the other launcher stays as it is'), icon: 'import', - words: 'import prism bring', + words: 'import prism multimc curseforge atlauncher gdlauncher modrinth bring', run: () => (app.prismImportOpen = true), }, { diff --git a/ui/src/lib/views/skins/Skins.svelte b/ui/src/lib/views/skins/Skins.svelte index eabbf8a..fe0db4d 100644 --- a/ui/src/lib/views/skins/Skins.svelte +++ b/ui/src/lib/views/skins/Skins.svelte @@ -3,7 +3,7 @@