Merge remote-tracking branch 'origin/main' into sw1132

This commit is contained in:
Ludovic Marie
2026-10-23 02:09:13 +02:00
39 changed files with 4755 additions and 669 deletions
+1 -1
View File
@@ -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.
+323
View File
@@ -0,0 +1,323 @@
//! The launcher's pixel art, drawn here rather than shipped: the stone texture behind the pages
//! and the landscape behind Home (the vanilla grass block is `browser::images::grass_block`).
//! GPUI samples images smoothly, so every image is baked at the window's scale with each texel a
//! whole block of device pixels, and drawn at exactly its size: the edges stay sharp. Each image
//! is made once per appearance and scale, then reused.
use gpui::RenderImage;
use horizon_theme as tokens;
use std::collections::HashMap;
use std::sync::Arc;
/// What an image is, to find it again.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Key {
Stone { dark: bool, scale: u32 },
Scene { dark: bool, scale: u32 },
}
#[derive(Default)]
pub struct Art {
made: HashMap<Key, Arc<RenderImage>>,
}
/// The stone texture comes in squares of this many logical pixels (4 by 4 tiles).
pub const STONE: f32 = tokens::TILE_TEXEL * (tokens::TILE_TEXELS * 4) as f32;
/// Home's landscape: texels of this many logical pixels, and its size in texels.
pub const SCENE_TEXEL: f32 = 6.;
pub const SCENE_SIZE: (usize, usize) = (220, 56);
impl Art {
/// The page's stone texture, for a window at `scale`.
pub fn stone(&mut self, page: u32, dark: bool, scale: f32) -> Arc<RenderImage> {
let key = Key::Stone {
dark,
scale: scale_key(scale),
};
self.made
.entry(key)
.or_insert_with(|| {
let n = tokens::TILE_TEXELS * 4;
bake(&opaque(&stone(page, n)), n, n, tokens::TILE_TEXEL, scale)
})
.clone()
}
/// Home's landscape: a sunset in the dark appearance, a dawn in the light one.
pub fn scene(&mut self, dark: bool, scale: f32) -> Arc<RenderImage> {
let key = Key::Scene {
dark,
scale: scale_key(scale),
};
self.made
.entry(key)
.or_insert_with(|| {
let (w, h) = SCENE_SIZE;
let palette = if dark { &SUNSET } else { &DAWN };
bake(&opaque(&scene(palette, 3, w, h)), w, h, SCENE_TEXEL, scale)
})
.clone()
}
}
/// `0xRRGGBB` texels, opaque.
fn opaque(texels: &[u32]) -> Vec<[u8; 4]> {
texels
.iter()
.map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 255])
.collect()
}
/// The colour at the top of Home's sky, for the banner above the landscape when it is taller.
pub fn sky_top(dark: bool) -> u32 {
if dark {
SUNSET.sky[0]
} else {
DAWN.sky[0]
}
}
fn scale_key(scale: f32) -> u32 {
(scale * 100.).round() as u32
}
/// `texels` (RGBA, row by row) as an image whose texels are `texel` logical pixels square at
/// `scale`. Texel edges fall on whole device pixels where the scale allows (1×, 2×, 3×).
pub fn bake(texels: &[[u8; 4]], w: usize, h: usize, texel: f32, scale: f32) -> Arc<RenderImage> {
let size = |n: usize| ((n as f32 * texel * scale).round() as u32).max(1);
let (dw, dh) = (size(w), size(h));
let mut buf = image::RgbaImage::new(dw, dh);
for (y, row) in buf.rows_mut().enumerate() {
let ty = (y * h / dh as usize).min(h - 1);
for (x, px) in row.enumerate() {
let tx = (x * w / dw as usize).min(w - 1);
let [r, g, b, a] = texels[ty * w + tx];
// GPUI wants BGRA, its alpha premultiplied.
let pre = |c: u8| (c as u32 * a as u32 / 255) as u8;
*px = image::Rgba([pre(b), pre(g), pre(r), a]);
}
}
Arc::new(RenderImage::new([image::Frame::new(buf)]))
}
/// A small, fixed random sequence (xorshift), so the art is the same on every start.
struct Rng(u32);
impl Rng {
fn next(&mut self) -> f32 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
self.0 = x;
(x >> 8) as f32 / (1 << 24) as f32
}
}
fn shade(c: u32, by: i16) -> u32 {
[16, 8, 0].iter().fold(0, |out, s| {
let v = (((c >> s) & 255) as i16 + by).clamp(0, 255) as u32;
out | v << s
})
}
fn mix(a: u32, b: u32, t: f32) -> u32 {
[16, 8, 0].iter().fold(0, |out, s| {
let (x, y) = (((a >> s) & 255) as f32, ((b >> s) & 255) as f32);
out | ((x + (y - x) * t).round() as u32) << s
})
}
/// `n` by `n` texels of stone: the page colour in a few close shades, with darker flecks.
fn stone(page: u32, n: usize) -> Vec<u32> {
let shades = tokens::TILE_SHADES.map(|by| shade(page, by));
let mut rng = Rng(0x9e37_79b9);
let mut out: Vec<u32> = (0..n * n)
.map(|_| {
let v = rng.next();
shades[if v < 0.5 {
0
} else if v < 0.78 {
1
} else if v < 0.93 {
2
} else {
3
}]
})
.collect();
for _ in 0..n * n / 50 {
let (x, y) = (
(rng.next() * n as f32) as usize,
(rng.next() * n as f32) as usize,
);
let len = 1 + (rng.next() * 3.) as usize;
for i in 0..len {
out[y * n + (x + i) % n] = shades[4];
out[((y + 1) % n) * n + (x + i + 1) % n] = shades[4];
}
}
out
}
/// A landscape's colours: the sky from the top down, the sun's bands, then the hills from far
/// to near, the near hill's top edge, and the trees.
pub struct Palette {
sky: &'static [u32],
sun: [u32; 3],
far: u32,
mid: u32,
near: u32,
top: u32,
trees: u32,
}
/// The sunset of Horizon's first icon: night blue to violet to coral, and a sun in three bands.
pub const SUNSET: Palette = Palette {
sky: &[
0x0a0f2c, 0x26206a, 0x4b2a7e, 0x7c3a88, 0xc4527a, 0xee6e5a, 0xffb25e,
],
sun: [0xfff6cf, 0xffd272, 0xff9a44],
far: 0x4a2f7e,
mid: 0x2b1f5e,
near: 0x151a45,
top: 0x3d2f80,
trees: 0x0e1236,
};
/// The light appearance's morning: lavender to peach, soft violet hills.
pub const DAWN: Palette = Palette {
sky: &[
0x8d7fd8, 0xa596e2, 0xbcaeea, 0xd2c4f0, 0xe7d2ee, 0xf6dce4, 0xffe6d6,
],
sun: [0xffffff, 0xfff1d0, 0xffd9a8],
far: 0xa898dc,
mid: 0x8676c8,
near: 0x6a5ab4,
top: 0x9a8ae0,
trees: 0x4c3e94,
};
/// A blocky landscape, `w` by `h` texels: banded sky, a sun half set behind the far hills and cut
/// into slices like Horizon's mark, flat clouds, three ridges of hills and a few square trees.
pub fn scene(p: &Palette, seed: u32, w: usize, h: usize) -> Vec<u32> {
let mut rng = Rng(seed.wrapping_mul(0x2545_f491) | 1);
let mut out = vec![0; w * h];
let horizon = h * 62 / 100;
let band = horizon as f32 / p.sky.len() as f32;
for y in 0..h {
let f = y as f32 / band;
let i = (f as usize).min(p.sky.len() - 1);
let dither = f - i as f32 > 0.88 && i + 1 < p.sky.len();
for x in 0..w {
out[y * w + x] = if dither && (x + y) % 2 == 1 {
p.sky[i + 1]
} else {
p.sky[i]
};
}
}
let rect = |out: &mut Vec<u32>, x: isize, y: isize, rw: usize, rh: usize, c: u32| {
for yy in y.max(0) as usize..((y + rh as isize).max(0) as usize).min(h) {
for xx in x.max(0) as usize..((x + rw as isize).max(0) as usize).min(w) {
out[yy * w + xx] = c;
}
}
};
for _ in 0..4 {
let cx = (rng.next() * w as f32) as isize;
let cy = (horizon as f32 * (0.12 + rng.next() * 0.4)) as isize;
let cw = 10 + (rng.next() * 14.) as usize;
let under = p.sky[((cy as f32 / band) as usize + 1).min(p.sky.len() - 1)];
let c = mix(under, 0xffffff, 0.12);
rect(&mut out, cx, cy, cw, 2, c);
rect(&mut out, cx + 3, cy - 2, cw.saturating_sub(6), 2, c);
}
let r = (h as f32 * 0.2) as isize;
let (cx, cy) = (
(w as f32 * 0.68) as isize,
horizon as isize - (h as f32 * 0.11) as isize,
);
for dy in -r..=0 {
let half = ((r * r - dy * dy) as f32).sqrt().round() as isize;
let t = (dy + r) as f32 / r as f32;
let c = p.sun[if t < 0.4 {
0
} else if t < 0.75 {
1
} else {
2
}];
if (cy + dy) % 5 != 0 || (dy as f32) < -r as f32 * 0.6 {
rect(&mut out, cx - half, cy + dy, (half * 2) as usize, 1, c);
}
}
let ridge = |rng: &mut Rng, base: f32, amp: f32, rough: f32| -> Vec<usize> {
let (mut y, mut v) = (base, 0.);
(0..w)
.map(|x| {
if x % 2 == 0 {
v = (v + (rng.next() - 0.5) * rough) * 0.86;
y += v + (base - y) * 0.06;
}
y.clamp(base - amp, base + amp).round().max(0.) as usize
})
.collect()
};
let hf = h as f32;
let layers = [
(p.far, horizon as f32 - hf * 0.1, hf * 0.12, 3.2, None),
(p.mid, horizon as f32 + hf * 0.02, hf * 0.09, 2.6, None),
(
p.near,
horizon as f32 + hf * 0.18,
hf * 0.07,
2.2,
Some(p.top),
),
];
let mut near = Vec::new();
for (c, base, amp, rough, top) in layers {
let hs = ridge(&mut rng, base, amp, rough);
for (x, &y) in hs.iter().enumerate() {
for yy in y.min(h)..h {
out[yy * w + x] = c;
}
if let (Some(top), true) = (top, y < h) {
out[y * w + x] = top;
}
}
near = hs;
}
for _ in 0..w / 26 {
let tx = 4 + (rng.next() * (w - 10) as f32) as isize;
let ty = near[tx as usize] as isize;
rect(&mut out, tx - 2, ty - 8, 5, 5, p.trees);
rect(&mut out, tx - 1, ty - 10, 3, 2, p.trees);
rect(&mut out, tx, ty - 3, 1, 3, p.trees);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn art_is_the_same_on_every_start() {
assert_eq!(scene(&SUNSET, 3, 40, 20), scene(&SUNSET, 3, 40, 20));
assert_eq!(stone(0x0f0d17, 16), stone(0x0f0d17, 16));
}
#[test]
fn the_stone_stays_within_its_shades() {
let shades = tokens::TILE_SHADES.map(|by| shade(0x0f0d17, by));
assert!(stone(0x0f0d17, 64).iter().all(|c| shades.contains(c)));
}
#[test]
fn texels_cover_whole_device_pixels() {
let image = bake(&opaque(&[0x112233; 4]), 2, 2, 4., 2.);
let size = image.size(0);
assert_eq!((size.width.0, size.height.0), (16, 16));
}
}
+39
View File
@@ -2218,6 +2218,17 @@ pub fn spawn(job: Job, mut cmd: Command, tx: Sender<Msg>) -> Result<Running, Str
Ok(Running { child, stdin })
}
/// The launcher's appearance, as the player picks it in Settings.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Appearance {
#[default]
Dark,
Light,
/// Follow the system's light or dark.
System,
}
#[derive(Default, serde::Serialize, serde::Deserialize)]
pub struct Settings {
pub selected: Option<String>,
@@ -2242,6 +2253,9 @@ pub struct Settings {
/// builds" switch instead; [`Settings::parse`] reads its `beta_builds: true` as Alpha.
#[serde(default)]
pub update_channel: UpdateChannel,
/// Dark, Light, or the system's: the launcher's look. Dark by default.
#[serde(default)]
pub appearance: Appearance,
/// The player has read what the "I'm playing" ping holds (`telemetry::PING`): on the
/// first-run question, or on the Play page once if they answered that before it existed.
#[serde(default)]
@@ -2270,6 +2284,13 @@ impl Settings {
{
fields.remove("update_channel");
}
// The same for an appearance from a newer launcher.
if fields
.get("appearance")
.is_some_and(|a| serde_json::from_value::<Appearance>(a.clone()).is_err())
{
fields.remove("appearance");
}
}
serde_json::from_value(value).unwrap_or_default()
}
@@ -2520,6 +2541,24 @@ mod tests {
);
}
#[test]
fn the_appearance_is_dark_unless_picked_and_an_unknown_one_keeps_the_rest() {
assert_eq!(Settings::parse("{}").appearance, Appearance::Dark);
let light = Settings::parse(r#"{"appearance": "light", "game_args": "--x"}"#);
assert_eq!(light.appearance, Appearance::Light);
let future = Settings::parse(r#"{"appearance": "sepia", "game_args": "--x"}"#);
assert_eq!(
(future.appearance, future.game_args.as_str()),
(Appearance::Dark, "--x")
);
let settings = Settings {
appearance: Appearance::System,
..Settings::default()
};
let text = serde_json::to_string(&settings).unwrap();
assert!(text.contains(r#""appearance":"system""#), "{text}");
}
#[test]
fn the_update_channel_is_stored_by_name_and_the_old_beta_switch_reads_as_alpha() {
let read = |text: &str| Settings::parse(text).update_channel;
+232
View File
@@ -0,0 +1,232 @@
//! The blocky look's parts (`docs/design-system.md`, "Blocks"): pixel type, pixel icons, panels
//! with a dark outline, a light bevel on top and a darker lip below, sunk wells, badges, the
//! inventory tabs, and the slots that hold icons downloaded at run time.
use crate::theme::{self, Theme};
use gpui::{
div, img, prelude::*, px, svg, AnyElement, App, ClickEvent, Div, FontWeight, Hsla, ImageSource,
ObjectFit, SharedString, Stateful, Svg, Window,
};
use std::borrow::Cow;
/// The icons, served to `svg()` as `icons/<name>.svg`.
pub struct Assets;
impl gpui::AssetSource for Assets {
fn load(&self, path: &str) -> gpui::Result<Option<Cow<'static, [u8]>>> {
let name = path
.strip_prefix("icons/")
.and_then(|p| p.strip_suffix(".svg"));
Ok(name.and_then(horizon_theme::icons::get).map(Cow::Borrowed))
}
fn list(&self, _path: &str) -> gpui::Result<Vec<SharedString>> {
Ok(horizon_theme::icons::ALL
.iter()
.map(|(name, _)| format!("icons/{name}.svg").into())
.collect())
}
}
/// A pixel icon (`horizon_theme::icons`) in `color`.
pub fn icon(name: &'static str, size: f32, color: Hsla) -> Svg {
svg()
.path(format!("icons/{name}.svg"))
.flex_none()
.size(px(size))
.text_color(color)
}
/// Text in the pixel face: headings, navigation, buttons, badges.
pub fn pixel(size: f32, weight: FontWeight) -> Div {
div()
.font_family(theme::PIXEL)
.font_weight(weight)
.text_size(px(size))
.line_height(px((size * 1.2).round()))
}
/// The light edge along the top of a raised block and the darker lip along its bottom; the
/// block must be `relative`.
pub fn edges(top: Hsla, bottom: Hsla, lip: f32) -> [AnyElement; 2] {
[
div()
.absolute()
.top_0()
.left_0()
.right_0()
.h(px(theme::BEVEL))
.bg(top)
.into_any_element(),
div()
.absolute()
.bottom_0()
.left_0()
.right_0()
.h(px(lip))
.bg(bottom)
.into_any_element(),
]
}
/// A panel: rows, cards, notices, dialogs.
pub fn panel(t: &Theme) -> Div {
div()
.relative()
.bg(t.panel)
.border_2()
.border_color(t.outline)
.children(edges(t.bevel, t.lip, theme::BEVEL))
}
/// A small label in a block of its colour: "Runs", "Partly", a version.
pub fn badge(label: impl Into<SharedString>, color: Hsla, t: &Theme) -> Div {
let tint = if t.dark { 0.14 } else { 0.12 };
div()
.flex()
.flex_none()
.items_center()
.gap(px(6.))
.h(px(22.))
.px(px(8.))
.bg(color.opacity(tint))
.border_2()
.border_color(t.outline)
.child(div().size(px(6.)).bg(color))
.child(
pixel(12., FontWeight::MEDIUM)
.text_color(color)
.child(label.into()),
)
}
/// Inventory tabs: a row of tabs on top of a panel, the open one joined to it.
pub fn tabs<T: Copy + PartialEq + 'static>(
id: &'static str,
options: &[(T, &'static str, &'static str)],
current: T,
t: &Theme,
on_pick: impl Fn(T, &mut Window, &mut App) + Clone + 'static,
) -> Div {
let t = *t;
div()
.flex()
.items_end()
.gap(px(4.))
.children(options.iter().map(|&(value, label, icon_name)| {
let open = current == value;
let pick = on_pick.clone();
let tab = div()
.id(SharedString::from(format!("{id}-{label}")))
.relative()
.flex()
.items_center()
.gap(px(8.))
.h(px(if open { 42. } else { 38. }))
.px(px(14.))
.border_2()
.border_b_0()
.border_color(t.outline)
.cursor_pointer()
.bg(if open { t.panel } else { t.side })
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.h(px(theme::BEVEL))
.bg(if open { t.bevel } else { t.raised }),
)
.child(icon(icon_name, 18., if open { t.accent } else { t.muted }))
.child(
pixel(15., FontWeight::MEDIUM)
.text_color(if open { t.ink } else { t.muted })
.child(label),
)
.when(!open, |d| d.hover(move |s| s.bg(t.raised)))
// The open tab covers the panel's outline under it.
.when(open, |d| d.mb(px(-2.)))
.on_click(move |_: &ClickEvent, window, cx| pick(value, window, cx));
crate::keyboard(tab, &t)
}))
}
/// A square slot for an icon: the picture at `source` when there is one, else the first letter of
/// `name` on a raised block.
pub fn slot(source: Option<ImageSource>, name: &str, size: f32, t: &Theme) -> Div {
let frame = div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(size))
.overflow_hidden()
.border_2()
.border_color(t.outline)
.bg(t.well);
match source {
Some(source) => frame.child(img(source).size(px(size - 4.)).object_fit(ObjectFit::Cover)),
None => frame.bg(t.raised).child(
pixel((size * 0.42).round(), FontWeight::BOLD)
.text_color(t.muted)
.child(
name.chars()
.find(|c| c.is_alphanumeric())
.unwrap_or('?')
.to_uppercase()
.to_string(),
),
),
}
}
/// Lays the stone texture over an area of `w` by `h` logical pixels.
pub fn stone(image: std::sync::Arc<gpui::RenderImage>, w: f32, h: f32) -> Div {
let step = crate::art::STONE;
let (cols, rows) = ((w / step).ceil() as usize, (h / step).ceil() as usize);
let mut layer = div()
.absolute()
.top_0()
.left_0()
.size_full()
.overflow_hidden();
for y in 0..rows {
for x in 0..cols {
layer = layer.child(
img(image.clone())
.absolute()
.left(px(x as f32 * step))
.top(px(y as f32 * step))
.size(px(step)),
);
}
}
layer
}
/// A clickable block in the sidebar: an instance or a server.
pub fn side_item(id: SharedString, selected: bool, t: &Theme) -> Stateful<Div> {
let t = *t;
div()
.id(id)
.relative()
.flex()
.items_center()
.gap(px(10.))
.p(px(6.))
.cursor_pointer()
.when(selected, |d| {
d.bg(t.raised)
.children(edges(t.bevel, t.lip, theme::BEVEL))
.child(
div()
.absolute()
.left(px(-10.))
.top(px(8.))
.bottom(px(8.))
.w(px(4.))
.bg(t.accent),
)
})
.when(!selected, |d| d.hover(move |s| s.bg(t.raised.opacity(0.6))))
}
+15
View File
@@ -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<Project, String>;
/// Versions, newest first.
fn versions(&self, project: &Project) -> Result<Vec<Version>, String>;
/// The project's page: description, gallery, links, authors.
fn details(&self, project: &Project) -> Result<details::Details, String> {
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<details::Tags, String> {
Ok(details::Tags::default())
}
/// Downloads one of its files into `folder`, checked ([`download::fetch`]).
fn fetch(
&self,
+5 -2
View File
@@ -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() {
+368
View File
@@ -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<String>,
/// One loader (`neoforge`, `fabric`, `iris`...), in place of the kind's defaults.
pub loader: Option<String>,
/// One Minecraft version, in place of the one Horizon plays.
pub game_version: Option<String>,
pub environment: Option<Environment>,
/// None: by relevance with search text, else by downloads.
pub sort: Option<Sort>,
}
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<Tag>,
pub loaders: Vec<String>,
/// Release versions, newest first.
pub game_versions: Vec<String>,
}
/// 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<Image>,
pub links: Vec<Link>,
pub authors: Vec<String>,
pub followers: u64,
pub published: String,
pub updated: String,
pub categories: Vec<String>,
/// `required`, `optional`, `unsupported` or `unknown`.
pub client_side: String,
pub server_side: String,
}
fn strings(v: &Value) -> Vec<String> {
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<String> {
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<String> = 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<Tag> = 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::<Vec<_>>(),
["A", "B"]
);
assert_eq!(
d.links.iter().map(|l| l.label.as_str()).collect::<Vec<_>>(),
["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());
}
}
+265
View File
@@ -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<PathBuf> {
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<PathBuf, String> {
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<PathBuf, String> {
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
/// (`<resources>/assets/minecraft/textures/block/`), never shipped. Kept beside the cache.
pub fn grass_block(home: &Path, resources: &Path) -> Option<PathBuf> {
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<u8>, 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<u8>, 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);
}
}
+47 -22
View File
@@ -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<Kind> {
.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<String> = 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<details::Details, String> {
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<details::Tags, String> {
static TAGS: std::sync::Mutex<Option<(Value, Value, Value)>> = 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<Value, String> {
+7 -7
View File
@@ -1036,13 +1036,13 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> {
let file =
installed::fetch_modpack(&*source, &p, &folder, &progress(p.title.clone()))?;
let log = &|line: String| eprintln!("{line}");
let pack = modpacks::import(&file, log)?;
println!(
"Imported {} ({}): horizon-launcher modpack port {}",
pack.title(),
pack.summary(),
pack.slug
);
let resources = backend::resolve_version(None)
.ok()
.filter(|t| backend::is_prepared(t))
.map(|t| backend::resources(&t));
let pack = modpacks::import_and_port(&file, resources.as_deref(), log)?;
println!("{} ({})", modpacks::outcome(&pack), pack.summary());
println!("Play it: horizon-launcher modpack play {}", pack.slug);
return Ok(());
}
let done = installed::install(&*source, &p, everything, &home, &line)?;
+119
View File
@@ -0,0 +1,119 @@
//! Long lists in the page's scroll area (the hundred releases on Versions and Patch notes) draw
//! only the rows near what is on screen. A row far off screen becomes an empty block as tall as
//! it was the last time it was drawn, so the page keeps its length and the scrollbar its place.
use gpui::{div, px, Bounds, Div, IntoElement, ParentElement, Pixels, ScrollHandle, Styled};
use std::{cell::RefCell, rc::Rc};
#[derive(Clone, Default)]
pub struct Cull(Rc<RefCell<Drawn>>);
/// Where each row was in the last frame, and the scroll offset and the viewport's width then
/// (a narrower window wraps text, and the heights no longer hold).
#[derive(Default)]
struct Drawn {
rows: Vec<Bounds<Pixels>>,
offset: Pixels,
width: Pixels,
}
impl Cull {
/// A column for `rows` rows that remembers where they were drawn. Rows come from `row(i)`, or
/// an empty block when row `i` was more than a screen away from the viewport last frame and
/// `keep(i)` is false (a row being installed or showing an error is always drawn).
pub fn column<E: IntoElement>(
&self,
handle: &ScrollHandle,
rows: usize,
gap: f32,
keep: impl Fn(usize) -> bool,
mut row: impl FnMut(usize) -> E,
) -> Div {
let far = self.far(handle, rows);
let skipped: Vec<Option<Pixels>> = (0..rows).map(|i| far(i).filter(|_| !keep(i))).collect();
let gaps = skipped.iter().any(Option::is_some);
let state = self.0.clone();
let scroll = handle.clone();
div()
.flex()
.flex_col()
.children(skipped.iter().enumerate().map(|(i, skip)| match skip {
Some(height) => div().flex_none().h(*height).mb(px(gap)).into_any_element(),
None => row(i).into_any_element(),
}))
.on_children_prepainted(move |bounds, window, _| {
let view = scroll.bounds();
// A jump of more than a screen (the scrollbar dragged) can bring an empty block
// into view: draw again, with the rows where they are now.
if gaps
&& bounds
.iter()
.zip(&skipped)
.any(|(b, skip)| skip.is_some() && !away(*b, px(0.), view))
{
window.refresh();
}
let mut drawn = state.borrow_mut();
drawn.rows = bounds;
drawn.offset = scroll.offset().y;
drawn.width = view.size.width;
})
}
/// For row `i`: its height when it was more than a screen away from the viewport.
fn far(&self, handle: &ScrollHandle, rows: usize) -> impl Fn(usize) -> Option<Pixels> {
let drawn = self.0.borrow();
let view = handle.bounds();
// The rows moved by however far the page scrolled since they were drawn.
let moved = handle.offset().y - drawn.offset;
let known =
drawn.rows.len() == rows && view.size.height > px(0.) && drawn.width == view.size.width;
let rows = if known {
drawn.rows.clone()
} else {
Vec::new()
};
move |i| {
let b = *rows.get(i)?;
away(b, moved, view).then_some(b.size.height)
}
}
}
/// Whether a row drawn at `row`, since moved down by `moved`, is more than a screen above or
/// below `view`.
fn away(row: Bounds<Pixels>, moved: Pixels, view: Bounds<Pixels>) -> bool {
row.bottom() + moved < view.top() - view.size.height
|| row.top() + moved > view.bottom() + view.size.height
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::{point, size};
fn at(y: f32, h: f32) -> Bounds<Pixels> {
Bounds::new(point(px(0.), px(y)), size(px(10.), px(h)))
}
#[test]
fn only_rows_more_than_a_screen_away_are_skipped() {
let view = at(100., 500.);
assert!(!away(at(100., 100.), px(0.), view));
assert!(!away(at(1000., 100.), px(0.), view));
assert!(away(at(1200., 100.), px(0.), view));
assert!(away(at(-600., 100.), px(0.), view));
// Scrolled 700 px down since: the row that was far below is now on screen.
assert!(!away(at(1200., 100.), px(-700.), view));
}
#[test]
fn nothing_is_skipped_before_the_rows_are_known() {
let cull = Cull::default();
cull.0.borrow_mut().rows = (0..10).map(|i| at(i as f32 * 2000., 100.)).collect();
// No viewport yet (the first frame), or another number of rows: every row is drawn.
let far = cull.far(&ScrollHandle::new(), 10);
assert!((0..10).all(|i| far(i).is_none()));
let far = cull.far(&ScrollHandle::new(), 11);
assert!((0..11).all(|i| far(i).is_none()));
}
}
+1027 -428
View File
File diff suppressed because it is too large Load Diff
+96 -6
View File
@@ -45,6 +45,9 @@ pub struct Imported {
pub fetched: Fetched,
/// The carried-over mods the profile loads.
pub mods: Vec<PathBuf>,
/// Mods left off, with why: a ported one an earlier one owns a namespace of, or one whose
/// jar only CurseForge serves (CurseForge downloads coming soon).
pub left_off: Vec<String>,
/// The mods the port step gets and carries over (content, data tier).
pub portable: usize,
}
@@ -105,6 +108,15 @@ pub fn load(work: &Path) -> Result<Imported, String> {
let rows: Vec<Row> = pipeline::read_json(&work.join("coverage.json")).unwrap_or_default();
let records: Vec<horizon_port_pack::inventory::Record> =
pipeline::read_json(&work.join("inventory.json")).unwrap_or_default();
let (mods, mut left_off) = pipeline::loadable(&carried(work));
let fetched = Fetched::load(work);
left_off.extend(
fetched
.files
.iter()
.filter(|o| o.how == How::NeedsKey)
.map(|o| format!("{}: CurseForge downloads coming soon", o.key)),
);
Ok(Imported {
slug: work
.file_name()
@@ -113,8 +125,9 @@ pub fn load(work: &Path) -> Result<Imported, String> {
work: work.to_path_buf(),
pack,
rows,
fetched: Fetched::load(work),
mods: carried(work),
fetched,
mods,
left_off,
portable: records.iter().filter(|r| pipeline::portable(r)).count(),
})
}
@@ -176,6 +189,47 @@ pub fn port(
load(work)
}
/// What the mod browser does with a modpack: imports it, then ports what this computer can
/// (from the pack's links and Modrinth), so it plays straight away. A port that fails leaves the
/// pack imported; the error says so.
pub fn import_and_port(
path: &Path,
resources: Option<&Path>,
log: Log,
) -> Result<Imported, String> {
let pack = import(path, log)?;
if pack.portable == 0 {
return Ok(pack);
}
port(&pack.work, resources, None, log)
.map_err(|e| format!("{} is imported, but porting it failed: {e}", pack.title()))
}
/// One line on what an import and port gave: the mods carried over and the ones that weren't.
pub fn outcome(pack: &Imported) -> String {
let not = pack.count(Status::NotYet);
format!(
"{} is imported{}: {} of its {} files play in Horizon ({} ported, {} partly), {} don't \
yet, {} aren't needed{}. Its list says why.",
pack.title(),
if pack.mods.is_empty() {
""
} else {
" and ported"
},
pack.count(Status::Ported) + pack.count(Status::Partial),
pack.rows.len(),
pack.count(Status::Ported),
pack.count(Status::Partial),
not,
pack.count(Status::NotNeeded),
match pack.left_off.len() {
0 => String::new(),
n => format!("; {n} are left off (listed under the pack)"),
},
)
}
/// 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()) {
@@ -192,7 +246,8 @@ pub fn profile_home(work: &Path) -> PathBuf {
/// 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);
// Only mods that load together: the game would refuse the later of two sharing a namespace.
let (mods, _) = pipeline::loadable(&carried(work));
if mods.is_empty() {
return Err("Nothing is ported yet: port the pack first.".into());
}
@@ -221,6 +276,34 @@ mod tests {
assert_eq!(slug(" "), "pack");
}
#[test]
fn jars_only_curseforge_serves_are_left_off_as_coming_soon() {
use horizon_port_pack::fetch::Outcome;
let work = std::env::temp_dir().join(format!("horizon-launcher-cf-{}", std::process::id()));
let _ = fs::remove_dir_all(&work);
fs::create_dir_all(&work).unwrap();
pipeline::write_json(&work.join("pack.json"), &Pack::default()).unwrap();
let fetched = Fetched {
files: vec![Outcome {
key: "allthemodium".into(),
file: "mods/allthemodium.jar".into(),
how: How::NeedsKey,
detail: String::new(),
}],
};
pipeline::write_json(&work.join("fetch.json"), &fetched).unwrap();
let pack = load(&work).unwrap();
assert_eq!(
pack.left_off,
["allthemodium: CurseForge downloads coming soon"]
);
assert!(pack
.jars()
.unwrap()
.contains("CurseForge downloads coming soon"));
fs::remove_dir_all(&work).unwrap();
}
#[test]
fn a_profile_has_its_own_home_and_mods() {
let root =
@@ -229,12 +312,19 @@ mod tests {
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"] {
for (id, namespaces) in [("a", ""), ("b", ""), ("d", "\"a\"")] {
let carry = work.join("mods").join(id).join("carry");
fs::create_dir_all(&carry).unwrap();
fs::write(carry.join("horizon-mod.toml"), "").unwrap();
fs::write(
carry.join("horizon-mod.toml"),
format!(
"id = \"{id}\"\nname = \"{id}\"\nversion = \"1\"\napi = \"0.2\"\n\
capabilities = [\"registries\"]\nnamespaces = [{namespaces}]\n"
),
)
.unwrap();
}
// Left out: no manifest.
// Left out: no manifest (c), and one owning a namespace of an earlier mod (d).
fs::create_dir_all(work.join("mods/c/carry")).unwrap();
apply_profile(&mut cmd, &work).unwrap();
let args: Vec<String> = cmd
+20 -7
View File
@@ -124,9 +124,8 @@ impl Launcher {
self.start_client(tag);
}
/// The imported packs, above the Modpacks tab's search.
pub(super) fn imported_packs(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
/// Reads the imported packs, once (the sidebar and the Modpacks tab both show them).
pub(super) fn load_packs(&mut self) {
if self.packs_loaded.is_none() {
self.packs = modpacks::list();
if self.pack_open.is_none() {
@@ -134,6 +133,12 @@ impl Launcher {
}
self.packs_loaded = Some(Instant::now());
}
}
/// The imported packs, above the Modpacks tab's search.
pub(super) fn imported_packs(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
self.load_packs();
let busy = self.pack_busy;
let pick = |id: &'static str, label: &'static str, folder: bool| {
let b = button(id, label, Kind::Secondary, &t);
@@ -153,12 +158,17 @@ impl Launcher {
.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(
.child(text(theme::CAPTION).w_full().text_color(t.muted).child(
".mrpack (Modrinth), .zip (CurseForge), or a Prism, MultiMC or CurseForge instance. \
Horizon ports what it can on this computer, from your own downloads, and plays \
the pack as its own profile. Nothing is uploaded or shared.",
));
let mut page = div().flex().flex_col().gap(px(32.)).child(actions);
let mut page = div()
.flex()
.flex_col()
.gap(px(16.))
.child(section_title("Your modpacks", "archive", &t))
.child(actions);
if busy || !self.pack_log.is_empty() {
page = page.child(self.pack_log_plate(&t));
}
@@ -173,7 +183,7 @@ impl Launcher {
);
}
if self.packs.len() > 1 {
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
let mut list = div().flex().flex_col();
for (i, p) in self.packs.iter().enumerate() {
let open = self.pack_open.as_ref() == Some(&p.slug);
let slug = p.slug.clone();
@@ -327,6 +337,9 @@ impl Launcher {
if let Some(jars) = p.jars() {
notes.push(jars);
}
for line in &p.left_off {
notes.push(format!("Left off: {line}."));
}
if !can_play {
notes.push("Playing needs a prepared Horizon version (Play page).".into());
}
@@ -345,7 +358,7 @@ impl Launcher {
});
}
});
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
let mut list = div().flex().flex_col();
for (i, r) in rows.iter().enumerate() {
let color = match r.status {
Status::Ported => t.success,
+180 -85
View File
@@ -11,11 +11,12 @@ use horizon_launcher::modpacks;
use horizon_port_pack::check::Check;
use std::collections::HashMap;
const KINDS: [(PackKind, &str); 4] = [
(PackKind::Mod, "Mods"),
(PackKind::Modpack, "Modpacks"),
(PackKind::ResourcePack, "Resource packs"),
(PackKind::ShaderPack, "Shader packs"),
/// The kinds, as the Mods page's tabs: name and icon.
const KINDS: [(PackKind, &str, &str); 4] = [
(PackKind::Mod, "Mods", "box"),
(PackKind::Modpack, "Modpacks", "archive"),
(PackKind::ResourcePack, "Resource packs", "image"),
(PackKind::ShaderPack, "Shader packs", "zap"),
];
/// Java mods checked at once.
const CHECKING: usize = 2;
@@ -31,6 +32,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<Box<Check>, 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 +44,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,21 +60,32 @@ pub(super) struct Mods {
installed: Vec<installed::Entry>,
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<Result<String, String>>,
updates: HashMap<(SourceId, String), String>,
confirm_remove: Option<String>,
/// Java mods' checks, by source and project.
checks: HashMap<(SourceId, String), Checking>,
tx: Sender<Event>,
pub(super) checks: HashMap<(SourceId, String), Checking>,
/// The project page, filters and images.
pub(super) browse: super::mods_project::Browse,
pub(super) tx: Sender<Event>,
rx: Receiver<Event>,
}
impl Mods {
/// Whether the Modpacks tab is open (the sidebar marks the pack shown there).
pub(super) fn on_modpacks(&self) -> bool {
self.kind == PackKind::Modpack
}
pub(super) fn new(cx: &mut App) -> Self {
let (tx, rx) = channel();
Self {
kind: PackKind::Mod,
kind: if std::env::var("HORIZON_LAUNCHER_PAGE").as_deref() == Ok("modpacks") {
PackKind::Modpack
} else {
PackKind::Mod
},
source: SourceId::Modrinth,
text: String::new(),
focus: cx.focus_handle().tab_index(0).tab_stop(true),
@@ -90,6 +104,7 @@ impl Mods {
updates: HashMap::new(),
confirm_remove: None,
checks: HashMap::new(),
browse: Default::default(),
tx,
rx,
}
@@ -99,14 +114,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;
@@ -138,10 +153,28 @@ fn short_sum(checksum: &str) -> String {
}
impl Launcher {
/// Opens the Mods page on its Modpacks tab, with the pack `slug` open when given (the
/// sidebar's packs and its + button).
pub(super) fn show_modpack(&mut self, slug: Option<String>) {
self.go(Page::Mods);
if slug.is_some() {
self.pack_open = slug;
}
if self.mods.kind != PackKind::Modpack {
self.mods.kind = PackKind::Modpack;
self.mods.browse.filters = Default::default();
self.mods.browse.open = None;
if self.mods.loaded {
self.mods_search(0);
}
}
}
/// Called with the launcher's other work: what the background sent.
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 +217,33 @@ impl Launcher {
};
m.checks.insert(key, state);
}
Event::Loaded(l) => loaded.push(l),
}
}
// `HORIZON_LAUNCHER_PROJECT=<slug>` (with `HORIZON_LAUNCHER_PAGE=mods`): opens that
// project's page once a search finds it, for screenshots.
if self.mods.browse.open.is_none() {
if let Ok(want) = std::env::var("HORIZON_LAUNCHER_PROJECT") {
if let Some(p) = self
.mods
.results
.iter()
.find(|p| p.id == want || p.slug == want)
.cloned()
{
std::env::remove_var("HORIZON_LAUNCHER_PROJECT");
self.mods_open(p);
}
}
}
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 +255,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 +282,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 +329,20 @@ 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<Project>) {
pub(super) fn mods_install(&mut self, source: SourceId, id: String, known: Option<Project>) {
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();
// A modpack is ported for the selected version as soon as it is imported.
let resources = self
.selected()
.filter(|tag| backend::is_prepared(tag))
.map(|tag| backend::resources(tag));
let tx = self.mods.tx.clone();
std::thread::spawn(move || {
let last = std::cell::Cell::new(-1);
let progress = |line: &str, f: f32| {
@@ -304,10 +366,10 @@ impl Launcher {
progress(&p.title, f)
})?;
let log = |line: String| progress(&line, 1.);
let pack = modpacks::import(&file, &log)?;
let pack = modpacks::import_and_port(&file, resources.as_deref(), &log)?;
return Ok(format!(
"{} is imported: it is listed above, ready to port.",
pack.title()
"{} Play it from the list above.",
modpacks::outcome(&pack)
));
}
let home = backend::game_home();
@@ -355,16 +417,17 @@ impl Launcher {
.track_focus(&m.focus)
.flex()
.items_center()
.gap(px(10.))
.w(px(320.))
.h(px(theme::FIELD))
.h(px(theme::FIELD + 4.))
.px(px(12.))
.overflow_hidden()
.rounded(px(theme::RADIUS))
.border_1()
.border_color(if focused { t.accent } else { t.rule })
.bg(t.surface)
.border_2()
.border_color(if focused { t.accent } else { t.outline })
.bg(t.well)
.text_size(px(theme::UI.px))
.cursor_text()
.child(blocks::icon("search", 18., t.muted))
.child(if m.text.is_empty() && !focused {
div().text_color(t.muted).child("Search, then Enter")
} else {
@@ -423,12 +486,15 @@ impl Launcher {
&t,
);
let this = cx.entity().downgrade();
let kinds = segments("mods-kind", &KINDS, self.mods.kind, &t, {
let kinds = blocks::tabs("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;
// Categories and loaders differ by kind.
this.mods.browse.filters = Default::default();
this.mods.browse.open = None;
this.mods_search(0);
}
cx.notify();
@@ -455,29 +521,7 @@ impl Launcher {
}));
// CurseForge support is coming soon: shown, inert, never searched (like the Microsoft
// account's "Coming soon").
let source_note = div()
.flex()
.flex_wrap()
.items_center()
.gap(px(8.))
.child(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();
});
}
}))
.child(disabled(button(
"mods-source-curseforge",
"CurseForge (coming soon)",
Kind::Ghost,
&t,
)));
let source_note = div().flex().child(source_switch(&t));
let controls = div()
.flex()
.flex_col()
@@ -488,19 +532,44 @@ impl Launcher {
.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);
.child(source_note)
.child(self.mods_filters(cx));
// The kinds are inventory tabs on the panel that holds the open one.
let body = blocks::panel(&t).flex().flex_col().gap(px(24.)).p(px(20.));
let page = |body: Div| {
div()
.flex()
.flex_col()
.gap(px(32.))
.child(header)
.child(div().flex().flex_col().child(kinds).child(body))
};
if let Some(project) = self.mods_project_page(cx) {
return page(body.children(self.mods_busy_plate()).child(project));
}
let mut body = body.children(self.mods_busy_plate());
if self.mods.kind == PackKind::Modpack {
body = body
.child(self.imported_packs(cx))
.child(div().h(px(2.)).bg(t.rule))
.child(section_title("Browse modpacks", "search", &t));
}
body = body.child(controls);
if let Some(list) = self.mods_installed_list(cx) {
body = body.child(list);
}
page(body.child(self.mods_results(cx)))
}
/// The install under way and the last install's answer.
pub(super) fn mods_busy_plate(&self) -> Vec<Div> {
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 +586,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<Self>) -> Option<Div> {
@@ -551,7 +612,7 @@ impl Launcher {
return None;
}
let busy = self.mods.busy.is_some();
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
let mut list = div().flex().flex_col();
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.));
@@ -650,8 +711,10 @@ impl Launcher {
)
}
fn mods_results(&self, cx: &mut Context<Self>) -> Div {
fn mods_results(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let found = self.mods.results.clone();
let icons: Vec<AnyElement> = found.iter().map(|p| self.mods_icon(p, 56.)).collect();
let m = &self.mods;
if let Some(e) = &m.error {
return div().child(notice(e.clone(), &t));
@@ -667,7 +730,8 @@ impl Launcher {
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);
let mut icons = icons.into_iter();
let mut list = div().flex().flex_col();
for (i, p) in m.results.iter().enumerate() {
let support = m.support(p);
let checking = p.kind == PackKind::Mod
@@ -678,14 +742,14 @@ impl Launcher {
&& p.support().installable();
let color = match support {
Support::Works => t.success,
Support::Partial(_) => t.accent,
Support::Partial(_) => t.warn,
Support::No(_) => t.muted,
};
let mut right = div()
.flex()
.items_center()
.gap(px(8.))
.child(caps(support.label()).flex_none().text_color(color));
let mut right = div().flex().items_center().gap(px(8.)).child(blocks::badge(
support.label(),
color,
&t,
));
let page_url = p.page.clone();
if !page_url.is_empty() {
right = right.child(
@@ -746,9 +810,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,
@@ -772,6 +849,24 @@ impl Launcher {
}
}
/// The source switch while Modrinth is the only source: Modrinth chosen, CurseForge shown as
/// coming soon and not clickable, like the Microsoft account's "Coming soon".
fn source_switch(t: &Theme) -> Stateful<Div> {
let soon = div()
.flex()
.items_center()
.h(px(theme::SEGMENT))
.px(px(14.))
.pb(px(2.))
.opacity(theme::DISABLED)
.child(
blocks::pixel(14., FontWeight::MEDIUM)
.text_color(t.muted)
.child("CurseForge (coming soon)"),
);
segments("mods-source", &SOURCES, SourceId::Modrinth, t, |_, _, _| {}).child(soon)
}
#[cfg(test)]
mod tests {
use super::*;
+596
View File
@@ -0,0 +1,596 @@
//! 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<Result<Details, String>>,
versions: Option<Result<Vec<Version>, String>>,
}
/// The project page, filters and images' share of the Mods page's state.
#[derive(Default)]
pub(super) struct Browse {
pub(super) open: Option<Opened>,
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<PathBuf>>,
image_queue: Option<std::sync::mpsc::Sender<(String, u32)>>,
}
/// What the background sends this module.
pub(super) enum Loaded {
Details((SourceId, String), Result<Details, String>),
Versions((SourceId, String), Result<Vec<Version>, String>),
Image((String, u32), Option<PathBuf>),
Tags((SourceId, PackKind), Result<Tags, String>),
}
/// 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<PathBuf> {
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));
blocks::slot(path.map(gpui::ImageSource::from), &p.title, side, &t).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<Self>) -> Div {
let t = self.theme;
let this = cx.entity().downgrade();
let f = self.mods.browse.filters.clone();
let sorts: Vec<(Option<Sort>, &'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.
pub(super) fn vanilla_icon(&self) -> Option<PathBuf> {
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<Self>) -> Option<Div> {
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.warn,
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();
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))
}
}
+61 -12
View File
@@ -154,21 +154,27 @@ pub enum Step {
Wait,
/// Show this page (an index into `Page::ALL`, wrapping).
Go(usize),
/// Show the longest list (Versions) and scroll it on every frame while [`Bench::scrolling`].
Scroll,
Quit,
}
const SWITCHING: Duration = Duration::from_secs(4);
const SCROLLING: Duration = Duration::from_secs(3);
const IDLE: Duration = Duration::from_secs(3);
/// The environment variable that makes a launcher window measure itself into the file it names.
const BENCH_ENV: &str = "HORIZON_LAUNCHER_BENCH";
/// A launcher window measuring itself: after its first frame it switches pages every tick for
/// a few seconds (each switch animates, so the UI draws continuously), then rests, then writes
/// what it measured for `benchmark` and quits.
/// a few seconds (each switch animates, so the UI draws continuously), scrolls the longest list
/// on every frame for a few more, then rests, then writes what it measured for `benchmark` and
/// quits.
pub struct Bench {
out: PathBuf,
began: Option<Instant>,
page: usize,
/// When scrolling began, and the UI frames drawn by then and by its end.
scroll: Option<(Instant, usize, Option<usize>)>,
idle_cpu: Option<(Instant, f64)>,
}
@@ -179,10 +185,16 @@ impl Bench {
out: out.into(),
began: None,
page: 0,
scroll: None,
idle_cpu: None,
})
}
/// The window scrolls its content on every frame now.
pub fn scrolling(&self) -> bool {
matches!(self.scroll, Some((_, _, None)))
}
pub fn tick(&mut self, perf: &Perf) -> Step {
let Some(first) = perf.first_frame else {
return Step::Wait;
@@ -192,6 +204,20 @@ impl Bench {
self.page += 1;
return Step::Go(self.page);
}
let frames = perf.ui_frame_times().len();
match &mut self.scroll {
None => {
self.scroll = Some((Instant::now(), frames, None));
return Step::Scroll;
}
Some((at, _, end @ None)) => {
if at.elapsed() < SCROLLING {
return Step::Wait;
}
*end = Some(frames);
}
Some(_) => {}
}
let pid = std::process::id();
let Some((rested, cpu)) = self.idle_cpu else {
self.idle_cpu = Some((
@@ -212,9 +238,15 @@ impl Bench {
.unwrap_or_default();
(now.saturating_sub(ago)).as_secs_f64() * 1000.0
};
let ui = perf.ui_frame_times();
let scroll = match self.scroll {
Some((_, from, Some(to))) => &ui[from.min(to)..to.min(ui.len())],
_ => &[],
};
let result = serde_json::json!({
"first_frame_epoch_ms": epoch_ms(first),
"ui_ms": perf.ui_frame_times(),
"ui_ms": ui,
"scroll_ms": scroll,
"rss_mb": horizon_bench::rss_bytes(pid).map(|b| b as f64 / f64::from(1 << 20)),
"cpu_idle_pct": cpu_idle_pct,
});
@@ -270,20 +302,36 @@ pub fn benchmark(repeats: usize) -> Result<PathBuf, String> {
}
rss.extend(result["rss_mb"].as_f64());
cpu.extend(result["cpu_idle_pct"].as_f64());
let ui: Vec<f32> = result["ui_ms"]
.as_array()
.into_iter()
.flatten()
.filter_map(|v| v.as_f64())
.map(|v| v as f32)
.collect();
let times = |key: &str| -> Vec<f32> {
result[key]
.as_array()
.into_iter()
.flatten()
.filter_map(|v| v.as_f64())
.map(|v| v as f32)
.collect()
};
let (ui, scroll) = (times("ui_ms"), times("scroll_ms"));
report
.frames
.extend(Frames::of("pages", repeat as u32, &ui, &[], &[]));
report
.frames
.extend(Frames::of("scroll", repeat as u32, &scroll, &[], &[]));
let mut sorted = scroll.clone();
sorted.sort_by(f32::total_cmp);
let at = |q: f32| {
sorted
.get(((sorted.len() as f32 - 1.) * q) as usize)
.copied()
};
eprintln!(
"start {}: {:.0} ms to the first frame",
"start {}: {:.0} ms to the first frame; scrolling {} frames, median {:.1} ms, p95 {:.1} ms",
repeat + 1,
starts.last().unwrap_or(&0.0)
starts.last().unwrap_or(&0.0),
sorted.len(),
at(0.5).unwrap_or(0.),
at(0.95).unwrap_or(0.)
);
}
report.metric("launcher.cold_start_ms", &starts[..starts.len().min(1)]);
@@ -364,6 +412,7 @@ mod tests {
began: None,
page: 0,
idle_cpu: None,
scroll: None,
};
assert!(matches!(bench.tick(&perf), Step::Wait));
perf.frame();
+9 -12
View File
@@ -49,7 +49,7 @@ impl Scrollbar {
/// Wrap the scroll container, reserving a narrow gutter so the bar never covers controls.
pub fn wrap(&self, content: Stateful<Div>, theme: &Theme) -> Div {
let state = self.clone();
let track_color = theme.rule;
let track_color = theme.well;
let thumb_color = theme.muted;
div()
.relative()
@@ -83,17 +83,14 @@ impl Scrollbar {
return;
};
let hitbox = hitbox.unwrap();
window.paint_quad(fill(bounds, track_color).corner_radii(px(3.)));
window.paint_quad(
fill(
Bounds::new(
point(bounds.left() + px(3.), bounds.top() + px(g.top)),
size(bounds.size.width - px(6.), px(g.thumb)),
),
thumb_color,
)
.corner_radii(px(3.)),
);
window.paint_quad(fill(bounds, track_color));
window.paint_quad(fill(
Bounds::new(
point(bounds.left() + px(3.), bounds.top() + px(g.top)),
size(bounds.size.width - px(6.), px(g.thumb)),
),
thumb_color,
));
window.on_mouse_event({
let state = state.clone();
move |ev: &MouseDownEvent, phase, window, cx| {
+16 -6
View File
@@ -114,6 +114,18 @@ pub(super) struct Create {
eula_missing: bool,
}
/// What the sidebar shows of the Servers page: its list once the page has read it, and whether
/// a server answers.
impl Servers {
pub(super) fn sidebar_list(&self) -> Option<&[Entry]> {
self.loaded.then_some(&self.list[..])
}
pub(super) fn is_up(&self, dir: &std::path::Path) -> bool {
self.statuses.get(dir).is_some_and(|s| s.phase == "running")
}
}
pub(super) struct Servers {
list: Vec<Entry>,
loaded: bool,
@@ -272,12 +284,10 @@ pub(super) fn stop_on_quit() {
/// The player's own name, to let them in on a friends-only server: the Microsoft account that plays,
/// else the name the game made up for them (`horizon-player.txt`).
fn own_name(accounts: &Accounts) -> Option<String> {
accounts.selected().map(|a| a.name.clone()).or_else(|| {
std::fs::read_to_string(backend::game_home().join("horizon-player.txt"))
.ok()
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
})
accounts
.selected()
.map(|a| a.name.clone())
.or_else(crate::offline_name)
}
fn bytes(n: u64) -> String {
+73 -22
View File
@@ -1,19 +1,29 @@
//! The launcher's view of Horizon's design tokens (`crates/horizon-theme`, described in
//! `docs/design-system.md`), which the game's menus and the website share: cool neutrals in two
//! appearances and one violet accent, Geist and Geist Mono (bundled, SIL Open Font License).
//! `docs/design-system.md`): the blocky look it shares with the website ("Blocks"), stone-dark or
//! lavender-light with Horizon's violet, Pixelify Sans for headings and controls, Geist and Geist
//! Mono for text (all bundled, SIL Open Font License).
use gpui::{rgb, Hsla, WindowAppearance};
use horizon_launcher::backend::Appearance;
use horizon_theme as tokens;
use std::time::Duration;
pub use tokens::{Step, BODY, CAPTION, DISPLAY, HEADING, LABEL, MICRO, TITLE, UI, WORDMARK};
pub const FONT: &str = tokens::FONT;
pub const MONO: &str = tokens::MONO;
pub const PIXEL: &str = tokens::PIXEL;
pub use tokens::{BLOCK_BEVEL as BEVEL, BLOCK_LIP as LIP};
/// Shapes and controls, shared with the game's menus and the website.
pub use tokens::{
CONTROL, CONTROL_LARGE, DISABLED, FIELD, GUTTER, INDEX, PLATE_BLEED, PRESSED, RADIUS,
RADIUS_PILL, RADIUS_PLATE, RISE, ROW, SEGMENT,
};
pub use tokens::{CONTROL_LARGE, DISABLED, FIELD, PRESSED, RISE, ROW, SEGMENT};
/// Blocks have square corners: these stay for the places that ask for a radius.
pub const RADIUS: f32 = 0.;
pub const RADIUS_PLATE: f32 = 0.;
/// Buttons are a little taller than the quiet look's, for their lip.
pub const CONTROL: f32 = 34.;
/// The top bar, and the sidebar of instances and servers.
pub const TOPBAR: f32 = 56.;
pub const SIDEBAR: f32 = 248.;
/// Motion: short and eased out, never bouncy.
pub const QUICK: Duration = tokens::QUICK.duration();
@@ -23,9 +33,15 @@ pub const STAGGER: Duration = tokens::STAGGER;
#[derive(Clone, Copy)]
pub struct Theme {
/// The page behind everything (under its stone texture), and its colour as `0xRRGGBB` for
/// the texture.
pub page: Hsla,
pub page_rgb: u32,
/// Hover plates, fields and the console: the raised panel colour.
pub plate_soft: Hsla,
/// Pressed plates, a switch that is off: the button colour.
pub plate: Hsla,
/// Dialogs and menus above the page: the panel colour.
pub surface: Hsla,
pub rule: Hsla,
pub ink: Hsla,
@@ -35,6 +51,21 @@ pub struct Theme {
pub on_accent: Hsla,
pub danger: Hsla,
pub success: Hsla,
pub warn: Hsla,
/// The blocky parts (`horizon_theme::Blocks`).
pub side: Hsla,
pub panel: Hsla,
pub raised: Hsla,
pub button: Hsla,
pub button_bevel: Hsla,
pub well: Hsla,
pub bevel: Hsla,
pub lip: Hsla,
pub outline: Hsla,
pub face: Hsla,
pub face_bevel: Hsla,
pub face_lip: Hsla,
pub on_face: Hsla,
pub dark: bool,
}
@@ -43,42 +74,61 @@ fn c(hex: u32) -> Hsla {
}
impl Theme {
/// The system's appearance; `HORIZON_LAUNCHER_APPEARANCE=light` or `dark` overrides it (for
/// The player's choice in Settings (dark unless they picked another), the system's when they
/// asked to follow it. `HORIZON_LAUNCHER_APPEARANCE=light` or `dark` overrides both (for
/// screenshots and tests).
pub fn for_appearance(appearance: WindowAppearance) -> Self {
pub fn for_appearance(choice: Appearance, system: WindowAppearance) -> Self {
match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() {
Ok("light") => return Self::light(),
Ok("dark") => return Self::dark(),
_ => {}
}
match appearance {
WindowAppearance::Light | WindowAppearance::VibrantLight => Self::light(),
match (choice, system) {
(Appearance::Light, _) => Self::light(),
(Appearance::System, WindowAppearance::Light | WindowAppearance::VibrantLight) => {
Self::light()
}
_ => Self::dark(),
}
}
pub fn dark() -> Self {
Self::from(tokens::DARK)
Self::from(tokens::BLOCKS_DARK)
}
pub fn light() -> Self {
Self::from(tokens::LIGHT)
Self::from(tokens::BLOCKS_LIGHT)
}
fn from(p: tokens::Palette) -> Self {
fn from(p: tokens::Blocks) -> Self {
Self {
page: c(p.page),
plate_soft: c(p.plate_soft),
plate: c(p.plate),
surface: c(p.surface),
page_rgb: p.page,
plate_soft: c(p.raised),
plate: c(p.button),
surface: c(p.panel),
rule: c(p.rule),
ink: c(p.ink),
ink_soft: c(p.ink_soft),
muted: c(p.muted),
accent: c(p.accent),
on_accent: c(p.on_accent),
on_accent: c(p.on_face),
danger: c(p.danger),
success: c(p.success),
warn: c(p.warn),
side: c(p.side),
panel: c(p.panel),
raised: c(p.raised),
button: c(p.button),
button_bevel: c(p.button_bevel),
well: c(p.well),
bevel: c(p.bevel),
lip: c(p.lip),
outline: c(p.outline),
face: c(p.face),
face_bevel: c(p.face_bevel),
face_lip: c(p.face_lip),
on_face: c(p.on_face),
dark: p.dark,
}
}
@@ -105,13 +155,14 @@ mod tests {
/// field (WCAG 1.4.11 asks 3:1 for those), and text over a selected suggestion.
#[test]
fn marks_and_selections_read_clearly() {
for p in [tokens::LIGHT, tokens::DARK] {
for p in [tokens::BLOCKS_LIGHT, tokens::BLOCKS_DARK] {
let theme = if p.dark { "dark" } else { "light" };
for (name, bg) in [
("page", p.page),
("plate_soft", p.plate_soft),
("plate", p.plate),
("surface", p.surface),
("raised", p.raised),
("button", p.button),
("panel", p.panel),
("well", p.well),
] {
let ring = tokens::contrast(p.accent, bg);
assert!(ring >= 3.0, "{theme} focus ring on {name}: {ring:.2}");
@@ -121,7 +172,7 @@ mod tests {
"{theme} refused field on {name}: {refused:.2}"
);
}
let selection = blend(p.accent, p.surface, SELECTION);
let selection = blend(p.accent, p.panel, SELECTION);
let ratio = tokens::contrast(p.ink, selection);
assert!(ratio >= 4.5, "{theme} text on a selection: {ratio:.2}");
}