From f53998674de95895558b99e00f572175293db3e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:37:12 +0200 Subject: [PATCH] Launcher mod browser: project pages, search filters, project icons and gallery A result's title opens its page in the launcher: icon, authors, downloads, followers, licence, verdict (for a Java mod, what ports and what doesn't) and Install, links, then Description (Markdown), Gallery and Versions tabs (browser::details, Source::details on Modrinth's project and members). Filters: sort (relevance, downloads, follows, newest, updated), loader, game version, environment and categories, from the source's tag lists. Icons and gallery images are fetched at run time over HTTPS from the sources' image CDNs only, size-capped, decoded and scaled to PNGs in a 128 MB disk cache (browser::images); a placeholder shows until they arrive. Vanilla's mark is a grass block drawn from the player's prepared game files. Modrinth's logo isn't shown: its branding is all rights reserved without written permission. Co-Authored-By: Claude Opus 5.5 --- docs/mod-browser.md | 35 ++ launcher/Cargo.toml | 2 +- launcher/src/browser.rs | 15 + launcher/src/browser/curseforge.rs | 7 +- launcher/src/browser/details.rs | 368 +++++++++++++++++ launcher/src/browser/images.rs | 265 +++++++++++++ launcher/src/browser/modrinth.rs | 69 +++- launcher/src/main.rs | 1 + launcher/src/mods_page.rs | 113 ++++-- launcher/src/mods_project.rs | 617 +++++++++++++++++++++++++++++ 10 files changed, 1435 insertions(+), 57 deletions(-) create mode 100644 launcher/src/browser/details.rs create mode 100644 launcher/src/browser/images.rs create mode 100644 launcher/src/mods_project.rs diff --git a/docs/mod-browser.md b/docs/mod-browser.md index 6601fea70..74959ab4c 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -71,6 +71,41 @@ report, **Port** and **Play** ([modpacks.md](modpacks.md)). Installed packs are file and the checksum they were checked against, with **Update to …** when a newer version runs and **Remove** (asked twice). +### Project pages, filters and icons + +A result's title opens its page inside the launcher, not in a web browser: its icon, authors, downloads, followers, +last update, licence and source, how well it runs (for a Java mod, what ports and what doesn't, from its check) with +**Install** or **Import**, the project's links (its page on the source, source code, issues, wiki, Discord, +donations; `https://` only, opened in the system browser), then three tabs: **Description** (the project's Markdown, +drawn by the launcher's renderer), **Gallery** and **Versions** (each version's date, loaders, game versions, file +and size, and the verdict of any version already checked). The data is `browser::details` (`Source::details`; on +Modrinth `GET /project/{id}` and `/project/{id}/members`, then `/project/{id}/version`). + +**Filters** sit above the results: the order (best match, relevance, downloads, follows, newest, updated) and, under +**Filters**, the loader, game version, environment (client, server) and categories, with the values the source lists +for the kind (Modrinth's `/tag/category`, `/tag/loader`, `/tag/game_version`, asked once per run). A loader or version +picked replaces the default (Java mod loaders and 26.3 for mods); a version other than 26.3 checks and installs the +newest file for 1.21 or later, as **Show everything** does. Changing tabs clears the filters. CurseForge support +is coming soon; its source already maps the order and the game version. + +**Icons and gallery images** are the projects' own, fetched at run time from the source's image server +(`browser::images`): HTTPS from `cdn.modrinth.com` (or CurseForge's `media.forgecdn.net` / `edge.forgecdn.net`) only, +at most 8 MB each, decoded (PNG, JPEG, WebP, GIF, at most 8192 pixels a side), scaled (icons 128 px, gallery 960 px) +and kept as PNGs in `mod-browser/images/` under the game folder, which is kept under 128 MB by dropping the oldest +files. A plate with the project's initial stands in until the icon arrives. Nothing of a project's art is in the +launcher or the repository. + +**Vanilla Minecraft** is marked with a grass block drawn at run time from the player's own prepared game files +(`assets/minecraft/textures/block/grass_block_*.png`, tinted with the plains grass colour): the game-version filter +shows it. No Mojang file or logo is in the launcher or the repository. + +**Source logos.** Modrinth's logo is not shown: Modrinth's own repository says its branding is all rights reserved and +"the use of Modrinth branding elements, including but not limited to the wrench-in-labyrinth logo, ... is strictly +prohibited without explicit written permission from Rinth, Inc." (`packages/assets/COPYING.md` in +[modrinth/code](https://github.com/modrinth/code/blob/main/packages/assets/COPYING.md)), and its +[terms](https://modrinth.com/legal/terms) ask for prior written permission to use its marks. Results name their source +in text ("from Modrinth") until Rinth, Inc. agrees. CurseForge support, and so its logo, is coming soon. + ## Installing, updating, removing `mod-browser.json` beside `options.txt` lists every file the browser installed: its source, project, version, file diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 1097d5675..006e35c5e 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -39,7 +39,7 @@ horizon-telemetry = { path = "../crates/horizon-telemetry" } getrandom = "0.3" # Players' heads on the Servers page, from the default skins in the player's own game files (already # in the lockfile through gpui). -image = { version = "0.25", default-features = false, features = ["png"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif"] } # Microsoft account secrets in the OS keychain: the Secret Service on Linux through oo7 (the same # build gpui uses), Keychain and Credential Manager through keyring. diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs index c4a6ff726..091560638 100644 --- a/launcher/src/browser.rs +++ b/launcher/src/browser.rs @@ -7,7 +7,9 @@ //! (`resourcepacks/`) and Java shader packs (`shaderpacks/`, Iris and OptiFine). Java code itself //! doesn't run in Horizon (docs/mods.md). pub mod curseforge; +pub mod details; pub mod download; +pub mod images; pub mod installed; pub mod java; pub mod modrinth; @@ -189,6 +191,7 @@ pub struct Query { pub everything: bool, pub offset: usize, pub limit: usize, + pub filters: details::Filters, } impl Query { @@ -199,6 +202,7 @@ impl Query { everything: false, offset: 0, limit: 20, + filters: details::Filters::default(), } } } @@ -210,6 +214,17 @@ pub trait Source: Send + Sync { fn project(&self, id: &str) -> Result; /// Versions, newest first. fn versions(&self, project: &Project) -> Result, String>; + /// The project's page: description, gallery, links, authors. + fn details(&self, project: &Project) -> Result { + Ok(details::Details { + body: project.summary.clone(), + ..details::Details::default() + }) + } + /// The values the search's filters can take for `kind`. + fn tags(&self, _kind: Kind) -> Result { + Ok(details::Tags::default()) + } /// Downloads one of its files into `folder`, checked ([`download::fetch`]). fn fetch( &self, diff --git a/launcher/src/browser/curseforge.rs b/launcher/src/browser/curseforge.rs index 04e722bba..0a7a04a5e 100644 --- a/launcher/src/browser/curseforge.rs +++ b/launcher/src/browser/curseforge.rs @@ -69,12 +69,15 @@ impl CurseForge { pub(super) fn search_url(query: &Query) -> String { let mut url = format!( - "{API}/mods/search?gameId={MINECRAFT}&classId={}&sortField=2&sortOrder=desc&index={}&pageSize={}", + "{API}/mods/search?gameId={MINECRAFT}&classId={}&sortField={}&sortOrder=desc&index={}&pageSize={}", class(query.kind), + query.filters.sort(&query.text).curseforge(), query.offset, query.limit.clamp(1, 50), ); - if !query.everything && matches!(query.kind, Kind::ResourcePack | Kind::Mod) { + if let Some(v) = &query.filters.game_version { + url.push_str(&format!("&gameVersion={}", encode(v))); + } else if !query.everything && matches!(query.kind, Kind::ResourcePack | Kind::Mod) { url.push_str(&format!("&gameVersion={GAME}")); } if !query.text.is_empty() { diff --git a/launcher/src/browser/details.rs b/launcher/src/browser/details.rs new file mode 100644 index 000000000..004db12b4 --- /dev/null +++ b/launcher/src/browser/details.rs @@ -0,0 +1,368 @@ +//! What the browser shows beyond a search hit: a project's page (description, gallery, links, +//! authors) and the search's filters (categories, loader, game version, environment, sort), with +//! the lists of values each source offers for them. Data only: `mods_page` draws it. +use super::{Kind, GAME}; +use serde_json::Value; + +/// How results are ordered. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Sort { + #[default] + Relevance, + Downloads, + Follows, + Newest, + Updated, +} + +impl Sort { + pub const ALL: [Sort; 5] = [ + Sort::Relevance, + Sort::Downloads, + Sort::Follows, + Sort::Newest, + Sort::Updated, + ]; + pub fn label(self) -> &'static str { + match self { + Sort::Relevance => "Relevance", + Sort::Downloads => "Downloads", + Sort::Follows => "Follows", + Sort::Newest => "Newest", + Sort::Updated => "Updated", + } + } + /// Modrinth's `index`. + pub fn modrinth(self) -> &'static str { + match self { + Sort::Relevance => "relevance", + Sort::Downloads => "downloads", + Sort::Follows => "follows", + Sort::Newest => "newest", + Sort::Updated => "updated", + } + } + /// CurseForge's `sortField` (`ModsSearchSortField`). + pub fn curseforge(self) -> u8 { + match self { + Sort::Relevance | Sort::Follows => 2, + Sort::Downloads => 6, + Sort::Newest => 11, + Sort::Updated => 3, + } + } +} + +/// Where a project runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Environment { + Client, + Server, +} + +impl Environment { + pub const ALL: [Environment; 2] = [Environment::Client, Environment::Server]; + pub fn label(self) -> &'static str { + match self { + Environment::Client => "Client", + Environment::Server => "Server", + } + } +} + +/// A search's filters. Empty: the browser's defaults (what runs in Horizon). +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Filters { + /// Every one of these categories (`decoration`, `worldgen`...). + pub categories: Vec, + /// One loader (`neoforge`, `fabric`, `iris`...), in place of the kind's defaults. + pub loader: Option, + /// One Minecraft version, in place of the one Horizon plays. + pub game_version: Option, + pub environment: Option, + /// None: by relevance with search text, else by downloads. + pub sort: Option, +} + +impl Filters { + /// The sort a search uses. + pub fn sort(&self, text: &str) -> Sort { + self.sort.unwrap_or(if text.is_empty() { + Sort::Downloads + } else { + Sort::Relevance + }) + } + /// A game version other than the one Horizon plays was asked for. + pub fn other_version(&self) -> bool { + self.game_version.as_deref().is_some_and(|v| v != GAME) + } +} + +/// One value a filter can take. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tag { + pub name: String, + /// The group a category is in on its source (`categories`, `features`, `resolutions`). + pub header: String, +} + +/// The values each filter can take for a kind. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Tags { + pub categories: Vec, + pub loaders: Vec, + /// Release versions, newest first. + pub game_versions: Vec, +} + +/// A gallery image. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Image { + pub url: String, + pub title: String, + pub description: String, + pub featured: bool, +} + +/// A link a project gives: its source, issues, wiki, Discord, donations. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Link { + pub label: String, + pub url: String, +} + +/// A project's page. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Details { + /// Markdown (Modrinth's body; HTML blocks in it are left as text the renderer skips). + pub body: String, + pub gallery: Vec, + pub links: Vec, + pub authors: Vec, + pub followers: u64, + pub published: String, + pub updated: String, + pub categories: Vec, + /// `required`, `optional`, `unsupported` or `unknown`. + pub client_side: String, + pub server_side: String, +} + +fn strings(v: &Value) -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect() +} + +fn text(v: &Value) -> String { + v.as_str().unwrap_or_default().to_owned() +} + +/// Only `https://` links are kept: a page never opens another scheme. +fn https(url: &str) -> Option { + url.starts_with("https://").then(|| url.to_owned()) +} + +/// Modrinth's `GET /project/{id}` and `GET /project/{id}/members`. +pub fn modrinth_details(project: &Value, members: &Value) -> Details { + let mut gallery: Vec<(i64, Image)> = project["gallery"] + .as_array() + .into_iter() + .flatten() + .filter_map(|g| { + Some(( + g["ordering"].as_i64().unwrap_or(0), + Image { + url: https(g["url"].as_str()?)?, + title: text(&g["title"]), + description: text(&g["description"]), + featured: g["featured"].as_bool().unwrap_or(false), + }, + )) + }) + .collect(); + gallery.sort_by_key(|(order, i)| (!i.featured, *order)); + let mut links = Vec::new(); + for (key, label) in [ + ("source_url", "Source"), + ("issues_url", "Issues"), + ("wiki_url", "Wiki"), + ("discord_url", "Discord"), + ] { + if let Some(url) = project[key].as_str().and_then(https) { + links.push(Link { + label: label.into(), + url, + }); + } + } + for d in project["donation_urls"].as_array().into_iter().flatten() { + if let Some(url) = d["url"].as_str().and_then(https) { + links.push(Link { + label: format!("Donate ({})", text(&d["platform"])), + url, + }); + } + } + let mut owners: Vec<(bool, String)> = members + .as_array() + .into_iter() + .flatten() + .filter_map(|m| { + let name = m["user"]["username"].as_str()?.to_owned(); + Some((m["role"].as_str() != Some("Owner"), name)) + }) + .collect(); + owners.sort(); + let mut categories = strings(&project["categories"]); + categories.extend(strings(&project["additional_categories"])); + Details { + body: text(&project["body"]), + gallery: gallery.into_iter().map(|(_, i)| i).collect(), + links, + authors: owners.into_iter().map(|(_, n)| n).collect(), + followers: project["followers"].as_u64().unwrap_or(0), + published: text(&project["published"]), + updated: text(&project["updated"]), + categories, + client_side: text(&project["client_side"]), + server_side: text(&project["server_side"]), + } +} + +/// Modrinth's `/tag/category`, `/tag/loader` and `/tag/game_version` for one project type. +pub fn modrinth_tags( + project_type: &str, + categories: &Value, + loaders: &Value, + versions: &Value, +) -> Tags { + let loader_names: Vec = loaders + .as_array() + .into_iter() + .flatten() + .filter(|l| { + l["supported_project_types"] + .as_array() + .is_some_and(|t| t.iter().any(|x| x == project_type)) + }) + .filter_map(|l| l["name"].as_str().map(str::to_owned)) + .collect(); + let mut categories: Vec = categories + .as_array() + .into_iter() + .flatten() + .filter(|c| c["project_type"] == project_type) + .filter_map(|c| { + let name = c["name"].as_str()?.to_owned(); + // Loaders are listed as categories too; the loader filter has them. + (!loader_names.contains(&name)).then(|| Tag { + name, + header: text(&c["header"]), + }) + }) + .collect(); + categories.sort_by(|a, b| (&a.header, &a.name).cmp(&(&b.header, &b.name))); + Tags { + categories, + loaders: loader_names, + game_versions: versions + .as_array() + .into_iter() + .flatten() + .filter(|v| v["version_type"] == "release") + .filter_map(|v| v["version"].as_str().map(str::to_owned)) + .collect(), + } +} + +/// The loaders a kind lists by default, when no loader is picked: Java mod loaders for mods, +/// Iris and OptiFine for shader packs (unless `everything`). +pub fn default_loaders(kind: Kind, everything: bool) -> Vec<&'static str> { + match kind { + Kind::Mod => super::java::LOADERS.to_vec(), + Kind::ShaderPack if !everything => vec!["iris", "optifine"], + _ => Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_modrinth_page() { + let project = json!({ + "body": "# Fences\nMore fences.", + "gallery": [ + {"url": "https://cdn.modrinth.com/data/x/images/b.png", "featured": false, "ordering": 0, "title": "B"}, + {"url": "https://cdn.modrinth.com/data/x/images/a.png", "featured": true, "ordering": 5, "title": "A"}, + {"url": "http://example.com/c.png", "featured": false, "ordering": 1} + ], + "source_url": "https://github.com/x/y", "issues_url": "javascript:alert(1)", + "wiki_url": null, "discord_url": "https://discord.gg/x", + "donation_urls": [{"platform": "Ko-fi", "url": "https://ko-fi.com/x"}], + "followers": 12, "categories": ["decoration"], "additional_categories": ["utility"], + "client_side": "required", "server_side": "required" + }); + let members = json!([ + {"user": {"username": "helper"}, "role": "Member"}, + {"user": {"username": "Macaw"}, "role": "Owner"} + ]); + let d = modrinth_details(&project, &members); + assert_eq!( + d.gallery + .iter() + .map(|i| i.title.as_str()) + .collect::>(), + ["A", "B"] + ); + assert_eq!( + d.links.iter().map(|l| l.label.as_str()).collect::>(), + ["Source", "Discord", "Donate (Ko-fi)"] + ); + assert_eq!(d.authors, ["Macaw", "helper"]); + assert_eq!(d.categories, ["decoration", "utility"]); + assert_eq!(d.followers, 12); + } + + #[test] + fn modrinth_tags_by_project_type() { + let categories = json!([ + {"name": "decoration", "project_type": "mod", "header": "categories"}, + {"name": "fabric", "project_type": "mod", "header": "loaders"}, + {"name": "16x", "project_type": "resourcepack", "header": "resolutions"} + ]); + let loaders = json!([ + {"name": "fabric", "supported_project_types": ["mod", "modpack"]}, + {"name": "iris", "supported_project_types": ["shader"]} + ]); + let versions = json!([ + {"version": "26.3", "version_type": "release"}, + {"version": "26.4-snapshot-1", "version_type": "snapshot"} + ]); + let t = modrinth_tags("mod", &categories, &loaders, &versions); + assert_eq!(t.categories.len(), 1); + assert_eq!(t.categories[0].name, "decoration"); + assert_eq!(t.loaders, ["fabric"]); + assert_eq!(t.game_versions, ["26.3"]); + } + + #[test] + fn sorts_default_to_relevance_with_text() { + let f = Filters::default(); + assert_eq!(f.sort(""), Sort::Downloads); + assert_eq!(f.sort("fences"), Sort::Relevance); + let f = Filters { + sort: Some(Sort::Updated), + game_version: Some("1.21.1".into()), + ..Filters::default() + }; + assert_eq!(f.sort("x"), Sort::Updated); + assert!(f.other_version()); + } +} diff --git a/launcher/src/browser/images.rs b/launcher/src/browser/images.rs new file mode 100644 index 000000000..fee2f219e --- /dev/null +++ b/launcher/src/browser/images.rs @@ -0,0 +1,265 @@ +//! Project icons and gallery images, fetched at run time from the sources' image servers and +//! kept on disk: nothing of a project's art is in the launcher. A URL is fetched only over HTTPS +//! from Modrinth's or CurseForge's CDN, at most [`MAX_DOWNLOAD`] bytes, decoded (PNG, JPEG, WebP, +//! GIF), scaled down and stored as a PNG the UI draws; the cache is kept under [`MAX_CACHE`] by +//! dropping the oldest files. +use sha1::{Digest, Sha1}; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +/// Hosts images may come from. +const HOSTS: [&str; 3] = [ + "https://cdn.modrinth.com/", + "https://media.forgecdn.net/", + "https://edge.forgecdn.net/", +]; +/// The most an image may weigh before decoding. +pub const MAX_DOWNLOAD: u64 = 8 << 20; +/// The most the cache keeps on disk. +pub const MAX_CACHE: u64 = 128 << 20; +/// Pixels: an icon's side, a gallery image's longest side. +pub const ICON: u32 = 128; +pub const GALLERY: u32 = 960; + +fn dir(home: &Path) -> PathBuf { + home.join("mod-browser/images") +} + +/// Why `url` is never fetched. +pub fn refuse(url: &str) -> Option<&'static str> { + if !HOSTS.iter().any(|h| url.starts_with(h)) { + return Some("not on Modrinth's or CurseForge's image servers over HTTPS"); + } + if url.len() > 2048 || url.contains(char::is_whitespace) { + return Some("not a plain URL"); + } + None +} + +/// Where the image of `url` scaled to `size` is kept. +pub fn path(home: &Path, url: &str, size: u32) -> PathBuf { + let hash: String = Sha1::digest(url.as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + dir(home).join(format!("{hash}-{size}.png")) +} + +/// The image if it is cached already. +pub fn cached(home: &Path, url: &str, size: u32) -> Option { + let p = path(home, url, size); + p.is_file().then_some(p) +} + +/// The image of `url`, no larger than `size` pixels a side: the cached one, else fetched, +/// decoded, scaled and stored. +pub fn fetch(home: &Path, url: &str, size: u32) -> Result { + if let Some(p) = cached(home, url, size) { + return Ok(p); + } + if let Some(why) = refuse(url) { + return Err(format!("{url}: {why}")); + } + let response = super::download::agent() + .get(url) + .call() + .map_err(|e| format!("{url}: {e}"))?; + let mut bytes = Vec::new(); + response + .into_reader() + .take(MAX_DOWNLOAD + 1) + .read_to_end(&mut bytes) + .map_err(|e| format!("{url}: {e}"))?; + if bytes.len() as u64 > MAX_DOWNLOAD { + return Err(format!("{url}: larger than {} MB", MAX_DOWNLOAD >> 20)); + } + store(home, url, size, &bytes) +} + +/// Decodes `bytes`, scales them to fit `size` and writes the PNG. +pub fn store(home: &Path, url: &str, size: u32, bytes: &[u8]) -> Result { + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .map_err(|e| e.to_string())?; + let mut limits = image::Limits::default(); + limits.max_image_width = Some(8192); + limits.max_image_height = Some(8192); + limits.max_alloc = Some(256 << 20); + reader.limits(limits); + let decoded = reader.decode().map_err(|e| format!("{url}: {e}"))?; + let scaled = if decoded.width() > size || decoded.height() > size { + decoded.resize(size, size, image::imageops::FilterType::Triangle) + } else { + decoded + }; + let target = path(home, url, size); + let folder = dir(home); + fs::create_dir_all(&folder).map_err(|e| format!("{}: {e}", folder.display()))?; + let part = target.with_extension("part"); + scaled + .save_with_format(&part, image::ImageFormat::Png) + .map_err(|e| format!("{}: {e}", part.display()))?; + fs::rename(&part, &target).map_err(|e| format!("{}: {e}", target.display()))?; + prune(&folder, MAX_CACHE); + Ok(target) +} + +/// Drops the oldest files until the folder holds at most `max` bytes. +fn prune(folder: &Path, max: u64) { + let mut files: Vec<(std::time::SystemTime, u64, PathBuf)> = fs::read_dir(folder) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let m = e.metadata().ok()?; + Some((m.modified().ok()?, m.len(), e.path())) + }) + .collect(); + let mut total: u64 = files.iter().map(|f| f.1).sum(); + files.sort(); + for (_, len, path) in files { + if total <= max { + break; + } + if fs::remove_file(&path).is_ok() { + total -= len; + } + } +} + +/// Vanilla Minecraft's mark: a grass block drawn from the player's own prepared game files +/// (`/assets/minecraft/textures/block/`), never shipped. Kept beside the cache. +pub fn grass_block(home: &Path, resources: &Path) -> Option { + let target = dir(home).join("grass-block.png"); + if target.is_file() { + return Some(target); + } + let textures = resources.join("assets/minecraft/textures/block"); + let load = |name: &str| image::open(textures.join(name)).ok().map(|i| i.to_rgba8()); + let (top, side, overlay) = ( + load("grass_block_top.png")?, + load("grass_block_side.png")?, + load("grass_block_side_overlay.png")?, + ); + let icon = draw_block(&top, &side, &overlay); + fs::create_dir_all(dir(home)).ok()?; + icon.save(&target).ok()?; + Some(target) +} + +/// The plains grass colour vanilla's grass block item shows (`GrassColor.getDefaultColor` +/// is the colormap at 0.5, 1.0: `#91BD59`). +const GRASS: [u8; 3] = [0x91, 0xBD, 0x59]; + +/// An isometric block, 64 pixels a side, from 16x16 faces: the top tinted, the sides with their +/// tinted overlay, the left side shaded as the game shades a side facing away from the light. +fn draw_block( + top: &image::RgbaImage, + side: &image::RgbaImage, + overlay: &image::RgbaImage, +) -> image::RgbaImage { + let size = 64u32; + let mut out = image::RgbaImage::new(size, size); + let at = |img: &image::RgbaImage, u: f32, v: f32| { + let (w, h) = (img.width().min(16), img.height().min(16)); + let x = ((u * w as f32) as u32).min(w - 1); + let y = ((v * h as f32) as u32).min(h - 1); + *img.get_pixel(x, y) + }; + let tint = |p: image::Rgba, shade: f32| { + let mut q = p; + for c in 0..3 { + q[c] = (p[c] as f32 * GRASS[c] as f32 / 255. * shade) as u8; + } + q + }; + let shade = |p: image::Rgba, s: f32| { + let mut q = p; + for c in 0..3 { + q[c] = (p[c] as f32 * s) as u8; + } + q + }; + let side_px = |u: f32, v: f32, s: f32| { + let o = at(overlay, u, v); + if o[3] > 0 { + tint(o, s) + } else { + shade(at(side, u, v), s) + } + }; + // The cube: the top face a diamond, two sides below it. + let (cx, h) = (size as f32 / 2., size as f32 / 4.); + for y in 0..size { + for x in 0..size { + let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); + let dx = (px - cx) / cx; + let dy = (py - h) / h; + let u = (dy + dx) / 2. + 0.5; + let v = (dy - dx) / 2. + 0.5; + let pixel = if (0. ..1.).contains(&u) && (0. ..1.).contains(&v) { + Some(tint(at(top, u, v), 1.0)) + } else if px < cx { + let u = px / cx; + let v = (py - h - u * h) / (2. * h); + (0. ..1.).contains(&v).then(|| side_px(u, v, 0.8)) + } else { + let u = (px - cx) / cx; + let v = (py - 2. * h + u * h) / (2. * h); + (0. ..1.).contains(&v).then(|| side_px(u, v, 0.6)) + }; + if let Some(p) = pixel { + out.put_pixel(x, y, p); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_sources_image_servers() { + assert!(refuse("https://cdn.modrinth.com/data/AANobbMI/icon.png").is_none()); + assert!(refuse("https://media.forgecdn.net/avatars/1/2.png").is_none()); + assert!(refuse("http://cdn.modrinth.com/data/x/icon.png").is_some()); + assert!(refuse("https://cdn.modrinth.com.evil.example/x.png").is_some()); + assert!(refuse("https://example.com/x.png").is_some()); + } + + #[test] + fn images_are_scaled_stored_and_pruned() { + let home = std::env::temp_dir().join(format!("horizon-images-{}", std::process::id())); + let _ = fs::remove_dir_all(&home); + let big = image::RgbaImage::from_pixel(300, 150, image::Rgba([1, 2, 3, 255])); + let mut png = Vec::new(); + big.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let url = "https://cdn.modrinth.com/data/x/icon.png"; + let p = store(&home, url, ICON, &png).unwrap(); + assert_eq!(cached(&home, url, ICON), Some(p.clone())); + assert_eq!(image::open(&p).unwrap().width(), ICON); + assert!(store(&home, url, ICON, b"not an image").is_err()); + prune(&dir(&home), 0); + assert!(cached(&home, url, ICON).is_none()); + fs::remove_dir_all(&home).unwrap(); + } + + #[test] + fn a_grass_block_from_faces() { + let face = |c: [u8; 4]| image::RgbaImage::from_pixel(16, 16, image::Rgba(c)); + let icon = draw_block( + &face([200, 200, 200, 255]), + &face([120, 80, 50, 255]), + &face([0, 0, 0, 0]), + ); + // The top is tinted grass, the sides dirt shaded, the corners empty. + assert_eq!(icon.get_pixel(32, 16)[1], (200. * 0xBD as f32 / 255.) as u8); + assert_eq!(icon.get_pixel(4, 40).0, [96, 64, 40, 255]); + assert_eq!(icon.get_pixel(60, 40).0, [72, 48, 30, 255]); + assert_eq!(icon.get_pixel(1, 1)[3], 0); + } +} diff --git a/launcher/src/browser/modrinth.rs b/launcher/src/browser/modrinth.rs index 77b5475bb..3fde04493 100644 --- a/launcher/src/browser/modrinth.rs +++ b/launcher/src/browser/modrinth.rs @@ -1,5 +1,5 @@ //! Modrinth's public API (api.modrinth.com/v2): no key, files with SHA-512 and SHA-1. -use super::{FileRef, Kind, Project, Query, Source, SourceId, Version, GAME}; +use super::{details, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME}; use serde_json::Value; const API: &str = "https://api.modrinth.com/v2"; @@ -23,26 +23,34 @@ fn kind_of(project_type: &str) -> Option { .find(|k| self::project_type(*k) == project_type) } -/// The search's facets (AND of ORs): the kind, and unless `everything` what runs. +/// The search's facets (AND of ORs): the kind, the filters, and unless `everything` what runs. pub(super) fn facets(query: &Query) -> String { + let f = &query.filters; let mut all = vec![vec![format!("project_type:{}", project_type(query.kind))]]; - if !query.everything { - match query.kind { - Kind::ResourcePack => all.push(vec![format!("versions:{GAME}")]), - Kind::ShaderPack => { - all.push(vec!["categories:iris".into(), "categories:optifine".into()]) - } - Kind::Modpack => {} - Kind::Mod => all.push(vec![format!("versions:{GAME}")]), + match &f.game_version { + Some(v) => all.push(vec![format!("versions:{v}")]), + None if !query.everything && matches!(query.kind, Kind::ResourcePack | Kind::Mod) => { + all.push(vec![format!("versions:{GAME}")]) } + None => {} } - if query.kind == Kind::Mod { - all.push( - super::java::LOADERS - .iter() - .map(|l| format!("categories:{l}")) - .collect(), - ); + let loaders: Vec = match &f.loader { + Some(l) => vec![format!("categories:{l}")], + None => details::default_loaders(query.kind, query.everything) + .iter() + .map(|l| format!("categories:{l}")) + .collect(), + }; + if !loaders.is_empty() { + all.push(loaders); + } + for c in &f.categories { + all.push(vec![format!("categories:{c}")]); + } + match f.environment { + Some(details::Environment::Client) => all.push(vec!["client_side!=unsupported".into()]), + Some(details::Environment::Server) => all.push(vec!["server_side!=unsupported".into()]), + None => {} } serde_json::to_string(&all).unwrap_or_default() } @@ -51,11 +59,7 @@ pub(super) fn search_url(query: &Query) -> String { let mut url = format!( "{API}/search?facets={}&index={}&offset={}&limit={}", encode(&facets(query)), - if query.text.is_empty() { - "downloads" - } else { - "relevance" - }, + query.filters.sort(&query.text).modrinth(), query.offset, query.limit.clamp(1, 100), ); @@ -193,6 +197,27 @@ impl Source for Modrinth { all.sort_by(|a, b| b.published.cmp(&a.published)); Ok(all) } + + fn details(&self, project: &Project) -> Result { + let id = encode(&project.id); + let p = get(&format!("{API}/project/{id}"))?; + let members = get(&format!("{API}/project/{id}/members")).unwrap_or_default(); + Ok(details::modrinth_details(&p, &members)) + } + + fn tags(&self, kind: Kind) -> Result { + static TAGS: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut cached = TAGS.lock().map_err(|_| "tags".to_string())?; + if cached.is_none() { + *cached = Some(( + get(&format!("{API}/tag/category"))?, + get(&format!("{API}/tag/loader"))?, + get(&format!("{API}/tag/game_version"))?, + )); + } + let (c, l, v) = cached.as_ref().expect("filled above"); + Ok(details::modrinth_tags(project_type(kind), c, l, v)) + } } fn get(url: &str) -> Result { diff --git a/launcher/src/main.rs b/launcher/src/main.rs index bb1e8dceb..5456c235a 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -9,6 +9,7 @@ mod markdown; mod mcp; mod modpacks_page; mod mods_page; +mod mods_project; mod perf; mod scrollbar; mod servers_page; diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs index fd6a24b76..e66c02490 100644 --- a/launcher/src/mods_page.rs +++ b/launcher/src/mods_page.rs @@ -31,6 +31,8 @@ pub(super) enum Event { Updates(HashMap<(SourceId, String), String>), /// A Java mod's check: its jar read, or why it couldn't be. Checked((SourceId, String), Result, String>), + /// A project page's part, an image or a filter's values (`mods_project`). + Loaded(super::mods_project::Loaded), } /// Where a Java mod's check is. @@ -41,8 +43,8 @@ pub(super) enum Checking { } pub(super) struct Mods { - kind: PackKind, - source: SourceId, + pub(super) kind: PackKind, + pub(super) source: SourceId, text: String, focus: FocusHandle, pub(super) focused: bool, @@ -57,13 +59,15 @@ pub(super) struct Mods { installed: Vec, loaded: bool, /// The project being installed, and the line and fraction of its download. - busy: Option<(String, String, f32)>, + pub(super) busy: Option<(String, String, f32)>, message: Option>, updates: HashMap<(SourceId, String), String>, confirm_remove: Option, /// Java mods' checks, by source and project. - checks: HashMap<(SourceId, String), Checking>, - tx: Sender, + pub(super) checks: HashMap<(SourceId, String), Checking>, + /// The project page, filters and images. + pub(super) browse: super::mods_project::Browse, + pub(super) tx: Sender, rx: Receiver, } @@ -90,6 +94,7 @@ impl Mods { updates: HashMap::new(), confirm_remove: None, checks: HashMap::new(), + browse: Default::default(), tx, rx, } @@ -99,14 +104,14 @@ impl Mods { self.focused = self.focus.is_focused(window); } - fn entry(&self, p: &Project) -> Option<&installed::Entry> { + pub(super) fn entry(&self, p: &Project) -> Option<&installed::Entry> { self.installed .iter() .find(|e| e.source == p.source && e.project == p.id) } /// How well a result runs: a Java mod's from its check once it has one. - fn support(&self, p: &Project) -> Support { + pub(super) fn support(&self, p: &Project) -> Support { let metadata = p.support(); if p.kind != PackKind::Mod || !metadata.installable() { return metadata; @@ -142,6 +147,7 @@ impl Launcher { pub(super) fn mods_tick(&mut self) -> bool { let mut changed = false; let mut to_check = Vec::new(); + let mut loaded = Vec::new(); while let Ok(event) = self.mods.rx.try_recv() { changed = true; let m = &mut self.mods; @@ -184,13 +190,17 @@ impl Launcher { }; m.checks.insert(key, state); } + Event::Loaded(l) => loaded.push(l), } } self.mods_check(to_check); + for l in loaded { + self.mods_loaded(l); + } changed } - fn mods_search(&mut self, offset: usize) { + pub(super) fn mods_search(&mut self, offset: usize) { let m = &mut self.mods; m.search += 1; m.searching = true; @@ -202,6 +212,7 @@ impl Launcher { everything: m.everything, offset, limit: PAGE, + filters: m.browse.filters.clone(), ..Query::new(&m.text, m.kind) }; let (tx, search, source) = (m.tx.clone(), m.search, m.source); @@ -228,7 +239,9 @@ impl Launcher { for p in &todo { m.checks.insert((p.source, p.id.clone()), Checking::Running); } - let (tx, everything) = (m.tx.clone(), m.everything); + // A version other than 26.3 asked for: check the newest file for 1.21 and later. + let everything = m.everything || m.browse.filters.other_version(); + let tx = m.tx.clone(); let queue = std::sync::Mutex::new(todo.into_iter()); std::thread::spawn(move || { let home = backend::game_home(); @@ -273,14 +286,15 @@ impl Launcher { /// 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) { + pub(super) 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); + let everything = self.mods.everything || self.mods.browse.filters.other_version(); + let tx = self.mods.tx.clone(); std::thread::spawn(move || { let last = std::cell::Cell::new(-1); let progress = |line: &str, f: f32| { @@ -429,6 +443,9 @@ impl Launcher { let _ = this.update(cx, |this, cx| { if this.mods.kind != kind { this.mods.kind = kind; + // Categories and loaders differ by kind. + this.mods.browse.filters = Default::default(); + this.mods.browse.open = None; this.mods_search(0); } cx.notify(); @@ -492,15 +509,39 @@ impl Launcher { .child(self.mods_field(cx)) .child(toggle), ) - .child(source_note); + .child(source_note) + .child(self.mods_filters(cx)); + if let Some(project) = self.mods_project_page(cx) { + return div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .children(self.mods_busy_plate()) + .child(project); + } let mut page = div() .flex() .flex_col() .gap(px(32.)) .child(header) .child(controls); + page = page.children(self.mods_busy_plate()); + if self.mods.kind == PackKind::Modpack { + page = page.child(self.imported_packs(cx)); + } + if let Some(list) = self.mods_installed_list(cx) { + page = page.child(list); + } + page.child(self.mods_results(cx)) + } + + /// The install under way and the last install's answer. + pub(super) fn mods_busy_plate(&self) -> Vec
{ + let t = self.theme; + let mut out = Vec::new(); if let Some((_, line, f)) = &self.mods.busy { - page = page.child( + out.push( plate(&t) .flex() .flex_col() @@ -517,25 +558,17 @@ impl Launcher { ); } 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)), + Some(Ok(done)) => out.push( + plate(&t) + .p(px(16.)) + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(done.clone()), + ), + Some(Err(e)) => out.push(notice(e.clone(), &t)), None => {} } - if self.mods.kind == PackKind::Modpack { - page = page.child(self.imported_packs(cx)); - } - if let Some(list) = self.mods_installed_list(cx) { - page = page.child(list); - } - page.child(self.mods_results(cx)) + out } fn mods_installed_list(&self, cx: &mut Context) -> Option
{ @@ -650,8 +683,10 @@ impl Launcher { ) } - fn mods_results(&self, cx: &mut Context) -> Div { + fn mods_results(&mut self, cx: &mut Context) -> Div { let t = self.theme; + let found = self.mods.results.clone(); + let icons: Vec = found.iter().map(|p| self.mods_icon(p, 40.)).collect(); let m = &self.mods; if let Some(e) = &m.error { return div().child(notice(e.clone(), &t)); @@ -667,6 +702,7 @@ impl Launcher { return centered(line, &t); } let busy = m.busy.as_ref().map(|b| b.0.as_str()); + let mut icons = icons.into_iter(); let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); for (i, p) in m.results.iter().enumerate() { let support = m.support(p); @@ -746,9 +782,22 @@ impl Launcher { .reason() .map(|r| div().text_color(t.ink_soft).child(r.to_string())), ); + let open = p.clone(); + let name = div() + .id(SharedString::from(format!("mods-open-{}", p.id))) + .flex() + .items_center() + .gap(px(12.)) + .cursor_pointer() + .child(icons.next().expect("one icon per result")) + .child(div().hover(|s| s.underline()).child(p.title.clone())) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_open(open.clone()); + cx.notify(); + })); list = list.child(index_row( i + 1, - p.title.clone(), + name, Some(detail.into_any_element()), Some(right.into_any_element()), &t, diff --git a/launcher/src/mods_project.rs b/launcher/src/mods_project.rs new file mode 100644 index 000000000..ef1d97975 --- /dev/null +++ b/launcher/src/mods_project.rs @@ -0,0 +1,617 @@ +//! The Mods page's project page, search filters and project icons (`horizon_launcher::browser`: +//! `details` for the data, `images` for the icons and gallery). Drawn only with the launcher's +//! shared components, so a restyle of those restyles this. +//! +//! - A result's title opens its page inside the launcher: icon, author, downloads, followers, +//! licence, how well it runs and Install, then Description (Markdown), Gallery, Versions and +//! the project's links. +//! - Filters: sort, loader, game version, environment and categories, with the values the +//! source lists for the kind. +//! - Icons and gallery images come from the source's image servers at run time, cached on disk; +//! a placeholder stands in until one arrives. +use super::mods_page::{Checking, Event}; +use super::*; +use gpui::img; +use horizon_launcher::browser::{ + self, + details::{Details, Environment, Filters, Sort, Tags}, + images, java, Kind as PackKind, Project, SourceId, Support, Version, +}; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; + +/// A project page's tabs. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Tab { + Description, + Gallery, + Versions, +} + +const TABS: [(Tab, &str); 3] = [ + (Tab::Description, "Description"), + (Tab::Gallery, "Gallery"), + (Tab::Versions, "Versions"), +]; + +/// The open project page. +pub(super) struct Opened { + pub(super) project: Project, + tab: Tab, + details: Option>, + versions: Option, String>>, +} + +/// The project page, filters and images' share of the Mods page's state. +#[derive(Default)] +pub(super) struct Browse { + pub(super) open: Option, + pub(super) filters: Filters, + pub(super) show_filters: bool, + tags: HashMap<(SourceId, PackKind), Tags>, + tags_asked: HashSet<(SourceId, PackKind)>, + /// Images on disk, by URL and size; `None` while they load or when they failed. + images: HashMap<(String, u32), Option>, + image_queue: Option>, +} + +/// What the background sends this module. +pub(super) enum Loaded { + Details((SourceId, String), Result), + Versions((SourceId, String), Result, String>), + Image((String, u32), Option), + Tags((SourceId, PackKind), Result), +} + +/// Images fetched at once. +const IMAGE_WORKERS: usize = 4; + +impl Launcher { + pub(super) fn mods_loaded(&mut self, loaded: Loaded) { + let b = &mut self.mods.browse; + fn open<'a>(b: &'a mut Browse, key: &(SourceId, String)) -> Option<&'a mut Opened> { + b.open + .as_mut() + .filter(|o| (o.project.source, &o.project.id) == (key.0, &key.1)) + } + match loaded { + Loaded::Details(key, d) => { + if let Some(o) = open(b, &key) { + o.details = Some(d); + } + } + Loaded::Versions(key, v) => { + if let Some(o) = open(b, &key) { + o.versions = Some(v); + } + } + Loaded::Image(key, path) => { + b.images.insert(key, path); + } + Loaded::Tags(key, Ok(tags)) => { + b.tags.insert(key, tags); + } + Loaded::Tags(_, Err(_)) => {} + } + } + + /// Opens a project's page and asks its source for the rest of it. + pub(super) fn mods_open(&mut self, project: Project) { + let key = (project.source, project.id.clone()); + let tx = self.mods.tx.clone(); + let p = project.clone(); + std::thread::spawn(move || { + let Some(source) = browser::source(p.source) else { + return; + }; + let d = source.details(&p); + let _ = tx.send(Event::Loaded(Loaded::Details(key.clone(), d))); + let v = source.versions(&p); + let _ = tx.send(Event::Loaded(Loaded::Versions(key, v))); + }); + self.mods.browse.open = Some(Opened { + project, + tab: Tab::Description, + details: None, + versions: None, + }); + } + + /// The image of `url` at `size` when it is on disk; else asks for it once. + fn mods_image(&mut self, url: &str, size: u32) -> Option { + let key = (url.to_owned(), size); + if let Some(state) = self.mods.browse.images.get(&key) { + return state.clone(); + } + let home = backend::game_home(); + if let Some(p) = images::cached(&home, url, size) { + self.mods.browse.images.insert(key, Some(p.clone())); + return Some(p); + } + self.mods.browse.images.insert(key.clone(), None); + if images::refuse(url).is_some() { + return None; + } + let b = &mut self.mods.browse; + let queue = b.image_queue.get_or_insert_with(|| { + let (send, receive) = std::sync::mpsc::channel::<(String, u32)>(); + let receive = std::sync::Arc::new(std::sync::Mutex::new(receive)); + for _ in 0..IMAGE_WORKERS { + let (receive, tx, home) = (receive.clone(), self.mods.tx.clone(), home.clone()); + std::thread::spawn(move || loop { + let Ok(next) = receive.lock().map(|r| r.recv()) else { + break; + }; + let Ok((url, size)) = next else { + break; + }; + let path = images::fetch(&home, &url, size).ok(); + if tx + .send(Event::Loaded(Loaded::Image((url, size), path))) + .is_err() + { + break; + } + }); + } + send + }); + let _ = queue.send(key); + None + } + + /// A project's icon, `side` pixels: its image, or its first letter on a plate until then. + pub(super) fn mods_icon(&mut self, p: &Project, side: f32) -> AnyElement { + let t = self.theme; + let path = p + .icon + .clone() + .and_then(|url| self.mods_image(&url, images::ICON)); + let frame = plate(&t) + .flex() + .flex_none() + .items_center() + .justify_center() + .size(px(side)) + .overflow_hidden(); + match path { + Some(path) => frame.child(img(path).size(px(side))).into_any_element(), + None => frame + .text_color(t.muted) + .child( + text(theme::UI).child( + p.title + .chars() + .next() + .map(|c| c.to_uppercase().to_string()) + .unwrap_or_default(), + ), + ) + .into_any_element(), + } + } + + /// The values the filters can take for the current kind and source, asked for once. + fn mods_tags(&mut self) -> Option<&Tags> { + let key = (self.mods.source, self.mods.kind); + if self.mods.browse.tags_asked.insert(key) { + let tx = self.mods.tx.clone(); + std::thread::spawn(move || { + let tags = browser::source(key.0) + .ok_or_else(|| "not set up".to_string()) + .and_then(|s| s.tags(key.1)); + let _ = tx.send(Event::Loaded(Loaded::Tags(key, tags))); + }); + } + self.mods.browse.tags.get(&key) + } + + /// Sets the filters and searches again. + fn mods_filter(&mut self, change: impl FnOnce(&mut Filters)) { + change(&mut self.mods.browse.filters); + self.mods_search(0); + } + + /// The filter bar: sort always; loader, version, environment and categories when shown. + pub(super) fn mods_filters(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + let this = cx.entity().downgrade(); + let f = self.mods.browse.filters.clone(); + let sorts: Vec<(Option, &'static str)> = std::iter::once((None, "Best match")) + .chain(Sort::ALL.iter().map(|s| (Some(*s), s.label()))) + .collect(); + let sort = segments("mods-sort", &sorts, f.sort, &t, { + let this = this.clone(); + move |value, _, cx| { + let _ = this.update(cx, |this, cx| { + this.mods_filter(|f| f.sort = value); + cx.notify(); + }); + } + }); + let shown = self.mods.browse.show_filters; + let active = f.categories.len() + + f.loader.is_some() as usize + + f.game_version.is_some() as usize + + f.environment.is_some() as usize; + let toggle = button( + "mods-filters", + if active > 0 { + format!("Filters ({active})") + } else { + "Filters".to_string() + }, + if shown { Kind::Secondary } else { Kind::Ghost }, + &t, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.mods.browse.show_filters = !this.mods.browse.show_filters; + cx.notify(); + })); + let mut bar = div().flex().flex_col().gap(px(12.)).child( + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(12.)) + .child(sort) + .child(toggle), + ); + if !shown { + return bar; + } + let Some(tags) = self.mods_tags().cloned() else { + return bar.child(caps("Loading filters").text_color(t.muted)); + }; + // A chip: on or off, one value of a filter. + let chip = |id: String, label: String, on: bool| { + button( + id, + label, + if on { Kind::Secondary } else { Kind::Ghost }, + &t, + ) + }; + let row = |title: &'static str| { + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(4.)) + .child(caps(title).text_color(t.muted).w(px(120.))) + }; + let mut loaders = row("Loader"); + for l in &tags.loaders { + let on = f.loader.as_deref() == Some(l.as_str()); + let value = l.clone(); + loaders = loaders.child(chip(format!("mods-loader-{l}"), l.clone(), on).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + let v = value.clone(); + this.mods_filter(|f| f.loader = if on { None } else { Some(v) }); + cx.notify(); + }), + )); + } + let mut versions = row("Game version"); + if let Some(path) = self.vanilla_icon() { + versions = versions.child(img(path).size(px(20.)).flex_none()); + } + for v in tags.game_versions.iter().take(12) { + let on = f.game_version.as_deref() == Some(v.as_str()); + let value = v.clone(); + versions = versions.child(chip(format!("mods-version-{v}"), v.clone(), on).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + let v = value.clone(); + this.mods_filter(|f| f.game_version = if on { None } else { Some(v) }); + cx.notify(); + }), + )); + } + let mut environment = row("Environment"); + for e in Environment::ALL { + let on = f.environment == Some(e); + environment = environment.child( + chip(format!("mods-env-{}", e.label()), e.label().into(), on).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_filter(|f| f.environment = if on { None } else { Some(e) }); + cx.notify(); + }), + ), + ); + } + let mut categories = row("Categories"); + for c in &tags.categories { + let on = f.categories.contains(&c.name); + let value = c.name.clone(); + categories = categories.child( + chip(format!("mods-cat-{}", c.name), c.name.replace('-', " "), on).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + let v = value.clone(); + this.mods_filter(|f| { + if !f.categories.contains(&v) { + f.categories.push(v); + } else { + f.categories.retain(|x| *x != v); + } + }); + cx.notify(); + }), + ), + ); + } + let clear = button("mods-clear", "Clear filters", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.mods_filter(|f| *f = Filters::default()); + cx.notify(); + }, + )); + bar = bar + .child(loaders) + .child(versions) + .child(environment) + .child(categories); + if active > 0 { + bar = bar.child(div().flex().child(clear)); + } + bar + } + + /// Vanilla's mark, drawn from the player's prepared game files when there are some. + fn vanilla_icon(&self) -> Option { + let tag = self.selected().filter(|tag| backend::is_prepared(tag))?; + images::grass_block(&backend::game_home(), &backend::resources(tag)) + } + + /// The open project's page. + pub(super) fn mods_project_page(&mut self, cx: &mut Context) -> Option
{ + let t = self.theme; + let o = self.mods.browse.open.as_ref()?; + let p = o.project.clone(); + let tab = o.tab; + let support = self.mods.support(&p); + let color = match support { + Support::Works => t.success, + Support::Partial(_) => t.accent, + Support::No(_) => t.muted, + }; + let back = button("mods-back", "Back to results", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.mods.browse.open = None; + cx.notify(); + }, + )); + let details = o.details.clone(); + let versions = o.versions.clone(); + let mut meta = vec![format!("{} downloads", thousands(p.downloads))]; + if let Some(Ok(d)) = &details { + meta.push(format!("{} followers", thousands(d.followers))); + if let Some(day) = d.updated.get(..10) { + meta.push(format!("updated {day}")); + } + } + if !p.license.is_empty() { + meta.push(p.license.clone()); + } + meta.push(format!("from {}", p.source.label())); + let authors = match &details { + Some(Ok(d)) if !d.authors.is_empty() => d.authors.join(", "), + _ => p.author.clone(), + }; + let icon = self.mods_icon(&p, 72.); + let busy = self.mods.busy.as_ref().map(|b| b.0.clone()); + let installed = self.mods.entry(&p).is_some(); + let checking = matches!( + self.mods.checks.get(&(p.source, p.id.clone())), + None | Some(Checking::Running) + ) && p.kind == PackKind::Mod + && p.support().installable(); + let mut action = div().flex().items_center().gap(px(8.)).child( + caps(if checking { + "Checking" + } else { + support.label() + }) + .flex_none() + .text_color(color), + ); + if busy.as_deref() == Some(p.id.as_str()) { + action = action.child(caps("Installing").text_color(t.accent)); + } else if installed { + action = action.child(caps("Installed").text_color(t.muted)); + } else if support.installable() && !checking { + let label = if p.kind == PackKind::Modpack { + "Import" + } else { + "Install" + }; + let mut install = button("mods-page-install", label, Kind::Primary, &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(); + })); + } + action = action.child(install); + } + let head = div() + .flex() + .items_center() + .gap(px(20.)) + .child(icon) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(4.)) + .child(text(theme::TITLE).text_color(t.ink).child(p.title.clone())) + .child( + text(theme::UI) + .text_color(t.muted) + .child(if authors.is_empty() { + p.summary.clone() + } else { + format!("by {authors} · {}", p.summary) + }), + ) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .child(meta.join(" · ")), + ), + ) + .child(action); + let mut page = div() + .flex() + .flex_col() + .gap(px(24.)) + .child(div().flex().child(back)) + .child(head); + if let Some(why) = support.reason() { + page = page.child( + text(theme::UI) + .text_color(t.ink_soft) + .child(why.to_string()), + ); + } + if let Some(Checking::Done(c)) = self.mods.checks.get(&(p.source, p.id.clone())) { + let lines = |title: &str, list: &[String]| { + div() + .flex() + .flex_col() + .gap(px(2.)) + .child(caps(title).text_color(t.muted)) + .children( + list.iter() + .map(|l| text(theme::CAPTION).text_color(t.ink_soft).child(l.clone())), + ) + }; + let mut what = div().flex().gap(px(32.)); + if !c.ports.is_empty() { + what = what.child(lines("Ports", &c.ports)); + } + if !c.skipped.is_empty() { + what = what.child(lines("Doesn't port", &c.skipped)); + } + page = page.child(what); + } + if let Some(Ok(d)) = &details { + let mut links = div().flex().flex_wrap().gap(px(8.)); + let page_url = p.page.clone(); + if !page_url.is_empty() { + links = links.child( + button( + "mods-link-page", + format!("{} page", p.source.label()), + Kind::Ghost, + &t, + ) + .on_click(move |_, _, cx| cx.open_url(&page_url)), + ); + } + for (i, l) in d.links.iter().enumerate() { + let url = l.url.clone(); + links = links.child( + button(format!("mods-link-{i}"), l.label.clone(), Kind::Ghost, &t) + .on_click(move |_, _, cx| cx.open_url(&url)), + ); + } + page = page.child(links); + } + let this = cx.entity().downgrade(); + page = page.child(div().flex().child(segments("mods-tab", &TABS, tab, &t, { + move |value, _, cx| { + let _ = this.update(cx, |this, cx| { + if let Some(o) = &mut this.mods.browse.open { + o.tab = value; + } + cx.notify(); + }); + } + }))); + let body = match tab { + Tab::Description => match &details { + None => centered("Loading…", &t), + Some(Err(e)) => notice(e.clone(), &t), + Some(Ok(d)) => div().max_w(px(760.)).child(markdown::render(&d.body, &t)), + }, + Tab::Gallery => match &details { + None => centered("Loading…", &t), + Some(Err(e)) => notice(e.clone(), &t), + Some(Ok(d)) if d.gallery.is_empty() => centered("No gallery images.", &t), + Some(Ok(d)) => { + let mut grid = div().flex().flex_wrap().gap(px(16.)); + for g in &d.gallery { + let shot = match self.mods_image(&g.url, images::GALLERY) { + Some(path) => img(path).w(px(360.)).h(px(203.)).into_any_element(), + None => plate(&t).w(px(360.)).h(px(203.)).into_any_element(), + }; + grid = grid.child( + div() + .flex() + .flex_col() + .gap(px(6.)) + .w(px(360.)) + .child(plate(&t).overflow_hidden().child(shot)) + .when(!g.title.is_empty(), |d| { + d.child( + text(theme::CAPTION) + .text_color(t.ink_soft) + .child(g.title.clone()), + ) + }), + ); + } + grid + } + }, + Tab::Versions => match &versions { + None => centered("Loading…", &t), + Some(Err(e)) => notice(e.clone(), &t), + Some(Ok(list)) => { + let mut rows = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, v) in list.iter().take(50).enumerate() { + let file = v.file(); + let mut detail = vec![ + v.published.get(..10).unwrap_or_default().to_string(), + v.loaders.join(", "), + ]; + let games: Vec<&str> = v + .game_versions + .iter() + .rev() + .take(4) + .map(String::as_str) + .collect(); + detail.push(games.join(", ")); + if let Some(f) = file { + detail.push(format!("{} · {:.1} MB", f.name, f.size as f64 / 1e6)); + } + let checked = file.and_then(|f| { + (p.kind == PackKind::Mod) + .then(|| java::cached(&backend::game_home(), f)) + .flatten() + }); + rows = rows.child(index_row( + i + 1, + v.number.clone(), + Some(detail.join(" · ").into_any_element()), + checked.map(|c| { + caps(c.verdict.label()) + .text_color(t.muted) + .into_any_element() + }), + &t, + )); + } + rows + } + }, + }; + Some(page.child(body)) + } +}