diff --git a/docs/design-system.md b/docs/design-system.md index 1980adc9c..bd4b635cb 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -134,12 +134,12 @@ Geist (400, 500, 600) and Geist Mono (400), bundled under the SIL Open Font Lice ## Surfaces -- **Launcher** (`launcher/`): top bar; Play is a page header (version as the title, its notes' - first line under it), the client/server segmented control, the version picker and Play, then - an index list of Resources, Minecraft folder (and the server rows). Versions and Patch notes - are index lists with the release name as the title; Settings is an index list of switches and - values. The opening is the faint wordmark drawn letter by letter, then the interface arrives. - The sunset photograph is gone: the window is the page colour, light or dark with the system. +- **Launcher** (`launcher/`): drawn in the Blocks look below. A top bar (wordmark, the pages as + tabs, the account chip, Settings), a sidebar (the instances, the hosted servers, the launcher's + own version and channel at its foot), and the page over a stone texture. Home opens on a pixel + landscape banner with the hero, the version picker and Play; Mods holds the resource pack, + shader pack and modpack tabs; Versions and Patch notes are lists of panels; Settings is + grouped panels of rows. Dark by default, Light or System in Settings (Appearance). - **Website** (`website/`): the Blocks look below. The same page structure as before (what it is, screenshots, parity, launcher, patch notes, community), headings in Pixelify Sans, lists as stacks of panels, the stone texture behind the page and Horizon's pixel landscape (a dawn or a @@ -162,11 +162,19 @@ of the main action. The game's menus keep `LIGHT` and `DARK`. - **Blocks, not rounded cards.** Every surface is square: a 2 px dark outline, a 2 px light bevel along the top and a darker lip along the bottom. The main action is the violet face with its own bevel and a 4 px lip; it sinks a pixel when pressed. Code and fields are sunk wells. -- **Pixel art drawn in code.** The stone behind the pages is 64 texels of the page colour in five - close shades (`TILE_SHADES`), never Minecraft's stone; the landscape is a banded sky, a sun cut in - slices like the mark, hills and square trees. `website/scripts/art.mjs` draws both. -- **Icons** (the launcher): Pixelarticons (MIT), 24 unit pixel SVGs in - `crates/horizon-theme/icons/pixel/`. +- **Inventory tabs** switch the kinds in Mods: the open tab joins the panel under it. +- **Slots** hold pictures: a mod's or pack's own icon and gallery images from its source, + downloaded when first shown and kept on disk (`launcher/src/browser/images.rs`); the launcher + ships no third-party pictures. The Horizon instance shows a grass block drawn from the player's + own prepared Minecraft textures. Sources are named in text ("from Modrinth"): Modrinth's logo is + all rights reserved, so it is not shown. +- **Pixel art drawn in code.** The stone behind the pages is close shades of the page colour + (`TILE_SHADES`), never Minecraft's stone; the landscape is a banded sky, a sun cut in slices like + the mark, hills and square trees (a sunset in dark, a dawn in light). The launcher bakes them in + `launcher/src/art.rs` at the window's scale so each texel covers whole device pixels; the website + draws them in `website/scripts/art.mjs`. +- **Icons**: Pixelarticons (MIT), 24 unit pixel SVGs in `crates/horizon-theme/icons/pixel/`, tinted + with the text colour. - **Contrast**: every text colour meets WCAG AA (4.5:1) on the panels, the page and the lightest stone shade in both palettes (`blocks_text_meets_wcag_aa_in_both_appearances`). diff --git a/launcher/src/art.rs b/launcher/src/art.rs new file mode 100644 index 000000000..ecae80714 --- /dev/null +++ b/launcher/src/art.rs @@ -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>, +} + +/// 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 { + 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 { + 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 { + 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 { + let shades = tokens::TILE_SHADES.map(|by| shade(page, by)); + let mut rng = Rng(0x9e37_79b9); + let mut out: Vec = (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 { + 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, 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 { + 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)); + } +} diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 1afbbd331..e86bd7e87 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -2218,6 +2218,17 @@ pub fn spawn(job: Job, mut cmd: Command, tx: Sender) -> Result, @@ -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::(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; diff --git a/launcher/src/blocks.rs b/launcher/src/blocks.rs new file mode 100644 index 000000000..1f3a36523 --- /dev/null +++ b/launcher/src/blocks.rs @@ -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/.svg`. +pub struct Assets; + +impl gpui::AssetSource for Assets { + fn load(&self, path: &str) -> gpui::Result>> { + 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> { + 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, 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( + 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, 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, 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
{ + 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)))) +} diff --git a/launcher/src/cull.rs b/launcher/src/cull.rs new file mode 100644 index 000000000..41df05610 --- /dev/null +++ b/launcher/src/cull.rs @@ -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>); + +/// 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>, + 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( + &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> = (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 { + 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, moved: Pixels, view: Bounds) -> 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 { + 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())); + } +} diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 6d8538aa4..2ffea2e98 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1,8 +1,11 @@ //! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft, //! and starts the client or a dedicated server. +mod art; +mod blocks; mod cli; mod collection; +mod cull; mod game_tools; mod internet; mod markdown; @@ -37,6 +40,7 @@ use theme::Theme; enum Page { Play, Versions, + /// Mods, resource and shader packs, and modpacks (imported ones and the browser's). Mods, Servers, Notes, @@ -44,13 +48,28 @@ enum Page { } impl Page { - const ALL: [(Page, &'static str); 6] = [ - (Page::Play, "Play"), - (Page::Versions, "Versions"), - (Page::Mods, "Mods"), - (Page::Servers, "Servers"), - (Page::Notes, "Patch notes"), - (Page::Settings, "Settings"), + /// `HORIZON_LAUNCHER_PAGE=mods` (or `modpacks`, `servers`, `versions`, `notes`, `settings`) + /// opens on that page, for screenshots; Home otherwise. + fn from_env() -> Page { + match std::env::var("HORIZON_LAUNCHER_PAGE").as_deref() { + Ok("mods" | "modpacks") => Page::Mods, + Ok("servers") => Page::Servers, + Ok("versions") => Page::Versions, + Ok("notes") => Page::Notes, + Ok("settings") => Page::Settings, + _ => Page::Play, + } + } + + /// Every page, with its name and icon: the top bar shows all but Settings, which has its + /// own button. + const ALL: [(Page, &'static str, &'static str); 6] = [ + (Page::Play, "Home", "home"), + (Page::Mods, "Mods", "package"), + (Page::Servers, "Servers", "server"), + (Page::Versions, "Versions", "archive"), + (Page::Notes, "Patch notes", "notes"), + (Page::Settings, "Settings", "sliders"), ]; } @@ -105,6 +124,8 @@ struct Launcher { /// How many times the page changed, for the page transition. switches: usize, content_scroll: Scrollbar, + /// The rows of the page's long list (Versions, Patch notes) last drawn. + long_list: cull::Cull, opening: Option, updates: Updates, checked: Option, @@ -183,13 +204,21 @@ struct Launcher { starting_pack: Option, /// The Mods page: the browser's search, installs and updates (`mods_page.rs`). mods: mods_page::Mods, + /// The name the game made up for an offline player (`horizon-player.txt`), for the top bar. + offline_name: Option, + /// The player's servers, for the sidebar until the Servers page has read them. + side_servers: Vec, + /// The pixel art made for this window (`art.rs`), and pictures downloaded by URL. + art: art::Art, + /// The window's scale, as of its last frame, for art drawn outside `render`'s reach. + scale: f32, } impl Launcher { fn new(window: &mut Window, cx: &mut Context) -> Self { let (tx, rx) = channel(); let appearance = cx.observe_window_appearance(window, |this, window, cx| { - this.theme = Theme::for_appearance(window.appearance()); + this.theme = Theme::for_appearance(this.settings.appearance, window.appearance()); cx.notify(); }); cx.spawn(async move |this, cx| loop { @@ -225,10 +254,11 @@ impl Launcher { settings.selected = installed.first().cloned(); } let mut this = Self { - theme: Theme::for_appearance(window.appearance()), - page: Page::Play, + theme: Theme::for_appearance(settings.appearance, window.appearance()), + page: Page::from_env(), switches: 0, content_scroll: Scrollbar::default(), + long_list: cull::Cull::default(), opening: (!settings.skip_opening).then(|| { let focus = cx.focus_handle(); window.focus(&focus); @@ -294,6 +324,10 @@ impl Launcher { pack_error: None, starting_pack: None, mods: mods_page::Mods::new(cx), + offline_name: offline_name(), + side_servers: horizon_launcher::servers::list(), + art: art::Art::default(), + scale: window.scale_factor(), }; if this.bench.is_some() { this.perf.keep_local_log(false); @@ -319,10 +353,13 @@ impl Launcher { } fn go(&mut self, page: Page) { + // The game may have made up a name since: read it again (a small file, once a switch). + self.offline_name = offline_name(); if page != self.page { self.page = page; self.switches += 1; self.content_scroll = Scrollbar::default(); + self.long_list = cull::Cull::default(); } self.picker_open = false; } @@ -408,6 +445,10 @@ impl Launcher { self.go(Page::ALL[page % Page::ALL.len()].0); changed = true; } + Some(perf::Step::Scroll) => { + self.go(Page::Versions); + changed = true; + } Some(perf::Step::Quit) => cx.quit(), Some(perf::Step::Wait) | None => {} } @@ -863,11 +904,13 @@ fn hover_layer(id: &SharedString, color: Hsla, radius: f32, bleed: f32) -> AnyEl layer.into_any_element() } -/// Text set in one step of the type scale. +/// Text set in one step of the type scale: headings (heading, title, display) in the pixel face. fn text(step: theme::Step) -> Div { let d = div().text_size(px(step.px)).line_height(px(step.line_px())); let d = if step.mono { d.font_family(theme::MONO) + } else if step.px >= theme::HEADING.px { + d.font_family(theme::PIXEL) } else { d }; @@ -878,13 +921,14 @@ fn text(step: theme::Step) -> Div { } } -/// A list index: `01`, `02`… in mono, in the column on the left of an index row. -fn index(n: usize, t: &Theme) -> Div { - text(theme::MICRO) - .w(px(theme::INDEX)) - .flex_none() - .text_color(t.muted) - .child(format!("{n:02}")) +/// A release's tag as a title: mono, so its digits read at a glance. +fn version_tag(tag: &str) -> Div { + div() + .font_family(theme::MONO) + .text_size(px(22.)) + .line_height(px(28.)) + .font_weight(FontWeight::MEDIUM) + .child(tag.trim_start_matches('v').to_string()) } /// Horizon's mark: two stems, their reflection below, and the horizon across in the accent. @@ -943,6 +987,9 @@ fn keyboard(el: Stateful
, t: &Theme) -> Stateful
{ }) } +/// A button: a block with a light bevel on top and a darker lip below, its label in the pixel +/// face. Primary (the one main action) is the violet face; Secondary a raised block; Ghost only +/// its label until the pointer is over it. fn button( id: impl Into, label: impl Into, @@ -952,9 +999,9 @@ fn button( let id: SharedString = id.into(); let t = *t; let hover = match kind { - Kind::Primary => t.on_accent.opacity(0.12), - Kind::Secondary => t.plate, - Kind::Ghost => t.plate_soft, + Kind::Primary => t.on_face.opacity(0.10), + Kind::Secondary => t.bevel.opacity(if t.dark { 0.10 } else { 0.35 }), + Kind::Ghost => t.raised, }; let base = div() .id(id.clone()) @@ -964,56 +1011,91 @@ fn button( .items_center() .justify_center() .h(px(theme::CONTROL)) - .px(px(16.)) - .rounded(px(theme::RADIUS_PILL)) - .text_size(px(theme::LABEL.px)) + .px(px(14.)) + .font_family(theme::PIXEL) + .text_size(px(15.)) .font_weight(FontWeight::MEDIUM) .cursor_pointer() - .child(hover_layer(&id, hover, theme::RADIUS_PILL, 0.)) - .child(div().relative().child(label.into())); - let base = keyboard(track_hover(base, id), &t); - match kind { + .child(hover_layer(&id, hover, 0., 0.)); + let base = match kind { Kind::Primary => base - .bg(t.accent) - .text_color(t.on_accent) - .active(|s| s.opacity(theme::PRESSED)), + .border_2() + .border_color(t.outline) + .children(blocks::edges(t.face_bevel, t.face_lip, theme::LIP)) + .bg(t.face) + .text_color(t.on_face), Kind::Secondary => base - .bg(t.plate_soft) - .text_color(t.ink) - .active(|s| s.opacity(theme::PRESSED)), - Kind::Ghost => base - .text_color(t.muted) - .hover(move |s| s.text_color(t.ink)) - .active(|s| s.opacity(theme::PRESSED)), - } + .border_2() + .border_color(t.outline) + .children(blocks::edges(t.button_bevel, t.lip, theme::LIP)) + .bg(t.button) + .text_color(t.ink), + Kind::Ghost => base.text_color(t.muted).hover(move |s| s.text_color(t.ink)), + }; + // The label sits on the block's face, above its lip; pressing pushes it down. + let base = base.child( + div() + .relative() + .flex() + .items_center() + .gap(px(8.)) + .pb(px(if kind == Kind::Ghost { 0. } else { 2. })) + .child(label.into()), + ); + keyboard(track_hover(base, id), &t).active(|s| s.opacity(theme::PRESSED).top(px(1.))) } -/// An on/off switch whose knob slides. +/// An on/off switch: a square knob sliding in a sunk track that turns violet when on. fn switch(id: &'static str, on: bool, t: &Theme) -> Stateful
{ - keyboard(div().id(id), t) + let t = *t; + let knob = if on { t.on_face } else { t.muted }; + keyboard(div().id(id), &t) .relative() .flex_none() - .w(px(36.)) - .h(px(20.)) - .rounded_full() + .w(px(44.)) + .h(px(24.)) + .border_2() + .border_color(t.outline) .cursor_pointer() - .bg(if on { t.accent } else { t.plate }) + .bg(if on { t.face } else { t.well }) .child( div() .absolute() .top(px(2.)) .size(px(16.)) - .rounded_full() - .bg(gpui::white()) + .bg(knob) + .child( + div() + .absolute() + .bottom_0() + .left_0() + .right_0() + .h(px(2.)) + .bg(if on { t.face_lip } else { t.lip }), + ) .with_animation( ElementId::named_usize(id, on as usize), Animation::new(theme::MOVE).with_easing(ease_out_quint()), - move |d, p| d.left(px(if on { 2. + 16. * p } else { 18. - 16. * p })), + move |d, p| d.left(px(if on { 2. + 20. * p } else { 22. - 20. * p })), ), ) } -/// A segmented control: a soft pill track, the chosen segment an ink pill. +/// A section's title inside a page: a pixel icon in the accent and the name in the pixel face. +fn section_title(label: &'static str, icon: &'static str, t: &Theme) -> Div { + div() + .flex() + .items_center() + .gap(px(10.)) + .child(blocks::icon(icon, 20., t.accent)) + .child( + blocks::pixel(18., FontWeight::SEMIBOLD) + .text_color(t.ink) + .child(label), + ) +} + +/// A segmented control: a sunk track, the chosen segment a raised block. fn segments( id: &'static str, options: &[(T, &'static str)], @@ -1028,25 +1110,34 @@ fn segments( .flex_none() .p(px(2.)) .gap(px(2.)) - .rounded(px(theme::RADIUS_PILL)) - .bg(t.plate_soft) + .border_2() + .border_color(t.outline) + .bg(t.well) .children(options.iter().map(|&(value, label)| { let active = current == value; let pick = on_pick.clone(); keyboard(div().id(SharedString::from(format!("{id}-{label}"))), &t) + .relative() .flex() .items_center() .h(px(theme::SEGMENT)) .px(px(14.)) - .rounded(px(theme::RADIUS_PILL)) - .text_size(px(theme::LABEL.px)) + .pb(px(2.)) + .font_family(theme::PIXEL) + .text_size(px(14.)) .font_weight(FontWeight::MEDIUM) .cursor_pointer() - .when(active, |d| d.bg(t.ink).text_color(t.page)) + .when(active, |d| { + d.bg(t.button).text_color(t.ink).children(blocks::edges( + t.button_bevel, + t.lip, + 3., + )) + }) .when(!active, |d| { d.text_color(t.muted).hover(move |s| s.text_color(t.ink)) }) - .child(label) + .child(div().relative().child(label)) .on_click(move |_: &ClickEvent, window, cx| pick(value, window, cx)) })) } @@ -1055,14 +1146,14 @@ fn disabled(b: Stateful
) -> Stateful
{ b.opacity(theme::DISABLED).cursor_default().tab_stop(false) } -/// A page's title in display type and one line on what it is for. +/// A page's title in the pixel face and one line on what it is for. fn page_header(title: &str, description: &str, t: &Theme) -> Div { div() .flex() .flex_col() - .gap(px(12.)) + .gap(px(10.)) .child( - text(theme::DISPLAY) + blocks::pixel(36., FontWeight::SEMIBOLD) .text_color(t.ink) .child(title.to_string()), ) @@ -1074,24 +1165,36 @@ fn page_header(title: &str, description: &str, t: &Theme) -> Div { ) } -/// One row of an index list: its number, a name with an optional detail under it, then a -/// value or a control on the right, and a rule below. +/// One row of a list, as its own panel: a name in the pixel face with an optional detail under +/// it, then a value or a control on the right. Rows were numbered in the quiet look; `_n` keeps +/// the call sites as they are. fn index_row( - n: usize, + _n: usize, name: impl IntoElement, detail: Option, right: Option, t: &Theme, ) -> Div { - div() + slot_row(None, name, detail, right, t) +} + +/// A row with an icon slot (`blocks::slot`) on its left: a project in the Mods page's lists. +fn slot_row( + slot: Option
, + name: impl IntoElement, + detail: Option, + right: Option, + t: &Theme, +) -> Div { + blocks::panel(t) .flex() .items_center() .gap(px(16.)) .min_h(px(theme::ROW)) + .mb(px(8.)) + .px(px(16.)) .py(px(12.)) - .border_b_1() - .border_color(t.rule) - .child(index(n, t)) + .children(slot) .child( div() .flex() @@ -1099,7 +1202,11 @@ fn index_row( .flex_1() .min_w_0() .gap(px(2.)) - .child(text(theme::UI).text_color(t.ink).child(name)) + .child( + blocks::pixel(16., FontWeight::MEDIUM) + .text_color(t.ink) + .child(name), + ) .children(detail.map(|d| { text(theme::CAPTION) .text_color(t.muted) @@ -1112,7 +1219,7 @@ fn index_row( /// A plate that stands apart from the page: notices, the console, the agents note. fn plate(t: &Theme) -> Div { - div().rounded(px(theme::RADIUS_PLATE)).bg(t.plate_soft) + blocks::panel(t) } /// Something went wrong: a dot in the danger colour, then what happened. @@ -1124,14 +1231,17 @@ fn notice(text_: String, t: &Theme) -> Div { .text_size(px(theme::UI.px)) .line_height(px(21.)) .text_color(t.ink) + .border_l(px(6.)) .child( div() - .flex_none() - .mt(px(7.)) - .size(px(6.)) - .rounded_full() + .absolute() + .top(px(-2.)) + .bottom(px(-2.)) + .left(px(-6.)) + .w(px(6.)) .bg(t.danger), ) + .child(blocks::icon("info-box", 20., t.danger)) .child(div().flex_1().min_w_0().child(text_)) } @@ -1146,6 +1256,21 @@ fn centered(text_: &str, t: &Theme) -> Div { .child(text(theme::UI).text_color(t.muted).child(text_.to_string())) } +/// The name the game made up for a player without an account, once it has run. +fn offline_name() -> Option { + player_name(&std::fs::read_to_string(backend::game_home().join("horizon-player.txt")).ok()?) +} + +/// The name in `horizon-player.txt`: the game writes `name:Player12345` (horizon-client's +/// offline_name.rs). +fn player_name(text: &str) -> Option { + text.lines() + .find_map(|line| line.trim().strip_prefix("name:")) + .map(str::trim) + .filter(|n| !n.is_empty()) + .map(str::to_owned) +} + /// `1234` as `1,234`. fn thousands(n: u64) -> String { let digits = n.to_string(); @@ -1179,11 +1304,15 @@ fn megabytes(bytes: u64) -> String { // ----- Pages ------------------------------------------------------------------------------------- impl Launcher { - /// The top bar: the mark and the name on the left, the pages on the right. - fn topbar(&self, cx: &mut Context) -> Div { + /// The top bar: the mark and the name over the sidebar, the pages with their icons, then + /// the account playing and the Settings button. + fn topbar(&mut self, cx: &mut Context) -> Div { let t = self.theme; - let mut nav = div().flex().items_center().gap(px(2.)); - for (page, label) in Page::ALL { + let mut nav = div().flex().h_full().gap(px(2.)); + for (page, label, icon) in Page::ALL { + if page == Page::Settings { + continue; + } let active = self.page == page; let id = SharedString::from(format!("nav-{label}")); let item = div() @@ -1191,98 +1320,403 @@ impl Launcher { .relative() .flex() .items_center() - .h(px(theme::CONTROL)) - .px(px(12.)) - .rounded(px(theme::RADIUS_PILL)) - .text_size(px(theme::LABEL.px)) + .gap(px(8.)) + .px(px(14.)) .cursor_pointer() - .when(active, |d| d.bg(t.plate_soft)) - .when(!active, |d| { - d.child(hover_layer(&id, t.plate_soft, theme::RADIUS_PILL, 0.)) + .when(active, |d| { + d.bg(t.raised).child( + div() + .absolute() + .left(px(8.)) + .right(px(8.)) + .bottom_0() + .h(px(4.)) + .bg(t.accent), + ) }) + .when(!active, |d| d.child(hover_layer(&id, t.raised, 0., 0.))) + .child(div().relative().child(blocks::icon( + icon, + 18., + if active { t.accent } else { t.muted }, + ))) .child( - div() + blocks::pixel(16., FontWeight::MEDIUM) .relative() - .when(active, |d| { - d.text_color(t.ink).font_weight(FontWeight::MEDIUM) - }) - .when(!active, |d| d.text_color(t.muted)) + .text_color(if active { t.ink } else { t.muted }) .child(label), ) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { this.go(page); cx.notify(); })); - nav = nav.child(track_hover(item, id)); + nav = nav.child(keyboard(track_hover(item, id), &t)); } - div() + // Only a signed-in account says "Microsoft account"; otherwise the name the game made up. + let (name, how) = match self.accounts.selected() { + Some(a) => (a.name.clone(), "Microsoft account"), + None => ( + self.offline_name.clone().unwrap_or_else(|| "Player".into()), + "Offline", + ), + }; + let account = keyboard(div().id("account"), &t) + .relative() .flex() - .flex_none() .items_center() - .justify_between() - .h(px(72.)) - .px(px(theme::GUTTER)) + .gap(px(10.)) + .h(px(40.)) + .pl(px(4.)) + .pr(px(12.)) + .bg(t.panel) + .border_2() + .border_color(t.outline) + .cursor_pointer() + .hover(move |s| s.bg(t.raised)) .child( div() .flex() .items_center() - .gap(px(10.)) - .child(mark(18., &t)) - .child( - text(theme::LABEL) - .font_weight(FontWeight::MEDIUM) - .text_color(t.ink) - .child("Horizon"), - ), + .justify_center() + .size(px(30.)) + .bg(t.well) + .child(blocks::icon("user", 18., t.muted)), ) - .child(nav) - } - - /// The footer: the launcher's version (or its update), and the community links. - fn footer(&self, cx: &mut Context) -> Div { - let t = self.theme; - let link = |id: &'static str, label: &'static str, url: String| { - caps(label) - .id(id) - .text_color(t.muted) - .cursor_pointer() - .hover(move |s| s.text_color(t.ink)) - .on_click(move |_, _, cx| cx.open_url(&url)) - }; - let version = match &self.self_update { - SelfUpdate::Ready(version) => div() - .flex() - .gap(px(12.)) - .child(caps(format!("Launcher updated to {version}")).text_color(t.muted)) - .child( - caps("Restart") - .id("restart") - .text_color(t.accent) - .cursor_pointer() - .hover(|s| s.opacity(0.8)) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.self_update = SelfUpdate::Failed(backend::restart()); - cx.notify(); - })), - ), - _ => caps(format!("Launcher {}", backend::VERSION)).text_color(t.muted), - }; - let mut links = div().flex().gap(px(20.)); - if !self.links.discord.is_empty() { - links = links.child(link("discord", "Discord", self.links.discord.clone())); - } - if !self.links.website.is_empty() { - links = links.child(link("website", "Website", self.links.website.clone())); - } + .child( + div() + .flex() + .flex_col() + .child( + blocks::pixel(14., FontWeight::MEDIUM) + .text_color(t.ink) + .child(name), + ) + .child(text(theme::CAPTION).text_color(t.muted).child(how)), + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.go(Page::Settings); + cx.notify(); + })); + let settings_open = self.page == Page::Settings; + let settings = keyboard(div().id("nav-Settings"), &t) + .relative() + .flex() + .items_center() + .justify_center() + .size(px(40.)) + .bg(if settings_open { t.raised } else { t.panel }) + .border_2() + .border_color(t.outline) + .cursor_pointer() + .hover(move |s| s.bg(t.raised)) + .when(settings_open, |d| { + d.child( + div() + .absolute() + .left_0() + .right_0() + .bottom_0() + .h(px(4.)) + .bg(t.accent), + ) + }) + .child(blocks::icon( + "sliders", + 20., + if settings_open { t.accent } else { t.ink_soft }, + )) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.go(Page::Settings); + cx.notify(); + })); div() .flex() .flex_none() .items_center() - .justify_between() - .h(px(48.)) - .px(px(theme::GUTTER)) - .child(version) - .child(links) + .h(px(theme::TOPBAR)) + .pl(px(18.)) + .pr(px(12.)) + .bg(t.side) + .border_b_2() + .border_color(t.outline) + .child( + div() + .flex() + .flex_none() + .items_center() + .gap(px(10.)) + .w(px(theme::SIDEBAR - 18.)) + .child(mark(24., &t)) + .child( + blocks::pixel(20., FontWeight::SEMIBOLD) + .text_color(t.ink) + .child("HORIZON"), + ), + ) + .child(nav) + .child( + div() + .ml_auto() + .flex() + .items_center() + .gap(px(8.)) + .child(account) + .child(settings), + ) + } + + /// The sidebar: Horizon and the imported modpacks, the player's servers, then the + /// launcher's own update, the community links and its version. + fn sidebar(&mut self, cx: &mut Context) -> Stateful
{ + let t = self.theme; + self.load_packs(); + let heading = |label: &'static str| { + div() + .flex() + .items_center() + .justify_between() + .px(px(6.)) + .pt(px(10.)) + .pb(px(6.)) + .child( + blocks::pixel(13., FontWeight::MEDIUM) + .text_color(t.muted) + .child(label), + ) + }; + let sub = |s: String| text(theme::CAPTION).text_color(t.muted).truncate().child(s); + let title = |s: String| { + blocks::pixel(15., FontWeight::MEDIUM) + .text_color(t.ink) + .truncate() + .child(s) + }; + let dot = |c: Hsla| { + div() + .absolute() + .left(px(42.)) + .top(px(42.)) + .size(px(10.)) + .bg(c) + .border_2() + .border_color(t.side) + }; + let add = keyboard(div().id("add-pack"), &t) + .flex() + .items_center() + .justify_center() + .size(px(24.)) + .bg(t.panel) + .border_2() + .border_color(t.outline) + .cursor_pointer() + .hover(move |s| s.bg(t.raised)) + .child(blocks::icon("plus", 14., t.ink_soft)) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.show_modpack(None); + cx.notify(); + })); + let mut list = div() + .flex() + .flex_col() + .gap(px(4.)) + .child(heading("INSTANCES").child(add)); + // Horizon itself, with a grass block from the player's own prepared files. + let tag = self.selected().cloned(); + let prepared = tag.as_deref().is_some_and(backend::is_prepared); + let grass = self.vanilla_icon(); + let on_play = self.page == Page::Play; + list = list.child( + blocks::side_item("side-horizon".into(), on_play, &t) + .child(match grass { + Some(g) => div() + .flex() + .items_center() + .justify_center() + .size(px(44.)) + .child(gpui::img(g).size(px(40.))), + None => blocks::slot(None, "Horizon", 44., &t), + }) + .child(dot(if prepared { t.success } else { t.warn })) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child(title("Horizon".into())) + .child(sub(if tag.is_none() { + "No version installed" + } else if prepared { + "Vanilla · ready" + } else { + "Needs preparing" + } + .into())), + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.go(Page::Play); + cx.notify(); + })), + ); + let on_packs = self.page == Page::Mods && self.mods.on_modpacks(); + for p in &self.packs { + let slug = p.slug.clone(); + let open = on_packs && self.pack_open.as_ref() == Some(&p.slug); + list = list.child( + blocks::side_item(format!("side-pack-{slug}").into(), open, &t) + .child(blocks::slot(None, p.title(), 44., &t)) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child(title(p.title().to_string())) + .child(sub(p.summary())), + ) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.show_modpack(Some(slug.clone())); + cx.notify(); + })), + ); + } + let servers: Vec<_> = self + .servers + .sidebar_list() + .map(<[_]>::to_vec) + .unwrap_or_else(|| self.side_servers.clone()); + if !servers.is_empty() { + list = list.child(heading("SERVERS")); + } + for e in servers { + let up = self.servers.is_up(&e.dir); + let open = self.page == Page::Servers && self.servers.open.as_ref() == Some(&e.dir); + let dir = e.dir.clone(); + list = list.child( + blocks::side_item(format!("side-server-{}", e.dir.display()).into(), open, &t) + .child( + div() + .flex() + .items_center() + .justify_center() + .size(px(44.)) + .bg(t.well) + .border_2() + .border_color(t.outline) + .child(blocks::icon("server", 22., t.ink_soft)), + ) + .child(dot(if up { t.success } else { t.muted })) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child(title(e.name.clone())) + .child(sub(if up { "Running" } else { "Stopped" }.into())), + ) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.servers.open = Some(dir.clone()); + this.go(Page::Servers); + cx.notify(); + })), + ); + } + let link = |id: &'static str, label: &'static str, icon: &'static str, url: String| { + div() + .id(id) + .flex() + .items_center() + .gap(px(10.)) + .px(px(8.)) + .py(px(6.)) + .text_color(t.muted) + .cursor_pointer() + .hover(move |s| s.text_color(t.ink).bg(t.raised.opacity(0.6))) + .child(blocks::icon(icon, 18., t.muted)) + .child(blocks::pixel(14., FontWeight::MEDIUM).child(label)) + .on_click(move |_, _, cx| cx.open_url(&url)) + }; + let mut foot = div().mt_auto().flex().flex_col().gap(px(2.)).pt(px(12.)); + match &self.self_update { + SelfUpdate::Downloading(version, f) => { + foot = foot.child( + blocks::panel(&t) + .flex() + .flex_col() + .gap(px(8.)) + .p(px(10.)) + .mb(px(6.)) + .child( + blocks::pixel(13., FontWeight::MEDIUM) + .text_color(t.ink) + .child(format!("Launcher {version} {:.0}%", f * 100.)), + ) + .child(div().flex().child(progress_bar(Some((*f, *f)), &t))), + ) + } + SelfUpdate::Ready(version) => { + foot = foot.child( + blocks::panel(&t) + .flex() + .flex_col() + .gap(px(8.)) + .p(px(10.)) + .mb(px(6.)) + .child( + blocks::pixel(13., FontWeight::MEDIUM) + .text_color(t.ink) + .child(format!("Launcher updated to {version}")), + ) + .child(button("restart", "Restart", Kind::Primary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.self_update = SelfUpdate::Failed(backend::restart()); + cx.notify(); + }), + )), + ) + } + _ => {} + } + if !self.links.discord.is_empty() { + foot = foot.child(link( + "discord", + "Discord", + "message", + self.links.discord.clone(), + )); + } + if !self.links.website.is_empty() { + foot = foot.child(link( + "website", + "Website", + "globe", + self.links.website.clone(), + )); + } + foot = foot.child( + caps(format!( + "Launcher {} · {}", + backend::VERSION, + self.settings.update_channel.label() + )) + .px(px(8.)) + .pt(px(6.)) + .text_color(t.muted), + ); + div() + .id("sidebar") + .flex() + .flex_col() + .flex_none() + .w(px(theme::SIDEBAR)) + .h_full() + .px(px(10.)) + .pb(px(12.)) + .bg(t.side) + .border_r_2() + .border_color(t.outline) + .overflow_y_scroll() + .child(list) + .child(foot) } fn picker(&self, cx: &mut Context) -> Div { @@ -1291,23 +1725,41 @@ impl Launcher { .selected() .cloned() .unwrap_or_else(|| "No version".into()); + // A block as tall as Play: "VERSION" over the tag, and a chevron. let mut wrap = div().relative().child( - div() - .id("picker") + keyboard(div().id("picker"), &t) + .relative() .flex() .items_center() - .gap(px(8.)) - .h(px(theme::CONTROL_LARGE)) - .px(px(16.)) - .rounded(px(theme::RADIUS_PILL)) - .bg(t.plate_soft) - .font_family(theme::MONO) - .text_size(px(theme::CAPTION.px)) - .text_color(t.ink) + .gap(px(16.)) + .h(px(60.)) + .pl(px(14.)) + .pr(px(12.)) + .bg(t.panel) + .border_2() + .border_color(t.outline) + .children(blocks::edges(t.bevel, t.lip, theme::BEVEL)) .cursor_pointer() - .hover(move |s| s.bg(t.plate)) - .child(label) - .child(div().text_color(t.muted).text_size(px(10.)).child("▾")) + .hover(move |s| s.bg(t.raised)) + .child( + div() + .flex() + .flex_col() + .gap(px(4.)) + .child( + blocks::pixel(11., FontWeight::MEDIUM) + .text_color(t.muted) + .child("VERSION"), + ) + .child( + div() + .font_family(theme::MONO) + .text_size(px(15.)) + .text_color(t.ink) + .child(label), + ), + ) + .child(blocks::icon("chevron-down", 20., t.muted)) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { this.picker_open = !this.picker_open; cx.notify(); @@ -1316,13 +1768,12 @@ impl Launcher { if self.picker_open { let mut menu = div() .absolute() - .top(px(theme::CONTROL_LARGE + 6.)) + .top(px(66.)) .right_0() .w(px(240.)) .p(px(6.)) - .rounded(px(theme::RADIUS_PLATE)) - .border_1() - .border_color(t.rule) + .border_2() + .border_color(t.outline) .bg(t.surface) .flex() .flex_col(); @@ -1382,10 +1833,12 @@ impl Launcher { fn play_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; let Some(tag) = self.selected().cloned() else { + // No hero without a version: the page starts below the top bar like the others. return div() .flex() .flex_col() .gap(px(24.)) + .pt(px(28.)) .child(page_header( "Play", "Start the game, or run a server for others to join.", @@ -1408,10 +1861,18 @@ impl Launcher { let running = self.client.is_some() || self.starting_client.is_some(); let play_label = if running { "Running" } else { "Play" }; let mut play = button("play", play_label, Kind::Primary, &t) - .min_w(px(132.)) - .h(px(theme::CONTROL_LARGE)) + .min_w(px(200.)) + .h(px(60.)) .px(px(28.)) - .text_size(px(theme::UI.px)); + .text_size(px(28.)) + .font_weight(FontWeight::SEMIBOLD) + .child( + div() + .absolute() + .left(px(26.)) + .top(px(17.)) + .child(blocks::icon("play", 22., t.on_face)), + ); if !prepared || self.preparing || running { play = disabled(play); } else { @@ -1481,8 +1942,7 @@ impl Launcher { let mut rows = div() .flex() .flex_col() - .border_t_1() - .border_color(t.rule) + .child(section_title("Ready to play", "check", &t).mb(px(12.))) .child(index_row( 1, "Resources", @@ -1502,33 +1962,74 @@ impl Launcher { &t, )); { - let who = match self.accounts.selected() { - Some(a) => format!("{} (Microsoft account)", a.name), - None => "Offline: online servers need a Microsoft account.".to_string(), - }; rows = rows.child(self.join_friend_row(prepared && !running, cx)); - rows = rows.child(index_row( - 4, - "Playing as", - Some(div().child(who).into_any_element()), - Some( - button("accounts", "Accounts…", Kind::Ghost, &t) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.go(Page::Settings); - cx.notify(); - })) - .into_any_element(), - ), - &t, - )); + // The top bar shows who plays; a row only when there is something to do about it: + // offline, in a build that can sign in. + if self.accounts.selected().is_none() && account::client_id().is_some() { + rows = rows.child(index_row( + 4, + "Playing offline", + Some( + div() + .child("Online servers need a Microsoft account.") + .into_any_element(), + ), + Some( + button("accounts", "Accounts…", Kind::Ghost, &t) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.go(Page::Settings); + cx.notify(); + })) + .into_any_element(), + ), + &t, + )); + } } - let mut page = div() + // The banner: Horizon's landscape (`art.rs`) under a veil of the page colour, the hero and + // the Play row over it. It reaches the content's edges and the top bar. + let scene = self.art.scene(t.dark, self.scale); + let veil = |angle: f32, from: f32, to: f32, at: f32| { + div() + .absolute() + .top_0() + .left_0() + .size_full() + .bg(gpui::linear_gradient( + angle, + gpui::linear_color_stop(t.page.opacity(from), 0.), + gpui::linear_color_stop(t.page.opacity(to), at), + )) + }; + let (w, h) = art::SCENE_SIZE; + let banner = div() + .relative() .flex() .flex_col() - .gap(px(32.)) - .child(hero) - .child(actions); + .justify_end() + .min_h(px(340.)) + .mx(px(-32.)) + .px(px(32.)) + .pb(px(28.)) + .gap(px(24.)) + .overflow_hidden() + .bg(gpui::rgb(art::sky_top(t.dark))) + .border_b_2() + .border_color(t.outline) + .child( + gpui::img(scene) + .absolute() + .bottom_0() + .left_0() + .w(px(w as f32 * art::SCENE_TEXEL)) + .h(px(h as f32 * art::SCENE_TEXEL)), + ) + .child(veil(90., 0.82, 0., 0.62)) + .child(veil(180., 0., 0.75, 1.)) + .child(div().relative().child(hero)) + .child(div().relative().child(actions)); + let mut page = div().flex().flex_col().gap(px(28.)).child(banner); // The preparation's progress and error right under the buttons, where the player // looks after pressing Prepare, not below the fold (#666). if self.preparing { @@ -1562,19 +2063,7 @@ impl Launcher { if let Some(crash) = self.crash.clone() { page = page.child(self.crash_notice(crash, cx)); } - // The signature: the name, huge and faint, at the foot of the page. - page.child( - div() - .mt(px(32.)) - .ml(px(-14.)) - .h(px(theme::WORDMARK.px * 0.74)) - .overflow_hidden() - .text_size(px(theme::WORDMARK.px)) - .line_height(px(theme::WORDMARK.px)) - .font_weight(FontWeight::MEDIUM) - .text_color(if t.dark { t.plate_soft } else { t.plate }) - .child("horizon"), - ) + page } /// "Horizon crashed": the report and the logs, and where to report it. @@ -1702,43 +2191,61 @@ impl Launcher { }; let title = "Horizon"; // Never squeezed by the rows below: the ping notice can make it tall. - let mut hero = - div() - .flex() - .flex_none() - .flex_col() - .gap(px(14.)) - .pt(px(24.)) - .child( - div() - .flex() - .items_center() - .gap(px(10.)) - .child(caps(format!("Minecraft {version}")).text_color(t.muted)) - .child(div().size(px(4.)).rounded_full().bg(t.rule)) - .child( - caps(if prepared { "Ready" } else { "Needs preparing" }) - .text_color(if prepared { t.success } else { t.muted }), - ) - .children(self.playing.map(|n| { - div() - .flex() - .items_center() - .gap(px(10.)) - .child(div().size(px(4.)).rounded_full().bg(t.rule)) - .child( - caps(format!("{} playing now", thousands(n))) - .text_color(t.muted), - ) - })), - ) - .child(text(theme::DISPLAY).text_color(t.ink).child(title)) - .child(text(theme::BODY).max_w(px(560.)).text_color(t.muted).child( - match summary { - Some(line) => format!("{}. {line}", tag.trim_start_matches('v')), - None => tag.trim_start_matches('v').to_string(), - }, - )); + let mut hero = div() + .flex() + .flex_none() + .flex_col() + .gap(px(12.)) + .child( + div() + .flex() + .child( + div() + .flex() + .flex_none() + .items_center() + .gap(px(10.)) + .px(px(10.)) + .py(px(5.)) + .bg(t.side.opacity(0.85)) + .border_2() + .border_color(t.outline) + .child( + div() + .size(px(8.)) + .bg(if prepared { t.success } else { t.warn }), + ) + .child(caps(format!("Minecraft {version}")).text_color(t.ink_soft)) + .child(div().size(px(4.)).bg(t.muted)) + .child( + caps(if prepared { "Ready" } else { "Needs preparing" }) + .text_color(if prepared { t.success } else { t.warn }), + ), + ) + .children(self.playing.map(|n| { + div() + .flex() + .items_center() + .gap(px(10.)) + .child(div().size(px(4.)).rounded_full().bg(t.rule)) + .child( + caps(format!("{} playing now", thousands(n))).text_color(t.muted), + ) + })), + ) + .child( + blocks::pixel(60., FontWeight::BOLD) + .line_height(px(62.)) + .text_color(t.ink) + .child(title), + ) + // The version is in the picker beside Play: here only what it brings. + .children(summary.map(|line| { + text(theme::BODY) + .max_w(px(560.)) + .text_color(t.ink_soft) + .child(line) + })); if let Some(release) = &self.updates.horizon { let installing = self.installing.as_ref().filter(|(t, _)| *t == release.tag); let line = div() @@ -1956,6 +2463,30 @@ impl Launcher { .on_click(|_, _, cx| cx.open_url(backend::README_URL)), ); let (accounts, n) = self.account_rows(cx); + let appearance = segments( + "appearance", + &[ + (backend::Appearance::Dark, "Dark"), + (backend::Appearance::Light, "Light"), + (backend::Appearance::System, "System"), + ], + self.settings.appearance, + &t, + { + let this = cx.entity().downgrade(); + move |choice, window, cx| { + let _ = this.update(cx, |this, cx| { + this.settings.appearance = choice; + this.settings.save(); + this.theme = Theme::for_appearance(choice, window.appearance()); + cx.notify(); + }); + } + }, + ); + let group = |label: &'static str, icon: &'static str| { + section_title(label, icon, &t).mt(px(20.)).mb(px(12.)) + }; div() .flex() .flex_col() @@ -1969,9 +2500,9 @@ impl Launcher { div() .flex() .flex_col() - .border_t_1() - .border_color(t.rule) + .child(group("Account", "user").mt_0()) .child(accounts) + .child(group("Updates", "reload")) .child(index_row( n + 1, "Install new versions automatically", @@ -1997,6 +2528,14 @@ impl Launcher { Some(update_channel.into_any_element()), &t, )) + .child(group("Launcher", "monitor")) + .child(index_row( + n + 3, + "Appearance", + Some(plain("Dark by default. System follows your computer's light or dark.")), + Some(appearance.into_any_element()), + &t, + )) .child(index_row( n + 3, "Show the opening", @@ -2004,7 +2543,9 @@ impl Launcher { Some(opening.into_any_element()), &t, )) + .child(group("Game", "gamepad")) .child(self.game_args_row(n + 4, cx)) + .child(group("About", "info-box")) .child(index_row(n + 5, "Horizon", Some(plain(&horizon)), horizon_action, &t)) .child(index_row( n + 6, @@ -2070,10 +2611,9 @@ impl Launcher { .h(px(30.)) .px(px(12.)) .overflow_hidden() - .rounded(px(6.)) - .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) .font_family(theme::MONO) .text_size(px(12.)) .cursor_text() @@ -2311,10 +2851,9 @@ impl Launcher { .h(px(30.)) .px(px(12.)) .overflow_hidden() - .rounded(px(6.)) - .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) .font_family(theme::MONO) .text_size(px(12.)) .cursor_text() @@ -2422,23 +2961,36 @@ impl Launcher { Load::Ready(r) if r.is_empty() => return page.child(centered("No releases yet.", &t)), Load::Ready(r) => r.clone(), }; - let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); - for (i, release) in releases.into_iter().enumerate() { - let tag = release.tag.clone(); - let installed = self.installed.contains(&tag); - let selected = self.selected() == Some(&tag); - let channel = backend::UpdateChannel::of(&release).label(); - let mut meta = vec![channel.to_string(), release.date.clone()]; - if let Some((_, size)) = release.asset { - meta.push(megabytes(size)); - } - let summary = release - .name - .split_once(": ") - .map(|(_, rest)| rest.to_string()) - .unwrap_or_else(|| release.name.clone()); - let right: gpui::AnyElement = - if let Some((_, p)) = self.installing.as_ref().filter(|(t, _)| *t == tag) { + // A hundred releases: only the rows near the screen are drawn. + let keep = |i: usize| { + let tag = &releases[i].tag; + self.installing.as_ref().is_some_and(|(t, _)| t == tag) + || self.install_error.as_ref().is_some_and(|(t, _)| t == tag) + || self.confirm_remove.as_ref() == Some(tag) + }; + let list = self.long_list.clone().column( + &self.content_scroll.handle, + releases.len(), + 8., + keep, + |i| { + let release = releases[i].clone(); + let tag = release.tag.clone(); + let installed = self.installed.contains(&tag); + let selected = self.selected() == Some(&tag); + let channel = backend::UpdateChannel::of(&release).label(); + let mut meta = vec![channel.to_string(), release.date.clone()]; + if let Some((_, size)) = release.asset { + meta.push(megabytes(size)); + } + let summary = release + .name + .split_once(": ") + .map(|(_, rest)| rest.to_string()) + .unwrap_or_else(|| release.name.clone()); + let right: gpui::AnyElement = if let Some((_, p)) = + self.installing.as_ref().filter(|(t, _)| *t == tag) + { div() .flex() .items_center() @@ -2515,82 +3067,77 @@ impl Launcher { } b.into_any_element() }; - let status = if selected { - Some(caps("In use").text_color(t.accent)) - } else if installed { - Some(caps("Installed").text_color(t.ink_soft)) - } else { - None - }; - let error = self - .install_error - .as_ref() - .filter(|(t, _)| *t == tag) - .map(|(_, e)| e.clone()); - let id = SharedString::from(format!("release-{tag}")); - let row = div() - .id(id.clone()) - .relative() - .flex() - .flex_col() - .gap(px(10.)) - .py(px(16.)) - .border_b_1() - .border_color(t.rule) - .child(hover_layer( - &id, - t.plate_soft, - theme::RADIUS_PLATE, - theme::PLATE_BLEED, - )) - .child( - div() - .relative() - .flex() - .items_center() - .gap(px(16.)) - .child(index(i + 1, &t)) - .child( - div() - .flex() - .flex_col() - .flex_1() - .min_w_0() - .gap(px(4.)) - .child( - text(theme::TITLE) - .text_color(t.ink) - .child(tag.trim_start_matches('v').to_string()), - ) - .child( - text(theme::UI) - .text_color(t.muted) - .truncate() - .child(summary), - ), - ) - .child( - div() - .flex() - .flex_col() - .items_end() - .gap(px(2.)) - .flex_none() - .children(status) - .child(caps(meta.join(" · ")).text_color(t.muted)), - ) - .child( - div() - .flex() - .justify_end() - .w(px(190.)) - .flex_none() - .child(right), - ), - ) - .children(error.map(|e| notice(e, &t))); - list = list.child(track_hover(row, id)); - } + let status = if selected { + Some(caps("In use").text_color(t.accent)) + } else if installed { + Some(caps("Installed").text_color(t.ink_soft)) + } else { + None + }; + let error = self + .install_error + .as_ref() + .filter(|(t, _)| *t == tag) + .map(|(_, e)| e.clone()); + let id = SharedString::from(format!("release-{tag}")); + let row = div() + .id(id.clone()) + .relative() + .flex() + .flex_col() + .gap(px(10.)) + .py(px(14.)) + .px(px(16.)) + .mb(px(8.)) + .bg(t.panel) + .border_2() + .border_color(t.outline) + .children(blocks::edges(t.bevel, t.lip, theme::BEVEL)) + .child(hover_layer(&id, t.raised, 0., 0.)) + .child( + div() + .relative() + .flex() + .items_center() + .gap(px(16.)) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(4.)) + .child(version_tag(&tag).text_color(t.ink)) + .child( + text(theme::UI) + .text_color(t.muted) + .truncate() + .child(summary), + ), + ) + .child( + div() + .flex() + .flex_col() + .items_end() + .gap(px(2.)) + .flex_none() + .children(status) + .child(caps(meta.join(" · ")).text_color(t.muted)), + ) + .child( + div() + .flex() + .justify_end() + .w(px(190.)) + .flex_none() + .child(right), + ), + ) + .children(error.map(|e| notice(e, &t))); + track_hover(row, id) + }, + ); page.child(list) } @@ -2652,27 +3199,34 @@ impl Launcher { } Load::Ready(r) => r.clone(), }; - let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); - for (i, release) in releases.iter().enumerate() { - let summary = release - .name - .split_once(": ") - .map(|(_, rest)| rest.to_string()) - .unwrap_or_default(); - list = list.child( + let list = self.long_list.clone().column( + &self.content_scroll.handle, + releases.len(), + 10., + |_| false, + |i| { + let release = &releases[i]; + let summary = release + .name + .split_once(": ") + .map(|(_, rest)| rest.to_string()) + .unwrap_or_default(); div() .flex() .flex_col() - .gap(px(20.)) - .py(px(28.)) - .border_b_1() - .border_color(t.rule) + .relative() + .gap(px(16.)) + .p(px(20.)) + .mb(px(10.)) + .bg(t.panel) + .border_2() + .border_color(t.outline) + .children(blocks::edges(t.bevel, t.lip, theme::BEVEL)) .child( div() .flex() .items_center() .gap(px(16.)) - .child(index(i + 1, &t)) .child( div() .flex() @@ -2680,11 +3234,7 @@ impl Launcher { .flex_1() .min_w_0() .gap(px(4.)) - .child( - text(theme::TITLE) - .text_color(t.ink) - .child(release.tag.trim_start_matches('v').to_string()), - ) + .child(version_tag(&release.tag).text_color(t.ink)) .when(!summary.is_empty(), |d| { d.child(text(theme::UI).text_color(t.muted).child(summary)) }), @@ -2693,8 +3243,7 @@ impl Launcher { ) .child( div() - .pl(px(theme::INDEX + 16.)) - .max_w(px(theme::INDEX + 16. + 640.)) + .max_w(px(640.)) .child(if release.body.trim().is_empty() { text(theme::UI) .text_color(t.muted) @@ -2703,27 +3252,30 @@ impl Launcher { } else { markdown::render(&release.body, &t) }), - ), - ); - } + ) + }, + ); page.child(list) } } /// A thin bar. A known fraction eases from its previous value; an unknown one shuttles slowly. +/// Progress: a sunk track filling with the accent; work of unknown length shuttles a block. fn progress_bar(fraction: Option<(f32, f32)>, t: &Theme) -> Div { let bar = div() .absolute() .top_0() - .h(px(2.)) - .rounded_full() - .bg(t.accent); + .bottom_0() + .bg(t.accent) + .border_b_2() + .border_color(t.face_lip); let track = div() .relative() .flex_1() - .h(px(2.)) - .rounded_full() - .bg(t.rule) + .h(px(12.)) + .border_2() + .border_color(t.outline) + .bg(t.well) .overflow_hidden(); match fraction { Some((from, to)) => { @@ -2749,7 +3301,11 @@ fn progress_bar(fraction: Option<(f32, f32)>, t: &Theme) -> Div { impl Render for Launcher { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = self.theme; + self.scale = window.scale_factor(); self.perf.frame(); + if self.bench.as_ref().is_some_and(perf::Bench::scrolling) { + self.bench_scroll(window); + } self.servers.note_focus(window); self.friend_focused = self.friend_focus.is_focused(window); self.mods.note_focus(window); @@ -2780,6 +3336,10 @@ impl Render for Launcher { if self.opening.is_none() && window.focused(cx).is_none() { window.focus(&self.root_focus); } + let size = window.viewport_size(); + let stone = self.art.stone(t.page_rgb, t.dark, window.scale_factor()); + let topbar = self.topbar(cx); + let sidebar = self.sidebar(cx); let mut root = div() .id("root") .track_focus(&self.root_focus) @@ -2809,6 +3369,7 @@ impl Render for Launcher { .font_family(theme::FONT) .text_color(t.ink) .overflow_hidden() + .child(blocks::stone(stone, size.width.into(), size.height.into())) .child( div() .relative() @@ -2817,29 +3378,35 @@ impl Render for Launcher { .size_full() .opacity(ui) .top(px(theme::RISE * (1. - ui))) - .child(self.topbar(cx)) + .child(topbar) .child( - self.content_scroll - .wrap( - div() - .id("content") - .relative() - .flex_1() - .min_h_0() - .overflow_y_scroll() - .child( - div() - .flex() - .px(px(theme::GUTTER)) - .pt(px(24.)) - .pb(px(48.)) - .child(content), - ), - &t, - ) - .flex_1(), - ) - .child(self.footer(cx)), + div().flex().flex_1().min_h_0().child(sidebar).child( + self.content_scroll + .wrap( + div() + .id("content") + .relative() + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child( + div() + .flex() + .px(px(32.)) + .pt(px(if self.page == Page::Play { + 0. + } else { + 28. + })) + .pb(px(48.)) + .child(content), + ), + &t, + ) + .flex_1() + .min_w_0(), + ), + ), ); if self.page == Page::Servers { if let Some(dialog) = self.create_dialog(cx) { @@ -2855,11 +3422,12 @@ impl Render for Launcher { let gone = 1. - ease_out_cubic(reveal / 0.6); let word = div() .flex() - .text_size(px(theme::WORDMARK.px * 0.6)) - .line_height(px(theme::WORDMARK.px * 0.6)) - .font_weight(FontWeight::MEDIUM) + .font_family(theme::PIXEL) + .text_size(px(theme::WORDMARK.px * 0.5)) + .line_height(px(theme::WORDMARK.px * 0.5)) + .font_weight(FontWeight::BOLD) .text_color(t.ink) - .children("horizon".chars().enumerate().map(|(i, c)| { + .children("HORIZON".chars().enumerate().map(|(i, c)| { let at = held - i as f32 * theme::STAGGER.as_secs_f32() * 1.5; let p = ease_out_cubic(at / theme::ENTER.as_secs_f32()); div() @@ -2929,6 +3497,19 @@ impl Launcher { (reveal, held.as_secs_f32()) } + /// `horizon-launcher benchmark`: scroll the page a little on every frame, back to the top at + /// the bottom, so the frame times measure scrolling. + fn bench_scroll(&mut self, window: &mut Window) { + let handle = &self.content_scroll.handle; + let mut offset = handle.offset(); + offset.y -= px(24.); + if -offset.y > handle.max_offset().height { + offset.y = px(0.); + } + handle.set_offset(offset); + window.request_animation_frame(); + } + fn skip_opening(&mut self) { if let Some(opening) = &mut self.opening { opening.reveal.get_or_insert_with(Instant::now); @@ -2942,42 +3523,59 @@ fn main() { if let Some(code) = cli::run() { std::process::exit(code); } - Application::new().run(|cx: &mut App| { - cx.text_system() - .add_fonts(vec![ - Cow::Borrowed(horizon_theme::fonts::GEIST_REGULAR), - Cow::Borrowed(horizon_theme::fonts::GEIST_MEDIUM), - Cow::Borrowed(horizon_theme::fonts::GEIST_SEMIBOLD), - Cow::Borrowed(horizon_theme::fonts::GEIST_MONO), - ]) - .expect("bundled fonts"); - let bounds = Bounds::centered(None, size(px(1040.), px(700.)), cx); - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(bounds)), - window_min_size: Some(size(px(820.), px(560.))), - titlebar: Some(TitlebarOptions { - title: Some("Horizon".into()), + Application::new() + .with_assets(blocks::Assets) + .run(|cx: &mut App| { + cx.text_system() + .add_fonts(vec![ + Cow::Borrowed(horizon_theme::fonts::GEIST_REGULAR), + Cow::Borrowed(horizon_theme::fonts::GEIST_MEDIUM), + Cow::Borrowed(horizon_theme::fonts::GEIST_SEMIBOLD), + Cow::Borrowed(horizon_theme::fonts::GEIST_MONO), + Cow::Borrowed(horizon_theme::fonts::PIXEL_MEDIUM), + Cow::Borrowed(horizon_theme::fonts::PIXEL_SEMIBOLD), + Cow::Borrowed(horizon_theme::fonts::PIXEL_BOLD), + ]) + .expect("bundled fonts"); + let bounds = Bounds::centered(None, size(px(1180.), px(760.)), cx); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(bounds)), + window_min_size: Some(size(px(960.), px(600.))), + titlebar: Some(TitlebarOptions { + title: Some("Horizon".into()), + ..Default::default() + }), + app_id: Some("horizon-launcher".into()), ..Default::default() - }), - app_id: Some("horizon-launcher".into()), - ..Default::default() - }, - |window, cx| cx.new(|cx| Launcher::new(window, cx)), - ) - .expect("window"); - cx.on_window_closed(|cx| { - servers_page::stop_on_quit(); - telemetry::send_before_exit(); - cx.quit() - }) - .detach(); - cx.activate(true); - }); + }, + |window, cx| cx.new(|cx| Launcher::new(window, cx)), + ) + .expect("window"); + cx.on_window_closed(|cx| { + servers_page::stop_on_quit(); + telemetry::send_before_exit(); + cx.quit() + }) + .detach(); + cx.activate(true); + }); } #[cfg(test)] mod tests { + #[test] + fn the_offline_name_is_read_from_its_key() { + use super::player_name; + assert_eq!( + player_name("name:Player63010\n").as_deref(), + Some("Player63010") + ); + assert_eq!(player_name("name:Steve\r\n").as_deref(), Some("Steve")); + assert_eq!(player_name("Player63010\n"), None); + assert_eq!(player_name(""), None); + } + #[test] fn counts_get_thousands_separators() { let shown: Vec = [0, 7, 999, 1000, 12_300, 1_234_500] diff --git a/launcher/src/modpacks_page.rs b/launcher/src/modpacks_page.rs index f3e2f1d7b..ccd0b3a4e 100644 --- a/launcher/src/modpacks_page.rs +++ b/launcher/src/modpacks_page.rs @@ -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) -> 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) -> 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(); @@ -348,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, diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs index 214048519..9cb834797 100644 --- a/launcher/src/mods_page.rs +++ b/launcher/src/mods_page.rs @@ -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; @@ -72,10 +73,19 @@ pub(super) struct Mods { } 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), @@ -143,6 +153,23 @@ 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) { + 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; @@ -193,6 +220,22 @@ impl Launcher { Event::Loaded(l) => loaded.push(l), } } + // `HORIZON_LAUNCHER_PROJECT=` (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); @@ -374,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 { @@ -442,7 +486,7 @@ 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| { @@ -477,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() @@ -510,35 +532,36 @@ impl Launcher { .flex_wrap() .items_center() .gap(px(12.)) - .child(kinds) .child(self.mods_field(cx)) .child(toggle), ) .child(source_note) .child(self.mods_filters(cx)); - if let Some(project) = self.mods_project_page(cx) { - return div() + // 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) - .children(self.mods_busy_plate()) - .child(project); + .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 page = div() - .flex() - .flex_col() - .gap(px(32.)) - .child(header) - .child(controls); - page = page.children(self.mods_busy_plate()); + let mut body = body.children(self.mods_busy_plate()); if self.mods.kind == PackKind::Modpack { - page = page.child(self.imported_packs(cx)); + 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) { - page = page.child(list); + body = body.child(list); } - page.child(self.mods_results(cx)) + page(body.child(self.mods_results(cx))) } /// The install under way and the last install's answer. @@ -589,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.)); @@ -691,7 +714,7 @@ impl Launcher { fn mods_results(&mut self, cx: &mut Context) -> Div { let t = self.theme; let found = self.mods.results.clone(); - let icons: Vec = found.iter().map(|p| self.mods_icon(p, 40.)).collect(); + let icons: Vec = 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)); @@ -708,7 +731,7 @@ impl Launcher { } let busy = m.busy.as_ref().map(|b| b.0.as_str()); let mut icons = icons.into_iter(); - let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + 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 @@ -719,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( @@ -826,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
{ + 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::*; diff --git a/launcher/src/mods_project.rs b/launcher/src/mods_project.rs index ef1d97975..c66cf174a 100644 --- a/launcher/src/mods_project.rs +++ b/launcher/src/mods_project.rs @@ -167,28 +167,7 @@ impl Launcher { .icon .clone() .and_then(|url| self.mods_image(&url, images::ICON)); - let frame = plate(&t) - .flex() - .flex_none() - .items_center() - .justify_center() - .size(px(side)) - .overflow_hidden(); - match path { - Some(path) => frame.child(img(path).size(px(side))).into_any_element(), - None => frame - .text_color(t.muted) - .child( - text(theme::UI).child( - p.title - .chars() - .next() - .map(|c| c.to_uppercase().to_string()) - .unwrap_or_default(), - ), - ) - .into_any_element(), - } + 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. @@ -357,7 +336,7 @@ impl Launcher { } /// Vanilla's mark, drawn from the player's prepared game files when there are some. - fn vanilla_icon(&self) -> Option { + pub(super) fn vanilla_icon(&self) -> Option { let tag = self.selected().filter(|tag| backend::is_prepared(tag))?; images::grass_block(&backend::game_home(), &backend::resources(tag)) } @@ -371,7 +350,7 @@ impl Launcher { let support = self.mods.support(&p); let color = match support { Support::Works => t.success, - Support::Partial(_) => t.accent, + Support::Partial(_) => t.warn, Support::No(_) => t.muted, }; let back = button("mods-back", "Back to results", Kind::Ghost, &t).on_click(cx.listener( @@ -573,7 +552,7 @@ impl Launcher { None => centered("Loading…", &t), Some(Err(e)) => notice(e.clone(), &t), Some(Ok(list)) => { - let mut rows = div().flex().flex_col().border_t_1().border_color(t.rule); + let mut rows = div().flex().flex_col(); for (i, v) in list.iter().take(50).enumerate() { let file = v.file(); let mut detail = vec![ diff --git a/launcher/src/perf.rs b/launcher/src/perf.rs index 7d652283f..f46393542 100644 --- a/launcher/src/perf.rs +++ b/launcher/src/perf.rs @@ -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, page: usize, + /// When scrolling began, and the UI frames drawn by then and by its end. + scroll: Option<(Instant, usize, Option)>, 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 { } rss.extend(result["rss_mb"].as_f64()); cpu.extend(result["cpu_idle_pct"].as_f64()); - let ui: Vec = 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 { + 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(); diff --git a/launcher/src/scrollbar.rs b/launcher/src/scrollbar.rs index 87cdbee77..757d3525e 100644 --- a/launcher/src/scrollbar.rs +++ b/launcher/src/scrollbar.rs @@ -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
, 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| { diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index b1338f1aa..b1e7eb775 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -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, 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 { - 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 { diff --git a/launcher/src/theme.rs b/launcher/src/theme.rs index 579259661..6425232c5 100644 --- a/launcher/src/theme.rs +++ b/launcher/src/theme.rs @@ -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}"); }