diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 4a281729d..af0588af6 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2664,6 +2664,7 @@ dependencies = [ "gpui", "horizon-bench", "horizon-friends", + "horizon-port-pack", "horizon-prepare", "horizon-telemetry", "horizon-theme", @@ -2680,6 +2681,18 @@ dependencies = [ "zip", ] +[[package]] +name = "horizon-port-pack" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "sha1", + "toml 1.1.8+spec-1.1.0", + "ureq", + "zip", +] + [[package]] name = "horizon-prepare" version = "0.1.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 8f5873f87..34af6e2a1 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -26,6 +26,8 @@ horizon-prepare = { path = "../crates/horizon-prepare" } # Join a friend: invite codes (the game does the joining). horizon-friends = { path = "../crates/horizon-friends" } horizon-bench = { path = "../crates/horizon-bench" } +# Import modpack: the porting pipeline, run on the player's own files (docs/modpacks.md). +horizon-port-pack = { path = "../crates/horizon-port-pack" } # Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md). horizon-telemetry = { path = "../crates/horizon-telemetry" } # The session file's random name. diff --git a/launcher/README.md b/launcher/README.md index e5edba182..b3dff7fde 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -25,6 +25,16 @@ The opening, then Play ([clip](docs/opening.webm)): preparation reuses checksum-verified game jars and libraries from the current or another installed Horizon version, so the original Minecraft install is only required when no valid imported copy exists. +- **Modpacks**: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, or a Prism, + MultiMC or CurseForge instance folder) and see its coverage report: per mod, ported, partial, + not yet or not needed, with the reason ([docs/modpacks.md](../docs/modpacks.md)). **Port** + gets the jars of what this computer can port today (content mods with data and assets only) + the player's own way: copied from a folder they have, or downloaded from the pack's own links + or the same file on Modrinth's CDN, hash checked; files only CurseForge has need its API key, so + they come from your installed instance. It carries them over for the selected version, and + **Play** starts the game as the pack's own profile (`ports//home/` in the game's home: + its own saves and options) with those mods. Nothing is uploaded or shared: mod jars and ports + stay on this computer. - **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, @@ -83,6 +93,11 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher account sign-out horizon-launcher account select play as this account horizon-launcher account offline play without an account + 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 + horizon-launcher modpack play [--version ] play it as its own profile + horizon-launcher modpack remove horizon-launcher benchmark [--repeats N] measure the launcher (see Performance log) horizon-launcher data [status] what data collection is allowed, the install ID, what waits horizon-launcher data allow|deny performance, crashes, bugs, benchmarks @@ -92,7 +107,7 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher data benchmark upload a benchmark report, printed first `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). @@ -192,6 +207,7 @@ bundled so the type is the same on every platform. ## Screenshots ![Server](docs/server.png) +![Modpacks](docs/modpacks.png) ![Versions](docs/versions.png) ![Patch notes](docs/patch-notes.png) ![Settings](docs/settings.png) diff --git a/launcher/docs/modpacks.png b/launcher/docs/modpacks.png new file mode 100644 index 000000000..9abe41c64 Binary files /dev/null and b/launcher/docs/modpacks.png differ diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 4f5d00ca0..6082d1ee9 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1709,6 +1709,10 @@ pub enum Msg { /// The selected account's session file for the game about to start (none = offline), or /// why it could not be renewed. Session(Result, String>), + /// A modpack step's line (`modpacks`). + PackLine(String), + /// A modpack step ended: the pack as it now is. + PackDone(Result, String>), } /// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`. diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index df9cfc6b1..b140979b3 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -76,6 +76,33 @@ enum DataCmd { }, } +#[derive(Subcommand)] +enum ModpackCmd { + /// The imported packs and their coverage (the default) + List, + /// Import a .mrpack, a CurseForge zip or an instance folder, and write its coverage report + Import { path: PathBuf }, + /// Get the jars of what this computer can port and carry them over + Port { + /// The pack's folder name, as list shows it + pack: String, + /// A folder with your own jars (an installed instance, a downloads folder) + #[arg(long)] + from: Option, + /// The installed version the ports are for (default: the selected one) + #[arg(long)] + version: Option, + }, + /// Play a ported pack as its own profile + Play { + pack: String, + #[arg(long)] + version: Option, + }, + /// Remove an imported pack: its jars, ports and the profile's saves + Remove { pack: String }, +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -161,6 +188,12 @@ enum Cmd { #[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 { + #[command(subcommand)] + action: Option, + }, /// Serve the Model Context Protocol on stdin and stdout, for AI agents Mcp, /// Measure the launcher: starts (the first is the cold one), page switching, idle CPU and @@ -400,6 +433,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("Horizon is in the applications menu."); } } + Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, Cmd::Mcp => unreachable!(), } Ok(()) @@ -591,3 +625,73 @@ fn data(action: DataCmd, as_json: bool) -> Result<(), String> { } Ok(()) } + +fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { + use horizon_launcher::modpacks::{self, Imported}; + use horizon_port_pack::report::Status; + let log = &|line: String| eprintln!("{line}"); + let work = |pack: &str| { + let work = modpacks::ports_dir().join(pack); + modpacks::load(&work).map(|_| work) + }; + let show = |p: &Imported| { + let counts: Vec = Status::ALL + .iter() + .map(|s| format!("{} {}", p.count(*s), s.label())) + .collect(); + if as_json { + json(serde_json::json!({ + "pack": p.slug, "name": p.title(), "summary": p.summary(), + "counts": Status::ALL.iter().map(|s| (s.label(), p.count(*s))).collect::>(), + "portable": p.portable, "ported_mods": p.mods.len(), "jars": p.jars(), + "report": p.work.join("coverage.md"), + })); + } else { + println!( + "{} ({})\n {}\n {}", + p.title(), + p.slug, + p.summary(), + counts.join(", ") + ); + println!(" {} portable, {} carried over", p.portable, p.mods.len()); + if let Some(jars) = p.jars() { + println!(" {jars}"); + } + println!(" {}", p.work.join("coverage.md").display()); + } + }; + match action { + ModpackCmd::List => { + let packs = modpacks::list(); + if packs.is_empty() && !as_json { + println!("No modpack imported yet: horizon-launcher modpack import "); + } + packs.iter().for_each(show); + } + ModpackCmd::Import { path } => show(&modpacks::import(&path, log)?), + ModpackCmd::Port { + pack, + from, + version, + } => { + let tag = backend::resolve_version(version.as_deref()).ok(); + let resources = tag + .filter(|t| backend::is_prepared(t)) + .map(|t| backend::resources(&t)); + show(&modpacks::port( + &work(&pack)?, + resources.as_deref(), + from.as_deref(), + log, + )?) + } + ModpackCmd::Play { pack, version } => { + let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; + modpacks::apply_profile(&mut cmd, &work(&pack)?)?; + attached(cmd)? + } + ModpackCmd::Remove { pack } => modpacks::remove(&work(&pack)?)?, + } + Ok(()) +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 5df6a7cbb..11023a46d 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -2,6 +2,7 @@ pub mod account; pub mod backend; pub mod desktop; +pub mod modpacks; pub mod mojang; pub mod sources; pub mod telemetry; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index cc66aa08e..ec1dacf78 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -6,6 +6,7 @@ mod collection; mod game_tools; mod markdown; mod mcp; +mod modpacks_page; mod perf; mod theme; @@ -29,14 +30,16 @@ use theme::Theme; enum Page { Play, Versions, + Modpacks, Notes, Settings, } impl Page { - const ALL: [(Page, &'static str); 4] = [ + const ALL: [(Page, &'static str); 5] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), + (Page::Modpacks, "Modpacks"), (Page::Notes, "Patch notes"), (Page::Settings, "Settings"), ]; @@ -161,6 +164,17 @@ struct Launcher { play_pressed: Option, /// `horizon-launcher benchmark` started this window to measure it. bench: Option, + /// The Modpacks page: the imported packs (read when the page first opens), the one shown, + /// the report's filter, and the pipeline step running now with its log. + packs: Vec, + packs_loaded: Option, + pack_open: Option, + pack_filter: Option, + pack_busy: bool, + pack_log: VecDeque, + pack_error: Option, + /// The game starting now plays this pack's profile (its work folder). + starting_pack: Option, } impl Launcher { @@ -266,6 +280,14 @@ impl Launcher { prepare_started: None, play_pressed: None, bench: perf::Bench::from_env(), + packs: Vec::new(), + packs_loaded: None, + pack_open: None, + pack_filter: None, + pack_busy: false, + pack_log: VecDeque::new(), + pack_error: None, + starting_pack: None, }; if this.bench.is_some() { this.perf.keep_local_log(false); @@ -406,6 +428,14 @@ 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) = + horizon_launcher::modpacks::apply_profile(&mut cmd, &work) + { + self.client_error = Some(e); + continue; + } + } if let Some(code) = self.joining.take() { if let Err(e) = backend::join_friend(&mut cmd, &code) { self.client_error = Some(e); @@ -473,6 +503,13 @@ impl Launcher { Err(e) => SelfUpdate::Failed(e), }; } + Msg::PackLine(line) => { + self.pack_log.push_back(line); + if self.pack_log.len() > LOG_LINES { + self.pack_log.pop_front(); + } + } + Msg::PackDone(result) => self.pack_done(result), Msg::Line(job, line) => { if job == Job::Client && line.starts_with(perf::GAME_FIRST_FRAME) { if let Some(pressed) = self.play_pressed.take() { @@ -671,37 +708,8 @@ impl Launcher { if self.client.is_some() || self.starting_client.is_some() { return; } - self.client_error = None; - self.crash = None; - self.prepare_log.clear(); - // A little earlier than the spawn: file times can be coarse. - self.client_started = - Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); - // The session (a network round trip when the token needs renewing) comes first; - // `drain` starts the game when it arrives. - self.starting_client = Some(tag); - self.play_pressed = Some(Instant::now()); - let tx = self.tx.clone(); - std::thread::spawn(move || { - let session = (|| { - let mut accounts = Accounts::load(); - let Some((a, secrets)) = account::session_for_launch( - &account::Endpoints::live(), - account::store(), - &mut accounts, - )? - else { - return Ok(None); - }; - account::write_session_file( - &backend::game_home().join("sessions"), - &a, - &secrets, - ) - .map(Some) - })(); - let _ = tx.send(Msg::Session(session)); - }); + self.starting_pack = None; + self.start_client(tag); } Mode::Server => { if let Some(server) = &mut self.server { @@ -729,6 +737,38 @@ impl Launcher { } } + /// Starts the game: the session first (a network round trip when the token needs + /// renewing), then `drain` starts the process when it arrives. + fn start_client(&mut self, tag: String) { + self.client_error = None; + self.crash = None; + self.prepare_log.clear(); + // A little earlier than the spawn: file times can be coarse. + self.client_started = + Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); + // The session (a network round trip when the token needs renewing) comes first; + // `drain` starts the game when it arrives. + self.starting_client = Some(tag); + self.play_pressed = Some(Instant::now()); + let tx = self.tx.clone(); + std::thread::spawn(move || { + let session = (|| { + let mut accounts = Accounts::load(); + let Some((a, secrets)) = account::session_for_launch( + &account::Endpoints::live(), + account::store(), + &mut accounts, + )? + else { + return Ok(None); + }; + account::write_session_file(&backend::game_home().join("sessions"), &a, &secrets) + .map(Some) + })(); + let _ = tx.send(Msg::Session(session)); + }); + } + fn choose_folder(&mut self, server: bool, cx: &mut Context) { let paths = cx.prompt_for_paths(PathPromptOptions { files: false, @@ -2774,6 +2814,7 @@ impl Render for Launcher { let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), + Page::Modpacks => self.modpacks_page(cx), Page::Notes => self.notes_page(cx), Page::Settings => self.settings_page(cx), }; diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs new file mode 100644 index 000000000..6d4553a14 --- /dev/null +++ b/launcher/src/modpacks.rs @@ -0,0 +1,249 @@ +//! Modpacks: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, an instance folder), +//! show what Horizon runs of it, port that on this computer from the player's own downloads, and +//! play it as a profile of its own (docs/modpacks.md). +//! +//! Each pack lives in `ports//` in the game's home: the work folder `horizon-port-pack` +//! writes (pack.json, inventory, the jars, the carried-over mods, the coverage report) and +//! `home/`, the profile's own saves and options. Nothing is uploaded or shared: mod jars are +//! often All Rights Reserved, so the ports stay on the player's machine. +use crate::backend; +use horizon_port_pack::{ + fetch::{Fetched, How}, + import::Pack, + pipeline::{self, Log}, + report::{Row, Status}, +}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Where imported packs live. +pub fn ports_dir() -> PathBuf { + backend::game_home().join("ports") +} + +/// A pack's folder name: its name in lowercase words joined by dashes. +pub fn slug(name: &str) -> String { + let words: Vec = name + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_ascii_lowercase) + .collect(); + if words.is_empty() { + "pack".into() + } else { + words.join("-") + } +} + +/// An imported pack, as its work folder has it. +pub struct Imported { + pub slug: String, + pub work: PathBuf, + pub pack: Pack, + pub rows: Vec, + pub fetched: Fetched, + /// The carried-over mods the profile loads. + pub mods: Vec, + /// The mods the port step gets and carries over (content, data tier). + pub portable: usize, +} + +impl Imported { + pub fn title(&self) -> &str { + if self.pack.name.is_empty() { + &self.slug + } else { + &self.pack.name + } + } + pub fn count(&self, status: Status) -> usize { + self.rows.iter().filter(|r| r.status == status).count() + } + /// "Minecraft 1.21.1 · neoforge 21.1.259 · 496 mods". + pub fn summary(&self) -> String { + let mut parts = Vec::new(); + if !self.pack.minecraft.is_empty() { + parts.push(format!("Minecraft {}", self.pack.minecraft)); + } + if !self.pack.loader.is_empty() { + parts.push(format!("{} {}", self.pack.loader, self.pack.loader_version)); + } + parts.push(format!("{} files", self.pack.files.len())); + parts.join(" · ") + } + /// What getting the jars did, in one line, or None before it ran. + pub fn jars(&self) -> Option { + if self.fetched.files.is_empty() { + return None; + } + let mut parts = Vec::new(); + for (how, what) in [ + (How::Downloaded, "downloaded"), + (How::Local, "copied from your folder"), + (How::Present, "already here"), + ( + How::NeedsKey, + "only on CurseForge (needs its API key: choose your installed instance instead)", + ), + (How::NotFound, "not found"), + (How::Failed, "failed"), + ] { + let n = self.fetched.count(how); + if n > 0 { + parts.push(format!("{n} {what}")); + } + } + Some(format!("Jars: {}.", parts.join(", "))) + } +} + +/// Reads the pack in `work`. +pub fn load(work: &Path) -> Result { + let pack: Pack = pipeline::read_json(&work.join("pack.json"))?; + let rows: Vec = pipeline::read_json(&work.join("coverage.json")).unwrap_or_default(); + let records: Vec = + pipeline::read_json(&work.join("inventory.json")).unwrap_or_default(); + Ok(Imported { + slug: work + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + work: work.to_path_buf(), + pack, + rows, + fetched: Fetched::load(work), + mods: carried(work), + portable: records.iter().filter(|r| pipeline::portable(r)).count(), + }) +} + +/// Every imported pack, by name. +pub fn list() -> Vec { + let mut packs: Vec = fs::read_dir(ports_dir()) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| load(&e.path()).ok()) + .collect(); + packs.sort_by_key(|p| p.title().to_ascii_lowercase()); + packs +} + +/// The carried-over mods in a work folder (`mods//carry/` with its manifest). +pub fn carried(work: &Path) -> Vec { + let mut mods: Vec = fs::read_dir(work.join("mods")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path().join("carry")) + .filter(|c| c.join("horizon-mod.toml").is_file()) + .collect(); + mods.sort(); + mods +} + +/// Imports the pack at `path` into `ports//` and writes its coverage report from +/// metadata (Modrinth answers by file hash; nothing is downloaded yet). Importing the same pack +/// again keeps the jars and ports it already has. +pub fn import(path: &Path, log: Log) -> Result { + let pack = horizon_port_pack::import::import(path)?; + let name = if pack.name.is_empty() || pack.name == "modlist" { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + } else { + pack.name.clone() + }; + let work = ports_dir().join(slug(&name)); + log(format!("Importing {name} into {}", work.display())); + pipeline::import(path, &work, log)?; + pipeline::inventory(&work, false, log)?; + pipeline::report(&work, log)?; + load(&work) +} + +/// Ports what this computer can: the portable mods' jars (from `from` when the player has them, +/// else the pack's links or Modrinth), carried over for `resources`, then the report again. +pub fn port( + work: &Path, + resources: Option<&Path>, + from: Option<&Path>, + log: Log, +) -> Result { + pipeline::port(work, resources, from, log)?; + load(work) +} + +/// Removes an imported pack: its jars, ports and the profile's saves. +pub fn remove(work: &Path) -> Result<(), String> { + if work.parent() != Some(ports_dir().as_path()) { + return Err(format!("{} is not an imported pack", work.display())); + } + fs::remove_dir_all(work).map_err(|e| format!("{}: {e}", work.display())) +} + +/// The profile's own game home: saves, options.txt, logs. +pub fn profile_home(work: &Path) -> PathBuf { + work.join("home") +} + +/// Turns the game's command into this pack's profile: its own home (the player's options.txt +/// copied in the first time, so keys and video settings carry over) and its carried-over mods. +pub fn apply_profile(cmd: &mut Command, work: &Path) -> Result<(), String> { + let mods = carried(work); + if mods.is_empty() { + return Err("Nothing is ported yet: port the pack first.".into()); + } + let home = profile_home(work); + fs::create_dir_all(&home).map_err(|e| format!("{}: {e}", home.display()))?; + let options = home.join("options.txt"); + let own = backend::game_home().join("options.txt"); + if !options.exists() && own.is_file() { + let _ = fs::copy(own, &options); + } + cmd.current_dir(&home).env("HORIZON_HOME", &home); + for m in mods { + cmd.arg("--dev-mod").arg(m); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slugs() { + assert_eq!(slug("All the Mods 10"), "all-the-mods-10"); + assert_eq!(slug("Create: Above & Beyond!"), "create-above-beyond"); + assert_eq!(slug(" "), "pack"); + } + + #[test] + fn a_profile_has_its_own_home_and_mods() { + let root = + std::env::temp_dir().join(format!("horizon-launcher-pack-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let work = root.join("ports/small"); + let mut cmd = Command::new("true"); + assert!(apply_profile(&mut cmd, &work).is_err()); + for id in ["a", "b"] { + let carry = work.join("mods").join(id).join("carry"); + fs::create_dir_all(&carry).unwrap(); + fs::write(carry.join("horizon-mod.toml"), "").unwrap(); + } + // Left out: no manifest. + fs::create_dir_all(work.join("mods/c/carry")).unwrap(); + apply_profile(&mut cmd, &work).unwrap(); + let args: Vec = cmd + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + assert_eq!(args.len(), 4); + assert!(args[1].ends_with("a/carry") && args[3].ends_with("b/carry")); + assert_eq!(cmd.get_current_dir(), Some(profile_home(&work).as_path())); + assert!(profile_home(&work).is_dir()); + fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/launcher/src/modpacks_page.rs b/launcher/src/modpacks_page.rs new file mode 100644 index 000000000..2398421c6 --- /dev/null +++ b/launcher/src/modpacks_page.rs @@ -0,0 +1,412 @@ +//! The Modpacks page: import a pack, read its coverage report, port what this computer can and +//! play it as its own profile (`horizon_launcher::modpacks`). +use super::*; +use horizon_launcher::modpacks::{self, Imported}; +use horizon_port_pack::report::Status; +use std::path::PathBuf; + +/// The report's filter: every row, or one status. +pub(super) const FILTERS: [(Option, &str); 5] = [ + (None, "All"), + (Some(Status::Ported), "Ported"), + (Some(Status::Partial), "Partial"), + (Some(Status::NotYet), "Not yet"), + (Some(Status::NotNeeded), "Not needed"), +]; + +/// Lines of the pipeline's log the page shows while it works. +const LOG_SHOWN: usize = 6; + +impl Launcher { + fn open_pack(&self) -> Option<&Imported> { + let slug = self.pack_open.as_ref()?; + self.packs.iter().find(|p| &p.slug == slug) + } + + /// Runs a pipeline step on a thread; its lines and its end arrive as messages. + fn pack_job( + &mut self, + job: impl FnOnce(&dyn Fn(String)) -> Result + Send + 'static, + ) { + if self.pack_busy { + return; + } + self.pack_busy = true; + self.pack_log.clear(); + self.pack_error = None; + let tx = self.tx.clone(); + std::thread::spawn(move || { + let lines = tx.clone(); + let log = move |line: String| { + let _ = lines.send(Msg::PackLine(line)); + }; + let result = job(&log); + let _ = tx.send(Msg::PackDone(result.map(Box::new))); + }); + } + + /// A finished step: the pack's new state, opened. + pub(super) fn pack_done(&mut self, result: Result, String>) { + self.pack_busy = false; + match result { + Ok(pack) => { + self.pack_open = Some(pack.slug.clone()); + self.packs.retain(|p| p.slug != pack.slug); + self.packs.push(*pack); + self.packs.sort_by_key(|p| p.title().to_ascii_lowercase()); + } + Err(e) => self.pack_error = Some(e), + } + } + + fn choose_pack(&mut self, folder: bool, cx: &mut Context) { + let paths = cx.prompt_for_paths(PathPromptOptions { + files: !folder, + directories: folder, + multiple: false, + prompt: Some("Import".into()), + }); + cx.spawn(async move |this, cx| { + if let Ok(Ok(Some(mut paths))) = paths.await { + if let Some(path) = paths.pop() { + let _ = this.update(cx, |this, cx| { + this.pack_job(move |log| modpacks::import(&path, log)); + cx.notify(); + }); + } + } + }) + .detach(); + } + + /// Ports the open pack; `from` is a folder of the player's jars, chosen when `ask`. + fn port_pack(&mut self, ask: bool, cx: &mut Context) { + let Some(work) = self.open_pack().map(|p| p.work.clone()) else { + return; + }; + let resources = self + .selected() + .filter(|tag| backend::is_prepared(tag)) + .map(|tag| backend::resources(tag)); + if !ask { + self.pack_job(move |log| modpacks::port(&work, resources.as_deref(), None, log)); + return; + } + let paths = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Use these jars".into()), + }); + cx.spawn(async move |this, cx| { + if let Ok(Ok(Some(mut paths))) = paths.await { + if let Some(from) = paths.pop() { + let _ = this.update(cx, |this, cx| { + this.pack_job(move |log| { + modpacks::port(&work, resources.as_deref(), Some(&from), log) + }); + cx.notify(); + }); + } + } + }) + .detach(); + } + + fn play_pack(&mut self, work: PathBuf) { + let Some(tag) = self.selected().cloned() else { + return; + }; + if self.client.is_some() || self.starting_client.is_some() { + return; + } + self.starting_pack = Some(work); + self.start_client(tag); + } + + pub(super) fn modpacks_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if self.packs_loaded.is_none() { + self.packs = modpacks::list(); + if self.pack_open.is_none() { + self.pack_open = self.packs.first().map(|p| p.slug.clone()); + } + self.packs_loaded = Some(Instant::now()); + } + let header = page_header( + "Modpacks", + "Bring a Java modpack: see what Horizon runs of it, port that on this computer from \ + your own downloads, and play it as its own profile. Nothing is uploaded or shared.", + &t, + ); + let busy = self.pack_busy; + let pick = |id: &'static str, label: &'static str, folder: bool| { + let b = button(id, label, Kind::Secondary, &t); + if busy { + disabled(b) + } else { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.choose_pack(folder, cx); + cx.notify(); + })) + } + }; + let actions = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .child(pick("import-file", "Import a pack file…", false)) + .child(pick("import-folder", "Import an instance folder…", true)) + .child(text(theme::CAPTION).text_color(t.muted).child( + ".mrpack (Modrinth), .zip (CurseForge), or a Prism, MultiMC or CurseForge instance", + )); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(actions); + if busy || !self.pack_log.is_empty() { + page = page.child(self.pack_log_plate(&t)); + } + if let Some(e) = &self.pack_error { + page = page.child(notice(e.clone(), &t)); + } + if self.packs.is_empty() { + return page.child(centered( + "No modpack yet. Import one to see what Horizon can run of it.", + &t, + )); + } + if self.packs.len() > 1 { + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in self.packs.iter().enumerate() { + let open = self.pack_open.as_ref() == Some(&p.slug); + let slug = p.slug.clone(); + let right = if open { + caps("Open").text_color(t.accent).into_any_element() + } else { + button(format!("open-{slug}"), "Open", Kind::Ghost, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.pack_open = Some(slug.clone()); + cx.notify(); + })) + .into_any_element() + }; + list = list.child(index_row( + i + 1, + p.title().to_string(), + Some(p.summary().into_any_element()), + Some(right), + &t, + )); + } + page = page.child(list); + } + match self.pack_detail(cx) { + Some(detail) => page.child(detail), + None => page, + } + } + + fn pack_log_plate(&self, t: &Theme) -> Div { + let start = self.pack_log.len().saturating_sub(LOG_SHOWN); + plate(t) + .flex() + .flex_col() + .gap(px(4.)) + .p(px(16.)) + .child( + caps(if self.pack_busy { "Working" } else { "Done" }) + .text_color(if self.pack_busy { t.accent } else { t.muted }), + ) + .children(self.pack_log.iter().skip(start).map(|line| { + text(theme::CAPTION) + .font_family(theme::MONO) + .text_color(t.ink_soft) + .truncate() + .child(line.clone()) + })) + } + + fn pack_detail(&self, cx: &mut Context) -> Option
{ + let t = self.theme; + let p = self.open_pack()?; + let mut counts = div().flex().gap(px(12.)); + for (status, label) in FILTERS.iter().skip(1) { + let status = status.expect("the first filter is All"); + let color = match status { + Status::Ported => t.success, + Status::Partial => t.accent, + _ => t.ink, + }; + counts = counts.child( + plate(&t) + .flex() + .flex_col() + .flex_1() + .gap(px(4.)) + .p(px(16.)) + .child( + text(theme::DISPLAY) + .text_color(color) + .child(p.count(status).to_string()), + ) + .child(caps(*label).text_color(t.muted)), + ); + } + let can_play = self.selected().is_some_and(|tag| backend::is_prepared(tag)); + let running = self.client.is_some() || self.starting_client.is_some(); + let mut buttons = div().flex().flex_wrap().items_center().gap(px(8.)); + let play_label = if p.mods.is_empty() { + "Play".to_string() + } else { + format!("Play with {} mods", p.mods.len()) + }; + let mut play = button("pack-play", play_label, Kind::Primary, &t); + if p.mods.is_empty() || !can_play || running || self.pack_busy { + play = disabled(play); + } else { + let work = p.work.clone(); + play = play.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.play_pack(work.clone()); + cx.notify(); + })); + } + let port_label = format!("Port {} mods", p.portable); + let mut port = button("pack-port", port_label, Kind::Secondary, &t); + let mut from = button("pack-from", "Use jars from my instance…", Kind::Ghost, &t); + if self.pack_busy || p.portable == 0 { + port = disabled(port); + from = disabled(from); + } else { + port = port.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.port_pack(false, cx); + cx.notify(); + })); + from = from.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.port_pack(true, cx); + cx.notify(); + })); + } + let confirming = self.confirm_remove.as_deref() == Some(p.slug.as_str()); + let slug = p.slug.clone(); + let work = p.work.clone(); + let remove = button( + "pack-remove", + if confirming { + "Remove for good" + } else { + "Remove" + }, + if confirming { + Kind::Secondary + } else { + Kind::Ghost + }, + &t, + ) + .when(confirming, |b| b.text_color(t.danger)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if this.confirm_remove.as_ref() == Some(&slug) { + match modpacks::remove(&work) { + Ok(()) => { + this.packs.retain(|p| p.slug != slug); + this.pack_open = this.packs.first().map(|p| p.slug.clone()); + } + Err(e) => this.pack_error = Some(e), + } + this.confirm_remove = None; + } else { + this.confirm_remove = Some(slug.clone()); + } + cx.notify(); + })); + buttons = buttons.child(play).child(port).child(from).child(remove); + let mut notes = vec![format!( + "Port gets the jars of the {} mods this computer can port today (content with data \ + and assets only) from the pack's own links, Modrinth, or your folder, and carries \ + them over. The ports stay here, in {}.", + p.portable, + short(&p.work) + )]; + if let Some(jars) = p.jars() { + notes.push(jars); + } + if !can_play { + notes.push("Playing needs a prepared Horizon version (Play page).".into()); + } + let mut rows: Vec<&horizon_port_pack::report::Row> = p + .rows + .iter() + .filter(|r| self.pack_filter.is_none_or(|s| r.status == s)) + .collect(); + rows.sort_by(|a, b| (a.status, &a.key).cmp(&(b.status, &b.key))); + let filter = segments("pack-filter", &FILTERS, self.pack_filter, &t, { + let this = cx.entity().downgrade(); + move |value, _, cx| { + let _ = this.update(cx, |this, cx| { + this.pack_filter = value; + cx.notify(); + }); + } + }); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, r) in rows.iter().enumerate() { + let color = match r.status { + Status::Ported => t.success, + Status::Partial => t.accent, + Status::NotYet => t.ink_soft, + Status::NotNeeded => t.muted, + }; + let name = if r.name.is_empty() || r.name == r.key { + r.key.clone() + } else { + format!("{} ({})", r.name, r.key) + }; + let detail = format!("{} · {} · {}: {}", r.class, r.tier, r.license, r.reason); + list = list.child(index_row( + i + 1, + name, + Some(detail.into_any_element()), + Some( + caps(r.status.label()) + .flex_none() + .text_color(color) + .into_any_element(), + ), + &t, + )); + } + Some( + div() + .flex() + .flex_col() + .gap(px(24.)) + .child( + div() + .flex() + .flex_col() + .gap(px(4.)) + .child( + text(theme::TITLE) + .text_color(t.ink) + .child(p.title().to_string()), + ) + .child(text(theme::UI).text_color(t.muted).child(p.summary())), + ) + .child(counts) + .child(buttons) + .children(self.client_error.clone().map(|e| notice(e, &t))) + .children(notes.into_iter().map(|n| { + text(theme::CAPTION) + .max_w(px(720.)) + .text_color(t.muted) + .child(n) + })) + .child(div().flex().child(filter)) + .child(list), + ) + } +}