1use std::sync::LazyLock;
13
14use super::style::AdaptiveColor;
15use crate::{JsonValue, style::Color, tailwind};
16
17macro_rules! theme_colors {
18 ($( $(#[doc = $doc:literal])* $field:ident = $key:literal $(| $alias:literal)* ),* $(,)?) => {
19 #[derive(Debug, Clone, Copy, PartialEq, Default)]
21 pub struct ThemeColors {
22 $( $(#[doc = $doc])* pub $field: AdaptiveColor, )*
23 }
24
25 impl ThemeColors {
26 fn by_key(&mut self, key: &str) -> Option<&mut AdaptiveColor> {
28 Some(match key {
29 $( $key $(| $alias)* => &mut self.$field, )*
30 _ => return None,
31 })
32 }
33 }
34 };
35}
36
37theme_colors! {
38 accent = "accent.background",
40 accent_foreground = "accent.foreground",
42 background = "background",
44 foreground = "foreground",
46 border = "border",
48 caret = "caret",
50 danger = "danger.background",
52 danger_active = "danger.active.background",
54 danger_foreground = "danger.foreground",
56 group_box = "group_box.background",
58 group_box_foreground = "group_box.foreground",
60 info = "info.background",
62 info_active = "info.active.background",
64 info_foreground = "info.foreground",
66 input = "input.border",
68 link = "link" | "link.foreground",
70 link_active = "link.active" | "link.active.foreground",
72 list = "list.background",
74 list_active = "list.active.background",
76 list_active_border = "list.active.border",
78 list_even = "list.even.background",
80 list_head = "list.head.background",
82 muted = "muted.background",
84 muted_foreground = "muted.foreground",
86 overlay = "overlay",
88 popover = "popover.background",
90 popover_foreground = "popover.foreground",
92 primary = "primary.background",
94 primary_active = "primary.active.background",
96 primary_foreground = "primary.foreground",
98 progress_bar = "progress.bar.background" | "progress_bar.background",
100 ring = "ring",
102 secondary = "secondary.background",
104 secondary_active = "secondary.active.background",
106 secondary_foreground = "secondary.foreground",
108 selection = "selection.background",
110 skeleton = "skeleton.background",
112 slider_bar = "slider.background" | "slider.bar.background",
114 slider_thumb = "slider.thumb.background",
116 success = "success.background",
118 success_active = "success.active.background",
120 success_foreground = "success.foreground",
122 switch = "switch.background",
124 switch_thumb = "switch.thumb.background",
126 tab = "tab.background",
128 tab_active = "tab.active.background",
130 tab_active_foreground = "tab.active.foreground",
132 tab_bar = "tab_bar.background",
134 tab_bar_segmented = "tab_bar.segmented.background",
136 tab_foreground = "tab.foreground",
138 warning = "warning.background",
140 warning_active = "warning.active.background",
142 warning_foreground = "warning.foreground",
144}
145
146#[derive(Debug, Clone, PartialEq)]
149pub struct Theme {
150 pub colors: ThemeColors,
152 pub radius: f32,
154 pub radius_lg: f32,
156 pub font_size: f32,
158}
159
160impl std::ops::Deref for Theme {
161 type Target = ThemeColors;
162
163 fn deref(&self) -> &ThemeColors {
164 &self.colors
165 }
166}
167
168#[derive(Debug, Clone, PartialEq)]
170pub struct ThemeError(pub String);
171
172impl std::fmt::Display for ThemeError {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 f.write_str(&self.0)
175 }
176}
177
178impl std::error::Error for ThemeError {}
179
180static DEFAULT: LazyLock<Theme> = LazyLock::new(|| {
181 let mut theme = Theme {
182 colors: ThemeColors::default(),
183 radius: 0.0,
184 radius_lg: 0.0,
185 font_size: 0.0,
186 };
187 theme
188 .apply(include_str!("default-theme.json"))
189 .expect("the default theme parses");
190 theme
191});
192
193impl Default for Theme {
194 fn default() -> Self {
195 DEFAULT.clone()
196 }
197}
198
199fn color(value: &JsonValue) -> Option<Color> {
201 let s = value.as_str()?;
202 Color::parse(s).or_else(|| PALETTE.colors.get(s).copied())
203}
204
205type Field = fn(&mut ThemeColors) -> &mut AdaptiveColor;
206
207static PRESSED: &[(&str, &str, Field)] = &[
209 ("primary.background", "primary.active.background", |c| {
210 &mut c.primary_active
211 }),
212 ("secondary.background", "secondary.active.background", |c| {
213 &mut c.secondary_active
214 }),
215 ("danger.background", "danger.active.background", |c| {
216 &mut c.danger_active
217 }),
218 ("info.background", "info.active.background", |c| {
219 &mut c.info_active
220 }),
221 ("success.background", "success.active.background", |c| {
222 &mut c.success_active
223 }),
224 ("warning.background", "warning.active.background", |c| {
225 &mut c.warning_active
226 }),
227 ("link", "link.active", |c| &mut c.link_active),
228];
229
230fn mix(c: Color, level: u8, amount: f32) -> Color {
233 let channel = |shift: u32| {
234 let v = ((c.0 >> shift) & 0xff) as f32;
235 ((v + (f32::from(level) - v) * amount).round() as u32) << shift
236 };
237 Color(channel(24) | channel(16) | channel(8) | c.0 & 0xff)
238}
239
240static PALETTE: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
241
242impl Theme {
243 pub fn from_json(json: &str) -> Result<Self, ThemeError> {
246 let mut theme = Self::default();
247 theme.apply(json)?;
248 Ok(theme)
249 }
250
251 fn apply(&mut self, json: &str) -> Result<(), ThemeError> {
255 let value: JsonValue =
256 serde_json::from_str(json).map_err(|e| ThemeError(format!("not JSON: {e}")))?;
257 let entries = match value.get("themes") {
258 Some(JsonValue::Array(entries)) => entries.as_slice(),
259 _ => return Err(ThemeError("expected `{ \"themes\": [...] }`".into())),
260 };
261 for entry in entries {
262 let dark = match entry.get("mode").and_then(JsonValue::as_str) {
263 Some("dark") => true,
264 Some("light") | None => false,
265 Some(m) => return Err(ThemeError(format!("unknown mode `{m}`"))),
266 };
267 let number = |key: &str| entry.get(key).and_then(JsonValue::as_f64).map(|n| n as f32);
268 if let Some(r) = number("radius") {
269 self.radius = r;
270 }
271 if let Some(r) = number("radius.lg") {
272 self.radius_lg = r;
273 }
274 if let Some(s) = number("font.size") {
275 self.font_size = s;
276 }
277 let Some(JsonValue::Object(colors)) = entry.get("colors") else {
278 continue;
279 };
280 for (base, active, field) in PRESSED {
283 if colors.get(*active).is_none_or(JsonValue::is_null)
284 && let Some(c) = colors.get(*base).and_then(color)
285 {
286 let field = field(&mut self.colors);
287 if dark {
288 field.dark = mix(c, 0xff, 0.12);
289 } else {
290 field.light = mix(c, 0x00, 0.12);
291 }
292 }
293 }
294 for (key, value) in colors {
295 let Some(field) = self.colors.by_key(key) else {
298 continue;
299 };
300 if value.is_null() {
302 continue;
303 }
304 let c = color(value)
305 .ok_or_else(|| ThemeError(format!("`{key}`: not a color: {value}")))?;
306 if dark {
307 field.dark = c;
308 } else {
309 field.light = c;
310 }
311 }
312 }
313 Ok(())
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use crate::ui::rgb;
321
322 #[test]
323 fn the_default_theme_has_every_color_in_both_modes() {
324 let theme = Theme::default();
325 assert_eq!(theme.primary.light, rgb(0x171717));
326 assert_eq!(theme.primary.dark, rgb(0xfafafa));
327 assert_eq!(
328 (theme.radius, theme.radius_lg, theme.font_size),
329 (12.0, 16.0, 16.0)
330 );
331 }
332
333 #[test]
334 fn a_theme_overrides_the_default_and_derives_pressed_colors() {
335 let theme = Theme::from_json(
336 r##"{ "themes": [
337 { "mode": "light", "radius": 8, "colors": {
338 "primary.background": "#7c3aed", "border": "red-500", "sidebar.background": "#000" } },
339 { "mode": "dark", "colors": { "primary.background": "#a78bfa", "primary.active.background": "#ffffff" } }
340 ] }"##,
341 )
342 .unwrap();
343 assert_eq!(theme.primary.light, rgb(0x7c3aed));
344 assert_eq!(theme.primary_active.light, mix(rgb(0x7c3aed), 0, 0.12));
346 assert_eq!(theme.primary_active.dark, rgb(0xffffff));
347 assert_eq!(theme.border.light, PALETTE.colors["red-500"]);
349 assert_eq!(theme.radius, 8.0);
350 assert_eq!(theme.secondary, Theme::default().secondary);
351 assert!(Theme::from_json(r#"{ "themes": [{ "colors": { "ring": 3 } }] }"#).is_err());
352 }
353
354 #[test]
355 fn colors_a_gpui_kit_theme_leaves_unset_keep_their_value() {
356 let theme = Theme::from_json(
358 r##"{ "themes": [{ "mode": "dark", "radius": null, "colors": {
359 "primary.background": null, "primary.active.background": null,
360 "danger.background": "#ff0000", "danger.active.background": null,
361 "ring": "#ff0000", "sidebar.background": null } }] }"##,
362 )
363 .unwrap();
364 let default = Theme::default();
365 assert_eq!(theme.primary, default.primary);
366 assert_eq!(theme.primary_active, default.primary_active);
367 assert_eq!(theme.radius, default.radius);
368 assert_eq!(theme.ring.dark, rgb(0xff0000));
369 assert_eq!(theme.ring.light, default.ring.light);
370 assert_eq!(theme.danger_active.dark, mix(rgb(0xff0000), 0xff, 0.12));
372 }
373}