Skip to main content

theme/
paint.rs

1//! Context-free paint helpers: the process-wide appearance mirror and the
2//! free functions ([`ink`], [`hairline`], [`wash`], …) that element builders
3//! call without a `cx` in scope.
4
5use std::{
6    cell::Cell,
7    sync::atomic::{AtomicU8, AtomicU32, Ordering},
8};
9
10use gpui::{BoxShadow, Hsla, hsla, point, px};
11
12use crate::Appearance;
13
14/// Appearance outside a local material scope.
15static CURRENT_APPEARANCE: AtomicU8 = AtomicU8::new(0);
16
17/// Revision of the installed palette.
18static THEME_GENERATION: AtomicU32 = AtomicU32::new(0);
19
20/// The appearance the context-free paint helpers are painting for.
21pub fn current_appearance() -> Appearance {
22    if let Some(appearance) = SCOPED_APPEARANCE.with(Cell::get) {
23        return appearance;
24    }
25    match CURRENT_APPEARANCE.load(Ordering::Relaxed) {
26        1 => Appearance::Light,
27        _ => Appearance::Dark,
28    }
29}
30
31/// Cache key for the installed palette and current content appearance.
32pub fn theme_generation() -> u32 {
33    palette_revision()
34        .wrapping_mul(2)
35        .wrapping_add(u32::from(current_appearance() == Appearance::Light))
36}
37
38pub(crate) fn palette_revision() -> u32 {
39    THEME_GENERATION.load(Ordering::Relaxed)
40}
41
42thread_local! {
43    static SCOPED_APPEARANCE: Cell<Option<Appearance>> = const { Cell::new(None) };
44}
45
46pub(crate) struct AppearanceScope(Option<Appearance>);
47
48impl AppearanceScope {
49    pub(crate) fn new(appearance: Appearance) -> Self {
50        Self(SCOPED_APPEARANCE.with(|scope| scope.replace(Some(appearance))))
51    }
52}
53
54impl Drop for AppearanceScope {
55    fn drop(&mut self) {
56        SCOPED_APPEARANCE.with(|scope| scope.set(self.0));
57    }
58}
59
60/// [`CURRENT_APPEARANCE`] is process-wide, so under the parallel test runner
61/// any test that flips it — or asserts on the output of a helper that reads it
62/// ([`ink`], [`hairline`], [`wash`], …) — must hold this lock. Crate-visible
63/// because such tests exist outside this module too (see motion's tests).
64/// Tests that flip the appearance restore Dark before releasing the guard.
65/// Compiled unconditionally (not `cfg(test)`) so downstream crates' tests can
66/// use it too; it is not part of the public API.
67#[doc(hidden)]
68pub fn lock_appearance() -> std::sync::MutexGuard<'static, ()> {
69    static APPEARANCE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
70    APPEARANCE_LOCK.lock().unwrap_or_else(|e| e.into_inner())
71}
72
73/// Mark the installed palette as a new one, so anything caching resolved
74/// colors drops what it has. A brand change moves every token without moving
75/// the appearance, which is why this is separate from
76/// [`set_current_appearance`].
77pub(crate) fn bump_generation() {
78    THEME_GENERATION.fetch_add(1, Ordering::Relaxed);
79}
80
81/// Point the context-free paint helpers at an appearance. Called by
82/// [`Theme::install`](crate::theme::Theme::install); exposed for tests that
83/// build a theme without an `App`.
84pub fn set_current_appearance(appearance: Appearance) {
85    let encoded = match appearance {
86        Appearance::Dark => 0,
87        Appearance::Light => 1,
88    };
89    if CURRENT_APPEARANCE.swap(encoded, Ordering::Relaxed) != encoded {
90        THEME_GENERATION.fetch_add(1, Ordering::Relaxed);
91    }
92}
93
94/// Light-mode alpha multiplier for **fills** (hover/active washes, chip and pill
95/// backgrounds).
96///
97/// This was 0.5 on the theory that dark ink on a bright field reads heavier and
98/// should be scaled back. That theory is right for a *large* wash and badly wrong
99/// for everything else: this palette leans on very low alphas for its subtle
100/// fills — the composer plate is `ink(0.03)`, key caps are `ink(0.05)` — and
101/// halving those produced 1.5% black on white, which is nothing. The composer
102/// lost its background entirely and selected tabs stopped reading as selected.
103///
104/// The established light-UI scales (Primer, Radix) land subtle ≈ 3–4%, hover ≈ 8%,
105/// selected ≈ 14% black — which is where the dark palette's white alphas already
106/// sit. So the honest multiplier is 1: the same number in both appearances, with
107/// only the *tone* flipping. Any per-state correction belongs in that state's
108/// token, not in a blanket multiplier.
109pub const INK_FILL_SCALE: f32 = 1.0;
110
111/// Light-mode alpha multiplier for **hairlines** (borders, dividers, rings).
112/// Opposite of fills: a 1px edge has to hold its own against a bright surround,
113/// and the dark palette's white hairlines are deliberately faint. Scaling up
114/// keeps separators legible instead of dissolving into the panel.
115pub const INK_HAIRLINE_SCALE: f32 = 1.35;
116
117/// Lightness of [`hairline`] ink, dark then light.
118const HAIRLINE_TONE: (f32, f32) = (0.75, 0.25);
119
120/// Translucent **fill** ink for interactive states and chip plates: soft-white on
121/// dark, soft-black on light at [`INK_FILL_SCALE`] of the alpha.
122///
123/// Alphas are quoted in *dark-mode terms* at every call site — the dark theme is
124/// the tuned one — and the light value is derived. Callers keep one number and
125/// both appearances stay in the relationship the dark tuning established.
126///
127/// Fills must never rest on transparent BLACK in dark mode: fully opaque washes
128/// killed the glass and flashed dark mid-fade (user reports), so hover fades rest
129/// on `ink(0.0)`, which stays tonally correct at zero alpha.
130pub fn ink(alpha: f32) -> Hsla {
131    ink_for(current_appearance(), alpha)
132}
133
134pub(crate) fn ink_for(appearance: Appearance, alpha: f32) -> Hsla {
135    match appearance {
136        // Soft-white, not pure white: alphas are high enough to stay visible at
137        // the brightest backdrop the 0.90 glass scrim can produce.
138        Appearance::Dark => hsla(0.0, 0.0, 1.0, alpha),
139        Appearance::Light => hsla(0.0, 0.0, 0.0, alpha * INK_FILL_SCALE),
140    }
141}
142
143/// Translucent **hairline** ink for borders, dividers and rings: a light grey on
144/// dark, a dark grey on light at [`INK_HAIRLINE_SCALE`] of the alpha. Never
145/// pure white or black.
146///
147/// Separate from [`ink`] because edges and fills scale in opposite directions
148/// when the field brightens — a 1px line needs *more* ink on white, a plate needs
149/// less.
150pub fn hairline(alpha: f32) -> Hsla {
151    hairline_for(current_appearance(), alpha)
152}
153
154pub(crate) fn hairline_for(appearance: Appearance, alpha: f32) -> Hsla {
155    match appearance {
156        Appearance::Dark => hsla(0.0, 0.0, HAIRLINE_TONE.0, alpha),
157        Appearance::Light => hsla(
158            0.0,
159            0.0,
160            HAIRLINE_TONE.1,
161            (alpha * INK_HAIRLINE_SCALE).min(0.5),
162        ),
163    }
164}
165
166/// Interactive-state wash: a softened [`ink`] that stops short of pure black or
167/// white so hover plates read as tinted glass rather than paint.
168pub fn wash(alpha: f32) -> Hsla {
169    wash_for(current_appearance(), alpha)
170}
171
172pub(crate) fn wash_for(appearance: Appearance, alpha: f32) -> Hsla {
173    match appearance {
174        Appearance::Dark => hsla(0.0, 0.0, 0.92, alpha),
175        Appearance::Light => hsla(0.0, 0.0, 0.10, alpha * INK_FILL_SCALE),
176    }
177}
178
179/// Alpha of the standard modal backdrop in dark mode. Call sites that need a
180/// heavier or lighter scrim pass their own dark-mode alpha to [`scrim`].
181pub const SCRIM_ALPHA_DARK: f32 = 0.60;
182
183/// Modal backdrop at `alpha_dark` (quoted, as everywhere, in dark-mode terms).
184///
185/// Black in both appearances — a scrim's job is to darken what is behind it, and
186/// a "light scrim" of white would wash the modal out rather than seat it. What
187/// changes is strength: on a bright field a dark-mode-weight scrim reads as a
188/// blackout, so light mode scales to roughly half.
189pub fn scrim(alpha_dark: f32) -> Hsla {
190    scrim_for(current_appearance(), alpha_dark)
191}
192
193pub(crate) fn scrim_for(appearance: Appearance, alpha_dark: f32) -> Hsla {
194    match appearance {
195        Appearance::Dark => hsla(0.0, 0.0, 0.0, alpha_dark),
196        Appearance::Light => hsla(0.0, 0.0, 0.0, 0.32 * (alpha_dark / SCRIM_ALPHA_DARK)),
197    }
198}
199
200/// Recessed band behind a palette/picker header or footer strip.
201///
202/// A free function as well as a [`Theme`](crate::theme::Theme) field because the
203/// picker chrome that paints it is built from context-free helpers; both resolve
204/// to the same value.
205pub fn band() -> Hsla {
206    band_for(current_appearance())
207}
208
209pub(crate) fn band_for(appearance: Appearance) -> Hsla {
210    match appearance {
211        Appearance::Dark => hsla(0.0, 0.0, 0.0, 0.16),
212        // A recessed strip on white needs far less ink than on near-black; the
213        // dark 16% would read as a bruise.
214        Appearance::Light => hsla(0.0, 0.0, 0.0, 0.045),
215    }
216}
217
218/// Selected-state glass treatment (tabs, session rows, space rows):
219/// `../desktop`'s `--color-active` — white at 12% on dark, black at 6% on
220/// light, translucent enough for the vibrancy to read through (heavier flat
221/// washes blocked the glass, user request).
222///
223/// One rung over [`Theme::element_hover`](crate::theme::Theme::element_hover),
224/// carrying the ring in [`glass_selected_shadows`] on top. Selection *inside
225/// floating cards* is [`card_selected_bg`].
226pub fn glass_selected_bg() -> Hsla {
227    card_selected_bg()
228}
229
230/// The user message bubble's plate: the softened [`wash`] at 8% dark, 4%
231/// light. At the selection weight the bubble read too strong for settled
232/// content (user report), and an opaque plate before that read as a solid slab
233/// over glass.
234pub fn user_bubble_bg() -> Hsla {
235    match current_appearance() {
236        Appearance::Dark => wash(0.08),
237        Appearance::Light => wash(0.04),
238    }
239}
240
241/// Selected/keyboard-active treatment for rows and chips INSIDE a floating
242/// card (menu rows, the picker rail, segmented chips): `--color-active` again,
243/// tone-flipped by the palette convention so a card that is already the bright
244/// plane lifts with black at 6% rather than white.
245pub fn card_selected_bg() -> Hsla {
246    card_selected_bg_for(current_appearance())
247}
248
249pub(crate) fn card_selected_bg_for(appearance: Appearance) -> Hsla {
250    ink_for(appearance, if appearance.is_dark() { 0.12 } else { 0.06 })
251}
252
253/// The selected chip's bright outline, as an INSET shadow: gpui paints inset
254/// shadows ON TOP of the background, edges only — a border with zero layout
255/// cost. Drop shadows are filled rects painted BEHIND the element, and behind
256/// a 5% fill they showed straight through as an opaque dark plate with a
257/// greyed ring (user report) — nothing may paint behind a glass chip.
258///
259/// Light pins the ring at a flat 7% rather than the scaled hairline:
260/// heavier rings (the [`INK_HAIRLINE_SCALE`]d value, then 12%) outlined every
261/// selected chip in a dark box (user reports) — the ring should define the
262/// chip the way dark's 9% white ring does, not frame it.
263///
264/// There is deliberately NO drop-shadow seat under the light chip. Three
265/// recipes were tried (a tight 10% layer, a 6% contact + 5% ambient pair, a
266/// lone 4% whisper) and every one failed on sight: layers sum into a grey rim
267/// exactly where the chip meets the frost, gpui's small-radius blur reads
268/// coarse on a bright field, and the tab strip is a scroll container that
269/// clips its children vertically — any shadow escaping the chip gets cut off
270/// mid-fade. The near-opaque fill plus the ring carry selection, exactly as
271/// dark's wash plus ring does; the two appearances share one recipe now.
272pub fn glass_selected_shadows() -> Vec<BoxShadow> {
273    card_selected_shadows()
274}
275
276/// The elevation shadow a floating surface casts — `shadow_lg`'s shape, which
277/// is where it lived until the surface moved into the material. Painted cut to
278/// outside the shape, because the same drop shadow under a translucent fill is
279/// the grey plate [`card_selected_shadows`] records. [`SurfaceSpec::shadow`](crate::SurfaceSpec::shadow)
280/// says which looks carry one.
281pub fn surface_shadows() -> Vec<BoxShadow> {
282    vec![
283        BoxShadow {
284            color: hsla(0.0, 0.0, 0.0, 0.1),
285            offset: point(px(0.0), px(10.0)),
286            blur_radius: px(15.0),
287            spread_radius: px(-3.0),
288            inset: false,
289        },
290        BoxShadow {
291            color: hsla(0.0, 0.0, 0.0, 0.1),
292            offset: point(px(0.0), px(4.0)),
293            blur_radius: px(6.0),
294            spread_radius: px(-4.0),
295            inset: false,
296        },
297    ]
298}
299
300/// Centered frame shadow, with half-inset blur to leave room for its tail
301/// inside the transparent [`Theme::CLIENT_INSET`](crate::Theme::CLIENT_INSET) band.
302pub fn frame_shadows() -> Vec<BoxShadow> {
303    vec![BoxShadow {
304        color: hsla(0.0, 0.0, 0.0, 0.4),
305        offset: point(px(0.0), px(0.0)),
306        blur_radius: px(crate::Theme::CLIENT_INSET / 2.0),
307        spread_radius: px(0.0),
308        inset: false,
309    }]
310}
311
312/// The shadow `bezel::ui::window::content`'s floating card casts on the
313/// chrome around it. Its blur stays inside
314/// [`Theme::CONTENT_INSET`](crate::Theme::CONTENT_INSET), which the card's
315/// parent may clip at.
316pub fn content_shadows() -> Vec<BoxShadow> {
317    vec![BoxShadow {
318        color: hsla(0.0, 0.0, 0.0, 0.08),
319        offset: point(px(0.0), px(1.0)),
320        blur_radius: px(crate::Theme::CONTENT_INSET / 2.0),
321        spread_radius: px(0.0),
322        inset: false,
323    }]
324}
325
326/// Selection outline for rows and chips INSIDE a floating card (menu rows,
327/// the picker rail, segmented chips): the inset ring alone, in both
328/// appearances. Card rows fill with a translucent wash
329/// ([`card_selected_bg`]), and a drop shadow — a filled rect painted BEHIND
330/// the element — shows straight through a translucent fill as a grey plate
331/// (the same lesson [`glass_selected_shadows`] records for dark glass). The
332/// card already carries the elevation shadow; selection inside it only needs
333/// the edge.
334pub fn card_selected_shadows() -> Vec<BoxShadow> {
335    let color = match current_appearance() {
336        Appearance::Dark => hairline(0.09),
337        Appearance::Light => hsla(0.0, 0.0, HAIRLINE_TONE.1, 0.07),
338    };
339    vec![BoxShadow {
340        color,
341        offset: point(px(0.0), px(0.0)),
342        blur_radius: px(0.0),
343        spread_radius: px(1.0),
344        inset: true,
345    }]
346}