From 814b1be2d349411653634cb5f1e84dfa4737a14b Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:25:57 +0100 Subject: [PATCH 01/31] Set the game's memory from the instance's mods A new global setting, on by default, gives each instance 2 GB for Vanilla and up to 8 GB for big modpacks, never more than half of the computer's memory. An instance's own value still wins. Co-Authored-By: Claude Opus 5.5 --- crates/cubby-instance/src/lib.rs | 2 + crates/cubby-instance/src/memory.rs | 73 +++++++++++++++++++ crates/cubby-instance/src/settings.rs | 4 +- src-tauri/src/commands/app.rs | 4 +- src-tauri/src/commands/instances.rs | 35 ++++++++- src-tauri/src/commands/launch.rs | 11 +-- src-tauri/src/dto.rs | 4 + src-tauri/src/state.rs | 3 + ui/src/lib/dev/mock.ts | 3 +- ui/src/lib/i18n/fr-10.ts | 14 ++++ ui/src/lib/i18n/fr.ts | 2 + ui/src/lib/state.svelte.ts | 8 ++ ui/src/lib/types.ts | 5 +- .../views/instance-page/OverviewTab.svelte | 6 +- .../views/instance-page/SettingsTab.svelte | 10 ++- ui/src/lib/views/play/Crash.svelte | 2 +- ui/src/lib/views/settings/Settings.svelte | 11 +++ 17 files changed, 174 insertions(+), 23 deletions(-) create mode 100644 crates/cubby-instance/src/memory.rs create mode 100644 ui/src/lib/i18n/fr-10.ts diff --git a/crates/cubby-instance/src/lib.rs b/crates/cubby-instance/src/lib.rs index 9d68bbf..c58240b 100644 --- a/crates/cubby-instance/src/lib.rs +++ b/crates/cubby-instance/src/lib.rs @@ -1,6 +1,7 @@ //! Instances and their content, world backups, Prism Launcher import and launcher settings. mod backups; +pub mod memory; pub mod content; mod model; mod nbt; @@ -17,6 +18,7 @@ pub use content::{ }; pub use servers::{read_servers, write_servers, ServerEntry}; pub use backups::{backup_stamp, WorldBackup}; +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/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/settings.rs b/crates/cubby-instance/src/settings.rs index 8b3ff2c..0a437f2 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() } } } diff --git a/src-tauri/src/commands/app.rs b/src-tauri/src/commands/app.rs index 294979a..65c1030 100644 --- a/src-tauri/src/commands/app.rs +++ b/src-tauri/src/commands/app.rs @@ -6,15 +6,13 @@ 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), } } diff --git a/src-tauri/src/commands/instances.rs b/src-tauri/src/commands/instances.rs index 3bd46e4..b4a303f 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] diff --git a/src-tauri/src/commands/launch.rs b/src-tauri/src/commands/launch.rs index 448cb54..853b6eb 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, diff --git a/src-tauri/src/dto.rs b/src-tauri/src/dto.rs index e430f8c..61cf821 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, } } } diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index b9739c7..99cb7e9 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -37,6 +37,8 @@ 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, } impl Core { @@ -69,6 +71,7 @@ impl Core { games: GameManager::new(), login: Mutex::new(None), tasks: Mutex::new(HashSet::new()), + total_memory_mb: crate::commands::total_memory_mb(), paths, }) } diff --git a/ui/src/lib/dev/mock.ts b/ui/src/lib/dev/mock.ts index 6e25f50..0e8be14 100644 --- a/ui/src/lib/dev/mock.ts +++ b/ui/src/lib/dev/mock.ts @@ -118,6 +118,7 @@ const inst = (p: Partial & Pick = { + // 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)', +} 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 b8ee333..a103878 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)) } diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index ecd37c4..43bc600 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 diff --git a/ui/src/lib/views/instance-page/OverviewTab.svelte b/ui/src/lib/views/instance-page/OverviewTab.svelte index ab68330..512fa83 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 @@ -254,7 +254,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/SettingsTab.svelte b/ui/src/lib/views/instance-page/SettingsTab.svelte index 42d0efe..fdd56b0 100644 --- a/ui/src/lib/views/instance-page/SettingsTab.svelte +++ b/ui/src/lib/views/instance-page/SettingsTab.svelte @@ -130,7 +130,9 @@ // Java and memory const o = $derived(instance.javaOverrides) - const g = $derived(app.settings?.java ?? { auto: true, minMemoryMb: 1024, maxMemoryMb: 4096, jvmArgs: '' }) + const g = $derived(app.settings?.java ?? { auto: true, autoMemory: true, minMemoryMb: 1024, maxMemoryMb: 4096, jvmArgs: '' }) + /** What the global settings give this instance. */ + const globalMax = $derived(g.autoMemory ? instance.recommendedMemoryMb || g.maxMemoryMb : g.maxMemoryMb) const usesGlobal = $derived(o.executable == null && o.minMemoryMb == null && o.maxMemoryMb == null && o.jvmArgs == null) const total = $derived(app.info?.totalMemoryMb ?? 8192) const memMax = $derived(Math.max(2048, Math.floor(total / 512) * 512)) @@ -142,11 +144,11 @@ function setGlobal(on: boolean) { if (on) void save({ javaOverrides: { executable: null, minMemoryMb: null, maxMemoryMb: null, jvmArgs: null } }) - else void overrides({ minMemoryMb: g.minMemoryMb, maxMemoryMb: g.maxMemoryMb }) + else void overrides({ minMemoryMb: Math.min(g.minMemoryMb, globalMax), maxMemoryMb: globalMax }) } let memDraft = $state(null) - const mem = $derived(memDraft ?? o.maxMemoryMb ?? g.maxMemoryMb) + const mem = $derived(memDraft ?? o.maxMemoryMb ?? globalMax) let memTimer: ReturnType | undefined function setMemory(v: number) { @@ -332,7 +334,7 @@ {#if usesGlobal}
-
{t(g.jvmArgs.trim() ? 'Memory {memory} · Java picked automatically · global JVM arguments' : 'Memory {memory} · Java picked automatically', { memory: megabytes(g.maxMemoryMb) })}
+
{t(g.jvmArgs.trim() ? 'Memory {memory} · Java picked automatically · global JVM arguments' : 'Memory {memory} · Java picked automatically', { memory: g.autoMemory ? t('{n}, set from its mods', { n: megabytes(globalMax) }) : megabytes(globalMax) })}
{t('The same as every instance that uses the global settings.')}
diff --git a/ui/src/lib/views/play/Crash.svelte b/ui/src/lib/views/play/Crash.svelte index 8bac3f0..3f83747 100644 --- a/ui/src/lib/views/play/Crash.svelte +++ b/ui/src/lib/views/play/Crash.svelte @@ -67,7 +67,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(() => { diff --git a/ui/src/lib/views/settings/Settings.svelte b/ui/src/lib/views/settings/Settings.svelte index 265211d..cdef88c 100644 --- a/ui/src/lib/views/settings/Settings.svelte +++ b/ui/src/lib/views/settings/Settings.svelte @@ -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}
Date: Sun, 8 Nov 2026 16:28:22 +0100 Subject: [PATCH 02/31] Datapacks of a world: listing, turning on and off, adding from files or Modrinth (backend) Co-Authored-By: Claude Opus 5.5 --- crates/cubby-instance/src/datapacks.rs | 262 +++++++++++++++++++++++++ crates/cubby-instance/src/lib.rs | 2 + crates/cubby-modrinth/src/datapacks.rs | 76 +++++++ crates/cubby-modrinth/src/lib.rs | 2 + src-tauri/src/commands/datapacks.rs | 109 ++++++++++ src-tauri/src/commands/mod.rs | 1 + src-tauri/src/lib.rs | 6 + 7 files changed, 458 insertions(+) create mode 100644 crates/cubby-instance/src/datapacks.rs create mode 100644 crates/cubby-modrinth/src/datapacks.rs create mode 100644 src-tauri/src/commands/datapacks.rs 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/lib.rs b/crates/cubby-instance/src/lib.rs index c58240b..de41705 100644 --- a/crates/cubby-instance/src/lib.rs +++ b/crates/cubby-instance/src/lib.rs @@ -1,6 +1,7 @@ //! Instances and their content, world backups, Prism Launcher import and launcher settings. mod backups; +pub mod datapacks; pub mod memory; pub mod content; mod model; @@ -18,6 +19,7 @@ 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 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}; diff --git a/crates/cubby-modrinth/src/datapacks.rs b/crates/cubby-modrinth/src/datapacks.rs new file mode 100644 index 0000000..97058cd --- /dev/null +++ b/crates/cubby-modrinth/src/datapacks.rs @@ -0,0 +1,76 @@ +//! Datapacks: they go into a world (`saves//datapacks`), not into the instance, so they have their +//! own search and download instead of the install plans of mods and packs. + +use cubby_common::{Error, Result}; + +use crate::browse::hit_from_search; +use crate::client::Modrinth; +use crate::model::{FileInfo, SearchResults}; + +/// Search facets for datapacks made for `game_version` (any version when empty). +pub fn datapack_facets(game_version: &str) -> Vec> { + let mut facets = vec![vec!["project_type:datapack".to_string()]]; + let version = game_version.trim(); + if !version.is_empty() { + facets.push(vec![format!("versions:{version}")]); + } + facets +} + +impl Modrinth { + /// Datapacks for a game version: by relevance with a query, else the most downloaded. 20 per page. + pub async fn search_datapacks(&self, query: &str, game_version: &str, offset: u32) -> Result { + let facets = serde_json::to_string(&datapack_facets(game_version)).map_err(|e| Error::Other(e.to_string()))?; + let text = query.trim(); + let mut params = vec![ + ("facets", facets), + ("index", if text.is_empty() { "downloads" } else { "relevance" }.to_string()), + ("offset", offset.to_string()), + ("limit", "20".to_string()), + ]; + if !text.is_empty() { + params.insert(0, ("query", text.to_string())); + } + let response = self.search_raw(¶ms).await?; + Ok(SearchResults { + hits: response.hits.into_iter().map(hit_from_search).collect(), + total: response.total_hits, + offset: response.offset, + limit: response.limit, + }) + } + + /// The `.zip` of the newest datapack version of a project for `game_version`. + pub async fn datapack_file(&self, id_or_slug: &str, game_version: &str) -> Result { + let versions = self.project_versions_raw(id_or_slug, &["datapack".to_string()], &[game_version.to_string()]).await?; + let newest = versions + .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(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn facets_for_a_version() { + assert_eq!(datapack_facets("1.21.1"), vec![vec!["project_type:datapack".to_string()], vec!["versions:1.21.1".to_string()]]); + assert_eq!(datapack_facets(" "), vec![vec!["project_type:datapack".to_string()]]); + } +} diff --git a/crates/cubby-modrinth/src/lib.rs b/crates/cubby-modrinth/src/lib.rs index aac42a7..9c4959c 100644 --- a/crates/cubby-modrinth/src/lib.rs +++ b/crates/cubby-modrinth/src/lib.rs @@ -4,6 +4,7 @@ pub mod api; mod browse; mod client; +mod datapacks; mod install; mod local; mod model; @@ -11,6 +12,7 @@ pub mod mrpack; mod resolve; pub use browse::{facets, search_params}; +pub use datapacks::datapack_facets; pub use client::{Modrinth, API_BASE, USER_AGENT}; pub use model::*; pub use mrpack::{sanitize_path, MrpackIndex, PackLoader}; diff --git a/src-tauri/src/commands/datapacks.rs b/src-tauri/src/commands/datapacks.rs new file mode 100644 index 0000000..cb3d743 --- /dev/null +++ b/src-tauri/src/commands/datapacks.rs @@ -0,0 +1,109 @@ +//! 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 +} + +/// Modrinth datapacks made for the instance's Minecraft version. +#[tauri::command] +pub async fn search_datapacks( + core: State<'_, Core>, + id: String, + query: String, + offset: u32, +) -> CmdResult { + let inst = core.store.get(&id).msg()?; + Ok(core + .modrinth + .search_datapacks(&query, &inst.minecraft, offset) + .await + .msg()? + .into()) +} + +/// Downloads the newest version of a Modrinth datapack for the instance's Minecraft version into the world. +/// Returns the file name. +#[tauri::command] +pub async fn install_datapack( + core: State<'_, Core>, + id: String, + world: String, + project_id: String, +) -> CmdResult { + let inst = core.store.get(&id).msg()?; + let game = core.store.game_dir(&inst); + let file = core + .modrinth + .datapack_file(project_id.trim(), &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) +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 48a5c3a..a3346a1 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -20,6 +20,7 @@ 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 instances; pub(crate) mod launch; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6b6bd71..27add1c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -126,6 +126,12 @@ pub fn run() { packs::import_pack_url, packs::blocked_files, packs::find_blocked_files, + commands::datapacks::list_datapacks, + commands::datapacks::set_datapack_enabled, + commands::datapacks::remove_datapack, + commands::datapacks::add_datapack_files, + commands::datapacks::search_datapacks, + commands::datapacks::install_datapack, ]) .build(tauri::generate_context!()) .expect("error while building Cubby") From 8ef91972eed78b5623c970c80584ebe26d47da1d Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:29:58 +0100 Subject: [PATCH 03/31] Datapacks in the Worlds tab: turn on and off, add from files or Modrinth Co-Authored-By: Claude Opus 5.5 --- ui/src/lib/api.ts | 13 + ui/src/lib/dev/mock.ts | 6 +- ui/src/lib/dev/mockExtra.ts | 79 ++++++ ui/src/lib/i18n/fr-10.ts | 24 ++ ui/src/lib/types.ts | 12 + .../views/instance-page/WorldDatapacks.svelte | 252 ++++++++++++++++++ .../lib/views/instance-page/WorldsTab.svelte | 3 + 7 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 ui/src/lib/dev/mockExtra.ts create mode 100644 ui/src/lib/views/instance-page/WorldDatapacks.svelte diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 9d4a502..d55755d 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -8,6 +8,7 @@ import type { BlockedFile, ContentUpdate, DataFolder, + Datapack, InstallPlan, SkinProfile, DefaultSkin, @@ -194,6 +195,18 @@ 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 }), + // 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 }), + /** Modrinth datapacks for the instance's Minecraft version, 20 per page. */ + searchDatapacks: (id: string, query: string, offset: number) => call('search_datapacks', { id, query, offset }), + /** Downloads the newest version for the instance's Minecraft version into the world; returns its file name. */ + installDatapack: (id: string, world: string, projectId: string) => call('install_datapack', { id, world, projectId }), + listPrismInstances: () => call('list_prism_instances'), importPrism: (paths: string[]) => call('import_prism', { paths }), openUrl: (url: string) => call('open_url', { url }), diff --git a/ui/src/lib/dev/mock.ts b/ui/src/lib/dev/mock.ts index 0e8be14..eb321fd 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 { handleExtra, NOT_HANDLED } from './mockExtra' import { OPTIONAL_MODS, PACKS, PACK_DESCRIPTION, PACK_MARKDOWN, PROVIDERS, SORTERS, morePacks, type MockPackDef } from './mockPacks' import type { Account, @@ -1045,8 +1046,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..6a0972e --- /dev/null +++ b/ui/src/lib/dev/mockExtra.ts @@ -0,0 +1,79 @@ +// 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, ProjectHit } 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, + kind: 'mod', + 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'], + clientSide: 'unsupported', + serverSide: 'required', +})) as unknown as ProjectHit[] + +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 'search_datapacks': { + await sleep(300) + const q = String(args.query ?? '').trim().toLowerCase() + const hits = DATAPACK_HITS.filter((h) => !q || `${h.title} ${h.summary}`.toLowerCase().includes(q)) + return { hits, total: hits.length, offset: 0, limit: 20 } + } + 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 + } + default: + return NOT_HANDLED + } +} diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index 3fcdf26..cb215b4 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -11,4 +11,28 @@ export const FR_10: Record = { '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.', } diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 43bc600..2875114 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -525,3 +525,15 @@ 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 +} diff --git a/ui/src/lib/views/instance-page/WorldDatapacks.svelte b/ui/src/lib/views/instance-page/WorldDatapacks.svelte new file mode 100644 index 0000000..42b0f9c --- /dev/null +++ b/ui/src/lib/views/instance-page/WorldDatapacks.svelte @@ -0,0 +1,252 @@ + + + +
+

{t('Datapacks · {length}', { length: packs?.length ?? 0 })}

+ {#if packs === null} +

{t('Reading datapacks…')}

+ {:else if !packs.length} +

{t('No datapacks in this world. They 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} +
+ + +
+ {#if running} +

{t('Close the game to change datapacks. They load when the world opens.')}

+ {/if} +
+ +{#if finding} + {#snippet findActions()} + + {/snippet} + (finding = false)} actions={findActions}> +
+ + {#if hits === null} +

{t('Searching Modrinth…')}

+ {:else if searchError} +

{searchError}

+ {:else if !hits.length} +

{t('No datapacks for Minecraft {minecraft} match.', { minecraft: instance.minecraft })}

+ {:else} +
    + {#each hits as h (h.id)} +
  • + {#if h.iconUrl} + + {:else} + + {/if} +
    + {h.title} + {h.summary} + {t('{author} · {downloads} downloads', { author: h.author, downloads: compactNum(h.downloads) })} +
    + {#if installed.includes(h.id)} + + {:else} + + {/if} +
  • + {/each} +
+ {/if} +
+
+{/if} + + diff --git a/ui/src/lib/views/instance-page/WorldsTab.svelte b/ui/src/lib/views/instance-page/WorldsTab.svelte index 98e77a0..3c832f8 100644 --- a/ui/src/lib/views/instance-page/WorldsTab.svelte +++ b/ui/src/lib/views/instance-page/WorldsTab.svelte @@ -8,6 +8,7 @@ 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' let { instance, data }: { instance: Instance; data: InstanceData } = $props() @@ -191,6 +192,8 @@ {#if running}

{t('Close the game to restore or delete a world.')}

{/if} + +

{t('Moves to the trash. Its backups stay.')}

From 220d02eafda864b233c049b94b42eb4c25880703 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:32:00 +0100 Subject: [PATCH 04/31] Review changelogs before updating, and undo the last update Updates now record which old file became which new one next to the backup of the old files. Undo puts the old files back and moves the new ones to the instance's trash. Co-Authored-By: Claude Opus 5.5 --- crates/cubby-instance/src/lib.rs | 2 + crates/cubby-instance/src/update_backups.rs | 210 ++++++++++++++++++ src-tauri/src/commands/discover.rs | 27 +++ src-tauri/src/lib.rs | 2 + ui/src/lib/api.ts | 6 + ui/src/lib/dev/mockExtra.ts | 21 +- ui/src/lib/i18n/fr-10.ts | 13 ++ ui/src/lib/types.ts | 8 + .../views/instance-page/InstancePage.svelte | 14 +- ui/src/lib/views/instance-page/ModsTab.svelte | 114 +++++++++- 10 files changed, 411 insertions(+), 6 deletions(-) create mode 100644 crates/cubby-instance/src/update_backups.rs diff --git a/crates/cubby-instance/src/lib.rs b/crates/cubby-instance/src/lib.rs index de41705..dda7f2b 100644 --- a/crates/cubby-instance/src/lib.rs +++ b/crates/cubby-instance/src/lib.rs @@ -11,6 +11,7 @@ mod servers; pub mod skins; mod settings; mod store; +pub mod update_backups; mod util; pub use content::{ @@ -20,6 +21,7 @@ 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 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}; 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/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/lib.rs b/src-tauri/src/lib.rs index 27add1c..67c5d7c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -126,6 +126,8 @@ pub fn run() { packs::import_pack_url, packs::blocked_files, packs::find_blocked_files, + commands::discover::list_update_backups, + commands::discover::undo_update, commands::datapacks::list_datapacks, commands::datapacks::set_datapack_enabled, commands::datapacks::remove_datapack, diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index d55755d..597cd6d 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -8,6 +8,7 @@ import type { BlockedFile, ContentUpdate, DataFolder, + UpdateBackup, Datapack, InstallPlan, SkinProfile, @@ -165,6 +166,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 }), diff --git a/ui/src/lib/dev/mockExtra.ts b/ui/src/lib/dev/mockExtra.ts index 6a0972e..b5fd738 100644 --- a/ui/src/lib/dev/mockExtra.ts +++ b/ui/src/lib/dev/mockExtra.ts @@ -1,6 +1,6 @@ // 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, ProjectHit } from '../types' +import type { Datapack, ProjectHit, UpdateBackup } from '../types' export const NOT_HANDLED = Symbol('not handled') @@ -40,6 +40,17 @@ const DATAPACK_HITS: ProjectHit[] = [ serverSide: 'required', })) as unknown as ProjectHit[] +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': @@ -73,6 +84,14 @@ export async function handleExtra(command: string, args: Record): P 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 + } default: return NOT_HANDLED } diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index cb215b4..5a4e33c 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -35,4 +35,17 @@ export const FR_10: Record = { 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.', } diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 2875114..2b23731 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -537,3 +537,11 @@ export interface Datapack { 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 }[] +} diff --git a/ui/src/lib/views/instance-page/InstancePage.svelte b/ui/src/lib/views/instance-page/InstancePage.svelte index f901f7a..27f4892 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) { diff --git a/ui/src/lib/views/instance-page/ModsTab.svelte b/ui/src/lib/views/instance-page/ModsTab.svelte index ab52cef..c7b09a2 100644 --- a/ui/src/lib/views/instance-page/ModsTab.svelte +++ b/ui/src/lib/views/instance-page/ModsTab.svelte @@ -7,14 +7,15 @@ + +{#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 27f4892..de6f858 100644 --- a/ui/src/lib/views/instance-page/InstancePage.svelte +++ b/ui/src/lib/views/instance-page/InstancePage.svelte @@ -248,6 +248,7 @@ + +{#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/SettingsTab.svelte b/ui/src/lib/views/instance-page/SettingsTab.svelte index fdd56b0..b600ce5 100644 --- a/ui/src/lib/views/instance-page/SettingsTab.svelte +++ b/ui/src/lib/views/instance-page/SettingsTab.svelte @@ -18,6 +18,7 @@ + +
+

{t('Map')}

+ {#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 3c832f8..fc658a4 100644 --- a/ui/src/lib/views/instance-page/WorldsTab.svelte +++ b/ui/src/lib/views/instance-page/WorldsTab.svelte @@ -9,6 +9,7 @@ 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() @@ -192,6 +193,8 @@ {#if running}

{t('Close the game to restore or delete a world.')}

{/if} + +
From ca317f7812cff058956a55e51d57c96cec496f75 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:46:18 +0100 Subject: [PATCH 10/31] Show the instance being played on Discord MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A small IPC client talks to the Discord app on the same computer. It needs a Discord application id at build time (CUBBY_DISCORD_CLIENT_ID); players can turn it off in Settings › Game. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 1 + Cargo.lock | 10 + Cargo.toml | 1 + README.md | 1 + crates/cubby-discord/Cargo.toml | 12 + crates/cubby-discord/src/lib.rs | 265 ++++++++++++++++++++++ crates/cubby-instance/src/settings.rs | 3 + src-tauri/Cargo.toml | 1 + src-tauri/src/commands/app.rs | 1 + src-tauri/src/commands/launch.rs | 26 +++ src-tauri/src/commands/settings.rs | 1 + src-tauri/src/dto.rs | 2 + src-tauri/src/state.rs | 15 ++ ui/src/lib/dev/mock.ts | 3 +- ui/src/lib/i18n/fr-10.ts | 5 + ui/src/lib/types.ts | 4 + ui/src/lib/views/settings/Settings.svelte | 5 +- 17 files changed, 354 insertions(+), 2 deletions(-) create mode 100644 crates/cubby-discord/Cargo.toml create mode 100644 crates/cubby-discord/src/lib.rs 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/Cargo.lock b/Cargo.lock index 66163e0..f267824 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -741,6 +741,7 @@ dependencies = [ "cubby-auth", "cubby-common", "cubby-curseforge", + "cubby-discord", "cubby-ftb", "cubby-instance", "cubby-java", @@ -833,6 +834,15 @@ dependencies = [ "zip 2.6.1", ] +[[package]] +name = "cubby-discord" +version = "2026.11.0-beta.1" +dependencies = [ + "serde", + "serde_json", + "tracing", +] + [[package]] name = "cubby-ftb" version = "2026.11.0-beta.1" diff --git a/Cargo.toml b/Cargo.toml index da104c0..1d16c5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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..3fc6dcc 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ npm run tauri dev Two values can be set at build time: - `CUBBY_CURSEFORGE_API_KEY`: a [CurseForge API key](https://console.curseforge.com). Without it, CurseForge search is turned off, and everything else works. +- `CUBBY_DISCORD_CLIENT_ID`: optional. The id of a Discord application whose Rich Presence art has an image named `cubby`. With it, Discord shows which instance the player is playing (Settings › Game › Show on Discord). - `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. The interface also runs in a plain browser with sample data, which is handy for working on screens: `npm run dev` in `ui/`. 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..4199f25 --- /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 std::time::Duration; + +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; + 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/src/settings.rs b/crates/cubby-instance/src/settings.rs index 0a437f2..fdaf77b 100644 --- a/crates/cubby-instance/src/settings.rs +++ b/crates/cubby-instance/src/settings.rs @@ -158,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 { @@ -182,6 +184,7 @@ impl Default for Settings { updates: UpdateSettings::default(), curseforge_api_key: None, onboarded: false, + discord_presence: true, } } } diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 607cd5a..e94a321 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 diff --git a/src-tauri/src/commands/app.rs b/src-tauri/src/commands/app.rs index 65c1030..9f4dad1 100644 --- a/src-tauri/src/commands/app.rs +++ b/src-tauri/src/commands/app.rs @@ -14,6 +14,7 @@ pub fn app_info(core: State<'_, Core>) -> AppInfoDto { curseforge_key: core.curseforge_key_with_source().map(|(_, source)| source), total_memory_mb: core.total_memory_mb, dev_build: cfg!(debug_assertions), + discord: core.discord.is_some(), } } diff --git a/src-tauri/src/commands/launch.rs b/src-tauri/src/commands/launch.rs index 853b6eb..7dfb1ed 100644 --- a/src-tauri/src/commands/launch.rs +++ b/src-tauri/src/commands/launch.rs @@ -175,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 { @@ -188,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() @@ -316,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/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 61cf821..9f09a30 100644 --- a/src-tauri/src/dto.rs +++ b/src-tauri/src/dto.rs @@ -426,6 +426,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)] diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 99cb7e9..1f21e97 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -39,6 +39,10 @@ pub struct Core { 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 { @@ -72,6 +76,8 @@ impl Core { 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, }) } @@ -115,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/ui/src/lib/dev/mock.ts b/ui/src/lib/dev/mock.ts index 769f97d..59fa78d 100644 --- a/ui/src/lib/dev/mock.ts +++ b/ui/src/lib/dev/mock.ts @@ -176,6 +176,7 @@ let settings: Settings = { downloadConcurrency: 4, msaClientId: null, trackPlayTime: true, + discordPresence: true, showPlayTime: true, proxy: { mode: 'system', url: '' }, updates: { mode: 'ask', channel: 'preview', skipped: null }, @@ -546,7 +547,7 @@ export async function handle(command: string, args: Record): Promis 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': { diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index d71297b..ea032e8 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -127,4 +127,9 @@ export const FR_10: Record = { '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.', } diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 3c9f6eb..021dd1b 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -176,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 { @@ -202,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 = diff --git a/ui/src/lib/views/settings/Settings.svelte b/ui/src/lib/views/settings/Settings.svelte index cdef88c..15a8603 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' }, @@ -572,6 +572,9 @@ />

{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 }))} From 6d1f86a1f6eb558a00befa9409b72da92780d34e Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:47:26 +0100 Subject: [PATCH 11/31] Use as_chunks in the NBT reader and the CurseForge fingerprint Co-Authored-By: Claude Opus 5.5 --- crates/cubby-curseforge/src/export.rs | 7 +++---- crates/cubby-instance/src/nbt.rs | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/cubby-curseforge/src/export.rs b/crates/cubby-curseforge/src/export.rs index a64df6b..1e6073a 100644 --- a/crates/cubby-curseforge/src/export.rs +++ b/crates/cubby-curseforge/src/export.rs @@ -17,15 +17,14 @@ 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 mut chunks = data.chunks_exact(4); - for chunk in &mut chunks { - let mut k = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + 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; } - let rest = chunks.remainder(); if !rest.is_empty() { for (i, b) in rest.iter().enumerate() { h ^= (*b as u32) << (8 * i); diff --git a/crates/cubby-instance/src/nbt.rs b/crates/cubby-instance/src/nbt.rs index 0965c40..bdfa4e4 100644 --- a/crates/cubby-instance/src/nbt.rs +++ b/crates/cubby-instance/src/nbt.rs @@ -243,7 +243,7 @@ impl Reader<'_> { 12 => { let n = self.len()?; let bytes = self.take(n.checked_mul(8)?)?; - Tag::LongArray(bytes.chunks_exact(8).map(|c| i64::from_be_bytes(c.try_into().unwrap_or([0; 8]))).collect()) + Tag::LongArray(bytes.as_chunks::<8>().0.iter().map(|c| i64::from_be_bytes(*c)).collect()) } _ => return None, }) From 406a816155a5910531134d437126b3831fe38c6e Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:49:23 +0100 Subject: [PATCH 12/31] Let the export and copy dialogs keep the dialog's width Co-Authored-By: Claude Opus 5.5 --- ui/src/lib/views/instance-page/CopyOptionsDialog.svelte | 1 - ui/src/lib/views/instance-page/ExportDialog.svelte | 1 - 2 files changed, 2 deletions(-) diff --git a/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte b/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte index 3bb3e25..d697b06 100644 --- a/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte +++ b/ui/src/lib/views/instance-page/CopyOptionsDialog.svelte @@ -73,7 +73,6 @@ display: flex; flex-direction: column; gap: var(--space-3); - min-width: min(460px, 80vw); } .field { display: flex; diff --git a/ui/src/lib/views/instance-page/ExportDialog.svelte b/ui/src/lib/views/instance-page/ExportDialog.svelte index 150d94b..ea64af4 100644 --- a/ui/src/lib/views/instance-page/ExportDialog.svelte +++ b/ui/src/lib/views/instance-page/ExportDialog.svelte @@ -139,7 +139,6 @@ display: flex; flex-direction: column; gap: var(--space-3); - min-width: min(480px, 80vw); } .include { gap: var(--space-2); From 35363b8e1736c0f3378ac9ba724d875903ee1629 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:53:49 +0100 Subject: [PATCH 13/31] Name the other launchers in the import footer, not only Prism Co-Authored-By: Claude Opus 5.5 --- ui/src/lib/i18n/fr-10.ts | 4 ++++ ui/src/lib/views/create/ImportSource.svelte | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index ea032e8..adb7b38 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -132,4 +132,8 @@ export const FR_10: Record = { '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', } diff --git a/ui/src/lib/views/create/ImportSource.svelte b/ui/src/lib/views/create/ImportSource.svelte index c29915d..fe077af 100644 --- a/ui/src/lib/views/create/ImportSource.svelte +++ b/ui/src/lib/views/create/ImportSource.svelte @@ -172,8 +172,8 @@
- {t('Coming from Prism Launcher?')} - + {t('Coming from Prism, CurseForge, the Modrinth App or another launcher?')} +
From 8a79d6435ec3784193ba9dcb9d02738d4267c1c7 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:57:36 +0100 Subject: [PATCH 14/31] Readable mod panel and working world icons on macOS - The asset protocol refused files under .minecraft on macOS and Linux (hidden folder): world icons and screenshots didn't show. - Mod panel: actions right under the status, changelog as plain text with links reduced to their text, four lines with a button for the rest, and separate tags for on/off and update available. - Datapack buttons wrap inside the world panel. Co-Authored-By: Claude Opus 5.5 --- src-tauri/tauri.conf.json | 7 ++- ui/src/lib/i18n/fr-10.ts | 6 ++ ui/src/lib/views/instance-page/ModsTab.svelte | 62 +++++++++++++------ .../views/instance-page/WorldDatapacks.svelte | 3 + 4 files changed, 56 insertions(+), 22 deletions(-) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index adff1db..04fafc5 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -47,9 +47,10 @@ "devCsp": null, "assetProtocol": { "enable": true, - "scope": [ - "$DATA/Cubby/instances/**" - ] + "scope": { + "allow": ["$DATA/Cubby/instances/**"], + "requireLiteralLeadingDot": false + } } } }, diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index adb7b38..d8f4a3f 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -136,4 +136,10 @@ export const FR_10: Record = { // 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é', } diff --git a/ui/src/lib/views/instance-page/ModsTab.svelte b/ui/src/lib/views/instance-page/ModsTab.svelte index c7b09a2..b31a78c 100644 --- a/ui/src/lib/views/instance-page/ModsTab.svelte +++ b/ui/src/lib/views/instance-page/ModsTab.svelte @@ -195,14 +195,26 @@ }) /** A Markdown changelog as short plain lines. */ + /** Changelog lines as plain text: Markdown links keep their text ("([#3916](https://…))" → "(#3916)"), bare URLs go. */ function notes(md: string): string[] { return md .split('\n') - .map((l) => l.replace(/^\s*(#+|[-*+]|\d+\.)\s*/, '').replace(/[*_`]/g, '').trim()) + .map((l) => + l + .replace(/^\s*(#+|[-*+]|\d+\.)\s*/, '') + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/\(?\s*https?:\/\/\S+?\s*\)?(?=\s|$)/g, '') + .replace(/[*_`]/g, '') + .replace(/\(\s*\)/g, '') + .trim(), + ) .filter(Boolean) - .slice(0, 8) } + const NOTES_SHOWN = 4 + /** The selected mod whose whole changelog is shown. */ + let notesOpen = $state(null) + const authors = (m: ModFile) => (m.authors.length ? `by ${m.authors.join(', ')}` : undefined) @@ -318,14 +330,23 @@
{#if m.version}{m.version}{/if} {#if !m.enabled} - {t('Off')} - {:else if sel.update} - {t('On · update ready')} - {:else if data.updates && sel.source} - {t('On · up to date')} + {t('Turned off')} {:else} - {t('On')} + {t('Turned on')} + {/if} + {#if sel.update} + {t('Update available')} + {:else if data.updates && sel.source} + {t('Up to date')} + {/if} +
+
+ {#if sel.source}{/if} + {#if sel.update} + {/if} + +

{t('What it does')}

@@ -351,25 +372,27 @@

{t('Also loaded from')} {sel.twins.map((t) => t.fileName).join(', ')}{t('. Keep one.')}

{/if} {#if sel.update} + {@const lines = notes(sel.update.changelog)} + {@const all = notesOpen === sel.key}
-

{t('New in {latestVersion}', { latestVersion: sel.update.latestVersion })}

- {#if notes(sel.update.changelog).length} +

{t('What’s new')}

+

{sel.update.latestVersion}

+ {#if lines.length}
    - {#each notes(sel.update.changelog) as line, i (i)}
  • {line}
  • {/each} + {#each all ? lines : lines.slice(0, NOTES_SHOWN) as line, i (i)}
  • {line}
  • {/each}
+ {#if lines.length > NOTES_SHOWN} +
+ +
+ {/if} {:else}

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

{/if}
{/if} -
- {#if sel.source}{/if} - {#if sel.update} - - {/if} - - -
{:else}

{t('Pick a mod to see what it does and its file.')}

{/if} @@ -598,5 +621,6 @@ margin: 0; padding-inline-start: 20px; list-style: square; + overflow-wrap: anywhere; } diff --git a/ui/src/lib/views/instance-page/WorldDatapacks.svelte b/ui/src/lib/views/instance-page/WorldDatapacks.svelte index 42b0f9c..59a8441 100644 --- a/ui/src/lib/views/instance-page/WorldDatapacks.svelte +++ b/ui/src/lib/views/instance-page/WorldDatapacks.svelte @@ -231,9 +231,12 @@ display: flex; flex-direction: column; } + /* Full width, so the two buttons wrap inside the panel instead of sticking out of it */ .actions { + align-self: stretch; display: flex; flex-wrap: wrap; + justify-content: flex-end; gap: var(--space-2); } .finder { From f8ffb598f2e90342261b6f7321cb008f02ca8b45 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:59:41 +0100 Subject: [PATCH 15/31] Two buttons in a side panel wrap instead of sticking out of it The equal-halves grid let long labels overflow the panel (Find on Modrinth / Add from file). They now share the row when they fit, and take a row each when they don't. Co-Authored-By: Claude Opus 5.5 --- ui/src/app.css | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ui/src/app.css b/ui/src/app.css index 3a23c1c..c0c61e5 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -57,13 +57,16 @@ aside :where(div, span, p):has(> :is(.cb-btn, .cb-iconbtn)):not(:has(> :not(.cb- flex-wrap: wrap; justify-content: flex-end; } +/* Two buttons share the row equally; when their labels don't fit side by side, each takes a full row + (a grid of two halves made long labels stick out of the panel). */ 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; + display: flex; + flex-wrap: wrap; 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%; + flex: 1 1 0; + min-width: max-content; justify-content: center; white-space: nowrap; } From 11102b552580ada4aef2ce8ebaef7a7493dc04b2 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:06:59 +0100 Subject: [PATCH 16/31] Crash screen: name two mods the Fabric loader says don't work together "Mod 'Sodium' is incompatible with version 1.11.7 or earlier of mod 'Iris'" is now a conflict naming both, with the versions, and offers to update the other mod or undo the last update when it touched one of them. Log entries that hold several lines are read line by line. First UI tests: npm test. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 2 +- ui/package.json | 3 +- ui/src/lib/i18n/fr-10.ts | 14 ++++++ ui/src/lib/views/play/Crash.svelte | 32 +++++++++++- ui/src/lib/views/play/crash.test.ts | 75 +++++++++++++++++++++++++++++ ui/src/lib/views/play/crash.ts | 32 +++++++++++- ui/src/lib/views/play/crashText.ts | 44 ++++++++++++++++- 7 files changed, 195 insertions(+), 7 deletions(-) create mode 100644 ui/src/lib/views/play/crash.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 24f7243..73e1ef8 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 diff --git a/ui/package.json b/ui/package.json index f785dde..715973f 100644 --- a/ui/package.json +++ b/ui/package.json @@ -7,7 +7,8 @@ "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/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index d8f4a3f..e37993b 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -142,4 +142,18 @@ export const FR_10: Record = { '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', } diff --git a/ui/src/lib/views/play/Crash.svelte b/ui/src/lib/views/play/Crash.svelte index 3f83747..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(() => { @@ -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/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)) From 824276c85a574130c04fd3d1d42568fa478881e6 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:14:46 +0100 Subject: [PATCH 17/31] =?UTF-8?q?Discover=20=E2=80=BA=20Datapacks:=20searc?= =?UTF-8?q?h,=20pages=20and=20installs=20into=20a=20world?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Datapacks get their own Discover tab and project pages; installing asks for the instance and the world. Find on Modrinth in the Worlds tab opens it set to that world, instead of a search dialog. Also fixes See the full page in Discover's install dialog, which read the project after closing it. Co-Authored-By: Claude Opus 5.5 --- crates/cubby-modrinth/src/browse.rs | 15 +- crates/cubby-modrinth/src/datapacks.rs | 68 ++---- crates/cubby-modrinth/src/lib.rs | 1 - crates/cubby-modrinth/src/model.rs | 6 +- crates/cubby-modrinth/src/resolve.rs | 1 + src-tauri/src/commands/datapacks.rs | 23 +-- src-tauri/src/dto.rs | 1 + src-tauri/src/lib.rs | 1 - ui/src/lib/api.ts | 6 +- ui/src/lib/dev/mock.ts | 4 +- ui/src/lib/dev/mockExtra.ts | 45 +++- ui/src/lib/i18n/fr-10.ts | 25 +++ ui/src/lib/state.svelte.ts | 14 ++ ui/src/lib/types.ts | 2 +- .../lib/views/discover/DatapackInstall.svelte | 194 ++++++++++++++++++ ui/src/lib/views/discover/Discover.svelte | 33 ++- ui/src/lib/views/discover/ProjectPage.svelte | 3 +- ui/src/lib/views/discover/WorldPicker.svelte | 88 ++++++++ ui/src/lib/views/discover/discover.ts | 19 +- .../discover/project/DescriptionTab.svelte | 13 ++ .../discover/project/ProjectAside.svelte | 7 +- .../views/instance-page/WorldDatapacks.svelte | 125 +---------- 22 files changed, 473 insertions(+), 221 deletions(-) create mode 100644 ui/src/lib/views/discover/DatapackInstall.svelte create mode 100644 ui/src/lib/views/discover/WorldPicker.svelte 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 index 97058cd..1551657 100644 --- a/crates/cubby-modrinth/src/datapacks.rs +++ b/crates/cubby-modrinth/src/datapacks.rs @@ -1,53 +1,24 @@ //! Datapacks: they go into a world (`saves//datapacks`), not into the instance, so they have their -//! own search and download instead of the install plans of mods and packs. +//! own download instead of the install plans of mods and packs. Discover searches them like other projects. use cubby_common::{Error, Result}; -use crate::browse::hit_from_search; use crate::client::Modrinth; -use crate::model::{FileInfo, SearchResults}; - -/// Search facets for datapacks made for `game_version` (any version when empty). -pub fn datapack_facets(game_version: &str) -> Vec> { - let mut facets = vec![vec!["project_type:datapack".to_string()]]; - let version = game_version.trim(); - if !version.is_empty() { - facets.push(vec![format!("versions:{version}")]); - } - facets -} +use crate::model::FileInfo; impl Modrinth { - /// Datapacks for a game version: by relevance with a query, else the most downloaded. 20 per page. - pub async fn search_datapacks(&self, query: &str, game_version: &str, offset: u32) -> Result { - let facets = serde_json::to_string(&datapack_facets(game_version)).map_err(|e| Error::Other(e.to_string()))?; - let text = query.trim(); - let mut params = vec![ - ("facets", facets), - ("index", if text.is_empty() { "downloads" } else { "relevance" }.to_string()), - ("offset", offset.to_string()), - ("limit", "20".to_string()), - ]; - if !text.is_empty() { - params.insert(0, ("query", text.to_string())); - } - let response = self.search_raw(¶ms).await?; - Ok(SearchResults { - hits: response.hits.into_iter().map(hit_from_search).collect(), - total: response.total_hits, - offset: response.offset, - limit: response.limit, - }) - } - - /// The `.zip` of the newest datapack version of a project for `game_version`. - pub async fn datapack_file(&self, id_or_slug: &str, game_version: &str) -> Result { - let versions = self.project_versions_raw(id_or_slug, &["datapack".to_string()], &[game_version.to_string()]).await?; - let newest = versions - .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}")))?; + /// 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() @@ -63,14 +34,3 @@ impl Modrinth { }) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn facets_for_a_version() { - assert_eq!(datapack_facets("1.21.1"), vec![vec!["project_type:datapack".to_string()], vec!["versions:1.21.1".to_string()]]); - assert_eq!(datapack_facets(" "), vec![vec!["project_type:datapack".to_string()]]); - } -} diff --git a/crates/cubby-modrinth/src/lib.rs b/crates/cubby-modrinth/src/lib.rs index 163a19f..5e09cc9 100644 --- a/crates/cubby-modrinth/src/lib.rs +++ b/crates/cubby-modrinth/src/lib.rs @@ -13,7 +13,6 @@ pub mod mrpack; mod resolve; pub use browse::{facets, search_params}; -pub use datapacks::datapack_facets; pub use export::{pack_dependencies, ExportSpec, ExportSummary}; pub use client::{Modrinth, API_BASE, USER_AGENT}; pub use model::*; 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/src-tauri/src/commands/datapacks.rs b/src-tauri/src/commands/datapacks.rs index 44e79fa..61b96f1 100644 --- a/src-tauri/src/commands/datapacks.rs +++ b/src-tauri/src/commands/datapacks.rs @@ -66,24 +66,8 @@ pub async fn add_datapack_files( blocking(move || cubby_instance::import_datapacks(&dir, &world, &paths).msg()).await } -/// Modrinth datapacks made for the instance's Minecraft version. -#[tauri::command] -pub async fn search_datapacks( - core: State<'_, Core>, - id: String, - query: String, - offset: u32, -) -> CmdResult { - let inst = core.store.get(&id).msg()?; - Ok(core - .modrinth - .search_datapacks(&query, &inst.minecraft, offset) - .await - .msg()? - .into()) -} - -/// Downloads the newest version of a Modrinth datapack for the instance's Minecraft version into the world. +/// 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( @@ -91,12 +75,13 @@ pub async fn install_datapack( 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(), &inst.minecraft) + .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()?; diff --git a/src-tauri/src/dto.rs b/src-tauri/src/dto.rs index 9f09a30..b7d0e3c 100644 --- a/src-tauri/src/dto.rs +++ b/src-tauri/src/dto.rs @@ -539,6 +539,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 e2b0aa6..6e6a434 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -139,7 +139,6 @@ pub fn run() { commands::datapacks::set_datapack_enabled, commands::datapacks::remove_datapack, commands::datapacks::add_datapack_files, - commands::datapacks::search_datapacks, commands::datapacks::install_datapack, commands::datapacks::render_world_map, ]) diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 23d8d7f..8be5dc0 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -227,10 +227,8 @@ export const api = { 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 }), - /** Modrinth datapacks for the instance's Minecraft version, 20 per page. */ - searchDatapacks: (id: string, query: string, offset: number) => call('search_datapacks', { id, query, offset }), - /** Downloads the newest version for the instance's Minecraft version into the world; returns its file name. */ - installDatapack: (id: string, world: string, projectId: string) => call('install_datapack', { id, world, projectId }), + /** 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 }), diff --git a/ui/src/lib/dev/mock.ts b/ui/src/lib/dev/mock.ts index 59fa78d..d3fe8db 100644 --- a/ui/src/lib/dev/mock.ts +++ b/ui/src/lib/dev/mock.ts @@ -3,7 +3,7 @@ // that appear as installed. Add `?onboarding` to the URL to see the first-launch assistant. import { pixelArt, svgUrl } from './pixelart' -import { handleExtra, NOT_HANDLED } from './mockExtra' +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, @@ -544,6 +544,8 @@ function packSummary(provider: ProviderId, d: MockPackDef): PackSummary { const capeState = { active: 'cape-migrator' as string | null } export async function handle(command: string, args: Record): Promise { + const datapack = handleDatapackProject(command, args) + if (datapack !== NOT_HANDLED) return datapack await sleep(60) switch (command) { case 'app_info': diff --git a/ui/src/lib/dev/mockExtra.ts b/ui/src/lib/dev/mockExtra.ts index f2490cb..cf58c53 100644 --- a/ui/src/lib/dev/mockExtra.ts +++ b/ui/src/lib/dev/mockExtra.ts @@ -1,6 +1,6 @@ // 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, ProjectHit, UpdateBackup } from '../types' +import type { Datapack, Project, ProjectHit, ProjectVersion, UpdateBackup } from '../types' export const NOT_HANDLED = Symbol('not handled') @@ -24,7 +24,6 @@ const DATAPACK_HITS: ProjectHit[] = [ ].map(([slug, title, author, summary, downloads]) => ({ id: `dp-${slug}`, slug: slug as string, - kind: 'mod', title: title as string, author: author as string, summary: summary as string, @@ -36,10 +35,46 @@ const DATAPACK_HITS: ProjectHit[] = [ 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', @@ -68,12 +103,6 @@ export async function handleExtra(command: string, args: Record): P } case 'add_datapack_files': return [] - case 'search_datapacks': { - await sleep(300) - const q = String(args.query ?? '').trim().toLowerCase() - const hits = DATAPACK_HITS.filter((h) => !q || `${h.title} ${h.summary}`.toLowerCase().includes(q)) - return { hits, total: hits.length, offset: 0, limit: 20 } - } case 'install_datapack': { await sleep(800) const hit = DATAPACK_HITS.find((h) => h.id === args.projectId) diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index e37993b..8c02efd 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -156,4 +156,29 @@ export const FR_10: Record = { '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.', } diff --git a/ui/src/lib/state.svelte.ts b/ui/src/lib/state.svelte.ts index 61ac90c..cb4764a 100644 --- a/ui/src/lib/state.svelte.ts +++ b/ui/src/lib/state.svelte.ts @@ -222,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) diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 021dd1b..6f2dd54 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -251,7 +251,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' diff --git a/ui/src/lib/views/discover/DatapackInstall.svelte b/ui/src/lib/views/discover/DatapackInstall.svelte new file mode 100644 index 0000000..509ce0b --- /dev/null +++ b/ui/src/lib/views/discover/DatapackInstall.svelte @@ -0,0 +1,194 @@ + + + +
+ {#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/ProjectPage.svelte b/ui/src/lib/views/discover/ProjectPage.svelte index fd80bca..77ecbae 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) 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..f001b4b 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,7 +31,11 @@ }) - +{#if kind === 'datapack'} + +{:else} + +{/if} {#if links.length}
diff --git a/ui/src/lib/views/instance-page/WorldDatapacks.svelte b/ui/src/lib/views/instance-page/WorldDatapacks.svelte index 59a8441..bcd5e89 100644 --- a/ui/src/lib/views/instance-page/WorldDatapacks.svelte +++ b/ui/src/lib/views/instance-page/WorldDatapacks.svelte @@ -1,13 +1,12 @@ - +
@@ -139,7 +88,7 @@ {/if}
- +
{#if running} @@ -147,46 +96,6 @@ {/if}
-{#if finding} - {#snippet findActions()} - - {/snippet} - (finding = false)} actions={findActions}> -
- - {#if hits === null} -

{t('Searching Modrinth…')}

- {:else if searchError} -

{searchError}

- {:else if !hits.length} -

{t('No datapacks for Minecraft {minecraft} match.', { minecraft: instance.minecraft })}

- {:else} -
    - {#each hits as h (h.id)} -
  • - {#if h.iconUrl} - - {:else} - - {/if} -
    - {h.title} - {h.summary} - {t('{author} · {downloads} downloads', { author: h.author, downloads: compactNum(h.downloads) })} -
    - {#if installed.includes(h.id)} - - {:else} - - {/if} -
  • - {/each} -
- {/if} -
-
-{/if} - From 7d8c3b0880e843c2d20f745a8f2460a2600b7883 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:18:40 +0100 Subject: [PATCH 18/31] Side panels: one shared layout, starting with the Mods panel Inspector components and styles (eyebrow, head with one status line, actions in two equal columns, sections, details, notices, the destructive action at the bottom). The old global rules that pushed side panel buttons to the right are gone. Co-Authored-By: Claude Opus 5.5 --- ui/src/app.css | 24 --- ui/src/lib/cubby/Inspector.svelte | 20 ++ ui/src/lib/cubby/InspectorHead.svelte | 42 +++++ ui/src/lib/cubby/InspectorNotice.svelte | 16 ++ ui/src/lib/cubby/InspectorPath.svelte | 12 ++ ui/src/lib/cubby/InspectorSection.svelte | 15 ++ ui/src/lib/cubby/InspectorStatus.svelte | 8 + ui/src/lib/cubby/index.ts | 7 + .../views/instance-page/InstancePage.svelte | 6 +- ui/src/lib/views/instance-page/ModsTab.svelte | 174 ++++++------------ ui/src/main.ts | 1 + ui/src/styles/inspector.css | 98 ++++++++++ 12 files changed, 273 insertions(+), 150 deletions(-) create mode 100644 ui/src/lib/cubby/Inspector.svelte create mode 100644 ui/src/lib/cubby/InspectorHead.svelte create mode 100644 ui/src/lib/cubby/InspectorNotice.svelte create mode 100644 ui/src/lib/cubby/InspectorPath.svelte create mode 100644 ui/src/lib/cubby/InspectorSection.svelte create mode 100644 ui/src/lib/cubby/InspectorStatus.svelte create mode 100644 ui/src/styles/inspector.css diff --git a/ui/src/app.css b/ui/src/app.css index c0c61e5..1803ded 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -49,27 +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; -} -/* Two buttons share the row equally; when their labels don't fit side by side, each takes a full row - (a grid of two halves made long labels stick out of the panel). */ -aside :where(div, span, p):has(> .cb-btn:first-child:nth-last-child(2)):not(:has(> :not(.cb-btn))) { - display: flex; - flex-wrap: wrap; - 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 { - flex: 1 1 0; - min-width: max-content; - justify-content: center; - white-space: nowrap; -} -aside > :is(.cb-btn, .cb-iconbtn):not(.wide) { - align-self: flex-end; -} 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/index.ts b/ui/src/lib/cubby/index.ts index 703e5d0..93493a9 100644 --- a/ui/src/lib/cubby/index.ts +++ b/ui/src/lib/cubby/index.ts @@ -36,6 +36,13 @@ export { default as LogViewer } from './LogViewer.svelte'; 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/views/instance-page/InstancePage.svelte b/ui/src/lib/views/instance-page/InstancePage.svelte index 9f27539..c0d2bf5 100644 --- a/ui/src/lib/views/instance-page/InstancePage.svelte +++ b/ui/src/lib/views/instance-page/InstancePage.svelte @@ -610,14 +610,10 @@ background: var(--bg-chrome); border-inline-start: var(--border-chrome) solid var(--edge); } + /* The panel's content is an Inspector (src/styles/inspector.css): this only makes it scroll on its own. */ .layout > :global(.ip-aside) > :global(.ip-aside__inner) { - box-sizing: border-box; - display: flex; - flex-direction: column; - gap: var(--space-4); height: 100%; overflow-y: auto; - padding: var(--space-6) var(--space-5); } @media (max-width: 1099px) { .page { diff --git a/ui/src/lib/views/instance-page/ModsTab.svelte b/ui/src/lib/views/instance-page/ModsTab.svelte index b31a78c..64a57db 100644 --- a/ui/src/lib/views/instance-page/ModsTab.svelte +++ b/ui/src/lib/views/instance-page/ModsTab.svelte @@ -9,7 +9,7 @@ import { t } from '../../i18n.svelte' import { tick, untrack } from 'svelte' import { api } from '../../api' - import { Banner, Button, Dialog, Icon, InstanceIcon, MetaChip, ModRow, ProgressBar, SegmentedControl, StatusTag, TextField } from '../../cubby' + import { Banner, Button, Dialog, Icon, Inspector, InspectorHead, InspectorNotice, InspectorPath, InspectorSection, InspectorStatus, InstanceIcon, MetaChip, ModRow, ProgressBar, SegmentedControl, TextField } from '../../cubby' import { bytes, fold, num, plural, relativeTime } from '../../format' import { projectArt } from '../../icon' import { app } from '../../state.svelte' @@ -312,73 +312,48 @@
{#if removing} @@ -500,8 +493,6 @@ flex: 1; } p, - h2, - h3, dl, dd { margin: 0; @@ -509,12 +500,6 @@ .muted { color: var(--ink-muted); } - .warn { - color: var(--gold-text); - } - .wrap { - overflow-wrap: anywhere; - } .list { background: var(--surface); @@ -570,57 +555,4 @@ .empty :global(.cb-btn) { margin-top: var(--space-2); } - - .who { - display: flex; - align-items: center; - gap: var(--space-4); - } - .who__text { - min-width: 0; - display: flex; - flex-direction: column; - gap: 2px; - } - .who__text h2 { - overflow-wrap: anywhere; - outline: none; - } - .chips, - .actions { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-2); - } - .part { - display: flex; - flex-direction: column; - gap: 6px; - } - .facts { - display: grid; - grid-template-columns: auto minmax(0, 1fr); - 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; - } - .flag { - display: flex; - align-items: flex-start; - gap: var(--space-2); - } - .changes { - display: flex; - flex-direction: column; - gap: var(--space-1); - margin: 0; - padding-inline-start: 20px; - list-style: square; - overflow-wrap: anywhere; - } diff --git a/ui/src/main.ts b/ui/src/main.ts index 7abf0bb..6162fbd 100644 --- a/ui/src/main.ts +++ b/ui/src/main.ts @@ -2,6 +2,7 @@ import { mount } from 'svelte' import './styles/fonts.css' import './styles/tokens.css' import './styles/cubby.css' +import './styles/inspector.css' import './app.css' import App from './App.svelte' diff --git a/ui/src/styles/inspector.css b/ui/src/styles/inspector.css new file mode 100644 index 0000000..cfda081 --- /dev/null +++ b/ui/src/styles/inspector.css @@ -0,0 +1,98 @@ +/* The inspector: the one side panel layout every screen uses (see lib/cubby/Inspector*.svelte). + Order, top to bottom: eyebrow, head (media, title, one line of subtitle), one status line, actions (one primary, + secondary ones in two equal columns), sections (title, count, small action), details, and the footer with the + destructive action. Everything lines up on the left and nothing wraps out of the panel. */ + +.cb-ins { + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: var(--space-6); + min-height: 100%; + padding: var(--space-6) var(--space-5); +} + +/* Head */ +.cb-ins-head { display: flex; flex-direction: column; gap: var(--space-3); min-width: 0; } +.cb-ins-eyebrow { margin: 0; font-family: var(--font-caps); font-size: 12px; line-height: 16px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-muted); } +.cb-ins-who { display: flex; gap: 14px; align-items: center; min-width: 0; } +.cb-ins-who__text { min-width: 0; display: flex; flex-direction: column; gap: 2px; } +.cb-ins-title { margin: 0; font-family: var(--font-sans); font-size: 18px; line-height: 24px; font-weight: 600; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; outline: none; } +.cb-ins-title--big { font-size: 22px; line-height: 28px; } +.cb-ins-title--empty { color: var(--ink-muted); } +.cb-ins-sub { margin: 0; font-size: 13px; line-height: 18px; color: var(--ink-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.cb-ins-sub--mono { font-family: var(--font-mono); font-size: 12px; } + +/* Media: 56 px next to the title, or full width above it */ +.cb-ins-media { box-sizing: border-box; width: 56px; height: 56px; flex: none; display: grid; place-items: center; overflow: hidden; border: var(--border-block) solid var(--edge); box-shadow: var(--shadow-block-sm); background: var(--surface); color: var(--ink-muted); image-rendering: pixelated; } +.cb-ins-media > img { width: 100%; height: 100%; object-fit: cover; display: block; } +.cb-ins-media--big { width: 96px; height: 96px; } +.cb-ins-media--wide { width: 100%; height: auto; aspect-ratio: 16 / 9; } +.cb-ins-media--empty { background: transparent; border-style: dashed; border-color: var(--line); box-shadow: none; } +button.cb-ins-media { padding: 0; cursor: zoom-in; } +button.cb-ins-media:focus-visible { box-shadow: var(--focus-ring); } + +/* Status line: one line, never wraps */ +.cb-ins-meta { display: flex; gap: var(--space-3); align-items: center; flex-wrap: nowrap; white-space: nowrap; overflow: hidden; min-height: 24px; } +.cb-ins-meta > * { flex: none; } +.cb-ins-meta .cb-chip { max-width: 160px; overflow: hidden; text-overflow: ellipsis; } +.cb-ins-st { display: inline-flex; gap: 6px; align-items: center; font-size: 13px; line-height: 18px; font-weight: 500; flex: none; } +.cb-ins-st::before { content: ''; width: 8px; height: 8px; background: currentColor; flex: none; } +.cb-ins-st--ok { color: var(--grass-text); } +.cb-ins-st--update { color: var(--diamond-text); } +.cb-ins-st--off { color: var(--ink-muted); } +.cb-ins-st--warn { color: var(--gold-text); } +.cb-ins-st--bad { color: var(--redstone-text); } + +/* Actions: one primary on its own row, the others in two equal columns */ +.cb-ins-acts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-2); } +.cb-ins-acts > .cb-btn, .cb-ins-acts > .cb-play { width: 100%; min-width: 0; justify-content: center; } +.cb-ins-acts > .cb-btn .cb-btn__label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cb-ins-acts > .wide, .cb-ins-acts > .cb-play, .cb-ins-acts > :only-child { grid-column: 1 / -1; } + +/* Sections */ +.cb-ins-sec { display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.cb-ins-sec__h { display: flex; align-items: center; gap: var(--space-2); min-height: 28px; } +.cb-ins-sec__h > .cb-ins-eyebrow { flex: 1; min-width: 0; } +.cb-ins-sec__n { color: var(--ink-muted); font-weight: 400; letter-spacing: 0; } +.cb-ins-sec__h > .cb-btn { flex: none; } +.cb-ins-text { margin: 0; font-size: 14px; line-height: 21px; } +.cb-ins-hint { margin: 0; font-size: 13px; line-height: 19px; color: var(--ink-muted); } +.cb-ins-list { margin: 0; padding-left: 18px; font-size: 13px; line-height: 19px; display: flex; flex-direction: column; gap: var(--space-1); list-style: square; overflow-wrap: anywhere; } + +/* Details */ +.cb-ins-facts { margin: 0; display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: var(--space-2) var(--space-3); font-size: 14px; line-height: 20px; } +.cb-ins-facts > dt { color: var(--ink-muted); font-size: 13px; } +.cb-ins-facts > dd { margin: 0; min-width: 0; display: flex; gap: 6px; align-items: center; overflow: hidden; } +.cb-ins-facts > dd > span:not(.cb-chip) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cb-ins-path { grid-column: 1 / -1; display: flex; gap: var(--space-2); align-items: center; min-width: 0; background: var(--field); border: var(--border-hair) solid var(--line); padding: 4px 4px 4px 10px; font-family: var(--font-mono); font-size: 12px; line-height: 18px; } +.cb-ins-path > span { flex: 1; min-width: 0; overflow-wrap: anywhere; -webkit-user-select: text; user-select: text; } + +/* Rows: datapacks, backups, checks, folders, optional mods... */ +.cb-ins-rows { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; border-top: var(--border-hair) solid var(--line); } +.cb-ins-row { display: flex; gap: 10px; align-items: center; padding: var(--space-2) 0; border-bottom: var(--border-hair) solid var(--line); min-width: 0; } +.cb-ins-row__ic { box-sizing: border-box; width: 32px; height: 32px; flex: none; display: grid; place-items: center; overflow: hidden; border: var(--border-block) solid var(--edge); background: var(--surface); color: var(--ink-muted); } +.cb-ins-row__ic > img { width: 100%; height: 100%; object-fit: cover; image-rendering: pixelated; } +.cb-ins-row__txt { flex: 1; min-width: 0; display: flex; flex-direction: column; } +.cb-ins-row__t { font-size: 14px; line-height: 20px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.cb-ins-row__s { font-size: 12px; line-height: 17px; color: var(--ink-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.cb-ins-row--off .cb-ins-row__t { color: var(--ink-muted); } +.cb-ins-row > .cb-btn, .cb-ins-row > .cb-iconbtn { flex: none; } + +/* Notice */ +.cb-ins-notice { display: flex; gap: 10px; padding: 10px var(--space-3); border: var(--border-block) solid var(--gold); background: color-mix(in srgb, var(--gold) 9%, transparent); font-size: 13px; line-height: 19px; } +.cb-ins-notice--info { border-color: var(--diamond); background: color-mix(in srgb, var(--diamond) 8%, transparent); } +.cb-ins-notice--bad { border-color: var(--redstone-text); background: color-mix(in srgb, var(--redstone) 10%, transparent); } +.cb-ins-notice__icon { flex: none; margin-top: 1px; color: var(--gold-text); } +.cb-ins-notice--info .cb-ins-notice__icon { color: var(--diamond-text); } +.cb-ins-notice--bad .cb-ins-notice__icon { color: var(--redstone-text); } +.cb-ins-notice__body { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; min-width: 0; overflow-wrap: anywhere; } +.cb-ins-notice__body strong { font-weight: 500; } + +/* Footer: the destructive action, always last */ +.cb-ins-foot { margin-top: auto; padding-top: var(--space-4); border-top: var(--border-hair) solid var(--line); display: flex; align-items: center; gap: var(--space-3); } +.cb-ins-foot > .cb-btn { flex: none; } +.cb-ins-foot > .cb-ins-hint { flex: 1; font-size: 12px; line-height: 17px; } + +/* Loading */ +.cb-ins-skel { display: block; height: 12px; background: var(--surface); } From bd8fc9b4b712039f127882dc140eda9100105894 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:19:57 +0100 Subject: [PATCH 19/31] Resource pack and shader pack panels in the shared side panel layout Co-Authored-By: Claude Opus 5.5 --- .../instance-page/ResourcePacksTab.svelte | 118 ++++++++---------- .../lib/views/instance-page/ShadersTab.svelte | 116 +++++++---------- 2 files changed, 101 insertions(+), 133 deletions(-) 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/ShadersTab.svelte b/ui/src/lib/views/instance-page/ShadersTab.svelte index 3a2ccb1..e634da4 100644 --- a/ui/src/lib/views/instance-page/ShadersTab.svelte +++ b/ui/src/lib/views/instance-page/ShadersTab.svelte @@ -1,7 +1,7 @@ -
-

{t('Datapacks · {length}', { length: packs?.length ?? 0 })}

+{#snippet packActions()} + + +{/snippet} + {#if packs === null} -

{t('Reading datapacks…')}

+

{t('Reading datapacks…')}

{:else if !packs.length} -

{t('No datapacks in this world. They add structures, biomes or rules to one world, without mods.')}

+

{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))} +
    • +
      + {p.name} + {p.description ?? (p.isDir ? t('Folder') : bytes(p.size))}
      toggle(p, on)} /> remove(p)} /> @@ -87,18 +90,10 @@ {/each}
    {/if} -
    - - -
    - {#if running} -

    {t('Close the game to change datapacks. They load when the world opens.')}

    - {/if} -
+ diff --git a/ui/src/lib/views/instance-page/WorldMap.svelte b/ui/src/lib/views/instance-page/WorldMap.svelte index 2df4696..c1b8ac2 100644 --- a/ui/src/lib/views/instance-page/WorldMap.svelte +++ b/ui/src/lib/views/instance-page/WorldMap.svelte @@ -2,7 +2,7 @@ -
-

{t('Map')}

+{#snippet drawAction()} + +{/snippet} + {#if map} -

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

+

{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]}

+

{failed[key]}

{:else} -

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

+

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

{/if} -
- -
-
+ {#if big && map} (big = false)}> @@ -60,18 +59,12 @@ {/if} From 4c7b45927f0ff19511ee5e84d2458998fe5e34f9 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:26:28 +0100 Subject: [PATCH 21/31] Account, screenshot, server, storage, running game and crash panels in the shared layout Co-Authored-By: Claude Opus 5.5 --- ui/src/lib/views/accounts/Accounts.svelte | 109 ++------ ui/src/lib/views/captures/Screenshots.svelte | 152 +++-------- ui/src/lib/views/downloads/Downloads.svelte | 133 +++++----- ui/src/lib/views/play/CrashAside.svelte | 156 ++++------- ui/src/lib/views/play/Running.svelte | 203 ++++---------- ui/src/lib/views/servers/Servers.svelte | 265 +++++-------------- 6 files changed, 305 insertions(+), 713 deletions(-) diff --git a/ui/src/lib/views/accounts/Accounts.svelte b/ui/src/lib/views/accounts/Accounts.svelte index da2015e..7de3d91 100644 --- a/ui/src/lib/views/accounts/Accounts.svelte +++ b/ui/src/lib/views/accounts/Accounts.svelte @@ -110,7 +110,7 @@ diff --git a/ui/src/lib/views/play/Running.svelte b/ui/src/lib/views/play/Running.svelte index 6ab66b8..60e2483 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, PlayButton, SegmentedControl, StatusTag, TextField, type SegmentedOption } 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 @@ {/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,8 @@ 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/servers/Servers.svelte b/ui/src/lib/views/servers/Servers.svelte index f597686..1495bbd 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, PlayButton, ServerRow, StatusTag, TextField } from '../../cubby' import { num } from '../../format' import { iconOf } from '../../icon' import { app } from '../../state.svelte' @@ -375,121 +375,90 @@ @@ -677,54 +646,12 @@ 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); @@ -734,52 +661,4 @@ 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); - } From 8f582f7d71ddc8c37e60de8576852e6643207b47 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:29:15 +0100 Subject: [PATCH 22/31] Install, modpack, new instance and skin panels follow the side panel model; French text Same spacing, section titles, details and action grid as the other side panels. Co-Authored-By: Claude Opus 5.5 --- ui/src/lib/i18n/fr-10.ts | 65 ++++++++++++ ui/src/lib/views/accounts/Accounts.svelte | 4 +- ui/src/lib/views/create/CustomForm.svelte | 98 +++++-------------- ui/src/lib/views/create/PackPage.svelte | 18 +--- ui/src/lib/views/discover/InstallPanel.svelte | 11 +-- ui/src/lib/views/discover/ProjectPage.svelte | 2 +- .../discover/project/ProjectAside.svelte | 11 +-- ui/src/lib/views/skins/Skins.svelte | 58 +++++------ 8 files changed, 132 insertions(+), 135 deletions(-) diff --git a/ui/src/lib/i18n/fr-10.ts b/ui/src/lib/i18n/fr-10.ts index 8c02efd..6d8a37c 100644 --- a/ui/src/lib/i18n/fr-10.ts +++ b/ui/src/lib/i18n/fr-10.ts @@ -181,4 +181,69 @@ export const FR_10: Record = { '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/views/accounts/Accounts.svelte b/ui/src/lib/views/accounts/Accounts.svelte index 7de3d91..72c72c8 100644 --- a/ui/src/lib/views/accounts/Accounts.svelte +++ b/ui/src/lib/views/accounts/Accounts.svelte @@ -335,11 +335,11 @@ {#if !selected.isDefault}{/if} - +
-
UUID
{t('Your player ID on every server')}
selected && copyUuid(selected.id)} />
+

{t('Your player ID on every server')}.

{t('Sign-in tokens are stored in plain text in')} accounts.json{t(', in Cubby’s data folder on this PC. Signing out deletes them. Cubby never sees your password.')} diff --git a/ui/src/lib/views/create/CustomForm.svelte b/ui/src/lib/views/create/CustomForm.svelte index 1c65042..cfe4ee6 100644 --- a/ui/src/lib/views/create/CustomForm.svelte +++ b/ui/src/lib/views/create/CustomForm.svelte @@ -332,53 +332,50 @@ @@ -574,8 +571,6 @@ margin: 0; color: var(--gold-text); } - - .aside { box-sizing: border-box; flex: 0 0 var(--size-inspector); @@ -584,50 +579,9 @@ overflow: auto; display: flex; flex-direction: column; - gap: var(--space-4); + gap: var(--space-6); padding: var(--space-6) var(--space-5); background: var(--bg-chrome); border-inline-start: var(--border-chrome) solid var(--edge); } - .dl { - display: flex; - flex-direction: column; - margin: 0; - padding: 0; - list-style: none; - background: var(--surface); - border: var(--border-block) solid var(--edge); - box-shadow: var(--shadow-block-sm); - } - .dl li { - display: grid; - grid-template-columns: 18px minmax(0, 1fr); - gap: 10px; - align-items: start; - padding: var(--space-2) var(--space-3); - border-bottom: var(--border-hair) solid var(--line); - } - .dl .dl__foot { - align-items: center; - padding: 10px var(--space-3); - background: var(--bg); - border-bottom: 0; - } - .dl__icon { - display: inline-flex; - padding-top: 1px; - color: var(--ink-muted); - } - .go { - display: flex; - flex-direction: column; - gap: var(--space-2); - margin-top: auto; - } - .go :global(.cb-btn) { - width: 100%; - } - .go p { - margin: var(--space-1) 0 0; - } diff --git a/ui/src/lib/views/create/PackPage.svelte b/ui/src/lib/views/create/PackPage.svelte index 4daa3a9..f1b850f 100644 --- a/ui/src/lib/views/create/PackPage.svelte +++ b/ui/src/lib/views/create/PackPage.svelte @@ -284,7 +284,7 @@