From aeab053a3fe4283ff7ab754a2cb608e321796d7a Mon Sep 17 00:00:00 2001 From: gaelcado Date: Wed, 19 Aug 2026 19:11:07 +0200 Subject: [PATCH 1/9] feat(ui): add coherent accent color palettes --- crates/ui/src/appearance.rs | 42 ++- crates/ui/src/composer.rs | 4 +- crates/ui/src/history.rs | 3 +- crates/ui/src/lib.rs | 4 +- crates/ui/src/loaders.rs | 22 +- crates/ui/src/markdown/render.rs | 18 +- crates/ui/src/pickers.rs | 19 +- crates/ui/src/settings.rs | 5 + crates/ui/src/settings/appearance.rs | 122 +++++++- crates/ui/src/settings/widgets.rs | 49 +-- crates/ui/src/shell.rs | 43 ++- crates/ui/src/shell/spaces.rs | 8 +- crates/ui/src/theme.rs | 452 ++++++++++++++++++++++++--- crates/ui/src/transcript.rs | 9 +- 14 files changed, 624 insertions(+), 176 deletions(-) diff --git a/crates/ui/src/appearance.rs b/crates/ui/src/appearance.rs index c2ec568813..8209ab66d1 100644 --- a/crates/ui/src/appearance.rs +++ b/crates/ui/src/appearance.rs @@ -25,7 +25,7 @@ use gpui::{App, Global, Subscription, Window}; use serde::{Deserialize, Serialize}; use crate::settings::UiSettings; -use crate::theme::{Appearance, Theme}; +use crate::theme::{AccentColor, Appearance, Theme}; /// The user's appearance preference. Persisted in `ui-settings.json`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -59,6 +59,7 @@ impl AppearanceMode { pub struct AppearanceState { pub mode: AppearanceMode, pub system: Appearance, + pub accent: AccentColor, /// Where `ui-settings.json` lives, so a menu action can persist the choice /// without routing through the shell entity that normally owns settings. pub data_dir: PathBuf, @@ -78,16 +79,17 @@ pub fn resolve(mode: AppearanceMode, system: Appearance) -> Appearance { /// Install the appearance globals and the matching theme. Call once at boot, /// before any window opens, so the first frame is already the right palette /// (installing later produces a visible dark-to-light flash). -pub fn init(mode: AppearanceMode, data_dir: impl Into, cx: &mut App) { +pub fn init(mode: AppearanceMode, accent: AccentColor, data_dir: impl Into, cx: &mut App) { let system = Appearance::from_window(cx.window_appearance()); tracing::debug!(?mode, ?system, "appearance: initial"); cx.set_global(AppearanceState { mode, system, + accent, data_dir: data_dir.into(), }); sync_ns_appearance(mode); - Theme::install(resolve(mode, system), cx); + Theme::install_preferences(resolve(mode, system), accent, cx); } /// The mode currently in effect (defaults to `System` before [`init`]). @@ -97,6 +99,12 @@ pub fn mode(cx: &App) -> AppearanceMode { .unwrap_or_default() } +pub fn accent(cx: &App) -> AccentColor { + cx.try_global::() + .map(|state| state.accent) + .unwrap_or_default() +} + /// Change the user's preference, repaint if that changed the palette, and write /// the choice to disk. pub fn set_mode(mode: AppearanceMode, cx: &mut App) { @@ -113,6 +121,21 @@ pub fn set_mode(mode: AppearanceMode, cx: &mut App) { persist(mode, &data_dir); } +/// Change the interactive accent without changing any semantic theme roles. +pub fn set_accent(accent: AccentColor, cx: &mut App) { + if !cx.has_global::() { + return; + } + let state = cx.global_mut::(); + if state.accent == accent { + return; + } + state.accent = accent; + let data_dir = state.data_dir.clone(); + apply(cx); + persist_accent(accent, &data_dir); +} + /// Read-modify-write `ui-settings.json` for just the appearance key. /// /// Deliberately a fresh load rather than a write of some cached struct: the @@ -127,6 +150,14 @@ fn persist(mode: AppearanceMode, data_dir: &Path) { } } +fn persist_accent(accent: AccentColor, data_dir: &Path) { + let mut settings = UiSettings::load(data_dir); + settings.accent_color = accent; + if let Err(err) = settings.save(data_dir) { + tracing::warn!(error = %err, "could not persist accent color"); + } +} + /// Subscribe a window to OS appearance changes. The returned [`Subscription`] /// must outlive the window — callers typically `.detach()` it. /// @@ -172,12 +203,13 @@ pub fn apply(cx: &mut App) { }; sync_ns_appearance(state.mode); let wanted = resolve(state.mode, state.system); + let accent = state.accent; let changed = !cx .try_global::() - .is_some_and(|t| t.appearance == wanted); + .is_some_and(|theme| theme.appearance == wanted && theme.accent_color == accent); if changed { tracing::debug!(?wanted, "appearance: installing palette"); - Theme::install(wanted, cx); + Theme::install_preferences(wanted, accent, cx); cx.refresh_windows(); } // Unconditional, even when the palette did not move: this is the only thing diff --git a/crates/ui/src/composer.rs b/crates/ui/src/composer.rs index 1df7409d6a..d4f1cfc583 100644 --- a/crates/ui/src/composer.rs +++ b/crates/ui/src/composer.rs @@ -2493,7 +2493,7 @@ impl ComposerInput { self.line_height = px(INPUT_LINE_HEIGHT); // Chips read as inline code: the markdown renderer's recipe (mono font - // + `code_text` violet) over the rounded `code_wash` painted beneath. + // + the spectrum's `code_text`) over the rounded `code_wash` beneath. let (chip_font, chip_color) = { let theme = Theme::of(cx); (gpui::font(theme.font_mono.clone()), theme.code_text) @@ -2869,7 +2869,7 @@ impl gpui::Element for ComposerTextElement { let origin = point(bounds.left(), bounds.top() - scroll); let selection_color = Theme::of(cx).selection; let caret_color = Theme::of(cx).caret; - // The inline-code recipe: chips wash violet like `code` spans do. + // The inline-code recipe: chips use the spectrum wash like `code` spans. let mention_color = Theme::of(cx).code_wash; let mut mention_quads = Vec::new(); diff --git a/crates/ui/src/history.rs b/crates/ui/src/history.rs index bb63432b0e..cc39ebf98b 100644 --- a/crates/ui/src/history.rs +++ b/crates/ui/src/history.rs @@ -413,9 +413,10 @@ impl Render for GitHistoryFetchButton { }) }) .child(if fetching { - crate::loaders::mini_gradient_spinner( + crate::loaders::mini_glyph_spinner( "history-fetch-all-spinner", 1.75, + theme.glyph, cx.entity_id(), cx, ) diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 8882f77913..4aead37958 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -160,8 +160,10 @@ pub fn run_app(config: UiConfig) { // final one on the very first frame, or the window flashes the wrong // palette while settings load. let data_dir = config.boot().data_dir.clone(); + let ui_settings = settings::UiSettings::load(&data_dir); appearance::init( - settings::UiSettings::load(&data_dir).appearance, + ui_settings.appearance, + ui_settings.accent_color, data_dir, cx, ); diff --git a/crates/ui/src/loaders.rs b/crates/ui/src/loaders.rs index f7bb5c33b3..e028749d4a 100644 --- a/crates/ui/src/loaders.rs +++ b/crates/ui/src/loaders.rs @@ -15,7 +15,7 @@ use gpui::{ }; use crate::motion::{self, GRADIENT_SPIN, PULSE_STAGGER, SPLASH_OUT, ZERON_PULSE}; -use crate::theme::Theme; +use crate::theme::{GlyphPalette, Theme}; // Shared with the terminal viewport (`zeron_proto::motion`) so both animate the // same loaders from the same numbers. @@ -147,24 +147,22 @@ pub fn gradient_spinner( })) } -/// A 2×3 miniature of [`gradient_spinner`] sized for a status-dot slot -/// (sessions-sidebar working rows): same row tints and pulse timing, but the -/// brightness SNAKES around the grid's perimeter (every cell of a 2×3 grid is -/// on the ring) instead of sweeping as a vertical wave — a tiny radial chase. -/// ~6×10px footprint at the default 2.5px cells. -pub fn mini_gradient_spinner( +/// A 2×3 activity glyph sized for compact status slots. Its color is an +/// explicit accent-preset role supplied by the caller, while brightness snakes +/// around the grid's perimeter as a tiny radial chase. +pub fn mini_glyph_spinner( key: impl Into, cell_px: f32, + palette: GlyphPalette, view: EntityId, cx: &mut App, ) -> impl IntoElement { - let tints = GSPIN_ROW_TINTS.map(|t| gpui::rgb(t).into()); - mini_spinner_tinted(key, cell_px, tints, view, cx) + mini_spinner_tinted(key, cell_px, palette.rows(), view, cx) } -/// [`mini_gradient_spinner`] in a single flat tint — the grayscale take for -/// surfaces where the brand gradient would pull focus (the sidebar -/// connection line): same grid, snake, and timing, color left to the caller. +/// Grayscale variant for surfaces where an accent would pull focus (the +/// sidebar connection line): same grid, snake, and timing, color left to the +/// caller. pub fn mini_mono_spinner( key: impl Into, cell_px: f32, diff --git a/crates/ui/src/markdown/render.rs b/crates/ui/src/markdown/render.rs index 5e7030506a..088fb36d9b 100644 --- a/crates/ui/src/markdown/render.rs +++ b/crates/ui/src/markdown/render.rs @@ -262,7 +262,7 @@ pub fn render_block( .min_w(px(18.0)) .text_size(px(MD_TEXT_SIZE)) .line_height(px(MD_LINE_HEIGHT)) - .text_color(theme.accent.opacity(0.85)) + .text_color(theme.accent) .child(SharedString::from(format!("{}.", start + item_ix as u64))) .into_any_element(), None => div() @@ -278,7 +278,7 @@ pub fn render_block( .w(px(5.0)) .h(px(5.0)) .rounded_full() - .bg(theme.accent.opacity(0.85)), + .bg(theme.accent), ) .into_any_element(), }; @@ -499,14 +499,12 @@ pub struct FlatText { pub code_ranges: Vec>, } -/// Inline-code tint (round 9): the original is neutral (chat-view.tsx mdTheme -/// `inlineCode: #f0f0f0 on white/8%`), but the user asked for "a nice purple" -/// — violet-300 text over a violet-400 wash, readable on the #060606 panel. +/// Inline-code tint: a text-safe use of the selected accent identity. pub fn inline_code_text(theme: &Theme) -> Hsla { - theme.code_text // violet-300 + theme.code_text } pub fn inline_code_wash(theme: &Theme) -> Hsla { - theme.code_wash // violet-400/12 + theme.code_wash } /// Rounded-wash geometry: small radius on a slightly inset box (paint-only — /// x extends 2px past the glyphs, y insets 2px from the 22px line box). @@ -559,7 +557,7 @@ fn flatten_runs_weighted(runs: &[InlineRun], theme: &Theme, base_weight: FontWei // theme underlines in the text color; indigo is reserved for primary // actions). let is_link = run.style.link.is_some(); - // Inline code reads violet (see `inline_code_text`); everything else + // Inline code uses the spectrum's code tone; everything else // stays the monochrome foreground. let color = if run.style.code { inline_code_text(theme) @@ -730,9 +728,9 @@ fn flat_text_element( .into_any_element() } -/// Selection tint: the accent hue under the glyphs, dark-panel strength. +/// Selection tint shared with native inputs and the composer. fn selection_wash(theme: &Theme) -> Hsla { - theme.accent.opacity(0.35) // indigo-400 + theme.selection } /// Selection support for a plain (non-markdown) text element — the user diff --git a/crates/ui/src/pickers.rs b/crates/ui/src/pickers.rs index 75ea4238af..b3f002f0ee 100644 --- a/crates/ui/src/pickers.rs +++ b/crates/ui/src/pickers.rs @@ -3226,9 +3226,7 @@ impl Pickers { theme.text_muted.opacity(0.75) }), ) - .when(favorites_view, |el| { - el.child(rail_indicator(picker_purple(&theme))) - }), + .when(favorites_view, |el| el.child(rail_indicator(theme.accent))), ); // Full-bleed divider, aligned with the search row's bottom // hairline (see the height math there) — one line across. @@ -3271,9 +3269,7 @@ impl Pickers { theme.text_muted }), )) - .when(is_viewed, |el| { - el.child(rail_indicator(picker_purple(&theme))) - }), + .when(is_viewed, |el| el.child(rail_indicator(theme.accent))), ); } column.into_any_element() @@ -3718,17 +3714,6 @@ fn rail_indicator(tint: gpui::Hsla) -> gpui::Div { .bg(tint) } -/// The picker's selection purple — the app's violet identity (the "nice -/// purple" family inline code wears), NOT the indigo `accent`: the indigo -/// bar read blue against the glass (user request). violet-400 on dark, -/// violet-600 on light (AA against white). -fn picker_purple(theme: &Theme) -> gpui::Hsla { - match theme.appearance { - crate::theme::Appearance::Dark => crate::theme::oklch(0.702, 0.183, 293.541), - crate::theme::Appearance::Light => crate::theme::oklch(0.541, 0.281, 293.009), - } -} - /// Centered muted note filling an empty model list ("No models found"). fn empty_list_note(theme: &Theme, copy: &str) -> AnyElement { div() diff --git a/crates/ui/src/settings.rs b/crates/ui/src/settings.rs index 485adcaac2..4063262823 100644 --- a/crates/ui/src/settings.rs +++ b/crates/ui/src/settings.rs @@ -127,6 +127,8 @@ pub struct UiSettings { pub appearance: crate::appearance::AppearanceMode, /// Changes pane: side-by-side diffs instead of the unified stack. pub diff_split: bool, + /// Interactive identity accent. Defaults to the upstream Zeron color. + pub accent_color: crate::theme::AccentColor, } impl Default for UiSettings { @@ -155,6 +157,7 @@ impl Default for UiSettings { keymap: KeymapConfig::default(), appearance: crate::appearance::AppearanceMode::default(), diff_split: false, + accent_color: crate::theme::AccentColor::default(), } } } @@ -440,6 +443,7 @@ mod tests { }, appearance: crate::appearance::AppearanceMode::Light, diff_split: true, + accent_color: crate::theme::AccentColor::Cyan, }; settings.save(dir.path()).unwrap(); assert_eq!(UiSettings::load(dir.path()), settings); @@ -473,6 +477,7 @@ mod tests { .unwrap(); let loaded = UiSettings::load(dir.path()); assert_eq!(loaded.appearance, crate::appearance::AppearanceMode::System); + assert_eq!(loaded.accent_color, crate::theme::AccentColor::Zeron); assert_eq!(loaded.sidebar_width, 300.0); assert!(!loaded.sound_enabled, "other keys still parse"); assert!( diff --git a/crates/ui/src/settings/appearance.rs b/crates/ui/src/settings/appearance.rs index 3ec3476bc9..58524633b3 100644 --- a/crates/ui/src/settings/appearance.rs +++ b/crates/ui/src/settings/appearance.rs @@ -14,8 +14,9 @@ use gpui::{ }; use crate::appearance::{self, AppearanceMode}; +use crate::icons; use crate::settings::widgets; -use crate::theme::{Appearance, Theme}; +use crate::theme::{AccentColor, Appearance, Theme}; pub struct AppearancePage; @@ -39,6 +40,13 @@ fn bar(fraction: f32, tone: Hsla) -> gpui::Div { .bg(tone) } +fn accent_helper(accent: AccentColor) -> String { + format!( + "{} · Controls, glyphs, selections, code, and activity.", + accent.label() + ) +} + /// Which corners a miniature rounds — the split card needs each half to round /// only its outer side so the two meet flush down the middle. #[derive(Clone, Copy, PartialEq, Eq)] @@ -110,7 +118,7 @@ fn miniature(theme: &Theme, corners: Corners) -> AnyElement { /// The System card: light on the left, dark on the right. Each half is a /// complete miniature clipped to its side, which is what makes the card read as /// "whichever one the system is on". -fn miniature_split() -> AnyElement { +fn miniature_split(accent: AccentColor) -> AnyElement { div() .size_full() .flex() @@ -120,14 +128,14 @@ fn miniature_split() -> AnyElement { .w_1_2() .h_full() .overflow_hidden() - .child(miniature(&Theme::light(), Corners::Left)), + .child(miniature(&Theme::light_with_accent(accent), Corners::Left)), ) .child( div() .w_1_2() .h_full() .overflow_hidden() - .child(miniature(&Theme::dark(), Corners::Right)), + .child(miniature(&Theme::dark_with_accent(accent), Corners::Right)), ) .into_any_element() } @@ -136,11 +144,11 @@ fn miniature_split() -> AnyElement { /// /// The one place `Theme::light()`/`Theme::dark()` are legitimately built outside /// the installed global: a preview has to show the palette you are *not* using. -fn preview(mode: AppearanceMode) -> AnyElement { +fn preview(mode: AppearanceMode, accent: AccentColor) -> AnyElement { match mode { - AppearanceMode::System => miniature_split(), - AppearanceMode::Light => miniature(&Theme::light(), Corners::All), - AppearanceMode::Dark => miniature(&Theme::dark(), Corners::All), + AppearanceMode::System => miniature_split(accent), + AppearanceMode::Light => miniature(&Theme::light_with_accent(accent), Corners::All), + AppearanceMode::Dark => miniature(&Theme::dark_with_accent(accent), Corners::All), } } @@ -166,18 +174,47 @@ impl Render for AppearancePage { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = Theme::of(cx).clone(); let current = appearance::mode(cx); + let current_accent = appearance::accent(cx); let system = cx .try_global::() .map(|state| state.system) .unwrap_or_default(); let cards = AppearanceMode::ALL.into_iter().map(|mode| { - widgets::option_card(&theme, mode.label(), mode == current, preview(mode)) - .id(SharedString::from(format!("appearance-{}", mode.label()))) + widgets::option_card( + &theme, + mode.label(), + mode == current, + preview(mode, current_accent), + ) + .id(SharedString::from(format!("appearance-{}", mode.label()))) + .on_click(cx.listener(move |_, _, _, cx| { + appearance::set_mode(mode, cx); + cx.notify(); + })) + }); + + let accent_swatches = AccentColor::ALL.into_iter().map(|accent| { + let swatch_theme = Theme::for_preferences(theme.appearance, accent); + let selected = accent == current_accent; + div() + .id(SharedString::from(format!("accent-{}", accent.label()))) + .flex_none() + .w(px(28.0)) + .h(px(32.0)) + .pb(px(4.0)) + .border_b_2() + .border_color(if selected { + swatch_theme.accent + } else { + theme.border + }) + .cursor_pointer() .on_click(cx.listener(move |_, _, _, cx| { - appearance::set_mode(mode, cx); + appearance::set_accent(accent, cx); cx.notify(); })) + .child(div().size_full().rounded(px(5.0)).bg(swatch_theme.accent)) }); div() @@ -190,8 +227,7 @@ impl Render for AppearancePage { .child( widgets::page_subtitle( &theme, - "How zeron picks between light and dark. This setting stays on this \ - device.", + "Choose how Zeron looks. These settings stay on this device.", ) .max_w(px(512.0)) .line_height(px(20.0)), @@ -212,6 +248,44 @@ impl Render for AppearancePage { .text_color(theme.text_muted) .line_height(px(18.0)) .child(helper(current, system)), + ) + .child( + widgets::section_card(&theme).child( + widgets::card_row(&theme, true) + .child(widgets::row_tile(&theme, icons::TUNING)) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .flex() + .flex_col() + .child(widgets::row_title(&theme, "Accent color")) + .child(widgets::meta_line( + &theme, + vec![ + div() + .w_full() + .min_w_0() + .truncate() + .child(SharedString::from(accent_helper( + current_accent, + ))) + .into_any_element(), + ], + )), + ) + .child( + div() + .flex_none() + .ml(px(24.0)) + .flex() + .flex_row() + .items_center() + .gap(px(6.0)) + .children(accent_swatches), + ), + ), ), ) } @@ -229,6 +303,28 @@ mod tests { } } + #[test] + fn accent_choices_form_a_labeled_palette() { + assert_eq!(AccentColor::default(), AccentColor::Zeron); + assert_eq!(AccentColor::ALL.len(), 7); + for accent in AccentColor::ALL { + assert!(!accent.label().is_empty()); + assert!(!matches!(accent.label(), "Red" | "Purple")); + } + } + + #[test] + fn accent_helper_describes_the_palette_roles_concisely() { + let copy = accent_helper(AccentColor::Pink); + assert!(copy.starts_with("Pink ·")); + assert!(copy.contains("glyphs")); + assert!(!copy.contains("Sidebar stays")); + assert!( + copy.len() < 64, + "copy is too long for the settings row: {copy}" + ); + } + #[test] fn system_helper_names_the_resolved_appearance() { let dark = helper(AppearanceMode::System, Appearance::Dark); diff --git a/crates/ui/src/settings/widgets.rs b/crates/ui/src/settings/widgets.rs index 2389b714e3..a9db07d4b1 100644 --- a/crates/ui/src/settings/widgets.rs +++ b/crates/ui/src/settings/widgets.rs @@ -88,14 +88,11 @@ pub const OPTION_CARD_HEIGHT: f32 = 148.0; /// are axis-aligned rectangles, so `overflow_hidden` on the frame clips to its /// bounding box and not to its corner radius — a preview that paints its own /// background will square off the corners and cover the frame's border with it. -pub const OPTION_CARD_RADIUS: f32 = 10.0; -/// Clear space between the frame and the selection ring. -const RING_GAP: f32 = 2.0; -/// Thickness of the selection ring. -const RING_WIDTH: f32 = 2.0; +pub const OPTION_CARD_RADIUS: f32 = 6.0; -/// One card in an [`option_card_row`]: a fixed-height preview frame that carries -/// the selection ring, with a caption underneath. +/// One card in an [`option_card_row`]: a fixed-height preview frame with a quiet +/// selected edge and caption underneath. There is deliberately no outer card +/// or ring; the preview itself is the control. /// /// `preview` fills the frame and **must round its own corners** to /// [`OPTION_CARD_RADIUS`] if it paints a background — see that constant. @@ -109,22 +106,6 @@ pub fn option_card( selected: bool, preview: AnyElement, ) -> gpui::Div { - let frame = div() - .h(px(OPTION_CARD_HEIGHT)) - .w_full() - .rounded(px(OPTION_CARD_RADIUS)) - .overflow_hidden() - .border_1() - .border_color(theme.border) - .child(preview); - - // The ring is a *wrapper border*, not a spread shadow. A shadow's spread - // grows the rectangle without growing its corner radius, so the halo's - // corners tighten relative to the frame's and the two visibly drift apart by - // a pixel at each rounded corner. Concentric borders can't do that: each - // element rounds itself, and the outer radius is the inner one plus the gap - // it sits behind. Always present, transparent when unselected, so selecting a - // card never reflows the row. div() .flex_1() .min_w_0() @@ -135,22 +116,24 @@ pub fn option_card( .cursor_pointer() .child( div() + .h(px(OPTION_CARD_HEIGHT)) .w_full() - .rounded(px(OPTION_CARD_RADIUS + RING_GAP + RING_WIDTH)) - .p(px(RING_GAP)) - .border_2() - .border_color(if selected { - theme.accent - } else { - gpui::transparent_black() - }) - .child(frame), + .rounded(px(OPTION_CARD_RADIUS)) + .overflow_hidden() + .border_1() + .border_color(if selected { theme.accent } else { theme.border }) + .child(preview), ) .child( div() .text_size(px(13.0)) + .font_weight(if selected { + gpui::FontWeight::MEDIUM + } else { + gpui::FontWeight::NORMAL + }) .text_color(if selected { - theme.text + theme.accent } else { theme.text_muted }) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 06ab12b1f9..4add3814b0 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -3563,7 +3563,8 @@ impl Shell { } fn render_sidebar(&mut self, cx: &mut Context) -> AnyElement { - let theme = Theme::of(cx).clone(); + let installed_theme = Theme::of(cx); + let theme = Theme::sidebar(installed_theme.appearance, installed_theme.accent_color); let inner: AnyElement = match self.route { Route::Settings(section) => self.render_settings_nav(section, &theme, cx), Route::Chat => self.render_chat_sidebar(&theme, cx), @@ -3754,6 +3755,8 @@ impl Shell { } }; let shows_metadata = branch.is_some() || change_request.is_some(); + let queued = queued && !undelivered; + let working = status == zeron_proto::ChatIndicator::Working && !queued && !undelivered; let corner_body: AnyElement = if corner_hovered { div() .flex() @@ -3796,22 +3799,20 @@ impl Shell { } else { match status_label { Some(label) => { - // Glyph slot: Working carries its active thread glyph - // beside the accent word; Done wears the check; other - // statuses retain a quiet semantic dot. + // Glyph slot: Working wears the preset's animated pixel + // glyph beside its label, Done wears the check, and the + // remaining statuses use a compact dot. let glyph: AnyElement = if status == zeron_proto::ChatIndicator::Completed { icon(icons::CHECK) .size(px(11.0)) .flex_none() .text_color(status_color) .into_any_element() - } else if status == zeron_proto::ChatIndicator::Working - && !queued - && !undelivered - { - loaders::mini_gradient_spinner( + } else if working { + loaders::mini_glyph_spinner( format!("chat-working-{id}"), 2.0, + theme.glyph, cx.entity_id(), cx, ) @@ -4325,23 +4326,12 @@ impl Shell { }; let failed = matches!(self.update_flow, UpdateFlow::Failed(_)); let tone = if failed { theme.danger } else { theme.accent }; - // Dark-purple GLASS tint (user request), not the 400-level accent as - // a fill: deep pigment at partial alpha tints the blur showing - // through instead of compositing into the slab that a bright indigo - // fill produced (earlier user report). Light chrome gets a lavender - // accent wash instead — dark purple under indigo-600 text goes muddy. + // Follow the selected spectrum with a low-emphasis glass tint rather + // than painting the bright text accent as a solid slab. let (chip_bg, chip_bg_hover) = if failed { (theme.danger.opacity(0.14), theme.danger.opacity(0.22)) } else { - match theme.appearance { - crate::theme::Appearance::Dark => { - let purple = crate::theme::oklch(0.35, 0.12, 277.0); - (purple.opacity(0.45), purple.opacity(0.60)) - } - crate::theme::Appearance::Light => { - (theme.accent.opacity(0.10), theme.accent.opacity(0.16)) - } - } + (theme.accent_wash, theme.accent.opacity(0.16)) }; let mut strip = div() @@ -6301,9 +6291,10 @@ impl Shell { .justify_center() .group_hover(group.clone(), |s| s.opacity(0.0)) .child(if subagent_running { - loaders::mini_gradient_spinner( + loaders::mini_glyph_spinner( format!("subagent-tab-{ix}"), 2.0, + theme.glyph, cx.entity_id(), cx, ) @@ -7201,6 +7192,10 @@ fn header_icon_button( impl Render for Shell { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { self.viewport_width = f32::from(window.viewport_size().width); + // Appearance actions persist independently of the shell. Mirror the + // globals before any later debounced settings save can overwrite them. + self.settings.appearance = crate::appearance::mode(cx); + self.settings.accent_color = crate::appearance::accent(cx); let theme = Theme::of(cx); // The shell tone (zeron `.frost`): the surface the sidebar sits on and // the main panel floats over as an inset rounded card. On macOS the diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 3dfdccf6cc..3a34399709 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -232,13 +232,11 @@ pub(super) struct RenameSpaceDialog { /// Dot color for a chat's display status (tab dots + Sessions rows). pub(super) fn status_dot_color(status: ChatIndicator, theme: &Theme) -> gpui::Hsla { match status { - // Pink, not amber — the harsh yellow read as a warning; running is - // routine (user request). Non-done statuses sit well below full + // Preset activity tone, not warning amber: running is routine. + // Non-done statuses sit well below full // strength: at full alpha the colored words shouted across the // whole sidebar (user request) — only Done keeps its pop. - ChatIndicator::Working => { - theme.busy.opacity(0.55) // pink-400, muted - } + ChatIndicator::Working => theme.busy.opacity(0.55), // Blue: "asking you a question" must read differently from "busy // working" at a glance. ChatIndicator::AwaitingInput => theme.accent.opacity(0.6), diff --git a/crates/ui/src/theme.rs b/crates/ui/src/theme.rs index 0fcb89fcd3..892581f32b 100644 --- a/crates/ui/src/theme.rs +++ b/crates/ui/src/theme.rs @@ -35,8 +35,147 @@ use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; use gpui::{App, Global, Hsla, SharedString, hsla}; +use serde::{Deserialize, Serialize}; use zeron_syntax::HighlightKind; +/// User-selectable accent family. A choice is one color identity, not a +/// miniature multi-hue theme: every interactive accent role stays on the same +/// authored hue in both appearances. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AccentColor { + /// The exact upstream Zeron indigo. + #[default] + #[serde(alias = "violet", alias = "indigo", alias = "red", alias = "purple")] + Zeron, + Orange, + Amber, + Green, + #[serde(alias = "teal")] + Cyan, + Blue, + Pink, +} + +impl AccentColor { + pub const ALL: [Self; 7] = [ + Self::Zeron, + Self::Orange, + Self::Amber, + Self::Green, + Self::Cyan, + Self::Blue, + Self::Pink, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::Zeron => "Zeron", + Self::Orange => "Orange", + Self::Amber => "Amber", + Self::Green => "Green", + Self::Cyan => "Cyan", + Self::Blue => "Blue", + Self::Pink => "Pink", + } + } + + fn tokens(self, appearance: Appearance) -> AccentTokens { + // These are deliberately authored pairs. Runtime contrast correction + // used to gamut-clip OKLCH into sRGB and then mutate HSL lightness, + // producing different chroma and apparent hues across light/dark. + let (primary, strong) = match (self, appearance) { + (Self::Zeron, Appearance::Dark) => { + (oklch(0.673, 0.182, 276.935), oklch(0.585, 0.233, 277.117)) + } + (Self::Zeron, Appearance::Light) => { + (oklch(0.511, 0.262, 276.966), oklch(0.511, 0.262, 276.966)) + } + (Self::Orange, Appearance::Dark) => (oklch(0.75, 0.18, 55.0), oklch(0.54, 0.19, 55.0)), + (Self::Orange, Appearance::Light) => (oklch(0.50, 0.19, 55.0), oklch(0.50, 0.19, 55.0)), + (Self::Amber, Appearance::Dark) => (oklch(0.80, 0.17, 84.0), oklch(0.52, 0.14, 84.0)), + (Self::Amber, Appearance::Light) => (oklch(0.48, 0.14, 84.0), oklch(0.48, 0.14, 84.0)), + (Self::Green, Appearance::Dark) => (oklch(0.75, 0.17, 150.0), oklch(0.50, 0.15, 150.0)), + (Self::Green, Appearance::Light) => { + (oklch(0.46, 0.14, 150.0), oklch(0.46, 0.14, 150.0)) + } + (Self::Cyan, Appearance::Dark) => (oklch(0.76, 0.13, 205.0), oklch(0.49, 0.12, 205.0)), + (Self::Cyan, Appearance::Light) => (oklch(0.45, 0.11, 205.0), oklch(0.45, 0.11, 205.0)), + (Self::Blue, Appearance::Dark) => (oklch(0.70, 0.17, 255.0), oklch(0.50, 0.20, 255.0)), + (Self::Blue, Appearance::Light) => (oklch(0.47, 0.21, 255.0), oklch(0.47, 0.21, 255.0)), + (Self::Pink, Appearance::Dark) => (oklch(0.72, 0.18, 350.0), oklch(0.51, 0.20, 350.0)), + (Self::Pink, Appearance::Light) => (oklch(0.48, 0.20, 350.0), oklch(0.48, 0.20, 350.0)), + }; + AccentTokens { + primary, + strong, + wash: match appearance { + Appearance::Dark => strong.opacity(0.45), + Appearance::Light => primary.opacity(0.10), + }, + selection: primary.opacity(if appearance.is_dark() { 0.35 } else { 0.24 }), + caret: primary, + code_text: primary, + code_wash: primary.opacity(match appearance { + Appearance::Dark => 0.12, + Appearance::Light => 0.10, + }), + activity: primary, + glyph: GlyphPalette::for_accent(primary, strong, appearance), + } + } +} + +/// The three authored rows of the animated 2×3 pixel glyph. Keeping this as a +/// palette entity preserves the mark's light→mid→deep personality while letting +/// every accent preset own it as one coherent family. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct GlyphPalette { + pub light: Hsla, + pub mid: Hsla, + pub deep: Hsla, +} + +impl GlyphPalette { + fn for_accent(primary: Hsla, strong: Hsla, appearance: Appearance) -> Self { + let mut light = primary; + let mut deep = strong; + match appearance { + Appearance::Dark => { + light.l = (light.l + 0.14).min(0.90); + light.s *= 0.72; + } + Appearance::Light => { + light.l = (light.l + 0.11).min(0.76); + light.s *= 0.78; + deep.l = (deep.l - 0.09).max(0.22); + } + } + Self { + light, + mid: primary, + deep, + } + } + + pub fn rows(self) -> [Hsla; 3] { + [self.light, self.mid, self.deep] + } +} + +#[derive(Debug, Clone, Copy)] +struct AccentTokens { + primary: Hsla, + strong: Hsla, + wash: Hsla, + selection: Hsla, + caret: Hsla, + code_text: Hsla, + code_wash: Hsla, + activity: Hsla, + glyph: GlyphPalette, +} + /// Which appearance the app is painting. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum Appearance { @@ -273,6 +412,13 @@ impl SyntaxPalette { invalid: red, } } + + fn for_appearance(appearance: Appearance, text: Hsla, comment: Hsla, danger: Hsla) -> Self { + match appearance { + Appearance::Dark => Self::dark(text, comment, danger), + Appearance::Light => Self::light(text, comment, danger), + } + } } /// Git history intentionally softens lane saturation so the graph remains @@ -287,6 +433,8 @@ fn git_graph_tone(mut color: Hsla) -> Hsla { pub struct Theme { /// Which appearance these tokens were built for. pub appearance: Appearance, + /// The selected interactive accent used to build this theme. + pub accent_color: AccentColor, // ---- paint: neutral surfaces ---- /// Main content panel. Dark: the deepest plane (#060606). Light: pure white — @@ -348,11 +496,12 @@ pub struct Theme { pub on_solid: Hsla, // ---- paint: accents ---- - /// Accent — indigo. Text/icon weight: indigo-400 on dark, indigo-600 on light - /// (the 400 fails AA on white). + /// Primary tone in the selected accent family. pub accent: Hsla, /// Stronger accent for fills that carry [`Self::on_accent`] text. pub accent_strong: Hsla, + /// Low-emphasis wash of the same accent for tinted identity surfaces. + pub accent_wash: Hsla, /// Label color on top of [`Self::accent_strong`]. pub on_accent: Hsla, /// Danger — red (errors, stop button). @@ -365,8 +514,10 @@ pub struct Theme { pub warning_muted: Hsla, /// Success / online — emerald. pub success: Hsla, - /// Working / streaming indicator — pink. + /// Working / streaming indicator in the selected accent family. pub busy: Hsla, + /// Three-tone animated pixel glyph palette in the selected accent family. + pub glyph: GlyphPalette, /// Softer success for text on a success-tinted chip. pub success_muted: Hsla, @@ -391,14 +542,13 @@ pub struct Theme { pub selection: Hsla, /// Terminal block cursor. pub cursor: Hsla, - /// Composer text caret. A blue distinct from `accent` — sampled from the - /// original composer, not derived, so it keeps its own token. + /// Composer text caret in the selected accent family. pub caret: Hsla, /// Destructive-action button fill (danger plate, carries [`Self::on_accent`]). pub danger_strong: Hsla, // ---- paint: code & diff ---- - /// Inline-code text — violet, per the user's "a nice purple" request. + /// Inline-code text in the selected accent family. pub code_text: Hsla, /// Inline-code wash behind [`Self::code_text`]. pub code_wash: Hsla, @@ -612,8 +762,14 @@ impl Theme { /// reference screenshots of the original app (docs/reference): main panel /// `#060606`, shell/sidebar `#0d0d0d`. pub fn dark() -> Self { + Self::dark_with_accent(AccentColor::default()) + } + + pub fn dark_with_accent(accent_color: AccentColor) -> Self { + let accent = accent_color.tokens(Appearance::Dark); Self { appearance: Appearance::Dark, + accent_color, bg: grey(6), // main panel — sampled #060606 surface: grey(13), // shell / sidebar — sampled #0d0d0d surface_raised: neutral(0.235), @@ -628,28 +784,35 @@ impl Theme { text_muted: neutral(0.708), // ~neutral-400 text_faint: neutral(0.556), // ~neutral-500 text_dim: grey(0x98), - solid: neutral(0.922), // near-white plate - on_solid: grey(0x0e), // near-black label - accent: oklch(0.673, 0.182, 276.935), // indigo-400 - accent_strong: oklch(0.585, 0.233, 277.117), // indigo-500 + solid: neutral(0.922), // near-white plate + on_solid: grey(0x0e), // near-black label + accent: accent.primary, + accent_strong: accent.strong, + accent_wash: accent.wash, on_accent: neutral(0.985), danger: oklch(0.704, 0.191, 22.216), // red-400 danger_muted: oklch(0.808, 0.114, 19.571), // red-300 warning: oklch(0.828, 0.189, 84.429), // amber-400 warning_muted: oklch(0.924, 0.12, 95.746), // amber-200 success: oklch(0.765, 0.177, 163.223), // emerald-400 - busy: oklch(0.718, 0.202, 349.761), // pink-400 + busy: accent.activity, + glyph: accent.glyph, success_muted: oklch(0.845, 0.143, 164.978), // emerald-300 surface_raised_hover: neutral(0.29), band: band_for(Appearance::Dark), input_bg: hsla(0.0, 0.0, 1.0, 0.03), - selection: hsla(0.66, 0.6, 0.55, 0.35), + selection: accent.selection, cursor: hsla(0.0, 0.0, 1.0, 0.35), - caret: hsla(0.66, 0.7, 0.7, 1.0), + caret: accent.caret, danger_strong: oklch(0.58, 0.16, 25.0), - code_text: oklch(0.811, 0.111, 293.571), // violet-300 - code_wash: oklch(0.702, 0.183, 293.541).opacity(0.12), // violet-400/12 - syntax: SyntaxPalette::dark(neutral(0.922), neutral(0.60), oklch(0.704, 0.191, 22.216)), + code_text: accent.code_text, + code_wash: accent.code_wash, + syntax: SyntaxPalette::for_appearance( + Appearance::Dark, + neutral(0.922), + neutral(0.60), + oklch(0.704, 0.191, 22.216), + ), diff_add: oklch(0.765, 0.177, 163.223), // emerald-400 diff_del: oklch(0.704, 0.191, 22.216), // red-400 diff_hunk_bg: hsla(0.6, 0.35, 0.6, 0.05), @@ -669,8 +832,14 @@ impl Theme { /// from the 400 to the 600 step at identical hue so they clear WCAG AA on /// white instead of glowing. pub fn light() -> Self { + Self::light_with_accent(AccentColor::default()) + } + + pub fn light_with_accent(accent_color: AccentColor) -> Self { + let accent = accent_color.tokens(Appearance::Light); Self { appearance: Appearance::Light, + accent_color, bg: grey(0xff), // main panel — clean white // Deeper than ~neutral-100 looks on paper: the content card is pure // white and sits *inside* this surface, so too small a step leaves the @@ -702,15 +871,17 @@ impl Theme { text_dim: neutral(0.50), solid: neutral(0.205), // near-black plate, deeper than body text on_solid: neutral(0.985), // near-white label - accent: oklch(0.511, 0.262, 276.966), // indigo-600 - accent_strong: oklch(0.511, 0.262, 276.966), // indigo-600 fill + accent: accent.primary, + accent_strong: accent.strong, + accent_wash: accent.wash, on_accent: neutral(0.985), danger: oklch(0.577, 0.245, 27.325), // red-600 danger_muted: oklch(0.505, 0.213, 27.518), // red-700 warning: oklch(0.555, 0.163, 48.998), // amber-700 — carries 12px text warning_muted: oklch(0.473, 0.137, 46.201), // amber-800 success: oklch(0.596, 0.145, 163.225), // emerald-600 - busy: oklch(0.592, 0.249, 0.584), // pink-600 + busy: accent.activity, + glyph: accent.glyph, success_muted: oklch(0.508, 0.118, 165.612), // emerald-700 // Opaque pills darken on hover here rather than brighten — same // "brighten the plate, don't wash it out" rule, read the other way. @@ -719,13 +890,18 @@ impl Theme { // the dark 16% would read as a bruise. band: band_for(Appearance::Light), input_bg: grey(0xff), - selection: hsla(0.66, 0.75, 0.62, 0.28), + selection: accent.selection, cursor: hsla(0.0, 0.0, 0.0, 0.55), - caret: hsla(0.66, 0.78, 0.42, 1.0), + caret: accent.caret, danger_strong: oklch(0.51, 0.20, 25.0), - code_text: oklch(0.491, 0.27, 292.581), // violet-700 - code_wash: oklch(0.541, 0.281, 293.009).opacity(0.10), // violet-600/10 - syntax: SyntaxPalette::light(neutral(0.25), neutral(0.48), oklch(0.505, 0.213, 27.518)), + code_text: accent.code_text, + code_wash: accent.code_wash, + syntax: SyntaxPalette::for_appearance( + Appearance::Light, + neutral(0.25), + neutral(0.48), + oklch(0.505, 0.213, 27.518), + ), diff_add: oklch(0.596, 0.145, 163.225), // emerald-600 diff_del: oklch(0.577, 0.245, 27.325), // red-600 diff_hunk_bg: hsla(0.6, 0.35, 0.35, 0.07), @@ -738,18 +914,46 @@ impl Theme { /// Build the theme for an appearance. pub fn for_appearance(appearance: Appearance) -> Self { + Self::for_preferences(appearance, AccentColor::default()) + } + + pub fn for_preferences(appearance: Appearance, accent: AccentColor) -> Self { match appearance { - Appearance::Dark => Self::dark(), - Appearance::Light => Self::light(), + Appearance::Dark => Self::dark_with_accent(accent), + Appearance::Light => Self::light_with_accent(accent), } } + /// Sidebar chrome deliberately keeps Zeron's authored identity palette, + /// while live activity and glyphs inherit their explicit roles from the + /// selected preset. This keeps navigation stable without freezing status + /// feedback to one hard-coded color. + pub fn sidebar(appearance: Appearance, selected_accent: AccentColor) -> Self { + let mut theme = Self::for_preferences(appearance, AccentColor::Zeron); + let selected = selected_accent.tokens(appearance); + theme.busy = selected.activity; + theme.glyph = selected.glyph; + theme + } + /// Install the theme for `appearance` as the gpui global and point the /// context-free paint helpers at it. The **only** way the appearance should /// change — setting the global directly leaves [`current_appearance`] stale. pub fn install(appearance: Appearance, cx: &mut App) { + Self::install_preferences(appearance, AccentColor::default(), cx); + } + + pub fn install_preferences(appearance: Appearance, accent: AccentColor, cx: &mut App) { + let accent_changed = cx + .try_global::() + .is_some_and(|theme| theme.accent_color != accent); set_current_appearance(appearance); - cx.set_global(Self::for_appearance(appearance)); + cx.set_global(Self::for_preferences(appearance, accent)); + // An accent-only swap leaves CURRENT_APPEARANCE unchanged, but cached + // resolved colors still need to be discarded for the next frame. + if accent_changed { + THEME_GENERATION.fetch_add(1, Ordering::Relaxed); + } } /// Read the theme global. @@ -1189,6 +1393,147 @@ mod tests { assert!((contrast_ratio(black, white) - contrast_ratio(white, black)).abs() < 1e-4); } + #[test] + fn zeron_accent_is_the_exact_upstream_default() { + let dark = Theme::dark(); + let light = Theme::light(); + assert_eq!(dark.accent_color, AccentColor::Zeron); + assert_eq!(dark.accent, oklch(0.673, 0.182, 276.935)); + assert_eq!(dark.accent_strong, oklch(0.585, 0.233, 277.117)); + assert_eq!(dark.code_text, dark.accent); + assert_eq!(dark.busy, dark.accent); + assert_eq!(dark.glyph.mid, dark.accent); + assert_eq!(dark.caret, dark.accent); + assert_eq!(light.accent, oklch(0.511, 0.262, 276.966)); + assert_eq!(light.accent_strong, oklch(0.511, 0.262, 276.966)); + assert_eq!(light.code_text, light.accent); + assert_eq!(light.busy, light.accent); + assert_eq!(light.glyph.mid, light.accent); + assert_eq!(light.caret, light.accent); + } + + #[test] + fn previous_preview_accent_names_migrate_without_resetting_settings() { + for old_default in ["violet", "indigo", "red", "purple"] { + assert_eq!( + serde_json::from_str::(&format!(r#""{old_default}""#)).unwrap(), + AccentColor::Zeron + ); + } + assert_eq!( + serde_json::from_str::(r#""teal""#).unwrap(), + AccentColor::Cyan + ); + } + + #[test] + fn sidebar_keeps_zeron_chrome_but_inherits_activity_roles() { + for appearance in [Appearance::Dark, Appearance::Light] { + for selected_accent in AccentColor::ALL { + let selected = Theme::for_preferences(appearance, selected_accent); + let sidebar = Theme::sidebar(appearance, selected_accent); + assert_eq!(sidebar.accent_color, AccentColor::Zeron); + assert_eq!(sidebar.accent, Theme::for_appearance(appearance).accent); + assert_eq!(sidebar.busy, selected.busy); + assert_eq!(sidebar.glyph, selected.glyph); + if selected_accent != AccentColor::Zeron { + assert_ne!(sidebar.accent, selected.accent); + } + } + } + } + + #[test] + fn every_accent_is_one_coherent_color_identity() { + let default_dark = Theme::dark(); + let default_light = Theme::light(); + for accent in AccentColor::ALL { + for (theme, baseline) in [ + (Theme::dark_with_accent(accent), &default_dark), + (Theme::light_with_accent(accent), &default_light), + ] { + assert_eq!(theme.accent_color, accent); + for (surface_name, surface) in [ + ("content", theme.bg), + ("shell", theme.surface), + ("card", theme.surface_card), + ] { + assert!( + contrast_ratio(theme.accent, surface) >= 4.5, + "{} {:?} accent is only {:.2}:1 on the {surface_name} surface", + accent.label(), + theme.appearance, + contrast_ratio(theme.accent, surface) + ); + } + assert!( + contrast_ratio(theme.on_accent, theme.accent_strong) >= 4.0, + "{} {:?} solid is only {:.2}:1 against its label", + accent.label(), + theme.appearance, + contrast_ratio(theme.on_accent, theme.accent_strong) + ); + assert!(contrast_ratio(theme.code_text, theme.bg) >= 4.5); + assert!(contrast_ratio(theme.busy, theme.bg) >= 3.0); + assert_eq!(theme.code_text, theme.accent); + assert_eq!(theme.busy, theme.accent); + assert_eq!(theme.glyph.mid, theme.accent); + assert_ne!(theme.glyph.light, theme.glyph.mid); + assert_ne!(theme.glyph.deep, theme.glyph.mid); + assert_eq!(theme.caret, theme.accent); + assert_eq!( + theme.selection, + theme.accent.opacity(if theme.appearance.is_dark() { + 0.35 + } else { + 0.24 + }) + ); + assert!(hue_distance(theme.accent.h, theme.accent_strong.h) <= 0.04); + + // Semantic colors and code syntax keep their meaning. Accent + // preferences only recolor interactive identity roles. + assert_eq!(theme.danger, baseline.danger); + assert_eq!(theme.warning, baseline.warning); + assert_eq!(theme.success, baseline.success); + assert_eq!(theme.diff_add, baseline.diff_add); + assert_eq!(theme.diff_del, baseline.diff_del); + if accent != AccentColor::Zeron { + assert_ne!(theme.code_text, baseline.code_text); + assert_ne!(theme.busy, baseline.busy); + assert_ne!(theme.selection, baseline.selection); + } + assert_eq!(theme.syntax.keyword, baseline.syntax.keyword); + assert_eq!(theme.syntax.string, baseline.syntax.string); + assert_eq!(theme.syntax.number, baseline.syntax.number); + } + } + } + + fn hue_distance(a: f32, b: f32) -> f32 { + let distance = (a - b).abs(); + distance.min(1.0 - distance) + } + + #[test] + fn every_settings_swatch_has_a_distinct_primary() { + let previews = AccentColor::ALL.map(|accent| { + let theme = Theme::dark_with_accent(accent); + (accent, theme.accent) + }); + for (index, (accent, color)) in previews.iter().enumerate() { + for (other_accent, other_color) in previews.iter().skip(index + 1) { + assert_ne!( + color, + other_color, + "{} and {} share the same primary", + accent.label(), + other_accent.label() + ); + } + } + } + /// The core claim of the light palette: it is *paired* to dark by contrast /// ratio, not mirrored by lightness. Each text token must land within 1.0 of /// its counterpart's ratio against its own background. @@ -1329,29 +1674,36 @@ mod tests { HighlightKind::Embedded, HighlightKind::Invalid, ]; - for theme in [Theme::dark(), Theme::light()] { - let add_bg = flatten(theme.diff_add.opacity(0.055), theme.bg); - let del_bg = flatten(theme.diff_del.opacity(0.055), theme.bg); - for kind in kinds { - let color = theme.syntax.color(kind); - let floor = if matches!( - kind, - HighlightKind::Comment - | HighlightKind::Operator - | HighlightKind::Punctuation - | HighlightKind::Embedded - ) { - 3.0 - } else { - 4.5 - }; - for (name, background) in [("code", theme.bg), ("add", add_bg), ("del", del_bg)] { - let ratio = contrast_ratio(color, background); - assert!( - ratio >= floor, - "{:?} {kind:?} is {ratio:.2}:1 on {name}", - theme.appearance - ); + for accent in AccentColor::ALL { + for theme in [ + Theme::dark_with_accent(accent), + Theme::light_with_accent(accent), + ] { + let add_bg = flatten(theme.diff_add.opacity(0.055), theme.bg); + let del_bg = flatten(theme.diff_del.opacity(0.055), theme.bg); + for kind in kinds { + let color = theme.syntax.color(kind); + let floor = if matches!( + kind, + HighlightKind::Comment + | HighlightKind::Operator + | HighlightKind::Punctuation + | HighlightKind::Embedded + ) { + 3.0 + } else { + 4.5 + }; + for (name, background) in [("code", theme.bg), ("add", add_bg), ("del", del_bg)] + { + let ratio = contrast_ratio(color, background); + assert!( + ratio >= floor, + "{} {:?} {kind:?} is {ratio:.2}:1 on {name}", + accent.label(), + theme.appearance + ); + } } } } diff --git a/crates/ui/src/transcript.rs b/crates/ui/src/transcript.rs index 616005e183..90f5881354 100644 --- a/crates/ui/src/transcript.rs +++ b/crates/ui/src/transcript.rs @@ -3560,6 +3560,7 @@ impl Transcript { cx: &mut Context, ) -> AnyElement { use crate::attachments::AttachmentSnapshot; + let glyph = Theme::of(cx).glyph; let device_ids = self.attachment_device_ids(cx); let mut strip = div() .w_full() @@ -3653,9 +3654,10 @@ impl Transcript { )); let indicator: AnyElement = match uploading { Some(pct) => crate::loaders::upload_progress_ring(pct, 34.0), - None => crate::loaders::mini_gradient_spinner( + None => crate::loaders::mini_glyph_spinner( format!("att-sending-{row_id}-{aix}"), 3.0, + glyph, cx.entity_id(), cx, ) @@ -4754,7 +4756,7 @@ impl Transcript { /// A sent message's text with its file-mention chips. The same recipe as the /// markdown renderer's inline code (`flat_text_element`): chip ranges shape in -/// the mono font at `code_text` violet, [`StyledText`] supplies wrapped glyph +/// the mono font at the spectrum's `code_text`, [`StyledText`] supplies wrapped glyph /// geometry through its layout handle, and a canvas paints the rounded /// `code_wash` *beneath* the glyphs — so chips wrap, clip, and scroll exactly /// like the text they decorate. @@ -5199,12 +5201,13 @@ fn chip_header_row( row.child( div() .flex_none() - .child(crate::loaders::mini_gradient_spinner( + .child(crate::loaders::mini_glyph_spinner( format!( "subagent-chip-{}", tool.subagent_ref.as_deref().unwrap_or_default() ), 2.0, + theme.glyph, view, cx, )), From eeeb537065d92eae162f8ebc61e14268c146dfe6 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 01:48:33 +0200 Subject: [PATCH 2/9] Add theme registry and VS Code imports Support independent light and dark variants, semantic and terminal palettes, surface preferences, accent overlays, and last-known-good custom theme persistence. --- ARCHITECTURE.md | 11 +- Cargo.lock | 60 + Cargo.toml | 4 + crates/ui/Cargo.toml | 1 + crates/ui/src/appearance.rs | 134 ++- crates/ui/src/lib.rs | 6 +- crates/ui/src/settings.rs | 54 +- crates/ui/src/settings/appearance.rs | 1627 +++++++++++++++++++++++--- crates/ui/src/shell.rs | 13 +- crates/ui/src/terminal/view.rs | 300 ++--- crates/ui/src/theme.rs | 425 +++++-- 11 files changed, 2153 insertions(+), 482 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 1386970dc3..c0e8a949e9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -142,6 +142,8 @@ zeron/ rpc/ zeron-rpc # UiRpc/ControlRpc: typed req/resp/stream over WS (tokio- # tungstenite) + in-memory transport; device-room virtual # sockets ({s,k,to,from} frames) + theme/ zeron-theme # source-neutral theme schema + built-in/custom registry, + # validation, provenance, and local VS Code compiler ui/ zeron-ui # gpui app: shell, sidebar, conversation, composer, # terminal view, diff pane, settings, animation kit apps/ @@ -199,8 +201,13 @@ feature spec `docs/research/feature-inventory.md` §1. ease-out width/height transitions for sidebar/panes, sidebar-resort **slide animation** (we own the list, so animate row positions directly — the View Transitions equivalent, 260ms cubic-bezier(0.22,1,0.36,1)), reduced-motion switch. -- **Theme**: always-dark monochrome, oklch-derived neutral scale precomputed to Hsla, hairline - borders, Geist/Geist Mono bundled fonts. +- **Theme**: independent light/dark resolved variants, theme-owned semantic/syntax/terminal + palettes, optional interaction-accent overlays, and a device-local surface preference that + resolves each variant's recommended frost/opaque treatment without changing theme selection. + Forced frost derives contrast-checked tints from mapped theme surfaces. Local VS Code + file/package compilation and imported/linked custom families retain last-known-good + persistence. Colors remain paint-only; hairline borders and bundled Geist/Geist Mono remain + shared presentation foundations. ## 5. Engine plan diff --git a/Cargo.lock b/Cargo.lock index 568c2a38ce..96afa60493 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3479,6 +3479,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "json5" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1" +dependencies = [ + "pest", + "pest_derive", + "serde", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -4941,6 +4952,19 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "plist" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85" +dependencies = [ + "base64", + "indexmap", + "quick-xml 0.41.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.17.16" @@ -5268,6 +5292,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + [[package]] name = "quick_cache" version = "0.6.24" @@ -6865,6 +6898,7 @@ dependencies = [ "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -6873,6 +6907,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "time-macros" +version = "0.2.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -9282,6 +9326,21 @@ dependencies = [ "tree-sitter-yaml", ] +[[package]] +name = "zeron-theme" +version = "0.2.19" +dependencies = [ + "anyhow", + "clap", + "json5", + "plist", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror 2.0.19", +] + [[package]] name = "zeron-ui" version = "0.2.27" @@ -9312,6 +9371,7 @@ dependencies = [ "zeron-proto", "zeron-rpc", "zeron-syntax", + "zeron-theme", "zeron-update", ] diff --git a/Cargo.toml b/Cargo.toml index 326b2839d7..72261e8c3a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "2" members = [ + "crates/theme", "crates/proto", "crates/doc", "crates/sync", @@ -29,6 +30,7 @@ zeron-rpc = { path = "crates/rpc" } zeron-update = { path = "crates/update" } zeron-ui = { path = "crates/ui" } zeron-syntax = { path = "crates/syntax" } +zeron-theme = { path = "crates/theme" } # CRDT loro = "1.13" @@ -81,6 +83,8 @@ async-trait = "0.1" # serialization serde = { version = "1", features = ["derive"] } serde_json = "1" +json5 = "0.4" +plist = "1" uuid = { version = "1", features = ["v4", "serde"] } # storage diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index c3cc375a59..8b6b88e8d5 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -14,6 +14,7 @@ zeron-harness.workspace = true zeron-rpc.workspace = true zeron-update.workspace = true zeron-syntax.workspace = true +zeron-theme.workspace = true gpui.workspace = true gpui_platform.workspace = true gpui_tokio.workspace = true diff --git a/crates/ui/src/appearance.rs b/crates/ui/src/appearance.rs index 8209ab66d1..bfaffa8e7c 100644 --- a/crates/ui/src/appearance.rs +++ b/crates/ui/src/appearance.rs @@ -23,9 +23,10 @@ use std::path::{Path, PathBuf}; use gpui::{App, Global, Subscription, Window}; use serde::{Deserialize, Serialize}; +use zeron_theme::{AccentSelection, SurfacePreference, ThemeSelection}; use crate::settings::UiSettings; -use crate::theme::{AccentColor, Appearance, Theme}; +use crate::theme::{Appearance, Theme}; /// The user's appearance preference. Persisted in `ui-settings.json`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -59,7 +60,9 @@ impl AppearanceMode { pub struct AppearanceState { pub mode: AppearanceMode, pub system: Appearance, - pub accent: AccentColor, + pub themes: ThemeSelection, + pub accent: AccentSelection, + pub surface: SurfacePreference, /// Where `ui-settings.json` lives, so a menu action can persist the choice /// without routing through the shell entity that normally owns settings. pub data_dir: PathBuf, @@ -79,17 +82,33 @@ pub fn resolve(mode: AppearanceMode, system: Appearance) -> Appearance { /// Install the appearance globals and the matching theme. Call once at boot, /// before any window opens, so the first frame is already the right palette /// (installing later produces a visible dark-to-light flash). -pub fn init(mode: AppearanceMode, accent: AccentColor, data_dir: impl Into, cx: &mut App) { +pub fn init( + mode: AppearanceMode, + themes: ThemeSelection, + accent: AccentSelection, + surface: SurfacePreference, + data_dir: impl Into, + cx: &mut App, +) { let system = Appearance::from_window(cx.window_appearance()); tracing::debug!(?mode, ?system, "appearance: initial"); cx.set_global(AppearanceState { mode, system, + themes: themes.clone(), accent, + surface, data_dir: data_dir.into(), }); sync_ns_appearance(mode); - Theme::install_preferences(resolve(mode, system), accent, cx); + let appearance = resolve(mode, system); + Theme::install_selection( + appearance, + themes.variant_id(model_appearance(appearance)), + accent, + surface, + cx, + ); } /// The mode currently in effect (defaults to `System` before [`init`]). @@ -99,12 +118,24 @@ pub fn mode(cx: &App) -> AppearanceMode { .unwrap_or_default() } -pub fn accent(cx: &App) -> AccentColor { +pub fn themes(cx: &App) -> ThemeSelection { + cx.try_global::() + .map(|state| state.themes.clone()) + .unwrap_or_default() +} + +pub fn accent(cx: &App) -> AccentSelection { cx.try_global::() .map(|state| state.accent) .unwrap_or_default() } +pub fn surface(cx: &App) -> SurfacePreference { + cx.try_global::() + .map(|state| state.surface) + .unwrap_or_default() +} + /// Change the user's preference, repaint if that changed the palette, and write /// the choice to disk. pub fn set_mode(mode: AppearanceMode, cx: &mut App) { @@ -122,7 +153,25 @@ pub fn set_mode(mode: AppearanceMode, cx: &mut App) { } /// Change the interactive accent without changing any semantic theme roles. -pub fn set_accent(accent: AccentColor, cx: &mut App) { +pub fn set_theme(appearance: Appearance, variant_id: impl Into, cx: &mut App) { + if !cx.has_global::() { + return; + } + let variant_id = variant_id.into(); + let state = cx.global_mut::(); + if state.themes.variant_id(model_appearance(appearance)) == variant_id { + return; + } + state + .themes + .set_variant(model_appearance(appearance), variant_id); + let data_dir = state.data_dir.clone(); + let themes = state.themes.clone(); + apply(cx); + persist_themes(themes, &data_dir); +} + +pub fn set_accent(accent: AccentSelection, cx: &mut App) { if !cx.has_global::() { return; } @@ -136,6 +185,21 @@ pub fn set_accent(accent: AccentColor, cx: &mut App) { persist_accent(accent, &data_dir); } +/// Change glass independently from appearance, theme, and accent selections. +pub fn set_surface(surface: SurfacePreference, cx: &mut App) { + if !cx.has_global::() { + return; + } + let state = cx.global_mut::(); + if state.surface == surface { + return; + } + state.surface = surface; + let data_dir = state.data_dir.clone(); + apply(cx); + persist_surface(surface, &data_dir); +} + /// Read-modify-write `ui-settings.json` for just the appearance key. /// /// Deliberately a fresh load rather than a write of some cached struct: the @@ -150,14 +214,30 @@ fn persist(mode: AppearanceMode, data_dir: &Path) { } } -fn persist_accent(accent: AccentColor, data_dir: &Path) { +fn persist_themes(themes: ThemeSelection, data_dir: &Path) { let mut settings = UiSettings::load(data_dir); - settings.accent_color = accent; + settings.theme_selection = themes; + if let Err(err) = settings.save(data_dir) { + tracing::warn!(error = %err, "could not persist themes"); + } +} + +fn persist_accent(accent: AccentSelection, data_dir: &Path) { + let mut settings = UiSettings::load(data_dir); + settings.accent = accent; if let Err(err) = settings.save(data_dir) { tracing::warn!(error = %err, "could not persist accent color"); } } +fn persist_surface(surface: SurfacePreference, data_dir: &Path) { + let mut settings = UiSettings::load(data_dir); + settings.surface = surface; + if let Err(err) = settings.save(data_dir) { + tracing::warn!(error = %err, "could not persist surface preference"); + } +} + /// Subscribe a window to OS appearance changes. The returned [`Subscription`] /// must outlive the window — callers typically `.detach()` it. /// @@ -204,12 +284,17 @@ pub fn apply(cx: &mut App) { sync_ns_appearance(state.mode); let wanted = resolve(state.mode, state.system); let accent = state.accent; - let changed = !cx - .try_global::() - .is_some_and(|theme| theme.appearance == wanted && theme.accent_color == accent); + let surface = state.surface; + let variant_id = state.themes.variant_id(model_appearance(wanted)).to_owned(); + let changed = !cx.try_global::().is_some_and(|theme| { + theme.appearance == wanted + && theme.variant_id.as_ref() == variant_id + && theme.accent_selection == accent + && theme.surface_preference == surface + }); if changed { - tracing::debug!(?wanted, "appearance: installing palette"); - Theme::install_preferences(wanted, accent, cx); + tracing::debug!(?wanted, %variant_id, "appearance: installing palette"); + Theme::install_selection(wanted, &variant_id, accent, surface, cx); cx.refresh_windows(); } // Unconditional, even when the palette did not move: this is the only thing @@ -222,6 +307,29 @@ pub fn apply(cx: &mut App) { reapply_window_background(cx); } +/// Rebuild the current palette after the installed custom registry changes. +/// Unlike [`apply`], this deliberately reinstalls even when the selected id is +/// unchanged because a linked theme may have recompiled under that same id. +pub fn apply_registry_change(cx: &mut App) { + let Some(state) = cx.try_global::() else { + return; + }; + let wanted = resolve(state.mode, state.system); + let accent = state.accent; + let surface = state.surface; + let variant_id = state.themes.variant_id(model_appearance(wanted)).to_owned(); + Theme::install_selection(wanted, &variant_id, accent, surface, cx); + cx.refresh_windows(); + reapply_window_background(cx); +} + +fn model_appearance(appearance: Appearance) -> zeron_theme::Appearance { + match appearance { + Appearance::Dark => zeron_theme::Appearance::Dark, + Appearance::Light => zeron_theme::Appearance::Light, + } +} + /// Tell AppKit which appearance the app's windows use, so the chrome *it* /// draws — the traffic lights above all — matches the palette *we* paint. /// gpui never sets `NSAppearance`, so before this a pinned in-app theme left diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 4aead37958..c112ed5edb 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -39,6 +39,7 @@ pub mod state; pub mod syntax_cache; pub mod terminal; pub mod theme; +pub mod theme_library; pub mod transcript; use std::borrow::Cow; @@ -161,9 +162,12 @@ pub fn run_app(config: UiConfig) { // palette while settings load. let data_dir = config.boot().data_dir.clone(); let ui_settings = settings::UiSettings::load(&data_dir); + theme_library::init(data_dir.clone(), cx); appearance::init( ui_settings.appearance, - ui_settings.accent_color, + ui_settings.theme_selection, + ui_settings.accent, + ui_settings.surface, data_dir, cx, ); diff --git a/crates/ui/src/settings.rs b/crates/ui/src/settings.rs index 4063262823..26056386ec 100644 --- a/crates/ui/src/settings.rs +++ b/crates/ui/src/settings.rs @@ -125,10 +125,18 @@ pub struct UiSettings { pub keymap: KeymapConfig, /// Light/dark preference. Defaults to following the OS. pub appearance: crate::appearance::AppearanceMode, + /// Independently selected light and dark theme variants. + pub theme_selection: zeron_theme::ThemeSelection, /// Changes pane: side-by-side diffs instead of the unified stack. pub diff_split: bool, - /// Interactive identity accent. Defaults to the upstream Zeron color. - pub accent_color: crate::theme::AccentColor, + /// Interactive identity overlay; imported themes default to their own accent. + pub accent: zeron_theme::AccentSelection, + /// Glass policy, independent from the selected appearance, theme, and accent. + pub surface: zeron_theme::SurfacePreference, + /// Pre-theme settings used `accentColor`. Read it once, migrate to + /// [`Self::accent`], and never write it again. + #[serde(default, rename = "accentColor", skip_serializing)] + legacy_accent_color: Option, } impl Default for UiSettings { @@ -156,8 +164,11 @@ impl Default for UiSettings { terminal_open: false, keymap: KeymapConfig::default(), appearance: crate::appearance::AppearanceMode::default(), + theme_selection: zeron_theme::ThemeSelection::default(), diff_split: false, - accent_color: crate::theme::AccentColor::default(), + accent: zeron_theme::AccentSelection::default(), + surface: zeron_theme::SurfacePreference::default(), + legacy_accent_color: None, } } } @@ -364,7 +375,7 @@ impl UiSettings { pub fn load(data_dir: &Path) -> Self { match std::fs::read_to_string(Self::path(data_dir)) { Ok(text) => match serde_json::from_str::(&text) { - Ok(settings) => settings.clamped(), + Ok(settings) => settings.migrated().clamped(), Err(err) => { tracing::warn!(error = %err, "ui-settings corrupt; using defaults"); Self::default() @@ -385,6 +396,16 @@ impl UiSettings { std::fs::rename(&tmp, &path) } + fn migrated(mut self) -> Self { + if self.accent == zeron_theme::AccentSelection::ThemeDefault + && let Some(accent) = self.legacy_accent_color.take() + { + self.accent = zeron_theme::AccentSelection::Preset(accent.into()); + } + self.legacy_accent_color = None; + self + } + pub fn path(data_dir: &Path) -> PathBuf { data_dir.join(FILE_NAME) } @@ -442,8 +463,14 @@ mod tests { ..KeymapConfig::default() }, appearance: crate::appearance::AppearanceMode::Light, + theme_selection: zeron_theme::ThemeSelection { + light: "catppuccin-latte".into(), + dark: "catppuccin-mocha".into(), + }, diff_split: true, - accent_color: crate::theme::AccentColor::Cyan, + accent: zeron_theme::AccentSelection::Preset(zeron_theme::AccentPreset::Cyan), + surface: zeron_theme::SurfacePreference::Frosted, + legacy_accent_color: None, }; settings.save(dir.path()).unwrap(); assert_eq!(UiSettings::load(dir.path()), settings); @@ -477,7 +504,8 @@ mod tests { .unwrap(); let loaded = UiSettings::load(dir.path()); assert_eq!(loaded.appearance, crate::appearance::AppearanceMode::System); - assert_eq!(loaded.accent_color, crate::theme::AccentColor::Zeron); + assert_eq!(loaded.accent, zeron_theme::AccentSelection::ThemeDefault); + assert_eq!(loaded.surface, zeron_theme::SurfacePreference::ThemeDefault); assert_eq!(loaded.sidebar_width, 300.0); assert!(!loaded.sound_enabled, "other keys still parse"); assert!( @@ -490,6 +518,20 @@ mod tests { ); } + #[test] + fn legacy_accent_color_migrates_to_an_explicit_preset() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(UiSettings::path(dir.path()), r#"{"accentColor":"cyan"}"#).unwrap(); + let loaded = UiSettings::load(dir.path()); + assert_eq!( + loaded.accent, + zeron_theme::AccentSelection::Preset(zeron_theme::AccentPreset::Cyan) + ); + loaded.save(dir.path()).unwrap(); + let saved = std::fs::read_to_string(UiSettings::path(dir.path())).unwrap(); + assert!(!saved.contains("accentColor")); + } + #[test] fn missing_and_corrupt_files_yield_defaults() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ui/src/settings/appearance.rs b/crates/ui/src/settings/appearance.rs index 58524633b3..6ac89c1dc0 100644 --- a/crates/ui/src/settings/appearance.rs +++ b/crates/ui/src/settings/appearance.rs @@ -1,37 +1,190 @@ -//! Settings → Appearance: pick between following the system and pinning light or -//! dark. -//! -//! Uses [`widgets::option_card_row`] — a preview-card picker, because the choice -//! is a *look*, and a miniature of the result says more than a sentence about it. -//! The control itself is theme-agnostic; only the previews below know what a -//! theme is. -//! -//! Stateless. The choice lives in the [`crate::appearance`] globals, and -//! `set_mode` repaints every window, so this page has nothing of its own to hold. +//! Settings → Appearance: system behavior, independent light/dark variants, +//! and the optional interactive accent overlay. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; use gpui::{ - AnyElement, Context, Hsla, IntoElement, Render, SharedString, Window, div, prelude::*, px, + AnyElement, Context, Entity, Hsla, IntoElement, Render, SharedString, Subscription, Window, + div, prelude::*, px, +}; +use zeron_theme::vscode::{ImportReport, SourceCompilation}; +use zeron_theme::{ + AccentPreset, AccentSelection, CustomThemeEntry, CustomThemeStatus, InstallMode, + SurfacePreference, SurfaceTreatment, ThemeRegistry, ThemeSelection, }; use crate::appearance::{self, AppearanceMode}; +use crate::composer::{ComposerInput, ComposerInputEvent}; use crate::icons; +use crate::popover::{self, Popup}; use crate::settings::widgets; -use crate::theme::{AccentColor, Appearance, Theme}; +use crate::theme::{Appearance, Theme}; +use crate::theme_library; + +struct ImportDialog { + input: Entity, + _events: Subscription, + mode: InstallMode, + compilation: Option, + selected: HashSet, + review_variant: Option, + error: Option, +} -pub struct AppearancePage; +pub struct AppearancePage { + light_theme_menu: Popup<()>, + dark_theme_menu: Popup<()>, + import_dialog: Option, + review_entry: Option, + library_error: Option, +} impl AppearancePage { pub fn new(_cx: &mut Context) -> Self { - Self + Self { + light_theme_menu: Popup::default(), + dark_theme_menu: Popup::default(), + import_dialog: None, + review_entry: None, + library_error: None, + } + } + + fn open_import(&mut self, cx: &mut Context) { + let input = + cx.new(|cx| ComposerInput::new("Theme file, package.json, or extension folder", cx)); + let events = cx.subscribe(&input, |this: &mut Self, _, event, cx| { + if matches!(event, ComposerInputEvent::Submitted) { + this.compile_import(cx); + } + }); + self.import_dialog = Some(ImportDialog { + input, + _events: events, + mode: InstallMode::Snapshot, + compilation: None, + selected: HashSet::new(), + review_variant: None, + error: None, + }); + cx.notify(); + } + + fn compile_import(&mut self, cx: &mut Context) { + let Some(dialog) = self.import_dialog.as_mut() else { + return; + }; + let source = dialog.input.read(cx).text().trim().to_owned(); + if source.is_empty() { + dialog.error = Some("Choose a local theme file or extension folder.".into()); + cx.notify(); + return; + } + let path = PathBuf::from(&source); + let family_name = source_name(&path); + let family_id = format!("custom-{}", slug(&family_name)); + match theme_library::compile(&path, &family_id, &family_name) { + Ok(compilation) => { + dialog.selected = compilation + .family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect(); + dialog.review_variant = compilation + .family + .variants + .first() + .map(|variant| variant.id.clone()); + dialog.compilation = Some(compilation); + dialog.error = None; + } + Err(error) => dialog.error = Some(error.to_string().into()), + } + cx.notify(); + } + + fn choose_import_source(&mut self, cx: &mut Context) { + let receiver = cx.prompt_for_paths(gpui::PathPromptOptions { + files: true, + directories: true, + multiple: false, + prompt: Some("Choose Theme Source".into()), + }); + cx.spawn(async move |this, cx| { + let path = match receiver.await { + Ok(Ok(Some(mut paths))) => paths.pop(), + _ => None, + }; + let Some(path) = path else { + return; + }; + let _ = this.update(cx, |page, cx| { + if let Some(dialog) = page.import_dialog.as_mut() { + dialog.input.update(cx, |input, cx| { + input.set_text(path.display().to_string(), cx) + }); + } + page.compile_import(cx); + }); + }) + .detach(); + } + + fn finish_import(&mut self, cx: &mut Context) { + let Some(dialog) = self.import_dialog.as_mut() else { + return; + }; + let Some(compilation) = dialog.compilation.take() else { + return; + }; + let selected = dialog.selected.iter().cloned().collect::>(); + match theme_library::install(compilation.clone(), &selected, dialog.mode, cx) { + Ok(_) => self.import_dialog = None, + Err(error) => { + dialog.compilation = Some(compilation); + dialog.error = Some(error.to_string().into()); + } + } + cx.notify(); + } +} + +fn source_name(path: &Path) -> String { + let path = if path.file_name().and_then(|name| name.to_str()) == Some("package.json") { + path.parent().unwrap_or(path) + } else { + path + }; + path.file_stem() + .and_then(|name| name.to_str()) + .filter(|name| !name.is_empty()) + .unwrap_or("Custom theme") + .to_owned() +} + +fn slug(value: &str) -> String { + let mut result = String::new(); + let mut separator = false; + for character in value.chars().flat_map(char::to_lowercase) { + if character.is_ascii_alphanumeric() { + if separator && !result.is_empty() { + result.push('-'); + } + result.push(character); + separator = false; + } else { + separator = true; + } + } + if result.is_empty() { + "theme".into() + } else { + result } } -/// One placeholder bar in the miniature, width given as a fraction of its -/// container. -/// -/// Relative rather than fixed px because the System card renders this same -/// miniature into *half* a card. Fixed widths were wider than the squeezed -/// content pane and spilled out over the card edge. fn bar(fraction: f32, tone: Hsla) -> gpui::Div { div() .h(px(5.0)) @@ -40,15 +193,82 @@ fn bar(fraction: f32, tone: Hsla) -> gpui::Div { .bg(tone) } -fn accent_helper(accent: AccentColor) -> String { - format!( - "{} · Controls, glyphs, selections, code, and activity.", - accent.label() - ) +fn accent_helper(accent: AccentSelection) -> String { + match accent { + AccentSelection::ThemeDefault => { + "Theme default · Uses the palette's intended color.".into() + } + AccentSelection::Preset(preset) => format!( + "{} · Controls, glyphs, selections, code, and activity.", + preset.label() + ), + } +} + +fn surface_label(surface: SurfacePreference) -> &'static str { + match surface { + SurfacePreference::ThemeDefault => "Theme default", + SurfacePreference::Frosted => "Frosted", + SurfacePreference::Opaque => "Opaque", + } +} + +fn surface_helper(surface: SurfacePreference, resolved: SurfaceTreatment) -> String { + match surface { + SurfacePreference::ThemeDefault => format!( + "Theme default · This theme recommends {} surfaces.", + match resolved { + SurfaceTreatment::Frosted => "frosted", + SurfaceTreatment::Opaque => "opaque", + } + ), + SurfacePreference::Frosted => { + "Frosted · Uses theme-colored glass wherever the platform supports blur.".into() + } + SurfacePreference::Opaque => "Opaque · Keeps surfaces solid across every theme.".into(), + } +} + +fn surface_choice( + theme: &Theme, + surface: SurfacePreference, + selected: bool, +) -> gpui::Stateful { + div() + .id(SharedString::from(format!( + "appearance-surface-{}", + surface_label(surface).to_lowercase().replace(' ', "-") + ))) + .h(px(30.0)) + .px(px(10.0)) + .rounded(px(7.0)) + .border_1() + .border_color(if selected { theme.accent } else { theme.border }) + .bg(if selected { + theme.accent_wash + } else { + theme.surface_raised.opacity(0.28) + }) + .text_size(px(11.5)) + .font_weight(if selected { + gpui::FontWeight::MEDIUM + } else { + gpui::FontWeight::NORMAL + }) + .text_color(if selected { + theme.accent + } else { + theme.text_muted + }) + .flex() + .items_center() + .cursor_pointer() + .when(!selected, |control| { + control.hover(|style| style.bg(theme.surface_raised_hover)) + }) + .child(surface_label(surface)) } -/// Which corners a miniature rounds — the split card needs each half to round -/// only its outer side so the two meet flush down the middle. #[derive(Clone, Copy, PartialEq, Eq)] enum Corners { All, @@ -56,14 +276,6 @@ enum Corners { Right, } -/// A miniature of the app in `theme`: sidebar strip, inset content card, a few -/// placeholder lines. Built from the theme's own tokens rather than fixed -/// swatches, so the previews stay honest if the palette is retuned. -/// -/// Rounds itself: the card frame cannot do it for us (see -/// [`widgets::OPTION_CARD_RADIUS`]). Only this root paints a background that -/// reaches the corners — the sidebar strip is transparent and the content card is -/// inset — so rounding here is enough. fn miniature(theme: &Theme, corners: Corners) -> AnyElement { let line = theme.text.opacity(0.22); let strong = theme.text.opacity(0.34); @@ -75,7 +287,6 @@ fn miniature(theme: &Theme, corners: Corners) -> AnyElement { Corners::Right => root.rounded_tr(r).rounded_br(r), }; root.child( - // Sidebar strip. div() .w(px(44.0)) .h_full() @@ -92,7 +303,6 @@ fn miniature(theme: &Theme, corners: Corners) -> AnyElement { .child(bar(1.0, line)), ) .child( - // Inset content card — the same rounded plate the real shell floats. div() .flex_1() .min_w_0() @@ -115,10 +325,13 @@ fn miniature(theme: &Theme, corners: Corners) -> AnyElement { .into_any_element() } -/// The System card: light on the left, dark on the right. Each half is a -/// complete miniature clipped to its side, which is what makes the card read as -/// "whichever one the system is on". -fn miniature_split(accent: AccentColor) -> AnyElement { +fn miniature_split( + themes: &ThemeSelection, + accent: AccentSelection, + surface: SurfacePreference, +) -> AnyElement { + let light = Theme::for_selection(Appearance::Light, &themes.light, accent, surface); + let dark = Theme::for_selection(Appearance::Dark, &themes.dark, accent, surface); div() .size_full() .flex() @@ -128,35 +341,39 @@ fn miniature_split(accent: AccentColor) -> AnyElement { .w_1_2() .h_full() .overflow_hidden() - .child(miniature(&Theme::light_with_accent(accent), Corners::Left)), + .child(miniature(&light, Corners::Left)), ) .child( div() .w_1_2() .h_full() .overflow_hidden() - .child(miniature(&Theme::dark_with_accent(accent), Corners::Right)), + .child(miniature(&dark, Corners::Right)), ) .into_any_element() } -/// The preview graphic for a mode. -/// -/// The one place `Theme::light()`/`Theme::dark()` are legitimately built outside -/// the installed global: a preview has to show the palette you are *not* using. -fn preview(mode: AppearanceMode, accent: AccentColor) -> AnyElement { +fn preview( + mode: AppearanceMode, + themes: &ThemeSelection, + accent: AccentSelection, + surface: SurfacePreference, +) -> AnyElement { match mode { - AppearanceMode::System => miniature_split(accent), - AppearanceMode::Light => miniature(&Theme::light_with_accent(accent), Corners::All), - AppearanceMode::Dark => miniature(&Theme::dark_with_accent(accent), Corners::All), + AppearanceMode::System => miniature_split(themes, accent, surface), + AppearanceMode::Light => miniature( + &Theme::for_selection(Appearance::Light, &themes.light, accent, surface), + Corners::All, + ), + AppearanceMode::Dark => miniature( + &Theme::for_selection(Appearance::Dark, &themes.dark, accent, surface), + Corners::All, + ), } } -/// Helper copy under the picker. fn helper(mode: AppearanceMode, system: Appearance) -> SharedString { match mode { - // Naming the resolved appearance makes "System" concrete — otherwise the - // card says nothing about what you actually get right now. AppearanceMode::System => { let resolved = if system.is_dark() { "dark" } else { "light" }; format!( @@ -170,52 +387,1121 @@ fn helper(mode: AppearanceMode, system: Appearance) -> SharedString { } } -impl Render for AppearancePage { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let theme = Theme::of(cx).clone(); - let current = appearance::mode(cx); - let current_accent = appearance::accent(cx); - let system = cx - .try_global::() - .map(|state| state.system) - .unwrap_or_default(); +fn model_appearance(appearance: Appearance) -> zeron_theme::Appearance { + match appearance { + Appearance::Dark => zeron_theme::Appearance::Dark, + Appearance::Light => zeron_theme::Appearance::Light, + } +} - let cards = AppearanceMode::ALL.into_iter().map(|mode| { - widgets::option_card( - &theme, - mode.label(), - mode == current, - preview(mode, current_accent), +fn palette_preview(theme: &Theme) -> gpui::Div { + div() + .flex_none() + .w(px(30.0)) + .h(px(18.0)) + .rounded(px(5.0)) + .overflow_hidden() + .border_1() + .border_color(theme.border) + .flex() + .child(div().w_1_3().h_full().bg(theme.surface)) + .child(div().w_1_3().h_full().bg(theme.bg)) + .child(div().w_1_3().h_full().bg(theme.accent)) +} + +fn compact_action( + theme: &Theme, + label: &str, + id: impl Into, +) -> gpui::Stateful { + let id = id.into(); + popover::btn_ghost(theme, label, id.clone()).id(id) +} + +fn import_scene_preview(variant: &zeron_theme::ThemeVariant) -> AnyElement { + let theme = Theme::from_variant( + variant, + AccentSelection::ThemeDefault, + SurfacePreference::ThemeDefault, + ); + div() + .w_full() + .h(px(86.0)) + .flex() + .gap(px(8.0)) + .child( + div() + .w(px(152.0)) + .h_full() + .overflow_hidden() + .rounded(px(8.0)) + .border_1() + .border_color(theme.border) + .child(miniature(&theme, Corners::All)), + ) + .child( + div() + .flex_1() + .min_w_0() + .h_full() + .rounded(px(8.0)) + .border_1() + .border_color(theme.border) + .bg(theme.bg) + .p(px(9.0)) + .flex() + .flex_col() + .gap(px(6.0)) + .child( + div() + .text_size(px(10.0)) + .font_family(theme.font_mono.clone()) + .child( + div() + .text_color(theme.syntax.keyword) + .child("fn ") + .child(div().text_color(theme.syntax.function).child("preview")) + .child(div().text_color(theme.syntax.punctuation).child("() {")), + ), + ) + .child( + div() + .text_size(px(10.0)) + .font_family(theme.font_mono.clone()) + .text_color(theme.syntax.string) + .child(" \"Theme mapping\""), + ) + .child( + div() + .mt_auto() + .h(px(12.0)) + .flex() + .rounded(px(3.0)) + .overflow_hidden() + .children( + theme + .terminal + .ansi + .iter() + .take(8) + .map(|color| div().flex_1().h_full().bg(*color)), + ), + ), + ) + .child( + div() + .w(px(84.0)) + .h_full() + .rounded(px(8.0)) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .p(px(8.0)) + .flex() + .flex_col() + .gap(px(6.0)) + .child( + div() + .h(px(12.0)) + .rounded(px(3.0)) + .bg(theme.diff_add.opacity(0.35)), + ) + .child( + div() + .h(px(12.0)) + .rounded(px(3.0)) + .bg(theme.diff_del.opacity(0.35)), + ) + .child(div().h(px(12.0)).rounded(px(3.0)).bg(theme.accent_wash)), + ) + .into_any_element() +} + +fn report_panel(theme: &Theme, report: &ImportReport) -> gpui::Stateful { + let summary = format!( + "{} mapped · {} inferred/fallback · {} unsupported · {} warnings", + report.mappings.len(), + report.fallbacks.len(), + report.dropped.len(), + report.warnings.len() + ); + div() + .id(SharedString::from(format!( + "theme-report-{}", + report.source_hash + ))) + .mt(px(8.0)) + .w_full() + .max_h(px(168.0)) + .overflow_y_scroll() + .rounded(px(8.0)) + .border_1() + .border_color(theme.border) + .bg(theme.surface_raised.opacity(0.35)) + .p(px(10.0)) + .text_size(px(11.0)) + .line_height(px(16.0)) + .text_color(theme.text_muted) + .child(div().text_color(theme.text).child(summary)) + .children(report.fallbacks.iter().map(|message| { + div() + .mt(px(4.0)) + .child(SharedString::from(format!("Fallback · {message}"))) + })) + .children(report.warnings.iter().map(|message| { + div() + .mt(px(4.0)) + .child(SharedString::from(format!("Warning · {message}"))) + })) + .children(report.mappings.iter().take(12).map(|mapping| { + div().mt(px(4.0)).child(SharedString::from(format!( + "{} ← {}", + mapping.zeron_role, mapping.vscode_key + ))) + })) +} + +fn accent_swatch( + page_theme: &Theme, + selection: AccentSelection, + selected: bool, +) -> gpui::Stateful { + let swatch_theme = Theme::for_selection( + page_theme.appearance, + page_theme.variant_id.as_ref(), + selection, + page_theme.surface_preference, + ); + let sample = match selection { + AccentSelection::ThemeDefault => div() + .size_full() + .rounded(px(6.0)) + .bg(swatch_theme.accent_wash) + .flex() + .items_center() + .justify_center() + .gap(px(2.0)) + .child( + div() + .w(px(4.0)) + .h(px(13.0)) + .rounded(px(2.0)) + .bg(swatch_theme.glyph.light), + ) + .child( + div() + .w(px(4.0)) + .h(px(16.0)) + .rounded(px(2.0)) + .bg(swatch_theme.glyph.mid), ) - .id(SharedString::from(format!("appearance-{}", mode.label()))) - .on_click(cx.listener(move |_, _, _, cx| { - appearance::set_mode(mode, cx); + .child( + div() + .w(px(4.0)) + .h(px(11.0)) + .rounded(px(2.0)) + .bg(swatch_theme.glyph.deep), + ), + AccentSelection::Preset(_) => div().size_full().rounded(px(6.0)).bg(swatch_theme.accent), + }; + div() + .id(SharedString::from(format!("accent-{}", selection.label()))) + .flex_none() + .w(px(30.0)) + .h(px(34.0)) + .pb(px(4.0)) + .border_b_2() + .border_color(if selected { + swatch_theme.accent + } else { + gpui::transparent_black() + }) + .cursor_pointer() + .child( + div() + .size(px(30.0)) + .p(px(2.0)) + .rounded(px(8.0)) + .border_1() + .border_color(if selected { + page_theme.border_strong + } else { + page_theme.border + }) + .bg(page_theme.surface_raised.opacity(0.42)) + .child(sample), + ) +} + +impl AppearancePage { + fn theme_menu(&self, appearance: Appearance) -> &Popup<()> { + match appearance { + Appearance::Light => &self.light_theme_menu, + Appearance::Dark => &self.dark_theme_menu, + } + } + + fn theme_menu_mut(&mut self, appearance: Appearance) -> &mut Popup<()> { + match appearance { + Appearance::Light => &mut self.light_theme_menu, + Appearance::Dark => &mut self.dark_theme_menu, + } + } + + fn close_theme_menu(&mut self, appearance: Appearance, cx: &mut Context) { + if !self.theme_menu_mut(appearance).begin_close() { + return; + } + match appearance { + Appearance::Light => popover::reap_popup(cx, |page| &mut page.light_theme_menu), + Appearance::Dark => popover::reap_popup(cx, |page| &mut page.dark_theme_menu), + } + } + + fn render_theme_selector( + &mut self, + appearance_kind: Appearance, + selections: &ThemeSelection, + theme: &Theme, + cx: &mut Context, + ) -> AnyElement { + let registry = ThemeRegistry::active(); + let selected_id = selections + .variant_id(model_appearance(appearance_kind)) + .to_owned(); + let selected_variant = registry + .variant(&selected_id) + .or_else(|| { + registry + .variants_for(model_appearance(appearance_kind)) + .next() + }) + .expect("the built-in registry has both appearances"); + let selected_theme = Theme::for_selection( + appearance_kind, + &selected_variant.id, + AccentSelection::ThemeDefault, + theme.surface_preference, + ); + let open = self.theme_menu(appearance_kind).is_open(); + + let mut trigger = div() + .id(SharedString::from(format!( + "{}-theme-selector", + if appearance_kind.is_light() { + "light" + } else { + "dark" + } + ))) + .relative() + .flex_none() + .w(px(218.0)) + .h(px(34.0)) + .px(px(10.0)) + .rounded(px(8.0)) + .border_1() + .border_color(if open { + theme.border_strong + } else { + theme.border + }) + .bg(theme.surface_raised.opacity(if open { 0.75 } else { 0.42 })) + .flex() + .items_center() + .gap(px(8.0)) + .cursor_pointer() + .when(!open, |el| { + el.hover(|style| style.bg(theme.surface_raised_hover)) + }) + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(move |this, _, _, _| { + this.theme_menu_mut(appearance_kind).note_trigger_press(); + }), + ) + .on_click(cx.listener(move |this, _, _, cx| { + if this.theme_menu_mut(appearance_kind).take_press_was_open() { + this.close_theme_menu(appearance_kind, cx); + } else { + let other = if appearance_kind.is_light() { + Appearance::Dark + } else { + Appearance::Light + }; + this.close_theme_menu(other, cx); + this.theme_menu_mut(appearance_kind).open(()); + } cx.notify(); })) - }); + .child(palette_preview(&selected_theme)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(px(12.5)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(theme.text) + .child(SharedString::from(selected_variant.name.clone())), + ) + .child( + icons::icon(icons::SORT_VERTICAL) + .size(px(14.0)) + .text_color(theme.text_muted.opacity(if open { 0.9 } else { 0.45 })), + ); - let accent_swatches = AccentColor::ALL.into_iter().map(|accent| { - let swatch_theme = Theme::for_preferences(theme.appearance, accent); - let selected = accent == current_accent; + if self.theme_menu(appearance_kind).get().is_some() { + let closing = self.theme_menu(appearance_kind).closing_since(); + let heading = if appearance_kind.is_light() { + "Light themes" + } else { + "Dark themes" + }; + let menu = popover::popover_card(theme) + .w(px(260.0)) + .on_mouse_down_out(cx.listener(move |this, _, _, cx| { + this.close_theme_menu(appearance_kind, cx); + cx.notify(); + })) + .flex() + .flex_col() + .gap(px(2.0)) + .child(popover::menu_heading(theme, heading)) + .children( + registry + .variants_for(model_appearance(appearance_kind)) + .enumerate() + .map(|(index, variant)| { + let id = variant.id.clone(); + let name = variant.name.clone(); + let active = id == selected_id; + let sample = Theme::for_selection( + appearance_kind, + &id, + AccentSelection::ThemeDefault, + theme.surface_preference, + ); + popover::menu_row( + theme, + active, + SharedString::from(format!( + "appearance-theme-menu-{appearance_kind:?}-{index}" + )), + ) + .id(SharedString::from(format!( + "appearance-theme-row-{appearance_kind:?}-{index}" + ))) + .on_click(cx.listener(move |this, _, _, cx| { + appearance::set_theme(appearance_kind, id.clone(), cx); + this.close_theme_menu(appearance_kind, cx); + cx.notify(); + })) + .child(palette_preview(&sample)) + .child(div().flex_1().min_w_0().truncate().child(name)) + .when(active, |row| { + row.child( + icons::icon(icons::CHECK) + .size(px(14.0)) + .text_color(theme.accent), + ) + }) + }), + ) + .into_any_element(); + trigger = trigger.child(popover::anchored_menu_below( + SharedString::from(format!( + "appearance-{}-theme-menu", + if appearance_kind.is_light() { + "light" + } else { + "dark" + } + )), + menu, + closing, + )); + } + + trigger.into_any_element() + } + + fn render_import_dialog( + &mut self, + viewport: gpui::Size, + theme: &Theme, + cx: &mut Context, + ) -> Option { + let dialog = self.import_dialog.as_ref()?; + let input = dialog.input.clone(); + let mode = dialog.mode; + let compilation = dialog.compilation.clone(); + let selected = dialog.selected.clone(); + let review_variant = dialog.review_variant.clone(); + let error = dialog.error.clone(); + + let mode_control = |label: &'static str, value: InstallMode| { + let active = mode == value; div() - .id(SharedString::from(format!("accent-{}", accent.label()))) - .flex_none() - .w(px(28.0)) - .h(px(32.0)) - .pb(px(4.0)) - .border_b_2() - .border_color(if selected { - swatch_theme.accent + .id(SharedString::from(format!( + "theme-import-mode-{}", + slug(label) + ))) + .px(px(10.0)) + .py(px(6.0)) + .rounded(px(7.0)) + .border_1() + .border_color(if active { theme.accent } else { theme.border }) + .bg(if active { + theme.accent_wash + } else { + theme.surface_raised.opacity(0.35) + }) + .text_size(px(12.0)) + .text_color(if active { + theme.accent } else { - theme.border + theme.text_muted }) .cursor_pointer() + .on_click(cx.listener(move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + dialog.mode = value; + } + cx.notify(); + })) + .child(label) + }; + + let mut card = popover::dialog_card(theme) + .id("theme-import-card") + .w(px(660.0)) + .max_h(px(720.0)) + .overflow_y_scroll() + .child(popover::dialog_title(theme, "Add a custom theme")); + + if let Some(ref compilation) = compilation { + card = card + .child( + popover::dialog_body( + theme, + format!( + "{} detected · Choose the variants to keep. Runtime components use the resolved Zeron palette, never VS Code token names.", + compilation.family.name + ), + ) + .mt(px(6.0)), + ) + .child( + div() + .mt(px(12.0)) + .flex() + .gap(px(8.0)) + .child(mode_control("Import snapshot", InstallMode::Snapshot)) + .child(mode_control("Link source", InstallMode::Link)), + ); + for variant in &compilation.family.variants { + let variant_id = variant.id.clone(); + let selected_now = selected.contains(&variant_id); + let review_open = review_variant.as_deref() == Some(variant_id.as_str()); + let appearance = if variant.appearance.is_dark() { + "Dark" + } else { + "Light" + }; + let report = compilation.reports.get(&variant.id); + card = card.child( + div() + .mt(px(10.0)) + .rounded(px(10.0)) + .border_1() + .border_color(if selected_now { + theme.border_strong + } else { + theme.border + }) + .bg(theme.surface_raised.opacity(0.28)) + .p(px(10.0)) + .child( + div() + .flex() + .items_center() + .gap(px(8.0)) + .child( + div() + .id(SharedString::from(format!( + "theme-import-select-{variant_id}" + ))) + .size(px(18.0)) + .rounded(px(5.0)) + .border_1() + .border_color(if selected_now { + theme.accent + } else { + theme.border_strong + }) + .bg(if selected_now { theme.accent } else { theme.bg }) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(selected_now, |item| { + item.child( + icons::icon(icons::CHECK) + .size(px(12.0)) + .text_color(theme.on_accent), + ) + }) + .on_click(cx.listener({ + let variant_id = variant_id.clone(); + move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + if !dialog.selected.remove(&variant_id) { + dialog.selected.insert(variant_id.clone()); + } + } + cx.notify(); + } + })), + ) + .child( + div() + .flex_1() + .min_w_0() + .child( + div() + .text_size(px(12.5)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(theme.text) + .child(SharedString::from(variant.name.clone())), + ) + .child( + div() + .text_size(px(11.0)) + .text_color(theme.text_muted) + .child(appearance), + ), + ) + .child( + compact_action( + theme, + if review_open { + "Hide mapping" + } else { + "Review mapping" + }, + format!("theme-import-review-{variant_id}"), + ) + .on_click(cx.listener({ + let variant_id = variant_id.clone(); + move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + dialog.review_variant = + if dialog.review_variant.as_deref() + == Some(variant_id.as_str()) + { + None + } else { + Some(variant_id.clone()) + }; + } + cx.notify(); + } + })), + ), + ) + .when(review_open, |row| { + row.child(import_scene_preview(variant)) + .when_some(report, |row, report| { + row.child(report_panel(theme, report)) + }) + }), + ); + } + for failure in &compilation.failures { + card = card.child( + div() + .mt(px(8.0)) + .text_size(px(11.0)) + .text_color(theme.warning) + .child(SharedString::from(format!( + "{} could not be compiled · {}", + failure.name, failure.message + ))), + ); + } + } else { + card = card + .child( + popover::dialog_body( + theme, + "Paste a VS Code theme JSON/JSONC file, package.json, or extension folder. Zeron detects variants and appearance automatically.", + ) + .mt(px(6.0)), + ) + .child( + div() + .mt(px(14.0)) + .flex() + .items_center() + .gap(px(8.0)) + .child( + popover::dialog_field(input.into_any_element()) + .flex_1() + .min_w_0(), + ) + .child( + compact_action(theme, "Choose…", "theme-import-choose") + .on_click(cx.listener(|this, _, _, cx| { + this.choose_import_source(cx) + })), + ), + ) + .child( + div() + .mt(px(10.0)) + .flex() + .gap(px(8.0)) + .child(mode_control("Import snapshot", InstallMode::Snapshot)) + .child(mode_control("Link source", InstallMode::Link)), + ); + } + + if let Some(error) = error { + card = card.child( + div() + .mt(px(10.0)) + .text_size(px(11.5)) + .text_color(theme.danger) + .child(error), + ); + } + + let ready = compilation.is_some() && !selected.is_empty(); + card = card.child( + div() + .mt(px(16.0)) + .flex() + .justify_end() + .gap(px(8.0)) + .child( + popover::btn_ghost(theme, "Cancel", "theme-import-cancel") + .id("theme-import-cancel") + .on_click(cx.listener(|this, _, _, cx| { + this.import_dialog = None; + cx.notify(); + })), + ) + .when(compilation.is_none(), |actions| { + actions.child( + popover::btn_primary(theme, "Analyze source") + .id("theme-import-analyze") + .on_click(cx.listener(|this, _, _, cx| this.compile_import(cx))), + ) + }) + .when(compilation.is_some(), |actions| { + actions.child( + popover::btn_primary(theme, "Import selected") + .id("theme-import-finish") + .opacity(if ready { 1.0 } else { 0.45 }) + .when(ready, |button| { + button + .on_click(cx.listener(|this, _, _, cx| this.finish_import(cx))) + }), + ) + }), + ); + Some(popover::modal( + "theme-import-dialog", + viewport, + card.into_any_element(), + )) + } + + fn render_review_dialog( + &mut self, + viewport: gpui::Size, + theme: &Theme, + cx: &mut Context, + ) -> Option { + let entry_id = self.review_entry.as_ref()?; + let entry = theme_library::entries(cx) + .into_iter() + .find(|entry| &entry.id == entry_id)?; + let mut card = popover::dialog_card(theme) + .id("theme-review-card") + .w(px(660.0)) + .max_h(px(720.0)) + .overflow_y_scroll() + .child(popover::dialog_title(theme, "Theme mapping")) + .child( + popover::dialog_body(theme, format!("{} · {}", entry.name, entry.source.label())) + .mt(px(6.0)), + ); + for variant in &entry.family.variants { + card = card + .child( + div() + .mt(px(14.0)) + .text_size(px(12.5)) + .font_weight(gpui::FontWeight::MEDIUM) + .child(SharedString::from(variant.name.clone())), + ) + .child(import_scene_preview(variant)); + if let Some(report) = entry.reports.get(&variant.id) { + card = card.child(report_panel(theme, report)); + } + } + card = card.child( + div().mt(px(16.0)).flex().justify_end().child( + popover::btn_primary(theme, "Done") + .id("theme-review-close") + .on_click(cx.listener(|this, _, _, cx| { + this.review_entry = None; + cx.notify(); + })), + ), + ); + Some(popover::modal( + "theme-review-dialog", + viewport, + card.into_any_element(), + )) + } + + fn render_library_entry( + &mut self, + entry: CustomThemeEntry, + theme: &Theme, + cx: &mut Context, + ) -> AnyElement { + let id = entry.id.clone(); + let linked = entry.source.is_linked(); + let source = entry + .source + .path() + .map(|path| path.display().to_string()) + .unwrap_or_else(|| "Self-contained snapshot".into()); + let status = match &entry.status { + CustomThemeStatus::Ready => format!( + "{} · {} variant{} · {}", + entry.source.label(), + entry.family.variants.len(), + if entry.family.variants.len() == 1 { + "" + } else { + "s" + }, + source + ), + CustomThemeStatus::Warning { message } => { + format!("Using last known good · {message}") + } + }; + widgets::card_row(theme, false) + .child(widgets::row_tile( + theme, + if linked { + icons::GLOBAL + } else { + icons::DOCUMENT + }, + )) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(theme, &entry.name)) + .child( + div() + .truncate() + .text_size(px(11.0)) + .text_color( + if matches!(entry.status, CustomThemeStatus::Warning { .. }) { + theme.warning + } else { + theme.text_muted + }, + ) + .child(SharedString::from(status)), + ), + ) + .child( + div() + .flex_none() + .flex() + .items_center() + .gap(px(2.0)) + .when(linked, |actions| { + actions.child( + compact_action(theme, "Reload", format!("theme-reload-{id}")).on_click( + cx.listener({ + let id = id.clone(); + move |_, _, _, cx| { + let _ = theme_library::reload(&id, cx); + cx.notify(); + } + }), + ), + ) + }) + .child( + compact_action(theme, "Reveal", format!("theme-reveal-{id}")).on_click( + cx.listener({ + let id = id.clone(); + move |this, _, _, cx| { + if let Err(error) = theme_library::reveal(&id, cx) { + this.library_error = Some(error.to_string().into()); + } + cx.notify(); + } + }), + ), + ) + .child( + compact_action(theme, "Review", format!("theme-review-{id}")).on_click( + cx.listener({ + let id = id.clone(); + move |this, _, _, cx| { + this.review_entry = Some(id.clone()); + cx.notify(); + } + }), + ), + ) + .child( + compact_action(theme, "Duplicate", format!("theme-duplicate-{id}")) + .on_click(cx.listener({ + let id = id.clone(); + move |this, _, _, cx| { + if let Err(error) = + theme_library::duplicate_as_snapshot(&id, cx) + { + this.library_error = Some(error.to_string().into()); + } + cx.notify(); + } + })), + ) + .when(linked, |actions| { + actions.child( + compact_action(theme, "Unlink", format!("theme-unlink-{id}")).on_click( + cx.listener({ + let id = id.clone(); + move |this, _, _, cx| { + if let Err(error) = theme_library::unlink(&id, cx) { + this.library_error = Some(error.to_string().into()); + } + cx.notify(); + } + }), + ), + ) + }) + .child( + compact_action(theme, "Remove", format!("theme-remove-{id}")) + .text_color(theme.danger) + .on_click(cx.listener(move |this, _, _, cx| { + if let Err(error) = theme_library::remove(&id, cx) { + this.library_error = Some(error.to_string().into()); + } + cx.notify(); + })), + ), + ) + .into_any_element() + } + + fn render_theme_library(&mut self, theme: &Theme, cx: &mut Context) -> AnyElement { + let entries = theme_library::entries(cx); + let (linked, imported): (Vec<_>, Vec<_>) = entries + .into_iter() + .partition(|entry| entry.source.is_linked()); + let builtins = ThemeRegistry::builtin().families.len(); + let mut rows = vec![ + widgets::card_row(theme, true) + .child(widgets::row_tile(theme, icons::FOLDER_WITH_FILES)) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(theme, "Theme library")) + .child(widgets::meta_line( + theme, + vec![ + div() + .child("Built-in, imported, and linked theme families.") + .into_any_element(), + ], + )), + ) + .child( + popover::btn_primary(theme, "Add theme") + .id("theme-library-add") + .on_click(cx.listener(|this, _, _, cx| this.open_import(cx))), + ) + .into_any_element(), + widgets::card_row(theme, false) + .child(widgets::row_tile(theme, icons::ZERON_LOGO)) + .child( + div() + .flex_1() + .child(widgets::row_title(theme, "Built-in")) + .child(widgets::meta_line( + theme, + vec![ + div() + .child(SharedString::from(format!( + "{builtins} curated families · Updated with Zeron." + ))) + .into_any_element(), + ], + )), + ) + .into_any_element(), + ]; + if !imported.is_empty() { + rows.push( + div() + .px(px(16.0)) + .pt(px(12.0)) + .pb(px(4.0)) + .border_t_1() + .border_color(theme.border) + .text_size(px(10.5)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(theme.text_faint) + .child("IMPORTED") + .into_any_element(), + ); + rows.extend( + imported + .into_iter() + .map(|entry| self.render_library_entry(entry, theme, cx)), + ); + } + if !linked.is_empty() { + rows.push( + div() + .px(px(16.0)) + .pt(px(12.0)) + .pb(px(4.0)) + .border_t_1() + .border_color(theme.border) + .text_size(px(10.5)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(theme.text_faint) + .child("LINKED") + .into_any_element(), + ); + rows.extend( + linked + .into_iter() + .map(|entry| self.render_library_entry(entry, theme, cx)), + ); + } + widgets::section_card(theme) + .children(rows) + .into_any_element() + } +} + +impl Render for AppearancePage { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = Theme::of(cx).clone(); + let current_mode = appearance::mode(cx); + let current_themes = appearance::themes(cx); + let current_accent = appearance::accent(cx); + let current_surface = appearance::surface(cx); + let system = cx + .try_global::() + .map(|state| state.system) + .unwrap_or_default(); + + let cards = AppearanceMode::ALL + .into_iter() + .map(|mode| { + widgets::option_card( + &theme, + mode.label(), + mode == current_mode, + preview(mode, ¤t_themes, current_accent, current_surface), + ) + .id(SharedString::from(format!("appearance-{}", mode.label()))) .on_click(cx.listener(move |_, _, _, cx| { - appearance::set_accent(accent, cx); + appearance::set_mode(mode, cx); cx.notify(); })) - .child(div().size_full().rounded(px(5.0)).bg(swatch_theme.accent)) - }); + }) + .collect::>(); + + let mut theme_rows = Vec::new(); + for (index, appearance_kind) in [Appearance::Light, Appearance::Dark] + .into_iter() + .enumerate() + { + let label = if appearance_kind.is_light() { + "Light theme" + } else { + "Dark theme" + }; + let selector = self.render_theme_selector(appearance_kind, ¤t_themes, &theme, cx); + theme_rows.push( + widgets::card_row(&theme, index == 0) + .child(widgets::row_tile(&theme, icons::TUNING)) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(&theme, label)) + .child(widgets::meta_line( + &theme, + vec![ + div() + .child(SharedString::from( + "Used whenever this appearance is active.", + )) + .into_any_element(), + ], + )), + ) + .child(selector), + ); + } + + let mut accent_choices = vec![AccentSelection::ThemeDefault]; + accent_choices.extend(AccentPreset::ALL.map(AccentSelection::Preset)); + let accent_controls = accent_choices + .into_iter() + .map(|selection| { + let selected = selection == current_accent; + accent_swatch(&theme, selection, selected).on_click(cx.listener( + move |_, _, _, cx| { + appearance::set_accent(selection, cx); + cx.notify(); + }, + )) + }) + .collect::>(); + let surface_controls = SurfacePreference::ALL + .into_iter() + .map(|surface| { + surface_choice(&theme, surface, surface == current_surface).on_click(cx.listener( + move |_, _, _, cx| { + appearance::set_surface(surface, cx); + cx.notify(); + }, + )) + }) + .collect::>(); + let library = self.render_theme_library(&theme, cx); + let library_warning = self + .library_error + .clone() + .or_else(|| theme_library::load_warning(cx).map(SharedString::from)); + let modal = self + .render_import_dialog(window.viewport_size(), &theme, cx) + .or_else(|| self.render_review_dialog(window.viewport_size(), &theme, cx)); div() .id("appearance-page") @@ -238,7 +1524,7 @@ impl Render for AppearancePage { .flex() .flex_col() .gap(px(12.0)) - .child(widgets::field_label(&theme, "Theme")) + .child(widgets::field_label(&theme, "Appearance")) .child(widgets::option_card_row().children(cards)), ) .child( @@ -247,47 +1533,83 @@ impl Render for AppearancePage { .text_size(px(12.0)) .text_color(theme.text_muted) .line_height(px(18.0)) - .child(helper(current, system)), + .child(helper(current_mode, system)), ) + .child(widgets::section_card(&theme).children(theme_rows)) .child( - widgets::section_card(&theme).child( - widgets::card_row(&theme, true) - .child(widgets::row_tile(&theme, icons::TUNING)) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .flex() - .flex_col() - .child(widgets::row_title(&theme, "Accent color")) - .child(widgets::meta_line( - &theme, - vec![ - div() - .w_full() - .min_w_0() - .truncate() - .child(SharedString::from(accent_helper( - current_accent, - ))) - .into_any_element(), - ], - )), - ) - .child( - div() - .flex_none() - .ml(px(24.0)) - .flex() - .flex_row() - .items_center() - .gap(px(6.0)) - .children(accent_swatches), - ), - ), - ), + widgets::section_card(&theme) + .child( + widgets::card_row(&theme, true) + .child(widgets::row_tile(&theme, icons::TUNING)) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(&theme, "Accent color")) + .child(widgets::meta_line( + &theme, + vec![ + div() + .child(SharedString::from(accent_helper( + current_accent, + ))) + .into_any_element(), + ], + )), + ) + .child( + div() + .flex_none() + .ml(px(10.0)) + .flex() + .items_center() + .gap(px(6.0)) + .children(accent_controls), + ), + ) + .child( + widgets::card_row(&theme, false) + .child(widgets::row_tile(&theme, icons::WIDGET)) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(&theme, "Glass")) + .child(widgets::meta_line( + &theme, + vec![ + div() + .child(SharedString::from(surface_helper( + current_surface, + theme.surface_treatment, + ))) + .into_any_element(), + ], + )), + ) + .child( + div() + .flex_none() + .ml(px(10.0)) + .flex() + .items_center() + .gap(px(6.0)) + .children(surface_controls), + ), + ), + ) + .child(library) + .when_some(library_warning, |page, warning| { + page.child( + div() + .mt(px(8.0)) + .text_size(px(11.5)) + .text_color(theme.warning) + .child(warning), + ) + }), ) + .children(modal) } } @@ -304,24 +1626,39 @@ mod tests { } #[test] - fn accent_choices_form_a_labeled_palette() { - assert_eq!(AccentColor::default(), AccentColor::Zeron); - assert_eq!(AccentColor::ALL.len(), 7); - for accent in AccentColor::ALL { - assert!(!accent.label().is_empty()); - assert!(!matches!(accent.label(), "Red" | "Purple")); - } + fn registry_offers_both_appearances_and_keeps_single_dark_families_valid() { + let registry = ThemeRegistry::builtin(); + assert_eq!( + registry + .variants_for(zeron_theme::Appearance::Light) + .count(), + 10 + ); + assert_eq!( + registry.variants_for(zeron_theme::Appearance::Dark).count(), + 20 + ); } #[test] - fn accent_helper_describes_the_palette_roles_concisely() { - let copy = accent_helper(AccentColor::Pink); + fn accent_helper_explains_default_and_override_scope() { + assert!(accent_helper(AccentSelection::ThemeDefault).contains("intended")); + let copy = accent_helper(AccentSelection::Preset(AccentPreset::Pink)); assert!(copy.starts_with("Pink ·")); assert!(copy.contains("glyphs")); - assert!(!copy.contains("Sidebar stays")); + } + + #[test] + fn surface_helper_explains_theme_default_and_global_overrides() { + let default = surface_helper(SurfacePreference::ThemeDefault, SurfaceTreatment::Opaque); + assert!(default.contains("theme recommends opaque")); + assert!( + surface_helper(SurfacePreference::Frosted, SurfaceTreatment::Opaque) + .contains("wherever the platform supports blur") + ); assert!( - copy.len() < 64, - "copy is too long for the settings row: {copy}" + surface_helper(SurfacePreference::Opaque, SurfaceTreatment::Frosted) + .contains("across every theme") ); } @@ -333,8 +1670,6 @@ mod tests { assert!(light.contains("currently light"), "got {light}"); } - /// The pinned modes must not claim to follow anything — that copy is the only - /// thing telling the user the system setting is being ignored. #[test] fn pinned_helpers_do_not_mention_following() { for mode in [AppearanceMode::Light, AppearanceMode::Dark] { @@ -345,14 +1680,4 @@ mod tests { } } } - - /// The previews must differ from each other, or the picker is decoration. - /// Comparing the tones they are built from is the closest we can get without - /// a renderer. - #[test] - fn light_and_dark_previews_draw_from_different_palettes() { - let (l, d) = (Theme::light(), Theme::dark()); - assert_ne!(l.surface.l, d.surface.l); - assert_ne!(l.bg.l, d.bg.l); - } } diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 4add3814b0..313c844240 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -1389,8 +1389,7 @@ impl Shell { self.debug_upload = None; if let Some((pct, img_path)) = spec.split_once(':') && let Ok(pct) = pct.parse::() - && let Ok(att) = - crate::attachments::stage_file(std::path::Path::new(img_path)) + && let Ok(att) = crate::attachments::stage_file(std::path::Path::new(img_path)) { let pending_path = format!("pending/{}/{}", att.id, att.name); let device_ids: Vec = { @@ -3563,8 +3562,10 @@ impl Shell { } fn render_sidebar(&mut self, cx: &mut Context) -> AnyElement { - let installed_theme = Theme::of(cx); - let theme = Theme::sidebar(installed_theme.appearance, installed_theme.accent_color); + // The sidebar is part of the resolved theme. A second fixed-Zeron + // palette here made imported families look split in half and froze + // activity/glyph personality independently of the selected variant. + let theme = Theme::of(cx).clone(); let inner: AnyElement = match self.route { Route::Settings(section) => self.render_settings_nav(section, &theme, cx), Route::Chat => self.render_chat_sidebar(&theme, cx), @@ -7195,7 +7196,9 @@ impl Render for Shell { // Appearance actions persist independently of the shell. Mirror the // globals before any later debounced settings save can overwrite them. self.settings.appearance = crate::appearance::mode(cx); - self.settings.accent_color = crate::appearance::accent(cx); + self.settings.theme_selection = crate::appearance::themes(cx); + self.settings.accent = crate::appearance::accent(cx); + self.settings.surface = crate::appearance::surface(cx); let theme = Theme::of(cx); // The shell tone (zeron `.frost`): the surface the sidebar sits on and // the main panel floats over as an inset rounded card. On macOS the diff --git a/crates/ui/src/terminal/view.rs b/crates/ui/src/terminal/view.rs index 7d853280df..5e1b96b658 100644 --- a/crates/ui/src/terminal/view.rs +++ b/crates/ui/src/terminal/view.rs @@ -1,8 +1,6 @@ //! Terminal paint + input encoding. //! -//! - the ANSI palette on the terminal background (feature-inventory §1.10) — -//! `#090909` dark, `#fafafa` light — and the 256-color cube/grayscale -//! resolution, both resolved per [`Appearance`]; +//! - theme-owned background/ANSI16 plus the xterm 256-color cube/grayscale; //! - keystroke → PTY byte encoding (printables, control keys, arrows/nav //! escape sequences, Ctrl- combos, Alt prefixing); //! - the 12 ms input coalescer and the 80 ms resize debounce constants (the @@ -18,7 +16,7 @@ use gpui::{ SharedString, Style, TextRun, Window, fill, font, outline, point, px, relative, size, }; -use crate::theme::{Appearance, Theme, current_appearance, rgb_to_hsl}; +use crate::theme::{Appearance, Theme, rgb_to_hsl}; use super::emulator::{CellColor, CellSnapshot, Side}; use super::panel::TerminalPanel; @@ -38,28 +36,6 @@ pub const RESIZE_DEBOUNCE_MS: u64 = 80; // Palette // --------------------------------------------------------------------------- -/// Terminal background for an appearance. -/// -/// Dark is `#090909`, one small step *up* from the app's `#060606` content -/// plane — the terminal reads as its own pane without becoming a lighter box. -/// Light mirrors that relationship rather than inverting the literal value: -/// the content plane is already pure white, so the terminal steps one notch -/// *down* to `#fafafa`. The step is bigger than dark's 3/255 for the reason the -/// theme's light surfaces are (`Theme::light`): a near-white delta that reads -/// as separation on near-black disappears entirely on white. -pub fn terminal_bg_for(appearance: Appearance) -> Hsla { - match appearance { - Appearance::Dark => rgb8(0x09, 0x09, 0x09), - Appearance::Light => rgb8(0xfa, 0xfa, 0xfa), - } -} - -/// Terminal background in the appearance currently installed — the -/// context-free form, same shape as [`crate::theme::ink`]. -pub fn terminal_bg() -> Hsla { - terminal_bg_for(current_appearance()) -} - /// The panel fill behind the grid. On glass the opaque tone thins to a /// translucent wash so the blurred desktop reads through like the rest of the /// chrome (same move as [`Theme::card_glass_bg`]); opaque platforms keep the @@ -67,86 +43,12 @@ pub fn terminal_bg() -> Hsla { /// their own opaque quads on top. pub fn terminal_panel_bg(theme: &Theme) -> Hsla { if theme.is_glass() { - terminal_bg_for(theme.appearance).opacity(0.4) + theme.terminal.background.opacity(0.4) } else { - terminal_bg_for(theme.appearance) + theme.terminal.background } } -/// Selection wash over the grid. -/// -/// Deliberately *achromatic*, which is where this differs from -/// [`Theme::selection`] — the composer's blue. A saturated wash sits on top of -/// sixteen ANSI hues and drags every one of them toward itself: red text under -/// blue reads purple, green reads teal. A neutral veil changes lightness only, -/// so selected output keeps the colors the program asked for — the whole point -/// of tuning those palettes per appearance in the first place. -/// -/// White on dark, black on light, the same direction [`crate::theme::ink`] -/// takes. The alpha is heavier than a hover wash because this has to read as a -/// deliberate highlight at a glance, and lighter than a plate because the -/// glyphs underneath still have to be legible through it. -pub fn terminal_selection_for(appearance: Appearance) -> Hsla { - match appearance { - Appearance::Dark => gpui::hsla(0.0, 0.0, 1.0, 0.22), - // Slightly heavier: an equal alpha of black on near-white reads fainter - // than white on near-black, because the surround is brighter to begin - // with. - Appearance::Light => gpui::hsla(0.0, 0.0, 0.0, 0.16), - } -} - -/// The 16 ANSI colors tuned for the near-black background (indexes 0-7 normal, -/// 8-15 bright). -const ANSI16_DARK: [(u8, u8, u8); 16] = [ - (0x24, 0x24, 0x24), // black — visible against #090909 - (0xf8, 0x71, 0x71), // red - (0x4a, 0xde, 0x80), // green - (0xfa, 0xcc, 0x15), // yellow - (0x60, 0xa5, 0xfa), // blue - (0xc0, 0x84, 0xfc), // magenta - (0x22, 0xd3, 0xee), // cyan - (0xd4, 0xd4, 0xd8), // white - (0x52, 0x52, 0x5b), // bright black - (0xfc, 0xa5, 0xa5), // bright red - (0x86, 0xef, 0xac), // bright green - (0xfd, 0xe0, 0x47), // bright yellow - (0x93, 0xc5, 0xfd), // bright blue - (0xd8, 0xb4, 0xfe), // bright magenta - (0x67, 0xe8, 0xf9), // bright cyan - (0xfa, 0xfa, 0xfa), // bright white -]; - -/// The same 16 slots for the light background — same hue families as -/// [`ANSI16_DARK`], moved down the tonal scale (the 400/300 steps the dark -/// table uses fail on white; these are the 600/700 steps, the same swap -/// `Theme::light` makes for its accents). -/// -/// "Bright" stays *more prominent*, which on a light field means **darker**, -/// not lighter — a literal translation of the dark table would make the bright -/// half the invisible half, which is the bug this fixes in its purest form. -const ANSI16_LIGHT: [(u8, u8, u8); 16] = [ - (0x1f, 0x1f, 0x1f), // black - (0xdc, 0x26, 0x26), // red — red-600 - (0x16, 0xa3, 0x4a), // green — green-600 - // Amber-700, not yellow-600: yellow is the one hue whose 600 step is still - // bright enough to fail AA on white (2.8:1). `Theme::light` drops its - // `warning` token to the same step for the same reason. - (0xb4, 0x53, 0x09), // yellow — amber-700 - (0x25, 0x63, 0xeb), // blue — blue-600 - (0x93, 0x33, 0xea), // magenta — purple-600 - (0x0e, 0x74, 0x90), // cyan — cyan-700 (600 is too pale on white) - (0x3f, 0x3f, 0x46), // white — the body-text tone, zinc-700 - (0x71, 0x71, 0x7a), // bright black — zinc-500 - (0xb9, 0x1c, 0x1c), // bright red — red-700 - (0x15, 0x80, 0x3d), // bright green — green-700 - (0x92, 0x40, 0x0e), // bright yellow — amber-800 - (0x1d, 0x4e, 0xd8), // bright blue — blue-700 - (0x7e, 0x22, 0xce), // bright magenta — purple-700 - (0x15, 0x5e, 0x75), // bright cyan — cyan-800 - (0x18, 0x18, 0x1b), // bright white — max emphasis, zinc-900 -]; - fn rgb8(r: u8, g: u8, b: u8) -> Hsla { let (h, s, l) = rgb_to_hsl(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0); gpui::hsla(h, s, l, 1.0) @@ -155,12 +57,11 @@ fn rgb8(r: u8, g: u8, b: u8) -> Hsla { /// xterm 256-color cube component levels. const CUBE_LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255]; -/// Resolve an indexed color (0-255) to RGB components for an appearance. +/// Resolve the xterm extended-color range to RGB components. /// /// Three ranges, treated differently on purpose: /// -/// - **0-15** are *named* slots ("red", "bright blue"), not literal values — -/// every terminal emulator re-tints them per theme, so they swap tables. +/// - **0-15** are named slots and are resolved directly from `Theme::terminal`. /// - **16-231** is the 6×6×6 cube: a program asking for index 196 is asking for /// `#ff0000` by arithmetic, and remapping it would be inventing colors the /// caller did not pick. Left alone in both appearances, same as iTerm/Apple @@ -171,12 +72,9 @@ const CUBE_LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255]; /// stays the faintest and 255 the strongest in both. Without this the ramp is /// the single biggest legibility hole on white, because its bright end — /// where most "dim hint" text lands — is the end that vanishes. -pub fn indexed_rgb(appearance: Appearance, index: u8) -> (u8, u8, u8) { +fn extended_indexed_rgb(appearance: Appearance, index: u8) -> (u8, u8, u8) { match index { - 0..=15 => match appearance { - Appearance::Dark => ANSI16_DARK[index as usize], - Appearance::Light => ANSI16_LIGHT[index as usize], - }, + 0..=15 => unreachable!("ANSI16 is resolved from the active theme"), 16..=231 => { let n = index as usize - 16; ( @@ -200,10 +98,11 @@ pub fn indexed_rgb(appearance: Appearance, index: u8) -> (u8, u8, u8) { /// Resolve a cell color to paint against the theme. pub fn resolve_color(color: CellColor, theme: &Theme) -> Hsla { match color { - CellColor::Foreground => theme.text, - CellColor::Background => terminal_bg_for(theme.appearance), + CellColor::Foreground => theme.terminal.foreground, + CellColor::Background => theme.terminal.background, + CellColor::Indexed(ix @ 0..=15) => theme.terminal.ansi[ix as usize], CellColor::Indexed(ix) => { - let (r, g, b) = indexed_rgb(theme.appearance, ix); + let (r, g, b) = extended_indexed_rgb(theme.appearance, ix); rgb8(r, g, b) } CellColor::Rgb(r, g, b) => rgb8(r, g, b), @@ -601,7 +500,7 @@ impl gpui::Element for TerminalElement { point(origin.x + cell_w * start as f32, y), size(cell_w * (col - start) as f32, line_h), ), - terminal_selection_for(theme.appearance), + theme.terminal.selection, )); sel_start = None; } @@ -1019,132 +918,84 @@ mod tests { assert!(!c.push(b"")); } - /// Relative luminance, for contrast assertions (WCAG 2.x definition). - fn luminance(r: u8, g: u8, b: u8) -> f32 { - let f = |c: u8| { - let c = c as f32 / 255.0; - if c <= 0.03928 { - c / 12.92 - } else { - ((c + 0.055) / 1.055).powf(2.4) - } - }; - 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b) - } - - fn contrast(a: (u8, u8, u8), b: (u8, u8, u8)) -> f32 { - let (la, lb) = (luminance(a.0, a.1, a.2), luminance(b.0, b.1, b.2)); - let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) }; - (hi + 0.05) / (lo + 0.05) - } - #[test] fn cube_is_appearance_independent() { for appearance in [Appearance::Dark, Appearance::Light] { // 16 = cube origin (0,0,0); 231 = cube max (255,255,255). - assert_eq!(indexed_rgb(appearance, 16), (0, 0, 0)); - assert_eq!(indexed_rgb(appearance, 231), (255, 255, 255)); + assert_eq!(extended_indexed_rgb(appearance, 16), (0, 0, 0)); + assert_eq!(extended_indexed_rgb(appearance, 231), (255, 255, 255)); // 196 = pure red corner: 16 + 36*5. - assert_eq!(indexed_rgb(appearance, 196), (255, 0, 0)); + assert_eq!(extended_indexed_rgb(appearance, 196), (255, 0, 0)); // 21 = pure blue corner. - assert_eq!(indexed_rgb(appearance, 21), (0, 0, 255)); + assert_eq!(extended_indexed_rgb(appearance, 21), (0, 0, 255)); } } #[test] fn grayscale_ramp_mirrors_in_light() { // Dark: 232 → 8 (faintest), 255 → 238 (strongest). - assert_eq!(indexed_rgb(Appearance::Dark, 232), (8, 8, 8)); - assert_eq!(indexed_rgb(Appearance::Dark, 255), (238, 238, 238)); + assert_eq!(extended_indexed_rgb(Appearance::Dark, 232), (8, 8, 8)); + assert_eq!(extended_indexed_rgb(Appearance::Dark, 255), (238, 238, 238)); // Light reverses it so the faint end stays faint against white. - assert_eq!(indexed_rgb(Appearance::Light, 232), (238, 238, 238)); - assert_eq!(indexed_rgb(Appearance::Light, 255), (8, 8, 8)); - } - - #[test] - fn ansi_range_hits_the_appearance_table() { - assert_eq!(indexed_rgb(Appearance::Dark, 1), ANSI16_DARK[1]); - assert_eq!(indexed_rgb(Appearance::Light, 1), ANSI16_LIGHT[1]); - assert_ne!(ANSI16_DARK, ANSI16_LIGHT); + assert_eq!( + extended_indexed_rgb(Appearance::Light, 232), + (238, 238, 238) + ); + assert_eq!(extended_indexed_rgb(Appearance::Light, 255), (8, 8, 8)); } #[test] - fn terminal_bg_tracks_the_appearance() { - let dark = terminal_bg_for(Appearance::Dark); - assert_eq!(dark.s, 0.0); - assert!((dark.l - 9.0 / 255.0).abs() < 1e-4); - - let light = terminal_bg_for(Appearance::Light); - assert_eq!(light.s, 0.0); - assert!((light.l - 250.0 / 255.0).abs() < 1e-4); + fn registered_theme_owns_terminal_background_foreground_selection_and_ansi() { + let theme = Theme::for_selection( + Appearance::Dark, + "dracula", + zeron_theme::AccentSelection::ThemeDefault, + zeron_theme::SurfacePreference::ThemeDefault, + ); + assert_eq!(terminal_panel_bg(&theme), theme.terminal.background); + assert_eq!( + resolve_color(CellColor::Foreground, &theme), + theme.terminal.foreground + ); + assert_eq!( + resolve_color(CellColor::Background, &theme), + theme.terminal.background + ); + assert_eq!( + resolve_color(CellColor::Indexed(1), &theme), + theme.terminal.ansi[1] + ); + assert!(theme.terminal.selection.a > 0.0 && theme.terminal.selection.a < 0.5); } - /// Slot 0 is "black" — the one slot whose job is to sit *at* the dark end - /// of the scale, not to be readable text. It draws box edges and shaded - /// blocks, so it gets the grey floor below rather than the text floor. - const ANSI_BLACK: usize = 0; - - /// The regression this module's light table exists to prevent: every ANSI - /// slot has to be readable on its *own* background. The dark table on the - /// light background is what the bug looked like. - /// - /// Two floors, because the table holds two kinds of thing. The twelve - /// chromatic slots carry text and clear AA for the 13px mono the grid - /// paints at. The black/bright-black pair are structural greys — box - /// drawing and dim hints — and the *dark* palette, which shipped tuned by - /// eye and is not what this change touches, puts bright-black at 2.58:1. - /// Holding them to the text floor would fail the palette that was already - /// correct, so they only have to separate from the background. #[test] - fn every_ansi_slot_is_legible_on_its_background() { - const MIN_TEXT: f32 = 3.0; - const MIN_GREY: f32 = 1.25; - let cases = [ - (Appearance::Dark, ANSI16_DARK, (0x09, 0x09, 0x09)), - (Appearance::Light, ANSI16_LIGHT, (0xfa, 0xfa, 0xfa)), - ]; - for (appearance, table, bg) in cases { - for (ix, color) in table.iter().enumerate() { - let grey = ix % 8 == ANSI_BLACK; - let min = if grey { MIN_GREY } else { MIN_TEXT }; - let ratio = contrast(*color, bg); - assert!( - ratio >= min, - "{appearance:?} ANSI {ix} {color:?} is {ratio:.2}:1 on {bg:?}, want {min}:1" + fn every_registered_variant_resolves_all_ansi_slots_from_its_theme() { + for variant in zeron_theme::ThemeRegistry::builtin() + .families + .iter() + .flat_map(|family| &family.variants) + { + let appearance = match variant.appearance { + zeron_theme::Appearance::Dark => Appearance::Dark, + zeron_theme::Appearance::Light => Appearance::Light, + }; + let theme = Theme::for_selection( + appearance, + &variant.id, + zeron_theme::AccentSelection::ThemeDefault, + zeron_theme::SurfacePreference::ThemeDefault, + ); + for index in 0..16 { + assert_eq!( + resolve_color(CellColor::Indexed(index), &theme), + theme.terminal.ansi[index as usize], + "{} ANSI {index}", + variant.id ); } } } - /// "Bright" means *more* prominent in both appearances — which is darker on - /// a light field, not lighter. A literal copy of the dark table would fail - /// this in all seven checked slots. - /// - /// The black pair is the standing exception: "bright black" is the dim-text - /// grey in every terminal palette, so it steps *lighter* than black in both - /// appearances. Inverting it on light would put the most common dim-text - /// color below `#1f1f1f`, i.e. heavier than body text — the opposite of dim. - #[test] - fn bright_slots_gain_emphasis_in_both_appearances() { - let lum = |c: (u8, u8, u8)| luminance(c.0, c.1, c.2); - for ix in 0..8 { - if ix == ANSI_BLACK { - continue; - } - assert!( - lum(ANSI16_DARK[ix + 8]) > lum(ANSI16_DARK[ix]), - "dark ANSI {ix}: bright should be lighter on near-black" - ); - assert!( - lum(ANSI16_LIGHT[ix + 8]) < lum(ANSI16_LIGHT[ix]), - "light ANSI {ix}: bright should be darker on near-white" - ); - } - // The exception, asserted rather than merely skipped. - assert!(lum(ANSI16_DARK[8]) > lum(ANSI16_DARK[ANSI_BLACK])); - assert!(lum(ANSI16_LIGHT[8]) > lum(ANSI16_LIGHT[ANSI_BLACK])); - } - #[test] fn timing_constants_match_spec() { assert_eq!(COALESCE_MS, 12); @@ -1251,21 +1102,4 @@ mod tests { fn drag_threshold_matches_the_gpui_default() { assert_eq!(SELECTION_DRAG_THRESHOLD, 2.0); } - - /// The selection veil must stay achromatic, or it tints the ANSI text it - /// covers instead of just lifting it. - #[test] - fn selection_wash_is_neutral_and_translucent() { - for appearance in [Appearance::Dark, Appearance::Light] { - let wash = terminal_selection_for(appearance); - assert_eq!(wash.s, 0.0, "{appearance:?} selection must have no hue"); - assert!( - wash.a > 0.0 && wash.a < 0.5, - "{appearance:?} selection must veil the cell, not replace it" - ); - } - // Opposite directions: lighten the dark grid, darken the light one. - assert_eq!(terminal_selection_for(Appearance::Dark).l, 1.0); - assert_eq!(terminal_selection_for(Appearance::Light).l, 0.0); - } } diff --git a/crates/ui/src/theme.rs b/crates/ui/src/theme.rs index 892581f32b..edefefdc59 100644 --- a/crates/ui/src/theme.rs +++ b/crates/ui/src/theme.rs @@ -37,6 +37,10 @@ use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; use gpui::{App, Global, Hsla, SharedString, hsla}; use serde::{Deserialize, Serialize}; use zeron_syntax::HighlightKind; +use zeron_theme::{ + AccentPreset, AccentSelection, Color as ModelColor, SurfacePreference, SurfaceTreatment, + ThemeRegistry, ThemeVariant, +}; /// User-selectable accent family. A choice is one color identity, not a /// miniature multi-hue theme: every interactive accent role stays on the same @@ -126,6 +130,34 @@ impl AccentColor { } } +impl From for AccentPreset { + fn from(value: AccentColor) -> Self { + match value { + AccentColor::Zeron => Self::Zeron, + AccentColor::Orange => Self::Orange, + AccentColor::Amber => Self::Amber, + AccentColor::Green => Self::Green, + AccentColor::Cyan => Self::Cyan, + AccentColor::Blue => Self::Blue, + AccentColor::Pink => Self::Pink, + } + } +} + +impl From for AccentColor { + fn from(value: AccentPreset) -> Self { + match value { + AccentPreset::Zeron => Self::Zeron, + AccentPreset::Orange => Self::Orange, + AccentPreset::Amber => Self::Amber, + AccentPreset::Green => Self::Green, + AccentPreset::Cyan => Self::Cyan, + AccentPreset::Blue => Self::Blue, + AccentPreset::Pink => Self::Pink, + } + } +} + /// The three authored rows of the animated 2×3 pixel glyph. Keeping this as a /// palette entity preserves the mark's light→mid→deep personality while letting /// every accent preset own it as one coherent family. @@ -236,6 +268,22 @@ pub fn theme_generation() -> u32 { THEME_GENERATION.load(Ordering::Relaxed) } +fn model_appearance(appearance: zeron_theme::Appearance) -> Appearance { + match appearance { + zeron_theme::Appearance::Dark => Appearance::Dark, + zeron_theme::Appearance::Light => Appearance::Light, + } +} + +fn model_color(color: ModelColor) -> Hsla { + let (h, s, l) = rgb_to_hsl( + color.r as f32 / 255.0, + color.g as f32 / 255.0, + color.b as f32 / 255.0, + ); + hsla(h, s, l, color.a as f32 / 255.0) +} + /// [`CURRENT_APPEARANCE`] is process-wide, so under the parallel test runner /// any test that flips it — or asserts on the output of a helper that reads it /// ([`ink`], [`hairline`], [`wash`], …) — must hold this lock. Crate-visible @@ -343,6 +391,43 @@ impl SyntaxPalette { } } + fn from_variant(variant: &ThemeVariant, fallback: Self) -> Self { + let color = |key: &str, fallback: Hsla| { + variant + .syntax + .get(key) + .copied() + .map(model_color) + .unwrap_or(fallback) + }; + Self { + comment: color("comment", fallback.comment), + keyword: color("keyword", fallback.keyword), + string: color("string", fallback.string), + string_special: color("stringSpecial", fallback.string_special), + escape: color("escape", fallback.escape), + number: color("number", fallback.number), + boolean: color("boolean", fallback.boolean), + type_name: color("type", fallback.type_name), + type_builtin: color("typeBuiltin", fallback.type_builtin), + constructor: color("constructor", fallback.constructor), + function: color("function", fallback.function), + function_builtin: color("functionBuiltin", fallback.function_builtin), + macro_name: color("macro", fallback.macro_name), + property: color("property", fallback.property), + constant: color("constant", fallback.constant), + variable: color("variable", fallback.variable), + variable_special: color("variableSpecial", fallback.variable_special), + parameter: color("parameter", fallback.parameter), + operator: color("operator", fallback.operator), + punctuation: color("punctuation", fallback.punctuation), + tag: color("tag", fallback.tag), + attribute: color("attribute", fallback.attribute), + label: color("label", fallback.label), + invalid: color("invalid", fallback.invalid), + } + } + fn dark(text: Hsla, comment: Hsla, danger: Hsla) -> Self { // Same sources and 72% saturation treatment as history::graph_color. let indigo = git_graph_tone(oklch(0.673, 0.182, 276.935)); @@ -433,6 +518,17 @@ fn git_graph_tone(mut color: Hsla) -> Hsla { pub struct Theme { /// Which appearance these tokens were built for. pub appearance: Appearance, + /// Stable id of the resolved theme variant. + pub variant_id: SharedString, + /// Stable id of the family that owns [`Self::variant_id`]. + pub family_id: SharedString, + /// Whether the base theme or a user preset owns interactive identity. + pub accent_selection: AccentSelection, + /// The persisted policy that resolved [`Self::surface_treatment`]. + pub surface_preference: SurfacePreference, + /// The effective treatment after applying [`Self::surface_preference`] to + /// the selected variant's recommendation. + pub surface_treatment: SurfaceTreatment, /// The selected interactive accent used to build this theme. pub accent_color: AccentColor, @@ -561,6 +657,9 @@ pub struct Theme { /// Diff: hunk-header wash (bluish grey). pub diff_hunk_bg: Hsla, + /// Theme-owned terminal background, selection, and ANSI16 palette. + pub terminal: TerminalColors, + // ---- fonts ---- /// UI font family (bundling of Geist lands with asset work; until then the /// text system falls back to the system sans when the family is missing). @@ -572,6 +671,34 @@ pub struct Theme { pub font_mono_fallback: SharedString, } +#[derive(Debug, Clone)] +pub struct TerminalColors { + pub background: Hsla, + pub foreground: Hsla, + pub selection: Hsla, + pub ansi: [Hsla; 16], +} + +impl TerminalColors { + fn from_variant(variant: &ThemeVariant) -> Self { + Self { + background: model_color(variant.terminal.background), + foreground: model_color(variant.terminal.foreground), + selection: model_color(variant.terminal.selection), + ansi: variant.terminal.ansi.map(model_color), + } + } + + fn zeron(appearance: Appearance) -> Self { + let id = match appearance { + Appearance::Dark => "zeron-dark", + Appearance::Light => "zeron-light", + }; + let registry = ThemeRegistry::active(); + Self::from_variant(registry.variant(id).expect("Zeron terminal palette exists")) + } +} + impl Theme { // ---- numbers drive layout (px) ---- /// Frost translucency over the blurred window background (macOS vibrancy). @@ -626,31 +753,44 @@ impl Theme { /// line-box whitespace rather than separating layout regions. pub const TEXT_STACK_GAP: f32 = 1.0; - /// The frost tint painted over the blurred window background (macOS glass). - /// Dark: darker than `surface`, matched to the reference vibrancy scrim - /// `hsl(0 0% 3%)`. Light: a near-white frost run heavier than dark's — see - /// [`Self::GLASS_ALPHA_LIGHT`]. On opaque platforms this IS the surface - /// tone (no tint swap). + /// The selected theme's shell tint painted over the blurred window + /// background (macOS glass). Keeping the hue theme-owned matters when a + /// user forces frost onto a palette authored for an opaque workbench: a + /// fixed Zeron grey would erase that palette's identity. pub fn glass(&self) -> Hsla { - match self.appearance { - Appearance::Dark => { - if Self::GLASS_ALPHA < 1.0 { - grey(8).opacity(Self::GLASS_ALPHA) - } else { - self.surface - } - } - Appearance::Light => { - if Self::GLASS_ALPHA_LIGHT < 1.0 { - // 0xfa, not the surface's 0xf4-ish grey: at 90% coverage - // the tint IS the sidebar tone, and the darker grey read - // as a dingy pane next to the white content card. - grey(0xfa).opacity(Self::GLASS_ALPHA_LIGHT) - } else { - self.surface - } + if self.surface_treatment == SurfaceTreatment::Opaque { + return self.surface; + } + let base = match self.appearance { + Appearance::Dark => Self::GLASS_ALPHA, + Appearance::Light => Self::GLASS_ALPHA_LIGHT, + }; + self.surface + .opacity(self.contrast_checked_glass_alpha(base)) + } + + /// Raise a requested tint's coverage until primary and muted shell text + /// remain legible against the adverse desktop luminance for this + /// appearance. A theme with unusually delicate contrast may therefore get + /// denser glass, never silently broken text. + fn contrast_checked_glass_alpha(&self, base: f32) -> f32 { + if base >= 1.0 { + return 1.0; + } + let adverse_backdrop = match self.appearance { + Appearance::Dark => grey(0xff), + Appearance::Light => grey(0), + }; + for step in 0..=20 { + let alpha = base + (1.0 - base) * step as f32 / 20.0; + let composite = flatten(self.surface.opacity(alpha), adverse_backdrop); + if contrast_ratio(self.text, composite) >= 4.5 + && contrast_ratio(self.text_muted, composite) >= 3.0 + { + return alpha; } } + 1.0 } /// Whether this appearance paints translucent chrome over the blurred @@ -670,40 +810,23 @@ impl Theme { /// wgpu platforms keep opaque floats until tested). The window chrome /// itself stays opaque off macOS either way. pub fn is_frost(&self) -> bool { - cfg!(any(target_os = "macos", target_os = "linux")) + self.surface_treatment == SurfaceTreatment::Frosted + && cfg!(any(target_os = "macos", target_os = "linux")) } - /// Hover wash for chrome that sits ON GLASS (sidebar rows, tabs, titlebar - /// buttons). One recipe, both appearances: the 11% [`wash`], tone-flipped - /// by the palette convention (soft-white on dark, soft-black on light). - /// - /// Hover and selection share the SAME fill (selection adds only the ring). - /// Light previously ran heavy white washes here (hover 0.55, selection - /// 0.92) after a black-hover-next-to-white-selection mismatch report; now - /// hover and selection are *both* the tone-flipped wash, so they lift the - /// same way again. Light's alpha sits under dark's: dark's 11% at the - /// light tone read too dark over the bright frost (user report). + /// Theme-owned hover wash for chrome that sits on glass (sidebar rows, + /// tabs, titlebar buttons). The importer maps this role from the source + /// theme, so forcing frost does not reintroduce Zeron's neutral hover. pub fn glass_hover(&self) -> Hsla { - match self.appearance { - Appearance::Dark => wash_for(Appearance::Dark, 0.11), - Appearance::Light => wash_for(Appearance::Light, 0.06), - } + self.element_hover } - /// The translucent tint floating cards paint over their backdrop blur - /// (see [`crate::frost::frosted`]). Dark: the reference zeron - /// `.glass-surface` menu tint verbatim — `oklch(0.33 0 0 / 34%)`. The - /// previous `surface_overlay` at 65% was tuned back when the tint had to - /// *approximate* the composited recipe without a real blur; kept over the - /// blur it buried the backdrop's colour and menus read as flat grey slabs - /// next to the hue-inheriting chrome (user report). At 34% the blurred - /// backdrop carries the card and the mid-grey only lifts it off the - /// plane. Light: heavier — a translucent white tint left menu text - /// ghosting over whatever sat behind the popover, so light coverage - /// steps up to keep rows on a known background. + /// The theme-owned tint floating cards paint over their backdrop blur (see + /// [`crate::frost::frosted`]). Light coverage stays heavier because dark + /// text is more vulnerable to unpredictable content behind a popover. pub fn glass_overlay(&self) -> Hsla { match self.appearance { - Appearance::Dark => oklch(0.33, 0.0, 0.0).opacity(0.34), + Appearance::Dark => self.surface_overlay.opacity(0.50), Appearance::Light => self.surface_overlay.opacity(0.85), } } @@ -769,6 +892,11 @@ impl Theme { let accent = accent_color.tokens(Appearance::Dark); Self { appearance: Appearance::Dark, + variant_id: "zeron-dark".into(), + family_id: "zeron".into(), + accent_selection: AccentSelection::Preset(accent_color.into()), + surface_preference: SurfacePreference::ThemeDefault, + surface_treatment: SurfaceTreatment::Frosted, accent_color, bg: grey(6), // main panel — sampled #060606 surface: grey(13), // shell / sidebar — sampled #0d0d0d @@ -816,6 +944,7 @@ impl Theme { diff_add: oklch(0.765, 0.177, 163.223), // emerald-400 diff_del: oklch(0.704, 0.191, 22.216), // red-400 diff_hunk_bg: hsla(0.6, 0.35, 0.6, 0.05), + terminal: TerminalColors::zeron(Appearance::Dark), font_sans: "Geist".into(), font_mono: "Geist Mono".into(), font_sans_fallback: system_sans().into(), @@ -839,6 +968,11 @@ impl Theme { let accent = accent_color.tokens(Appearance::Light); Self { appearance: Appearance::Light, + variant_id: "zeron-light".into(), + family_id: "zeron".into(), + accent_selection: AccentSelection::Preset(accent_color.into()), + surface_preference: SurfacePreference::ThemeDefault, + surface_treatment: SurfaceTreatment::Frosted, accent_color, bg: grey(0xff), // main panel — clean white // Deeper than ~neutral-100 looks on paper: the content card is pure @@ -905,6 +1039,7 @@ impl Theme { diff_add: oklch(0.596, 0.145, 163.225), // emerald-600 diff_del: oklch(0.577, 0.245, 27.325), // red-600 diff_hunk_bg: hsla(0.6, 0.35, 0.35, 0.07), + terminal: TerminalColors::zeron(Appearance::Light), font_sans: "Geist".into(), font_mono: "Geist Mono".into(), font_sans_fallback: system_sans().into(), @@ -924,15 +1059,92 @@ impl Theme { } } - /// Sidebar chrome deliberately keeps Zeron's authored identity palette, - /// while live activity and glyphs inherit their explicit roles from the - /// selected preset. This keeps navigation stable without freezing status - /// feedback to one hard-coded color. - pub fn sidebar(appearance: Appearance, selected_accent: AccentColor) -> Self { - let mut theme = Self::for_preferences(appearance, AccentColor::Zeron); - let selected = selected_accent.tokens(appearance); - theme.busy = selected.activity; - theme.glyph = selected.glyph; + /// Resolve one complete registered variant and then apply the narrowly + /// scoped accent policy. Components consume only the resulting semantic + /// tokens; VS Code keys never escape the importer. + pub fn for_selection( + appearance: Appearance, + variant_id: &str, + accent_selection: AccentSelection, + surface_preference: SurfacePreference, + ) -> Self { + let registry = ThemeRegistry::active(); + let fallback_id = match appearance { + Appearance::Dark => "zeron-dark", + Appearance::Light => "zeron-light", + }; + let variant = registry + .variant(variant_id) + .filter(|variant| model_appearance(variant.appearance) == appearance) + .or_else(|| registry.variant(fallback_id)) + .expect("the built-in registry contains both Zeron appearances"); + Self::from_variant(variant, accent_selection, surface_preference) + } + + pub(crate) fn from_variant( + variant: &ThemeVariant, + accent_selection: AccentSelection, + surface_preference: SurfacePreference, + ) -> Self { + let appearance = model_appearance(variant.appearance); + let accent_color = match accent_selection { + AccentSelection::ThemeDefault => AccentColor::Zeron, + AccentSelection::Preset(preset) => preset.into(), + }; + let mut theme = Self::for_preferences(appearance, accent_color); + let colors = &variant.colors; + let accent = variant.accent_for(accent_selection); + theme.variant_id = variant.id.clone().into(); + theme.family_id = variant.family_id.clone().into(); + theme.accent_selection = accent_selection; + theme.surface_preference = surface_preference; + theme.surface_treatment = surface_preference.resolve(variant.recommended_surface_treatment); + theme.bg = model_color(colors.background); + theme.surface = model_color(colors.shell); + theme.surface_raised = model_color(colors.raised); + theme.surface_card = model_color(colors.card); + theme.surface_dialog = model_color(colors.dialog); + theme.surface_overlay = model_color(colors.overlay); + theme.element_hover = model_color(colors.hover); + theme.element_active = model_color(colors.active); + theme.border = model_color(colors.border); + theme.border_strong = model_color(colors.border_strong); + theme.text = model_color(colors.text); + theme.text_muted = model_color(colors.text_muted); + theme.text_faint = model_color(colors.text_faint); + theme.text_dim = model_color(colors.text_muted); + theme.solid = model_color(colors.solid); + theme.on_solid = model_color(colors.on_solid); + theme.accent = model_color(accent.primary); + theme.accent_strong = model_color(accent.strong); + theme.accent_wash = model_color(accent.wash); + theme.on_accent = model_color(accent.on); + theme.danger = model_color(colors.danger); + theme.danger_muted = model_color(colors.danger_muted); + theme.warning = model_color(colors.warning); + theme.warning_muted = model_color(colors.warning_muted); + theme.success = model_color(colors.success); + theme.success_muted = model_color(colors.success_muted); + theme.busy = model_color(accent.activity); + theme.glyph = GlyphPalette { + light: model_color(accent.glyph[0]), + mid: model_color(accent.glyph[1]), + deep: model_color(accent.glyph[2]), + }; + theme.surface_raised_hover = model_color(colors.raised); + theme.band = model_color(colors.hover); + theme.input_bg = model_color(colors.input); + theme.selection = model_color(accent.selection); + theme.cursor = model_color(colors.cursor); + theme.caret = model_color(accent.caret); + theme.danger_strong = model_color(colors.danger); + theme.code_text = model_color(accent.primary); + theme.code_wash = model_color(accent.wash); + theme.syntax = SyntaxPalette::from_variant(variant, theme.syntax); + theme.diff_add = model_color(colors.diff_add); + theme.diff_del = model_color(colors.diff_delete); + theme.diff_hunk_bg = model_color(colors.diff_hunk); + theme.terminal = TerminalColors::from_variant(variant); theme } @@ -956,6 +1168,28 @@ impl Theme { } } + pub fn install_selection( + appearance: Appearance, + variant_id: &str, + accent_selection: AccentSelection, + surface_preference: SurfacePreference, + cx: &mut App, + ) { + let next = + Self::for_selection(appearance, variant_id, accent_selection, surface_preference); + let changed = cx.try_global::().is_some_and(|theme| { + theme.variant_id != next.variant_id + || theme.accent_selection != next.accent_selection + || theme.surface_preference != next.surface_preference + || theme.appearance != next.appearance + }); + set_current_appearance(appearance); + cx.set_global(next); + if changed { + THEME_GENERATION.fetch_add(1, Ordering::Relaxed); + } + } + /// Read the theme global. pub fn of(cx: &App) -> &Theme { cx.global::() @@ -1427,19 +1661,68 @@ mod tests { } #[test] - fn sidebar_keeps_zeron_chrome_but_inherits_activity_roles() { - for appearance in [Appearance::Dark, Appearance::Light] { - for selected_accent in AccentColor::ALL { - let selected = Theme::for_preferences(appearance, selected_accent); - let sidebar = Theme::sidebar(appearance, selected_accent); - assert_eq!(sidebar.accent_color, AccentColor::Zeron); - assert_eq!(sidebar.accent, Theme::for_appearance(appearance).accent); - assert_eq!(sidebar.busy, selected.busy); - assert_eq!(sidebar.glyph, selected.glyph); - if selected_accent != AccentColor::Zeron { - assert_ne!(sidebar.accent, selected.accent); - } - } + fn theme_recommendation_and_surface_override_resolve_independently() { + let catppuccin = Theme::for_selection( + Appearance::Dark, + "catppuccin-mocha", + AccentSelection::ThemeDefault, + SurfacePreference::ThemeDefault, + ); + let zeron = Theme::dark(); + assert_ne!(catppuccin.surface, zeron.surface); + assert_eq!(catppuccin.busy, catppuccin.accent); + assert_eq!(catppuccin.glyph.mid, catppuccin.accent); + assert_eq!(catppuccin.surface_treatment, SurfaceTreatment::Opaque); + assert!(!catppuccin.is_glass()); + + let frosted = Theme::for_selection( + Appearance::Dark, + "catppuccin-mocha", + AccentSelection::ThemeDefault, + SurfacePreference::Frosted, + ); + assert_eq!(frosted.variant_id, catppuccin.variant_id); + assert_eq!(frosted.accent, catppuccin.accent); + assert_eq!(frosted.surface_treatment, SurfaceTreatment::Frosted); + assert_eq!(frosted.glass().h, frosted.surface.h); + assert_eq!(frosted.glass().s, frosted.surface.s); + assert_eq!(frosted.glass().l, frosted.surface.l); + + let opaque_zeron = Theme::for_selection( + Appearance::Dark, + "zeron-dark", + AccentSelection::ThemeDefault, + SurfacePreference::Opaque, + ); + assert_eq!(opaque_zeron.surface_treatment, SurfaceTreatment::Opaque); + assert_eq!(opaque_zeron.glass(), opaque_zeron.surface); + } + + #[test] + fn forced_frost_preserves_shell_text_contrast_for_every_builtin() { + let registry = ThemeRegistry::builtin(); + for variant in registry.families.iter().flat_map(|family| &family.variants) { + let appearance = model_appearance(variant.appearance); + let theme = Theme::from_variant( + variant, + AccentSelection::ThemeDefault, + SurfacePreference::Frosted, + ); + let adverse_backdrop = match appearance { + Appearance::Dark => grey(0xff), + Appearance::Light => grey(0), + }; + let composite = flatten(theme.glass(), adverse_backdrop); + assert!( + contrast_ratio(theme.text, composite) >= 4.5, + "{} primary shell text", + variant.id + ); + assert!( + contrast_ratio(theme.text_muted, composite) >= 3.0, + "{} muted shell text", + variant.id + ); } } From 52f08ff2d2fb8d90c2408f66b894ef1f1b589c57 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 01:48:43 +0200 Subject: [PATCH 3/9] Add theme registry and VS Code importer --- CONTEXT.md | 19 + crates/theme/Cargo.toml | 19 + crates/theme/src/bin/zeron-theme-import.rs | 68 + crates/theme/src/builtins.rs | 1338 +++++++++++++++++ crates/theme/src/lib.rs | 802 ++++++++++ crates/theme/src/library.rs | 419 ++++++ crates/theme/src/vscode.rs | 1080 +++++++++++++ crates/ui/src/theme_library.rs | 168 +++ ...tom-themes-compile-to-resolved-families.md | 26 + ...surface-preference-from-theme-selection.md | 5 + docs/theme-system.md | 149 ++ 11 files changed, 4093 insertions(+) create mode 100644 CONTEXT.md create mode 100644 crates/theme/Cargo.toml create mode 100644 crates/theme/src/bin/zeron-theme-import.rs create mode 100644 crates/theme/src/builtins.rs create mode 100644 crates/theme/src/lib.rs create mode 100644 crates/theme/src/library.rs create mode 100644 crates/theme/src/vscode.rs create mode 100644 crates/ui/src/theme_library.rs create mode 100644 docs/adr/0001-custom-themes-compile-to-resolved-families.md create mode 100644 docs/adr/0002-separate-surface-preference-from-theme-selection.md create mode 100644 docs/theme-system.md diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000000..a0ede71367 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,19 @@ +# Domain context + +## Theme vocabulary + +- **Theme family** — A named collection of related theme variants that share an origin, such as Night Owl and Night Owl Light. +- **Theme variant** — One complete, resolved palette for a single appearance (`light` or `dark`). Runtime UI consumes variants, not source-format tokens. +- **Theme source** — The durable origin of a custom family: an imported snapshot, linked file, or linked package. +- **Imported snapshot** — A self-contained copy of a compiled theme family. It no longer follows changes to its original file and can be duplicated for editing. +- **Linked theme** — A custom family that follows a source on disk and can be reloaded without re-importing it. +- **Linked file** — A link to one VS Code-compatible theme definition. +- **Linked package** — A link to a VS Code extension folder or `package.json` that declares one or more related theme variants. +- **Last known good** — The most recent successfully compiled family retained by a linked theme when its current source is missing or invalid. +- **Import report** — A per-variant summary of mapped roles, fallbacks, unsupported values, and inferred decisions produced during compilation. +- **Mapping review** — The optional advanced view of an import report. Normal theme selection and import do not expose token names. +- **Theme default accent** — The interaction accent chosen or inferred for a theme variant by its authoring source. +- **Accent override** — A Zeron preset that replaces interaction roles only; syntax, terminal ANSI, diff, warning, error, and success colors remain owned by the theme. +- **Recommended surface treatment** — A theme variant's authored recommendation for whether its surfaces are frosted or opaque. It is used only when the user keeps the surface preference at theme default. +- **Surface preference** — A device-local choice of theme default, frosted, or opaque that is independent of appearance, theme, and accent selections. +- **Resolved surface treatment** — The effective frosted or opaque treatment produced by applying the surface preference to the active variant's recommendation. diff --git a/crates/theme/Cargo.toml b/crates/theme/Cargo.toml new file mode 100644 index 0000000000..0421fc624d --- /dev/null +++ b/crates/theme/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "zeron-theme" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +clap.workspace = true +json5.workspace = true +plist.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/theme/src/bin/zeron-theme-import.rs b/crates/theme/src/bin/zeron-theme-import.rs new file mode 100644 index 0000000000..5cc7731f31 --- /dev/null +++ b/crates/theme/src/bin/zeron-theme-import.rs @@ -0,0 +1,68 @@ +use std::fs; +use std::path::PathBuf; + +use anyhow::{Context as _, Result}; +use clap::{Parser, ValueEnum}; +use zeron_theme::Appearance; +use zeron_theme::vscode::{ImportOptions, import_file}; + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum AppearanceArg { + Dark, + Light, +} + +impl From for Appearance { + fn from(value: AppearanceArg) -> Self { + match value { + AppearanceArg::Dark => Self::Dark, + AppearanceArg::Light => Self::Light, + } + } +} + +/// Convert a VS Code JSON/JSONC color theme into a complete Zeron theme draft. +#[derive(Debug, Parser)] +struct Args { + #[arg(long)] + input: PathBuf, + #[arg(long)] + output: PathBuf, + #[arg(long)] + report: PathBuf, + #[arg(long)] + id: String, + #[arg(long)] + family_id: String, + #[arg(long)] + name: String, + #[arg(long, value_enum)] + appearance: AppearanceArg, + #[arg(long)] + source_url: String, + #[arg(long)] + revision: String, + #[arg(long)] + license: String, +} + +fn main() -> Result<()> { + let args = Args::parse(); + let imported = import_file( + &args.input, + ImportOptions { + id: args.id, + family_id: args.family_id, + name: args.name, + appearance: args.appearance.into(), + source_url: args.source_url, + revision: args.revision, + license: args.license, + }, + )?; + fs::write(&args.output, serde_json::to_vec_pretty(&imported.theme)?) + .with_context(|| format!("could not write {}", args.output.display()))?; + fs::write(&args.report, serde_json::to_vec_pretty(&imported.report)?) + .with_context(|| format!("could not write {}", args.report.display()))?; + Ok(()) +} diff --git a/crates/theme/src/builtins.rs b/crates/theme/src/builtins.rs new file mode 100644 index 0000000000..d386613409 --- /dev/null +++ b/crates/theme/src/builtins.rs @@ -0,0 +1,1338 @@ +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use sha2::{Digest, Sha256}; + +use crate::{ + AccentRoles, Appearance, Color, SurfaceTreatment, TerminalPalette, ThemeColors, ThemeFamily, + ThemeRegistry, ThemeSource, ThemeVariant, +}; + +pub fn builtin_registry() -> &'static ThemeRegistry { + static REGISTRY: OnceLock = OnceLock::new(); + REGISTRY.get_or_init(|| ThemeRegistry { + families: vec![ + family("zeron", "Zeron", vec![zeron_light(), zeron_dark()]), + family( + "vscode-default", + "VS Code Default", + vec![vscode_light(), vscode_dark()], + ), + family( + "catppuccin", + "Catppuccin", + vec![catppuccin_latte(), catppuccin_mocha()], + ), + family( + "tokyo-night", + "Tokyo Night", + vec![tokyo_light(), tokyo_dark()], + ), + family("dracula", "Dracula", vec![dracula()]), + family("github", "GitHub", vec![github_light(), github_dark()]), + family("ayu", "Ayu", vec![ayu_light(), ayu_dark(), ayu_mirage()]), + family("gruvbox", "Gruvbox", vec![gruvbox_light(), gruvbox_dark()]), + family( + "rose-pine", + "Rosé Pine", + vec![rose_pine_dawn(), rose_pine_moon()], + ), + family("nord", "Nord", vec![nord()]), + family("one-dark-pro", "One Dark Pro", vec![one_dark_pro()]), + family("atom-one-dark", "Atom One Dark", vec![atom_one_dark()]), + family( + "night-owl", + "Night Owl", + vec![night_owl_light(), night_owl()], + ), + family( + "winter-is-coming", + "Winter is Coming", + vec![winter_light(), winter_dark_blue()], + ), + family("palenight", "Palenight", vec![palenight()]), + family("synthwave-84", "SynthWave '84", vec![synthwave_84()]), + family( + "shades-of-purple", + "Shades of Purple", + vec![shades_of_purple()], + ), + family("cobalt2", "Cobalt2", vec![cobalt2()]), + family("andromeda", "Andromeda", vec![andromeda()]), + ], + }) +} + +fn family(id: &str, name: &str, variants: Vec) -> ThemeFamily { + ThemeFamily { + id: id.into(), + name: name.into(), + variants, + } +} + +struct Seeds<'a> { + id: &'a str, + family_id: &'a str, + name: &'a str, + appearance: Appearance, + treatment: SurfaceTreatment, + background: &'a str, + shell: &'a str, + raised: &'a str, + card: &'a str, + text: &'a str, + muted: &'a str, + faint: &'a str, + accent: &'a str, + danger: &'a str, + warning: &'a str, + success: &'a str, + terminal_background: &'a str, + ansi: [&'a str; 16], + syntax: [&'a str; 12], + source: ThemeSource, +} + +fn variant(seed: Seeds<'_>) -> ThemeVariant { + let background = c(seed.background); + let shell = c(seed.shell); + let raised = c(seed.raised); + let card = c(seed.card); + let text = c(seed.text); + let muted = c(seed.muted).ensure_contrast(background, 4.5); + let faint = c(seed.faint); + let danger = c(seed.danger); + let warning = c(seed.warning); + let success = c(seed.success); + let accent = AccentRoles::derive(c(seed.accent), seed.appearance, background); + let dark = seed.appearance.is_dark(); + let border_tone = if dark { Color::WHITE } else { Color::BLACK }; + let solid = if dark { + Color::rgb(235, 235, 239) + } else { + Color::rgb(35, 35, 40) + }; + let colors = ThemeColors { + background, + shell, + raised, + card, + dialog: card.mix(raised, if dark { 0.18 } else { 0.04 }), + overlay: card.mix(raised, if dark { 0.34 } else { 0.02 }), + hover: border_tone.with_alpha(if dark { 0.11 } else { 0.06 }), + active: accent.primary.with_alpha(if dark { 0.18 } else { 0.10 }), + border: border_tone.with_alpha(if dark { 0.10 } else { 0.12 }), + border_strong: border_tone.with_alpha(if dark { 0.18 } else { 0.22 }), + text, + text_muted: muted, + text_faint: faint, + solid, + on_solid: solid.best_on_color(), + danger, + danger_muted: danger.mix(text, 0.28), + warning, + warning_muted: warning.mix(text, 0.25), + success, + success_muted: success.mix(text, 0.25), + input: if dark { raised.with_alpha(0.72) } else { card }, + cursor: text.with_alpha(if dark { 0.40 } else { 0.55 }), + diff_add: success, + diff_delete: danger, + diff_hunk: accent.primary.with_alpha(if dark { 0.08 } else { 0.07 }), + }; + let terminal_background = c(seed.terminal_background); + let mut variant = ThemeVariant { + id: seed.id.into(), + family_id: seed.family_id.into(), + name: seed.name.into(), + appearance: seed.appearance, + recommended_surface_treatment: seed.treatment, + colors, + accent, + syntax: syntax(seed.syntax), + terminal: TerminalPalette { + background: terminal_background, + foreground: text.ensure_contrast(terminal_background, 4.5), + selection: border_tone.with_alpha(if dark { 0.22 } else { 0.16 }), + ansi: seed.ansi.map(c), + }, + source: seed.source, + }; + // Hash the checked-in resolved definition itself (with the hash field + // blanked), not merely its source URL. This makes provenance sensitive to + // curation edits as well as upstream revision changes. + variant.source.asset_hash.clear(); + let encoded = serde_json::to_vec(&variant).expect("built-in theme serializes"); + variant.source.asset_hash = format!("sha256:{:x}", Sha256::digest(encoded)); + variant +} + +fn syntax(colors: [&str; 12]) -> BTreeMap { + let [ + comment, + keyword, + string, + number, + type_name, + function, + property, + variable, + punctuation, + tag, + attribute, + invalid, + ] = colors.map(c); + BTreeMap::from([ + ("comment".into(), comment), + ("keyword".into(), keyword), + ("string".into(), string), + ("stringSpecial".into(), attribute), + ("escape".into(), attribute), + ("number".into(), number), + ("boolean".into(), number), + ("type".into(), type_name), + ("typeBuiltin".into(), type_name), + ("constructor".into(), type_name), + ("function".into(), function), + ("functionBuiltin".into(), function), + ("macro".into(), keyword), + ("property".into(), property), + ("constant".into(), number), + ("variable".into(), variable), + ("variableSpecial".into(), keyword), + ("parameter".into(), variable), + ("operator".into(), keyword), + ("punctuation".into(), punctuation), + ("tag".into(), tag), + ("attribute".into(), attribute), + ("label".into(), function), + ("embedded".into(), punctuation), + ("invalid".into(), invalid), + ]) +} + +fn source(id: &str, format: &str, url: &str, revision: &str, license: &str) -> ThemeSource { + ThemeSource { + format: format.into(), + url: url.into(), + revision: revision.into(), + license: license.into(), + asset_hash: format!("pending:{id}"), + } +} + +fn c(value: &str) -> Color { + value.parse().expect("built-in theme colors are valid") +} + +const ANSI_DARK: [&str; 16] = [ + "#242424", "#f87171", "#4ade80", "#facc15", "#60a5fa", "#c084fc", "#22d3ee", "#d4d4d8", + "#52525b", "#fca5a5", "#86efac", "#fde047", "#93c5fd", "#d8b4fe", "#67e8f9", "#fafafa", +]; + +const ANSI_LIGHT: [&str; 16] = [ + "#1f1f1f", "#dc2626", "#16a34a", "#b45309", "#2563eb", "#9333ea", "#0e7490", "#3f3f46", + "#71717a", "#b91c1c", "#15803d", "#92400e", "#1d4ed8", "#7e22ce", "#155e75", "#18181b", +]; + +fn zeron_dark() -> ThemeVariant { + variant(Seeds { + id: "zeron-dark", + family_id: "zeron", + name: "Zeron Dark", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Frosted, + background: "#060606", + shell: "#0d0d0d", + raised: "#343438", + card: "#0e0e0e", + text: "#e8e8ea", + muted: "#a9a9ae", + faint: "#85858a", + accent: "#8b7cf6", + danger: "#f87171", + warning: "#facc15", + success: "#34d399", + terminal_background: "#090909", + ansi: ANSI_DARK, + syntax: [ + "#92929a", "#8b7cf6", "#34d399", "#facc15", "#c084fc", "#60a5fa", "#f472b6", "#e8e8ea", + "#a1a1aa", "#f472b6", "#22d3ee", "#f87171", + ], + source: source( + "zeron-dark", + "native", + "https://github.com/zeronsh/comet", + "d138049", + "MIT", + ), + }) +} + +fn zeron_light() -> ThemeVariant { + variant(Seeds { + id: "zeron-light", + family_id: "zeron", + name: "Zeron Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Frosted, + background: "#ffffff", + shell: "#f3f3f5", + raised: "#ededf0", + card: "#ffffff", + text: "#303035", + muted: "#62626a", + faint: "#797981", + accent: "#5b43e8", + danger: "#dc2626", + warning: "#a16207", + success: "#15803d", + terminal_background: "#fafafa", + ansi: ANSI_LIGHT, + syntax: [ + "#6b7280", "#5b43e8", "#15803d", "#a16207", "#7e22ce", "#2563eb", "#be185d", "#303035", + "#52525b", "#be185d", "#0e7490", "#b91c1c", + ], + source: source( + "zeron-light", + "native", + "https://github.com/zeronsh/comet", + "d138049", + "MIT", + ), + }) +} + +fn vscode_dark() -> ThemeVariant { + variant(Seeds { + id: "vscode-dark-plus", + family_id: "vscode-default", + name: "Dark+", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#1e1e1e", + shell: "#181818", + raised: "#2a2d2e", + card: "#252526", + text: "#d4d4d4", + muted: "#a8a8a8", + faint: "#858585", + accent: "#007acc", + danger: "#f48771", + warning: "#cca700", + success: "#89d185", + terminal_background: "#1e1e1e", + ansi: [ + "#000000", "#cd3131", "#0dbc79", "#e5e510", "#2472c8", "#bc3fbc", "#11a8cd", "#e5e5e5", + "#666666", "#f14c4c", "#23d18b", "#f5f543", "#3b8eea", "#d670d6", "#29b8db", "#e5e5e5", + ], + syntax: [ + "#6a9955", "#c586c0", "#ce9178", "#b5cea8", "#4ec9b0", "#dcdcaa", "#9cdcfe", "#d4d4d4", + "#d4d4d4", "#569cd6", "#9cdcfe", "#f44747", + ], + source: source( + "vscode-dark-plus", + "vscode", + "https://github.com/microsoft/vscode", + "e33d147d4c0fa65ce17cb73ec9d798f064b4bf1f", + "MIT", + ), + }) +} + +fn vscode_light() -> ThemeVariant { + variant(Seeds { + id: "vscode-light-plus", + family_id: "vscode-default", + name: "Light+", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#ffffff", + shell: "#f3f3f3", + raised: "#e8e8e8", + card: "#ffffff", + text: "#1f1f1f", + muted: "#616161", + faint: "#767676", + accent: "#0078d4", + danger: "#a1260d", + warning: "#895503", + success: "#008000", + terminal_background: "#ffffff", + ansi: ANSI_LIGHT, + syntax: [ + "#008000", "#0000ff", "#a31515", "#098658", "#267f99", "#795e26", "#001080", "#1f1f1f", + "#1f1f1f", "#800000", "#ff0000", "#cd3131", + ], + source: source( + "vscode-light-plus", + "vscode", + "https://github.com/microsoft/vscode", + "e33d147d4c0fa65ce17cb73ec9d798f064b4bf1f", + "MIT", + ), + }) +} + +fn catppuccin_mocha() -> ThemeVariant { + variant(Seeds { + id: "catppuccin-mocha", + family_id: "catppuccin", + name: "Catppuccin Mocha", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#1e1e2e", + shell: "#181825", + raised: "#313244", + card: "#242436", + text: "#cdd6f4", + muted: "#a6adc8", + faint: "#9399b2", + accent: "#cba6f7", + danger: "#f38ba8", + warning: "#f9e2af", + success: "#a6e3a1", + terminal_background: "#1e1e2e", + ansi: [ + "#45475a", "#f38ba8", "#a6e3a1", "#f9e2af", "#89b4fa", "#f5c2e7", "#94e2d5", "#bac2de", + "#585b70", "#f38ba8", "#a6e3a1", "#f9e2af", "#89b4fa", "#f5c2e7", "#94e2d5", "#a6adc8", + ], + syntax: [ + "#6c7086", "#cba6f7", "#a6e3a1", "#fab387", "#f9e2af", "#89b4fa", "#94e2d5", "#cdd6f4", + "#bac2de", "#f38ba8", "#f5c2e7", "#f38ba8", + ], + source: source( + "catppuccin-mocha", + "vscode", + "https://github.com/catppuccin/vscode", + "befc9e6fc41980f4241408f7049755d47c06ff45", + "MIT", + ), + }) +} + +fn catppuccin_latte() -> ThemeVariant { + variant(Seeds { + id: "catppuccin-latte", + family_id: "catppuccin", + name: "Catppuccin Latte", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#eff1f5", + shell: "#e6e9ef", + raised: "#dce0e8", + card: "#f7f8fa", + text: "#4c4f69", + muted: "#5c5f77", + faint: "#6c6f85", + accent: "#8839ef", + danger: "#d20f39", + warning: "#df8e1d", + success: "#40a02b", + terminal_background: "#eff1f5", + ansi: [ + "#5c5f77", "#d20f39", "#40a02b", "#df8e1d", "#1e66f5", "#ea76cb", "#179299", "#acb0be", + "#6c6f85", "#d20f39", "#40a02b", "#df8e1d", "#1e66f5", "#ea76cb", "#179299", "#bcc0cc", + ], + syntax: [ + "#8c8fa1", "#8839ef", "#40a02b", "#fe640b", "#df8e1d", "#1e66f5", "#179299", "#4c4f69", + "#6c6f85", "#d20f39", "#ea76cb", "#d20f39", + ], + source: source( + "catppuccin-latte", + "vscode", + "https://github.com/catppuccin/vscode", + "befc9e6fc41980f4241408f7049755d47c06ff45", + "MIT", + ), + }) +} + +fn tokyo_dark() -> ThemeVariant { + variant(Seeds { + id: "tokyo-night", + family_id: "tokyo-night", + name: "Tokyo Night", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#1a1b26", + shell: "#16161e", + raised: "#292e42", + card: "#1f2335", + text: "#c0caf5", + muted: "#9aa5ce", + faint: "#7f87ad", + accent: "#7aa2f7", + danger: "#f7768e", + warning: "#e0af68", + success: "#9ece6a", + terminal_background: "#1a1b26", + ansi: [ + "#15161e", "#f7768e", "#9ece6a", "#e0af68", "#7aa2f7", "#bb9af7", "#7dcfff", "#a9b1d6", + "#414868", "#f7768e", "#9ece6a", "#e0af68", "#7aa2f7", "#bb9af7", "#7dcfff", "#c0caf5", + ], + syntax: [ + "#565f89", "#bb9af7", "#9ece6a", "#ff9e64", "#2ac3de", "#7aa2f7", "#73daca", "#c0caf5", + "#9abdf5", "#f7768e", "#e0af68", "#f7768e", + ], + source: source( + "tokyo-night", + "vscode", + "https://github.com/tokyo-night/tokyo-night-vscode-theme", + "7c0f11eaef322f293621ca7befe462214b7ea468", + "MIT", + ), + }) +} + +fn tokyo_light() -> ThemeVariant { + variant(Seeds { + id: "tokyo-night-light", + family_id: "tokyo-night", + name: "Tokyo Night Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#d5d6db", + shell: "#cbccd1", + raised: "#bfc0c6", + card: "#e1e2e7", + text: "#343b59", + muted: "#485e7d", + faint: "#5a6378", + accent: "#34548a", + danger: "#8c4351", + warning: "#8f5e15", + success: "#33635c", + terminal_background: "#d5d6db", + ansi: [ + "#0f0f14", "#8c4351", "#33635c", "#8f5e15", "#34548a", "#5a4a78", "#0f4b6e", "#828594", + "#4c505e", "#8c4351", "#33635c", "#8f5e15", "#34548a", "#5a4a78", "#0f4b6e", "#343b59", + ], + syntax: [ + "#6c6e75", "#5a4a78", "#33635c", "#965027", "#0f4b6e", "#34548a", "#166775", "#343b59", + "#485e7d", "#8c4351", "#8f5e15", "#8c4351", + ], + source: source( + "tokyo-night-light", + "vscode", + "https://github.com/tokyo-night/tokyo-night-vscode-theme", + "7c0f11eaef322f293621ca7befe462214b7ea468", + "MIT", + ), + }) +} + +fn dracula() -> ThemeVariant { + variant(Seeds { + id: "dracula", + family_id: "dracula", + name: "Dracula", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#282a36", + shell: "#21222c", + raised: "#44475a", + card: "#2d303e", + text: "#f8f8f2", + muted: "#c5c8c6", + faint: "#9a9cab", + accent: "#bd93f9", + danger: "#ff5555", + warning: "#f1fa8c", + success: "#50fa7b", + terminal_background: "#282a36", + ansi: [ + "#21222c", "#ff5555", "#50fa7b", "#f1fa8c", "#bd93f9", "#ff79c6", "#8be9fd", "#f8f8f2", + "#6272a4", "#ff6e6e", "#69ff94", "#ffffa5", "#d6acff", "#ff92df", "#a4ffff", "#ffffff", + ], + syntax: [ + "#6272a4", "#ff79c6", "#f1fa8c", "#bd93f9", "#8be9fd", "#50fa7b", "#8be9fd", "#f8f8f2", + "#f8f8f2", "#ff79c6", "#50fa7b", "#ff5555", + ], + source: source( + "dracula", + "vscode", + "https://github.com/dracula/visual-studio-code", + "1b9ecf4d7e0c8cc2e2e890a7a41ad1db5fff1e6c", + "MIT", + ), + }) +} + +fn github_light() -> ThemeVariant { + variant(Seeds { + id: "github-light", + family_id: "github", + name: "GitHub Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#ffffff", + shell: "#f6f8fa", + raised: "#d0d7de", + card: "#ffffff", + text: "#1f2328", + muted: "#656d76", + faint: "#818b98", + accent: "#0969da", + danger: "#cf222e", + warning: "#9a6700", + success: "#1a7f37", + terminal_background: "#ffffff", + ansi: [ + "#24292f", "#cf222e", "#1a7f37", "#9a6700", "#0969da", "#8250df", "#1b7c83", "#6e7781", + "#57606a", "#a40e26", "#116329", "#7d4e00", "#0550ae", "#6639ba", "#0a6b74", "#1f2328", + ], + syntax: [ + "#6e7781", "#cf222e", "#0a3069", "#0550ae", "#953800", "#8250df", "#116329", "#1f2328", + "#57606a", "#116329", "#953800", "#cf222e", + ], + source: source( + "github-light", + "vscode", + "https://github.com/primer/github-vscode-theme", + "cd78e5e4e7bcf132a6f428ae0f32264bb1b729cf", + "MIT", + ), + }) +} + +fn github_dark() -> ThemeVariant { + variant(Seeds { + id: "github-dark", + family_id: "github", + name: "GitHub Dark", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#0d1117", + shell: "#010409", + raised: "#21262d", + card: "#161b22", + text: "#e6edf3", + muted: "#8b949e", + faint: "#6e7681", + accent: "#2f81f7", + danger: "#f85149", + warning: "#d29922", + success: "#3fb950", + terminal_background: "#0d1117", + ansi: [ + "#484f58", "#ff7b72", "#3fb950", "#d29922", "#58a6ff", "#bc8cff", "#39c5cf", "#b1bac4", + "#6e7681", "#ffa198", "#56d364", "#e3b341", "#79c0ff", "#d2a8ff", "#56d4dd", "#f0f6fc", + ], + syntax: [ + "#8b949e", "#ff7b72", "#a5d6ff", "#79c0ff", "#ffa657", "#d2a8ff", "#7ee787", "#e6edf3", + "#b1bac4", "#7ee787", "#ffa657", "#f85149", + ], + source: source( + "github-dark", + "vscode", + "https://github.com/primer/github-vscode-theme", + "cd78e5e4e7bcf132a6f428ae0f32264bb1b729cf", + "MIT", + ), + }) +} + +fn ayu_light() -> ThemeVariant { + variant(Seeds { + id: "ayu-light", + family_id: "ayu", + name: "Ayu Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#fcfcfc", + shell: "#f8f9fa", + raised: "#e6e9ed", + card: "#fafafa", + text: "#5c6166", + muted: "#828e9f", + faint: "#969da8", + accent: "#f29718", + danger: "#e65050", + warning: "#eba400", + success: "#6cbf43", + terminal_background: "#f8f9fa", + ansi: [ + "#000000", "#f06b6c", "#6cbf43", "#e7a100", "#21a1e2", "#a176cb", "#4abc96", "#c7c7c7", + "#686868", "#f07171", "#86b300", "#eba400", "#22a4e6", "#a37acc", "#4cbf99", "#d1d1d1", + ], + syntax: [ + "#adaeb1", "#fa8532", "#86b300", "#a37acc", "#55b4d4", "#f29718", "#f07171", "#5c6166", + "#828e9f", "#55b4d4", "#e59645", "#e65050", + ], + source: source( + "ayu-light", + "vscode", + "https://github.com/ayu-theme/vscode-ayu", + "444ef92911cb75c3933c8003e3a7c79b6b6c914f", + "MIT", + ), + }) +} + +fn ayu_dark() -> ThemeVariant { + variant(Seeds { + id: "ayu-dark", + family_id: "ayu", + name: "Ayu Dark", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#10141c", + shell: "#0d1017", + raised: "#1b1f29", + card: "#141821", + text: "#bfbdb6", + muted: "#8a9199", + faint: "#5a6673", + accent: "#e6b450", + danger: "#d95757", + warning: "#ffb454", + success: "#70bf56", + terminal_background: "#0d1017", + ansi: [ + "#1b1f29", "#f06b73", "#70bf56", "#fdb04c", "#4fbfff", "#d0a1ff", "#93e2c8", "#c7c7c7", + "#686868", "#f07178", "#aad94c", "#ffb454", "#59c2ff", "#d2a6ff", "#95e6cb", "#ffffff", + ], + syntax: [ + "#5a6673", "#ff8f40", "#aad94c", "#d2a6ff", "#39bae6", "#ffb454", "#f07178", "#bfbdb6", + "#8a9199", "#39bae6", "#e6c08a", "#d95757", + ], + source: source( + "ayu-dark", + "vscode", + "https://github.com/ayu-theme/vscode-ayu", + "444ef92911cb75c3933c8003e3a7c79b6b6c914f", + "MIT", + ), + }) +} + +fn ayu_mirage() -> ThemeVariant { + variant(Seeds { + id: "ayu-mirage", + family_id: "ayu", + name: "Ayu Mirage", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#242936", + shell: "#1f2430", + raised: "#343d4d", + card: "#282e3b", + text: "#cccac2", + muted: "#8a94a6", + faint: "#6e7c8f", + accent: "#ffcc66", + danger: "#ff6666", + warning: "#ffcc66", + success: "#87d96c", + terminal_background: "#1f2430", + ansi: [ + "#171b24", "#f28273", "#87d96c", "#fcca60", "#6acdff", "#ddbbff", "#93e2c8", "#c7c7c7", + "#686868", "#f28779", "#d5ff80", "#ffcd66", "#73d0ff", "#dfbfff", "#95e6cb", "#ffffff", + ], + syntax: [ + "#6e7c8f", "#ffa659", "#d5ff80", "#dfbfff", "#5ccfe6", "#ffcd66", "#f28779", "#cccac2", + "#8a94a6", "#5ccfe6", "#d9be98", "#ff6666", + ], + source: source( + "ayu-mirage", + "vscode", + "https://github.com/ayu-theme/vscode-ayu", + "444ef92911cb75c3933c8003e3a7c79b6b6c914f", + "MIT", + ), + }) +} + +fn gruvbox_light() -> ThemeVariant { + variant(Seeds { + id: "gruvbox-light", + family_id: "gruvbox", + name: "Gruvbox Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#fbf1c7", + shell: "#f2e5bc", + raised: "#d5c4a1", + card: "#f9f5d7", + text: "#3c3836", + muted: "#665c54", + faint: "#7c6f64", + accent: "#076678", + danger: "#9d0006", + warning: "#b57614", + success: "#79740e", + terminal_background: "#fbf1c7", + ansi: [ + "#ebdbb2", "#cc241d", "#98971a", "#d79921", "#458588", "#b16286", "#689d6a", "#7c6f64", + "#928374", "#9d0006", "#79740e", "#b57614", "#076678", "#8f3f71", "#427b58", "#3c3836", + ], + syntax: [ + "#928374", "#9d0006", "#79740e", "#8f3f71", "#b57614", "#076678", "#427b58", "#3c3836", + "#665c54", "#9d0006", "#af3a03", "#cc241d", + ], + source: source( + "gruvbox-light", + "vscode", + "https://github.com/jdinhify/vscode-theme-gruvbox", + "ca3b8ad203e84a884ca33fb84b5795cf43032709", + "MIT", + ), + }) +} + +fn gruvbox_dark() -> ThemeVariant { + variant(Seeds { + id: "gruvbox-dark", + family_id: "gruvbox", + name: "Gruvbox Dark", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#282828", + shell: "#1d2021", + raised: "#504945", + card: "#32302f", + text: "#ebdbb2", + muted: "#bdae93", + faint: "#928374", + accent: "#8ec07c", + danger: "#fb4934", + warning: "#fabd2f", + success: "#b8bb26", + terminal_background: "#282828", + ansi: [ + "#3c3836", "#cc241d", "#98971a", "#d79921", "#458588", "#b16286", "#689d6a", "#a89984", + "#928374", "#fb4934", "#b8bb26", "#fabd2f", "#83a598", "#d3869b", "#8ec07c", "#ebdbb2", + ], + syntax: [ + "#928374", "#fb4934", "#b8bb26", "#d3869b", "#fabd2f", "#83a598", "#8ec07c", "#ebdbb2", + "#bdae93", "#fb4934", "#fe8019", "#fb4934", + ], + source: source( + "gruvbox-dark", + "vscode", + "https://github.com/jdinhify/vscode-theme-gruvbox", + "ca3b8ad203e84a884ca33fb84b5795cf43032709", + "MIT", + ), + }) +} + +fn rose_pine_dawn() -> ThemeVariant { + variant(Seeds { + id: "rose-pine-dawn", + family_id: "rose-pine", + name: "Rosé Pine Dawn", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#faf4ed", + shell: "#f2e9e1", + raised: "#dfdad9", + card: "#fffaf3", + text: "#575279", + muted: "#797593", + faint: "#9893a5", + accent: "#907aa9", + danger: "#b4637a", + warning: "#ea9d34", + success: "#56949f", + terminal_background: "#faf4ed", + ansi: [ + "#f2e9e1", "#b4637a", "#286983", "#ea9d34", "#56949f", "#907aa9", "#d7827e", "#575279", + "#797593", "#b4637a", "#286983", "#ea9d34", "#56949f", "#907aa9", "#d7827e", "#575279", + ], + syntax: [ + "#9893a5", "#286983", "#ea9d34", "#d7827e", "#56949f", "#b4637a", "#56949f", "#d7827e", + "#797593", "#56949f", "#907aa9", "#b4637a", + ], + source: source( + "rose-pine-dawn", + "vscode", + "https://github.com/rose-pine/vscode", + "d8f5ebe8e096fa833e997c07eb7685ee1677a4ba", + "MIT", + ), + }) +} + +fn rose_pine_moon() -> ThemeVariant { + variant(Seeds { + id: "rose-pine-moon", + family_id: "rose-pine", + name: "Rosé Pine Moon", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#232136", + shell: "#1f1d2e", + raised: "#393552", + card: "#2a273f", + text: "#e0def4", + muted: "#908caa", + faint: "#6e6a86", + accent: "#c4a7e7", + danger: "#eb6f92", + warning: "#f6c177", + success: "#9ccfd8", + terminal_background: "#232136", + ansi: [ + "#393552", "#eb6f92", "#3e8fb0", "#f6c177", "#9ccfd8", "#c4a7e7", "#ea9a97", "#e0def4", + "#908caa", "#eb6f92", "#3e8fb0", "#f6c177", "#9ccfd8", "#c4a7e7", "#ea9a97", "#e0def4", + ], + syntax: [ + "#6e6a86", "#3e8fb0", "#f6c177", "#ea9a97", "#9ccfd8", "#eb6f92", "#9ccfd8", "#ea9a97", + "#908caa", "#9ccfd8", "#c4a7e7", "#eb6f92", + ], + source: source( + "rose-pine-moon", + "vscode", + "https://github.com/rose-pine/vscode", + "d8f5ebe8e096fa833e997c07eb7685ee1677a4ba", + "MIT", + ), + }) +} + +fn nord() -> ThemeVariant { + variant(Seeds { + id: "nord", + family_id: "nord", + name: "Nord", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#2e3440", + shell: "#292e39", + raised: "#434c5e", + card: "#3b4252", + text: "#d8dee9", + muted: "#aeb6c4", + faint: "#7f899b", + accent: "#88c0d0", + danger: "#bf616a", + warning: "#ebcb8b", + success: "#a3be8c", + terminal_background: "#2e3440", + ansi: [ + "#3b4252", "#bf616a", "#a3be8c", "#ebcb8b", "#81a1c1", "#b48ead", "#88c0d0", "#e5e9f0", + "#4c566a", "#bf616a", "#a3be8c", "#ebcb8b", "#81a1c1", "#b48ead", "#8fbcbb", "#eceff4", + ], + syntax: [ + "#616e88", "#81a1c1", "#a3be8c", "#b48ead", "#8fbcbb", "#88c0d0", "#d08770", "#d8dee9", + "#aeb6c4", "#81a1c1", "#8fbcbb", "#bf616a", + ], + source: source( + "nord", + "vscode", + "https://github.com/nordtheme/visual-studio-code", + "8ead09822c02d0d49d0f764104505e5a34d3689f", + "MIT", + ), + }) +} + +fn one_dark_pro() -> ThemeVariant { + variant(Seeds { + id: "one-dark-pro", + family_id: "one-dark-pro", + name: "One Dark Pro", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#282c34", + shell: "#21252b", + raised: "#2c313a", + card: "#21252b", + text: "#abb2bf", + muted: "#9da5b4", + faint: "#7f848e", + accent: "#528bff", + danger: "#e05561", + warning: "#d19a66", + success: "#8cc265", + terminal_background: "#282c34", + ansi: [ + "#3f4451", "#e05561", "#8cc265", "#d18f52", "#4aa5f0", "#c162de", "#42b3c2", "#d7dae0", + "#4f5666", "#ff616e", "#a5e075", "#f0a45d", "#4dc4ff", "#de73ff", "#4cd1e0", "#e6e6e6", + ], + syntax: [ + "#7f848e", "#c678dd", "#e06c75", "#c678dd", "#e5c07b", "#e5c07b", "#d19a66", "#abb2bf", + "#abb2bf", "#c678dd", "#56b6c2", "#e05561", + ], + source: source( + "one-dark-pro", + "vscode", + "https://github.com/Binaryify/OneDark-Pro", + "e6ccf638d5b69aa38cd1005edb0ee7ba7ef6fedc", + "MIT", + ), + }) +} + +fn atom_one_dark() -> ThemeVariant { + variant(Seeds { + id: "atom-one-dark", + family_id: "atom-one-dark", + name: "Atom One Dark", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#282c34", + shell: "#21252b", + raised: "#2c313a", + card: "#21252b", + text: "#abb2bf", + muted: "#9da5b4", + faint: "#5c6370", + accent: "#528bff", + danger: "#e06c75", + warning: "#d19a66", + success: "#98c379", + terminal_background: "#282c34", + ansi: [ + "#282c34", "#e06c75", "#98c379", "#e5c07b", "#61afef", "#c678dd", "#56b6c2", "#abb2bf", + "#5c6370", "#e06c75", "#98c379", "#e5c07b", "#61afef", "#c678dd", "#56b6c2", "#ffffff", + ], + syntax: [ + "#5c6370", "#c678dd", "#98c379", "#d19a66", "#e5c07b", "#61afef", "#56b6c2", "#e06c75", + "#abb2bf", "#e06c75", "#61afef", "#e06c75", + ], + source: source( + "atom-one-dark", + "vscode", + "https://github.com/akamud/vscode-theme-onedark", + "a8be970644982221f9b61fb1c4b3da74b4beab79", + "MIT", + ), + }) +} + +fn night_owl() -> ThemeVariant { + variant(Seeds { + id: "night-owl", + family_id: "night-owl", + name: "Night Owl", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#011627", + shell: "#01111d", + raised: "#0b253a", + card: "#071d2e", + text: "#d6deeb", + muted: "#8ca6ba", + faint: "#637777", + accent: "#82aaff", + danger: "#ef5350", + warning: "#ffeb95", + success: "#22da6e", + terminal_background: "#011627", + ansi: [ + "#011627", "#ef5350", "#22da6e", "#c5e478", "#82aaff", "#c792ea", "#21c7a8", "#ffffff", + "#575656", "#ef5350", "#22da6e", "#ffeb95", "#82aaff", "#c792ea", "#7fdbca", "#ffffff", + ], + syntax: [ + "#637777", "#82aaff", "#c5e478", "#f78c6c", "#ffcb8b", "#c5e478", "#bec5d4", "#d7dbe0", + "#82aaff", "#7fdbca", "#f78c6c", "#ef5350", + ], + source: source( + "night-owl", + "vscode", + "https://github.com/sdras/night-owl-vscode-theme", + "cc291eba7976b20d7c66bde6883c27b902196b07", + "MIT", + ), + }) +} + +fn night_owl_light() -> ThemeVariant { + variant(Seeds { + id: "night-owl-light", + family_id: "night-owl", + name: "Night Owl Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#fbfbfb", + shell: "#f0f0f0", + raised: "#d3e8f8", + card: "#ffffff", + text: "#403f53", + muted: "#66657a", + faint: "#7a8297", + accent: "#4876d6", + danger: "#de3d3b", + warning: "#a67d00", + success: "#08916a", + terminal_background: "#f6f6f6", + ansi: [ + "#403f53", "#de3d3b", "#08916a", "#e0af02", "#288ed7", "#d6438a", "#2aa298", "#93a1a1", + "#403f53", "#de3d3b", "#08916a", "#daaa01", "#288ed7", "#d6438a", "#2aa298", "#403f53", + ], + syntax: [ + "#6f7896", "#4876d6", "#0c8f75", "#aa0982", "#111111", "#4876d6", "#111111", "#403f53", + "#4876d6", "#111111", "#aa0982", "#de3d3b", + ], + source: source( + "night-owl-light", + "vscode", + "https://github.com/sdras/night-owl-vscode-theme", + "cc291eba7976b20d7c66bde6883c27b902196b07", + "MIT", + ), + }) +} + +fn winter_dark_blue() -> ThemeVariant { + variant(Seeds { + id: "winter-dark-blue", + family_id: "winter-is-coming", + name: "Winter is Coming Dark Blue", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#011627", + shell: "#01111d", + raised: "#0b253a", + card: "#071d2e", + text: "#d6deeb", + muted: "#8ca6ba", + faint: "#5f7e97", + accent: "#219fd5", + danger: "#ef5350", + warning: "#ffca28", + success: "#22da6e", + terminal_background: "#011627", + ansi: [ + "#011627", "#ef5350", "#22da6e", "#f7ecb5", "#219fd5", "#c792ea", "#80cbc4", "#d6deeb", + "#5f7e97", "#ef9a9a", "#addb67", "#ffcb6b", "#82aaff", "#c792ea", "#7fdbca", "#ffffff", + ], + syntax: [ + "#8095a8", "#c792ea", "#78bd65", "#8dec95", "#d29ffc", "#87aff4", "#7fdbca", "#cbcdd2", + "#4fb4d8", "#6dbdfa", "#f7ecb5", "#ef5350", + ], + source: source( + "winter-dark-blue", + "vscode", + "https://github.com/johnpapa/vscode-winteriscoming", + "260547834cb6ac37dd5b8bb5842cc1c8d3164946", + "MIT", + ), + }) +} + +fn winter_light() -> ThemeVariant { + variant(Seeds { + id: "winter-light", + family_id: "winter-is-coming", + name: "Winter is Coming Light", + appearance: Appearance::Light, + treatment: SurfaceTreatment::Opaque, + background: "#ffffff", + shell: "#f3f3f3", + raised: "#e5e5e5", + card: "#ffffff", + text: "#1857a4", + muted: "#62626a", + faint: "#66768a", + accent: "#2f86d2", + danger: "#de3d3b", + warning: "#9b6a00", + success: "#08916a", + terminal_background: "#ffffff", + ansi: [ + "#011627", "#de3d3b", "#08916a", "#c5a332", "#236ebf", "#7c4dff", "#0097a7", "#7e8993", + "#403f53", "#f76c6c", "#49d0b0", "#e7c244", "#4e8cdf", "#b15a91", "#00bcd4", "#403f53", + ], + syntax: [ + "#357b42", "#7942a8", "#87429a", "#174781", "#0444ac", "#b1108e", "#207b76", "#224555", + "#4f7aa0", "#0444ac", "#b46a0f", "#c73532", + ], + source: source( + "winter-light", + "vscode", + "https://github.com/johnpapa/vscode-winteriscoming", + "260547834cb6ac37dd5b8bb5842cc1c8d3164946", + "MIT", + ), + }) +} + +fn palenight() -> ThemeVariant { + variant(Seeds { + id: "palenight", + family_id: "palenight", + name: "Palenight", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#292d3e", + shell: "#232635", + raised: "#34384c", + card: "#292d3e", + text: "#eeffff", + muted: "#a6accd", + faint: "#697098", + accent: "#82aaff", + danger: "#ff5572", + warning: "#ffcb6b", + success: "#c3e88d", + terminal_background: "#292d3e", + ansi: [ + "#676e95", "#ff5572", "#a9c77d", "#ffcb6b", "#82aaff", "#c792ea", "#89ddff", "#ffffff", + "#676e95", "#ff5572", "#c3e88d", "#ffcb6b", "#82aaff", "#c792ea", "#89ddff", "#ffffff", + ], + syntax: [ + "#697098", "#c792ea", "#c3e88d", "#f78c6c", "#eeffff", "#ffcb6b", "#89ddff", "#bfc7d5", + "#82aaff", "#89ddff", "#7986e7", "#ff5572", + ], + source: source( + "palenight", + "vscode", + "https://github.com/whizkydee/vscode-palenight-theme", + "6291efaace90855abe3d79025327ca41b9a3138c", + "MIT", + ), + }) +} + +fn synthwave_84() -> ThemeVariant { + variant(Seeds { + id: "synthwave-84", + family_id: "synthwave-84", + name: "SynthWave '84", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#262335", + shell: "#241b2f", + raised: "#37294d", + card: "#2a2139", + text: "#ffffff", + muted: "#b8b5c6", + faint: "#848bbd", + accent: "#ff7edb", + danger: "#fe4450", + warning: "#fede5d", + success: "#72f1b8", + terminal_background: "#262335", + ansi: [ + "#242424", "#fe4450", "#72f1b8", "#f3e70f", "#03edf9", "#ff7edb", "#03edf9", "#d4d4d8", + "#52525b", "#fe4450", "#72f1b8", "#fede5d", "#03edf9", "#ff7edb", "#03edf9", "#fafafa", + ], + syntax: [ + "#848bbd", "#72f1b8", "#f97e72", "#2ee2fa", "#fe4450", "#72f1b8", "#2ee2fa", "#f8f8f2", + "#72f1b8", "#72f1b8", "#dd5500", "#fe4450", + ], + source: source( + "synthwave-84", + "vscode", + "https://github.com/robb0wen/synthwave-vscode", + "ecfa2fe1279f7233663fa3f98a96e6756000567b", + "MIT", + ), + }) +} + +fn shades_of_purple() -> ThemeVariant { + variant(Seeds { + id: "shades-of-purple", + family_id: "shades-of-purple", + name: "Shades of Purple", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#2d2b55", + shell: "#222244", + raised: "#393668", + card: "#1e1e3f", + text: "#ffffff", + muted: "#b8afea", + faint: "#8d84c7", + accent: "#fad000", + danger: "#ec3a37", + warning: "#fad000", + success: "#3ad900", + terminal_background: "#1e1e3f", + ansi: [ + "#000000", "#ec3a37", "#3ad900", "#fad000", "#7857fe", "#ff2c70", "#80fcff", "#ffffff", + "#5c5c61", "#ec3a37", "#3ad900", "#fad000", "#6943ff", "#fb94ff", "#80fcff", "#ffffff", + ], + syntax: [ + "#b362ff", "#ff628c", "#fb94ff", "#fad000", "#fb94ff", "#fad000", "#fad000", "#9effff", + "#fad000", "#fad000", "#ff9d00", "#ec3a37", + ], + source: source( + "shades-of-purple", + "vscode", + "https://github.com/ahmadawais/shades-of-purple-vscode", + "e8eb49f33e5db05ceba6677367b33ddb27ad821c", + "MIT", + ), + }) +} + +fn cobalt2() -> ThemeVariant { + variant(Seeds { + id: "cobalt2", + family_id: "cobalt2", + name: "Cobalt2", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#193549", + shell: "#15232d", + raised: "#20455e", + card: "#122738", + text: "#ffffff", + muted: "#b7c9d3", + faint: "#7da1b5", + accent: "#ffc600", + danger: "#ff628c", + warning: "#ffc600", + success: "#3ad900", + terminal_background: "#122738", + ansi: [ + "#000000", "#ff628c", "#3ad900", "#ffc600", "#0088ff", "#fb94ff", "#80fcff", "#ffffff", + "#0050a4", "#ff628c", "#3ad900", "#ffc600", "#0088ff", "#fb94ff", "#80fcff", "#ffffff", + ], + syntax: [ + "#0088ff", "#ff9d00", "#ffee80", "#ffc600", "#ff68b8", "#ffc600", "#9effff", "#ffffff", + "#ffee80", "#ffc600", "#ffb454", "#f44542", + ], + source: source( + "cobalt2", + "vscode", + "https://github.com/wesbos/cobalt2-vscode", + "c4e9574372b85afad1682ed0fdd1ac0411c62512", + "MIT", + ), + }) +} + +fn andromeda() -> ThemeVariant { + variant(Seeds { + id: "andromeda", + family_id: "andromeda", + name: "Andromeda", + appearance: Appearance::Dark, + treatment: SurfaceTreatment::Opaque, + background: "#23262e", + shell: "#1e2027", + raised: "#2d313b", + card: "#23262e", + text: "#d5ced9", + muted: "#a6a0aa", + faint: "#746f77", + accent: "#00e8c6", + danger: "#ee5d43", + warning: "#ff9f2e", + success: "#96e072", + terminal_background: "#23262e", + ansi: [ + "#242424", "#ee5d43", "#96e072", "#ffe66d", "#7cb7ff", "#ff00aa", "#00e8c6", "#d4d4d8", + "#52525b", "#ee5d43", "#96e072", "#ffe66d", "#7cb7ff", "#ff00aa", "#00e8c6", "#fafafa", + ], + syntax: [ + "#a0a1a7", "#ee5d43", "#96e072", "#f39c12", "#ffe66d", "#ffe66d", "#d5ced9", "#f39c12", + "#96e072", "#f92672", "#ee5d43", "#ee5d43", + ], + source: source( + "andromeda", + "vscode", + "https://github.com/EliverLara/Andromeda", + "d1abb48c69493000aa0133a32d594eb25e523d4f", + "MIT", + ), + }) +} diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs new file mode 100644 index 0000000000..aa7afcb17d --- /dev/null +++ b/crates/theme/src/lib.rs @@ -0,0 +1,802 @@ +//! Zeron's source-neutral theme domain model. +//! +//! Runtime code consumes complete [`ThemeVariant`] values. Import formats such +//! as VS Code are deliberately isolated in [`vscode`], so a component never +//! needs to understand a workbench color id or TextMate scope. + +mod builtins; +mod library; +pub mod vscode; + +use std::collections::{BTreeMap, HashSet}; +use std::fmt; +use std::str::FromStr; +use std::sync::{OnceLock, RwLock}; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +pub use builtins::builtin_registry; +pub use library::{ + CustomThemeEntry, CustomThemeLibrary, CustomThemeSource, CustomThemeStatus, InstallMode, +}; + +fn custom_families() -> &'static RwLock> { + static CUSTOM: OnceLock>> = OnceLock::new(); + CUSTOM.get_or_init(|| RwLock::new(Vec::new())) +} + +/// Replace the process-wide custom portion of the runtime registry. +/// +/// The UI calls this after loading or mutating the durable theme library. The +/// returned registry remains source-neutral: renderers still see only resolved +/// families and variants. +pub fn replace_custom_families(families: Vec) { + *custom_families() + .write() + .expect("custom theme registry lock was poisoned") = families; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Appearance { + #[default] + Dark, + Light, +} + +impl Appearance { + pub const ALL: [Self; 2] = [Self::Light, Self::Dark]; + + pub fn is_dark(self) -> bool { + matches!(self, Self::Dark) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SurfaceTreatment { + #[default] + Opaque, + Frosted, +} + +/// The device-local policy applied to a theme variant's recommended surface +/// treatment. This is deliberately independent from theme and accent choices. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SurfacePreference { + #[default] + ThemeDefault, + Frosted, + Opaque, +} + +impl SurfacePreference { + pub const ALL: [Self; 3] = [Self::ThemeDefault, Self::Frosted, Self::Opaque]; + + pub fn resolve(self, recommended: SurfaceTreatment) -> SurfaceTreatment { + match self { + Self::ThemeDefault => recommended, + Self::Frosted => SurfaceTreatment::Frosted, + Self::Opaque => SurfaceTreatment::Opaque, + } + } +} + +/// A color serialized as `#rrggbb` or `#rrggbbaa`. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct Color { + pub r: u8, + pub g: u8, + pub b: u8, + pub a: u8, +} + +impl Color { + pub const BLACK: Self = Self::rgb(0, 0, 0); + pub const WHITE: Self = Self::rgb(255, 255, 255); + + pub const fn rgb(r: u8, g: u8, b: u8) -> Self { + Self { r, g, b, a: 255 } + } + + pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { + Self { r, g, b, a } + } + + pub fn with_alpha(self, alpha: f32) -> Self { + Self { + a: (alpha.clamp(0.0, 1.0) * 255.0).round() as u8, + ..self + } + } + + pub fn blend_over(self, background: Self) -> Self { + let alpha = self.a as f32 / 255.0; + let blend = |front: u8, back: u8| { + (front as f32 * alpha + back as f32 * (1.0 - alpha)).round() as u8 + }; + Self::rgb( + blend(self.r, background.r), + blend(self.g, background.g), + blend(self.b, background.b), + ) + } + + pub fn mix(self, other: Self, amount: f32) -> Self { + let amount = amount.clamp(0.0, 1.0); + let mix = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * amount).round() as u8; + Self::rgba( + mix(self.r, other.r), + mix(self.g, other.g), + mix(self.b, other.b), + mix(self.a, other.a), + ) + } + + pub fn contrast(self, background: Self) -> f32 { + let foreground = if self.a == 255 { + self + } else { + self.blend_over(background) + }; + let (a, b) = (foreground.luminance(), background.luminance()); + (a.max(b) + 0.05) / (a.min(b) + 0.05) + } + + pub fn best_on_color(self) -> Self { + if Self::WHITE.contrast(self) >= Self::BLACK.contrast(self) { + Self::WHITE + } else { + Self::BLACK + } + } + + /// Move toward black or white until the requested contrast is met. + pub fn ensure_contrast(self, background: Self, minimum: f32) -> Self { + if self.contrast(background) >= minimum { + return self; + } + let target = if Self::BLACK.contrast(background) >= Self::WHITE.contrast(background) { + Self::BLACK + } else { + Self::WHITE + }; + for step in 1..=20 { + let candidate = self.mix(target, step as f32 / 20.0); + if candidate.contrast(background) >= minimum { + return candidate; + } + } + target + } + + fn luminance(self) -> f32 { + let linear = |channel: u8| { + let value = channel as f32 / 255.0; + if value <= 0.04045 { + value / 12.92 + } else { + ((value + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * linear(self.r) + 0.7152 * linear(self.g) + 0.0722 * linear(self.b) + } +} + +impl fmt::Debug for Color { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self) + } +} + +impl fmt::Display for Color { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.a == 255 { + write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b) + } else { + write!( + f, + "#{:02x}{:02x}{:02x}{:02x}", + self.r, self.g, self.b, self.a + ) + } + } +} + +impl FromStr for Color { + type Err = ColorParseError; + + fn from_str(value: &str) -> Result { + let value = value.trim().strip_prefix('#').ok_or(ColorParseError)?; + let expand = |c: u8| (c << 4) | c; + let nibble = |c: u8| match c { + b'0'..=b'9' => Ok(c - b'0'), + b'a'..=b'f' => Ok(c - b'a' + 10), + b'A'..=b'F' => Ok(c - b'A' + 10), + _ => Err(ColorParseError), + }; + let pair = |bytes: &[u8]| -> Result { + Ok((nibble(bytes[0])? << 4) | nibble(bytes[1])?) + }; + let bytes = value.as_bytes(); + match bytes.len() { + 3 => Ok(Self::rgb( + expand(nibble(bytes[0])?), + expand(nibble(bytes[1])?), + expand(nibble(bytes[2])?), + )), + 4 => Ok(Self::rgba( + expand(nibble(bytes[0])?), + expand(nibble(bytes[1])?), + expand(nibble(bytes[2])?), + expand(nibble(bytes[3])?), + )), + 6 => Ok(Self::rgb( + pair(&bytes[0..2])?, + pair(&bytes[2..4])?, + pair(&bytes[4..6])?, + )), + 8 => Ok(Self::rgba( + pair(&bytes[0..2])?, + pair(&bytes[2..4])?, + pair(&bytes[4..6])?, + pair(&bytes[6..8])?, + )), + _ => Err(ColorParseError), + } + } +} + +impl Serialize for Color { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.to_string()) + } +} + +impl<'de> Deserialize<'de> for Color { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + String::deserialize(deserializer)? + .parse() + .map_err(serde::de::Error::custom) + } +} + +#[derive(Debug, Clone, Copy, thiserror::Error)] +#[error("expected a CSS hex color (#rgb, #rgba, #rrggbb, or #rrggbbaa)")] +pub struct ColorParseError; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AccentPreset { + #[default] + Zeron, + Orange, + Amber, + Green, + Cyan, + Blue, + Pink, +} + +impl AccentPreset { + pub const ALL: [Self; 7] = [ + Self::Zeron, + Self::Orange, + Self::Amber, + Self::Green, + Self::Cyan, + Self::Blue, + Self::Pink, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::Zeron => "Zeron", + Self::Orange => "Orange", + Self::Amber => "Amber", + Self::Green => "Green", + Self::Cyan => "Cyan", + Self::Blue => "Blue", + Self::Pink => "Pink", + } + } + + pub fn color(self, appearance: Appearance) -> Color { + let (dark, light) = match self { + Self::Zeron => ("#8b7cf6", "#5b43e8"), + Self::Orange => ("#fb923c", "#c2410c"), + Self::Amber => ("#fbbf24", "#a16207"), + Self::Green => ("#4ade80", "#15803d"), + Self::Cyan => ("#22d3ee", "#0e7490"), + Self::Blue => ("#60a5fa", "#2563eb"), + Self::Pink => ("#f472b6", "#be185d"), + }; + if appearance.is_dark() { dark } else { light } + .parse() + .expect("built-in accent colors are valid") + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AccentSelection { + #[default] + ThemeDefault, + Preset(AccentPreset), +} + +impl AccentSelection { + pub fn label(self) -> &'static str { + match self { + Self::ThemeDefault => "Theme default", + Self::Preset(preset) => preset.label(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct AccentRoles { + pub primary: Color, + pub strong: Color, + pub wash: Color, + pub on: Color, + pub selection: Color, + pub caret: Color, + pub activity: Color, + pub glyph: [Color; 3], +} + +impl AccentRoles { + pub fn derive(primary: Color, appearance: Appearance, background: Color) -> Self { + let primary = primary.ensure_contrast(background, 3.0); + let on = primary.best_on_color(); + let mut strong = primary; + if on.contrast(strong) < 4.5 { + strong = strong.ensure_contrast(on, 4.5); + } + let light = primary.mix( + if appearance.is_dark() { + Color::WHITE + } else { + background + }, + if appearance.is_dark() { 0.28 } else { 0.18 }, + ); + let deep = primary.mix( + if appearance.is_dark() { + Color::BLACK + } else { + Color::BLACK + }, + if appearance.is_dark() { 0.18 } else { 0.26 }, + ); + Self { + primary, + strong, + wash: primary.with_alpha(if appearance.is_dark() { 0.22 } else { 0.12 }), + on, + selection: primary.with_alpha(if appearance.is_dark() { 0.35 } else { 0.24 }), + caret: primary, + activity: primary, + glyph: [light, primary, deep], + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThemeSelection { + pub light: String, + pub dark: String, +} + +impl Default for ThemeSelection { + fn default() -> Self { + Self { + light: "zeron-light".into(), + dark: "zeron-dark".into(), + } + } +} + +impl ThemeSelection { + pub fn variant_id(&self, appearance: Appearance) -> &str { + if appearance.is_dark() { + &self.dark + } else { + &self.light + } + } + + pub fn set_variant(&mut self, appearance: Appearance, id: impl Into) { + if appearance.is_dark() { + self.dark = id.into(); + } else { + self.light = id.into(); + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThemeSource { + pub format: String, + pub url: String, + pub revision: String, + pub license: String, + pub asset_hash: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThemeColors { + pub background: Color, + pub shell: Color, + pub raised: Color, + pub card: Color, + pub dialog: Color, + pub overlay: Color, + pub hover: Color, + pub active: Color, + pub border: Color, + pub border_strong: Color, + pub text: Color, + pub text_muted: Color, + pub text_faint: Color, + pub solid: Color, + pub on_solid: Color, + pub danger: Color, + pub danger_muted: Color, + pub warning: Color, + pub warning_muted: Color, + pub success: Color, + pub success_muted: Color, + pub input: Color, + pub cursor: Color, + pub diff_add: Color, + pub diff_delete: Color, + pub diff_hunk: Color, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TerminalPalette { + pub background: Color, + pub foreground: Color, + pub selection: Color, + pub ansi: [Color; 16], +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThemeVariant { + pub id: String, + pub family_id: String, + pub name: String, + pub appearance: Appearance, + /// The author's recommended treatment. Runtime applies the user's + /// [`SurfacePreference`] before components consume the variant. + #[serde(alias = "surfaceTreatment")] + pub recommended_surface_treatment: SurfaceTreatment, + pub colors: ThemeColors, + pub accent: AccentRoles, + pub syntax: BTreeMap, + pub terminal: TerminalPalette, + pub source: ThemeSource, +} + +impl ThemeVariant { + pub fn accent_for(&self, selection: AccentSelection) -> AccentRoles { + match selection { + AccentSelection::ThemeDefault => self.accent, + AccentSelection::Preset(preset) => AccentRoles::derive( + preset.color(self.appearance), + self.appearance, + self.colors.background, + ), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ThemeFamily { + pub id: String, + pub name: String, + pub variants: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ThemeRegistry { + pub families: Vec, +} + +impl ThemeRegistry { + pub fn builtin() -> &'static Self { + builtin_registry() + } + + /// Built-ins plus the currently installed custom families. + pub fn active() -> Self { + let mut families = Self::builtin().families.clone(); + families.extend( + custom_families() + .read() + .expect("custom theme registry lock was poisoned") + .iter() + .cloned(), + ); + Self { families } + } + + pub fn variant(&self, id: &str) -> Option<&ThemeVariant> { + self.families + .iter() + .flat_map(|family| &family.variants) + .find(|variant| variant.id == id) + } + + pub fn variants_for(&self, appearance: Appearance) -> impl Iterator { + self.families + .iter() + .flat_map(|family| &family.variants) + .filter(move |variant| variant.appearance == appearance) + } + + pub fn resolve(&self, selection: &ThemeSelection, appearance: Appearance) -> &ThemeVariant { + self.variant(selection.variant_id(appearance)) + .or_else(|| { + self.variant(if appearance.is_dark() { + "zeron-dark" + } else { + "zeron-light" + }) + }) + .expect("the built-in registry always contains both Zeron variants") + } + + pub fn validate(&self) -> Vec { + let mut issues = Vec::new(); + let mut ids = HashSet::new(); + for family in &self.families { + for variant in &family.variants { + if variant.id.trim().is_empty() || !ids.insert(&variant.id) { + issues.push(ValidationIssue::error( + &variant.id, + "variant id must be unique", + )); + } + validate_contrast( + &mut issues, + variant, + "text", + variant.colors.text, + variant.colors.background, + 4.5, + ); + validate_contrast( + &mut issues, + variant, + "muted text", + variant.colors.text_muted, + variant.colors.background, + 4.5, + ); + validate_contrast( + &mut issues, + variant, + "accent", + variant.accent.primary, + variant.colors.background, + 3.0, + ); + validate_contrast( + &mut issues, + variant, + "on-accent", + variant.accent.on, + variant.accent.strong, + 4.5, + ); + validate_contrast( + &mut issues, + variant, + "terminal foreground", + variant.terminal.foreground, + variant.terminal.background, + 4.5, + ); + if variant.source.url.is_empty() + || variant.source.revision.is_empty() + || variant.source.license.is_empty() + || variant.source.asset_hash.is_empty() + { + issues.push(ValidationIssue::error( + &variant.id, + "source provenance is incomplete", + )); + } + for (index, color) in variant.terminal.ansi.iter().enumerate().skip(1).take(6) { + if color.contrast(variant.terminal.background) < 3.0 { + issues.push(ValidationIssue::warning( + &variant.id, + format!("terminal ANSI slot {index} is below 3:1"), + )); + } + } + } + } + issues + } +} + +fn validate_contrast( + issues: &mut Vec, + variant: &ThemeVariant, + role: &str, + foreground: Color, + background: Color, + minimum: f32, +) { + let actual = foreground.contrast(background); + if actual < minimum { + issues.push(ValidationIssue::error( + &variant.id, + format!("{role} contrast is {actual:.2}:1; expected {minimum:.1}:1"), + )); + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ValidationSeverity { + Warning, + Error, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ValidationIssue { + pub variant_id: String, + pub severity: ValidationSeverity, + pub message: String, +} + +impl ValidationIssue { + fn error(variant_id: &str, message: impl Into) -> Self { + Self { + variant_id: variant_id.into(), + severity: ValidationSeverity::Error, + message: message.into(), + } + } + + fn warning(variant_id: &str, message: impl Into) -> Self { + Self { + variant_id: variant_id.into(), + severity: ValidationSeverity::Warning, + message: message.into(), + } + } +} + +/// Stable visual QA scenes every bundled variant must be reviewed against. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum VisualFixture { + Sidebar, + TranscriptMarkdown, + TranscriptCode, + Composer, + PickerPopover, + AppearanceSettings, + Diff, + Terminal, + EmptyState, + Dialog, +} + +impl VisualFixture { + pub const ALL: [Self; 10] = [ + Self::Sidebar, + Self::TranscriptMarkdown, + Self::TranscriptCode, + Self::Composer, + Self::PickerPopover, + Self::AppearanceSettings, + Self::Diff, + Self::Terminal, + Self::EmptyState, + Self::Dialog, + ]; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn colors_round_trip_all_supported_css_hex_lengths() { + for source in ["#abc", "#abcd", "#102030", "#10203040"] { + let color: Color = source.parse().unwrap(); + let json = serde_json::to_string(&color).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), color); + } + } + + #[test] + fn accent_overlay_meets_interaction_contrast() { + for appearance in Appearance::ALL { + let background = if appearance.is_dark() { + Color::rgb(6, 6, 6) + } else { + Color::WHITE + }; + for preset in AccentPreset::ALL { + let roles = AccentRoles::derive(preset.color(appearance), appearance, background); + assert!( + roles.primary.contrast(background) >= 3.0, + "{appearance:?} {preset:?}" + ); + assert!( + roles.on.contrast(roles.strong) >= 4.5, + "{appearance:?} {preset:?}" + ); + } + } + } + + #[test] + fn surface_preference_resolves_independently_from_theme_recommendation() { + assert_eq!( + SurfacePreference::ThemeDefault.resolve(SurfaceTreatment::Frosted), + SurfaceTreatment::Frosted + ); + assert_eq!( + SurfacePreference::ThemeDefault.resolve(SurfaceTreatment::Opaque), + SurfaceTreatment::Opaque + ); + for recommended in [SurfaceTreatment::Frosted, SurfaceTreatment::Opaque] { + assert_eq!( + SurfacePreference::Frosted.resolve(recommended), + SurfaceTreatment::Frosted + ); + assert_eq!( + SurfacePreference::Opaque.resolve(recommended), + SurfaceTreatment::Opaque + ); + } + } + + #[test] + fn builtins_have_complete_provenance_and_no_validation_errors() { + let registry = ThemeRegistry::builtin(); + assert_eq!(registry.families.len(), 19); + assert!(registry.variant("zeron-light").is_some()); + assert!(registry.variant("zeron-dark").is_some()); + let errors: Vec<_> = registry + .validate() + .into_iter() + .filter(|issue| issue.severity == ValidationSeverity::Error) + .collect(); + assert!(errors.is_empty(), "{errors:#?}"); + } + + #[test] + fn visual_fixture_matrix_covers_every_variant_and_scene() { + let registry = ThemeRegistry::builtin(); + let variants = registry + .families + .iter() + .map(|family| family.variants.len()) + .sum::(); + assert_eq!(variants, 30); + assert_eq!(variants * VisualFixture::ALL.len(), 300); + } +} diff --git a/crates/theme/src/library.rs b/crates/theme/src/library.rs new file mode 100644 index 0000000000..d72e5746ad --- /dev/null +++ b/crates/theme/src/library.rs @@ -0,0 +1,419 @@ +use std::collections::{BTreeMap, HashSet}; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; + +use crate::vscode::{ + CompileOptions, DetectedThemeSource, ImportReport, SourceCompilation, compile_source, +}; +use crate::{ThemeFamily, replace_custom_families}; + +const LIBRARY_FILE: &str = "theme-library.json"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InstallMode { + Snapshot, + Link, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CustomThemeSource { + ImportedSnapshot { imported_from: Option }, + LinkedFile { path: PathBuf }, + LinkedPackage { path: PathBuf }, +} + +impl CustomThemeSource { + pub fn path(&self) -> Option<&Path> { + match self { + Self::ImportedSnapshot { imported_from } => imported_from.as_deref(), + Self::LinkedFile { path } | Self::LinkedPackage { path } => Some(path), + } + } + + pub fn is_linked(&self) -> bool { + matches!(self, Self::LinkedFile { .. } | Self::LinkedPackage { .. }) + } + + pub fn label(&self) -> &'static str { + match self { + Self::ImportedSnapshot { .. } => "Imported", + Self::LinkedFile { .. } => "Linked file", + Self::LinkedPackage { .. } => "Linked package", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CustomThemeStatus { + Ready, + Warning { message: String }, +} + +impl Default for CustomThemeStatus { + fn default() -> Self { + Self::Ready + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomThemeEntry { + pub id: String, + pub name: String, + pub source: CustomThemeSource, + pub family: ThemeFamily, + pub reports: BTreeMap, + pub selected_variant_ids: Vec, + #[serde(default)] + pub status: CustomThemeStatus, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomThemeLibrary { + #[serde(default)] + pub entries: Vec, +} + +impl CustomThemeLibrary { + pub fn path(data_dir: &Path) -> PathBuf { + data_dir.join(LIBRARY_FILE) + } + + pub fn load(data_dir: &Path) -> Result { + let path = Self::path(data_dir); + let source = match fs::read_to_string(&path) { + Ok(source) => source, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()), + Err(error) => { + return Err(error).with_context(|| format!("could not read {}", path.display())); + } + }; + serde_json::from_str(&source).with_context(|| format!("could not parse {}", path.display())) + } + + pub fn save(&self, data_dir: &Path) -> Result<()> { + fs::create_dir_all(data_dir) + .with_context(|| format!("could not create {}", data_dir.display()))?; + let path = Self::path(data_dir); + let temporary = path.with_extension("json.tmp"); + fs::write(&temporary, serde_json::to_vec_pretty(self)?) + .with_context(|| format!("could not write {}", temporary.display()))?; + fs::rename(&temporary, &path) + .with_context(|| format!("could not replace {}", path.display()))?; + Ok(()) + } + + pub fn install_runtime(&self) { + replace_custom_families( + self.entries + .iter() + .map(|entry| entry.family.clone()) + .collect(), + ); + } + + pub fn entry(&self, id: &str) -> Option<&CustomThemeEntry> { + self.entries.iter().find(|entry| entry.id == id) + } + + pub fn compile(path: &Path, family_id: &str, family_name: &str) -> Result { + compile_source( + path, + CompileOptions { + family_id: family_id.into(), + family_name: family_name.into(), + source_url: path.display().to_string(), + revision: "local".into(), + license: "User supplied".into(), + }, + ) + } + + pub fn install( + &mut self, + compilation: SourceCompilation, + selected_variant_ids: &[String], + mode: InstallMode, + ) -> Result { + let selected: HashSet<_> = selected_variant_ids.iter().collect(); + let mut family = compilation.family; + family + .variants + .retain(|variant| selected.is_empty() || selected.contains(&variant.id)); + if family.variants.is_empty() { + bail!("select at least one successfully compiled variant"); + } + let entry_id = unique_id( + &family.id, + self.entries.iter().map(|entry| entry.id.as_str()), + ); + let old_variant_ids = family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect::>(); + if entry_id != family.id { + rekey_family(&mut family, &entry_id); + } + let selected_variant_ids = family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect::>(); + let mut reports = BTreeMap::new(); + for (old_id, variant) in old_variant_ids.iter().zip(&family.variants) { + if let Some(report) = compilation.reports.get(old_id) { + reports.insert(variant.id.clone(), report.clone()); + } + } + let path = compilation.path; + let source = match (mode, compilation.source_kind) { + (InstallMode::Snapshot, _) => CustomThemeSource::ImportedSnapshot { + imported_from: Some(path), + }, + (InstallMode::Link, DetectedThemeSource::File) => { + CustomThemeSource::LinkedFile { path } + } + (InstallMode::Link, DetectedThemeSource::Package) => { + CustomThemeSource::LinkedPackage { path } + } + }; + self.entries.push(CustomThemeEntry { + id: entry_id.clone(), + name: family.name.clone(), + source, + family, + reports, + selected_variant_ids, + status: CustomThemeStatus::Ready, + }); + Ok(entry_id) + } + + /// Reload a linked source. The existing compiled family is only replaced + /// after a complete successful compile, preserving the last known good + /// version on any source error. + pub fn reload(&mut self, id: &str) -> Result<()> { + let entry = self + .entries + .iter_mut() + .find(|entry| entry.id == id) + .ok_or_else(|| anyhow!("unknown custom theme `{id}`"))?; + let path = match &entry.source { + CustomThemeSource::LinkedFile { path } | CustomThemeSource::LinkedPackage { path } => { + path.clone() + } + CustomThemeSource::ImportedSnapshot { .. } => bail!("imported snapshots cannot reload"), + }; + let compilation = match Self::compile(&path, &entry.id, &entry.name) { + Ok(compilation) if compilation.failures.is_empty() => compilation, + Ok(compilation) => { + let message = compilation + .failures + .iter() + .map(|failure| format!("{}: {}", failure.name, failure.message)) + .collect::>() + .join("; "); + entry.status = CustomThemeStatus::Warning { + message: message.clone(), + }; + return Err(anyhow!(message)); + } + Err(error) => { + entry.status = CustomThemeStatus::Warning { + message: error.to_string(), + }; + return Err(error); + } + }; + let wanted: HashSet<_> = entry.selected_variant_ids.iter().cloned().collect(); + let mut family = compilation.family; + family + .variants + .retain(|variant| wanted.contains(&variant.id)); + if family.variants.is_empty() { + let message = "the linked source no longer contains any selected variants".to_string(); + entry.status = CustomThemeStatus::Warning { + message: message.clone(), + }; + bail!(message); + } + entry.family = family; + entry.reports = compilation + .reports + .into_iter() + .filter(|(variant_id, _)| wanted.contains(variant_id)) + .collect(); + entry.status = CustomThemeStatus::Ready; + Ok(()) + } + + pub fn unlink(&mut self, id: &str) -> Result<()> { + let entry = self + .entries + .iter_mut() + .find(|entry| entry.id == id) + .ok_or_else(|| anyhow!("unknown custom theme `{id}`"))?; + let imported_from = entry.source.path().map(Path::to_path_buf); + entry.source = CustomThemeSource::ImportedSnapshot { imported_from }; + entry.status = CustomThemeStatus::Ready; + Ok(()) + } + + pub fn duplicate_as_snapshot(&mut self, id: &str) -> Result { + let original = self + .entries + .iter() + .find(|entry| entry.id == id) + .cloned() + .ok_or_else(|| anyhow!("unknown custom theme `{id}`"))?; + let new_id = unique_id( + &format!("{}-copy", original.id), + self.entries.iter().map(|entry| entry.id.as_str()), + ); + let mut duplicate = original; + duplicate.id = new_id.clone(); + duplicate.name = format!("{} Copy", duplicate.name); + let old_variant_ids = duplicate + .family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect::>(); + rekey_family(&mut duplicate.family, &new_id); + duplicate.reports = old_variant_ids + .iter() + .zip(&duplicate.family.variants) + .filter_map(|(old_id, variant)| { + duplicate + .reports + .get(old_id) + .cloned() + .map(|report| (variant.id.clone(), report)) + }) + .collect(); + duplicate.selected_variant_ids = duplicate + .family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect(); + duplicate.source = CustomThemeSource::ImportedSnapshot { + imported_from: duplicate.source.path().map(Path::to_path_buf), + }; + duplicate.status = CustomThemeStatus::Ready; + self.entries.push(duplicate); + Ok(new_id) + } + + pub fn remove(&mut self, id: &str) -> bool { + let before = self.entries.len(); + self.entries.retain(|entry| entry.id != id); + self.entries.len() != before + } +} + +fn unique_id<'a>(base: &str, existing: impl Iterator) -> String { + let existing = existing.collect::>(); + if !existing.contains(base) { + return base.into(); + } + (2..) + .map(|suffix| format!("{base}-{suffix}")) + .find(|candidate| !existing.contains(candidate.as_str())) + .expect("an unused numeric suffix always exists") +} + +fn rekey_family(family: &mut ThemeFamily, new_id: &str) { + let old_id = family.id.clone(); + family.id = new_id.into(); + for variant in &mut family.variants { + variant.family_id = new_id.into(); + variant.id = variant + .id + .strip_prefix(&old_id) + .map(|suffix| format!("{new_id}{suffix}")) + .unwrap_or_else(|| format!("{new_id}-{}", variant.id)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn package(dir: &Path) { + fs::create_dir_all(dir.join("themes")).unwrap(); + fs::write( + dir.join("package.json"), + r#"{ + "displayName": "Test Family", + "contributes": { "themes": [ + { "label": "Test Light", "uiTheme": "vs", "path": "./themes/light.json" }, + { "label": "Test Dark", "uiTheme": "vs-dark", "path": "./themes/dark.json" } + ] } + }"#, + ) + .unwrap(); + fs::write( + dir.join("themes/light.json"), + r##"{"colors":{"editor.background":"#ffffff","foreground":"#222222","focusBorder":"#0066cc"}}"##, + ) + .unwrap(); + fs::write( + dir.join("themes/dark.json"), + r##"{"colors":{"editor.background":"#111111","foreground":"#eeeeee","focusBorder":"#66aaff"}}"##, + ) + .unwrap(); + } + + #[test] + fn linked_reload_keeps_last_known_good_on_failure() { + let dir = tempfile::tempdir().unwrap(); + package(dir.path()); + let compiled = + CustomThemeLibrary::compile(dir.path(), "test-family", "Test Family").unwrap(); + let mut library = CustomThemeLibrary::default(); + let id = library.install(compiled, &[], InstallMode::Link).unwrap(); + let previous = library.entry(&id).unwrap().family.clone(); + fs::write(dir.path().join("themes/dark.json"), "not json").unwrap(); + + assert!(library.reload(&id).is_err()); + let entry = library.entry(&id).unwrap(); + assert_eq!(entry.family, previous); + assert!(matches!(entry.status, CustomThemeStatus::Warning { .. })); + } + + #[test] + fn snapshot_round_trips_and_duplicate_gets_independent_ids() { + let source = tempfile::tempdir().unwrap(); + package(source.path()); + let compiled = + CustomThemeLibrary::compile(source.path(), "test-family", "Test Family").unwrap(); + let mut library = CustomThemeLibrary::default(); + let id = library + .install(compiled, &[], InstallMode::Snapshot) + .unwrap(); + let copy = library.duplicate_as_snapshot(&id).unwrap(); + assert_ne!(id, copy); + assert!( + library + .entry(©) + .unwrap() + .family + .variants + .iter() + .all(|variant| variant.family_id == copy) + ); + + let data = tempfile::tempdir().unwrap(); + library.save(data.path()).unwrap(); + assert_eq!(CustomThemeLibrary::load(data.path()).unwrap(), library); + } +} diff --git a/crates/theme/src/vscode.rs b/crates/theme/src/vscode.rs new file mode 100644 index 0000000000..b057f5d38e --- /dev/null +++ b/crates/theme/src/vscode.rs @@ -0,0 +1,1080 @@ +//! Offline VS Code theme normalization and conversion. +//! +//! Conversion is intentionally deterministic and report-producing. Its output +//! is a curation draft, never a runtime dependency on a VSIX or remote source. + +use std::collections::{BTreeMap, HashSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +use crate::{ + AccentRoles, Appearance, Color, SurfaceTreatment, ThemeFamily, ThemeRegistry, ThemeSource, + ThemeVariant, +}; + +#[derive(Debug, Clone)] +pub struct ImportOptions { + pub id: String, + pub family_id: String, + pub name: String, + pub appearance: Appearance, + pub source_url: String, + pub revision: String, + pub license: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportResult { + pub theme: ThemeVariant, + pub report: ImportReport, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportReport { + pub source_files: Vec, + pub source_hash: String, + pub mappings: Vec, + pub fallbacks: Vec, + pub dropped: Vec, + pub warnings: Vec, + pub accent_candidates: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportMapping { + pub zeron_role: String, + pub vscode_key: String, + pub value: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccentCandidate { + pub vscode_key: String, + pub value: String, +} + +#[derive(Debug, Clone, Default)] +struct NormalizedTheme { + colors: BTreeMap, + token_colors: Vec, + semantic_token_colors: BTreeMap, + files: Vec, +} + +#[derive(Debug, Clone, Default)] +struct TokenRule { + scopes: Vec, + foreground: Option, + font_style: Option, +} + +#[derive(Debug, Clone, Default)] +struct SemanticStyle { + foreground: Option, + font_style: Option, +} + +#[derive(Debug, Clone)] +pub struct CompileOptions { + pub family_id: String, + pub family_name: String, + pub source_url: String, + pub revision: String, + pub license: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum DetectedThemeSource { + File, + Package, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VariantFailure { + pub name: String, + pub path: PathBuf, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceCompilation { + pub path: PathBuf, + pub source_kind: DetectedThemeSource, + pub family: ThemeFamily, + pub reports: BTreeMap, + pub failures: Vec, +} + +/// Detect and compile either a single VS Code theme file or an extension +/// package. Package variants are isolated: one bad variant is reported without +/// hiding the valid variants that the user can still choose to import. +pub fn compile_source(path: &Path, options: CompileOptions) -> Result { + let path = path + .canonicalize() + .with_context(|| format!("could not resolve {}", path.display()))?; + let package_json = if path.is_dir() { + let candidate = path.join("package.json"); + candidate.exists().then_some(candidate) + } else if path.file_name().and_then(|name| name.to_str()) == Some("package.json") { + Some(path.clone()) + } else { + None + }; + + if let Some(package_json) = package_json { + return compile_package(&path, &package_json, options); + } + compile_single_file(path, options) +} + +fn compile_single_file(path: PathBuf, options: CompileOptions) -> Result { + let normalized = load_theme(&path, &mut Vec::new())?; + let appearance = detect_appearance(&path, None, &normalized); + let name = theme_declared_name(&path).unwrap_or_else(|| options.family_name.clone()); + let imported = convert( + normalized, + ImportOptions { + id: options.family_id.clone(), + family_id: options.family_id.clone(), + name, + appearance, + source_url: options.source_url, + revision: options.revision, + license: options.license, + }, + )?; + let reports = BTreeMap::from([(imported.theme.id.clone(), imported.report)]); + Ok(SourceCompilation { + path, + source_kind: DetectedThemeSource::File, + family: ThemeFamily { + id: options.family_id, + name: options.family_name, + variants: vec![imported.theme], + }, + reports, + failures: Vec::new(), + }) +} + +fn compile_package( + selected_path: &Path, + package_json: &Path, + options: CompileOptions, +) -> Result { + let source = fs::read_to_string(package_json) + .with_context(|| format!("could not read {}", package_json.display()))?; + let manifest: Value = json5::from_str(&source) + .with_context(|| format!("could not parse {}", package_json.display()))?; + let declarations = manifest + .pointer("/contributes/themes") + .and_then(Value::as_array) + .ok_or_else(|| { + anyhow!( + "{} does not declare contributes.themes", + package_json.display() + ) + })?; + if declarations.is_empty() { + bail!("{} declares no theme variants", package_json.display()); + } + let package_root = package_json + .parent() + .ok_or_else(|| anyhow!("{} has no parent directory", package_json.display()))?; + let family_name = manifest + .get("displayName") + .or_else(|| manifest.get("name")) + .and_then(Value::as_str) + .filter(|name| !name.trim().is_empty()) + .unwrap_or(&options.family_name) + .to_owned(); + let mut variants = Vec::new(); + let mut reports = BTreeMap::new(); + let mut failures = Vec::new(); + let mut used_ids = HashSet::new(); + for (index, declaration) in declarations.iter().enumerate() { + let label = declaration + .get("label") + .and_then(Value::as_str) + .filter(|label| !label.trim().is_empty()) + .map(str::to_owned) + .unwrap_or_else(|| format!("Variant {}", index + 1)); + let relative = match declaration.get("path").and_then(Value::as_str) { + Some(path) => path, + None => { + failures.push(VariantFailure { + name: label, + path: package_json.to_path_buf(), + message: "theme declaration has no path".into(), + }); + continue; + } + }; + let theme_path = package_root.join(relative); + let mut id = format!("{}-{}", options.family_id, slug(&label)); + if !used_ids.insert(id.clone()) { + id = format!("{id}-{}", index + 1); + used_ids.insert(id.clone()); + } + let result = (|| { + let normalized = load_theme(&theme_path, &mut Vec::new())?; + let appearance = detect_appearance( + &theme_path, + declaration.get("uiTheme").and_then(Value::as_str), + &normalized, + ); + convert( + normalized, + ImportOptions { + id: id.clone(), + family_id: options.family_id.clone(), + name: label.clone(), + appearance, + source_url: options.source_url.clone(), + revision: options.revision.clone(), + license: options.license.clone(), + }, + ) + })(); + match result { + Ok(imported) => { + reports.insert(imported.theme.id.clone(), imported.report); + variants.push(imported.theme); + } + Err(error) => failures.push(VariantFailure { + name: label, + path: theme_path, + message: error.to_string(), + }), + } + } + if variants.is_empty() { + let details = failures + .iter() + .map(|failure| format!("{}: {}", failure.name, failure.message)) + .collect::>() + .join("; "); + bail!("no package variants compiled successfully: {details}"); + } + Ok(SourceCompilation { + path: selected_path.to_path_buf(), + source_kind: DetectedThemeSource::Package, + family: ThemeFamily { + id: options.family_id, + name: family_name, + variants, + }, + reports, + failures, + }) +} + +fn theme_declared_name(path: &Path) -> Option { + let source = fs::read_to_string(path).ok()?; + let value: Value = json5::from_str(&source).ok()?; + value + .get("name") + .and_then(Value::as_str) + .filter(|name| !name.trim().is_empty()) + .map(str::to_owned) +} + +fn detect_appearance( + path: &Path, + ui_theme: Option<&str>, + normalized: &NormalizedTheme, +) -> Appearance { + if let Some(ui_theme) = ui_theme { + return if ui_theme.eq_ignore_ascii_case("vs") { + Appearance::Light + } else { + Appearance::Dark + }; + } + if let Ok(source) = fs::read_to_string(path) + && let Ok(value) = json5::from_str::(&source) + && let Some(kind) = value.get("type").and_then(Value::as_str) + { + if kind.eq_ignore_ascii_case("light") { + return Appearance::Light; + } + if kind.eq_ignore_ascii_case("dark") { + return Appearance::Dark; + } + } + normalized + .colors + .get("editor.background") + .and_then(|value| value.parse::().ok()) + .map(|background| { + if Color::BLACK.contrast(background) > Color::WHITE.contrast(background) { + Appearance::Light + } else { + Appearance::Dark + } + }) + .unwrap_or(Appearance::Dark) +} + +fn slug(value: &str) -> String { + let mut output = String::new(); + let mut separator = false; + for character in value.chars().flat_map(char::to_lowercase) { + if character.is_ascii_alphanumeric() { + if separator && !output.is_empty() { + output.push('-'); + } + separator = false; + output.push(character); + } else { + separator = true; + } + } + if output.is_empty() { + "theme".into() + } else { + output + } +} + +pub fn import_file(path: &Path, options: ImportOptions) -> Result { + let normalized = load_theme(path, &mut Vec::new())?; + convert(normalized, options) +} + +fn load_theme(path: &Path, stack: &mut Vec) -> Result { + let path = path + .canonicalize() + .with_context(|| format!("could not resolve {}", path.display()))?; + if stack.contains(&path) { + bail!("VS Code theme include cycle: {}", path.display()); + } + stack.push(path.clone()); + let source = + fs::read_to_string(&path).with_context(|| format!("could not read {}", path.display()))?; + let value: Value = json5::from_str(&source) + .with_context(|| format!("could not parse JSONC theme {}", path.display()))?; + let object = value + .as_object() + .ok_or_else(|| anyhow!("{} is not a JSON object", path.display()))?; + + let mut theme = if let Some(include) = object.get("include").and_then(Value::as_str) { + let include_path = resolve_relative(&path, include); + load_theme(&include_path, stack)? + } else { + NormalizedTheme::default() + }; + theme.files.push(path.clone()); + + if let Some(colors) = object.get("colors").and_then(Value::as_object) { + for (key, value) in colors { + if let Some(value) = value.as_str() { + theme.colors.insert(key.clone(), value.into()); + } + } + } + + if let Some(token_colors) = object.get("tokenColors") { + match token_colors { + Value::Array(rules) => theme.token_colors.extend(parse_token_rules(rules)), + Value::String(relative) => { + let token_path = resolve_relative(&path, relative); + theme.files.push(token_path.clone()); + theme.token_colors.extend(load_token_file(&token_path)?); + } + _ => {} + } + } + + if let Some(semantic) = object.get("semanticTokenColors").and_then(Value::as_object) { + for (selector, style) in semantic { + theme + .semantic_token_colors + .insert(selector.clone(), parse_semantic_style(style)); + } + } + stack.pop(); + Ok(theme) +} + +fn resolve_relative(owner: &Path, relative: &str) -> PathBuf { + owner + .parent() + .unwrap_or_else(|| Path::new(".")) + .join(relative) +} + +fn parse_token_rules(values: &[Value]) -> Vec { + values + .iter() + .filter_map(|value| { + let object = value.as_object()?; + let scopes = match object.get("scope") { + Some(Value::String(scope)) => scope + .split(',') + .map(str::trim) + .filter(|scope| !scope.is_empty()) + .map(str::to_owned) + .collect(), + Some(Value::Array(scopes)) => scopes + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + _ => Vec::new(), + }; + let settings = object.get("settings")?.as_object()?; + Some(TokenRule { + scopes, + foreground: settings + .get("foreground") + .and_then(Value::as_str) + .map(str::to_owned), + font_style: settings + .get("fontStyle") + .and_then(Value::as_str) + .map(str::to_owned), + }) + }) + .collect() +} + +fn load_token_file(path: &Path) -> Result> { + let extension = path + .extension() + .and_then(|value| value.to_str()) + .unwrap_or_default(); + if extension.eq_ignore_ascii_case("tmTheme") || extension.eq_ignore_ascii_case("plist") { + return load_textmate_plist(path); + } + let source = fs::read_to_string(path) + .with_context(|| format!("could not read token file {}", path.display()))?; + let value: Value = json5::from_str(&source) + .with_context(|| format!("could not parse token file {}", path.display()))?; + let values = value + .as_array() + .or_else(|| value.get("tokenColors").and_then(Value::as_array)) + .ok_or_else(|| anyhow!("{} does not contain token rules", path.display()))?; + Ok(parse_token_rules(values)) +} + +fn load_textmate_plist(path: &Path) -> Result> { + let value = plist::Value::from_file(path) + .with_context(|| format!("could not parse TextMate plist {}", path.display()))?; + let settings = value + .as_dictionary() + .and_then(|dict| dict.get("settings")) + .and_then(plist::Value::as_array) + .ok_or_else(|| anyhow!("{} has no TextMate settings array", path.display()))?; + Ok(settings + .iter() + .filter_map(|value| { + let dict = value.as_dictionary()?; + let scopes = dict + .get("scope") + .and_then(plist::Value::as_string) + .map(|scope| { + scope + .split(',') + .map(str::trim) + .filter(|scope| !scope.is_empty()) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + let style = dict.get("settings")?.as_dictionary()?; + Some(TokenRule { + scopes, + foreground: style + .get("foreground") + .and_then(plist::Value::as_string) + .map(str::to_owned), + font_style: style + .get("fontStyle") + .and_then(plist::Value::as_string) + .map(str::to_owned), + }) + }) + .collect()) +} + +fn parse_semantic_style(value: &Value) -> SemanticStyle { + match value { + Value::String(foreground) => SemanticStyle { + foreground: Some(foreground.clone()), + font_style: None, + }, + Value::Object(style) => SemanticStyle { + foreground: style + .get("foreground") + .and_then(Value::as_str) + .map(str::to_owned), + font_style: style + .get("fontStyle") + .and_then(Value::as_str) + .map(str::to_owned), + }, + _ => SemanticStyle::default(), + } +} + +fn convert(theme: NormalizedTheme, options: ImportOptions) -> Result { + let registry = ThemeRegistry::builtin(); + let base_id = if options.appearance.is_dark() { + "zeron-dark" + } else { + "zeron-light" + }; + let mut output = registry + .variant(base_id) + .expect("Zeron base theme exists") + .clone(); + output.id = options.id.clone(); + output.family_id = options.family_id; + output.name = options.name; + output.appearance = options.appearance; + // VS Code themes are authored against a solid editor/workbench background. + // Keep that as their recommendation; users can independently force frost. + output.recommended_surface_treatment = SurfaceTreatment::Opaque; + + let mut report = ImportReport { + source_files: theme + .files + .iter() + .map(|path| path.display().to_string()) + .collect(), + ..ImportReport::default() + }; + report.fallbacks.push( + "surface treatment inferred as opaque because VS Code palettes target solid workbench backgrounds; the user's Zeron surface preference can override it" + .into(), + ); + macro_rules! apply { + ($role:expr, $keys:expr, $target:expr) => {{ + if let Some((key, value)) = first_color(&theme.colors, $keys, &mut report.warnings) { + *$target = value; + report.mappings.push(ImportMapping { + zeron_role: $role.into(), + vscode_key: key.into(), + value: value.to_string(), + }); + } else { + report.fallbacks.push(format!( + "{} retained the Zeron {} fallback", + $role, + if options.appearance.is_dark() { + "dark" + } else { + "light" + } + )); + } + }}; + } + + apply!( + "background", + &["editor.background"], + &mut output.colors.background + ); + apply!( + "shell", + &[ + "sideBar.background", + "activityBar.background", + "panel.background" + ], + &mut output.colors.shell + ); + apply!( + "raised", + &["list.hoverBackground", "input.background"], + &mut output.colors.raised + ); + apply!( + "card", + &["panel.background", "sideBar.background"], + &mut output.colors.card + ); + apply!( + "dialog", + &["editorWidget.background", "quickInput.background"], + &mut output.colors.dialog + ); + apply!( + "overlay", + &[ + "dropdown.background", + "menu.background", + "editorWidget.background" + ], + &mut output.colors.overlay + ); + apply!( + "hover", + &["list.hoverBackground", "toolbar.hoverBackground"], + &mut output.colors.hover + ); + apply!( + "active", + &[ + "list.activeSelectionBackground", + "list.inactiveSelectionBackground" + ], + &mut output.colors.active + ); + apply!( + "border", + &["panel.border", "widget.border", "contrastBorder"], + &mut output.colors.border + ); + apply!( + "borderStrong", + &["focusBorder", "contrastActiveBorder"], + &mut output.colors.border_strong + ); + apply!( + "text", + &["foreground", "editor.foreground"], + &mut output.colors.text + ); + apply!( + "textMuted", + &["descriptionForeground", "tab.inactiveForeground"], + &mut output.colors.text_muted + ); + apply!( + "textFaint", + &["disabledForeground", "input.placeholderForeground"], + &mut output.colors.text_faint + ); + apply!("solid", &["button.background"], &mut output.colors.solid); + apply!( + "onSolid", + &["button.foreground"], + &mut output.colors.on_solid + ); + apply!( + "danger", + &[ + "editorError.foreground", + "errorForeground", + "gitDecoration.deletedResourceForeground" + ], + &mut output.colors.danger + ); + apply!( + "warning", + &[ + "editorWarning.foreground", + "gitDecoration.modifiedResourceForeground" + ], + &mut output.colors.warning + ); + apply!( + "success", + &[ + "gitDecoration.addedResourceForeground", + "testing.iconPassed" + ], + &mut output.colors.success + ); + apply!("input", &["input.background"], &mut output.colors.input); + apply!( + "cursor", + &["editorCursor.foreground"], + &mut output.colors.cursor + ); + apply!( + "diffAdd", + &[ + "diffEditor.insertedTextBackground", + "gitDecoration.addedResourceForeground" + ], + &mut output.colors.diff_add + ); + apply!( + "diffDelete", + &[ + "diffEditor.removedTextBackground", + "gitDecoration.deletedResourceForeground" + ], + &mut output.colors.diff_delete + ); + apply!( + "diffHunk", + &[ + "diffEditor.diagonalFill", + "editor.findMatchHighlightBackground" + ], + &mut output.colors.diff_hunk + ); + + let accent_keys = [ + "focusBorder", + "textLink.foreground", + "button.background", + "activityBarBadge.background", + "progressBar.background", + "editorCursor.foreground", + ]; + for key in accent_keys { + if let Some(value) = theme.colors.get(key) + && let Ok(color) = value.parse::() + { + report.accent_candidates.push(AccentCandidate { + vscode_key: key.into(), + value: color.to_string(), + }); + } + } + if let Some(candidate) = report.accent_candidates.first() { + let primary = candidate.value.parse()?; + output.accent = AccentRoles::derive(primary, options.appearance, output.colors.background); + report.mappings.push(ImportMapping { + zeron_role: "accent.*".into(), + vscode_key: candidate.vscode_key.clone(), + value: candidate.value.clone(), + }); + } else { + report + .fallbacks + .push("accent.* retained the Zeron fallback; curate a native accent".into()); + } + + apply!( + "terminal.background", + &["terminal.background"], + &mut output.terminal.background + ); + apply!( + "terminal.foreground", + &["terminal.foreground"], + &mut output.terminal.foreground + ); + apply!( + "terminal.selection", + &["terminal.selectionBackground"], + &mut output.terminal.selection + ); + let ansi_keys = [ + "terminal.ansiBlack", + "terminal.ansiRed", + "terminal.ansiGreen", + "terminal.ansiYellow", + "terminal.ansiBlue", + "terminal.ansiMagenta", + "terminal.ansiCyan", + "terminal.ansiWhite", + "terminal.ansiBrightBlack", + "terminal.ansiBrightRed", + "terminal.ansiBrightGreen", + "terminal.ansiBrightYellow", + "terminal.ansiBrightBlue", + "terminal.ansiBrightMagenta", + "terminal.ansiBrightCyan", + "terminal.ansiBrightWhite", + ]; + for (index, key) in ansi_keys.iter().enumerate() { + apply!( + &format!("terminal.ansi[{index}]"), + &[*key], + &mut output.terminal.ansi[index] + ); + } + + map_syntax(&theme, &mut output, &mut report); + let mut hasher = Sha256::new(); + for path in &theme.files { + hasher + .update(fs::read(path).with_context(|| format!("could not hash {}", path.display()))?); + } + report.source_hash = format!("sha256:{:x}", hasher.finalize()); + output.source = ThemeSource { + format: "vscode".into(), + url: options.source_url, + revision: options.revision, + license: options.license, + asset_hash: String::new(), + }; + let encoded = serde_json::to_vec(&output).context("could not hash generated theme")?; + output.source.asset_hash = format!("sha256:{:x}", Sha256::digest(encoded)); + Ok(ImportResult { + theme: output, + report, + }) +} + +fn first_color<'a>( + colors: &'a BTreeMap, + keys: &[&'a str], + warnings: &mut Vec, +) -> Option<(&'a str, Color)> { + for key in keys { + if let Some(value) = colors.get(*key) { + match value.parse() { + Ok(color) => return Some((key, color)), + Err(_) => warnings.push(format!("ignored unsupported color {key}={value}")), + } + } + } + None +} + +fn map_syntax(theme: &NormalizedTheme, output: &mut ThemeVariant, report: &mut ImportReport) { + for rule in &theme.token_colors { + let Some(foreground) = rule.foreground.as_deref() else { + continue; + }; + let Ok(color) = foreground.parse::() else { + report + .warnings + .push(format!("ignored TextMate color {foreground}")); + continue; + }; + if let Some(style) = rule.font_style.as_deref().filter(|value| !value.is_empty()) { + report.dropped.push(format!( + "TextMate fontStyle `{style}` for {}", + rule.scopes.join(", ") + )); + } + for scope in &rule.scopes { + if let Some(role) = syntax_role_for_scope(scope) { + output.syntax.insert(role.into(), color); + report.mappings.push(ImportMapping { + zeron_role: format!("syntax.{role}"), + vscode_key: scope.clone(), + value: color.to_string(), + }); + } + } + } + for (selector, style) in &theme.semantic_token_colors { + if let Some(font_style) = style + .font_style + .as_deref() + .filter(|value| !value.is_empty()) + { + report + .dropped + .push(format!("semantic fontStyle `{font_style}` for {selector}")); + } + let Some(foreground) = style.foreground.as_deref() else { + continue; + }; + let Ok(color) = foreground.parse::() else { + continue; + }; + if let Some(role) = syntax_role_for_semantic(selector) { + output.syntax.insert(role.into(), color); + report.mappings.push(ImportMapping { + zeron_role: format!("syntax.{role}"), + vscode_key: format!("semantic:{selector}"), + value: color.to_string(), + }); + } + } +} + +fn syntax_role_for_scope(scope: &str) -> Option<&'static str> { + let scope = scope.to_ascii_lowercase(); + let pairs = [ + ("comment", "comment"), + ("invalid", "invalid"), + ("keyword", "keyword"), + ("storage", "keyword"), + ("string", "string"), + ("constant.numeric", "number"), + ("constant.language", "boolean"), + ("entity.name.type", "type"), + ("support.type", "typeBuiltin"), + ("entity.name.function", "function"), + ("support.function", "functionBuiltin"), + ("entity.other.attribute", "attribute"), + ("entity.name.tag", "tag"), + ("variable.parameter", "parameter"), + ("variable.other.property", "property"), + ("variable", "variable"), + ("constant", "constant"), + ("keyword.operator", "operator"), + ("punctuation", "punctuation"), + ]; + pairs + .into_iter() + .find_map(|(needle, role)| scope.contains(needle).then_some(role)) +} + +fn syntax_role_for_semantic(selector: &str) -> Option<&'static str> { + let token = selector.split(['.', ':']).next()?.to_ascii_lowercase(); + match token.as_str() { + "comment" => Some("comment"), + "keyword" | "modifier" => Some("keyword"), + "string" | "regexp" => Some("string"), + "number" => Some("number"), + "type" | "class" | "interface" | "enum" | "struct" => Some("type"), + "function" | "method" => Some("function"), + "property" | "enummember" => Some("property"), + "parameter" => Some("parameter"), + "variable" => Some("variable"), + "macro" => Some("macro"), + "decorator" => Some("attribute"), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn options() -> ImportOptions { + ImportOptions { + id: "test-dark".into(), + family_id: "test".into(), + name: "Test Dark".into(), + appearance: Appearance::Dark, + source_url: "https://example.test/theme".into(), + revision: "abc123".into(), + license: "MIT".into(), + } + } + + #[test] + fn resolves_jsonc_includes_and_semantic_overlays() { + let dir = tempfile::tempdir().unwrap(); + fs::write( + dir.path().join("base.json"), + r##"{ + // comments and trailing commas are valid VS Code theme input + "colors": { "editor.background": "#101010", "foreground": "#eeeeee", }, + "tokenColors": [{ "scope": "comment", "settings": { "foreground": "#777777" } }], + }"##, + ) + .unwrap(); + fs::write( + dir.path().join("theme.json"), + r##"{ + "include": "./base.json", + "colors": { "focusBorder": "#00aaff", "terminal.ansiRed": "#ff0000" }, + "semanticTokenColors": { "function": "#00ff00" }, + }"##, + ) + .unwrap(); + let imported = import_file(&dir.path().join("theme.json"), options()).unwrap(); + assert_eq!(imported.theme.colors.background, "#101010".parse().unwrap()); + assert_eq!( + imported.theme.syntax["function"], + "#00ff00".parse().unwrap() + ); + assert_eq!(imported.theme.syntax["comment"], "#777777".parse().unwrap()); + assert_eq!(imported.theme.terminal.ansi[1], "#ff0000".parse().unwrap()); + assert_eq!(imported.report.source_files.len(), 2); + assert!(!imported.report.accent_candidates.is_empty()); + } + + #[test] + fn reports_dropped_font_styles() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join("theme.json"), r##"{ + "tokenColors": [{ "scope": "keyword", "settings": { "foreground": "#ff00ff", "fontStyle": "italic bold" } }] + }"##).unwrap(); + let imported = import_file(&dir.path().join("theme.json"), options()).unwrap(); + assert!( + imported + .report + .dropped + .iter() + .any(|item| item.contains("italic bold")) + ); + } + + #[test] + fn package_detection_classifies_variants_and_keeps_partial_failures() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir_all(dir.path().join("themes")).unwrap(); + fs::write( + dir.path().join("package.json"), + r#"{ + "displayName": "Package Family", + "contributes": { "themes": [ + { "label": "Package Light", "uiTheme": "vs", "path": "./themes/light.json" }, + { "label": "Package Dark", "uiTheme": "vs-dark", "path": "./themes/dark.json" }, + { "label": "Broken", "uiTheme": "vs-dark", "path": "./themes/missing.json" } + ] } + }"#, + ) + .unwrap(); + fs::write( + dir.path().join("themes/light.json"), + r##"{"colors":{"editor.background":"#ffffff","foreground":"#222222"}}"##, + ) + .unwrap(); + fs::write( + dir.path().join("themes/dark.json"), + r##"{"colors":{"editor.background":"#111111","foreground":"#eeeeee"}}"##, + ) + .unwrap(); + + let compiled = compile_source( + dir.path(), + CompileOptions { + family_id: "package-family".into(), + family_name: "Fallback name".into(), + source_url: dir.path().display().to_string(), + revision: "local".into(), + license: "User supplied".into(), + }, + ) + .unwrap(); + assert_eq!(compiled.source_kind, DetectedThemeSource::Package); + assert_eq!(compiled.family.name, "Package Family"); + assert_eq!(compiled.family.variants.len(), 2); + assert_eq!(compiled.failures.len(), 1); + assert!(compiled.family.variants.iter().any(|variant| { + variant.name == "Package Light" && variant.appearance == Appearance::Light + })); + assert!(compiled.family.variants.iter().any(|variant| { + variant.name == "Package Dark" && variant.appearance == Appearance::Dark + })); + } + + #[test] + fn standalone_file_detects_declared_appearance() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("paper.json"); + fs::write( + &path, + r##"{ + "name": "Paper", + "type": "light", + "colors": { "editor.background": "#fafafa", "foreground": "#222222" } + }"##, + ) + .unwrap(); + let compiled = compile_source( + &path, + CompileOptions { + family_id: "paper".into(), + family_name: "Paper".into(), + source_url: path.display().to_string(), + revision: "local".into(), + license: "User supplied".into(), + }, + ) + .unwrap(); + assert_eq!(compiled.source_kind, DetectedThemeSource::File); + assert_eq!(compiled.family.variants[0].name, "Paper"); + assert_eq!(compiled.family.variants[0].appearance, Appearance::Light); + } +} diff --git a/crates/ui/src/theme_library.rs b/crates/ui/src/theme_library.rs new file mode 100644 index 0000000000..5e162f00eb --- /dev/null +++ b/crates/ui/src/theme_library.rs @@ -0,0 +1,168 @@ +//! Durable custom-theme library and the bridge into the active runtime registry. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, Result, anyhow}; +use gpui::{App, Global}; +use zeron_theme::vscode::SourceCompilation; +use zeron_theme::{ + CustomThemeEntry, CustomThemeLibrary, InstallMode, ThemeRegistry, replace_custom_families, +}; + +use crate::appearance; +use crate::theme::Appearance; + +pub struct ThemeLibraryState { + pub data_dir: PathBuf, + pub library: CustomThemeLibrary, + pub load_warning: Option, +} + +impl Global for ThemeLibraryState {} + +pub fn init(data_dir: impl Into, cx: &mut App) { + let data_dir = data_dir.into(); + let (library, load_warning) = match CustomThemeLibrary::load(&data_dir) { + Ok(library) => (library, None), + Err(error) => { + tracing::warn!(error = %error, "could not load custom theme library"); + (CustomThemeLibrary::default(), Some(error.to_string())) + } + }; + library.install_runtime(); + cx.set_global(ThemeLibraryState { + data_dir, + library, + load_warning, + }); +} + +pub fn entries(cx: &App) -> Vec { + cx.try_global::() + .map(|state| state.library.entries.clone()) + .unwrap_or_default() +} + +pub fn load_warning(cx: &App) -> Option { + cx.try_global::() + .and_then(|state| state.load_warning.clone()) +} + +pub fn compile(path: &Path, family_id: &str, family_name: &str) -> Result { + CustomThemeLibrary::compile(path, family_id, family_name) +} + +pub fn install( + compilation: SourceCompilation, + selected_variant_ids: &[String], + mode: InstallMode, + cx: &mut App, +) -> Result { + if !cx.has_global::() { + return Err(anyhow!("custom theme library is not initialized")); + } + let state = cx.global_mut::(); + let id = state + .library + .install(compilation, selected_variant_ids, mode)?; + persist_and_activate(state)?; + reconcile_and_refresh(cx); + Ok(id) +} + +pub fn reload(id: &str, cx: &mut App) -> Result<()> { + if !cx.has_global::() { + return Err(anyhow!("custom theme library is not initialized")); + } + let state = cx.global_mut::(); + let result = state.library.reload(id); + // Reload failures update the durable warning while deliberately preserving + // the last known good family. + persist_and_activate(state)?; + reconcile_and_refresh(cx); + result +} + +pub fn unlink(id: &str, cx: &mut App) -> Result<()> { + mutate(cx, |library| library.unlink(id)) +} + +pub fn duplicate_as_snapshot(id: &str, cx: &mut App) -> Result { + if !cx.has_global::() { + return Err(anyhow!("custom theme library is not initialized")); + } + let state = cx.global_mut::(); + let duplicate = state.library.duplicate_as_snapshot(id)?; + persist_and_activate(state)?; + reconcile_and_refresh(cx); + Ok(duplicate) +} + +pub fn remove(id: &str, cx: &mut App) -> Result<()> { + mutate(cx, |library| { + library + .remove(id) + .then_some(()) + .ok_or_else(|| anyhow!("unknown custom theme `{id}`")) + }) +} + +pub fn reveal(id: &str, cx: &App) -> Result<()> { + let path = cx + .try_global::() + .and_then(|state| state.library.entry(id)) + .and_then(|entry| entry.source.path()) + .ok_or_else(|| anyhow!("theme source has no location to reveal"))?; + cx.reveal_path(path); + Ok(()) +} + +fn mutate( + cx: &mut App, + operation: impl FnOnce(&mut CustomThemeLibrary) -> Result, +) -> Result { + if !cx.has_global::() { + return Err(anyhow!("custom theme library is not initialized")); + } + let state = cx.global_mut::(); + let output = operation(&mut state.library)?; + persist_and_activate(state)?; + reconcile_and_refresh(cx); + Ok(output) +} + +fn persist_and_activate(state: &mut ThemeLibraryState) -> Result<()> { + state + .library + .save(&state.data_dir) + .context("could not save custom theme library")?; + replace_custom_families( + state + .library + .entries + .iter() + .map(|entry| entry.family.clone()) + .collect(), + ); + state.load_warning = None; + Ok(()) +} + +fn reconcile_and_refresh(cx: &mut App) { + let registry = ThemeRegistry::active(); + let selected = appearance::themes(cx); + for appearance_kind in [Appearance::Light, Appearance::Dark] { + let model = if appearance_kind.is_light() { + zeron_theme::Appearance::Light + } else { + zeron_theme::Appearance::Dark + }; + let selected_id = selected.variant_id(model); + if registry.variant(selected_id).is_none() + && let Some(fallback) = registry.variants_for(model).next() + { + appearance::set_theme(appearance_kind, fallback.id.clone(), cx); + } + } + appearance::apply_registry_change(cx); +} diff --git a/docs/adr/0001-custom-themes-compile-to-resolved-families.md b/docs/adr/0001-custom-themes-compile-to-resolved-families.md new file mode 100644 index 0000000000..b59ac342b7 --- /dev/null +++ b/docs/adr/0001-custom-themes-compile-to-resolved-families.md @@ -0,0 +1,26 @@ +# ADR 0001: Compile custom theme sources into resolved families + +- Status: Accepted +- Date: 2026-08-22 + +## Context + +Zeron supports native built-ins and needs to accept VS Code-compatible files and extension packages. Source formats contain workbench keys, TextMate scopes, semantic-token selectors, includes, and package metadata that should not leak into runtime components. Linked sources may also become temporarily missing or invalid. + +## Decision + +Every custom source compiles into the same source-neutral `ThemeFamily` and `ThemeVariant` model used by built-ins. Durable sources are represented as `ImportedSnapshot`, `LinkedFile`, or `LinkedPackage`. + +Imported snapshots persist their compiled family. Linked sources persist both their location and their last successfully compiled family. A failed reload records a quiet warning and continues using the last known good family; it never replaces working runtime data with an invalid result. + +Compilation detects package variants and light/dark appearance, maps workbench, syntax, semantic-token, terminal, and accent roles, and emits a per-variant import report. Runtime UI resolves only compiled Zeron roles and never reads VS Code tokens. + +Theme-default accents remain part of the compiled variant. Zeron accent presets override interaction roles only and do not alter syntax, terminal ANSI, diff, warning, error, or success roles. + +## Consequences + +- Built-in, imported, and linked families share one runtime registry and rendering path. +- Source-specific complexity stays in import adapters and can grow without changing components. +- Linked themes remain usable during transient source failures. +- Persistence is larger than storing links alone because it includes last-known-good compiled data and reports. +- Source changes are not reflected until an explicit or future automatic reload succeeds. diff --git a/docs/adr/0002-separate-surface-preference-from-theme-selection.md b/docs/adr/0002-separate-surface-preference-from-theme-selection.md new file mode 100644 index 0000000000..1fb597188d --- /dev/null +++ b/docs/adr/0002-separate-surface-preference-from-theme-selection.md @@ -0,0 +1,5 @@ +# Separate surface preference from theme selection + +Zeron treats glass as an independent, device-local surface preference instead of a property that changes implicitly with theme selection. Each theme variant retains a recommended surface treatment (`Frosted` for Zeron and `Opaque` for VS Code-derived themes), while the user may preserve that recommendation or globally force `Frosted` or `Opaque`; forced frost derives its tints from the selected theme's own shell and background roles, and unsupported window compositors remain opaque. + +This preserves theme authors' contrast assumptions by default while allowing users to keep a consistent glass preference across every built-in and custom theme. Syntax, terminal, semantic, status, diff, and accent roles are unaffected by surface preference. diff --git a/docs/theme-system.md b/docs/theme-system.md new file mode 100644 index 0000000000..f5ae44455c --- /dev/null +++ b/docs/theme-system.md @@ -0,0 +1,149 @@ +# Theme system + +Zeron themes are complete, source-neutral `ThemeVariant` values owned by the +`zeron-theme` crate. Runtime components consume only Zeron semantic roles. VS +Code workbench ids and TextMate selectors stop at the source compiler. + +## Runtime model + +- `ThemeFamily` groups related variants. +- `ThemeVariant` is one completely resolved light or dark palette. +- `ThemeSelection` stores independent light and dark variant ids. +- `AccentSelection::ThemeDefault` preserves the variant's authored accent. +- `AccentSelection::Preset` derives a contrast-checked interaction overlay. +- Every variant records a recommended `SurfaceTreatment`: Zeron recommends + frost, while VS Code-derived themes recommend opaque surfaces because that is + what their authors targeted. +- `SurfacePreference` is a separate device-local choice: `Theme default`, + `Frosted`, or `Opaque`. It does not change appearance, theme, or accent + selection. +- Terminal background, foreground, selection and ANSI16 colors belong to the + variant instead of the terminal renderer. + +Accent overlays affect controls, focus, selections, caret, activity and the +three-tone glyph. They do not recolor syntax, terminal ANSI, status, or diff +semantics. + +Surface preference affects only surface composition. Theme default preserves +the variant's recommendation; either override remains active while users move +between built-in, imported, and linked themes. Forced frost derives window, +floating, input, card, and hover tints from the variant's mapped shell roles +instead of fixed Zeron greys. Its window tint becomes denser when necessary to +keep primary text at 4.5:1 and muted text at 3:1 against the adverse desktop +luminance. + +macOS can frost the main window. Linux and Windows keep the main window opaque +because compositor blur is not guaranteed; supported floating surfaces can +still frost on macOS and Linux. The preference remains portable even where a +particular surface cannot honor blur. + +The built-in registry contains 30 variants across 19 families: + +- Zeron Light and Dark +- VS Code Light+ and Dark+ +- Catppuccin Latte and Mocha +- Tokyo Night Light and Tokyo Night +- Dracula +- GitHub Light and Dark +- Ayu Light, Dark, and Mirage +- Gruvbox Light and Dark +- Rosé Pine Dawn and Moon +- Nord +- One Dark Pro +- Atom One Dark +- Night Owl and Night Owl Light +- Winter is Coming Dark Blue and Light +- Palenight +- SynthWave '84 +- Shades of Purple +- Cobalt2 +- Andromeda + +Every bundled variant records source URL, exact upstream revision, license, and +a SHA-256 hash of the resolved curated definition. + +Appearance settings keep light and dark choices in ordinary settings rows. +Each row opens a palette-preview menu, which allows the catalog to grow without +turning the page into a grid of bespoke buttons. Accent remains a compact +right-aligned swatch control; its three-tone first swatch means “Theme default.” +Glass is an adjacent conventional settings row with a compact +`Theme default` / `Frosted` / `Opaque` selector. + +## VS Code import + +The importer supports JSONC, trailing commas, +`include` inheritance, inline or external token rules, TextMate plist files, +workbench colors, semantic token colors, and terminal ANSI colors. + +Appearance settings accept a single theme file, an extension `package.json`, or +an extension folder. Packages are detected from `contributes.themes`; variants +are classified by `uiTheme`, an explicit theme `type`, or the resolved editor +background. Each package variant compiles independently so a broken variant is +reported without hiding valid siblings. Users can select all or individual +variants, preview representative workbench/code/terminal/diff roles, and open +the optional mapping review. + +The importer records `Opaque` as the variant's recommended surface treatment +and reports that inference. This preserves the source palette by default while +still allowing the independent Zeron surface preference to force frost. + +The custom library has three source forms: + +- `ImportedSnapshot` persists a self-contained compiled copy. +- `LinkedFile` follows one source theme file. +- `LinkedPackage` follows a VS Code extension package. + +Linked sources reload explicitly. A failed reload stores a quiet warning and +continues using the last successfully compiled family. All three forms compile +to the same `ThemeFamily` model as built-ins, so runtime components remain +unaware of VS Code tokens. The library is stored in +`{data_dir}/theme-library.json` and is loaded before the first palette is +installed. + +The `zeron-theme-import` development tool exposes the same single-file adapter +for built-in curation: + +Example: + +```bash +cargo run -p zeron-theme --bin zeron-theme-import -- \ + --input /path/to/theme.json \ + --output /tmp/theme.zeron.json \ + --report /tmp/theme.report.json \ + --id example-dark \ + --family-id example \ + --name "Example Dark" \ + --appearance dark \ + --source-url https://github.com/example/theme \ + --revision 0123456789abcdef \ + --license MIT +``` + +The report records every source mapping, fallback, unsupported font style, +invalid color, and accent candidate. Zeron does not fetch or execute VSIX +packages at runtime; custom sources are local files and folders compiled into +resolved data. + +## Acceptance and visual QA + +`ThemeRegistry::validate` checks unique ids, provenance, text contrast, +interaction contrast, on-accent contrast, and terminal foreground contrast. +Tests also exercise every preset against both appearances. + +Before adding or updating a bundled variant, review both appearances where +available across every `VisualFixture` scene: + +1. Sidebar +2. Transcript Markdown +3. Transcript code +4. Composer +5. Picker/popover +6. Appearance settings +7. Diff +8. Terminal +9. Empty state +10. Dialog + +Review normal, hover, active, focused, selected, disabled, working, warning, +error, and success states. Importer reports and automated contrast checks are +gates, not substitutes for this visual pass. From dbdeb816faf19fa3030514a3701a0ecaa7b3a11b Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 12:42:15 +0200 Subject: [PATCH 4/9] Harden custom themes and polish appearance settings --- CONTEXT.md | 6 +- crates/theme/src/lib.rs | 48 +- crates/theme/src/library.rs | 222 +++- crates/theme/src/vscode.rs | 419 +++++++- crates/ui/src/appearance.rs | 2 +- crates/ui/src/popover.rs | 22 + crates/ui/src/settings/appearance.rs | 973 +++++++++++------- crates/ui/src/shell.rs | 12 +- crates/ui/src/shell/spaces.rs | 19 +- crates/ui/src/theme.rs | 259 ++++- crates/ui/src/theme_library.rs | 83 +- ...tom-themes-compile-to-resolved-families.md | 13 +- docs/theme-system.md | 47 +- 13 files changed, 1638 insertions(+), 487 deletions(-) diff --git a/CONTEXT.md b/CONTEXT.md index a0ede71367..a86a4d92cd 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -4,14 +4,16 @@ - **Theme family** — A named collection of related theme variants that share an origin, such as Night Owl and Night Owl Light. - **Theme variant** — One complete, resolved palette for a single appearance (`light` or `dark`). Runtime UI consumes variants, not source-format tokens. -- **Theme source** — The durable origin of a custom family: an imported snapshot, linked file, or linked package. -- **Imported snapshot** — A self-contained copy of a compiled theme family. It no longer follows changes to its original file and can be duplicated for editing. +- **Theme source** — The durable origin of a custom family: an imported snapshot, linked file, linked package, or editable native file. +- **Imported snapshot** — A self-contained copy of a compiled theme family. It no longer follows changes to its original source. - **Linked theme** — A custom family that follows a source on disk and can be reloaded without re-importing it. - **Linked file** — A link to one VS Code-compatible theme definition. - **Linked package** — A link to a VS Code extension folder or `package.json` that declares one or more related theme variants. +- **Editable theme** — A duplicate stored as a native resolved-family JSON file. Users edit the file directly and explicitly reload it; invalid edits preserve the last known good family. - **Last known good** — The most recent successfully compiled family retained by a linked theme when its current source is missing or invalid. - **Import report** — A per-variant summary of mapped roles, fallbacks, unsupported values, and inferred decisions produced during compilation. - **Mapping review** — The optional advanced view of an import report. Normal theme selection and import do not expose token names. +- **Theme hardening** — Deterministic post-mapping repairs that prefer stronger semantically related source colors, minimally adjust only shared Zeron roles when needed, and record every decision in the mapping review. - **Theme default accent** — The interaction accent chosen or inferred for a theme variant by its authoring source. - **Accent override** — A Zeron preset that replaces interaction roles only; syntax, terminal ANSI, diff, warning, error, and success colors remain owned by the theme. - **Recommended surface treatment** — A theme variant's authored recommendation for whether its surfaces are frosted or opaque. It is used only when the user keeps the surface preference at theme default. diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index aa7afcb17d..19556fe87b 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -568,7 +568,7 @@ impl ThemeRegistry { for family in &self.families { for variant in &family.variants { if variant.id.trim().is_empty() || !ids.insert(&variant.id) { - issues.push(ValidationIssue::error( + issues.push(ValidationIssue::structural_error( &variant.id, "variant id must be unique", )); @@ -618,14 +618,20 @@ impl ThemeRegistry { || variant.source.license.is_empty() || variant.source.asset_hash.is_empty() { - issues.push(ValidationIssue::error( + issues.push(ValidationIssue::structural_error( &variant.id, "source provenance is incomplete", )); } - for (index, color) in variant.terminal.ansi.iter().enumerate().skip(1).take(6) { + for (index, color) in variant.terminal.ansi.iter().enumerate() { + // Slots 0 and 8 are structural black/dim colors. Every + // chromatic normal and bright slot is expected to remain + // distinguishable as terminal text. + if index % 8 == 0 { + continue; + } if color.contrast(variant.terminal.background) < 3.0 { - issues.push(ValidationIssue::warning( + issues.push(ValidationIssue::contrast_warning( &variant.id, format!("terminal ANSI slot {index} is below 3:1"), )); @@ -647,7 +653,7 @@ fn validate_contrast( ) { let actual = foreground.contrast(background); if actual < minimum { - issues.push(ValidationIssue::error( + issues.push(ValidationIssue::contrast_error( &variant.id, format!("{role} contrast is {actual:.2}:1; expected {minimum:.1}:1"), )); @@ -661,29 +667,57 @@ pub enum ValidationSeverity { Error, } +/// Whether a validation issue makes a theme structurally unsafe to install or +/// describes a visual quality problem that the compiler/runtime can harden. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ValidationCategory { + Structural, + #[default] + Contrast, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ValidationIssue { pub variant_id: String, + #[serde(default)] + pub category: ValidationCategory, pub severity: ValidationSeverity, pub message: String, } impl ValidationIssue { - fn error(variant_id: &str, message: impl Into) -> Self { + fn structural_error(variant_id: &str, message: impl Into) -> Self { + Self { + variant_id: variant_id.into(), + category: ValidationCategory::Structural, + severity: ValidationSeverity::Error, + message: message.into(), + } + } + + fn contrast_error(variant_id: &str, message: impl Into) -> Self { Self { variant_id: variant_id.into(), + category: ValidationCategory::Contrast, severity: ValidationSeverity::Error, message: message.into(), } } - fn warning(variant_id: &str, message: impl Into) -> Self { + fn contrast_warning(variant_id: &str, message: impl Into) -> Self { Self { variant_id: variant_id.into(), + category: ValidationCategory::Contrast, severity: ValidationSeverity::Warning, message: message.into(), } } + + pub fn is_blocking(&self) -> bool { + self.category == ValidationCategory::Structural + && self.severity == ValidationSeverity::Error + } } /// Stable visual QA scenes every bundled variant must be reviewed against. diff --git a/crates/theme/src/library.rs b/crates/theme/src/library.rs index d72e5746ad..fd9aad73c9 100644 --- a/crates/theme/src/library.rs +++ b/crates/theme/src/library.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use crate::vscode::{ CompileOptions, DetectedThemeSource, ImportReport, SourceCompilation, compile_source, }; -use crate::{ThemeFamily, replace_custom_families}; +use crate::{ThemeFamily, ThemeRegistry, replace_custom_families}; const LIBRARY_FILE: &str = "theme-library.json"; @@ -22,21 +22,36 @@ pub enum InstallMode { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum CustomThemeSource { - ImportedSnapshot { imported_from: Option }, - LinkedFile { path: PathBuf }, - LinkedPackage { path: PathBuf }, + ImportedSnapshot { + imported_from: Option, + }, + LinkedFile { + path: PathBuf, + }, + LinkedPackage { + path: PathBuf, + }, + /// A native resolved-family file created by Zeron for direct editing. + EditableFile { + path: PathBuf, + }, } impl CustomThemeSource { pub fn path(&self) -> Option<&Path> { match self { Self::ImportedSnapshot { imported_from } => imported_from.as_deref(), - Self::LinkedFile { path } | Self::LinkedPackage { path } => Some(path), + Self::LinkedFile { path } + | Self::LinkedPackage { path } + | Self::EditableFile { path } => Some(path), } } pub fn is_linked(&self) -> bool { - matches!(self, Self::LinkedFile { .. } | Self::LinkedPackage { .. }) + matches!( + self, + Self::LinkedFile { .. } | Self::LinkedPackage { .. } | Self::EditableFile { .. } + ) } pub fn label(&self) -> &'static str { @@ -44,6 +59,7 @@ impl CustomThemeSource { Self::ImportedSnapshot { .. } => "Imported", Self::LinkedFile { .. } => "Linked file", Self::LinkedPackage { .. } => "Linked package", + Self::EditableFile { .. } => "Editable file", } } } @@ -162,6 +178,10 @@ impl CustomThemeLibrary { if entry_id != family.id { rekey_family(&mut family, &entry_id); } + let errors = validation_errors(&family); + if !errors.is_empty() { + bail!("theme validation failed: {}", errors.join("; ")); + } let selected_variant_ids = family .variants .iter() @@ -210,6 +230,28 @@ impl CustomThemeLibrary { CustomThemeSource::LinkedFile { path } | CustomThemeSource::LinkedPackage { path } => { path.clone() } + CustomThemeSource::EditableFile { path } => { + let path = path.clone(); + let family = match load_editable_family(&path, &entry.id) { + Ok(family) => family, + Err(error) => { + entry.status = CustomThemeStatus::Warning { + message: error.to_string(), + }; + return Err(error); + } + }; + entry.selected_variant_ids = family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect(); + entry.name = family.name.clone(); + entry.family = family; + entry.reports.clear(); + entry.status = CustomThemeStatus::Ready; + return Ok(()); + } CustomThemeSource::ImportedSnapshot { .. } => bail!("imported snapshots cannot reload"), }; let compilation = match Self::compile(&path, &entry.id, &entry.name) { @@ -245,6 +287,14 @@ impl CustomThemeLibrary { }; bail!(message); } + let errors = validation_errors(&family); + if !errors.is_empty() { + let message = format!("theme validation failed: {}", errors.join("; ")); + entry.status = CustomThemeStatus::Warning { + message: message.clone(), + }; + bail!(message); + } entry.family = family; entry.reports = compilation .reports @@ -313,6 +363,51 @@ impl CustomThemeLibrary { Ok(new_id) } + /// Duplicate a compiled family into a native, user-editable file. Reveal + /// opens that file in the system file manager; Reload validates it and + /// preserves the last known good family if an edit is invalid. + pub fn duplicate_as_editable(&mut self, id: &str, data_dir: &Path) -> Result { + let original = self + .entries + .iter() + .find(|entry| entry.id == id) + .cloned() + .ok_or_else(|| anyhow!("unknown custom theme `{id}`"))?; + let new_id = unique_id( + &format!("{}-copy", original.id), + self.entries.iter().map(|entry| entry.id.as_str()), + ); + let mut family = original.family; + family.name = format!("{} Copy", family.name); + rekey_family(&mut family, &new_id); + + let editable_dir = data_dir.join("custom-themes"); + fs::create_dir_all(&editable_dir) + .with_context(|| format!("could not create {}", editable_dir.display()))?; + let path = editable_dir.join(format!("{new_id}.zeron-theme.json")); + let temporary = path.with_extension("json.tmp"); + fs::write(&temporary, serde_json::to_vec_pretty(&family)?) + .with_context(|| format!("could not write {}", temporary.display()))?; + fs::rename(&temporary, &path) + .with_context(|| format!("could not replace {}", path.display()))?; + + let selected_variant_ids = family + .variants + .iter() + .map(|variant| variant.id.clone()) + .collect(); + self.entries.push(CustomThemeEntry { + id: new_id.clone(), + name: family.name.clone(), + source: CustomThemeSource::EditableFile { path }, + family, + reports: BTreeMap::new(), + selected_variant_ids, + status: CustomThemeStatus::Ready, + }); + Ok(new_id) + } + pub fn remove(&mut self, id: &str) -> bool { let before = self.entries.len(); self.entries.retain(|entry| entry.id != id); @@ -320,6 +415,35 @@ impl CustomThemeLibrary { } } +fn load_editable_family(path: &Path, expected_id: &str) -> Result { + let source = fs::read_to_string(path) + .with_context(|| format!("could not read editable theme {}", path.display()))?; + let family: ThemeFamily = serde_json::from_str(&source) + .with_context(|| format!("could not parse editable theme {}", path.display()))?; + if family.id != expected_id { + bail!( + "editable theme family id must remain `{expected_id}` (found `{}`)", + family.id + ); + } + let errors = validation_errors(&family); + if !errors.is_empty() { + bail!("editable theme validation failed: {}", errors.join("; ")); + } + Ok(family) +} + +fn validation_errors(family: &ThemeFamily) -> Vec { + ThemeRegistry { + families: vec![family.clone()], + } + .validate() + .into_iter() + .filter(|issue| issue.is_blocking()) + .map(|issue| format!("{}: {}", issue.variant_id, issue.message)) + .collect() +} + fn unique_id<'a>(base: &str, existing: impl Iterator) -> String { let existing = existing.collect::>(); if !existing.contains(base) { @@ -390,6 +514,33 @@ mod tests { assert!(matches!(entry.status, CustomThemeStatus::Warning { .. })); } + #[test] + fn linked_reload_hardens_low_contrast_palette() { + let dir = tempfile::tempdir().unwrap(); + package(dir.path()); + let compiled = + CustomThemeLibrary::compile(dir.path(), "test-family", "Test Family").unwrap(); + let mut library = CustomThemeLibrary::default(); + let id = library.install(compiled, &[], InstallMode::Link).unwrap(); + fs::write( + dir.path().join("themes/dark.json"), + r##"{"colors":{"editor.background":"#111111","foreground":"#111111","focusBorder":"#66aaff"}}"##, + ) + .unwrap(); + + library.reload(&id).unwrap(); + let entry = library.entry(&id).unwrap(); + let variant = &entry.family.variants[0]; + assert!(variant.colors.text.contrast(variant.colors.background) >= 4.5); + assert!( + entry + .reports + .values() + .any(|report| !report.adjustments.is_empty()) + ); + assert_eq!(entry.status, CustomThemeStatus::Ready); + } + #[test] fn snapshot_round_trips_and_duplicate_gets_independent_ids() { let source = tempfile::tempdir().unwrap(); @@ -416,4 +567,63 @@ mod tests { library.save(data.path()).unwrap(); assert_eq!(CustomThemeLibrary::load(data.path()).unwrap(), library); } + + #[test] + fn contrast_findings_do_not_block_install() { + let source = tempfile::tempdir().unwrap(); + package(source.path()); + let mut compiled = + CustomThemeLibrary::compile(source.path(), "test-family", "Test Family").unwrap(); + let variant = &mut compiled.family.variants[0]; + variant.colors.text = variant.colors.background; + + CustomThemeLibrary::default() + .install(compiled, &[], InstallMode::Snapshot) + .unwrap(); + } + + #[test] + fn install_rejects_structurally_invalid_palettes() { + let source = tempfile::tempdir().unwrap(); + package(source.path()); + let mut compiled = + CustomThemeLibrary::compile(source.path(), "test-family", "Test Family").unwrap(); + compiled.family.variants[0].source.asset_hash.clear(); + + let error = CustomThemeLibrary::default() + .install(compiled, &[], InstallMode::Snapshot) + .unwrap_err(); + assert!(error.to_string().contains("theme validation failed")); + } + + #[test] + fn editable_duplicate_reloads_and_keeps_last_known_good_on_failure() { + let source = tempfile::tempdir().unwrap(); + package(source.path()); + let compiled = + CustomThemeLibrary::compile(source.path(), "test-family", "Test Family").unwrap(); + let mut library = CustomThemeLibrary::default(); + let id = library + .install(compiled, &[], InstallMode::Snapshot) + .unwrap(); + let data = tempfile::tempdir().unwrap(); + let copy = library.duplicate_as_editable(&id, data.path()).unwrap(); + let path = match &library.entry(©).unwrap().source { + CustomThemeSource::EditableFile { path } => path.clone(), + source => panic!("expected editable source, found {source:?}"), + }; + + let mut edited = library.entry(©).unwrap().family.clone(); + edited.name = "Edited Copy".into(); + fs::write(&path, serde_json::to_vec_pretty(&edited).unwrap()).unwrap(); + library.reload(©).unwrap(); + assert_eq!(library.entry(©).unwrap().name, "Edited Copy"); + + let last_known_good = library.entry(©).unwrap().family.clone(); + fs::write(&path, "not json").unwrap(); + assert!(library.reload(©).is_err()); + let entry = library.entry(©).unwrap(); + assert_eq!(entry.family, last_known_good); + assert!(matches!(entry.status, CustomThemeStatus::Warning { .. })); + } } diff --git a/crates/theme/src/vscode.rs b/crates/theme/src/vscode.rs index b057f5d38e..e8f222969d 100644 --- a/crates/theme/src/vscode.rs +++ b/crates/theme/src/vscode.rs @@ -14,7 +14,7 @@ use sha2::{Digest, Sha256}; use crate::{ AccentRoles, Appearance, Color, SurfaceTreatment, ThemeFamily, ThemeRegistry, ThemeSource, - ThemeVariant, + ThemeVariant, ValidationIssue, }; #[derive(Debug, Clone)] @@ -44,7 +44,24 @@ pub struct ImportReport { pub fallbacks: Vec, pub dropped: Vec, pub warnings: Vec, + /// Deterministic repairs made after mapping so the compiled Zeron roles + /// remain usable without erasing the source theme's syntax identity. + #[serde(default)] + pub adjustments: Vec, pub accent_candidates: Vec, + /// Resolved-palette checks run after mapping and hardening. Structural + /// errors block install; contrast findings remain reviewable. + #[serde(default)] + pub validation: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportAdjustment { + pub zeron_role: String, + pub original: String, + pub resolved: String, + pub reason: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -297,11 +314,13 @@ fn detect_appearance( normalized: &NormalizedTheme, ) -> Appearance { if let Some(ui_theme) = ui_theme { - return if ui_theme.eq_ignore_ascii_case("vs") { - Appearance::Light - } else { - Appearance::Dark - }; + match ui_theme.to_ascii_lowercase().as_str() { + "vs" | "hc-light" => return Appearance::Light, + "vs-dark" | "hc-black" => return Appearance::Dark, + // Future or third-party values still get the more reliable + // explicit-type/background inference below. + _ => {} + } } if let Ok(source) = fs::read_to_string(path) && let Ok(value) = json5::from_str::(&source) @@ -541,6 +560,7 @@ fn convert(theme: NormalizedTheme, options: ImportOptions) -> Result Result Result Color { + if color.a == 255 { + return color; + } + let resolved = color.blend_over(background); + record_adjustment( + report, + role, + color, + resolved, + "flattened a translucent foundational surface against the theme background", + ); + resolved +} + +fn harden_foreground( + source: &NormalizedTheme, + report: &mut ImportReport, + role: &str, + current: Color, + candidate_keys: &[&str], + backgrounds: &[Color], + minimum: f32, + preferred_target: Option, +) -> Color { + let current_contrast = minimum_contrast(current, backgrounds); + if current_contrast >= minimum { + return current; + } + + for key in candidate_keys { + let Some(value) = source.colors.get(*key) else { + continue; + }; + let Ok(candidate) = value.parse::() else { + continue; + }; + if minimum_contrast(candidate, backgrounds) >= minimum { + record_adjustment( + report, + role, + current, + candidate, + format!("used {key} because the mapped color reached only {current_contrast:.2}:1"), + ); + if let Some(mapping) = report + .mappings + .iter_mut() + .find(|mapping| mapping.zeron_role == role) + { + mapping.vscode_key = (*key).into(); + mapping.value = candidate.to_string(); + } + return candidate; + } + } + + let resolved = ensure_contrast_across(current, backgrounds, minimum, preferred_target); + record_adjustment( + report, + role, + current, + resolved, + format!( + "preserved the source hue while raising worst-case contrast from {current_contrast:.2}:1 to {:.2}:1", + minimum_contrast(resolved, backgrounds) + ), + ); + resolved +} + +fn ensure_contrast_across( + color: Color, + backgrounds: &[Color], + minimum: f32, + preferred_target: Option, +) -> Color { + if minimum_contrast(color, backgrounds) >= minimum { + return color; + } + let mut targets = Vec::with_capacity(3); + if let Some(target) = preferred_target { + targets.push(target); + } + targets.extend([Color::BLACK, Color::WHITE]); + + let mut best = color; + let mut best_contrast = minimum_contrast(color, backgrounds); + for target in targets { + for step in 1..=100 { + let candidate = color.mix(target, step as f32 / 100.0); + let contrast = minimum_contrast(candidate, backgrounds); + if contrast > best_contrast { + best = candidate; + best_contrast = contrast; + } + if contrast >= minimum { + return candidate; + } + } + } + best +} + +fn minimum_contrast(color: Color, backgrounds: &[Color]) -> f32 { + backgrounds + .iter() + .map(|background| color.contrast(*background)) + .fold(f32::INFINITY, f32::min) +} + +fn harden_accent(output: &mut ThemeVariant, report: &mut ImportReport, backgrounds: &[Color]) { + let current = output.accent.primary; + if minimum_contrast(current, backgrounds) >= 3.0 { + return; + } + for candidate in &report.accent_candidates { + let Ok(primary) = candidate.value.parse::() else { + continue; + }; + if minimum_contrast(primary, backgrounds) >= 3.0 { + output.accent = + AccentRoles::derive(primary, output.appearance, output.colors.background); + record_adjustment( + report, + "accent.*", + current, + output.accent.primary, + format!("used {} to keep interactions at 3:1", candidate.vscode_key), + ); + return; + } + } + let primary = ensure_contrast_across(current, backgrounds, 3.0, None); + output.accent = AccentRoles::derive(primary, output.appearance, output.colors.background); + record_adjustment( + report, + "accent.*", + current, + output.accent.primary, + "preserved the source hue while raising interaction contrast to 3:1", + ); +} + +fn record_adjustment( + report: &mut ImportReport, + role: &str, + original: Color, + resolved: Color, + reason: impl Into, +) { + if original == resolved { + return; + } + report.adjustments.push(ImportAdjustment { + zeron_role: role.into(), + original: original.to_string(), + resolved: resolved.to_string(), + reason: reason.into(), + }); +} + fn first_color<'a>( colors: &'a BTreeMap, keys: &[&'a str], @@ -999,6 +1306,106 @@ mod tests { ); } + #[test] + fn hardens_ayu_style_low_contrast_workbench_roles_without_blocking_import() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ayu-mirage.json"); + fs::write( + &path, + r##"{ + "name": "Ayu Mirage", + "type": "dark", + "colors": { + "editor.background": "#242936", + "foreground": "#707a8c", + "descriptionForeground": "#707a8c", + "editor.foreground": "#cccac2", + "focusBorder": "#ffcc66", + "terminal.background": "#242936", + "terminal.foreground": "#707a8c" + } + }"##, + ) + .unwrap(); + + let imported = import_file(&path, options()).unwrap(); + assert_eq!( + imported.theme.colors.text, + "#cccac2".parse::().unwrap() + ); + assert!( + imported + .theme + .colors + .text_muted + .contrast(imported.theme.colors.background) + >= 4.5 + ); + assert!( + imported + .theme + .terminal + .foreground + .contrast(imported.theme.terminal.background) + >= 4.5 + ); + assert!(imported.report.adjustments.iter().any(|adjustment| { + adjustment.zeron_role == "text" && adjustment.reason.contains("editor.foreground") + })); + assert!( + imported + .report + .validation + .iter() + .all(|issue| !issue.is_blocking()) + ); + } + + #[test] + fn flattens_translucent_foundational_surfaces() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("transparent.json"); + fs::write( + &path, + r##"{ + "colors": { + "editor.background": "#101820cc", + "sideBar.background": "#ffffff10", + "foreground": "#ffffff" + } + }"##, + ) + .unwrap(); + + let imported = import_file(&path, options()).unwrap(); + assert_eq!(imported.theme.colors.background.a, 255); + assert_eq!(imported.theme.colors.shell.a, 255); + assert!(imported.report.adjustments.iter().any(|adjustment| { + adjustment.zeron_role == "background" + && adjustment.reason.contains("translucent foundational") + })); + } + + #[test] + fn appearance_detection_handles_high_contrast_and_unknown_ui_themes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("theme.json"); + fs::write(&path, r##"{"colors":{"editor.background":"#ffffff"}}"##).unwrap(); + let mut normalized = NormalizedTheme::default(); + normalized + .colors + .insert("editor.background".into(), "#ffffff".into()); + + assert_eq!( + detect_appearance(&path, Some("hc-light"), &normalized), + Appearance::Light + ); + assert_eq!( + detect_appearance(&path, Some("third-party-theme-kind"), &normalized), + Appearance::Light + ); + } + #[test] fn package_detection_classifies_variants_and_keeps_partial_failures() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ui/src/appearance.rs b/crates/ui/src/appearance.rs index bfaffa8e7c..699e1e3217 100644 --- a/crates/ui/src/appearance.rs +++ b/crates/ui/src/appearance.rs @@ -318,7 +318,7 @@ pub fn apply_registry_change(cx: &mut App) { let accent = state.accent; let surface = state.surface; let variant_id = state.themes.variant_id(model_appearance(wanted)).to_owned(); - Theme::install_selection(wanted, &variant_id, accent, surface, cx); + Theme::reinstall_selection(wanted, &variant_id, accent, surface, cx); cx.refresh_windows(); reapply_window_background(cx); } diff --git a/crates/ui/src/popover.rs b/crates/ui/src/popover.rs index 9e627e99bd..278a76c904 100644 --- a/crates/ui/src/popover.rs +++ b/crates/ui/src/popover.rs @@ -788,6 +788,28 @@ pub fn band() -> gpui::Hsla { crate::theme::band() } +/// Shared shell for command-palette-style flows. The recessed header/footer +/// bands are supplied by callers, while this owns the glass tint, outline, +/// radius, clipping, and shadow that make Cmd+K and its sibling flows read as +/// one component family. +pub fn palette_card(theme: &Theme, width: Pixels, corner_radius: f32) -> gpui::Div { + div() + .w(width) + .rounded(px(corner_radius)) + .border_1() + .border_color(hairline(0.10)) + .bg(if theme.is_frost() { + theme.glass_overlay() + } else { + theme.surface_overlay + }) + .shadow_lg() + .overflow_hidden() + .flex() + .flex_col() + .text_color(theme.text) +} + /// One footer key-cap (22px, rounded-5, `white/[0.05]`) holding arbitrary /// children — the base of [`key_hint`]/[`key_hint_pair`] and the search-bar /// chips ("⌘K", "esc"). diff --git a/crates/ui/src/settings/appearance.rs b/crates/ui/src/settings/appearance.rs index 6ac89c1dc0..f4d646f3d4 100644 --- a/crates/ui/src/settings/appearance.rs +++ b/crates/ui/src/settings/appearance.rs @@ -5,8 +5,8 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use gpui::{ - AnyElement, Context, Entity, Hsla, IntoElement, Render, SharedString, Subscription, Window, - div, prelude::*, px, + AnyElement, Context, Entity, FocusHandle, Focusable, Hsla, IntoElement, Render, SharedString, + Subscription, Window, div, prelude::*, px, }; use zeron_theme::vscode::{ImportReport, SourceCompilation}; use zeron_theme::{ @@ -25,6 +25,8 @@ use crate::theme_library; struct ImportDialog { input: Entity, _events: Subscription, + focus: FocusHandle, + focus_pending: bool, mode: InstallMode, compilation: Option, selected: HashSet, @@ -52,16 +54,51 @@ impl AppearancePage { } fn open_import(&mut self, cx: &mut Context) { - let input = - cx.new(|cx| ComposerInput::new("Theme file, package.json, or extension folder", cx)); - let events = cx.subscribe(&input, |this: &mut Self, _, event, cx| { - if matches!(event, ComposerInputEvent::Submitted) { - this.compile_import(cx); + let input = cx.new(|cx| { + ComposerInput::with_context( + "Theme file, package.json, or extension folder", + "PaletteSearch", + cx, + ) + }); + let events = cx.subscribe(&input, |this: &mut Self, _, event, cx| match event { + ComposerInputEvent::Edited => { + let source = this + .import_dialog + .as_ref() + .map(|dialog| PathBuf::from(dialog.input.read(cx).text().trim())); + if let Some(dialog) = this.import_dialog.as_mut() + && dialog + .compilation + .as_ref() + .zip(source.as_ref()) + .is_some_and(|(compilation, source)| compilation.path != *source) + { + dialog.compilation = None; + dialog.selected.clear(); + dialog.review_variant = None; + dialog.error = None; + cx.notify(); + } } + ComposerInputEvent::Submitted => { + if this + .import_dialog + .as_ref() + .is_some_and(|dialog| dialog.compilation.is_some()) + { + this.finish_import(cx); + } else { + this.compile_import(cx); + } + } + _ => {} }); self.import_dialog = Some(ImportDialog { input, _events: events, + focus: cx.focus_handle(), + focus_pending: true, mode: InstallMode::Snapshot, compilation: None, selected: HashSet::new(), @@ -136,6 +173,11 @@ impl AppearancePage { let Some(dialog) = self.import_dialog.as_mut() else { return; }; + if dialog.selected.is_empty() { + dialog.error = Some("Select at least one variant to import.".into()); + cx.notify(); + return; + } let Some(compilation) = dialog.compilation.take() else { return; }; @@ -216,16 +258,14 @@ fn surface_label(surface: SurfacePreference) -> &'static str { fn surface_helper(surface: SurfacePreference, resolved: SurfaceTreatment) -> String { match surface { SurfacePreference::ThemeDefault => format!( - "Theme default · This theme recommends {} surfaces.", + "Uses this theme's {} default.", match resolved { SurfaceTreatment::Frosted => "frosted", SurfaceTreatment::Opaque => "opaque", } ), - SurfacePreference::Frosted => { - "Frosted · Uses theme-colored glass wherever the platform supports blur.".into() - } - SurfacePreference::Opaque => "Opaque · Keeps surfaces solid across every theme.".into(), + SurfacePreference::Frosted => "Theme-colored glass where supported.".into(), + SurfacePreference::Opaque => "Solid surfaces for every theme.".into(), } } @@ -372,21 +412,6 @@ fn preview( } } -fn helper(mode: AppearanceMode, system: Appearance) -> SharedString { - match mode { - AppearanceMode::System => { - let resolved = if system.is_dark() { "dark" } else { "light" }; - format!( - "Following the system appearance — currently {resolved}. Zeron switches with \ - macOS, including scheduled changes." - ) - .into() - } - AppearanceMode::Light => "Always light, whatever the system is set to.".into(), - AppearanceMode::Dark => "Always dark, whatever the system is set to.".into(), - } -} - fn model_appearance(appearance: Appearance) -> zeron_theme::Appearance { match appearance { Appearance::Dark => zeron_theme::Appearance::Dark, @@ -519,11 +544,13 @@ fn import_scene_preview(variant: &zeron_theme::ThemeVariant) -> AnyElement { fn report_panel(theme: &Theme, report: &ImportReport) -> gpui::Stateful { let summary = format!( - "{} mapped · {} inferred/fallback · {} unsupported · {} warnings", + "{} mapped · {} adjusted · {} inferred/fallback · {} unsupported · {} warnings · {} validation", report.mappings.len(), + report.adjustments.len(), report.fallbacks.len(), report.dropped.len(), - report.warnings.len() + report.warnings.len(), + report.validation.len(), ); div() .id(SharedString::from(format!( @@ -543,6 +570,12 @@ fn report_panel(theme: &Theme, report: &ImportReport) -> gpui::Stateful gpui::Stateful, theme: &Theme, + window: &mut Window, cx: &mut Context, ) -> Option { + { + let dialog = self.import_dialog.as_mut()?; + if std::mem::take(&mut dialog.focus_pending) { + let input_focus = dialog.input.focus_handle(cx); + window.focus(&input_focus, cx); + } + } let dialog = self.import_dialog.as_ref()?; let input = dialog.input.clone(); + let focus = dialog.focus.clone(); let mode = dialog.mode; let compilation = dialog.compilation.clone(); let selected = dialog.selected.clone(); let review_variant = dialog.review_variant.clone(); let error = dialog.error.clone(); + let ready = compilation.is_some() && !selected.is_empty(); + let card_radius = 14.0; + let hairline = crate::theme::hairline(0.06); + let band = popover::band(); - let mode_control = |label: &'static str, value: InstallMode| { + let mode_control = |label: &'static str, description: &'static str, value: InstallMode| { let active = mode == value; - div() - .id(SharedString::from(format!( - "theme-import-mode-{}", - slug(label) - ))) - .px(px(10.0)) - .py(px(6.0)) - .rounded(px(7.0)) - .border_1() - .border_color(if active { theme.accent } else { theme.border }) - .bg(if active { - theme.accent_wash - } else { - theme.surface_raised.opacity(0.35) - }) - .text_size(px(12.0)) - .text_color(if active { - theme.accent - } else { - theme.text_muted - }) - .cursor_pointer() - .on_click(cx.listener(move |this, _, _, cx| { - if let Some(dialog) = this.import_dialog.as_mut() { - dialog.mode = value; + popover::menu_row( + theme, + active, + SharedString::from(format!("theme-import-mode-hover-{}", slug(label))), + ) + .id(SharedString::from(format!( + "theme-import-mode-{}", + slug(label) + ))) + .on_click(cx.listener(move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + dialog.mode = value; + } + cx.notify(); + })) + .child( + div() + .flex_1() + .min_w_0() + .child( + div() + .text_size(px(12.0)) + .text_color(if active { theme.text } else { theme.text_muted }) + .child(label), + ) + .child( + div() + .mt(px(1.0)) + .text_size(px(10.5)) + .text_color(theme.text_muted.opacity(0.55)) + .child(description), + ), + ) + .when(active, |row| { + row.child( + icons::icon(icons::CHECK) + .size(px(13.0)) + .flex_none() + .text_color(theme.accent), + ) + }) + }; + + let action_label = if compilation.is_some() { + "Import selected" + } else { + "Analyze" + }; + let action = popover::btn_primary(theme, "") + .id("theme-import-action") + .h(px(24.0)) + .px(px(8.0)) + .py(px(0.0)) + .rounded(px(5.0)) + .flex_none() + .flex() + .items_center() + .gap(px(5.0)) + .text_size(px(12.0)) + .when(compilation.is_some() && !ready, |button| { + button.opacity(0.45) + }) + .when(compilation.is_none() || ready, |button| { + button.on_click(cx.listener(move |this, _, _, cx| { + if this + .import_dialog + .as_ref() + .is_some_and(|dialog| dialog.compilation.is_some()) + { + this.finish_import(cx); + } else { + this.compile_import(cx); } - cx.notify(); })) - .child(label) - }; + }) + .child( + icons::icon(icons::RETURN) + .size(px(11.0)) + .text_color(theme.on_solid.opacity(0.8)), + ) + .child(action_label); - let mut card = popover::dialog_card(theme) - .id("theme-import-card") - .w(px(660.0)) - .max_h(px(720.0)) + let header = div() + .h(px(48.0)) + .flex_none() + .rounded_t(px(card_radius)) + .pl(px(12.0)) + .pr(px(10.0)) + .flex() + .items_center() + .gap(px(10.0)) + .bg(band) + .border_b_1() + .border_color(hairline) + .child( + popover::key_cap(theme).child( + icons::icon(icons::DOCUMENT_ADD) + .size(px(13.0)) + .text_color(theme.text_muted.opacity(0.75)), + ), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(14.0)) + .child(input.into_any_element()), + ) + .child( + popover::btn_ghost(theme, "Browse", "theme-import-browse") + .id("theme-import-browse") + .h(px(24.0)) + .px(px(8.0)) + .py(px(0.0)) + .rounded(px(5.0)) + .flex_none() + .on_click(cx.listener(|this, _, _, cx| this.choose_import_source(cx))), + ) + .child(action) + .child( + popover::key_cap(theme) + .id("theme-import-esc") + .cursor_pointer() + .hover(|style| style.bg(crate::theme::ink(0.09))) + .on_click(cx.listener(|this, _, _, cx| { + this.import_dialog = None; + cx.notify(); + })) + .text_size(px(11.0)) + .font_family(theme.font_mono.clone()) + .text_color(theme.text_muted.opacity(0.7)) + .child("esc"), + ); + + let mut main = div() + .id("theme-import-main") + .flex_1() + .min_w_0() + .h_full() .overflow_y_scroll() - .child(popover::dialog_title(theme, "Add a custom theme")); + .px(px(8.0)) + .py(px(8.0)) + .flex() + .flex_col() + .gap(px(3.0)); if let Some(ref compilation) = compilation { - card = card - .child( - popover::dialog_body( - theme, - format!( - "{} detected · Choose the variants to keep. Runtime components use the resolved Zeron palette, never VS Code token names.", - compilation.family.name - ), - ) - .mt(px(6.0)), - ) + main = main + .child(popover::menu_heading(theme, "Detected variants")) .child( div() - .mt(px(12.0)) - .flex() - .gap(px(8.0)) - .child(mode_control("Import snapshot", InstallMode::Snapshot)) - .child(mode_control("Link source", InstallMode::Link)), + .px(px(8.0)) + .pb(px(5.0)) + .text_size(px(11.0)) + .text_color(theme.text_muted.opacity(0.6)) + .child(SharedString::from(format!( + "{} · Select the variants to keep", + compilation.family.name + ))), ); for variant in &compilation.family.variants { let variant_id = variant.id.clone(); @@ -910,118 +1069,127 @@ impl AppearancePage { "Light" }; let report = compilation.reports.get(&variant.id); - card = card.child( - div() - .mt(px(10.0)) - .rounded(px(10.0)) - .border_1() - .border_color(if selected_now { - theme.border_strong - } else { - theme.border - }) - .bg(theme.surface_raised.opacity(0.28)) - .p(px(10.0)) - .child( - div() - .flex() - .items_center() - .gap(px(8.0)) - .child( - div() - .id(SharedString::from(format!( - "theme-import-select-{variant_id}" - ))) - .size(px(18.0)) - .rounded(px(5.0)) - .border_1() - .border_color(if selected_now { - theme.accent - } else { - theme.border_strong - }) - .bg(if selected_now { theme.accent } else { theme.bg }) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .when(selected_now, |item| { - item.child( - icons::icon(icons::CHECK) - .size(px(12.0)) - .text_color(theme.on_accent), - ) - }) - .on_click(cx.listener({ - let variant_id = variant_id.clone(); - move |this, _, _, cx| { - if let Some(dialog) = this.import_dialog.as_mut() { - if !dialog.selected.remove(&variant_id) { - dialog.selected.insert(variant_id.clone()); - } - } - cx.notify(); - } - })), - ) - .child( - div() - .flex_1() - .min_w_0() - .child( - div() - .text_size(px(12.5)) - .font_weight(gpui::FontWeight::MEDIUM) - .text_color(theme.text) - .child(SharedString::from(variant.name.clone())), + let sample = Theme::from_variant( + variant, + AccentSelection::ThemeDefault, + SurfacePreference::ThemeDefault, + ); + main = main.child( + popover::menu_row( + theme, + selected_now, + SharedString::from(format!("theme-import-row-hover-{variant_id}")), + ) + .id(SharedString::from(format!("theme-import-row-{variant_id}"))) + .flex_col() + .items_stretch() + .child( + div() + .flex() + .items_center() + .gap(px(9.0)) + .child( + div() + .id(SharedString::from(format!( + "theme-import-select-{variant_id}" + ))) + .size(px(18.0)) + .rounded(px(5.0)) + .border_1() + .border_color(if selected_now { + theme.accent + } else { + theme.border_strong + }) + .bg(if selected_now { theme.accent } else { theme.bg }) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(selected_now, |item| { + item.child( + icons::icon(icons::CHECK) + .size(px(12.0)) + .text_color(theme.on_accent), ) - .child( - div() - .text_size(px(11.0)) - .text_color(theme.text_muted) - .child(appearance), - ), - ) - .child( - compact_action( - theme, - if review_open { - "Hide mapping" - } else { - "Review mapping" - }, - format!("theme-import-review-{variant_id}"), - ) + }) .on_click(cx.listener({ let variant_id = variant_id.clone(); move |this, _, _, cx| { if let Some(dialog) = this.import_dialog.as_mut() { - dialog.review_variant = - if dialog.review_variant.as_deref() - == Some(variant_id.as_str()) - { - None - } else { - Some(variant_id.clone()) - }; + if !dialog.selected.remove(&variant_id) { + dialog.selected.insert(variant_id.clone()); + } } cx.notify(); } })), - ), + ) + .child(palette_preview(&sample)) + .child( + div() + .flex_1() + .min_w_0() + .child( + div() + .text_size(px(12.5)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(theme.text) + .child(SharedString::from(variant.name.clone())), + ) + .child( + div() + .text_size(px(11.0)) + .text_color(theme.text_muted.opacity(0.65)) + .child(appearance), + ), + ) + .child( + compact_action( + theme, + if review_open { + "Hide mapping" + } else { + "Review mapping" + }, + format!("theme-import-review-{variant_id}"), + ) + .on_click(cx.listener({ + let variant_id = variant_id.clone(); + move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + dialog.review_variant = + if dialog.review_variant.as_deref() + == Some(variant_id.as_str()) + { + None + } else { + Some(variant_id.clone()) + }; + } + cx.notify(); + } + })), + ), + ) + .when(review_open, |row| { + row.child( + div() + .mt(px(8.0)) + .pt(px(8.0)) + .border_t_1() + .border_color(hairline) + .child(import_scene_preview(variant)), ) - .when(review_open, |row| { - row.child(import_scene_preview(variant)) - .when_some(report, |row, report| { - row.child(report_panel(theme, report)) - }) - }), + .when_some(report, |row, report| row.child(report_panel(theme, report))) + }), ); } for failure in &compilation.failures { - card = card.child( + main = main.child( div() - .mt(px(8.0)) + .px(px(8.0)) + .py(px(5.0)) .text_size(px(11.0)) .text_color(theme.warning) .child(SharedString::from(format!( @@ -1031,90 +1199,176 @@ impl AppearancePage { ); } } else { - card = card - .child( - popover::dialog_body( - theme, - "Paste a VS Code theme JSON/JSONC file, package.json, or extension folder. Zeron detects variants and appearance automatically.", - ) - .mt(px(6.0)), - ) + main = main + .child(popover::menu_heading(theme, "Add a theme")) .child( - div() - .mt(px(14.0)) - .flex() - .items_center() - .gap(px(8.0)) + popover::menu_row(theme, false, "theme-import-local-source-hover") + .id("theme-import-local-source") + .on_click(cx.listener(|this, _, _, cx| this.choose_import_source(cx))) .child( - popover::dialog_field(input.into_any_element()) - .flex_1() - .min_w_0(), + icons::icon(icons::FOLDER_WITH_FILES) + .size(px(15.0)) + .flex_none() + .text_color(theme.text_muted.opacity(0.8)), ) .child( - compact_action(theme, "Choose…", "theme-import-choose") - .on_click(cx.listener(|this, _, _, cx| { - this.choose_import_source(cx) - })), - ), + div() + .flex_1() + .min_w_0() + .child( + div() + .text_size(px(12.5)) + .text_color(theme.text) + .child("Choose a local source"), + ) + .child( + div() + .mt(px(1.0)) + .text_size(px(10.5)) + .text_color(theme.text_muted.opacity(0.55)) + .child("Theme file, package.json, or extension folder"), + ), + ) + .child(popover::kbd_hint(theme, "Browse")), ) .child( div() - .mt(px(10.0)) - .flex() - .gap(px(8.0)) - .child(mode_control("Import snapshot", InstallMode::Snapshot)) - .child(mode_control("Link source", InstallMode::Link)), + .mx(px(8.0)) + .mt(px(7.0)) + .pt(px(10.0)) + .border_t_1() + .border_color(hairline) + .text_size(px(11.0)) + .line_height(px(16.0)) + .text_color(theme.text_muted.opacity(0.55)) + .child( + "Zeron detects light and dark variants, maps the palette, and validates contrast before import.", + ), ); } - if let Some(error) = error { - card = card.child( + let rail = div() + .w(px(196.0)) + .flex_none() + .h_full() + .border_l_1() + .border_color(hairline) + .px(px(8.0)) + .py(px(8.0)) + .flex() + .flex_col() + .gap(px(3.0)) + .child(popover::menu_heading(theme, "Import mode")) + .child(mode_control( + "Import snapshot", + "Keep a self-contained copy", + InstallMode::Snapshot, + )) + .child(mode_control( + "Link source", + "Reload changes from disk", + InstallMode::Link, + )) + .child(div().h(px(1.0)).mx(px(2.0)).my(px(7.0)).bg(hairline)) + .child( div() - .mt(px(10.0)) - .text_size(px(11.5)) - .text_color(theme.danger) - .child(error), + .px(px(8.0)) + .flex() + .items_start() + .gap(px(6.0)) + .text_size(px(10.5)) + .line_height(px(15.0)) + .text_color(theme.text_muted.opacity(0.5)) + .child( + icons::icon(icons::INFO_CIRCLE) + .size(px(12.0)) + .flex_none() + .mt(px(1.0)), + ) + .child("Theme tokens are compiled into Zeron roles."), ); - } - let ready = compilation.is_some() && !selected.is_empty(); - card = card.child( - div() - .mt(px(16.0)) - .flex() - .justify_end() - .gap(px(8.0)) - .child( - popover::btn_ghost(theme, "Cancel", "theme-import-cancel") - .id("theme-import-cancel") - .on_click(cx.listener(|this, _, _, cx| { - this.import_dialog = None; - cx.notify(); - })), + let body = div() + .h(px(if compilation.is_some() { 460.0 } else { 250.0 })) + .flex() + .items_stretch() + .child(main) + .child(rail); + + let footer = div() + .flex_none() + .rounded_b(px(card_radius)) + .bg(band) + .border_t_1() + .border_color(hairline) + .px(px(12.0)) + .py(px(8.0)) + .flex() + .items_center() + .gap(px(12.0)) + .child(popover::key_hint( + theme, + icons::RETURN, + if compilation.is_some() { + "Import selected" + } else { + "Analyze" + }, + )) + .child(popover::key_hint_text(theme, "esc", "Close")) + .when_some(error, |footer, error| { + footer.child( + div() + .ml_auto() + .min_w_0() + .truncate() + .text_size(px(11.0)) + .text_color(theme.danger) + .child(error), ) - .when(compilation.is_none(), |actions| { - actions.child( - popover::btn_primary(theme, "Analyze source") - .id("theme-import-analyze") - .on_click(cx.listener(|this, _, _, cx| this.compile_import(cx))), - ) - }) - .when(compilation.is_some(), |actions| { - actions.child( - popover::btn_primary(theme, "Import selected") - .id("theme-import-finish") - .opacity(if ready { 1.0 } else { 0.45 }) - .when(ready, |button| { - button - .on_click(cx.listener(|this, _, _, cx| this.finish_import(cx))) - }), - ) - }), - ); - Some(popover::modal( + }); + + let card = popover::palette_card(theme, px(680.0), card_radius) + .id("theme-import-card") + .track_focus(&focus) + .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| { + match popover::classify_key( + event.keystroke.key.as_str(), + event.keystroke.modifiers.platform, + event.keystroke.modifiers.control, + ) { + popover::MenuKey::Escape => { + this.import_dialog = None; + cx.notify(); + } + popover::MenuKey::Enter | popover::MenuKey::ModEnter => { + if this + .import_dialog + .as_ref() + .is_some_and(|dialog| dialog.compilation.is_some()) + { + this.finish_import(cx); + } else { + this.compile_import(cx); + } + } + _ => {} + } + })) + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.import_dialog = None; + cx.notify(); + })) + .child(header) + .child(body) + .child(footer) + .into_any_element(); + + Some(popover::modal_glass( "theme-import-dialog", viewport, - card.into_any_element(), + card, + card_radius, )) } @@ -1270,18 +1524,20 @@ impl AppearancePage { ), ) .child( - compact_action(theme, "Duplicate", format!("theme-duplicate-{id}")) - .on_click(cx.listener({ - let id = id.clone(); - move |this, _, _, cx| { - if let Err(error) = - theme_library::duplicate_as_snapshot(&id, cx) - { - this.library_error = Some(error.to_string().into()); - } - cx.notify(); + compact_action( + theme, + "Duplicate as editable", + format!("theme-duplicate-{id}"), + ) + .on_click(cx.listener({ + let id = id.clone(); + move |this, _, _, cx| { + if let Err(error) = theme_library::duplicate_as_editable(&id, cx) { + this.library_error = Some(error.to_string().into()); } - })), + cx.notify(); + } + })), ) .when(linked, |actions| { actions.child( @@ -1312,14 +1568,17 @@ impl AppearancePage { .into_any_element() } - fn render_theme_library(&mut self, theme: &Theme, cx: &mut Context) -> AnyElement { + fn render_theme_library_rows( + &mut self, + theme: &Theme, + cx: &mut Context, + ) -> Vec { let entries = theme_library::entries(cx); let (linked, imported): (Vec<_>, Vec<_>) = entries .into_iter() .partition(|entry| entry.source.is_linked()); - let builtins = ThemeRegistry::builtin().families.len(); let mut rows = vec![ - widgets::card_row(theme, true) + widgets::card_row(theme, false) .child(widgets::row_tile(theme, icons::FOLDER_WITH_FILES)) .child( div() @@ -1330,7 +1589,7 @@ impl AppearancePage { theme, vec![ div() - .child("Built-in, imported, and linked theme families.") + .child("Import or link custom themes.") .into_any_element(), ], )), @@ -1341,24 +1600,6 @@ impl AppearancePage { .on_click(cx.listener(|this, _, _, cx| this.open_import(cx))), ) .into_any_element(), - widgets::card_row(theme, false) - .child(widgets::row_tile(theme, icons::ZERON_LOGO)) - .child( - div() - .flex_1() - .child(widgets::row_title(theme, "Built-in")) - .child(widgets::meta_line( - theme, - vec![ - div() - .child(SharedString::from(format!( - "{builtins} curated families · Updated with Zeron." - ))) - .into_any_element(), - ], - )), - ) - .into_any_element(), ]; if !imported.is_empty() { rows.push( @@ -1400,9 +1641,7 @@ impl AppearancePage { .map(|entry| self.render_library_entry(entry, theme, cx)), ); } - widgets::section_card(theme) - .children(rows) - .into_any_element() + rows } } @@ -1413,11 +1652,6 @@ impl Render for AppearancePage { let current_themes = appearance::themes(cx); let current_accent = appearance::accent(cx); let current_surface = appearance::surface(cx); - let system = cx - .try_global::() - .map(|state| state.system) - .unwrap_or_default(); - let cards = AppearanceMode::ALL .into_iter() .map(|mode| { @@ -1465,7 +1699,8 @@ impl Render for AppearancePage { ], )), ) - .child(selector), + .child(selector) + .into_any_element(), ); } @@ -1494,13 +1729,73 @@ impl Render for AppearancePage { )) }) .collect::>(); - let library = self.render_theme_library(&theme, cx); + let mut settings_rows = theme_rows; + settings_rows.push( + widgets::card_row(&theme, false) + .child(widgets::row_tile(&theme, icons::TUNING)) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(&theme, "Accent color")) + .child(widgets::meta_line( + &theme, + vec![ + div() + .child(SharedString::from(accent_helper(current_accent))) + .into_any_element(), + ], + )), + ) + .child( + div() + .flex_none() + .ml(px(10.0)) + .flex() + .items_center() + .gap(px(6.0)) + .children(accent_controls), + ) + .into_any_element(), + ); + settings_rows.push( + widgets::card_row(&theme, false) + .child(widgets::row_tile(&theme, icons::WIDGET)) + .child( + div() + .flex_1() + .min_w_0() + .child(widgets::row_title(&theme, "Glass")) + .child(widgets::meta_line( + &theme, + vec![ + div() + .child(SharedString::from(surface_helper( + current_surface, + theme.surface_treatment, + ))) + .into_any_element(), + ], + )), + ) + .child( + div() + .flex_none() + .ml(px(10.0)) + .flex() + .items_center() + .gap(px(6.0)) + .children(surface_controls), + ) + .into_any_element(), + ); + settings_rows.extend(self.render_theme_library_rows(&theme, cx)); let library_warning = self .library_error .clone() .or_else(|| theme_library::load_warning(cx).map(SharedString::from)); let modal = self - .render_import_dialog(window.viewport_size(), &theme, cx) + .render_import_dialog(window.viewport_size(), &theme, window, cx) .or_else(|| self.render_review_dialog(window.viewport_size(), &theme, cx)); div() @@ -1527,78 +1822,7 @@ impl Render for AppearancePage { .child(widgets::field_label(&theme, "Appearance")) .child(widgets::option_card_row().children(cards)), ) - .child( - div() - .mt(px(16.0)) - .text_size(px(12.0)) - .text_color(theme.text_muted) - .line_height(px(18.0)) - .child(helper(current_mode, system)), - ) - .child(widgets::section_card(&theme).children(theme_rows)) - .child( - widgets::section_card(&theme) - .child( - widgets::card_row(&theme, true) - .child(widgets::row_tile(&theme, icons::TUNING)) - .child( - div() - .flex_1() - .min_w_0() - .child(widgets::row_title(&theme, "Accent color")) - .child(widgets::meta_line( - &theme, - vec![ - div() - .child(SharedString::from(accent_helper( - current_accent, - ))) - .into_any_element(), - ], - )), - ) - .child( - div() - .flex_none() - .ml(px(10.0)) - .flex() - .items_center() - .gap(px(6.0)) - .children(accent_controls), - ), - ) - .child( - widgets::card_row(&theme, false) - .child(widgets::row_tile(&theme, icons::WIDGET)) - .child( - div() - .flex_1() - .min_w_0() - .child(widgets::row_title(&theme, "Glass")) - .child(widgets::meta_line( - &theme, - vec![ - div() - .child(SharedString::from(surface_helper( - current_surface, - theme.surface_treatment, - ))) - .into_any_element(), - ], - )), - ) - .child( - div() - .flex_none() - .ml(px(10.0)) - .flex() - .items_center() - .gap(px(6.0)) - .children(surface_controls), - ), - ), - ) - .child(library) + .child(widgets::section_card(&theme).children(settings_rows)) .when_some(library_warning, |page, warning| { page.child( div() @@ -1651,33 +1875,14 @@ mod tests { #[test] fn surface_helper_explains_theme_default_and_global_overrides() { let default = surface_helper(SurfacePreference::ThemeDefault, SurfaceTreatment::Opaque); - assert!(default.contains("theme recommends opaque")); + assert!(default.contains("opaque default")); assert!( surface_helper(SurfacePreference::Frosted, SurfaceTreatment::Opaque) - .contains("wherever the platform supports blur") + .contains("where supported") ); assert!( surface_helper(SurfacePreference::Opaque, SurfaceTreatment::Frosted) - .contains("across every theme") + .contains("every theme") ); } - - #[test] - fn system_helper_names_the_resolved_appearance() { - let dark = helper(AppearanceMode::System, Appearance::Dark); - let light = helper(AppearanceMode::System, Appearance::Light); - assert!(dark.contains("currently dark"), "got {dark}"); - assert!(light.contains("currently light"), "got {light}"); - } - - #[test] - fn pinned_helpers_do_not_mention_following() { - for mode in [AppearanceMode::Light, AppearanceMode::Dark] { - for system in [Appearance::Light, Appearance::Dark] { - let copy = helper(mode, system).to_lowercase(); - assert!(!copy.contains("following"), "{mode:?}: {copy}"); - assert!(copy.contains("whatever the system"), "{mode:?}: {copy}"); - } - } - } } diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 313c844240..c8012fd56b 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -2181,13 +2181,15 @@ impl Shell { cx.background_executor() .timer(Duration::from_millis(SAVE_DEBOUNCE_MS)) .await; - // Re-stamp the appearance from the global before writing. The View - // menu changes it through `appearance::set_mode`, which never touches - // this shell's in-memory copy — without this, the next pane resize - // would quietly write the boot-time appearance back over the user's - // choice. + // Re-stamp every appearance-owned value from the globals before + // writing. These settings persist independently of the shell, and + // correctness must not depend on a Shell render happening before + // this debounce fires. let Ok(snapshot) = this.update(cx, |shell, cx| { shell.settings.appearance = crate::appearance::mode(cx); + shell.settings.theme_selection = crate::appearance::themes(cx); + shell.settings.accent = crate::appearance::accent(cx); + shell.settings.surface = crate::appearance::surface(cx); shell.settings.clone() }) else { return; diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 3a34399709..25936d3192 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -2728,25 +2728,8 @@ impl Shell { }); let card = - div() + popover::palette_card(&theme, px(680.0), card_radius) .id("add-space-palette") - .w(px(680.0)) - .rounded(px(card_radius)) - .border_1() - .border_color(crate::theme::hairline(0.10)) - // The popover_card glass recipe: a translucent tint over the - // frosted backdrop blur (`popover::modal` wraps in `frosted`) — - // an opaque fill here killed the vibrancy every other float has. - .bg(if theme.is_frost() { - theme.glass_overlay() - } else { - theme.surface_overlay - }) - .shadow_lg() - .overflow_hidden() - .flex() - .flex_col() - .text_color(theme.text) // On the keyboard dispatch path (see `AddSpaceFlow::focus`) — the // pickers' proven structure for frame-level keys with a focused // child input. diff --git a/crates/ui/src/theme.rs b/crates/ui/src/theme.rs index edefefdc59..50e9a9b27e 100644 --- a/crates/ui/src/theme.rs +++ b/crates/ui/src/theme.rs @@ -284,6 +284,44 @@ fn model_color(color: ModelColor) -> Hsla { hsla(h, s, l, color.a as f32 / 255.0) } +fn harden_model_foreground( + color: ModelColor, + backgrounds: &[ModelColor], + minimum: f32, + preferred_target: Option, +) -> ModelColor { + let minimum_contrast = |candidate: ModelColor| { + backgrounds + .iter() + .map(|background| candidate.contrast(*background)) + .fold(f32::INFINITY, f32::min) + }; + if minimum_contrast(color) >= minimum { + return color; + } + let mut targets = Vec::with_capacity(3); + if let Some(target) = preferred_target { + targets.push(target); + } + targets.extend([ModelColor::BLACK, ModelColor::WHITE]); + let mut best = color; + let mut best_contrast = minimum_contrast(color); + for target in targets { + for step in 1..=100 { + let candidate = color.mix(target, step as f32 / 100.0); + let contrast = minimum_contrast(candidate); + if contrast > best_contrast { + best = candidate; + best_contrast = contrast; + } + if contrast >= minimum { + return candidate; + } + } + } + best +} + /// [`CURRENT_APPEARANCE`] is process-wide, so under the parallel test runner /// any test that flips it — or asserts on the output of a helper that reads it /// ([`ink`], [`hairline`], [`wash`], …) — must hold this lock. Crate-visible @@ -774,18 +812,19 @@ impl Theme { /// appearance. A theme with unusually delicate contrast may therefore get /// denser glass, never silently broken text. fn contrast_checked_glass_alpha(&self, base: f32) -> f32 { - if base >= 1.0 { - return 1.0; - } - let adverse_backdrop = match self.appearance { - Appearance::Dark => grey(0xff), - Appearance::Light => grey(0), - }; + self.contrast_checked_tint_alpha(self.surface, base, self.adverse_backdrop()) + } + + /// Increase tint coverage only as far as needed for Zeron's shared text + /// roles. This is used for both window glass and in-app frosted surfaces, + /// whose blurred content can otherwise invalidate an imported palette's + /// original solid-background assumptions. + fn contrast_checked_tint_alpha(&self, tint: Hsla, base: f32, backdrop: Hsla) -> f32 { for step in 0..=20 { let alpha = base + (1.0 - base) * step as f32 / 20.0; - let composite = flatten(self.surface.opacity(alpha), adverse_backdrop); - if contrast_ratio(self.text, composite) >= 4.5 - && contrast_ratio(self.text_muted, composite) >= 3.0 + let composite = flatten(tint.opacity(alpha), backdrop); + if painted_contrast(self.text, composite) >= 4.5 + && painted_contrast(self.text_muted, composite) >= 3.0 { return alpha; } @@ -793,6 +832,13 @@ impl Theme { 1.0 } + fn adverse_backdrop(&self) -> Hsla { + match self.appearance { + Appearance::Dark => grey(0xff), + Appearance::Light => grey(0), + } + } + /// Whether this appearance paints translucent chrome over the blurred /// desktop. Glass-only recipes — backdrop blurs, translucent popover /// tints, per-glyph edge fades — must gate on this, not on @@ -825,10 +871,19 @@ impl Theme { /// [`crate::frost::frosted`]). Light coverage stays heavier because dark /// text is more vulnerable to unpredictable content behind a popover. pub fn glass_overlay(&self) -> Hsla { - match self.appearance { + let base = match self.appearance { Appearance::Dark => self.surface_overlay.opacity(0.50), Appearance::Light => self.surface_overlay.opacity(0.85), + }; + if !self.is_frost() { + return self.surface_overlay; } + self.surface_overlay + .opacity(self.contrast_checked_tint_alpha( + self.surface_overlay, + base.a, + self.adverse_backdrop(), + )) } /// The composer pill / question panel fill. Light's `input_bg` is opaque @@ -838,11 +893,17 @@ impl Theme { /// over the 0.80 frost — lowered on user request). Dark's 3% white wash /// is already glass-native. pub fn input_glass_bg(&self) -> Hsla { - if self.is_frost() && matches!(self.appearance, Appearance::Light) { - self.input_bg.opacity(0.30) - } else { - self.input_bg + if !self.is_frost() { + return self.input_bg; } + let base = if matches!(self.appearance, Appearance::Light) { + 0.30 + } else { + self.input_bg.a + }; + let window = flatten(self.glass(), self.adverse_backdrop()); + self.input_bg + .opacity(self.contrast_checked_tint_alpha(self.input_bg, base, window)) } /// Section-card fill (settings cards and similar in-panel cards). The @@ -850,11 +911,12 @@ impl Theme { /// frosted blur (user report), so glass thins it to a translucent tint; /// opaque platforms keep the true card tone. pub fn card_glass_bg(&self) -> Hsla { - if self.is_glass() { - self.surface.opacity(0.40) - } else { - self.surface + if !self.is_frost() { + return self.surface; } + let window = flatten(self.glass(), self.adverse_backdrop()); + self.surface + .opacity(self.contrast_checked_tint_alpha(self.surface, 0.40, window)) } /// The standard modal backdrop — see [`scrim`]. @@ -1094,6 +1156,28 @@ impl Theme { let mut theme = Self::for_preferences(appearance, accent_color); let colors = &variant.colors; let accent = variant.accent_for(accent_selection); + let text_backgrounds = [ + colors.background, + colors.shell, + colors.raised, + colors.card, + colors.dialog, + colors.overlay, + colors.input, + ]; + let is_curated_builtin = ThemeRegistry::builtin() + .variant(&variant.id) + .is_some_and(|builtin| builtin == variant); + let safe_text = if is_curated_builtin { + colors.text + } else { + harden_model_foreground(colors.text, &text_backgrounds, 4.5, None) + }; + let safe_text_muted = if is_curated_builtin { + colors.text_muted + } else { + harden_model_foreground(colors.text_muted, &text_backgrounds, 4.5, Some(safe_text)) + }; theme.variant_id = variant.id.clone().into(); theme.family_id = variant.family_id.clone().into(); theme.accent_selection = accent_selection; @@ -1109,12 +1193,16 @@ impl Theme { theme.element_active = model_color(colors.active); theme.border = model_color(colors.border); theme.border_strong = model_color(colors.border_strong); - theme.text = model_color(colors.text); - theme.text_muted = model_color(colors.text_muted); + theme.text = model_color(safe_text); + theme.text_muted = model_color(safe_text_muted); theme.text_faint = model_color(colors.text_faint); - theme.text_dim = model_color(colors.text_muted); + theme.text_dim = model_color(safe_text_muted); theme.solid = model_color(colors.solid); - theme.on_solid = model_color(colors.on_solid); + theme.on_solid = model_color(if is_curated_builtin { + colors.on_solid + } else { + harden_model_foreground(colors.on_solid, &[colors.solid], 4.5, Some(safe_text)) + }); theme.accent = model_color(accent.primary); theme.accent_strong = model_color(accent.strong); theme.accent_wash = model_color(accent.wash); @@ -1145,6 +1233,14 @@ impl Theme { theme.diff_del = model_color(colors.diff_delete); theme.diff_hunk_bg = model_color(colors.diff_hunk); theme.terminal = TerminalColors::from_variant(variant); + if !is_curated_builtin { + theme.terminal.foreground = model_color(harden_model_foreground( + variant.terminal.foreground, + &[variant.terminal.background], + 4.5, + Some(safe_text), + )); + } theme } @@ -1174,6 +1270,45 @@ impl Theme { accent_selection: AccentSelection, surface_preference: SurfacePreference, cx: &mut App, + ) { + Self::install_selection_inner( + appearance, + variant_id, + accent_selection, + surface_preference, + false, + cx, + ); + } + + /// Re-resolve a selection after its registry entry changed in place. + /// Linked themes keep stable ids across reloads, so identity comparisons + /// cannot detect that their resolved colors moved. Forcing the generation + /// invalidates paint caches that contain already-resolved colors. + pub fn reinstall_selection( + appearance: Appearance, + variant_id: &str, + accent_selection: AccentSelection, + surface_preference: SurfacePreference, + cx: &mut App, + ) { + Self::install_selection_inner( + appearance, + variant_id, + accent_selection, + surface_preference, + true, + cx, + ); + } + + fn install_selection_inner( + appearance: Appearance, + variant_id: &str, + accent_selection: AccentSelection, + surface_preference: SurfacePreference, + force_generation: bool, + cx: &mut App, ) { let next = Self::for_selection(appearance, variant_id, accent_selection, surface_preference); @@ -1185,7 +1320,7 @@ impl Theme { }); set_current_appearance(appearance); cx.set_global(next); - if changed { + if changed || force_generation { THEME_GENERATION.fetch_add(1, Ordering::Relaxed); } } @@ -1537,6 +1672,10 @@ pub fn contrast_ratio(a: Hsla, b: Hsla) -> f32 { (hi + 0.05) / (lo + 0.05) } +fn painted_contrast(foreground: Hsla, background: Hsla) -> f32 { + contrast_ratio(flatten(foreground, background), background) +} + /// Composite `fg` (which may be translucent) over an opaque `bg`, returning the /// opaque result — the color the eye actually receives. pub fn flatten(fg: Hsla, bg: Hsla) -> Hsla { @@ -1714,15 +1853,83 @@ mod tests { }; let composite = flatten(theme.glass(), adverse_backdrop); assert!( - contrast_ratio(theme.text, composite) >= 4.5, + painted_contrast(theme.text, composite) >= 4.5, "{} primary shell text", variant.id ); assert!( - contrast_ratio(theme.text_muted, composite) >= 3.0, + painted_contrast(theme.text_muted, composite) >= 3.0, "{} muted shell text", variant.id ); + for (surface_name, surface) in [ + ( + "floating overlay", + flatten(theme.glass_overlay(), adverse_backdrop), + ), + ("settings card", flatten(theme.card_glass_bg(), composite)), + ("input", flatten(theme.input_glass_bg(), composite)), + ] { + assert!( + painted_contrast(theme.text, surface) >= 4.5, + "{} primary text on {surface_name}", + variant.id + ); + assert!( + painted_contrast(theme.text_muted, surface) >= 3.0, + "{} muted text on {surface_name}", + variant.id + ); + } + } + } + + #[test] + fn runtime_hardening_protects_native_custom_theme_edits() { + let mut variant = ThemeRegistry::builtin() + .variant("zeron-dark") + .unwrap() + .clone(); + variant.colors.text = variant.colors.background; + variant.colors.text_muted = variant.colors.background; + variant.colors.on_solid = variant.colors.solid; + variant.terminal.foreground = variant.terminal.background; + + let theme = Theme::from_variant( + &variant, + AccentSelection::ThemeDefault, + SurfacePreference::Opaque, + ); + assert!(painted_contrast(theme.text, theme.bg) >= 4.5); + assert!(painted_contrast(theme.text_muted, theme.bg) >= 4.5); + assert!(painted_contrast(theme.on_solid, theme.solid) >= 4.5); + assert!(painted_contrast(theme.terminal.foreground, theme.terminal.background) >= 4.5); + } + + #[test] + fn runtime_hardening_leaves_curated_builtin_text_unchanged() { + for variant in ThemeRegistry::builtin() + .families + .iter() + .flat_map(|family| &family.variants) + { + let theme = Theme::from_variant( + variant, + AccentSelection::ThemeDefault, + SurfacePreference::Opaque, + ); + assert_eq!( + theme.text, + model_color(variant.colors.text), + "{} text", + variant.id + ); + assert_eq!( + theme.text_muted, + model_color(variant.colors.text_muted), + "{} muted text", + variant.id + ); } } diff --git a/crates/ui/src/theme_library.rs b/crates/ui/src/theme_library.rs index 5e162f00eb..2c00057d2d 100644 --- a/crates/ui/src/theme_library.rs +++ b/crates/ui/src/theme_library.rs @@ -62,10 +62,9 @@ pub fn install( return Err(anyhow!("custom theme library is not initialized")); } let state = cx.global_mut::(); - let id = state - .library - .install(compilation, selected_variant_ids, mode)?; - persist_and_activate(state)?; + let mut next = state.library.clone(); + let id = next.install(compilation, selected_variant_ids, mode)?; + persist_and_activate(state, next)?; reconcile_and_refresh(cx); Ok(id) } @@ -75,10 +74,11 @@ pub fn reload(id: &str, cx: &mut App) -> Result<()> { return Err(anyhow!("custom theme library is not initialized")); } let state = cx.global_mut::(); - let result = state.library.reload(id); + let mut next = state.library.clone(); + let result = next.reload(id); // Reload failures update the durable warning while deliberately preserving // the last known good family. - persist_and_activate(state)?; + persist_and_activate(state, next)?; reconcile_and_refresh(cx); result } @@ -92,8 +92,21 @@ pub fn duplicate_as_snapshot(id: &str, cx: &mut App) -> Result { return Err(anyhow!("custom theme library is not initialized")); } let state = cx.global_mut::(); - let duplicate = state.library.duplicate_as_snapshot(id)?; - persist_and_activate(state)?; + let mut next = state.library.clone(); + let duplicate = next.duplicate_as_snapshot(id)?; + persist_and_activate(state, next)?; + reconcile_and_refresh(cx); + Ok(duplicate) +} + +pub fn duplicate_as_editable(id: &str, cx: &mut App) -> Result { + if !cx.has_global::() { + return Err(anyhow!("custom theme library is not initialized")); + } + let state = cx.global_mut::(); + let mut next = state.library.clone(); + let duplicate = next.duplicate_as_editable(id, &state.data_dir)?; + persist_and_activate(state, next)?; reconcile_and_refresh(cx); Ok(duplicate) } @@ -125,25 +138,23 @@ fn mutate( return Err(anyhow!("custom theme library is not initialized")); } let state = cx.global_mut::(); - let output = operation(&mut state.library)?; - persist_and_activate(state)?; + let mut next = state.library.clone(); + let output = operation(&mut next)?; + persist_and_activate(state, next)?; reconcile_and_refresh(cx); Ok(output) } -fn persist_and_activate(state: &mut ThemeLibraryState) -> Result<()> { - state - .library - .save(&state.data_dir) +fn persist_and_activate(state: &mut ThemeLibraryState, next: CustomThemeLibrary) -> Result<()> { + next.save(&state.data_dir) .context("could not save custom theme library")?; replace_custom_families( - state - .library - .entries + next.entries .iter() .map(|entry| entry.family.clone()) .collect(), ); + state.library = next; state.load_warning = None; Ok(()) } @@ -166,3 +177,41 @@ fn reconcile_and_refresh(cx: &mut App) { } appearance::apply_registry_change(cx); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn failed_persistence_leaves_library_state_unchanged() { + let data_dir = tempfile::tempdir().unwrap(); + let blocking_file = data_dir.path().join("not-a-directory"); + std::fs::write(&blocking_file, "occupied").unwrap(); + let original = CustomThemeLibrary::default(); + let mut state = ThemeLibraryState { + data_dir: blocking_file, + library: original.clone(), + load_warning: Some("previous warning".into()), + }; + let mut next = original.clone(); + next.entries.push(CustomThemeEntry { + id: "unpersisted".into(), + name: "Unpersisted".into(), + source: zeron_theme::CustomThemeSource::ImportedSnapshot { + imported_from: None, + }, + family: zeron_theme::ThemeFamily { + id: "unpersisted".into(), + name: "Unpersisted".into(), + variants: Vec::new(), + }, + reports: Default::default(), + selected_variant_ids: Vec::new(), + status: zeron_theme::CustomThemeStatus::Ready, + }); + + assert!(persist_and_activate(&mut state, next).is_err()); + assert_eq!(state.library, original); + assert_eq!(state.load_warning.as_deref(), Some("previous warning")); + } +} diff --git a/docs/adr/0001-custom-themes-compile-to-resolved-families.md b/docs/adr/0001-custom-themes-compile-to-resolved-families.md index b59ac342b7..25c2c9eba7 100644 --- a/docs/adr/0001-custom-themes-compile-to-resolved-families.md +++ b/docs/adr/0001-custom-themes-compile-to-resolved-families.md @@ -9,11 +9,18 @@ Zeron supports native built-ins and needs to accept VS Code-compatible files and ## Decision -Every custom source compiles into the same source-neutral `ThemeFamily` and `ThemeVariant` model used by built-ins. Durable sources are represented as `ImportedSnapshot`, `LinkedFile`, or `LinkedPackage`. +Every custom source compiles into the same source-neutral `ThemeFamily` and `ThemeVariant` model used by built-ins. Durable sources are represented as `ImportedSnapshot`, `LinkedFile`, `LinkedPackage`, or `EditableFile`. Editable files contain native resolved-family JSON produced by duplicating an installed family. -Imported snapshots persist their compiled family. Linked sources persist both their location and their last successfully compiled family. A failed reload records a quiet warning and continues using the last known good family; it never replaces working runtime data with an invalid result. +Imported snapshots persist their compiled family. Linked and editable sources persist both their location and their last successfully compiled family. A failed reload records a quiet warning and continues using the last known good family; it never replaces working runtime data with an invalid result. Library mutations reach the runtime registry only after their durable state has been written successfully. -Compilation detects package variants and light/dark appearance, maps workbench, syntax, semantic-token, terminal, and accent roles, and emits a per-variant import report. Runtime UI resolves only compiled Zeron roles and never reads VS Code tokens. +Compilation detects package variants and light/dark appearance, maps workbench, syntax, semantic-token, terminal, and accent roles, validates the resulting Zeron palette, and emits a complete per-variant import report. Runtime UI resolves only compiled Zeron roles and never reads VS Code tokens. + +Compilation also hardens shared Zeron foreground and interaction roles against +their resolved solid surfaces. Repairs prefer semantically related source +tokens before minimally adjusting a color and are recorded in the report. +Structural validation failures block installation; contrast findings are +diagnostic because runtime resolution repeats essential text safeguards and +forced frost derives safe tint density from the composited background. Theme-default accents remain part of the compiled variant. Zeron accent presets override interaction roles only and do not alter syntax, terminal ANSI, diff, warning, error, or success roles. diff --git a/docs/theme-system.md b/docs/theme-system.md index f5ae44455c..b983943f1d 100644 --- a/docs/theme-system.md +++ b/docs/theme-system.md @@ -30,7 +30,9 @@ between built-in, imported, and linked themes. Forced frost derives window, floating, input, card, and hover tints from the variant's mapped shell roles instead of fixed Zeron greys. Its window tint becomes denser when necessary to keep primary text at 4.5:1 and muted text at 3:1 against the adverse desktop -luminance. +luminance. Floating overlays, settings cards, and inputs run the same +composited-background check independently; a delicate palette can therefore +receive a thicker material on one surface without disabling frost everywhere. macOS can frost the main window. Linux and Windows keep the main window opaque because compositor blur is not guaranteed; supported floating surfaces can @@ -87,16 +89,31 @@ The importer records `Opaque` as the variant's recommended surface treatment and reports that inference. This preserves the source palette by default while still allowing the independent Zeron surface preference to force frost. -The custom library has three source forms: +After source mapping, a deterministic hardening pass checks Zeron's shared +roles across every solid surface where they are painted. It keeps VS Code's +semantic distinctions (`foreground`, `descriptionForeground`, +`editor.foreground`, and component-specific foregrounds), promotes a stronger +related source role when the preferred one cannot carry the Zeron role, and +only then adjusts the original color toward a contrast-safe anchor. Primary, +muted, button, terminal, focus/status, and interaction roles are covered. +Foundational surfaces with alpha are flattened against the resolved theme +background so an opaque import cannot accidentally expose the desktop. Syntax, +terminal ANSI, diff, warning, error, and success identity remain theme-owned; +their unresolved quality findings stay visible in the report. + +The custom library has four source forms: - `ImportedSnapshot` persists a self-contained compiled copy. - `LinkedFile` follows one source theme file. - `LinkedPackage` follows a VS Code extension package. - -Linked sources reload explicitly. A failed reload stores a quiet warning and -continues using the last successfully compiled family. All three forms compile -to the same `ThemeFamily` model as built-ins, so runtime components remain -unaware of VS Code tokens. The library is stored in +- `EditableFile` follows a native resolved-family JSON file created by + “Duplicate as editable”. + +Linked and editable sources reload explicitly. A failed reload or validation +stores a quiet warning and continues using the last successfully compiled +family. All four forms resolve to the same `ThemeFamily` model as built-ins, so +runtime components remain unaware of VS Code tokens. Library mutations are +activated only after the updated library is persisted successfully. The library is stored in `{data_dir}/theme-library.json` and is loaded before the first palette is installed. @@ -119,16 +136,22 @@ cargo run -p zeron-theme --bin zeron-theme-import -- \ --license MIT ``` -The report records every source mapping, fallback, unsupported font style, -invalid color, and accent candidate. Zeron does not fetch or execute VSIX -packages at runtime; custom sources are local files and folders compiled into -resolved data. +The report records every source mapping, hardening adjustment, fallback, +unsupported font style, invalid color, validation result, and accent candidate +without truncating the advanced mapping review. Structural errors such as +duplicate ids or incomplete provenance block installation. Contrast findings +remain reviewable because compiled imports and runtime native-theme resolution +apply deterministic safeguards rather than rejecting an otherwise valid +source. Zeron does not fetch or execute VSIX packages at runtime; custom +sources are local files and folders compiled into resolved data. ## Acceptance and visual QA `ThemeRegistry::validate` checks unique ids, provenance, text contrast, interaction contrast, on-accent contrast, and terminal foreground contrast. -Tests also exercise every preset against both appearances. +Issues are classified as structural or contrast so callers cannot accidentally +treat a repairable quality finding as corrupt data. Tests also exercise every +preset against both appearances and adverse frosted backdrops. Before adding or updating a bundled variant, review both appearances where available across every `VisualFixture` scene: From 997de8daddc3053ff5a057e79f2d1a6b7c063ab1 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 12:45:53 +0200 Subject: [PATCH 5/9] chore(theme): refresh lockfile for v0.2.21 --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 96afa60493..c81722b855 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9328,7 +9328,7 @@ dependencies = [ [[package]] name = "zeron-theme" -version = "0.2.19" +version = "0.2.21" dependencies = [ "anyhow", "clap", From 6a343b6d31ea7b20ffde74411f285aa6a29b5c8b Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 16:28:47 +0200 Subject: [PATCH 6/9] refine theme import experience --- crates/ui/src/settings/appearance.rs | 764 ++++++++++++++------------- docs/toolcraft/agent-worklog.md | 58 ++ 2 files changed, 450 insertions(+), 372 deletions(-) create mode 100644 docs/toolcraft/agent-worklog.md diff --git a/crates/ui/src/settings/appearance.rs b/crates/ui/src/settings/appearance.rs index f4d646f3d4..c92a3657e6 100644 --- a/crates/ui/src/settings/appearance.rs +++ b/crates/ui/src/settings/appearance.rs @@ -129,11 +129,9 @@ impl AppearancePage { .iter() .map(|variant| variant.id.clone()) .collect(); - dialog.review_variant = compilation - .family - .variants - .first() - .map(|variant| variant.id.clone()); + // Mapping diagnostics are useful, but they are an advanced + // inspection surface rather than part of the happy path. + dialog.review_variant = None; dialog.compilation = Some(compilation); dialog.error = None; } @@ -440,7 +438,18 @@ fn compact_action( id: impl Into, ) -> gpui::Stateful { let id = id.into(); - popover::btn_ghost(theme, label, id.clone()).id(id) + popover::btn_ghost(theme, label, id.clone()) + .id(id) + .h(px(28.0)) + .px(px(9.0)) + .py(px(0.0)) + .rounded(px(7.0)) + .border_1() + .border_color(theme.border) + .bg(theme.surface_raised.opacity(0.34)) + .flex() + .items_center() + .text_size(px(11.5)) } fn import_scene_preview(variant: &zeron_theme::ThemeVariant) -> AnyElement { @@ -893,172 +902,163 @@ impl AppearancePage { let review_variant = dialog.review_variant.clone(); let error = dialog.error.clone(); let ready = compilation.is_some() && !selected.is_empty(); - let card_radius = 14.0; - let hairline = crate::theme::hairline(0.06); - let band = popover::band(); + let hairline = crate::theme::hairline(0.08); let mode_control = |label: &'static str, description: &'static str, value: InstallMode| { let active = mode == value; - popover::menu_row( - theme, - active, - SharedString::from(format!("theme-import-mode-hover-{}", slug(label))), - ) - .id(SharedString::from(format!( - "theme-import-mode-{}", - slug(label) - ))) - .on_click(cx.listener(move |this, _, _, cx| { - if let Some(dialog) = this.import_dialog.as_mut() { - dialog.mode = value; - } - cx.notify(); - })) - .child( - div() - .flex_1() - .min_w_0() - .child( - div() - .text_size(px(12.0)) - .text_color(if active { theme.text } else { theme.text_muted }) - .child(label), - ) - .child( - div() - .mt(px(1.0)) - .text_size(px(10.5)) - .text_color(theme.text_muted.opacity(0.55)) - .child(description), - ), - ) - .when(active, |row| { - row.child( - icons::icon(icons::CHECK) - .size(px(13.0)) - .flex_none() - .text_color(theme.accent), + div() + .id(SharedString::from(format!( + "theme-import-mode-{}", + slug(label) + ))) + .flex_1() + .min_w_0() + .p(px(10.0)) + .rounded(px(9.0)) + .border_1() + .border_color(if active { theme.accent } else { theme.border }) + .bg(if active { + theme.accent_wash + } else { + theme.surface_raised.opacity(0.28) + }) + .cursor_pointer() + .when(!active, |control| { + control.hover(|style| style.bg(theme.surface_raised_hover)) + }) + .on_click(cx.listener(move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + dialog.mode = value; + } + cx.notify(); + })) + .child( + div() + .flex() + .items_center() + .gap(px(7.0)) + .child( + div() + .size(px(16.0)) + .rounded_full() + .border_1() + .border_color(if active { + theme.accent + } else { + theme.border_strong + }) + .flex() + .items_center() + .justify_center() + .when(active, |dot| { + dot.child(div().size(px(8.0)).rounded_full().bg(theme.accent)) + }), + ) + .child( + div() + .text_size(px(12.0)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(if active { theme.text } else { theme.text_muted }) + .child(label), + ), + ) + .child( + div() + .mt(px(4.0)) + .ml(px(23.0)) + .text_size(px(10.5)) + .text_color(theme.text_muted.opacity(0.68)) + .child(description), ) - }) }; - let action_label = if compilation.is_some() { - "Import selected" - } else { - "Analyze" + let section_label = |label: &'static str| { + div() + .mb(px(7.0)) + .text_size(px(11.0)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(theme.text_muted) + .child(label) }; - let action = popover::btn_primary(theme, "") - .id("theme-import-action") - .h(px(24.0)) - .px(px(8.0)) - .py(px(0.0)) - .rounded(px(5.0)) - .flex_none() - .flex() - .items_center() - .gap(px(5.0)) - .text_size(px(12.0)) - .when(compilation.is_some() && !ready, |button| { - button.opacity(0.45) - }) - .when(compilation.is_none() || ready, |button| { - button.on_click(cx.listener(move |this, _, _, cx| { - if this - .import_dialog - .as_ref() - .is_some_and(|dialog| dialog.compilation.is_some()) - { - this.finish_import(cx); - } else { - this.compile_import(cx); - } - })) - }) - .child( - icons::icon(icons::RETURN) - .size(px(11.0)) - .text_color(theme.on_solid.opacity(0.8)), - ) - .child(action_label); - let header = div() - .h(px(48.0)) - .flex_none() - .rounded_t(px(card_radius)) - .pl(px(12.0)) - .pr(px(10.0)) + let mut main = div() + .id("theme-import-main") + .max_h(px(520.0)) + .overflow_y_scroll() + .px(px(20.0)) + .pb(px(18.0)) .flex() - .items_center() - .gap(px(10.0)) - .bg(band) - .border_b_1() - .border_color(hairline) - .child( - popover::key_cap(theme).child( - icons::icon(icons::DOCUMENT_ADD) - .size(px(13.0)) - .text_color(theme.text_muted.opacity(0.75)), - ), - ) + .flex_col() + .child(section_label("Source")) .child( div() - .flex_1() - .min_w_0() - .text_size(px(14.0)) - .child(input.into_any_element()), - ) - .child( - popover::btn_ghost(theme, "Browse", "theme-import-browse") - .id("theme-import-browse") - .h(px(24.0)) - .px(px(8.0)) - .py(px(0.0)) - .rounded(px(5.0)) - .flex_none() - .on_click(cx.listener(|this, _, _, cx| this.choose_import_source(cx))), + .flex() + .items_center() + .gap(px(8.0)) + .child( + popover::dialog_field(input.into_any_element()) + .flex_1() + .min_w_0() + .h(px(36.0)) + .py(px(0.0)) + .flex() + .items_center(), + ) + .child( + compact_action(theme, "Browse…", "theme-import-browse") + .h(px(36.0)) + .px(px(12.0)) + .flex_none() + .on_click(cx.listener(|this, _, _, cx| this.choose_import_source(cx))), + ), ) - .child(action) .child( - popover::key_cap(theme) - .id("theme-import-esc") - .cursor_pointer() - .hover(|style| style.bg(crate::theme::ink(0.09))) - .on_click(cx.listener(|this, _, _, cx| { - this.import_dialog = None; - cx.notify(); - })) - .text_size(px(11.0)) - .font_family(theme.font_mono.clone()) - .text_color(theme.text_muted.opacity(0.7)) - .child("esc"), + div() + .mt(px(16.0)) + .child(section_label("Keep it up to date")) + .child( + div() + .flex() + .gap(px(8.0)) + .child(mode_control( + "Import a copy", + "Works independently from the original file.", + InstallMode::Snapshot, + )) + .child(mode_control( + "Link to source", + "Reload changes from the file on disk.", + InstallMode::Link, + )), + ), ); - let mut main = div() - .id("theme-import-main") - .flex_1() - .min_w_0() - .h_full() - .overflow_y_scroll() - .px(px(8.0)) - .py(px(8.0)) - .flex() - .flex_col() - .gap(px(3.0)); - if let Some(ref compilation) = compilation { - main = main - .child(popover::menu_heading(theme, "Detected variants")) - .child( - div() - .px(px(8.0)) - .pb(px(5.0)) - .text_size(px(11.0)) - .text_color(theme.text_muted.opacity(0.6)) - .child(SharedString::from(format!( - "{} · Select the variants to keep", - compilation.family.name - ))), - ); + main = main.child( + div() + .mt(px(18.0)) + .pt(px(16.0)) + .border_t_1() + .border_color(hairline) + .flex() + .items_baseline() + .justify_between() + .child(section_label("Detected themes").mb(px(0.0))) + .child( + div() + .text_size(px(10.5)) + .text_color(theme.text_muted.opacity(0.65)) + .child(SharedString::from(format!( + "{} variant{}", + compilation.family.variants.len(), + if compilation.family.variants.len() == 1 { + "" + } else { + "s" + } + ))), + ), + ); for variant in &compilation.family.variants { let variant_id = variant.id.clone(); let selected_now = selected.contains(&variant_id); @@ -1075,121 +1075,133 @@ impl AppearancePage { SurfacePreference::ThemeDefault, ); main = main.child( - popover::menu_row( - theme, - selected_now, - SharedString::from(format!("theme-import-row-hover-{variant_id}")), - ) - .id(SharedString::from(format!("theme-import-row-{variant_id}"))) - .flex_col() - .items_stretch() - .child( - div() - .flex() - .items_center() - .gap(px(9.0)) - .child( - div() - .id(SharedString::from(format!( - "theme-import-select-{variant_id}" - ))) - .size(px(18.0)) - .rounded(px(5.0)) - .border_1() - .border_color(if selected_now { - theme.accent - } else { - theme.border_strong - }) - .bg(if selected_now { theme.accent } else { theme.bg }) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .when(selected_now, |item| { - item.child( - icons::icon(icons::CHECK) - .size(px(12.0)) - .text_color(theme.on_accent), + div() + .id(SharedString::from(format!("theme-import-row-{variant_id}"))) + .mt(px(8.0)) + .p(px(11.0)) + .rounded(px(10.0)) + .border_1() + .border_color(if selected_now { + theme.accent.opacity(0.7) + } else { + theme.border + }) + .bg(if selected_now { + theme.accent_wash.opacity(0.42) + } else { + theme.surface_raised.opacity(0.22) + }) + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(9.0)) + .child( + div() + .id(SharedString::from(format!( + "theme-import-select-{variant_id}" + ))) + .size(px(18.0)) + .rounded(px(5.0)) + .border_1() + .border_color(if selected_now { + theme.accent + } else { + theme.border_strong + }) + .bg(if selected_now { theme.accent } else { theme.bg }) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(selected_now, |item| { + item.child( + icons::icon(icons::CHECK) + .size(px(12.0)) + .text_color(theme.on_accent), + ) + }) + .on_click(cx.listener({ + let variant_id = variant_id.clone(); + move |this, _, _, cx| { + if let Some(dialog) = this.import_dialog.as_mut() { + if !dialog.selected.remove(&variant_id) { + dialog.selected.insert(variant_id.clone()); + } + } + cx.notify(); + } + })), + ) + .child(palette_preview(&sample)) + .child( + div() + .flex_1() + .min_w_0() + .child( + div() + .text_size(px(12.5)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(theme.text) + .child(SharedString::from(variant.name.clone())), ) - }) + .child( + div() + .text_size(px(11.0)) + .text_color(theme.text_muted.opacity(0.65)) + .child(appearance), + ), + ) + .child( + compact_action( + theme, + if review_open { + "Hide details" + } else { + "Details" + }, + format!("theme-import-review-{variant_id}"), + ) .on_click(cx.listener({ let variant_id = variant_id.clone(); move |this, _, _, cx| { if let Some(dialog) = this.import_dialog.as_mut() { - if !dialog.selected.remove(&variant_id) { - dialog.selected.insert(variant_id.clone()); - } + dialog.review_variant = + if dialog.review_variant.as_deref() + == Some(variant_id.as_str()) + { + None + } else { + Some(variant_id.clone()) + }; } cx.notify(); } })), - ) - .child(palette_preview(&sample)) - .child( + ), + ) + .when(review_open, |row| { + row.child( div() - .flex_1() - .min_w_0() - .child( - div() - .text_size(px(12.5)) - .font_weight(gpui::FontWeight::MEDIUM) - .text_color(theme.text) - .child(SharedString::from(variant.name.clone())), - ) - .child( - div() - .text_size(px(11.0)) - .text_color(theme.text_muted.opacity(0.65)) - .child(appearance), - ), + .mt(px(10.0)) + .pt(px(10.0)) + .border_t_1() + .border_color(hairline) + .child(import_scene_preview(variant)), ) - .child( - compact_action( - theme, - if review_open { - "Hide mapping" - } else { - "Review mapping" - }, - format!("theme-import-review-{variant_id}"), - ) - .on_click(cx.listener({ - let variant_id = variant_id.clone(); - move |this, _, _, cx| { - if let Some(dialog) = this.import_dialog.as_mut() { - dialog.review_variant = - if dialog.review_variant.as_deref() - == Some(variant_id.as_str()) - { - None - } else { - Some(variant_id.clone()) - }; - } - cx.notify(); - } - })), - ), - ) - .when(review_open, |row| { - row.child( - div() - .mt(px(8.0)) - .pt(px(8.0)) - .border_t_1() - .border_color(hairline) - .child(import_scene_preview(variant)), - ) - .when_some(report, |row, report| row.child(report_panel(theme, report))) - }), + .when_some(report, |row, report| row.child(report_panel(theme, report))) + }), ); } for failure in &compilation.failures { main = main.child( div() - .px(px(8.0)) - .py(px(5.0)) + .mt(px(8.0)) + .p(px(10.0)) + .rounded(px(8.0)) + .bg(theme.warning.opacity(0.08)) .text_size(px(11.0)) .text_color(theme.warning) .child(SharedString::from(format!( @@ -1199,137 +1211,150 @@ impl AppearancePage { ); } } else { - main = main - .child(popover::menu_heading(theme, "Add a theme")) - .child( - popover::menu_row(theme, false, "theme-import-local-source-hover") - .id("theme-import-local-source") - .on_click(cx.listener(|this, _, _, cx| this.choose_import_source(cx))) - .child( - icons::icon(icons::FOLDER_WITH_FILES) - .size(px(15.0)) - .flex_none() - .text_color(theme.text_muted.opacity(0.8)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child( - div() - .text_size(px(12.5)) - .text_color(theme.text) - .child("Choose a local source"), - ) - .child( - div() - .mt(px(1.0)) - .text_size(px(10.5)) - .text_color(theme.text_muted.opacity(0.55)) - .child("Theme file, package.json, or extension folder"), - ), - ) - .child(popover::kbd_hint(theme, "Browse")), - ) - .child( - div() - .mx(px(8.0)) - .mt(px(7.0)) - .pt(px(10.0)) - .border_t_1() - .border_color(hairline) - .text_size(px(11.0)) - .line_height(px(16.0)) - .text_color(theme.text_muted.opacity(0.55)) - .child( - "Zeron detects light and dark variants, maps the palette, and validates contrast before import.", - ), - ); + main = main.child( + div() + .mt(px(14.0)) + .flex() + .items_start() + .gap(px(7.0)) + .text_size(px(11.0)) + .line_height(px(16.0)) + .text_color(theme.text_muted.opacity(0.72)) + .child( + icons::icon(icons::INFO_CIRCLE) + .size(px(13.0)) + .mt(px(1.0)) + .flex_none(), + ) + .child("Zeron finds light and dark variants automatically."), + ); } - let rail = div() - .w(px(196.0)) - .flex_none() - .h_full() - .border_l_1() - .border_color(hairline) - .px(px(8.0)) - .py(px(8.0)) - .flex() - .flex_col() - .gap(px(3.0)) - .child(popover::menu_heading(theme, "Import mode")) - .child(mode_control( - "Import snapshot", - "Keep a self-contained copy", - InstallMode::Snapshot, - )) - .child(mode_control( - "Link source", - "Reload changes from disk", - InstallMode::Link, - )) - .child(div().h(px(1.0)).mx(px(2.0)).my(px(7.0)).bg(hairline)) - .child( + if let Some(error) = error { + main = main.child( div() - .px(px(8.0)) + .mt(px(12.0)) + .p(px(10.0)) + .rounded(px(8.0)) + .bg(theme.danger.opacity(0.08)) .flex() .items_start() - .gap(px(6.0)) - .text_size(px(10.5)) - .line_height(px(15.0)) - .text_color(theme.text_muted.opacity(0.5)) + .gap(px(7.0)) + .text_size(px(11.0)) + .line_height(px(16.0)) + .text_color(theme.danger) .child( - icons::icon(icons::INFO_CIRCLE) - .size(px(12.0)) + icons::icon(icons::DANGER_TRIANGLE) + .size(px(13.0)) .flex_none() .mt(px(1.0)), ) - .child("Theme tokens are compiled into Zeron roles."), + .child(div().flex_1().min_w_0().truncate().child(error)), ); + } - let body = div() - .h(px(if compilation.is_some() { 460.0 } else { 250.0 })) + let header = div() + .px(px(20.0)) + .pt(px(18.0)) + .pb(px(16.0)) .flex() - .items_stretch() - .child(main) - .child(rail); + .items_start() + .gap(px(16.0)) + .child( + div() + .flex_1() + .min_w_0() + .child(popover::dialog_title(theme, "Add a theme")) + .child( + popover::dialog_body( + theme, + "Import a local theme into your library or keep it linked to its source.", + ) + .mt(px(4.0)), + ), + ) + .child( + div() + .id("theme-import-close") + .size(px(28.0)) + .rounded(px(7.0)) + .border_1() + .border_color(theme.border) + .bg(theme.surface_raised.opacity(0.28)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|style| style.bg(theme.surface_raised_hover)) + .on_click(cx.listener(|this, _, _, cx| { + this.import_dialog = None; + cx.notify(); + })) + .child( + icons::icon(icons::CLOSE) + .size(px(12.0)) + .text_color(theme.text_muted), + ), + ); let footer = div() - .flex_none() - .rounded_b(px(card_radius)) - .bg(band) .border_t_1() .border_color(hairline) - .px(px(12.0)) - .py(px(8.0)) + .bg(theme.surface_raised.opacity(0.18)) + .px(px(20.0)) + .py(px(12.0)) .flex() .items_center() - .gap(px(12.0)) - .child(popover::key_hint( - theme, - icons::RETURN, - if compilation.is_some() { - "Import selected" - } else { - "Analyze" - }, - )) - .child(popover::key_hint_text(theme, "esc", "Close")) - .when_some(error, |footer, error| { - footer.child( - div() - .ml_auto() - .min_w_0() - .truncate() - .text_size(px(11.0)) - .text_color(theme.danger) - .child(error), + .justify_end() + .gap(px(8.0)) + .child( + compact_action(theme, "Cancel", "theme-import-cancel") + .h(px(34.0)) + .px(px(13.0)) + .on_click(cx.listener(|this, _, _, cx| { + this.import_dialog = None; + cx.notify(); + })), + ) + .child( + popover::btn_primary( + theme, + if compilation.is_some() { + "Import selected" + } else { + "Analyze theme" + }, ) - }); + .id("theme-import-action") + .h(px(34.0)) + .px(px(14.0)) + .py(px(0.0)) + .flex() + .items_center() + .when(compilation.is_some() && !ready, |button| { + button.opacity(0.45) + }) + .when(compilation.is_none() || ready, |button| { + button.on_click(cx.listener(move |this, _, _, cx| { + if this + .import_dialog + .as_ref() + .is_some_and(|dialog| dialog.compilation.is_some()) + { + this.finish_import(cx); + } else { + this.compile_import(cx); + } + })) + }), + ); - let card = popover::palette_card(theme, px(680.0), card_radius) + let card = popover::dialog_card(theme) .id("theme-import-card") + .w(px(600.0)) + .max_h(px(760.0)) + .p(px(0.0)) + .overflow_hidden() .track_focus(&focus) .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| { match popover::classify_key( @@ -1360,16 +1385,11 @@ impl AppearancePage { cx.notify(); })) .child(header) - .child(body) + .child(main) .child(footer) .into_any_element(); - Some(popover::modal_glass( - "theme-import-dialog", - viewport, - card, - card_radius, - )) + Some(popover::modal("theme-import-dialog", viewport, card)) } fn render_review_dialog( diff --git a/docs/toolcraft/agent-worklog.md b/docs/toolcraft/agent-worklog.md new file mode 100644 index 0000000000..c8a4d0fbd3 --- /dev/null +++ b/docs/toolcraft/agent-worklog.md @@ -0,0 +1,58 @@ +# Agent worklog + +## 2026-08-22 — Theme import experience + +### Product goal + +Make adding a custom theme feel like a short settings task rather than a command-palette workflow, while keeping source compilation, variant selection, snapshot/link installation, and optional mapping review intact. + +### Control section inventory + +- Source + - Local file/package/folder field + - Browse action +- Installation + - Snapshot or linked-source choice +- Detected themes + - Variant selection + - Palette preview + - Optional mapping details +- Completion + - Cancel + - Analyze or import primary action +- Installed theme + - Reload when linked + - Reveal source + - Review mapping + - Duplicate as editable + - Unlink when linked + - Remove + +### Decisions + +- Use a conventional, compact modal with a title, supporting copy, body, and footer actions. +- Remove command-palette chrome, keyboard-hint footer, duplicated primary actions, and the permanent side rail. +- Keep snapshot/link as an inline segmented choice with concise explanations. +- Keep mapping details collapsed by default; show them only when requested for a variant. +- Render installed-theme actions as bordered controls rather than bare text. +- Preserve theme compilation, persistence, settings transfer, source linking, and runtime selection behavior. +- No timeline, layers, export changes, custom renderer, or new persistence are required. + +### Implementation plan + +- Update `crates/ui/src/settings/appearance.rs` to simplify the import dialog layout, make import errors visible in the body/footer, collapse technical mapping by default, and restyle installed-theme actions. +- Add or adjust focused unit coverage for any extracted presentation helpers where practical. +- Run `cargo fmt --check`, the relevant `zeron-ui` tests/checks, and a local app build. +- Verify the settings page and both import states in the local app browser/UI at the desktop viewport shown in the supplied screenshots. + +### Verification tier + +Tier 2: compile and test the affected Rust UI crate, then visually inspect the settings page plus empty and analyzed import states. The change is UI-only and does not alter compilation or persistence formats. + +### Verification result + +- `cargo fmt --check` passes. +- `cargo check -p zeron-ui` passes with existing workspace warnings. +- `cargo test -p zeron-ui --lib settings::appearance` passes (4 tests). +- A packaged debug build was opened on macOS and the Appearance page, installed-theme row, and empty import state were visually inspected at 1365 × 768. +- The final visual pass found and removed a remaining overflowing helper sentence; long error paths are now explicitly truncated within the dialog. From 8d2d2bc29f7f433e47bc0f7d3136bef2921fde5c Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 16:32:49 +0200 Subject: [PATCH 7/9] chore(theme): refresh lockfile for v0.2.27 --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index c81722b855..91b6e5df01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9328,7 +9328,7 @@ dependencies = [ [[package]] name = "zeron-theme" -version = "0.2.21" +version = "0.2.27" dependencies = [ "anyhow", "clap", From 222f63228dad3248337fc84136dbe291d4e40d31 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 19:27:19 +0200 Subject: [PATCH 8/9] fix(theme): harden linked imports and persistence --- THIRD_PARTY_NOTICES.md | 76 +++++++++++ crates/theme/src/builtins.rs | 2 +- crates/theme/src/library.rs | 216 ++++++++++++++++++++++++++---- crates/theme/src/vscode.rs | 252 ++++++++++++++++++++++++++++++++--- 4 files changed, 501 insertions(+), 45 deletions(-) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index bb9abb7bb9..39bd9efa3c 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -14,3 +14,79 @@ queries are consumed from the pinned Rust crates listed in `Cargo.lock`. | Tree-sitter TOML, Markdown, YAML, Kotlin, Swift, SQL, Lua, Nix, Make and Containerfile grammars and queries | pinned in `Cargo.lock` | MIT-compatible; see each crate | Crate repositories recorded in `Cargo.lock` | The full Zeron distribution remains licensed under the terms in `LICENSE`. + +## Bundled theme palette adaptations + +Zeron includes manually curated palette adaptations derived from the projects +below. The source repository and exact audited revision are also embedded in +each resolved theme variant. These projects are not affiliated with or endorsed +by Zeron. Their names identify the corresponding palette adaptations. + +| Theme project | Audited revision | License and upstream notice | +| --- | --- | --- | +| Visual Studio Code Dark+/Light+ | `e33d147d4c0fa65ce17cb73ec9d798f064b4bf1f` | [MIT](https://github.com/microsoft/vscode/blob/e33d147d4c0fa65ce17cb73ec9d798f064b4bf1f/LICENSE.txt) | +| Catppuccin for VS Code | `befc9e6fc41980f4241408f7049755d47c06ff45` | [MIT](https://github.com/catppuccin/vscode/blob/befc9e6fc41980f4241408f7049755d47c06ff45/LICENSE) | +| Tokyo Night VS Code Theme | `7c0f11eaef322f293621ca7befe462214b7ea468` | [MIT](https://github.com/tokyo-night/tokyo-night-vscode-theme/blob/7c0f11eaef322f293621ca7befe462214b7ea468/LICENSE.txt) | +| Dracula for Visual Studio Code | `1b9ecf4d7e0c8cc2e2e890a7a41ad1db5fff1e6c` | [MIT](https://github.com/dracula/visual-studio-code/blob/1b9ecf4d7e0c8cc2e2e890a7a41ad1db5fff1e6c/LICENSE) | +| GitHub VS Code Theme | `cd78e5e4e7bcf132a6f428ae0f32264bb1b729cf` | [MIT](https://github.com/primer/github-vscode-theme/blob/cd78e5e4e7bcf132a6f428ae0f32264bb1b729cf/LICENSE) | +| Ayu for VS Code | `444ef92911cb75c3933c8003e3a7c79b6b6c914f` | [MIT](https://github.com/ayu-theme/vscode-ayu/blob/444ef92911cb75c3933c8003e3a7c79b6b6c914f/LICENSE) | +| Gruvbox Theme | `ca3b8ad203e84a884ca33fb84b5795cf43032709` | [MIT](https://github.com/jdinhify/vscode-theme-gruvbox/blob/ca3b8ad203e84a884ca33fb84b5795cf43032709/LICENSE) | +| Rosé Pine for VS Code | `d8f5ebe8e096fa833e997c07eb7685ee1677a4ba` | [MIT](https://github.com/rose-pine/vscode/blob/d8f5ebe8e096fa833e997c07eb7685ee1677a4ba/LICENSE) | +| Nord Visual Studio Code | `8ead09822c02d0d49d0f764104505e5a34d3689f` | [MIT](https://github.com/nordtheme/visual-studio-code/blob/8ead09822c02d0d49d0f764104505e5a34d3689f/license) | +| One Dark Pro | `e6ccf638d5b69aa38cd1005edb0ee7ba7ef6fedc` | [MIT](https://github.com/Binaryify/OneDark-Pro/blob/e6ccf638d5b69aa38cd1005edb0ee7ba7ef6fedc/LICENSE.txt) | +| Atom One Dark Theme | `a8be970644982221f9b61fb1c4b3da74b4beab79` | [MIT](https://github.com/akamud/vscode-theme-onedark/blob/a8be970644982221f9b61fb1c4b3da74b4beab79/LICENSE) | +| Night Owl | `cc291eba7976b20d7c66bde6883c27b902196b07` | [MIT](https://github.com/sdras/night-owl-vscode-theme/blob/cc291eba7976b20d7c66bde6883c27b902196b07/LICENSE.md) | +| Winter is Coming | `260547834cb6ac37dd5b8bb5842cc1c8d3164946` | [MIT](https://github.com/johnpapa/vscode-winteriscoming/blob/260547834cb6ac37dd5b8bb5842cc1c8d3164946/LICENSE.md) | +| Palenight Theme | `6291efaace90855abe3d79025327ca41b9a3138c` | [MIT](https://github.com/whizkydee/vscode-palenight-theme/blob/6291efaace90855abe3d79025327ca41b9a3138c/license.md) | +| SynthWave '84 | `ecfa2fe1279f7233663fa3f98a96e6756000567b` | [MIT](https://github.com/robb0wen/synthwave-vscode/blob/ecfa2fe1279f7233663fa3f98a96e6756000567b/LICENSE) | +| Shades of Purple | `e8eb49f33e5db05ceba6677367b33ddb27ad821c` | [MIT text with an additional “With condition” section](https://github.com/ahmadawais/shades-of-purple-vscode/blob/e8eb49f33e5db05ceba6677367b33ddb27ad821c/LICENSE.md); Zeron is MIT-licensed, satisfying the stated condition | +| Cobalt2 | `c4e9574372b85afad1682ed0fdd1ac0411c62512` | [MIT](https://github.com/wesbos/cobalt2-vscode/blob/c4e9574372b85afad1682ed0fdd1ac0411c62512/LICENSE) | +| Andromeda | `d1abb48c69493000aa0133a32d594eb25e523d4f` | [MIT](https://github.com/EliverLara/Andromeda/blob/d1abb48c69493000aa0133a32d594eb25e523d4f/LICENSE.md) | + +The palette values are adapted under the corresponding upstream license. The +linked license pages contain each project's copyright and permission notice and +are pinned to the same revision as the adapted source. + +Copyright notices retained from those pinned upstream licenses: + +- Copyright (c) 2015 - present Microsoft Corporation +- Copyright (c) 2021 Catppuccin +- Copyright (c) 2018-present Enkia +- Copyright (c) 2016 Dracula Theme +- Copyright (c) 2020 Primer +- Copyright (c) 2016 Ike Kurghinyan +- Copyright © 2017 JD +- Copyright (c) 2021 Rosé Pine +- Copyright (c) 2016-present Sven Greb (https://www.svengreb.de) +- Copyright (c) 2013-2022 Binaryify +- Copyright (c) 2015 Mahmoud Ali +- Copyright (c) 2018 Sarah Drasner +- Copyright (c) 2015-2017 JohnPapa.net, LLC +- Copyright (c) 2017-present Olaolu Olawuyi +- Copyright (c) 2019 Robb Owen +- Copyright (c) 2015-∞ Ahmad Awais +- Copyright (c) 2018 Wes Bos, Roberto Achar +- Copyright (c) 2017 + +The common MIT permission notice for the adaptations above follows: + +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the “Software”), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +The pinned Shades of Purple license additionally says that anything built with +it should also be MIT licensed. Zeron is distributed under MIT terms. diff --git a/crates/theme/src/builtins.rs b/crates/theme/src/builtins.rs index d386613409..aea1bc187a 100644 --- a/crates/theme/src/builtins.rs +++ b/crates/theme/src/builtins.rs @@ -1258,7 +1258,7 @@ fn shades_of_purple() -> ThemeVariant { "vscode", "https://github.com/ahmadawais/shades-of-purple-vscode", "e8eb49f33e5db05ceba6677367b33ddb27ad821c", - "MIT", + "MIT with additional upstream condition; see THIRD_PARTY_NOTICES.md", ), }) } diff --git a/crates/theme/src/library.rs b/crates/theme/src/library.rs index fd9aad73c9..2bd929780a 100644 --- a/crates/theme/src/library.rs +++ b/crates/theme/src/library.rs @@ -1,6 +1,6 @@ use std::collections::{BTreeMap, HashSet}; use std::fs; -use std::io; +use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use anyhow::{Context as _, Result, anyhow, bail}; @@ -12,6 +12,9 @@ use crate::vscode::{ use crate::{ThemeFamily, ThemeRegistry, replace_custom_families}; const LIBRARY_FILE: &str = "theme-library.json"; +const MAX_LIBRARY_BYTES: u64 = 16 * 1024 * 1024; +const MAX_LIBRARY_ENTRIES: usize = 256; +const MAX_LIBRARY_VARIANTS: usize = 1024; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum InstallMode { @@ -104,26 +107,31 @@ impl CustomThemeLibrary { pub fn load(data_dir: &Path) -> Result { let path = Self::path(data_dir); - let source = match fs::read_to_string(&path) { + let backup = backup_path(&path); + let load_path = if path.exists() { &path } else { &backup }; + let source = match read_library_file(load_path) { Ok(source) => source, Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()), Err(error) => { return Err(error).with_context(|| format!("could not read {}", path.display())); } }; - serde_json::from_str(&source).with_context(|| format!("could not parse {}", path.display())) + let library: Self = serde_json::from_str(&source) + .with_context(|| format!("could not parse {}", load_path.display()))?; + library.validate_capacity()?; + Ok(library) } pub fn save(&self, data_dir: &Path) -> Result<()> { + self.validate_capacity()?; fs::create_dir_all(data_dir) .with_context(|| format!("could not create {}", data_dir.display()))?; let path = Self::path(data_dir); - let temporary = path.with_extension("json.tmp"); - fs::write(&temporary, serde_json::to_vec_pretty(self)?) - .with_context(|| format!("could not write {}", temporary.display()))?; - fs::rename(&temporary, &path) - .with_context(|| format!("could not replace {}", path.display()))?; - Ok(()) + let encoded = serde_json::to_vec_pretty(self)?; + if encoded.len() as u64 > MAX_LIBRARY_BYTES { + bail!("custom theme library exceeds the {MAX_LIBRARY_BYTES}-byte limit"); + } + replace_file_recoverably(&path, &encoded) } pub fn install_runtime(&self) { @@ -166,6 +174,7 @@ impl CustomThemeLibrary { if family.variants.is_empty() { bail!("select at least one successfully compiled variant"); } + self.ensure_capacity_for(family.variants.len())?; let entry_id = unique_id( &family.id, self.entries.iter().map(|entry| entry.id.as_str()), @@ -214,6 +223,7 @@ impl CustomThemeLibrary { selected_variant_ids, status: CustomThemeStatus::Ready, }); + self.validate_capacity()?; Ok(entry_id) } @@ -254,19 +264,24 @@ impl CustomThemeLibrary { } CustomThemeSource::ImportedSnapshot { .. } => bail!("imported snapshots cannot reload"), }; + let wanted: HashSet<_> = entry.selected_variant_ids.iter().cloned().collect(); let compilation = match Self::compile(&path, &entry.id, &entry.name) { - Ok(compilation) if compilation.failures.is_empty() => compilation, Ok(compilation) => { - let message = compilation + let selected_failures = compilation .failures .iter() + .filter(|failure| wanted.contains(&failure.id)) .map(|failure| format!("{}: {}", failure.name, failure.message)) - .collect::>() - .join("; "); - entry.status = CustomThemeStatus::Warning { - message: message.clone(), - }; - return Err(anyhow!(message)); + .collect::>(); + if selected_failures.is_empty() { + compilation + } else { + let message = selected_failures.join("; "); + entry.status = CustomThemeStatus::Warning { + message: message.clone(), + }; + return Err(anyhow!(message)); + } } Err(error) => { entry.status = CustomThemeStatus::Warning { @@ -275,7 +290,6 @@ impl CustomThemeLibrary { return Err(error); } }; - let wanted: HashSet<_> = entry.selected_variant_ids.iter().cloned().collect(); let mut family = compilation.family; family .variants @@ -324,6 +338,7 @@ impl CustomThemeLibrary { .find(|entry| entry.id == id) .cloned() .ok_or_else(|| anyhow!("unknown custom theme `{id}`"))?; + self.ensure_capacity_for(original.family.variants.len())?; let new_id = unique_id( &format!("{}-copy", original.id), self.entries.iter().map(|entry| entry.id.as_str()), @@ -373,6 +388,7 @@ impl CustomThemeLibrary { .find(|entry| entry.id == id) .cloned() .ok_or_else(|| anyhow!("unknown custom theme `{id}`"))?; + self.ensure_capacity_for(original.family.variants.len())?; let new_id = unique_id( &format!("{}-copy", original.id), self.entries.iter().map(|entry| entry.id.as_str()), @@ -385,11 +401,7 @@ impl CustomThemeLibrary { fs::create_dir_all(&editable_dir) .with_context(|| format!("could not create {}", editable_dir.display()))?; let path = editable_dir.join(format!("{new_id}.zeron-theme.json")); - let temporary = path.with_extension("json.tmp"); - fs::write(&temporary, serde_json::to_vec_pretty(&family)?) - .with_context(|| format!("could not write {}", temporary.display()))?; - fs::rename(&temporary, &path) - .with_context(|| format!("could not replace {}", path.display()))?; + replace_file_recoverably(&path, &serde_json::to_vec_pretty(&family)?)?; let selected_variant_ids = family .variants @@ -413,10 +425,105 @@ impl CustomThemeLibrary { self.entries.retain(|entry| entry.id != id); self.entries.len() != before } + + fn validate_capacity(&self) -> Result<()> { + if self.entries.len() > MAX_LIBRARY_ENTRIES { + bail!("custom theme library is limited to {MAX_LIBRARY_ENTRIES} entries"); + } + let variants = self + .entries + .iter() + .try_fold(0usize, |count, entry| { + count.checked_add(entry.family.variants.len()) + }) + .ok_or_else(|| anyhow!("custom theme variant count overflow"))?; + if variants > MAX_LIBRARY_VARIANTS { + bail!("custom theme library is limited to {MAX_LIBRARY_VARIANTS} variants"); + } + Ok(()) + } + + fn ensure_capacity_for(&self, additional_variants: usize) -> Result<()> { + if self.entries.len() >= MAX_LIBRARY_ENTRIES { + bail!("custom theme library is limited to {MAX_LIBRARY_ENTRIES} entries"); + } + let current = self + .entries + .iter() + .try_fold(0usize, |count, entry| { + count.checked_add(entry.family.variants.len()) + }) + .ok_or_else(|| anyhow!("custom theme variant count overflow"))?; + if current + .checked_add(additional_variants) + .is_none_or(|total| total > MAX_LIBRARY_VARIANTS) + { + bail!("custom theme library is limited to {MAX_LIBRARY_VARIANTS} variants"); + } + Ok(()) + } +} + +fn backup_path(path: &Path) -> PathBuf { + path.with_extension("json.bak") +} + +fn read_library_file(path: &Path) -> io::Result { + let size = fs::metadata(path)?.len(); + if size > MAX_LIBRARY_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("custom theme library exceeds the {MAX_LIBRARY_BYTES}-byte limit"), + )); + } + fs::read_to_string(path) +} + +/// Replace `path` without relying on rename-over-existing semantics (which +/// Windows does not provide). The backup also lets startup recover if the +/// process stops between the two renames. Symlinks are not followed here: the +/// managed data-dir path itself is replaced. +fn replace_file_recoverably(path: &Path, contents: &[u8]) -> Result<()> { + let temporary = path.with_extension("json.tmp"); + let backup = backup_path(path); + let mut file = fs::File::create(&temporary) + .with_context(|| format!("could not create {}", temporary.display()))?; + file.write_all(contents) + .with_context(|| format!("could not write {}", temporary.display()))?; + file.sync_all() + .with_context(|| format!("could not sync {}", temporary.display()))?; + drop(file); + + if !path.exists() { + fs::rename(&temporary, path) + .with_context(|| format!("could not install {}", path.display()))?; + return Ok(()); + } + if backup.exists() { + fs::remove_file(&backup) + .with_context(|| format!("could not remove stale backup {}", backup.display()))?; + } + fs::rename(path, &backup).with_context(|| format!("could not back up {}", path.display()))?; + if let Err(error) = fs::rename(&temporary, path) { + let restore = fs::rename(&backup, path); + return match restore { + Ok(()) => Err(error).with_context(|| format!("could not replace {}", path.display())), + Err(restore_error) => Err(anyhow!( + "could not replace {}; recovery copy remains at {} ({error}); restore failed: {restore_error}", + path.display(), + backup.display() + )), + }; + } + // The committed primary is authoritative. A stale backup is harmless and + // will be cleared before the next save; cleanup failure must not make the + // caller believe an already-committed replacement failed. + let _ = fs::remove_file(&backup); + Ok(()) } fn load_editable_family(path: &Path, expected_id: &str) -> Result { - let source = fs::read_to_string(path) + let source = read_library_file(path) .with_context(|| format!("could not read editable theme {}", path.display()))?; let family: ThemeFamily = serde_json::from_str(&source) .with_context(|| format!("could not parse editable theme {}", path.display()))?; @@ -514,6 +621,34 @@ mod tests { assert!(matches!(entry.status, CustomThemeStatus::Warning { .. })); } + #[test] + fn linked_reload_ignores_failures_in_unselected_sibling_variants() { + let dir = tempfile::tempdir().unwrap(); + package(dir.path()); + let compiled = + CustomThemeLibrary::compile(dir.path(), "test-family", "Test Family").unwrap(); + let selected = vec!["test-family-test-light".to_string()]; + let mut library = CustomThemeLibrary::default(); + let id = library + .install(compiled, &selected, InstallMode::Link) + .unwrap(); + fs::write(dir.path().join("themes/dark.json"), "not json").unwrap(); + fs::write( + dir.path().join("themes/light.json"), + r##"{"colors":{"editor.background":"#fafafa","foreground":"#202020","focusBorder":"#0066cc"}}"##, + ) + .unwrap(); + + library.reload(&id).unwrap(); + let entry = library.entry(&id).unwrap(); + assert_eq!(entry.family.variants.len(), 1); + assert_eq!( + entry.family.variants[0].colors.background, + "#fafafa".parse().unwrap() + ); + assert_eq!(entry.status, CustomThemeStatus::Ready); + } + #[test] fn linked_reload_hardens_low_contrast_palette() { let dir = tempfile::tempdir().unwrap(); @@ -565,9 +700,42 @@ mod tests { let data = tempfile::tempdir().unwrap(); library.save(data.path()).unwrap(); + library.save(data.path()).unwrap(); assert_eq!(CustomThemeLibrary::load(data.path()).unwrap(), library); } + #[test] + fn load_recovers_from_backup_left_between_replacement_renames() { + let data = tempfile::tempdir().unwrap(); + let library = CustomThemeLibrary::default(); + library.save(data.path()).unwrap(); + let path = CustomThemeLibrary::path(data.path()); + fs::rename(&path, backup_path(&path)).unwrap(); + + assert_eq!(CustomThemeLibrary::load(data.path()).unwrap(), library); + } + + #[test] + fn rejects_libraries_above_entry_limit_before_serializing_or_cloning() { + let source = tempfile::tempdir().unwrap(); + package(source.path()); + let compiled = + CustomThemeLibrary::compile(source.path(), "test-family", "Test Family").unwrap(); + let mut library = CustomThemeLibrary::default(); + let id = library + .install(compiled, &[], InstallMode::Snapshot) + .unwrap(); + let template = library.entry(&id).unwrap().clone(); + while library.entries.len() <= MAX_LIBRARY_ENTRIES { + library.entries.push(template.clone()); + } + + let data = tempfile::tempdir().unwrap(); + let error = library.save(data.path()).unwrap_err(); + assert!(error.to_string().contains("limited to 256 entries")); + assert!(!CustomThemeLibrary::path(data.path()).exists()); + } + #[test] fn contrast_findings_do_not_block_install() { let source = tempfile::tempdir().unwrap(); diff --git a/crates/theme/src/vscode.rs b/crates/theme/src/vscode.rs index e8f222969d..538691f349 100644 --- a/crates/theme/src/vscode.rs +++ b/crates/theme/src/vscode.rs @@ -17,6 +17,10 @@ use crate::{ ThemeVariant, ValidationIssue, }; +const MAX_SOURCE_BYTES: u64 = 4 * 1024 * 1024; +const MAX_INCLUDE_DEPTH: usize = 32; +const MAX_PACKAGE_VARIANTS: usize = 128; + #[derive(Debug, Clone)] pub struct ImportOptions { pub id: String, @@ -119,6 +123,7 @@ pub enum DetectedThemeSource { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VariantFailure { + pub id: String, pub name: String, pub path: PathBuf, pub message: String, @@ -157,7 +162,12 @@ pub fn compile_source(path: &Path, options: CompileOptions) -> Result Result { - let normalized = load_theme(&path, &mut Vec::new())?; + let root = path + .parent() + .ok_or_else(|| anyhow!("{} has no parent directory", path.display()))? + .canonicalize() + .with_context(|| format!("could not resolve theme root for {}", path.display()))?; + let normalized = load_theme(&path, &root, &mut Vec::new())?; let appearance = detect_appearance(&path, None, &normalized); let name = theme_declared_name(&path).unwrap_or_else(|| options.family_name.clone()); let imported = convert( @@ -191,8 +201,7 @@ fn compile_package( package_json: &Path, options: CompileOptions, ) -> Result { - let source = fs::read_to_string(package_json) - .with_context(|| format!("could not read {}", package_json.display()))?; + let source = read_bounded(package_json, "package manifest")?; let manifest: Value = json5::from_str(&source) .with_context(|| format!("could not parse {}", package_json.display()))?; let declarations = manifest @@ -207,9 +216,19 @@ fn compile_package( if declarations.is_empty() { bail!("{} declares no theme variants", package_json.display()); } + if declarations.len() > MAX_PACKAGE_VARIANTS { + bail!( + "{} declares {} theme variants; the limit is {MAX_PACKAGE_VARIANTS}", + package_json.display(), + declarations.len() + ); + } let package_root = package_json .parent() .ok_or_else(|| anyhow!("{} has no parent directory", package_json.display()))?; + let package_root = package_root + .canonicalize() + .with_context(|| format!("could not resolve package root {}", package_root.display()))?; let family_name = manifest .get("displayName") .or_else(|| manifest.get("name")) @@ -228,10 +247,16 @@ fn compile_package( .filter(|label| !label.trim().is_empty()) .map(str::to_owned) .unwrap_or_else(|| format!("Variant {}", index + 1)); + let mut id = format!("{}-{}", options.family_id, slug(&label)); + if !used_ids.insert(id.clone()) { + id = format!("{id}-{}", index + 1); + used_ids.insert(id.clone()); + } let relative = match declaration.get("path").and_then(Value::as_str) { Some(path) => path, None => { failures.push(VariantFailure { + id, name: label, path: package_json.to_path_buf(), message: "theme declaration has no path".into(), @@ -240,13 +265,8 @@ fn compile_package( } }; let theme_path = package_root.join(relative); - let mut id = format!("{}-{}", options.family_id, slug(&label)); - if !used_ids.insert(id.clone()) { - id = format!("{id}-{}", index + 1); - used_ids.insert(id.clone()); - } let result = (|| { - let normalized = load_theme(&theme_path, &mut Vec::new())?; + let normalized = load_theme(&theme_path, &package_root, &mut Vec::new())?; let appearance = detect_appearance( &theme_path, declaration.get("uiTheme").and_then(Value::as_str), @@ -271,6 +291,7 @@ fn compile_package( variants.push(imported.theme); } Err(error) => failures.push(VariantFailure { + id, name: label, path: theme_path, message: error.to_string(), @@ -299,7 +320,7 @@ fn compile_package( } fn theme_declared_name(path: &Path) -> Option { - let source = fs::read_to_string(path).ok()?; + let source = read_bounded(path, "theme source").ok()?; let value: Value = json5::from_str(&source).ok()?; value .get("name") @@ -322,7 +343,7 @@ fn detect_appearance( _ => {} } } - if let Ok(source) = fs::read_to_string(path) + if let Ok(source) = read_bounded(path, "theme source") && let Ok(value) = json5::from_str::(&source) && let Some(kind) = value.get("type").and_then(Value::as_str) { @@ -369,20 +390,30 @@ fn slug(value: &str) -> String { } pub fn import_file(path: &Path, options: ImportOptions) -> Result { - let normalized = load_theme(path, &mut Vec::new())?; + let canonical = path + .canonicalize() + .with_context(|| format!("could not resolve {}", path.display()))?; + let root = canonical + .parent() + .ok_or_else(|| anyhow!("{} has no parent directory", canonical.display()))? + .to_path_buf(); + let normalized = load_theme(&canonical, &root, &mut Vec::new())?; convert(normalized, options) } -fn load_theme(path: &Path, stack: &mut Vec) -> Result { +fn load_theme(path: &Path, root: &Path, stack: &mut Vec) -> Result { let path = path .canonicalize() .with_context(|| format!("could not resolve {}", path.display()))?; + ensure_contained(&path, root, "theme source")?; if stack.contains(&path) { bail!("VS Code theme include cycle: {}", path.display()); } + if stack.len() >= MAX_INCLUDE_DEPTH { + bail!("VS Code theme include depth exceeds {MAX_INCLUDE_DEPTH}"); + } stack.push(path.clone()); - let source = - fs::read_to_string(&path).with_context(|| format!("could not read {}", path.display()))?; + let source = read_bounded(&path, "theme source")?; let value: Value = json5::from_str(&source) .with_context(|| format!("could not parse JSONC theme {}", path.display()))?; let object = value @@ -391,7 +422,7 @@ fn load_theme(path: &Path, stack: &mut Vec) -> Result let mut theme = if let Some(include) = object.get("include").and_then(Value::as_str) { let include_path = resolve_relative(&path, include); - load_theme(&include_path, stack)? + load_theme(&include_path, root, stack)? } else { NormalizedTheme::default() }; @@ -410,6 +441,10 @@ fn load_theme(path: &Path, stack: &mut Vec) -> Result Value::Array(rules) => theme.token_colors.extend(parse_token_rules(rules)), Value::String(relative) => { let token_path = resolve_relative(&path, relative); + let token_path = token_path + .canonicalize() + .with_context(|| format!("could not resolve {}", token_path.display()))?; + ensure_contained(&token_path, root, "external token file")?; theme.files.push(token_path.clone()); theme.token_colors.extend(load_token_file(&token_path)?); } @@ -428,6 +463,30 @@ fn load_theme(path: &Path, stack: &mut Vec) -> Result Ok(theme) } +fn ensure_contained(path: &Path, root: &Path, kind: &str) -> Result<()> { + if !path.starts_with(root) { + bail!( + "{kind} {} resolves outside selected theme root {}; symlinks are allowed only when their targets remain inside the root", + path.display(), + root.display() + ); + } + Ok(()) +} + +fn read_bounded(path: &Path, kind: &str) -> Result { + let size = fs::metadata(path) + .with_context(|| format!("could not inspect {kind} {}", path.display()))? + .len(); + if size > MAX_SOURCE_BYTES { + bail!( + "{kind} {} is {size} bytes; the limit is {MAX_SOURCE_BYTES}", + path.display() + ); + } + fs::read_to_string(path).with_context(|| format!("could not read {kind} {}", path.display())) +} + fn resolve_relative(owner: &Path, relative: &str) -> PathBuf { owner .parent() @@ -478,8 +537,7 @@ fn load_token_file(path: &Path) -> Result> { if extension.eq_ignore_ascii_case("tmTheme") || extension.eq_ignore_ascii_case("plist") { return load_textmate_plist(path); } - let source = fs::read_to_string(path) - .with_context(|| format!("could not read token file {}", path.display()))?; + let source = read_bounded(path, "token file")?; let value: Value = json5::from_str(&source) .with_context(|| format!("could not parse token file {}", path.display()))?; let values = value @@ -490,6 +548,15 @@ fn load_token_file(path: &Path) -> Result> { } fn load_textmate_plist(path: &Path) -> Result> { + let size = fs::metadata(path) + .with_context(|| format!("could not inspect TextMate plist {}", path.display()))? + .len(); + if size > MAX_SOURCE_BYTES { + bail!( + "TextMate plist {} is {size} bytes; the limit is {MAX_SOURCE_BYTES}", + path.display() + ); + } let value = plist::Value::from_file(path) .with_context(|| format!("could not parse TextMate plist {}", path.display()))?; let settings = value @@ -819,8 +886,7 @@ fn convert(theme: NormalizedTheme, options: ImportOptions) -> Result= 3.0); + let adjustment = imported + .report + .adjustments + .iter() + .find(|adjustment| adjustment.zeron_role == "textFaint") + .expect("textFaint adjustment is reported"); + assert_eq!(adjustment.original, "#202020"); + assert_eq!(adjustment.resolved, faint.to_string()); + assert!(adjustment.reason.contains("descriptionForeground")); + let mapping = imported + .report + .mappings + .iter() + .find(|mapping| mapping.zeron_role == "textFaint") + .unwrap(); + assert_eq!(mapping.vscode_key, "descriptionForeground"); + assert_eq!(mapping.value, faint.to_string()); + } + + #[test] + fn rejects_package_declarations_and_includes_outside_selected_root() { + let dir = tempfile::tempdir().unwrap(); + let package = dir.path().join("package"); + fs::create_dir_all(&package).unwrap(); + fs::write( + package.join("package.json"), + r#"{"contributes":{"themes":[{"label":"Escape","path":"../outside.json"}]}}"#, + ) + .unwrap(); + fs::write( + dir.path().join("outside.json"), + r##"{"colors":{"editor.background":"#111111"}}"##, + ) + .unwrap(); + let error = compile_source( + &package, + CompileOptions { + family_id: "escape".into(), + family_name: "Escape".into(), + source_url: "local".into(), + revision: "local".into(), + license: "User supplied".into(), + }, + ) + .unwrap_err(); + assert!(error.to_string().contains("outside selected theme root")); + + let nested = package.join("nested"); + fs::create_dir_all(&nested).unwrap(); + fs::write( + nested.join("theme.json"), + r#"{"include":"../../outside.json"}"#, + ) + .unwrap(); + let error = import_file(&nested.join("theme.json"), options()).unwrap_err(); + assert!(error.to_string().contains("outside selected theme root")); + + fs::write( + nested.join("tokens.json"), + r#"{"tokenColors":"../../outside.json"}"#, + ) + .unwrap(); + let error = import_file(&nested.join("tokens.json"), options()).unwrap_err(); + assert!(error.to_string().contains("outside selected theme root")); + } + + #[test] + fn bounds_include_depth_and_source_size() { + let dir = tempfile::tempdir().unwrap(); + for index in 0..=MAX_INCLUDE_DEPTH { + let source = if index == MAX_INCLUDE_DEPTH { + "{}".to_string() + } else { + format!(r#"{{"include":"{}.json"}}"#, index + 1) + }; + fs::write(dir.path().join(format!("{index}.json")), source).unwrap(); + } + let error = import_file(&dir.path().join("0.json"), options()).unwrap_err(); + assert!(error.to_string().contains("include depth exceeds")); + + let large = dir.path().join("large.json"); + let file = fs::File::create(&large).unwrap(); + file.set_len(MAX_SOURCE_BYTES + 1).unwrap(); + let error = import_file(&large, options()).unwrap_err(); + assert!(error.to_string().contains("the limit is")); + + let package = dir.path().join("package"); + fs::create_dir_all(&package).unwrap(); + let declarations = (0..=MAX_PACKAGE_VARIANTS) + .map(|index| format!(r#"{{"label":"{index}","path":"{index}.json"}}"#)) + .collect::>() + .join(","); + fs::write( + package.join("package.json"), + format!(r#"{{"contributes":{{"themes":[{declarations}]}}}}"#), + ) + .unwrap(); + let error = compile_source( + &package, + CompileOptions { + family_id: "large".into(), + family_name: "Large".into(), + source_url: "local".into(), + revision: "local".into(), + license: "User supplied".into(), + }, + ) + .unwrap_err(); + assert!(error.to_string().contains("declares 129 theme variants")); + } + #[test] fn flattens_translucent_foundational_surfaces() { let dir = tempfile::tempdir().unwrap(); From 42bcf74eba0ff6535a0eca7fe2babc9b1db04283 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 19:48:03 +0200 Subject: [PATCH 9/9] chore: format theme contribution --- crates/ui/src/transcript.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/crates/ui/src/transcript.rs b/crates/ui/src/transcript.rs index 90f5881354..96479fc084 100644 --- a/crates/ui/src/transcript.rs +++ b/crates/ui/src/transcript.rs @@ -5198,20 +5198,16 @@ fn chip_header_row( .when(running, |row| { // The sidebar working-row spinner, in the chip's trailing slot — // paint-local (fixed footprint), so it never moves the layout. - row.child( - div() - .flex_none() - .child(crate::loaders::mini_glyph_spinner( - format!( - "subagent-chip-{}", - tool.subagent_ref.as_deref().unwrap_or_default() - ), - 2.0, - theme.glyph, - view, - cx, - )), - ) + row.child(div().flex_none().child(crate::loaders::mini_glyph_spinner( + format!( + "subagent-chip-{}", + tool.subagent_ref.as_deref().unwrap_or_default() + ), + 2.0, + theme.glyph, + view, + cx, + ))) }) .when_some(trail, |row, trail| { // Trailing tile matching the group header's: a chevron for the