voelin-gpui: VoelinTheme (every token of theme.slint, light and dark) written into gpui-component, Inter, the client's Lucide icons, the swatch page
Two layers, as the spikes' report settled: 1. `VoelinTheme`, a GPUI global (theme/tokens.rs): the 43 colour tokens of ui/theme.slint for light and dark (generated from the Slint file by a script, then checked by the test below), the backdrop gradient, and `Metrics`: the radii, spacing, type sizes, weights, control and shell sizes and the two durations at a text size factor (font-scale: the sidebar's `264 * max(1, scale)` and the top bar's `max(44, control + 8)` included). 2. gpui-component's `ThemeColor`, written on every change (theme/components.rs): the base of the report's table (background, foreground, border, input, ring, overlay; primary with hover, active and foreground from the client's accent; secondary and muted from surface-2 and its raised steps; gpui-component's "accent", which is a hover background, from surface-3; popover; list, table, sidebar, title and status bar, tabs, switch, slider, scrollbar, link, selection; danger, success, warning and info with a hover and active made by mixing and a text that is white or the window's ink, whichever contrasts more) and the 28 `button_*` fields a theme file would derive from them (without them the buttons keep the default theme's blue). The mixing, the WCAG contrast and `readable` are `Rgba` methods with tests. The window's background is bg-app; the backdrop and bg-rail stay in `VoelinTheme` (gpui-component has no rail, and GPUI's gradient has two stops against Slint's three: the swatch draws the first and the last and says so). The mode (`Choice`: system, light, dark) follows the window's appearance in `system` (`observe_window_appearance` calls `set_system_appearance`; a light or dark choice ignores the window) and sets the platform's window appearance where the platform draws the frame (macOS; a no-op elsewhere). The text size factor rewrites the metrics, the theme's font size (font-body) and radii. theme/slint_parity.rs reads ui/theme.slint at test time (`include_str!`) and compares every declaration of the `Theme` global with tokens.rs by name: the colours (dark and light), every length with the file's own arithmetic (a small evaluator of `*`, `+`, `max()` and token references) at four text sizes, the weights, durations, the font family and the backdrop's stops, and fails on a name on one side only or a declaration kind it does not know. A mutation check (accent, radius-md and the top bar's formula changed in tokens.rs) failed the tests with the names of the tokens, then was reverted. fonts.rs adds the five Inter TTFs of the Slint front end (`include_bytes!`) to GPUI's text system; the theme names the family. build.rs turns the 147 Lucide 1.48 SVGs of crates/voelin-ui/ui/assets/icons into a sorted table of `include_bytes!` (std only, no new dependency) that assets.rs serves as gpui-component's `icons/<name>.svg` before gpui-kit-assets' Lucide 1.43 catalogue (1,830 paths, which answers the rest and, as it does, an error for a path it lacks); a test checks that `mic.svg` is the client's, differs from the catalogue's, and that other icons fall through. Development switches (dev.rs): `VOELIN_OPEN=swatch`, `VOELIN_DEV_THEME= dark|light|system`, `VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE` (the Slint front end's names where they exist). swatch.rs is the page: the 43 colours in the groups of docs/ui.md's "Theme tokens" table with name and value (a test checks each token is in exactly one group), the backdrop, radii, spacing, the type scale, buttons, switches and checkboxes of gpui-component and 16 icons; it scrolls when the window is smaller. scripts/gpui-shot.sh makes the screenshot headless the way scripts/shots.sh does for Slint (xvfb-run, or GPUI_SHOT_HEADLESS=1 under headless.sh on NixOS; Wayland, the session bus and the XDG directories out of the environment), then closes the window with Alt+F4 and reports how the app ended. docs/ui/gpui-swatch-dark.png and -light.png are its output (Xvfb :97, openbox, lavapipe via wgpu's Vulkan backend, the debug binary, 1440x960, truecolour: a 256-colour reduction would change the tokens' values; the Slint pictures live in docs/screenshots/, the task asked for docs/ui/). Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets, the build script included), `cargo test -p voelin-gpui` 26 tests, cargo deny, `scripts/notices.sh --check`. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
27a13fcc7c
commit
2690b8a802
15 files changed
+1980
-30
No files matched your search
+9
-2
@@ -12,8 +12,15 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
window titled Voelin with one line of the app's state in it (the version,
|
||||
the voice connections that are up, the engine events handled, the seconds
|
||||
up), fed by the same engine and the same view models as the Slint app
|
||||
(`cargo run -p voelin-gpui --release`). The Slint app (`voelin`) is unchanged
|
||||
and stays the app; both run on one engine until the GPUI one reaches parity
|
||||
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
|
||||
radius, size and type token of the Slint app's `theme.slint`, light and dark
|
||||
(a test reads the Slint file and fails when the two differ), written into
|
||||
the widget library's theme too, in Inter, with the Slint app's Lucide icons.
|
||||
`system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows
|
||||
every token, a few widgets and the icons (`VOELIN_DEV_THEME`,
|
||||
`VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with
|
||||
`scripts/gpui-shot.sh`, docs/ui/). The Slint app (`voelin`) is unchanged and
|
||||
stays the app; both run on one engine until the GPUI one reaches parity
|
||||
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
|
||||
in software); no package ships it yet.
|
||||
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Embeds the client's Lucide icons: `crates/voelin-ui/ui/assets/icons/*.svg`
|
||||
//! (Lucide 1.48, the set the Slint front end draws) become a sorted table of
|
||||
//! `include_bytes!` in `$OUT_DIR/icons.rs`, which `assets.rs` serves as
|
||||
//! gpui-component's `icons/<name>.svg` paths before gpui-kit-assets' own
|
||||
//! (Lucide 1.43) catalogue. No dependency: the directory is read and the
|
||||
//! table written with `std`.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
let manifest =
|
||||
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
|
||||
let dir = manifest.join("../voelin-ui/ui/assets/icons");
|
||||
println!("cargo:rerun-if-changed={}", dir.display());
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir)
|
||||
.unwrap_or_else(|e| panic!("the client's icons are at {}: {e}", dir.display()))
|
||||
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
|
||||
.filter(|name| name.ends_with(".svg"))
|
||||
.collect();
|
||||
names.sort();
|
||||
assert!(!names.is_empty(), "no icons in {}", dir.display());
|
||||
let mut table = String::from(
|
||||
"/// The client's icons by file name, sorted.\npub static ICONS: &[(&str, &[u8])] = &[\n",
|
||||
);
|
||||
for name in &names {
|
||||
let path = dir.join(name);
|
||||
let path = path.canonicalize().unwrap_or(path);
|
||||
let _ = writeln!(table, "\t({name:?}, include_bytes!({:?})),", path.display().to_string());
|
||||
}
|
||||
table.push_str("];\n");
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("icons.rs");
|
||||
std::fs::write(out, table).expect("write icons.rs");
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! What `svg()` and gpui-component's `Icon` load by path. The client's own
|
||||
//! Lucide 1.48 icons (the 147 SVGs of the Slint front end, embedded by
|
||||
//! `build.rs`) answer `icons/<name>.svg` first, so every widget draws the
|
||||
//! icons the client draws; anything else (the rest of gpui-kit-assets'
|
||||
//! Lucide 1.43 catalogue, which gpui-component's `IconName` names) comes from
|
||||
//! gpui-kit-assets.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::{AssetSource, Result, SharedString};
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
|
||||
|
||||
/// The client's icons first, then gpui-kit-assets'.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Assets;
|
||||
|
||||
/// The client's icon of a file name (`mic.svg`), if it has one.
|
||||
pub fn client_icon(name: &str) -> Option<&'static [u8]> {
|
||||
ICONS.binary_search_by_key(&name, |(n, _)| n).ok().map(|i| ICONS[i].1)
|
||||
}
|
||||
|
||||
/// The names of the client's icons, sorted.
|
||||
pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
|
||||
ICONS.iter().map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
impl AssetSource for Assets {
|
||||
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
|
||||
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
|
||||
return Ok(Some(Cow::Borrowed(bytes)));
|
||||
}
|
||||
gpui_kit::assets::AllAssets.load(path)
|
||||
}
|
||||
|
||||
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
|
||||
gpui_kit::assets::AllAssets.list(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_client_set_is_embedded_and_sorted() {
|
||||
assert!(ICONS.len() >= 140, "{} icons", ICONS.len());
|
||||
assert!(ICONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
|
||||
for (name, bytes) in ICONS {
|
||||
assert!(std::str::from_utf8(bytes).is_ok_and(|text| text.contains("<svg")), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_icon_answers_before_gpui_kit_assets() {
|
||||
let name = client_icon_names().find(|n| *n == "mic.svg").expect("the client has a mic");
|
||||
let ours = client_icon(name).unwrap();
|
||||
let kit = gpui_kit::assets::AllAssets
|
||||
.load(&format!("icons/{name}"))
|
||||
.unwrap()
|
||||
.expect("gpui-kit-assets has a mic too");
|
||||
let served = Assets.load(&format!("icons/{name}")).unwrap().unwrap();
|
||||
assert_eq!(&*served, ours);
|
||||
assert_ne!(&*kit, ours, "Lucide 1.43 and 1.48 draw it differently, or this test is moot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_icons_and_other_paths_fall_through_to_gpui_kit_assets() {
|
||||
let kit = gpui_kit::assets::AllAssets.list("icons/").unwrap();
|
||||
let only_in_kit = kit
|
||||
.iter()
|
||||
.find(|path| client_icon(path.trim_start_matches("icons/")).is_none())
|
||||
.expect("the catalogue has icons the client lacks");
|
||||
assert!(Assets.load(only_in_kit).unwrap().is_some(), "{only_in_kit}");
|
||||
// gpui-kit-assets answers a path it does not have with an error, so do we.
|
||||
assert!(Assets.load("icons/no-such-icon.svg").is_err());
|
||||
assert!(Assets.load("nothing/here").is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,47 @@
|
||||
//! The development switches of the GPUI front end, read from the
|
||||
//! environment. They are the Slint front end's (docs/ui.md, "Development
|
||||
//! switches and screenshots") where the GPUI one has the same thing to
|
||||
//! switch, so that one recipe serves both.
|
||||
//! switch, so that one recipe serves both; the rest are new.
|
||||
//!
|
||||
//! - `VOELIN_OPEN=swatch`: the swatch page (every theme token, a few
|
||||
//! components, the icons) in place of the shell. The Slint front end's
|
||||
//! other pages do not exist here yet; they are named in a warning and
|
||||
//! skipped.
|
||||
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
|
||||
//! one the settings will give (`ui.theme` in the Slint front end).
|
||||
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
|
||||
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
|
||||
|
||||
use crate::theme::Choice;
|
||||
|
||||
/// A page the window can be opened on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Page {
|
||||
/// The shell. Today an empty window with the state line.
|
||||
Shell,
|
||||
/// Every theme token, a few components and the icons.
|
||||
Swatch,
|
||||
}
|
||||
|
||||
/// What the environment switched.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Switches {
|
||||
/// The page to open on.
|
||||
pub open: Page,
|
||||
/// The theme mode, when the switch names one.
|
||||
pub theme: Option<Choice>,
|
||||
/// The text size factor, when the switch names one.
|
||||
pub font_scale: Option<f32>,
|
||||
/// The window's size in pixels, when the switch names one.
|
||||
pub window: Option<(f32, f32)>,
|
||||
}
|
||||
|
||||
impl Default for Switches {
|
||||
fn default() -> Self {
|
||||
Self { open: Page::Shell, theme: None, font_scale: None, window: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Switches {
|
||||
/// The switches of this process's environment.
|
||||
pub fn from_env() -> Self {
|
||||
@@ -22,6 +52,28 @@ impl Switches {
|
||||
/// and left out.
|
||||
pub fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let mut switches = Self::default();
|
||||
if let Some(list) = get("VOELIN_OPEN") {
|
||||
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
|
||||
match what {
|
||||
"swatch" => switches.open = Page::Swatch,
|
||||
other => tracing::warn!(
|
||||
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch is)"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(name) = get("VOELIN_DEV_THEME") {
|
||||
match Choice::parse(name.trim()) {
|
||||
Some(choice) => switches.theme = Some(choice),
|
||||
None => tracing::warn!("VOELIN_DEV_THEME={name}: dark, light or system"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_FONT_SCALE") {
|
||||
match text.trim().parse::<f32>() {
|
||||
Ok(scale) if (0.5..=3.0).contains(&scale) => switches.font_scale = Some(scale),
|
||||
_ => tracing::warn!("VOELIN_FONT_SCALE={text}: a number from 0.5 to 3"),
|
||||
}
|
||||
}
|
||||
if let Some(text) = get("VOELIN_WINDOW_SIZE") {
|
||||
match parse_size(&text) {
|
||||
Some(size) => switches.window = Some(size),
|
||||
@@ -41,23 +93,43 @@ fn parse_size(text: &str) -> Option<(f32, f32)> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn size_of(text: &str) -> Switches {
|
||||
let text = text.to_owned();
|
||||
Switches::parse(|name| (name == "VOELIN_WINDOW_SIZE").then(|| text.clone()))
|
||||
fn env(pairs: &[(&str, &str)]) -> Switches {
|
||||
let map: HashMap<String, String> =
|
||||
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
Switches::parse(|name| map.get(name).cloned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_size_is_read() {
|
||||
assert_eq!(size_of("1440x960").window, Some((1440.0, 960.0)));
|
||||
assert_eq!(Switches::parse(|_| None), Switches::default());
|
||||
fn nothing_switched_is_the_shell_in_the_settings_theme() {
|
||||
assert_eq!(env(&[]), Switches::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_switch_is_read() {
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "swatch"),
|
||||
("VOELIN_DEV_THEME", "light"),
|
||||
("VOELIN_FONT_SCALE", "1.25"),
|
||||
("VOELIN_WINDOW_SIZE", "1440x960"),
|
||||
]);
|
||||
assert_eq!(s.open, Page::Swatch);
|
||||
assert_eq!(s.theme, Some(Choice::Light));
|
||||
assert_eq!(s.font_scale, Some(1.25));
|
||||
assert_eq!(s.window, Some((1440.0, 960.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_makes_no_sense_is_left_out() {
|
||||
for text in ["10x10", "1440", "axb", "99999x99999", ""] {
|
||||
assert_eq!(size_of(text), Switches::default(), "{text:?}");
|
||||
}
|
||||
let s = env(&[
|
||||
("VOELIN_OPEN", "settings:voice,home"),
|
||||
("VOELIN_DEV_THEME", "blue"),
|
||||
("VOELIN_FONT_SCALE", "9"),
|
||||
("VOELIN_WINDOW_SIZE", "10x10"),
|
||||
]);
|
||||
assert_eq!(s, Switches::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Inter, the UI font, as the Slint front end bundles it
|
||||
//! (`crates/voelin-ui/ui/assets/fonts`, OFL): the five files go into GPUI's
|
||||
//! text system and are used by family name ([`crate::theme::FONT_FAMILY`]),
|
||||
//! so nothing depends on what fontconfig finds for Latin text. Colour emoji
|
||||
//! come later (the chat slice; docs/design/gpui-spikes.md, "Emoji").
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::App;
|
||||
|
||||
/// The files of the family: regular, medium, semibold, bold, italic.
|
||||
const INTER: [&[u8]; 5] = [
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
|
||||
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
|
||||
];
|
||||
|
||||
/// Add Inter to GPUI's text system.
|
||||
pub fn load(cx: &mut App) {
|
||||
let fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|bytes| Cow::Borrowed(*bytes)).collect();
|
||||
if let Err(error) = cx.text_system().add_fonts(fonts) {
|
||||
tracing::warn!(%error, "cannot add Inter to the text system");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_files_are_fonts() {
|
||||
for bytes in INTER {
|
||||
assert!(bytes.len() > 100_000, "a font file, not {} bytes", bytes.len());
|
||||
assert!(matches!(&bytes[..4], [0, 1, 0, 0] | b"OTTO" | b"true"), "an sfnt header");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,12 @@
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub mod app;
|
||||
pub mod assets;
|
||||
pub mod dev;
|
||||
pub mod engine;
|
||||
pub mod fonts;
|
||||
pub mod swatch;
|
||||
pub mod theme;
|
||||
pub mod view;
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -19,8 +23,10 @@ use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOption
|
||||
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::assets::Assets;
|
||||
use crate::dev::Switches;
|
||||
use crate::engine::HostedEngine;
|
||||
use crate::theme::{Choice, VoelinTheme};
|
||||
use crate::view::MainView;
|
||||
|
||||
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
|
||||
@@ -63,9 +69,13 @@ fn open_main_window(cx: &mut App, switches: &Switches, engine: HostedEngine) ->
|
||||
let HostedEngine { engine, events, .. } = engine;
|
||||
let app = cx.new(move |cx| AppState::new(Some(engine), events, cx));
|
||||
let options = window_options(switches, cx);
|
||||
let page = switches.open;
|
||||
gpui_kit::open_window(options, cx, {
|
||||
let app = app.clone();
|
||||
move |window, cx| {
|
||||
// The window's own appearance, which may differ from the system's before
|
||||
// the window exists.
|
||||
VoelinTheme::set_system_appearance(cx, window.appearance());
|
||||
window.on_window_should_close(cx, {
|
||||
let app = app.clone();
|
||||
move |_, cx| {
|
||||
@@ -74,7 +84,7 @@ fn open_main_window(cx: &mut App, switches: &Switches, engine: HostedEngine) ->
|
||||
true
|
||||
}
|
||||
});
|
||||
cx.new(|cx| MainView::new(app, cx))
|
||||
cx.new(|cx| MainView::new(app, page, window, cx))
|
||||
}
|
||||
})
|
||||
.context("cannot open the main window")?;
|
||||
@@ -97,10 +107,19 @@ pub fn run() -> Result<()> {
|
||||
.context("cannot start the engine's runtime")?;
|
||||
let hosted = HostedEngine::start(&runtime);
|
||||
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
|
||||
gpui_kit::application().run({
|
||||
gpui_kit::application().with_assets(Assets).run({
|
||||
let failure = failure.clone();
|
||||
move |cx| {
|
||||
gpui_kit::init(cx);
|
||||
fonts::load(cx);
|
||||
// Until the settings are read here (the shell slice), the mode and
|
||||
// the text size are the development switches' or the defaults.
|
||||
VoelinTheme::init(
|
||||
cx,
|
||||
switches.theme.unwrap_or(Choice::System),
|
||||
cx.window_appearance(),
|
||||
switches.font_scale.unwrap_or(1.0),
|
||||
);
|
||||
if let Err(e) = open_main_window(cx, &switches, hosted) {
|
||||
*failure.borrow_mut() = Some(e);
|
||||
cx.quit();
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
//! The swatch page: every colour token of the theme with its name and value,
|
||||
//! the radii, the spacing, the type scale, a few gpui-component widgets (drawn
|
||||
//! from the second layer of the theme) and the client's icons, in the mode
|
||||
//! the theme is in. A development page (`VOELIN_OPEN=swatch`): the screenshots
|
||||
//! of a theme change, and what the screenshots in docs/ui/ show.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::checkbox::Checkbox;
|
||||
use gpui_kit::component::switch::Switch;
|
||||
use gpui_kit::{
|
||||
FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
|
||||
StatefulInteractiveElement as _, Styled as _, div, linear_color_stop, linear_gradient, px, svg,
|
||||
};
|
||||
|
||||
use crate::theme::{VoelinTheme, hsla, tokens::Rgba};
|
||||
|
||||
/// The colour tokens by the groups of docs/ui.md's "Theme tokens" table.
|
||||
pub const GROUPS: [(&str, &[&str]); 6] = [
|
||||
(
|
||||
"Backgrounds",
|
||||
&[
|
||||
"bg-app",
|
||||
"bg-rail",
|
||||
"surface",
|
||||
"surface-2",
|
||||
"surface-3",
|
||||
"surface-4",
|
||||
"scrim",
|
||||
"scrim-light",
|
||||
"overlay",
|
||||
],
|
||||
),
|
||||
("Lines", &["border", "border-strong", "border-popup", "glow"]),
|
||||
(
|
||||
"Accent",
|
||||
&[
|
||||
"accent",
|
||||
"accent-hover",
|
||||
"accent-pressed",
|
||||
"accent-soft",
|
||||
"accent-soft-hover",
|
||||
"accent-text",
|
||||
"name-text",
|
||||
"on-accent",
|
||||
],
|
||||
),
|
||||
(
|
||||
"States",
|
||||
&[
|
||||
"live",
|
||||
"live-soft",
|
||||
"danger",
|
||||
"danger-soft",
|
||||
"success",
|
||||
"success-soft",
|
||||
"warning",
|
||||
"warning-soft",
|
||||
"idle",
|
||||
"dnd",
|
||||
"offline",
|
||||
"gold",
|
||||
"info",
|
||||
],
|
||||
),
|
||||
("Text", &["text", "text-secondary", "text-muted", "text-disabled", "icon"]),
|
||||
("Meter", &["meter-low", "meter-mid", "meter-high", "meter-off"]),
|
||||
];
|
||||
|
||||
/// Icons shown, by the name of the client's file.
|
||||
const ICONS: [&str; 16] = [
|
||||
"mic.svg",
|
||||
"mic-off.svg",
|
||||
"headphones.svg",
|
||||
"volume-2.svg",
|
||||
"settings.svg",
|
||||
"search.svg",
|
||||
"bell.svg",
|
||||
"users.svg",
|
||||
"message-square.svg",
|
||||
"monitor-up.svg",
|
||||
"hash.svg",
|
||||
"lock.svg",
|
||||
"crown.svg",
|
||||
"plus.svg",
|
||||
"x.svg",
|
||||
"check.svg",
|
||||
];
|
||||
|
||||
fn heading(theme: &VoelinTheme, text: &str) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.text_size(px(m.font_md))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(hsla(theme.colors.text))
|
||||
.child(text.to_owned())
|
||||
}
|
||||
|
||||
fn chip(theme: &VoelinTheme, name: &str, color: Rgba) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.w(px(100.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(2.0))
|
||||
.child(
|
||||
div()
|
||||
.h(px(24.0))
|
||||
.rounded(px(m.radius_xs))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_strong))
|
||||
.bg(hsla(color)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(name.to_owned()),
|
||||
)
|
||||
.child(
|
||||
div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(color.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
fn colours(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let by_name: HashMap<&str, Rgba> = c.entries().into_iter().collect();
|
||||
let mut column = div().flex().flex_col().gap(px(m.space_4));
|
||||
for (group, names) in GROUPS {
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_3));
|
||||
for name in names {
|
||||
row = row.child(chip(theme, name, by_name[name]));
|
||||
}
|
||||
column = column.child(
|
||||
div().flex().flex_col().gap(px(m.space_2)).child(heading(theme, group)).child(row),
|
||||
);
|
||||
}
|
||||
column
|
||||
}
|
||||
|
||||
fn radii(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().gap(px(m.space_4));
|
||||
for (name, radius) in [
|
||||
("xs", m.radius_xs),
|
||||
("sm", m.radius_sm),
|
||||
("md", m.radius_md),
|
||||
("lg", m.radius_lg),
|
||||
("xl", m.radius_xl),
|
||||
("pill", m.radius_pill),
|
||||
] {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.gap(px(m.space_2))
|
||||
.child(
|
||||
div()
|
||||
.size(px(40.0))
|
||||
.rounded(px(radius))
|
||||
.bg(hsla(c.surface_4))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border_popup)),
|
||||
)
|
||||
.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(name)),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Radii")).child(row)
|
||||
}
|
||||
|
||||
fn spacing(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col().gap(px(m.space_1));
|
||||
for (name, space) in [
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.w(px(56.0))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(name),
|
||||
)
|
||||
.child(div().h(px(6.0)).w(px(space * 4.0)).rounded(px(2.0)).bg(hsla(c.accent)))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child(format!("{space} px")),
|
||||
),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Spacing")).child(rows)
|
||||
}
|
||||
|
||||
fn type_scale(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut rows = div().flex().flex_col();
|
||||
for (name, size, weight) in [
|
||||
("font-3xl", m.font_3xl, FontWeight::BOLD),
|
||||
("font-2xl", m.font_2xl, FontWeight::SEMIBOLD),
|
||||
("font-xl", m.font_xl, FontWeight::SEMIBOLD),
|
||||
("font-lg", m.font_lg, FontWeight::MEDIUM),
|
||||
("font-md", m.font_md, FontWeight::MEDIUM),
|
||||
("font-body", m.font_body, FontWeight::NORMAL),
|
||||
("font-sm", m.font_sm, FontWeight::NORMAL),
|
||||
("font-xs", m.font_xs, FontWeight::NORMAL),
|
||||
] {
|
||||
rows = rows.child(
|
||||
div()
|
||||
.text_size(px(size))
|
||||
.font_weight(weight)
|
||||
.text_color(hsla(c.text))
|
||||
.child(format!("{name} {size}: Raid tonight at 21:00")),
|
||||
);
|
||||
}
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Type")).child(rows)
|
||||
}
|
||||
|
||||
fn components(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let m = &theme.metrics;
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Components (gpui-component, through ThemeColor)"))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_wrap()
|
||||
.gap(px(m.space_3))
|
||||
.child(Button::new("primary").primary().label("Primary"))
|
||||
.child(Button::new("secondary").label("Secondary"))
|
||||
.child(Button::new("danger").danger().label("Danger"))
|
||||
.child(Button::new("success").success().label("Success"))
|
||||
.child(Button::new("warning").warning().label("Warning"))
|
||||
.child(Button::new("info").info().label("Info")),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(px(m.space_5))
|
||||
.child(Switch::new("on").checked(true))
|
||||
.child(Switch::new("off").checked(false))
|
||||
.child(Checkbox::new("checked").checked(true).label("Checked"))
|
||||
.child(Checkbox::new("unchecked").checked(false).label("Unchecked")),
|
||||
)
|
||||
}
|
||||
|
||||
fn backdrop(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m, b) = (&theme.colors, &theme.metrics, &theme.backdrop);
|
||||
let [first, _, last] = b.stops;
|
||||
// GPUI's gradient has two colour stops: the first and the last of three.
|
||||
let gradient = linear_gradient(
|
||||
b.angle,
|
||||
linear_color_stop(hsla(first.0), first.1),
|
||||
linear_color_stop(hsla(last.0), last.1),
|
||||
);
|
||||
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Backdrop")).child(
|
||||
div()
|
||||
.h(px(36.0))
|
||||
.rounded(px(m.radius_md))
|
||||
.border_1()
|
||||
.border_color(hsla(c.border))
|
||||
.bg(gradient)
|
||||
.px(px(m.space_3))
|
||||
.py(px(m.space_2))
|
||||
.text_size(px(m.font_xs))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(format!(
|
||||
"{}deg: {} to {}; the middle stop, {} at {}%, is not drawn",
|
||||
b.angle,
|
||||
first.0,
|
||||
last.0,
|
||||
b.stops[1].0,
|
||||
(b.stops[1].1 * 100.0).round()
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
fn icons(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_5));
|
||||
for name in ICONS {
|
||||
row = row.child(
|
||||
svg().path(format!("icons/{name}")).size(px(m.icon_lg)).text_color(hsla(c.icon)),
|
||||
);
|
||||
}
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_3))
|
||||
.child(heading(theme, "Icons (the client's Lucide 1.48, as gpui-component's icons/ paths)"))
|
||||
.child(row)
|
||||
}
|
||||
|
||||
/// The page: the colours on the left, the rest on the right; it scrolls when
|
||||
/// the window is smaller than it.
|
||||
pub fn swatch(theme: &VoelinTheme) -> impl IntoElement {
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
div()
|
||||
.id("swatch")
|
||||
.size_full()
|
||||
.overflow_y_scroll()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.p(px(m.space_6))
|
||||
.bg(hsla(c.bg_app))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_baseline()
|
||||
.gap(px(m.space_4))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_2xl))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.text_color(hsla(c.text))
|
||||
.child("Voelin theme"),
|
||||
)
|
||||
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(
|
||||
format!(
|
||||
"{} (setting {}), text size {}",
|
||||
if theme.is_dark() { "dark" } else { "light" },
|
||||
theme.choice().name(),
|
||||
m.font_scale
|
||||
),
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(px(m.space_8))
|
||||
.child(div().w(px(752.0)).flex_none().child(colours(theme)))
|
||||
.child(
|
||||
div()
|
||||
.w(px(600.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(m.space_4))
|
||||
.child(backdrop(theme))
|
||||
.child(radii(theme))
|
||||
.child(spacing(theme))
|
||||
.child(type_scale(theme))
|
||||
.child(components(theme))
|
||||
.child(icons(theme)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::*;
|
||||
use crate::assets::client_icon;
|
||||
use crate::theme::Palette;
|
||||
|
||||
#[test]
|
||||
fn every_colour_token_is_in_exactly_one_group() {
|
||||
let shown: Vec<&str> = GROUPS.iter().flat_map(|(_, names)| names.iter().copied()).collect();
|
||||
let unique: BTreeSet<&str> = shown.iter().copied().collect();
|
||||
assert_eq!(shown.len(), unique.len(), "a token in two groups");
|
||||
let tokens: BTreeSet<&str> = Palette::DARK.entries().into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(unique, tokens);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_icons_shown_are_the_clients() {
|
||||
for name in ICONS {
|
||||
assert!(client_icon(name).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! The second layer of the theme: the colours gpui-component's widgets read,
|
||||
//! written from the Voelin palette. gpui-component's `ThemeColor` is shadcn's
|
||||
//! vocabulary (about 135 colours: a background, a primary, a muted, one set
|
||||
//! for the list, one for the table, one for each kind of button); the
|
||||
//! client's tokens map onto it as docs/ui.md ("The GPUI front end") lists.
|
||||
//! What has no counterpart stays as the registered theme of the mode has it
|
||||
//! (charts' bullish and bearish colours, the cyan and magenta of the base
|
||||
//! palette).
|
||||
//!
|
||||
//! gpui-component's "accent" is a hover background, not a brand colour: the
|
||||
//! client's `accent` is its `primary`.
|
||||
|
||||
use gpui_kit::Hsla;
|
||||
use gpui_kit::component::ThemeColor;
|
||||
|
||||
use super::tokens::{Palette, Rgba};
|
||||
|
||||
/// A palette colour as GPUI's.
|
||||
pub fn hsla(color: Rgba) -> Hsla {
|
||||
gpui_kit::rgba(color.0).into()
|
||||
}
|
||||
|
||||
/// Of `base`, the colours a status button needs: hover, active, and a text
|
||||
/// that reads on it (white or the window's ink, whichever contrasts more).
|
||||
struct Status {
|
||||
base: Hsla,
|
||||
hover: Hsla,
|
||||
active: Hsla,
|
||||
foreground: Hsla,
|
||||
}
|
||||
|
||||
fn status(base: Rgba, ink: Rgba, dark: bool) -> Status {
|
||||
let toward_hover = if dark { Rgba(0xffff_ffff) } else { Rgba(0x0000_00ff) };
|
||||
Status {
|
||||
base: hsla(base),
|
||||
hover: hsla(base.mix(toward_hover, 0.14)),
|
||||
active: hsla(base.mix(Rgba(0x0000_00ff), 0.18)),
|
||||
foreground: hsla(base.readable(ink)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the palette's colours into `colors`, over what the registered theme
|
||||
/// of the mode left there. Every field that gpui-component's themes derive
|
||||
/// from another (the buttons fall back to `primary`, `danger`, ...) is written
|
||||
/// too, so that none keeps the default theme's blue.
|
||||
pub fn write(p: &Palette, dark: bool, colors: &mut ThemeColor) {
|
||||
let c = colors;
|
||||
let h = hsla;
|
||||
let clear = Hsla::transparent_black();
|
||||
|
||||
// The window and its text.
|
||||
c.background = h(p.bg_app);
|
||||
c.foreground = h(p.text);
|
||||
c.border = h(p.border);
|
||||
c.input = h(p.border_strong);
|
||||
c.ring = h(p.glow);
|
||||
c.overlay = h(p.scrim);
|
||||
c.window_border = h(p.border);
|
||||
c.caret = h(p.text);
|
||||
c.selection = h(p.accent_soft);
|
||||
c.drag_border = h(p.accent);
|
||||
c.drop_target = h(p.accent_soft);
|
||||
|
||||
// Links: one colour for all three states, as the client has one.
|
||||
c.link = h(p.accent_text);
|
||||
c.link_hover = h(p.accent_text);
|
||||
c.link_active = h(p.accent_text);
|
||||
|
||||
// The brand colour, and gpui-component's hover "accent".
|
||||
c.primary = h(p.accent);
|
||||
c.primary_hover = h(p.accent_hover);
|
||||
c.primary_active = h(p.accent_pressed);
|
||||
c.primary_foreground = h(p.on_accent);
|
||||
c.accent = h(p.surface_3);
|
||||
c.accent_foreground = h(p.text);
|
||||
|
||||
// Cards, inputs, menus, popovers.
|
||||
c.secondary = h(p.surface_2);
|
||||
c.secondary_hover = h(p.surface_3);
|
||||
c.secondary_active = h(p.surface_4);
|
||||
c.secondary_foreground = h(p.text);
|
||||
c.muted = h(p.surface_2);
|
||||
c.muted_foreground = h(p.text_muted);
|
||||
c.popover = h(p.surface_3);
|
||||
c.popover_foreground = h(p.text);
|
||||
c.group_box = h(p.surface_2);
|
||||
c.group_box_foreground = h(p.text);
|
||||
c.accordion = h(p.surface_2);
|
||||
c.description_list_label = h(p.surface_2);
|
||||
c.description_list_label_foreground = h(p.text_secondary);
|
||||
|
||||
// The status colours, with the text that reads on each.
|
||||
let [danger, success, warning, info] =
|
||||
[p.danger, p.success, p.warning, p.info].map(|base| status(base, p.bg_app, dark));
|
||||
(c.danger, c.danger_hover, c.danger_active, c.danger_foreground) =
|
||||
(danger.base, danger.hover, danger.active, danger.foreground);
|
||||
(c.success, c.success_hover, c.success_active, c.success_foreground) =
|
||||
(success.base, success.hover, success.active, success.foreground);
|
||||
(c.warning, c.warning_hover, c.warning_active, c.warning_foreground) =
|
||||
(warning.base, warning.hover, warning.active, warning.foreground);
|
||||
(c.info, c.info_hover, c.info_active, c.info_foreground) =
|
||||
(info.base, info.hover, info.active, info.foreground);
|
||||
|
||||
// Lists and tables: rows on the panel, hovered rows raised, the selected
|
||||
// row the soft accent with the accent's edge.
|
||||
c.list = h(p.surface);
|
||||
c.list_hover = h(p.surface_3);
|
||||
c.list_active = h(p.accent_soft);
|
||||
c.list_active_border = h(p.accent);
|
||||
c.list_even = h(p.surface);
|
||||
c.list_head = h(p.surface_2);
|
||||
c.table = h(p.surface);
|
||||
c.table_hover = h(p.surface_3);
|
||||
c.table_active = h(p.accent_soft);
|
||||
c.table_active_border = h(p.accent);
|
||||
c.table_even = h(p.surface);
|
||||
c.table_head = h(p.surface_2);
|
||||
c.table_head_foreground = h(p.text_secondary);
|
||||
c.table_foot = h(p.surface_2);
|
||||
c.table_foot_foreground = h(p.text_secondary);
|
||||
c.table_row_border = h(p.border);
|
||||
|
||||
// The panels around the content: the sidebar, the title and status bars.
|
||||
c.sidebar = h(p.surface);
|
||||
c.sidebar_foreground = h(p.text);
|
||||
c.sidebar_border = h(p.border);
|
||||
c.sidebar_accent = h(p.surface_3);
|
||||
c.sidebar_accent_foreground = h(p.text);
|
||||
c.sidebar_primary = h(p.accent);
|
||||
c.sidebar_primary_foreground = h(p.on_accent);
|
||||
c.title_bar = h(p.surface);
|
||||
c.title_bar_border = h(p.border);
|
||||
c.status_bar = h(p.surface);
|
||||
c.status_bar_border = h(p.border);
|
||||
|
||||
// Small widgets.
|
||||
c.scrollbar = clear;
|
||||
c.scrollbar_thumb = h(p.border_strong);
|
||||
c.scrollbar_thumb_hover = h(p.text_muted);
|
||||
c.slider_bar = h(p.accent);
|
||||
c.slider_thumb = h(p.on_accent);
|
||||
c.switch = h(p.surface_4);
|
||||
c.switch_thumb = h(p.on_accent);
|
||||
c.progress_bar = h(p.accent);
|
||||
c.skeleton = h(p.surface_3);
|
||||
c.tab = clear;
|
||||
c.tab_active = h(p.surface_2);
|
||||
c.tab_active_foreground = h(p.text);
|
||||
c.tab_bar = h(p.surface);
|
||||
c.tab_bar_segmented = h(p.surface_2);
|
||||
c.tab_foreground = h(p.text_secondary);
|
||||
|
||||
// The base palette and the charts: the client's state colours.
|
||||
c.red = h(p.danger);
|
||||
c.red_light = h(p.danger_soft);
|
||||
c.green = h(p.success);
|
||||
c.green_light = h(p.success_soft);
|
||||
c.yellow = h(p.warning);
|
||||
c.yellow_light = h(p.warning_soft);
|
||||
c.blue = h(p.info);
|
||||
c.blue_light = h(p.accent_soft);
|
||||
c.chart_1 = h(p.accent);
|
||||
c.chart_2 = h(p.success);
|
||||
c.chart_3 = h(p.warning);
|
||||
c.chart_4 = h(p.danger);
|
||||
c.chart_5 = h(p.info);
|
||||
|
||||
// The buttons: what a theme file leaves out they take from the colours
|
||||
// above, so they are written from them here.
|
||||
c.button = c.secondary;
|
||||
c.button_hover = c.secondary_hover;
|
||||
c.button_active = c.secondary_active;
|
||||
c.button_foreground = c.secondary_foreground;
|
||||
c.button_primary = c.primary;
|
||||
c.button_primary_hover = c.primary_hover;
|
||||
c.button_primary_active = c.primary_active;
|
||||
c.button_primary_foreground = c.primary_foreground;
|
||||
c.button_secondary = c.secondary;
|
||||
c.button_secondary_hover = c.secondary_hover;
|
||||
c.button_secondary_active = c.secondary_active;
|
||||
c.button_secondary_foreground = c.secondary_foreground;
|
||||
c.button_danger = c.danger;
|
||||
c.button_danger_hover = c.danger_hover;
|
||||
c.button_danger_active = c.danger_active;
|
||||
c.button_danger_foreground = c.danger_foreground;
|
||||
c.button_success = c.success;
|
||||
c.button_success_hover = c.success_hover;
|
||||
c.button_success_active = c.success_active;
|
||||
c.button_success_foreground = c.success_foreground;
|
||||
c.button_warning = c.warning;
|
||||
c.button_warning_hover = c.warning_hover;
|
||||
c.button_warning_active = c.warning_active;
|
||||
c.button_warning_foreground = c.warning_foreground;
|
||||
c.button_info = c.info;
|
||||
c.button_info_hover = c.info_hover;
|
||||
c.button_info_active = c.info_active;
|
||||
c.button_info_foreground = c.info_foreground;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn written(dark: bool) -> (Palette, ThemeColor) {
|
||||
let palette = if dark { Palette::DARK } else { Palette::LIGHT };
|
||||
let mut colors = ThemeColor::default();
|
||||
write(&palette, dark, &mut colors);
|
||||
(palette, colors)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_client_tokens_land_where_the_table_says() {
|
||||
for dark in [true, false] {
|
||||
let (p, c) = written(dark);
|
||||
assert_eq!(c.background, hsla(p.bg_app));
|
||||
assert_eq!(c.foreground, hsla(p.text));
|
||||
assert_eq!(c.primary, hsla(p.accent));
|
||||
assert_eq!(c.primary_hover, hsla(p.accent_hover));
|
||||
assert_eq!(c.primary_active, hsla(p.accent_pressed));
|
||||
assert_eq!(c.primary_foreground, hsla(p.on_accent));
|
||||
assert_eq!(
|
||||
c.accent,
|
||||
hsla(p.surface_3),
|
||||
"gpui-component's accent is a hover background"
|
||||
);
|
||||
assert_eq!(c.secondary, hsla(p.surface_2));
|
||||
assert_eq!(c.secondary_active, hsla(p.surface_4));
|
||||
assert_eq!(c.border, hsla(p.border));
|
||||
assert_eq!(c.input, hsla(p.border_strong));
|
||||
assert_eq!(c.ring, hsla(p.glow));
|
||||
assert_eq!(c.overlay, hsla(p.scrim));
|
||||
assert_eq!(c.list_active, hsla(p.accent_soft));
|
||||
assert_eq!(c.link, hsla(p.accent_text));
|
||||
assert_eq!(c.muted_foreground, hsla(p.text_muted));
|
||||
assert_eq!(c.sidebar, hsla(p.surface));
|
||||
assert_eq!(c.danger, hsla(p.danger));
|
||||
assert_eq!(c.success, hsla(p.success));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_buttons_follow_the_colours_they_fall_back_to() {
|
||||
let (_, c) = written(true);
|
||||
assert_eq!(c.button_primary, c.primary);
|
||||
assert_eq!(c.button_primary_hover, c.primary_hover);
|
||||
assert_eq!(c.button_danger_foreground, c.danger_foreground);
|
||||
assert_eq!(c.button, c.secondary);
|
||||
assert_eq!(c.button_info_active, c.info_active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_on_a_status_colour_is_the_one_that_reads_better() {
|
||||
for (p, dark) in [(Palette::DARK, true), (Palette::LIGHT, false)] {
|
||||
for base in [p.danger, p.success, p.warning, p.info] {
|
||||
let s = status(base, p.bg_app, dark);
|
||||
let chosen = base.readable(p.bg_app);
|
||||
let other = if chosen == Rgba(0xffff_ffff) { p.bg_app } else { Rgba(0xffff_ffff) };
|
||||
assert!(base.contrast(chosen) >= base.contrast(other), "{base} on {chosen}");
|
||||
assert_eq!(s.foreground, hsla(chosen));
|
||||
assert_ne!(s.hover, s.base);
|
||||
assert_ne!(s.active, s.base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixing_and_contrast_do_what_they_say() {
|
||||
let (black, white) = (Rgba(0x0000_00ff), Rgba(0xffff_ffff));
|
||||
assert_eq!(black.mix(white, 0.0), black);
|
||||
assert_eq!(black.mix(white, 1.0), white);
|
||||
assert_eq!(Rgba(0x1020_30c0).mix(white, 0.0), Rgba(0x1020_30c0), "opacity stays");
|
||||
assert!((black.contrast(white) - 21.0).abs() < 0.01);
|
||||
assert_eq!(black.readable(black), white);
|
||||
assert_eq!(Rgba(0xf5b3_01ff).readable(Rgba(0x060a_18ff)), Rgba(0x060a_18ff));
|
||||
assert_eq!(Rgba(0x12ab_34ff).to_string(), "#12ab34");
|
||||
assert_eq!(Rgba(0x12ab_3480).to_string(), "#12ab3480");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! The Voelin theme, in two layers (docs/ui.md, "The GPUI front end"):
|
||||
//!
|
||||
//! 1. [`VoelinTheme`], a GPUI global with every token of
|
||||
//! `crates/voelin-ui/ui/theme.slint`, light and dark ([`tokens`]), which a
|
||||
//! test keeps equal to the Slint file ([`slint_parity`]). The shell's own
|
||||
//! elements (the server rail, presence dots, meters, the backdrop) read it.
|
||||
//! 2. gpui-component's `ThemeColor`, the colours its widgets (inputs, lists,
|
||||
//! menus, dialogs) read, written from the first on every change
|
||||
//! ([`components`]), so that they look like ours.
|
||||
//!
|
||||
//! The mode is the client's `ui.theme`: `system` follows the window's
|
||||
//! appearance (and its changes), `light` and `dark` do not.
|
||||
|
||||
mod components;
|
||||
#[cfg(test)]
|
||||
mod slint_parity;
|
||||
pub mod tokens;
|
||||
|
||||
pub use components::hsla;
|
||||
use gpui_kit::component::{Theme, ThemeMode};
|
||||
use gpui_kit::{App, Global, WindowAppearance, px};
|
||||
pub use tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
/// The theme mode setting (`ui.theme` of the Slint front end).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Choice {
|
||||
/// Follow the window's appearance.
|
||||
System,
|
||||
/// Always light.
|
||||
Light,
|
||||
/// Always dark.
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
/// `system`, `light` or `dark`.
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
match text {
|
||||
"system" => Some(Self::System),
|
||||
"light" => Some(Self::Light),
|
||||
"dark" => Some(Self::Dark),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The setting's value.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the theme is dark, given whether the window's appearance is.
|
||||
pub fn resolve(self, system_dark: bool) -> bool {
|
||||
match self {
|
||||
Self::System => system_dark,
|
||||
Self::Light => false,
|
||||
Self::Dark => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a window's appearance is a dark one.
|
||||
pub fn is_dark(appearance: WindowAppearance) -> bool {
|
||||
matches!(appearance, WindowAppearance::Dark | WindowAppearance::VibrantDark)
|
||||
}
|
||||
|
||||
/// Every token of `theme.slint` for the resolved mode and text size; a GPUI
|
||||
/// global.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoelinTheme {
|
||||
choice: Choice,
|
||||
dark: bool,
|
||||
/// The colours of the resolved mode.
|
||||
pub colors: Palette,
|
||||
/// The window's backdrop gradient of the resolved mode.
|
||||
pub backdrop: Backdrop,
|
||||
/// The sizes, radii, type and durations at the text size factor.
|
||||
pub metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Global for VoelinTheme {}
|
||||
|
||||
impl VoelinTheme {
|
||||
/// The tokens for a mode (resolved against `system_dark`) and a text size
|
||||
/// factor.
|
||||
pub fn new(choice: Choice, system_dark: bool, font_scale: f32) -> Self {
|
||||
let dark = choice.resolve(system_dark);
|
||||
Self {
|
||||
choice,
|
||||
dark,
|
||||
colors: if dark { Palette::DARK } else { Palette::LIGHT },
|
||||
backdrop: if dark { Backdrop::DARK } else { Backdrop::LIGHT },
|
||||
metrics: Metrics::new(font_scale),
|
||||
}
|
||||
}
|
||||
|
||||
/// The theme mode that was set.
|
||||
pub fn choice(&self) -> Choice {
|
||||
self.choice
|
||||
}
|
||||
|
||||
/// Whether the colours are the dark ones.
|
||||
pub fn is_dark(&self) -> bool {
|
||||
self.dark
|
||||
}
|
||||
|
||||
/// Install the theme as the global and write it into gpui-component, which
|
||||
/// `gpui_kit::init` must have set up. `appearance` is the window's (or
|
||||
/// the system's before there is a window).
|
||||
pub fn init(cx: &mut App, choice: Choice, appearance: WindowAppearance, font_scale: f32) {
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The theme global.
|
||||
pub fn global(cx: &App) -> &Self {
|
||||
cx.global::<Self>()
|
||||
}
|
||||
|
||||
/// Change the mode (a setting changed), given the window's appearance now.
|
||||
pub fn set_choice(cx: &mut App, choice: Choice, appearance: WindowAppearance) {
|
||||
let (scale, current) = {
|
||||
let this = Self::global(cx);
|
||||
(this.metrics.font_scale, this.choice)
|
||||
};
|
||||
if current == choice && Self::global(cx).dark == choice.resolve(is_dark(appearance)) {
|
||||
return;
|
||||
}
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// The window's appearance changed; it matters only in `system` mode.
|
||||
pub fn set_system_appearance(cx: &mut App, appearance: WindowAppearance) {
|
||||
let this = Self::global(cx);
|
||||
if this.choice == Choice::System && this.dark != is_dark(appearance) {
|
||||
let (choice, scale) = (this.choice, this.metrics.font_scale);
|
||||
cx.set_global(Self::new(choice, is_dark(appearance), scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The text size factor changed (`ui.font_scale`).
|
||||
pub fn set_font_scale(cx: &mut App, font_scale: f32) {
|
||||
let this = Self::global(cx);
|
||||
if (this.metrics.font_scale - font_scale).abs() < f32::EPSILON {
|
||||
return;
|
||||
}
|
||||
// `dark` is what the mode resolved to: for every mode, resolving it again
|
||||
// against it gives the same.
|
||||
let (choice, dark) = (this.choice, this.dark);
|
||||
cx.set_global(Self::new(choice, dark, font_scale));
|
||||
Self::apply(cx);
|
||||
}
|
||||
|
||||
/// Write the global into gpui-component's theme: the mode, the colours of
|
||||
/// the second layer, the font, the base size and the radii.
|
||||
fn apply(cx: &mut App) {
|
||||
let this = Self::global(cx).clone();
|
||||
// The registered theme of the mode first (it sets whatever the second
|
||||
// layer leaves alone), then our colours over it in a second update, as
|
||||
// `Theme::update` says a mode change must be.
|
||||
Theme::change(if this.dark { ThemeMode::Dark } else { ThemeMode::Light }, None, cx);
|
||||
Theme::update(cx, |theme| {
|
||||
components::write(&this.colors, this.dark, &mut theme.colors);
|
||||
theme.font_family = FONT_FAMILY.into();
|
||||
theme.font_size = px(this.metrics.font_body);
|
||||
theme.radius = px(this.metrics.radius_sm);
|
||||
theme.radius_lg = px(this.metrics.radius_lg);
|
||||
});
|
||||
// Where the platform draws the window's frame itself (macOS), it follows
|
||||
// the mode; elsewhere this does nothing.
|
||||
cx.set_window_appearance(match this.choice {
|
||||
Choice::System => None,
|
||||
Choice::Light => Some(WindowAppearance::Light),
|
||||
Choice::Dark => Some(WindowAppearance::Dark),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpui::TestAppContext;
|
||||
use gpui_kit::component::ActiveTheme as _;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn start(cx: &mut TestAppContext, choice: Choice, appearance: WindowAppearance) {
|
||||
cx.update(|cx| {
|
||||
gpui_kit::init(cx);
|
||||
VoelinTheme::init(cx, choice, appearance, 1.0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mode_resolves_against_the_window() {
|
||||
assert!(Choice::System.resolve(true) && !Choice::System.resolve(false));
|
||||
assert!(Choice::Dark.resolve(false) && !Choice::Light.resolve(true));
|
||||
for choice in [Choice::System, Choice::Light, Choice::Dark] {
|
||||
assert_eq!(Choice::parse(choice.name()), Some(choice));
|
||||
}
|
||||
assert_eq!(Choice::parse("blue"), None);
|
||||
assert!(is_dark(WindowAppearance::VibrantDark) && !is_dark(WindowAppearance::VibrantLight));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_tokens_reach_gpui_component(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Light);
|
||||
cx.update(|cx| {
|
||||
let theme = cx.theme();
|
||||
assert!(theme.is_dark());
|
||||
assert_eq!(theme.colors.primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.colors.background, hsla(Palette::DARK.bg_app));
|
||||
assert_eq!(theme.colors.button_primary, hsla(Palette::DARK.accent));
|
||||
assert_eq!(theme.font_family.as_ref(), "Inter");
|
||||
assert_eq!(theme.font_size, px(14.0));
|
||||
assert_eq!(theme.radius, px(6.0));
|
||||
assert_eq!(theme.radius_lg, px(12.0));
|
||||
assert_eq!(VoelinTheme::global(cx).colors, Palette::DARK);
|
||||
assert_eq!(VoelinTheme::global(cx).backdrop, Backdrop::DARK);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn system_follows_the_window_appearance_and_light_and_dark_do_not(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::System, WindowAppearance::Light);
|
||||
let primary = |cx: &mut TestAppContext| cx.update(|cx| cx.theme().colors.primary);
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::VibrantLight));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
|
||||
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Dark, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
|
||||
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Light));
|
||||
assert_eq!(primary(cx), hsla(Palette::DARK.accent), "a dark choice ignores the window");
|
||||
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Light, WindowAppearance::Dark));
|
||||
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent), "so does a light one");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_text_size_scales_the_type_and_the_controls(cx: &mut TestAppContext) {
|
||||
start(cx, Choice::Dark, WindowAppearance::Dark);
|
||||
cx.update(|cx| VoelinTheme::set_font_scale(cx, 1.25));
|
||||
cx.update(|cx| {
|
||||
let theme = VoelinTheme::global(cx);
|
||||
assert!(theme.is_dark(), "the mode stays");
|
||||
assert_eq!(theme.metrics.font_body, 17.5);
|
||||
assert_eq!(theme.metrics.control_height, 45.0);
|
||||
assert_eq!(cx.theme().font_size, px(17.5));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
|
||||
//! read and every token in it is compared with the Rust value of the same
|
||||
//! name, light and dark and at four text sizes; a token on one side only, a
|
||||
//! value that differs, or a declaration of a kind this test does not know
|
||||
//! fails it. While both front ends live, a token changed in one place and
|
||||
//! not the other is caught here.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
|
||||
|
||||
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
|
||||
|
||||
/// What `theme.slint` declares: the kind and the expression of each property
|
||||
/// of the `Theme` global, in file order.
|
||||
fn declarations() -> Vec<(String, String, String)> {
|
||||
let without_comments: String = SLINT
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap_or(""))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
|
||||
let mut found = Vec::new();
|
||||
for statement in body.split(';') {
|
||||
let statement = statement.trim();
|
||||
let Some(rest) = ["in-out property", "out property", "in property"]
|
||||
.iter()
|
||||
.find_map(|prefix| statement.strip_prefix(prefix))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (kind, rest) =
|
||||
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
|
||||
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
|
||||
// One line, single spaces: `backdrop` is written over several.
|
||||
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `#rgb`-style literal as `Rgba`.
|
||||
fn colour(text: &str) -> Rgba {
|
||||
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
|
||||
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
|
||||
match hex.len() {
|
||||
6 => Rgba(value << 8 | 0xff),
|
||||
8 => Rgba(value),
|
||||
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
|
||||
fn by_mode(expr: &str) -> (String, String) {
|
||||
let Some(rest) = expr.strip_prefix("dark ?") else {
|
||||
return (expr.to_owned(), expr.to_owned());
|
||||
};
|
||||
let mut depth = 0;
|
||||
for (i, c) in rest.char_indices() {
|
||||
match c {
|
||||
'(' => depth += 1,
|
||||
')' => depth -= 1,
|
||||
':' if depth == 0 => {
|
||||
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panic!("no `:` in {expr:?}");
|
||||
}
|
||||
|
||||
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
|
||||
/// `*`, `+`, `max(a, b)` and parentheses.
|
||||
struct Eval<'a> {
|
||||
tokens: Vec<String>,
|
||||
at: usize,
|
||||
env: &'a BTreeMap<String, String>,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl<'a> Eval<'a> {
|
||||
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
|
||||
let mut tokens = Vec::new();
|
||||
let mut word = String::new();
|
||||
for c in expr.chars() {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
|
||||
word.push(c);
|
||||
} else {
|
||||
if !word.is_empty() {
|
||||
tokens.push(std::mem::take(&mut word));
|
||||
}
|
||||
if !c.is_whitespace() {
|
||||
tokens.push(c.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
tokens.push(word);
|
||||
}
|
||||
let mut eval = Eval { tokens, at: 0, env, scale };
|
||||
let value = eval.sum();
|
||||
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
|
||||
value
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<&str> {
|
||||
self.tokens.get(self.at).map(String::as_str)
|
||||
}
|
||||
|
||||
fn take(&mut self) -> String {
|
||||
self.at += 1;
|
||||
self.tokens[self.at - 1].clone()
|
||||
}
|
||||
|
||||
fn sum(&mut self) -> f64 {
|
||||
let mut value = self.product();
|
||||
while self.peek() == Some("+") {
|
||||
self.take();
|
||||
value += self.product();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn product(&mut self) -> f64 {
|
||||
let mut value = self.factor();
|
||||
while self.peek() == Some("*") {
|
||||
self.take();
|
||||
value *= self.factor();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn factor(&mut self) -> f64 {
|
||||
let token = self.take();
|
||||
if token == "(" {
|
||||
let value = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return value;
|
||||
}
|
||||
if token == "max" {
|
||||
assert_eq!(self.take(), "(");
|
||||
let a = self.sum();
|
||||
assert_eq!(self.take(), ",");
|
||||
let b = self.sum();
|
||||
assert_eq!(self.take(), ")");
|
||||
return a.max(b);
|
||||
}
|
||||
if token == "font-scale" {
|
||||
return self.scale;
|
||||
}
|
||||
if token.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
let number: String =
|
||||
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
|
||||
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
|
||||
}
|
||||
let expr =
|
||||
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
|
||||
Eval::run(&expr, self.env, self.scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names `theme.slint` declares that are state, not tokens: the mode and
|
||||
/// what it resolves to, and the text size factor (the factor is a parameter
|
||||
/// of [`Metrics`]).
|
||||
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
|
||||
|
||||
#[test]
|
||||
fn every_colour_is_the_same_in_both_files() {
|
||||
let slint: Vec<(String, String, String)> =
|
||||
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
|
||||
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
|
||||
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
|
||||
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &slint {
|
||||
let (d, l) = by_mode(expr);
|
||||
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
|
||||
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let ours: BTreeSet<&str> = dark.keys().copied().collect();
|
||||
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_length_weight_and_duration_is_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let env: BTreeMap<String, String> =
|
||||
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
|
||||
let numeric: Vec<&(String, String, String)> = all
|
||||
.iter()
|
||||
.filter(|(name, kind, _)| {
|
||||
matches!(kind.as_str(), "length" | "int" | "duration")
|
||||
&& !STATE.contains(&name.as_str())
|
||||
})
|
||||
.collect();
|
||||
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
|
||||
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
|
||||
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
|
||||
let mut names = BTreeSet::new();
|
||||
for (name, _, expr) in &numeric {
|
||||
let slint = Eval::run(expr, &env, f64::from(scale));
|
||||
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
|
||||
assert!(
|
||||
(slint - ours).abs() < 1e-3,
|
||||
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
|
||||
);
|
||||
names.insert(name.as_str());
|
||||
}
|
||||
let rust: BTreeSet<&str> = ours.keys().copied().collect();
|
||||
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
|
||||
let all = declarations();
|
||||
let get = |name: &str| {
|
||||
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
|
||||
};
|
||||
let gradient = |text: &str| -> Backdrop {
|
||||
let inner = text
|
||||
.trim()
|
||||
.strip_prefix("@linear-gradient(")
|
||||
.and_then(|t| t.strip_suffix(')'))
|
||||
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
|
||||
let mut parts = inner.split(',').map(str::trim);
|
||||
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
|
||||
let stops: Vec<(Rgba, f32)> = parts
|
||||
.map(|stop| {
|
||||
let (colour_text, position) = stop.split_once(' ').unwrap();
|
||||
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
|
||||
(colour(colour_text), percent / 100.0)
|
||||
})
|
||||
.collect();
|
||||
Backdrop { angle, stops: stops.try_into().expect("three stops") }
|
||||
};
|
||||
let (dark, light) = by_mode(&get("backdrop"));
|
||||
assert_eq!(gradient(&dark), Backdrop::DARK);
|
||||
assert_eq!(gradient(&light), Backdrop::LIGHT);
|
||||
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_declares_nothing_this_test_does_not_know() {
|
||||
let kinds: BTreeSet<String> = declarations()
|
||||
.into_iter()
|
||||
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
|
||||
.map(|(_, kind, _)| kind)
|
||||
.collect();
|
||||
let known: BTreeSet<String> = ["color", "brush", "length", "int", "duration", "string"]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect();
|
||||
assert_eq!(kinds, known);
|
||||
let declared: BTreeSet<String> = declarations().into_iter().map(|(name, _, _)| name).collect();
|
||||
for name in STATE {
|
||||
assert!(declared.contains(name), "{name} is declared");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! The tokens of `crates/voelin-ui/ui/theme.slint`, light and dark, as Rust
|
||||
//! values: the source of truth the GPUI front end copies. `theme.slint` stays
|
||||
//! the original while the Slint front end lives; the test in
|
||||
//! `theme/slint_parity.rs` reads it and fails when a value, a name or a
|
||||
//! formula here differs from it, so the two cannot drift apart.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A colour as `0xRRGGBBAA`, as the Slint file writes `#rrggbbaa` (`#rrggbb`
|
||||
/// is opaque).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Rgba(pub u32);
|
||||
|
||||
impl fmt::Debug for Rgba {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self}")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Rgba {
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.alpha() == 255 {
|
||||
write!(f, "#{:06x}", self.0 >> 8)
|
||||
} else {
|
||||
write!(f, "#{:08x}", self.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
/// Transparent black, for the widgets that draw nothing.
|
||||
pub const TRANSPARENT: Self = Self(0);
|
||||
|
||||
/// The opacity, 0 to 255.
|
||||
pub fn alpha(self) -> u8 {
|
||||
(self.0 & 0xff) as u8
|
||||
}
|
||||
|
||||
/// The same colour with another opacity.
|
||||
pub fn with_alpha(self, alpha: u8) -> Self {
|
||||
Self((self.0 & 0xffff_ff00) | u32::from(alpha))
|
||||
}
|
||||
|
||||
/// The channels, 0 to 1.
|
||||
pub fn channels(self) -> [f32; 3] {
|
||||
[24, 16, 8].map(|shift| ((self.0 >> shift) & 0xff) as f32 / 255.0)
|
||||
}
|
||||
|
||||
/// Mixed with `other` (of `amount`, 0 to 1), channel by channel, opacity
|
||||
/// from `self`.
|
||||
pub fn mix(self, other: Self, amount: f32) -> Self {
|
||||
let (a, b) = (self.channels(), other.channels());
|
||||
let channel =
|
||||
|i: usize| ((a[i] + (b[i] - a[i]) * amount) * 255.0).round().clamp(0.0, 255.0) as u32;
|
||||
Self(channel(0) << 24 | channel(1) << 16 | channel(2) << 8 | u32::from(self.alpha()))
|
||||
}
|
||||
|
||||
/// The relative luminance of WCAG 2, 0 (black) to 1 (white).
|
||||
pub fn luminance(self) -> f32 {
|
||||
let [r, g, b] = self
|
||||
.channels()
|
||||
.map(|c| if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) });
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/// The contrast ratio of WCAG 2 between two colours, 1 to 21.
|
||||
pub fn contrast(self, other: Self) -> f32 {
|
||||
let (a, b) = (self.luminance(), other.luminance());
|
||||
(a.max(b) + 0.05) / (a.min(b) + 0.05)
|
||||
}
|
||||
|
||||
/// Of white and `ink`, the one that reads better on `self`.
|
||||
pub fn readable(self, ink: Self) -> Self {
|
||||
let white = Self(0xffff_ffff);
|
||||
if self.contrast(white) >= self.contrast(ink) { white } else { ink }
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! palette {
|
||||
($($field:ident $name:literal: $dark:literal, $light:literal;)*) => {
|
||||
/// Every colour token of `theme.slint` for one mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Palette {
|
||||
$(
|
||||
#[doc = concat!("`", $name, "` of `theme.slint`.")]
|
||||
pub $field: Rgba,
|
||||
)*
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// The dark palette.
|
||||
pub const DARK: Self = Self { $($field: Rgba($dark),)* };
|
||||
/// The light palette.
|
||||
pub const LIGHT: Self = Self { $($field: Rgba($light),)* };
|
||||
|
||||
/// Every colour by the name it has in `theme.slint`, in its order.
|
||||
pub fn entries(&self) -> Vec<(&'static str, Rgba)> {
|
||||
vec![$(($name, self.$field),)*]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
palette! {
|
||||
bg_app "bg-app": 0x060a18ff, 0xe9eef9ff;
|
||||
bg_rail "bg-rail": 0x070c1dff, 0xdfe6f4ff;
|
||||
surface "surface": 0x0b1330ff, 0xf7f9feff;
|
||||
surface_2 "surface-2": 0x101a3cff, 0xffffffff;
|
||||
surface_3 "surface-3": 0x16224bff, 0xeaf0fbff;
|
||||
surface_4 "surface-4": 0x1c2b5cff, 0xdce5f7ff;
|
||||
scrim "scrim": 0x02050fc0, 0x0b132b80;
|
||||
scrim_light "scrim-light": 0x02050f73, 0x0b132b33;
|
||||
overlay "overlay": 0x060a18c8, 0x0b1330b0;
|
||||
border "border": 0x1b2750ff, 0xd3dceeff;
|
||||
border_strong "border-strong": 0x2a3a6eff, 0xb9c6e2ff;
|
||||
border_popup "border-popup": 0x3d5296ff, 0x9fb0d4ff;
|
||||
accent "accent": 0x2d6bffff, 0x2458e6ff;
|
||||
accent_hover "accent-hover": 0x4a82ffff, 0x3a6cf0ff;
|
||||
accent_pressed "accent-pressed": 0x1f55d9ff, 0x1b47c0ff;
|
||||
accent_soft "accent-soft": 0x18348aff, 0xd6e2ffff;
|
||||
accent_soft_hover "accent-soft-hover": 0x1d3d9cff, 0xc8d8ffff;
|
||||
accent_text "accent-text": 0x5c9dffff, 0x1d4fd6ff;
|
||||
name_text "name-text": 0x45b9ffff, 0x0f6cc4ff;
|
||||
on_accent "on-accent": 0xffffffff, 0xffffffff;
|
||||
glow "glow": 0x3f7bff90, 0x2458e660;
|
||||
live "live": 0xff2d55ff, 0xe0203fff;
|
||||
live_soft "live-soft": 0x3a0f22ff, 0xffe0e6ff;
|
||||
danger "danger": 0xff4d5eff, 0xd92c3cff;
|
||||
danger_soft "danger-soft": 0x3b1020ff, 0xffe3e6ff;
|
||||
success "success": 0x22d36bff, 0x16a557ff;
|
||||
success_soft "success-soft": 0x0d3326ff, 0xd7f5e4ff;
|
||||
warning "warning": 0xf5b301ff, 0xb77f00ff;
|
||||
warning_soft "warning-soft": 0x3a2a06ff, 0xfff0c8ff;
|
||||
idle "idle": 0xf5b301ff, 0xc98b00ff;
|
||||
dnd "dnd": 0xff4d5eff, 0xd92c3cff;
|
||||
offline "offline": 0x5f6d93ff, 0x8d99b5ff;
|
||||
gold "gold": 0xffc233ff, 0xd99a00ff;
|
||||
info "info": 0x3fb3ffff, 0x1180d6ff;
|
||||
text "text": 0xeef2ffff, 0x0e1733ff;
|
||||
text_secondary "text-secondary": 0xaeb9d8ff, 0x43506fff;
|
||||
text_muted "text-muted": 0x6d7ca6ff, 0x6f7b98ff;
|
||||
text_disabled "text-disabled": 0x46527aff, 0xa7b1c8ff;
|
||||
icon "icon": 0xb9c4e2ff, 0x43506fff;
|
||||
meter_low "meter-low": 0x21d07aff, 0x21d07aff;
|
||||
meter_mid "meter-mid": 0xf5d000ff, 0xf5d000ff;
|
||||
meter_high "meter-high": 0xff4d5eff, 0xff4d5eff;
|
||||
meter_off "meter-off": 0x1a2550ff, 0xd5ddefff;
|
||||
}
|
||||
|
||||
/// `@linear-gradient(angle, stop 0%, stop 55%, stop 100%)`: the window's
|
||||
/// backdrop. GPUI's `Background` has two colour stops, so what it draws
|
||||
/// ([`Backdrop::to_gpui`]) is the first and the last; the middle one stays
|
||||
/// here for the front end that can use it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The direction in degrees, as CSS and Slint take it (0 is to the top).
|
||||
pub angle: f32,
|
||||
/// Three stops: colour and position (0 to 1).
|
||||
pub stops: [(Rgba, f32); 3],
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// The dark backdrop.
|
||||
pub const DARK: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0x0a1230ff), 0.0), (Rgba(0x060a18ff), 0.55), (Rgba(0x0a1638ff), 1.0)],
|
||||
};
|
||||
/// The light backdrop.
|
||||
pub const LIGHT: Self = Self {
|
||||
angle: 160.0,
|
||||
stops: [(Rgba(0xf4f7fdff), 0.0), (Rgba(0xe6ecf8ff), 0.60), (Rgba(0xdde6f7ff), 1.0)],
|
||||
};
|
||||
}
|
||||
|
||||
/// The family of the UI font (`font-family` of `theme.slint`).
|
||||
pub const FONT_FAMILY: &str = "Inter";
|
||||
|
||||
/// Every size, radius, weight and duration token of `theme.slint` for one
|
||||
/// text size factor: lengths in logical pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Metrics {
|
||||
/// `font-scale`: multiplies every type size and the sizes that follow text.
|
||||
pub font_scale: f32,
|
||||
/// `radius-xs`.
|
||||
pub radius_xs: f32,
|
||||
/// `radius-sm`.
|
||||
pub radius_sm: f32,
|
||||
/// `radius-md`.
|
||||
pub radius_md: f32,
|
||||
/// `radius-lg`.
|
||||
pub radius_lg: f32,
|
||||
/// `radius-xl`.
|
||||
pub radius_xl: f32,
|
||||
/// `radius-pill`.
|
||||
pub radius_pill: f32,
|
||||
/// `space-1`.
|
||||
pub space_1: f32,
|
||||
/// `space-2`.
|
||||
pub space_2: f32,
|
||||
/// `space-3`.
|
||||
pub space_3: f32,
|
||||
/// `space-4`.
|
||||
pub space_4: f32,
|
||||
/// `space-5`.
|
||||
pub space_5: f32,
|
||||
/// `space-6`.
|
||||
pub space_6: f32,
|
||||
/// `space-7`.
|
||||
pub space_7: f32,
|
||||
/// `space-8`.
|
||||
pub space_8: f32,
|
||||
/// `font-xs` (scaled).
|
||||
pub font_xs: f32,
|
||||
/// `font-sm` (scaled).
|
||||
pub font_sm: f32,
|
||||
/// `font-body` (scaled).
|
||||
pub font_body: f32,
|
||||
/// `font-md` (scaled).
|
||||
pub font_md: f32,
|
||||
/// `font-lg` (scaled).
|
||||
pub font_lg: f32,
|
||||
/// `font-xl` (scaled).
|
||||
pub font_xl: f32,
|
||||
/// `font-2xl` (scaled).
|
||||
pub font_2xl: f32,
|
||||
/// `font-3xl` (scaled).
|
||||
pub font_3xl: f32,
|
||||
/// `weight-regular`.
|
||||
pub weight_regular: u16,
|
||||
/// `weight-medium`.
|
||||
pub weight_medium: u16,
|
||||
/// `weight-semibold`.
|
||||
pub weight_semibold: u16,
|
||||
/// `weight-bold`.
|
||||
pub weight_bold: u16,
|
||||
/// `row-height` (scaled).
|
||||
pub row_height: f32,
|
||||
/// `control-height` (scaled).
|
||||
pub control_height: f32,
|
||||
/// `control-height-sm` (scaled).
|
||||
pub control_height_sm: f32,
|
||||
/// `icon-sm`.
|
||||
pub icon_sm: f32,
|
||||
/// `icon-md`.
|
||||
pub icon_md: f32,
|
||||
/// `icon-lg`.
|
||||
pub icon_lg: f32,
|
||||
/// `glow-width`: the ring around focused and selected items.
|
||||
pub glow_width: f32,
|
||||
/// `rail-width`.
|
||||
pub rail_width: f32,
|
||||
/// `sidebar-width`: 264 and more with large text.
|
||||
pub sidebar_width: f32,
|
||||
/// `topbar-height`: 44, taller when large text makes the controls taller.
|
||||
pub topbar_height: f32,
|
||||
/// `right-panel-min`.
|
||||
pub right_panel_min: f32,
|
||||
/// `fast`, in milliseconds.
|
||||
pub fast_ms: u32,
|
||||
/// `normal`, in milliseconds.
|
||||
pub normal_ms: u32,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
/// The tokens at a text size factor (1 is the default).
|
||||
pub fn new(font_scale: f32) -> Self {
|
||||
let s = font_scale;
|
||||
let control_height = 36.0 * s;
|
||||
let space_3 = 8.0;
|
||||
Self {
|
||||
font_scale,
|
||||
radius_xs: 4.0,
|
||||
radius_sm: 6.0,
|
||||
radius_md: 8.0,
|
||||
radius_lg: 12.0,
|
||||
radius_xl: 16.0,
|
||||
radius_pill: 999.0,
|
||||
space_1: 2.0,
|
||||
space_2: 4.0,
|
||||
space_3,
|
||||
space_4: 12.0,
|
||||
space_5: 16.0,
|
||||
space_6: 20.0,
|
||||
space_7: 24.0,
|
||||
space_8: 32.0,
|
||||
font_xs: 11.0 * s,
|
||||
font_sm: 12.0 * s,
|
||||
font_body: 14.0 * s,
|
||||
font_md: 15.0 * s,
|
||||
font_lg: 17.0 * s,
|
||||
font_xl: 20.0 * s,
|
||||
font_2xl: 24.0 * s,
|
||||
font_3xl: 30.0 * s,
|
||||
weight_regular: 400,
|
||||
weight_medium: 500,
|
||||
weight_semibold: 600,
|
||||
weight_bold: 700,
|
||||
row_height: 32.0 * s,
|
||||
control_height,
|
||||
control_height_sm: 28.0 * s,
|
||||
icon_sm: 16.0,
|
||||
icon_md: 20.0,
|
||||
icon_lg: 24.0,
|
||||
glow_width: 2.0,
|
||||
rail_width: 72.0,
|
||||
sidebar_width: 264.0 * s.max(1.0),
|
||||
topbar_height: 44.0_f32.max(control_height + space_3),
|
||||
right_panel_min: 220.0,
|
||||
fast_ms: 120,
|
||||
normal_ms: 200,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every number token by the name it has in `theme.slint`, in its order:
|
||||
/// lengths in pixels, weights as they are, durations in milliseconds.
|
||||
pub fn entries(&self) -> Vec<(&'static str, f64)> {
|
||||
let m = self;
|
||||
[
|
||||
("radius-xs", m.radius_xs),
|
||||
("radius-sm", m.radius_sm),
|
||||
("radius-md", m.radius_md),
|
||||
("radius-lg", m.radius_lg),
|
||||
("radius-xl", m.radius_xl),
|
||||
("radius-pill", m.radius_pill),
|
||||
("space-1", m.space_1),
|
||||
("space-2", m.space_2),
|
||||
("space-3", m.space_3),
|
||||
("space-4", m.space_4),
|
||||
("space-5", m.space_5),
|
||||
("space-6", m.space_6),
|
||||
("space-7", m.space_7),
|
||||
("space-8", m.space_8),
|
||||
("font-xs", m.font_xs),
|
||||
("font-sm", m.font_sm),
|
||||
("font-body", m.font_body),
|
||||
("font-md", m.font_md),
|
||||
("font-lg", m.font_lg),
|
||||
("font-xl", m.font_xl),
|
||||
("font-2xl", m.font_2xl),
|
||||
("font-3xl", m.font_3xl),
|
||||
("row-height", m.row_height),
|
||||
("control-height", m.control_height),
|
||||
("control-height-sm", m.control_height_sm),
|
||||
("icon-sm", m.icon_sm),
|
||||
("icon-md", m.icon_md),
|
||||
("icon-lg", m.icon_lg),
|
||||
("glow-width", m.glow_width),
|
||||
("rail-width", m.rail_width),
|
||||
("sidebar-width", m.sidebar_width),
|
||||
("topbar-height", m.topbar_height),
|
||||
("right-panel-min", m.right_panel_min),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, f64::from(value)))
|
||||
.chain([
|
||||
("weight-regular", f64::from(m.weight_regular)),
|
||||
("weight-medium", f64::from(m.weight_medium)),
|
||||
("weight-semibold", f64::from(m.weight_semibold)),
|
||||
("weight-bold", f64::from(m.weight_bold)),
|
||||
("fast", f64::from(m.fast_ms)),
|
||||
("normal", f64::from(m.normal_ms)),
|
||||
])
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Metrics {
|
||||
fn default() -> Self {
|
||||
Self::new(1.0)
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,88 @@
|
||||
//! The window's content. Today the shell is not built (slice 1 of the
|
||||
//! migration): the window shows the one line of the root state that proves
|
||||
//! the loops run.
|
||||
//! The window's content. The shell is not built yet (slice 1 of the
|
||||
//! migration): the window is the theme's page with the one line of the root
|
||||
//! state that proves the loops run in a status bar, or, with
|
||||
//! `VOELIN_OPEN=swatch`, the swatch page above that bar.
|
||||
|
||||
use gpui_kit::component::ActiveTheme as _;
|
||||
use gpui_kit::{
|
||||
Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px,
|
||||
};
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::dev::Page;
|
||||
use crate::swatch::swatch;
|
||||
use crate::theme::{VoelinTheme, hsla};
|
||||
|
||||
/// What the main window draws, from the root state.
|
||||
/// What the main window draws, from the root state and the theme.
|
||||
pub struct MainView {
|
||||
app: Entity<AppState>,
|
||||
page: Page,
|
||||
}
|
||||
|
||||
impl MainView {
|
||||
/// A view of `app` that draws again whenever it changes.
|
||||
pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
|
||||
/// A view of `app` that draws again whenever it changes, and that keeps
|
||||
/// the theme in `system` mode in step with the window's appearance.
|
||||
pub fn new(
|
||||
app: Entity<AppState>,
|
||||
page: Page,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
cx.observe(&app, |_, _, cx| cx.notify()).detach();
|
||||
Self { app }
|
||||
cx.observe_window_appearance(window, |_, window, cx| {
|
||||
VoelinTheme::set_system_appearance(cx, window.appearance());
|
||||
})
|
||||
.detach();
|
||||
Self { app, page }
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for MainView {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let line = self.app.read(cx).state_line();
|
||||
let theme = cx.theme();
|
||||
let theme = VoelinTheme::global(cx).clone();
|
||||
let (c, m) = (&theme.colors, &theme.metrics);
|
||||
let page = match self.page {
|
||||
Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)),
|
||||
Page::Shell => div()
|
||||
.flex_1()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(m.space_3))
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_3xl))
|
||||
.text_color(hsla(c.text))
|
||||
.child(voelin_platform::APP_NAME),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(px(m.font_body))
|
||||
.text_color(hsla(c.text_muted))
|
||||
.child("The desktop shell is the next slice."),
|
||||
),
|
||||
};
|
||||
div()
|
||||
.size_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.bg(theme.background)
|
||||
.text_color(theme.foreground)
|
||||
.text_size(px(14.0))
|
||||
.child(line)
|
||||
.flex_col()
|
||||
.bg(hsla(c.bg_app))
|
||||
.text_color(hsla(c.text))
|
||||
.font_family(crate::theme::FONT_FAMILY)
|
||||
.child(page)
|
||||
.child(
|
||||
div()
|
||||
.h(px(m.control_height_sm))
|
||||
.px(px(m.space_5))
|
||||
.flex()
|
||||
.items_center()
|
||||
.bg(hsla(c.surface))
|
||||
.border_t_1()
|
||||
.border_color(hsla(c.border))
|
||||
.text_size(px(m.font_sm))
|
||||
.text_color(hsla(c.text_secondary))
|
||||
.child(line),
|
||||
)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/bin/sh
|
||||
# Take a screenshot of the GPUI front end with development switches set,
|
||||
# headless, and close its window the way a user would (docs/ui.md, "The GPUI
|
||||
# front end"): the equivalent of scripts/shots.sh for `voelin-gpui`.
|
||||
#
|
||||
# scripts/gpui-shot.sh <out.png> [<VOELIN_OPEN> [<width>x<height>]]
|
||||
#
|
||||
# The window opens on a display of its own, never the desktop's: the script
|
||||
# runs itself again under `xvfb-run` (Debian, Ubuntu, the CI image) unless
|
||||
# GPUI_SHOT_HEADLESS=1 says the caller already did that, as on NixOS:
|
||||
#
|
||||
# GPUI_SHOT_HEADLESS=1 spikes/gpui/shell.sh spikes/gpui/headless.sh -- \
|
||||
# scripts/gpui-shot.sh docs/ui/gpui-swatch-dark.png swatch 1440x960
|
||||
#
|
||||
# Wayland is taken out of the environment (GPUI prefers it, so the window
|
||||
# would open on the desktop), and so are the desktop's session bus and its
|
||||
# portals; the app's state and the XDG directories are a temporary one.
|
||||
# GPUI needs a Vulkan driver or OpenGL at run time: on a machine without a
|
||||
# GPU, Mesa's lavapipe (`mesa-vulkan-drivers`) draws in software. Without a
|
||||
# window manager (xvfb-run alone) the window is stopped with TERM, with one
|
||||
# (openbox, as headless.sh starts) it gets a close request, which is what the
|
||||
# last line says.
|
||||
#
|
||||
# VOELIN_BIN: the binary (default target/release/voelin-gpui, else
|
||||
# target/debug); DELAY: seconds the window is shown before the picture
|
||||
# (default 4). VOELIN_DEV_THEME, VOELIN_FONT_SCALE and the other switches of
|
||||
# `src/dev.rs` are passed on as set.
|
||||
set -eu
|
||||
out=${1:?usage: gpui-shot.sh <out.png> [<VOELIN_OPEN> [<width>x<height>]]}
|
||||
open=${2:-}
|
||||
size=${3:-1440x960}
|
||||
w=${size%x*}
|
||||
h=${size#*x}
|
||||
if [ "${GPUI_SHOT_HEADLESS:-}" != 1 ]; then
|
||||
command -v xvfb-run >/dev/null || {
|
||||
echo "gpui-shot.sh: no xvfb-run; start a display of your own and set GPUI_SHOT_HEADLESS=1" >&2
|
||||
exit 2
|
||||
}
|
||||
GPUI_SHOT_HEADLESS=1 exec xvfb-run -a -s "-screen 0 $((w * 2))x$((h * 2))x24" "$0" "$@"
|
||||
fi
|
||||
[ -n "${DISPLAY:-}" ] || { echo "gpui-shot.sh: no DISPLAY" >&2; exit 2; }
|
||||
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||
bin=${VOELIN_BIN:-}
|
||||
if [ -z "$bin" ]; then
|
||||
target=${CARGO_TARGET_DIR:-$root/target}
|
||||
for kind in release debug; do
|
||||
[ -x "$target/$kind/voelin-gpui" ] && { bin=$target/$kind/voelin-gpui; break; }
|
||||
done
|
||||
fi
|
||||
[ -x "$bin" ] || { echo "gpui-shot.sh: no voelin-gpui binary (cargo build -p voelin-gpui --release)" >&2; exit 2; }
|
||||
work=$(mktemp -d)
|
||||
trap 'kill ${pid:-} 2>/dev/null || true; rm -rf "$work"' EXIT INT TERM
|
||||
mkdir -p "$work/runtime"
|
||||
chmod 700 "$work/runtime"
|
||||
env -u WAYLAND_DISPLAY -u WAYLAND_SOCKET -u XDG_SESSION_TYPE -u DBUS_SESSION_BUS_ADDRESS \
|
||||
XDG_RUNTIME_DIR="$work/runtime" XDG_CONFIG_HOME="$work/config" XDG_DATA_HOME="$work/data" \
|
||||
XDG_CACHE_HOME="$work/cache" XDG_STATE_HOME="$work/state" VOELIN_DATA_DIR="$work/data/voelin" \
|
||||
GPUI_X11_SCALE_FACTOR=1 VOELIN_FFMPEG=0 \
|
||||
VOELIN_OPEN="$open" VOELIN_WINDOW_SIZE="$size" \
|
||||
"$bin" >"$work/app.log" 2>&1 &
|
||||
pid=$!
|
||||
i=0
|
||||
until win=$(xdotool search --name '^Voelin$' 2>/dev/null | head -1) && [ -n "$win" ]; do
|
||||
i=$((i + 1))
|
||||
kill -0 "$pid" 2>/dev/null || { echo "gpui-shot.sh: the app ended before its window:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
|
||||
[ $i -lt 300 ] || { echo "gpui-shot.sh: no window after 30 s:" >&2; tail -20 "$work/app.log" >&2; exit 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
sleep "${DELAY:-4}"
|
||||
xwd -id "$win" -silent | magick xwd:- "png:$out"
|
||||
echo "$out: $(magick identify -format '%wx%h' "$out")"
|
||||
# Close it as a user does; with no window manager, ask the process to end.
|
||||
xdotool windowactivate --sync "$win" 2>/dev/null || true
|
||||
xdotool key alt+F4 2>/dev/null || true
|
||||
i=0
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
i=$((i + 1))
|
||||
if [ $i -ge 30 ]; then
|
||||
kill -TERM "$pid" 2>/dev/null || true
|
||||
wait "$pid" 2>/dev/null || true
|
||||
echo "stopped with TERM (no window manager closed it)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 0.1
|
||||
done
|
||||
status=0
|
||||
wait "$pid" || status=$?
|
||||
echo "closed by the window manager, exit code $status"
|
||||
exit "$status"
|
||||
Reference in new issue
Block a user