diff --git a/docs/mod-browser.md b/docs/mod-browser.md index b7a9176c5..115877075 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -30,6 +30,15 @@ never offered for install. else removes the part file and installs nothing. - A file whose source lists no checksum is refused. +## The Mods page + +The launcher's **Mods** page has the three kinds as tabs, a search field (Enter searches), **Show everything** and, +once CurseForge is set up, a Modrinth / CurseForge switch. Each result is an index row: its summary, author, +downloads, source and licence, how well it runs (and why), **Page** (the project's page on its source) and +**Install** (**Import** for a modpack). Installed packs are listed above the results with their version, source, +file and the checksum they were checked against, with **Update to …** when a newer version runs and **Remove** +(asked twice). + ## Installing, updating, removing `mod-browser.json` beside `options.txt` lists every file the browser installed: its source, project, version, file diff --git a/launcher/README.md b/launcher/README.md index e95d72649..74054ea55 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -24,6 +24,12 @@ 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. +- **Mods**: search Modrinth (and CurseForge once the launcher has its API key) for resource + packs, Iris/OptiFine shader packs and modpacks, each marked Works, Partly or Doesn't run in + Horizon; Java mod jars are never offered. Install puts a pack and what it needs in + `resourcepacks/` or `shaderpacks/` only after its SHA-512 (SHA-1 on CurseForge) matches, and a + modpack goes to the Modpacks page; installed packs show their source and checksum, with Update + and Remove ([docs/mod-browser.md](../docs/mod-browser.md)). - **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** diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 3b2d0f32b..41bce0489 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -8,6 +8,7 @@ mod internet; mod markdown; mod mcp; mod modpacks_page; +mod mods_page; mod perf; mod scrollbar; mod servers_page; @@ -35,6 +36,7 @@ use theme::Theme; enum Page { Play, Versions, + Mods, Modpacks, Servers, Notes, @@ -42,9 +44,10 @@ enum Page { } impl Page { - const ALL: [(Page, &'static str); 6] = [ + const ALL: [(Page, &'static str); 7] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), + (Page::Mods, "Mods"), (Page::Modpacks, "Modpacks"), (Page::Servers, "Servers"), (Page::Notes, "Patch notes"), @@ -181,6 +184,8 @@ struct Launcher { pack_error: Option, /// The game starting now plays this pack's profile (its work folder). starting_pack: Option, + /// The Mods page: the browser's search, installs and updates (`mods_page.rs`). + mods: mods_page::Mods, } impl Launcher { @@ -291,6 +296,7 @@ impl Launcher { pack_log: VecDeque::new(), pack_error: None, starting_pack: None, + mods: mods_page::Mods::new(cx), }; if this.bench.is_some() { this.perf.keep_local_log(false); @@ -595,6 +601,7 @@ impl Launcher { } } changed |= self.servers_tick(); + changed |= self.mods_tick(); if let Some(sign_in) = &self.sign_in { let state = sign_in.state(); let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); @@ -2687,10 +2694,12 @@ impl Render for Launcher { self.perf.frame(); self.servers.note_focus(window); self.friend_focused = self.friend_focus.is_focused(window); + self.mods.note_focus(window); self.args_focused = self.args_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), + Page::Mods => self.mods_page(cx), Page::Modpacks => self.modpacks_page(cx), Page::Servers => self.servers_page(cx), Page::Notes => self.notes_page(cx), diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs new file mode 100644 index 000000000..25a825c93 --- /dev/null +++ b/launcher/src/mods_page.rs @@ -0,0 +1,675 @@ +//! The Mods page: search Modrinth (and CurseForge with a key) for resource packs, shader packs +//! and modpacks Horizon loads, see where each comes from and how well it runs, install it with +//! its checksum checked, and update or remove what was installed (`horizon_launcher::browser`). +use super::servers_page::{type_key, Key}; +use super::*; +use horizon_launcher::browser::{ + self, curseforge::CurseForge, installed, Kind as PackKind, Project, Query, SourceId, Support, +}; +use horizon_launcher::modpacks; +use std::collections::HashMap; + +const KINDS: [(PackKind, &str); 3] = [ + (PackKind::ResourcePack, "Resource packs"), + (PackKind::ShaderPack, "Shader packs"), + (PackKind::Modpack, "Modpacks"), +]; +const SOURCES: [(SourceId, &str); 2] = [ + (SourceId::Modrinth, "Modrinth"), + (SourceId::CurseForge, "CurseForge"), +]; +const PAGE: usize = 20; + +pub(super) enum Event { + /// A search's answer, for the search it was (stale answers are dropped) at that offset. + Found(u64, usize, Result, String>), + Progress(String, f32), + Done(Result, bool), + Updates(HashMap<(SourceId, String), String>), +} + +pub(super) struct Mods { + kind: PackKind, + source: SourceId, + curseforge: bool, + text: String, + focus: FocusHandle, + pub(super) focused: bool, + everything: bool, + /// Which search is the current one; answers for older ones are dropped. + search: u64, + searching: bool, + searched: bool, + results: Vec, + more: bool, + error: Option, + installed: Vec, + loaded: bool, + /// The project being installed, and the line and fraction of its download. + busy: Option<(String, String, f32)>, + message: Option>, + updates: HashMap<(SourceId, String), String>, + confirm_remove: Option, + tx: Sender, + rx: Receiver, +} + +impl Mods { + pub(super) fn new(cx: &mut App) -> Self { + let (tx, rx) = channel(); + Self { + kind: PackKind::ResourcePack, + source: SourceId::Modrinth, + curseforge: CurseForge::from_env().is_some(), + text: String::new(), + focus: cx.focus_handle().tab_index(0).tab_stop(true), + focused: false, + everything: false, + search: 0, + searching: false, + searched: false, + results: Vec::new(), + more: false, + error: None, + installed: Vec::new(), + loaded: false, + busy: None, + message: None, + updates: HashMap::new(), + confirm_remove: None, + tx, + rx, + } + } + + pub(super) fn note_focus(&mut self, window: &Window) { + self.focused = self.focus.is_focused(window); + } + + fn entry(&self, p: &Project) -> Option<&installed::Entry> { + self.installed + .iter() + .find(|e| e.source == p.source && e.project == p.id) + } +} + +/// `51404735` → `51.4M`. +fn count(n: u64) -> String { + match n { + 0..1_000 => n.to_string(), + 1_000..1_000_000 => format!("{:.1}k", n as f64 / 1e3), + _ => format!("{:.1}M", n as f64 / 1e6), + } +} + +/// A checksum as the page shows it: the algorithm and the first and last hex digits. +fn short_sum(checksum: &str) -> String { + let (algo, hex) = checksum.split_once(':').unwrap_or(("", checksum)); + if hex.len() <= 20 { + return checksum.to_string(); + } + format!("{algo} {}…{}", &hex[..12], &hex[hex.len() - 8..]) +} + +impl Launcher { + /// Called with the launcher's other work: what the background sent. + pub(super) fn mods_tick(&mut self) -> bool { + let mut changed = false; + while let Ok(event) = self.mods.rx.try_recv() { + changed = true; + let m = &mut self.mods; + match event { + Event::Found(search, offset, result) if search == m.search => { + m.searching = false; + m.searched = true; + match result { + Ok(found) => { + m.more = found.len() == PAGE; + m.results.truncate(offset); + m.results.extend(found); + m.error = None; + } + Err(e) => m.error = Some(e), + } + } + Event::Found(..) => {} + Event::Progress(line, f) => { + if let Some(busy) = &mut m.busy { + busy.1 = line; + busy.2 = f; + } + } + Event::Done(result, modpack) => { + m.busy = None; + m.message = Some(result); + m.installed = installed::Installed::load(&backend::game_home()).entries; + if modpack { + // The Modpacks page reads its list again. + self.packs_loaded = None; + } + } + Event::Updates(found) => m.updates = found, + } + } + changed + } + + fn mods_search(&mut self, offset: usize) { + let m = &mut self.mods; + m.search += 1; + m.searching = true; + if offset == 0 { + m.results.clear(); + m.more = false; + } + let query = Query { + everything: m.everything, + offset, + limit: PAGE, + ..Query::new(&m.text, m.kind) + }; + let (tx, search, source) = (m.tx.clone(), m.search, m.source); + std::thread::spawn(move || { + let result = browser::source(source) + .ok_or_else(|| format!("{} isn't set up.", source.label())) + .and_then(|s| s.search(&query)); + let _ = tx.send(Event::Found(search, offset, result)); + }); + } + + /// Looks for newer versions of what the browser installed. + fn mods_check_updates(&mut self) { + let entries = self.mods.installed.clone(); + if entries.is_empty() { + return; + } + let tx = self.mods.tx.clone(); + std::thread::spawn(move || { + let mut found = HashMap::new(); + for e in entries { + let Some(source) = browser::source(e.source) else { + continue; + }; + if let Ok(Some(v)) = installed::update_for(&*source, &e) { + found.insert((e.source, e.project.clone()), v.number); + } + } + let _ = tx.send(Event::Updates(found)); + }); + } + + /// Installs (or updates) a project on a thread: a pack into its folder, a modpack into + /// Modpacks. `known` is the project when the page has it; else it is asked for first. + fn mods_install(&mut self, source: SourceId, id: String, known: Option) { + if self.mods.busy.is_some() { + return; + } + self.mods.message = None; + self.mods.busy = Some((id.clone(), format!("Asking {}…", source.label()), 0.)); + self.mods.updates.remove(&(source, id.clone())); + let (tx, everything) = (self.mods.tx.clone(), self.mods.everything); + std::thread::spawn(move || { + let last = std::cell::Cell::new(-1); + let progress = |line: &str, f: f32| { + let pct = (f * 100.) as i32; + if last.replace(pct) != pct { + let _ = tx.send(Event::Progress(line.to_string(), f)); + } + }; + let mut modpack = false; + let result = browser::source(source) + .ok_or_else(|| format!("{} isn't set up.", source.label())) + .and_then(|source| { + let p = match known { + Some(p) => p, + None => source.project(&id)?, + }; + modpack = p.kind == PackKind::Modpack; + if modpack { + let folder = modpacks::ports_dir().join("downloads"); + let file = installed::fetch_modpack(&*source, &p, &folder, &|f| { + progress(&p.title, f) + })?; + let log = |line: String| progress(&line, 1.); + let pack = modpacks::import(&file, &log)?; + return Ok(format!( + "{} is imported: open it on the Modpacks page to port it.", + pack.title() + )); + } + let home = backend::game_home(); + let done = installed::install(&*source, &p, everything, &home, &progress)?; + let names: Vec = done + .iter() + .map(|e| format!("{} {}", e.title, e.number)) + .collect(); + let turn_on = match p.kind { + PackKind::ShaderPack => "Video Settings > Shader Packs", + _ => "Options > Resource Packs", + }; + Ok(format!( + "Installed {}, checksums checked. Turn it on in the game: {turn_on}.", + names.join(", ") + )) + }); + let _ = tx.send(Event::Done(result, modpack)); + }); + } + + fn mods_field(&mut self, cx: &mut Context) -> Stateful
{ + let t = self.theme; + let m = &self.mods; + let focused = m.focused; + let shown: String = { + let chars: Vec = m.text.chars().collect(); + chars[chars.len().saturating_sub(40)..].iter().collect() + }; + div() + .id("mods-search") + .track_focus(&m.focus) + .flex() + .items_center() + .w(px(320.)) + .h(px(theme::FIELD)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(theme::RADIUS)) + .border_1() + .border_color(if focused { t.accent } else { t.rule }) + .bg(t.surface) + .text_size(px(theme::UI.px)) + .cursor_text() + .child(if m.text.is_empty() && !focused { + div().text_color(t.muted).child("Search, then Enter") + } else { + div().text_color(t.ink).child(shown) + }) + .when(focused, |d| { + d.child(div().flex_none().w(px(1.)).h(px(16.)).bg(t.ink)) + }) + .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { + window.focus(&this.mods.focus); + cx.notify(); + })) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + let command = k.modifiers.control || k.modifiers.platform; + match type_key( + &mut this.mods.text, + false, + &k.key, + k.key_char.as_deref(), + command, + ) { + Key::Enter => this.mods_search(0), + Key::Escape => window.blur(), + Key::Paste => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + let line = text.lines().next().unwrap_or_default().trim().to_string(); + this.mods.text.push_str(&line); + } + } + Key::Edited => {} + Key::Pass => return, + } + if let Some((at, _)) = this.mods.text.char_indices().nth(100) { + this.mods.text.truncate(at); + } + cx.stop_propagation(); + cx.notify(); + })) + } + + pub(super) fn mods_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if !self.mods.loaded { + self.mods.loaded = true; + self.mods.installed = installed::Installed::load(&backend::game_home()).entries; + self.mods_check_updates(); + self.mods_search(0); + } + let header = page_header( + "Mods", + "Resource packs, shader packs and modpacks that Horizon loads. Each file is checked \ + against its source's checksum before it reaches your game folder.", + &t, + ); + let this = cx.entity().downgrade(); + let kinds = segments("mods-kind", &KINDS, self.mods.kind, &t, { + let this = this.clone(); + move |kind, _, cx| { + let _ = this.update(cx, |this, cx| { + if this.mods.kind != kind { + this.mods.kind = kind; + this.mods_search(0); + } + cx.notify(); + }); + } + }); + let everything = self.mods.everything; + let toggle = div() + .id("mods-everything") + .flex() + .items_center() + .gap(px(8.)) + .cursor_pointer() + .child(switch("mods-everything-switch", everything, &t)) + .child( + text(theme::LABEL) + .text_color(t.ink_soft) + .child("Show everything"), + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.mods.everything = !this.mods.everything; + this.mods_search(0); + cx.notify(); + })); + let source_note = if self.mods.curseforge { + segments("mods-source", &SOURCES, self.mods.source, &t, { + let this = this.clone(); + move |source, _, cx| { + let _ = this.update(cx, |this, cx| { + if this.mods.source != source { + this.mods.source = source; + this.mods_search(0); + } + cx.notify(); + }); + } + }) + .into_any_element() + } else { + text(theme::CAPTION) + .text_color(t.muted) + .child("From Modrinth. CurseForge comes once the launcher has its API key.") + .into_any_element() + }; + let controls = div() + .flex() + .flex_col() + .gap(px(12.)) + .child( + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(12.)) + .child(kinds) + .child(self.mods_field(cx)) + .child(toggle), + ) + .child(source_note); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(controls); + if let Some((_, line, f)) = &self.mods.busy { + page = page.child( + plate(&t) + .flex() + .flex_col() + .gap(px(8.)) + .p(px(16.)) + .child(caps("Installing").text_color(t.accent)) + .child( + text(theme::CAPTION) + .font_family(theme::MONO) + .text_color(t.ink_soft) + .truncate() + .child(format!("{line} {:.0}%", f * 100.)), + ), + ); + } + match &self.mods.message { + Some(Ok(done)) => { + page = page.child( + plate(&t) + .p(px(16.)) + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(done.clone()), + ) + } + Some(Err(e)) => page = page.child(notice(e.clone(), &t)), + None => {} + } + if let Some(list) = self.mods_installed_list(cx) { + page = page.child(list); + } + page.child(self.mods_results(cx)) + } + + fn mods_installed_list(&self, cx: &mut Context) -> Option
{ + let t = self.theme; + let kind = self.mods.kind; + let entries: Vec<&installed::Entry> = self + .mods + .installed + .iter() + .filter(|e| e.kind == kind) + .collect(); + if entries.is_empty() { + return None; + } + let busy = self.mods.busy.is_some(); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, e) in entries.into_iter().enumerate() { + let key = (e.source, e.project.clone()); + let mut right = div().flex().items_center().gap(px(8.)); + if let Some(number) = self.mods.updates.get(&key) { + let mut update = button( + SharedString::from(format!("mods-update-{}", e.project)), + format!("Update to {number}"), + Kind::Secondary, + &t, + ); + if busy { + update = disabled(update); + } else { + let (source, id) = key.clone(); + update = update.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_install(source, id.clone(), None); + cx.notify(); + })); + } + right = right.child(update); + } + let confirming = self.mods.confirm_remove.as_deref() == Some(e.project.as_str()); + let id = e.project.clone(); + let remove = button( + SharedString::from(format!("mods-remove-{}", e.project)), + 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.mods.confirm_remove.as_ref() == Some(&id) { + let home = backend::game_home(); + this.mods.message = Some( + installed::remove(&home, &id).map(|e| format!("Removed {}.", e.title)), + ); + this.mods.installed = installed::Installed::load(&home).entries; + this.mods.confirm_remove = None; + } else { + this.mods.confirm_remove = Some(id.clone()); + } + cx.notify(); + })); + right = right.child(remove); + let detail = div() + .flex() + .flex_col() + .child(format!( + "{} · from {}{} · {}", + e.number, + e.source.label(), + if e.dependency { + ", needed by another pack" + } else { + "" + }, + e.file + )) + .child( + div() + .font_family(theme::MONO) + .child(format!("checked: {}", short_sum(&e.checksum))), + ); + list = list.child(index_row( + i + 1, + e.title.clone(), + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + Some( + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(caps("Installed").text_color(t.muted)) + .child(list), + ) + } + + fn mods_results(&self, cx: &mut Context) -> Div { + let t = self.theme; + let m = &self.mods; + if let Some(e) = &m.error { + return div().child(notice(e.clone(), &t)); + } + if m.results.is_empty() { + let line = if m.searching || !m.searched { + "Searching…" + } else if m.everything { + "Nothing found." + } else { + "Nothing found that runs in Horizon. Show everything lists the rest." + }; + return centered(line, &t); + } + let busy = m.busy.as_ref().map(|b| b.0.as_str()); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in m.results.iter().enumerate() { + let support = p.support(); + let color = match support { + Support::Works => t.success, + Support::Partial(_) => t.accent, + Support::No(_) => t.muted, + }; + let mut right = div() + .flex() + .items_center() + .gap(px(8.)) + .child(caps(support.label()).flex_none().text_color(color)); + let page_url = p.page.clone(); + if !page_url.is_empty() { + right = right.child( + button( + SharedString::from(format!("mods-page-{}", p.id)), + "Page", + Kind::Ghost, + &t, + ) + .on_click(move |_, _, cx| cx.open_url(&page_url)), + ); + } + if busy == Some(p.id.as_str()) { + right = right.child(caps("Installing").text_color(t.accent)); + } else if m.entry(p).is_some() { + right = right.child(caps("Installed").text_color(t.muted)); + } else if support.installable() { + let label = if p.kind == PackKind::Modpack { + "Import" + } else { + "Install" + }; + let mut install = button( + SharedString::from(format!("mods-install-{}", p.id)), + label, + Kind::Secondary, + &t, + ); + if busy.is_some() { + install = disabled(install); + } else { + let p = p.clone(); + install = install.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_install(p.source, p.id.clone(), Some(p.clone())); + cx.notify(); + })); + } + right = right.child(install); + } + let mut by = Vec::new(); + if !p.author.is_empty() { + by.push(format!("by {}", p.author)); + } + by.push(format!("{} downloads", count(p.downloads))); + by.push(format!("from {}", p.source.label())); + if !p.license.is_empty() { + by.push(p.license.clone()); + } + let detail = div() + .flex() + .flex_col() + .child(div().truncate().child(p.summary.clone())) + .child(by.join(" · ")) + .children( + support + .reason() + .map(|r| div().text_color(t.ink_soft).child(r.to_string())), + ); + list = list.child(index_row( + i + 1, + p.title.clone(), + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + let mut out = div().flex().flex_col().child(list); + if m.more { + let mut more = button("mods-more", "More", Kind::Ghost, &t); + if m.searching { + more = disabled(more); + } else { + let offset = m.results.len(); + more = more.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_search(offset); + cx.notify(); + })); + } + out = out.child(div().flex().pt(px(16.)).child(more)); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_and_checksums_read_short() { + assert_eq!(count(999), "999"); + assert_eq!(count(1_500), "1.5k"); + assert_eq!(count(51_404_735), "51.4M"); + let sum = format!("SHA-512:{}", "ab".repeat(64)); + assert_eq!(short_sum(&sum), "SHA-512 abababababab…abababab"); + assert_eq!(short_sum("SHA-1:abcd"), "SHA-1:abcd"); + } +} diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index 625b6ffab..b1338f1aa 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -291,7 +291,7 @@ fn bytes(n: u64) -> String { /// A backup's date and kind from its name (`2026-10-19_11-28-57-manual.zip`, UTC), for people. /// What a key did in a one-line field. #[derive(Debug, PartialEq)] -enum Key { +pub(super) enum Key { Enter, Escape, /// Command/Ctrl-V: the caller pastes the clipboard's first line. @@ -303,7 +303,7 @@ enum Key { /// Types `key` into `text`. A `selected` suggestion is replaced by what's typed or pasted, and /// cleared by Backspace. -fn type_key( +pub(super) fn type_key( text: &mut String, selected: bool, key: &str,