diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 1e9fb7722..e233cc9a9 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -50,6 +50,7 @@ Start the client. horizon-launcher play +- `--instance`: The instance to play (its name or id; default: the selected one) - `--world`: Open or create this world (a folder under saves) at once - `--creative`: Creative mode for a new world - `--join`: Join a friend's world with its invite code @@ -257,6 +258,68 @@ Upload a benchmark report (docs/benchmark-report.md); it is printed first. MCP: `data_benchmark`, only when the player asks. +## `horizon-launcher instance list` + +The instances, each with its game folder (* = the one Play starts). + + horizon-launcher instance list + +MCP: `instance_list`. + +## `horizon-launcher instance create` + +Make an instance: empty but for your options and name, or a copy of another one's worlds, options and packs. + + horizon-launcher instance create + +- `NAME` +- `--copy`: The instance to copy (its name or id) + +MCP: `instance_create`. + +## `horizon-launcher instance rename` + +Rename an instance (its folder stays). + + horizon-launcher instance rename + +- `INSTANCE` +- `NAME` + +MCP: `instance_rename`. + +## `horizon-launcher instance icon` + +Set an instance's icon: a block or item name from your prepared files (grass_block), a colour (#3fa7d6), or none. + + horizon-launcher instance icon + +- `INSTANCE` +- `ICON` + +MCP: `instance_icon`. + +## `horizon-launcher instance group` + +Put an instance in a sidebar group, or take it out with no group. + + horizon-launcher instance group [GROUP] + +- `INSTANCE` +- `GROUP` + +MCP: `instance_group`. + +## `horizon-launcher instance select` + +Make Play start this instance. + + horizon-launcher instance select + +- `INSTANCE` + +MCP: `instance_select`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). diff --git a/launcher/README.md b/launcher/README.md index 9c6f3a9d9..89df726d1 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -69,6 +69,14 @@ The opening, then Play ([clip](docs/opening.webm)): access controls, one click changes them so friends you share with reach only the server's port (Remove the limit undoes it); custom access controls are never rewritten, the page gives the rule to add instead. Horizon never turns on Funnel. +- **Instances**: separate game folders, each with its own worlds, options and packs. The game's + folder stays the first one, "Horizon", exactly where it was; imported and registry modpacks are + instances too, in their own folders as before; new ones go to `instances//` in the game's + folder, empty but for the player's options and name, or a copy of another instance (never its + sign-in sessions, logs or data collection state). Names, icons (a block or item texture from the + player's prepared files, or a colour) and groups are kept in `instances.json` in the launcher's + data folder, so renaming moves nothing. Every instance follows the launcher's data collection + answer and No AI. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, @@ -152,7 +160,7 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code horizon-launcher install horizon-launcher remove horizon-launcher prepare [--minecraft ] [--version ] - horizon-launcher play [--version ] [--arg ]... start the client; --arg passes an extra argument through (repeatable) + horizon-launcher play [--version ] [--instance ] [--arg ]... start the client; --arg passes an extra argument through (repeatable) horizon-launcher server [--dir ] [--version ] [--accept-eula] horizon-launcher notes [] patch notes as plain text horizon-launcher links the Discord, sponsor and website links @@ -164,6 +172,10 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code horizon-launcher account sign-out horizon-launcher account select play as this account horizon-launcher account offline play without an account + horizon-launcher instance [list] the instances and their game folders (* = Play starts it) + horizon-launcher instance create [--copy ] empty, or a copy of one's worlds, options and packs + horizon-launcher instance rename|icon|group icon: a block or item name, #rrggbb or none + horizon-launcher instance select make Play start it horizon-launcher modpack [list] the imported packs and their coverage horizon-launcher modpack import a .mrpack, CurseForge zip or instance folder horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 55a78193a..dbd54aeee 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1585,9 +1585,10 @@ pub fn newest_crash_report() -> Option { crash_reports_in(&crash_reports_dir()).pop() } -/// The newest crash report written at or after `since` (one from the run that started then). -pub fn crash_report_since(since: std::time::SystemTime) -> Option { - crash_report_in_since(&crash_reports_dir(), since) +/// The newest crash report the game playing in `home` wrote at or after `since` (one from the +/// run that started then). +pub fn crash_report_since(home: &Path, since: std::time::SystemTime) -> Option { + crash_report_in_since(&home.join("crash-reports"), since) } fn crash_report_in_since(dir: &Path, since: std::time::SystemTime) -> Option { @@ -2517,6 +2518,9 @@ pub enum Appearance { #[derive(Default, serde::Serialize, serde::Deserialize)] pub struct Settings { pub selected: Option, + /// The instance Play starts (`instances`), by id. Unset means Horizon, the game's home. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instance: Option, pub minecraft_dir: Option, pub server_dir: Option, /// Unset means on: only a player who turned it off has `false` here. 0.1.1 wrote its diff --git a/launcher/src/browser/horizon/pack.rs b/launcher/src/browser/horizon/pack.rs index 95235a505..2b8e2db9e 100644 --- a/launcher/src/browser/horizon/pack.rs +++ b/launcher/src/browser/horizon/pack.rs @@ -37,7 +37,7 @@ pub fn list() -> Vec { list_in(&packs_dir()) } -fn list_in(dir: &Path) -> Vec { +pub(crate) fn list_in(dir: &Path) -> Vec { let mut packs: Vec = fs::read_dir(dir) .into_iter() .flatten() diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 7d6ff7514..22a850c02 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -3,6 +3,7 @@ use clap::{Parser, Subcommand}; use horizon_launcher::account::{self, Accounts}; use horizon_launcher::backend::{self, Release}; +use horizon_launcher::instances; use std::io::{IsTerminal, Write}; use std::path::PathBuf; use std::process::Command; @@ -155,6 +156,32 @@ enum ModpackCmd { Remove { pack: String }, } +#[derive(Subcommand)] +enum InstanceCmd { + /// The instances, each with its game folder (* = the one Play starts) + List, + /// Make an instance: empty but for your options and name, or a copy of another one's + /// worlds, options and packs + Create { + name: String, + /// The instance to copy (its name or id) + #[arg(long)] + copy: Option, + }, + /// Rename an instance (its folder stays) + Rename { instance: String, name: String }, + /// Set an instance's icon: a block or item name from your prepared files (grass_block), + /// a colour (#3fa7d6), or none + Icon { instance: String, icon: String }, + /// Put an instance in a sidebar group, or take it out with no group + Group { + instance: String, + group: Option, + }, + /// Make Play start this instance + Select { instance: String }, +} + #[derive(Subcommand)] enum ModsCmd { /// What the browser installed (the default) @@ -261,6 +288,9 @@ enum Cmd { Play { #[arg(long)] version: Option, + /// The instance to play (its name or id; default: the selected one) + #[arg(long)] + instance: Option, /// Open or create this world (a folder under saves) at once #[arg(long)] world: Option, @@ -341,6 +371,11 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// Instances: separate game folders, each with its own worlds, options and packs + Instance { + #[command(subcommand)] + action: Option, + }, /// Modpacks: import a Java pack, see its coverage report, port what this computer can and /// play it as its own profile (docs/modpacks.md) Modpack { @@ -606,12 +641,18 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } Cmd::Play { version, + instance, world, creative, join, arg, } => { let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; + let instance = match instance { + Some(name) => instances::find(&name)?, + None => instances::selected(), + }; + instances::apply(&mut cmd, &instance)?; if let Some(code) = join { backend::join_friend(&mut cmd, &code)?; } @@ -784,6 +825,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("Horizon is in the applications menu."); } } + Cmd::Instance { action } => instance(action.unwrap_or(InstanceCmd::List), as_json)?, Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?, Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?, @@ -1337,6 +1379,61 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { Ok(()) } +fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { + use instances::Icon; + let value = |i: &instances::Instance, selected: bool| { + serde_json::json!({ + "id": i.id, "name": i.name, "kind": format!("{:?}", i.kind).to_lowercase(), + "home": i.home, "icon": i.icon, "group": i.group, "selected": selected, + }) + }; + let line = |i: &instances::Instance, selected: bool| { + let mark = if selected { "*" } else { " " }; + let group = i + .group + .as_ref() + .map(|g| format!(" [{g}]")) + .unwrap_or_default(); + println!( + "{mark} {} ({}){group}\n {}", + i.name, + i.id, + i.home.display() + ); + }; + let changed = |i: instances::Instance| { + let selected = i.id == instances::selected().id; + match as_json { + true => json(value(&i, selected)), + false => line(&i, selected), + } + }; + match action { + InstanceCmd::List => { + let selected = instances::selected().id; + let all = instances::list(); + if as_json { + json(all.iter().map(|i| value(i, i.id == selected)).collect()); + } else { + all.iter().for_each(|i| line(i, i.id == selected)); + } + } + InstanceCmd::Create { name, copy } => changed(instances::create(&name, copy.as_deref())?), + InstanceCmd::Rename { instance, name } => { + changed(instances::edit(&instance, |m| m.name = Some(name))?) + } + InstanceCmd::Icon { instance, icon } => { + let icon = (icon != "none").then(|| Icon::parse(&icon)).transpose()?; + changed(instances::edit(&instance, |m| m.icon = icon)?) + } + InstanceCmd::Group { instance, group } => { + changed(instances::edit(&instance, |m| m.group = group)?) + } + InstanceCmd::Select { instance } => changed(instances::select(&instance)?), + } + Ok(()) +} + fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { use horizon_launcher::browser::horizon; use horizon_launcher::modpacks::{self, Imported}; diff --git a/launcher/src/instances.rs b/launcher/src/instances.rs new file mode 100644 index 000000000..d2e74dde1 --- /dev/null +++ b/launcher/src/instances.rs @@ -0,0 +1,414 @@ +//! Instances: separate game folders, each with its own worlds, options and packs. +//! +//! Nothing that exists moves. The game's home (`backend::game_home`) stays the default instance, +//! "Horizon", with its saves and options where they are. Imported modpacks (`ports//home/`) +//! and registry modpacks (`horizon-packs//home/`) are instances too, played from their own +//! folders as before. New instances get `instances//` in the game's home. What the player +//! chooses about an instance (its name, icon, group) is kept in `instances.json` in the +//! launcher's data folder, so renaming one never moves a folder. +use crate::backend; +use crate::browser::horizon::pack as registry_pack; +use crate::modpacks; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// The default instance's id: the game's home itself. +pub const DEFAULT: &str = "horizon"; +const FILE: &str = "instances.json"; +/// Where new instances live, in the game's home. +const OWN: &str = "instances"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// The game's home: what every player had before instances. + Default, + /// Made in the launcher: `instances//`. + Own, + /// An imported Java modpack (modpacks.rs). + Port, + /// A modpack from Horizon's registry. + Pack, +} + +/// What an instance shows in the sidebar: a block or item texture from the player's prepared +/// files (never shipped), or a colour. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Icon { + /// A texture name: `grass_block` (block/ is looked in first, then item/). + Texture(String), + /// `#rrggbb`. + Colour(String), +} + +impl Icon { + /// `#3fa7d6` is a colour; a texture's name is lowercase letters, digits and `_`. + pub fn parse(text: &str) -> Result { + let text = text.trim(); + if let Some(hex) = text.strip_prefix('#') { + if hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit()) { + return Ok(Icon::Colour(format!("#{}", hex.to_ascii_lowercase()))); + } + } else if !text.is_empty() + && text + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') + { + return Ok(Icon::Texture(text.into())); + } + Err(format!( + "{text}: give a block or item name (grass_block) or a colour (#3fa7d6)" + )) + } + + /// The texture's file in prepared resources, if it is a texture they hold. + pub fn texture(&self, resources: &Path) -> Option { + let Icon::Texture(name) = self else { + return None; + }; + let textures = resources.join("assets/minecraft/textures"); + ["block", "item"] + .iter() + .map(|kind| textures.join(kind).join(format!("{name}.png"))) + .find(|p| p.is_file()) + } +} + +/// The player's choices about one instance. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Meta { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option, +} + +/// `instances.json`: each instance's choices, by id. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +struct Store { + #[serde(default)] + instances: BTreeMap, +} + +impl Store { + fn load(data: &Path) -> Store { + fs::read_to_string(data.join(FILE)) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + fn save(&self, data: &Path) -> Result<(), String> { + fs::create_dir_all(data).map_err(|e| format!("{}: {e}", data.display()))?; + let text = serde_json::to_string_pretty(self).unwrap(); + fs::write(data.join(FILE), text).map_err(|e| format!("{FILE}: {e}")) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Instance { + /// `horizon`, an own instance's folder name, `port:` or `pack:`. + pub id: String, + pub name: String, + pub kind: Kind, + /// The folder the pack's tools work in: the game's home for Default and Own instances. + pub work: PathBuf, + /// The game folder it plays in: saves, options.txt, packs. + pub home: PathBuf, + pub icon: Option, + pub group: Option, +} + +/// The instances, by the default game home and the launcher's data folder: Horizon first, then +/// by group and name. +pub fn list() -> Vec { + list_in(&backend::game_home(), &backend::data_dir()) +} + +fn list_in(game_home: &Path, data: &Path) -> Vec { + let store = Store::load(data); + let mut found = vec![( + DEFAULT.to_string(), + "Horizon".to_string(), + Kind::Default, + game_home.to_path_buf(), + game_home.to_path_buf(), + )]; + let mut own: Vec<_> = fs::read_dir(game_home.join(OWN)) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.path().is_dir()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); + own.sort(); + for slug in own { + let dir = game_home.join(OWN).join(&slug); + found.push((slug.clone(), slug, Kind::Own, dir.clone(), dir)); + } + for p in modpacks::list_in(&game_home.join("ports")) { + let home = modpacks::profile_home(&p.work); + found.push(( + format!("port:{}", p.slug), + p.title().into(), + Kind::Port, + p.work, + home, + )); + } + for p in registry_pack::list_in(&game_home.join("horizon-packs")) { + let home = registry_pack::home(&p.work); + found.push((format!("pack:{}", p.id), p.name, Kind::Pack, p.work, home)); + } + let mut out: Vec = found + .into_iter() + .map(|(id, name, kind, work, home)| { + let meta = store.instances.get(&id).cloned().unwrap_or_default(); + Instance { + name: meta.name.unwrap_or(name), + icon: meta.icon, + group: meta.group, + id, + kind, + work, + home, + } + }) + .collect(); + out[1..].sort_by_key(|i| (i.group.clone(), i.name.to_lowercase())); + out +} + +/// The instance an id, a name (any case) or a pack's folder name names. +pub fn find(query: &str) -> Result { + find_in(&list(), query) +} + +fn find_in(all: &[Instance], query: &str) -> Result { + let q = query.trim(); + let bare = |id: &str| id.split_once(':').map_or(id, |(_, rest)| rest).to_string(); + all.iter() + .find(|i| i.id == q) + .or_else(|| all.iter().find(|i| i.name.eq_ignore_ascii_case(q))) + .or_else(|| all.iter().find(|i| bare(&i.id) == q)) + .cloned() + .ok_or_else(|| format!("No instance {q}: horizon-launcher instance list shows them")) +} + +/// The instance Play starts: the one picked in the launcher, else Horizon. +pub fn selected() -> Instance { + let all = list(); + backend::Settings::load() + .instance + .and_then(|id| all.iter().find(|i| i.id == id).cloned()) + .unwrap_or_else(|| all[0].clone()) +} + +pub fn select(query: &str) -> Result { + let instance = find(query)?; + let mut settings = backend::Settings::load(); + settings.instance = (instance.kind != Kind::Default).then(|| instance.id.clone()); + settings.save(); + Ok(instance) +} + +/// What a copy of a game folder leaves out: other instances and packs, logs and crash reports, +/// caches, data collection's state, and sign-in sessions (a session never leaves its folder). +const NOT_COPIED: &[&str] = &[ + OWN, + "ports", + "horizon-packs", + "logs", + "crash-reports", + "sessions", + "telemetry", + "mod-browser", + ".horizon-cache", +]; + +/// Files of the player, not of one instance, that a new instance starts with: the keys and video +/// settings, and the offline name (so the player stays the same player in its worlds). +const PLAYER_FILES: &[&str] = &["options.txt", "horizon-player.txt"]; + +/// Creates an instance named `name`: empty but for the player's options and offline name, or a +/// copy of `from`'s game folder (its worlds, options and packs). Nothing of `from` changes. +pub fn create(name: &str, from: Option<&str>) -> Result { + let from = from.map(find).transpose()?; + create_in( + &backend::game_home(), + &backend::data_dir(), + name, + from.as_ref(), + ) +} + +fn create_in( + game_home: &Path, + data: &Path, + name: &str, + from: Option<&Instance>, +) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err("An instance needs a name.".into()); + } + let all = list_in(game_home, data); + if all.iter().any(|i| i.name.eq_ignore_ascii_case(name)) { + return Err(format!("There is already an instance called {name}.")); + } + if let Some(from) = from.filter(|f| matches!(f.kind, Kind::Port | Kind::Pack)) { + return Err(format!( + "{} plays its pack's mods: import the pack again for a second copy.", + from.name + )); + } + let base = modpacks::slug(name); + let taken = |s: &str| s == DEFAULT || game_home.join(OWN).join(s).exists(); + let slug = (1..) + .map(|n| { + if n == 1 { + base.clone() + } else { + format!("{base}-{n}") + } + }) + .find(|s| !taken(s)) + .unwrap(); + let dir = game_home.join(OWN).join(&slug); + let made = match from { + Some(from) => copy_home(&from.home, &dir), + None => fs::create_dir_all(&dir).and_then(|()| { + for f in PLAYER_FILES { + let own = game_home.join(f); + if own.is_file() { + fs::copy(own, dir.join(f))?; + } + } + Ok(()) + }), + }; + if let Err(e) = made { + let _ = fs::remove_dir_all(&dir); + return Err(format!("Could not make {}: {e}", dir.display())); + } + let mut store = Store::load(data); + let meta = store.instances.entry(slug.clone()).or_default(); + meta.name = (name != slug).then(|| name.to_string()); + meta.icon = from.and_then(|f| f.icon.clone()); + meta.group = from.and_then(|f| f.group.clone()); + store.save(data)?; + find_in(&list_in(game_home, data), &slug) +} + +fn copy_home(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let name = entry.file_name(); + if NOT_COPIED.iter().any(|n| name == *n) { + continue; + } + let path = entry.path(); + if entry.file_type()?.is_dir() { + copy_dir(&path, &to.join(&name))?; + } else { + fs::copy(&path, to.join(&name))?; + } + } + Ok(()) +} + +fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let target = to.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_dir(&entry.path(), &target)?; + } else { + fs::copy(entry.path(), target)?; + } + } + Ok(()) +} + +/// Changes what the player chose about an instance: its name, icon or group. No folder moves. +pub fn edit(query: &str, change: impl FnOnce(&mut Meta)) -> Result { + edit_in(&backend::game_home(), &backend::data_dir(), query, change) +} + +fn edit_in( + game_home: &Path, + data: &Path, + query: &str, + change: impl FnOnce(&mut Meta), +) -> Result { + let all = list_in(game_home, data); + let instance = find_in(&all, query)?; + let mut store = Store::load(data); + let meta = store.instances.entry(instance.id.clone()).or_default(); + change(meta); + meta.name = meta.name.take().map(|n| n.trim().to_string()); + meta.group = meta + .group + .take() + .map(|g| g.trim().to_string()) + .filter(|g| !g.is_empty()); + if let Some(name) = &meta.name { + if name.is_empty() { + return Err("An instance needs a name.".into()); + } + if all + .iter() + .any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name)) + { + return Err(format!("There is already an instance called {name}.")); + } + } + store.save(data)?; + find_in(&list_in(game_home, data), &instance.id) +} + +/// Turns the game's command into this instance: its own game folder, and a pack's mods. The +/// player's answers that hold everywhere follow it in: data collection and No AI as the +/// launcher has them, and options.txt and the offline name when it has none yet. +pub fn apply(cmd: &mut Command, instance: &Instance) -> Result<(), String> { + match instance.kind { + Kind::Default => return Ok(()), + Kind::Own => { + fs::create_dir_all(&instance.home) + .map_err(|e| format!("{}: {e}", instance.home.display()))?; + cmd.current_dir(&instance.home) + .env("HORIZON_HOME", &instance.home); + } + Kind::Port | Kind::Pack => modpacks::apply_profile(cmd, &instance.work)?, + } + follow_player(&backend::game_home(), &instance.home); + Ok(()) +} + +fn follow_player(game_home: &Path, home: &Path) { + for f in PLAYER_FILES { + if !home.join(f).exists() && game_home.join(f).is_file() { + let _ = fs::copy(game_home.join(f), home.join(f)); + } + } + let consent = horizon_telemetry::consent::Consent::path(game_home); + if consent.is_file() { + let to = horizon_telemetry::consent::Consent::path(home); + let _ = fs::create_dir_all(to.parent().unwrap()); + let _ = fs::copy(consent, to); + } + let no_ai = horizon_core::no_ai::is_on(game_home); + if horizon_core::no_ai::is_on(home) != no_ai { + let _ = horizon_core::no_ai::set(home, no_ai); + } +} + +#[cfg(test)] +#[path = "instances/tests.rs"] +mod tests; diff --git a/launcher/src/instances/tests.rs b/launcher/src/instances/tests.rs new file mode 100644 index 000000000..586b620b3 --- /dev/null +++ b/launcher/src/instances/tests.rs @@ -0,0 +1,203 @@ +use super::*; +use std::collections::BTreeMap; + +fn scratch(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!( + "horizon-launcher-instances-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root +} + +fn put(path: &Path, text: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); +} + +/// Every file under `dir`, relative, with its bytes. +fn files(dir: &Path) -> BTreeMap> { + fn walk(root: &Path, dir: &Path, out: &mut BTreeMap>) { + for e in fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + walk(root, &p, out); + } else { + out.insert(p.strip_prefix(root).unwrap().into(), fs::read(&p).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, dir, &mut out); + out +} + +/// A game home as a player has it before instances: worlds, options, packs, a session, an +/// imported modpack and a registry modpack with their own worlds. +fn player_home(home: &Path) { + put(&home.join("saves/World/level.dat"), "world"); + put(&home.join("saves/World/region/r.0.0.mca"), "region"); + put(&home.join("saves/Other/level.dat"), "other"); + put(&home.join("options.txt"), "fov:90\n"); + put(&home.join("horizon-player.txt"), "name:Player123\n"); + put(&home.join("resourcepacks/faithful.zip"), "pack"); + put(&home.join("logs/latest.log"), "log"); + put(&home.join("sessions/a.json"), "token"); + put(&home.join("telemetry/consent.json"), "{}"); + let pack = horizon_port_pack::import::Pack { + name: "Small Pack".into(), + ..Default::default() + }; + put( + &home.join("ports/small-pack/pack.json"), + &serde_json::to_string(&pack).unwrap(), + ); + put( + &home.join("ports/small-pack/home/saves/Modded/level.dat"), + "modded", + ); + put( + &home.join("horizon-packs/cozy/pack.json"), + r#"{"id":"cozy","name":"Cozy","version":"1.0.0","sha256":"00","mods":[]}"#, + ); + put( + &home.join("horizon-packs/cozy/home/saves/Cozy/level.dat"), + "cozy", + ); +} + +#[test] +fn existing_worlds_stay_where_they_are_and_every_folder_becomes_an_instance() { + let root = scratch("migrate"); + let (home, data) = (root.join("horizon"), root.join("launcher")); + player_home(&home); + let before = files(&home); + + // A launcher with instances, on a player's existing folders: no instances.json yet. + let all = list_in(&home, &data); + let ids: Vec<&str> = all.iter().map(|i| i.id.as_str()).collect(); + assert_eq!(ids, [DEFAULT, "pack:cozy", "port:small-pack"]); + assert_eq!(all[0].name, "Horizon"); + assert_eq!(all[0].home, home); + assert_eq!(all[1].home, home.join("horizon-packs/cozy/home")); + assert_eq!(all[2].name, "Small Pack"); + assert_eq!(all[2].home, home.join("ports/small-pack/home")); + + // Everything the player can do with instances, then not one byte of theirs has moved. + let empty = create_in(&home, &data, "Survival", None).unwrap(); + let copy = create_in(&home, &data, "My copy", Some(&all[0])).unwrap(); + edit_in(&home, &data, DEFAULT, |m| m.name = Some("Main".into())).unwrap(); + edit_in(&home, &data, "Small Pack", |m| { + m.icon = Some(Icon::Texture("diamond".into())); + m.group = Some("Modded".into()); + }) + .unwrap(); + let after = files(&home); + for (path, bytes) in &before { + assert_eq!(after.get(path), Some(bytes), "{} changed", path.display()); + } + assert!(!data.join("settings.json").exists()); + + // The empty one has only the player's options and name; the copy has the worlds and + // packs, never the sessions, logs, data collection or other instances. + assert_eq!(empty.home, home.join("instances/survival")); + let empty_files: Vec = files(&empty.home).into_keys().collect(); + assert_eq!( + empty_files, + [PathBuf::from("horizon-player.txt"), "options.txt".into()] + ); + let copied = files(©.home); + for kept in [ + "saves/World/region/r.0.0.mca", + "saves/Other/level.dat", + "resourcepacks/faithful.zip", + ] { + assert_eq!(copied[Path::new(kept)], before[Path::new(kept)]); + } + assert!(copied.keys().all(|p| { + let top = p.components().next().unwrap().as_os_str().to_str().unwrap(); + !NOT_COPIED.contains(&top) + })); + + let all = list_in(&home, &data); + assert_eq!(all[0].name, "Main"); + let port = find_in(&all, "port:small-pack").unwrap(); + assert_eq!(port.group.as_deref(), Some("Modded")); + assert_eq!(port.home, home.join("ports/small-pack/home")); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn names_stay_unique_and_packs_are_not_copied() { + let root = scratch("names"); + let (home, data) = (root.join("horizon"), root.join("launcher")); + player_home(&home); + create_in(&home, &data, "Survival", None).unwrap(); + assert!(create_in(&home, &data, "survival", None).is_err()); + assert!(create_in(&home, &data, " ", None).is_err()); + // Another name with the same folder name gets the next free folder. + let second = create_in(&home, &data, "Survival!", None).unwrap(); + assert_eq!(second.id, "survival-2"); + assert_eq!(second.name, "Survival!"); + assert!(edit_in(&home, &data, "survival-2", |m| m.name = + Some("SURVIVAL".into())) + .is_err()); + let port = find_in(&list_in(&home, &data), "small-pack").unwrap(); + assert!(create_in(&home, &data, "Pack copy", Some(&port)).is_err()); + assert!(!home.join("instances/pack-copy").exists()); + // An empty group is no group. + let grouped = edit_in(&home, &data, "Survival", |m| m.group = Some(" ".into())).unwrap(); + assert_eq!(grouped.group, None); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn an_instance_follows_the_players_answers() { + let root = scratch("follow"); + let (main, own) = (root.join("main"), root.join("own")); + put(&main.join("options.txt"), "fov:90\n"); + put(&main.join("horizon-player.txt"), "name:Player123\n"); + put(&main.join("telemetry/consent.json"), r#"{"version":1}"#); + horizon_core::no_ai::set(&main, true).unwrap(); + put(&own.join("options.txt"), "fov:70\n"); + follow_player(&main, &own); + assert_eq!( + fs::read_to_string(own.join("options.txt")).unwrap(), + "fov:70\n" + ); + assert_eq!( + fs::read_to_string(own.join("horizon-player.txt")).unwrap(), + "name:Player123\n" + ); + assert_eq!( + fs::read_to_string(own.join("telemetry/consent.json")).unwrap(), + r#"{"version":1}"# + ); + assert!(horizon_core::no_ai::is_on(&own)); + horizon_core::no_ai::set(&main, false).unwrap(); + follow_player(&main, &own); + assert!(!horizon_core::no_ai::is_on(&own)); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn icons_are_a_texture_name_or_a_colour() { + assert_eq!(Icon::parse("#3FA7D6"), Ok(Icon::Colour("#3fa7d6".into()))); + assert_eq!( + Icon::parse("grass_block"), + Ok(Icon::Texture("grass_block".into())) + ); + for bad in ["#12345", "../x", "Grass", "", "#zzzzzz"] { + assert!(Icon::parse(bad).is_err(), "{bad}"); + } + let root = scratch("icon"); + put( + &root.join("assets/minecraft/textures/item/diamond.png"), + "png", + ); + let diamond = Icon::Texture("diamond".into()).texture(&root).unwrap(); + assert!(diamond.ends_with("item/diamond.png")); + assert_eq!(Icon::Texture("stone".into()).texture(&root), None); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 3cba3ed10..f1779c332 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -7,6 +7,7 @@ pub mod desktop; #[cfg(unix)] pub mod game_app; pub mod heads; +pub mod instances; pub mod modpacks; pub mod mojang; pub mod process; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 7cc6d0ccd..4003f5725 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -33,6 +33,7 @@ use gpui::{ }; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; +use horizon_launcher::instances; use horizon_launcher::telemetry; use scrollbar::Scrollbar; use std::borrow::Cow; @@ -535,13 +536,16 @@ impl Launcher { Err(e) => self.client_error = Some(format!("Playing offline: {e}")), } self.accounts = Accounts::load(); - if let Some(work) = self.starting_pack.take() { - if let Err(e) = + // A pack's Play button plays that pack; Play plays the selected instance. + let profile = match self.starting_pack.take() { + Some(work) => { horizon_launcher::modpacks::apply_profile(&mut cmd, &work) - { - self.client_error = Some(e); - continue; } + None => instances::apply(&mut cmd, &instances::selected()), + }; + if let Err(e) = profile { + self.client_error = Some(e); + continue; } if let Some(code) = self.joining.take() { if let Err(e) = backend::join_friend(&mut cmd, &code) { @@ -668,10 +672,12 @@ impl Launcher { } Job::Client => { self.client = None; + // The run's own game folder: an instance's or a pack's keeps its reports. + let home = self.client_home.clone().unwrap_or_else(backend::game_home); let report = self .client_started .take() - .and_then(backend::crash_report_since); + .and_then(|since| backend::crash_report_since(&home, since)); if error.is_some() && report.is_none() && self.switched_to_dx12() { self.client_error = Some( "Horizon's Vulkan renderer crashed while starting on this \ diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 8aff5aa13..cb4636429 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -6,6 +6,7 @@ use crate::cli_tools; use crate::game_tools::{self, GameTools}; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Logged}; +use horizon_launcher::instances; use serde_json::{json, Value}; use std::io::{BufRead, Write}; use std::path::PathBuf; @@ -29,6 +30,7 @@ fn session_tools() -> Value { json!([ { "name": "play", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world. CLI: horizon-launcher play", "inputSchema": { "type": "object", "properties": { "version": version, + "instance": { "type": "string", "description": "The instance to play, by name or id (instance_list). Default: the selected one." }, "world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." }, "creative": { "type": "boolean", "description": "Creative mode for a new world." }, "join": { "type": "string", "description": "Join a friend's world with its invite code. Only when the player asks." }, @@ -68,6 +70,11 @@ impl Session { } let tag = backend::resolve_version(arg_str(args, "version"))?; let mut cmd = backend::client(&tag)?; + let instance = match arg_str(args, "instance") { + Some(name) => instances::find(name)?, + None => instances::selected(), + }; + instances::apply(&mut cmd, &instance)?; cmd.args(game_tools::control_args()); if let Some(world) = arg_str(args, "world") { cmd.arg("--world").arg(world); diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs index acd8241a5..3b8e9451f 100644 --- a/launcher/src/modpacks.rs +++ b/launcher/src/modpacks.rs @@ -135,7 +135,11 @@ pub fn load(work: &Path) -> Result { /// Every imported pack, by name. pub fn list() -> Vec { - let mut packs: Vec = fs::read_dir(ports_dir()) + list_in(&ports_dir()) +} + +pub(crate) fn list_in(ports: &Path) -> Vec { + let mut packs: Vec = fs::read_dir(ports) .into_iter() .flatten() .flatten()