registry.rs

  1use std::sync::Arc;
  2use std::{fmt::Debug, path::Path};
  3
  4use anyhow::{anyhow, Context, Result};
  5use collections::HashMap;
  6use derive_more::{Deref, DerefMut};
  7use fs::Fs;
  8use futures::StreamExt;
  9use gpui::{AppContext, AssetSource, Global, HighlightStyle, SharedString};
 10use parking_lot::RwLock;
 11use refineable::Refineable;
 12use util::ResultExt;
 13
 14use crate::{
 15    try_parse_color, AccentColors, Appearance, AppearanceContent, PlayerColors, StatusColors,
 16    SyntaxTheme, SystemColors, Theme, ThemeColors, ThemeContent, ThemeFamily, ThemeFamilyContent,
 17    ThemeStyles,
 18};
 19
 20/// The metadata for a theme.
 21#[derive(Debug, Clone)]
 22pub struct ThemeMeta {
 23    /// The name of the theme.
 24    pub name: SharedString,
 25    /// The appearance of the theme.
 26    pub appearance: Appearance,
 27}
 28
 29/// The global [`ThemeRegistry`].
 30///
 31/// This newtype exists for obtaining a unique [`TypeId`](std::any::TypeId) when
 32/// inserting the [`ThemeRegistry`] into the context as a global.
 33///
 34/// This should not be exposed outside of this module.
 35#[derive(Default, Deref, DerefMut)]
 36struct GlobalThemeRegistry(Arc<ThemeRegistry>);
 37
 38impl Global for GlobalThemeRegistry {}
 39
 40struct ThemeRegistryState {
 41    themes: HashMap<SharedString, Arc<Theme>>,
 42}
 43
 44/// The registry for themes.
 45pub struct ThemeRegistry {
 46    state: RwLock<ThemeRegistryState>,
 47    assets: Box<dyn AssetSource>,
 48}
 49
 50impl ThemeRegistry {
 51    /// Returns the global [`ThemeRegistry`].
 52    pub fn global(cx: &AppContext) -> Arc<Self> {
 53        cx.global::<GlobalThemeRegistry>().0.clone()
 54    }
 55
 56    /// Returns the global [`ThemeRegistry`].
 57    ///
 58    /// Inserts a default [`ThemeRegistry`] if one does not yet exist.
 59    pub fn default_global(cx: &mut AppContext) -> Arc<Self> {
 60        cx.default_global::<GlobalThemeRegistry>().0.clone()
 61    }
 62
 63    /// Sets the global [`ThemeRegistry`].
 64    pub(crate) fn set_global(assets: Box<dyn AssetSource>, cx: &mut AppContext) {
 65        cx.set_global(GlobalThemeRegistry(Arc::new(ThemeRegistry::new(assets))));
 66    }
 67
 68    /// Creates a new [`ThemeRegistry`] with the given [`AssetSource`].
 69    pub fn new(assets: Box<dyn AssetSource>) -> Self {
 70        let registry = Self {
 71            state: RwLock::new(ThemeRegistryState {
 72                themes: HashMap::default(),
 73            }),
 74            assets,
 75        };
 76
 77        // We're loading our new versions of the One themes by default, as
 78        // we need them to be loaded for tests.
 79        //
 80        // These themes will get overwritten when `load_user_themes` is called
 81        // when Zed starts, so the One variants used will be the ones ported from Zed1.
 82        registry.insert_theme_families([crate::one_themes::one_family()]);
 83
 84        registry
 85    }
 86
 87    fn insert_theme_families(&self, families: impl IntoIterator<Item = ThemeFamily>) {
 88        for family in families.into_iter() {
 89            self.insert_themes(family.themes);
 90        }
 91    }
 92
 93    fn insert_themes(&self, themes: impl IntoIterator<Item = Theme>) {
 94        let mut state = self.state.write();
 95        for theme in themes.into_iter() {
 96            state.themes.insert(theme.name.clone(), Arc::new(theme));
 97        }
 98    }
 99
100    #[allow(unused)]
101    fn insert_user_theme_families(&self, families: impl IntoIterator<Item = ThemeFamilyContent>) {
102        for family in families.into_iter() {
103            self.insert_user_themes(family.themes);
104        }
105    }
106
107    /// Inserts user themes into the registry.
108    pub fn insert_user_themes(&self, themes: impl IntoIterator<Item = ThemeContent>) {
109        self.insert_themes(themes.into_iter().map(|user_theme| {
110            let mut theme_colors = match user_theme.appearance {
111                AppearanceContent::Light => ThemeColors::light(),
112                AppearanceContent::Dark => ThemeColors::dark(),
113            };
114            theme_colors.refine(&user_theme.style.theme_colors_refinement());
115
116            let mut status_colors = match user_theme.appearance {
117                AppearanceContent::Light => StatusColors::light(),
118                AppearanceContent::Dark => StatusColors::dark(),
119            };
120            status_colors.refine(&user_theme.style.status_colors_refinement());
121
122            let mut player_colors = match user_theme.appearance {
123                AppearanceContent::Light => PlayerColors::light(),
124                AppearanceContent::Dark => PlayerColors::dark(),
125            };
126            player_colors.merge(&user_theme.style.players);
127
128            let mut accent_colors = match user_theme.appearance {
129                AppearanceContent::Light => AccentColors::light(),
130                AppearanceContent::Dark => AccentColors::dark(),
131            };
132            accent_colors.merge(&user_theme.style.accents);
133
134            let syntax_highlights = user_theme
135                .style
136                .syntax
137                .iter()
138                .map(|(syntax_token, highlight)| {
139                    (
140                        syntax_token.clone(),
141                        HighlightStyle {
142                            color: highlight
143                                .color
144                                .as_ref()
145                                .and_then(|color| try_parse_color(color).ok()),
146                            background_color: highlight
147                                .background_color
148                                .as_ref()
149                                .and_then(|color| try_parse_color(color).ok()),
150                            font_style: highlight.font_style.map(Into::into),
151                            font_weight: highlight.font_weight.map(Into::into),
152                            ..Default::default()
153                        },
154                    )
155                })
156                .collect::<Vec<_>>();
157            let syntax_theme =
158                SyntaxTheme::merge(Arc::new(SyntaxTheme::default()), syntax_highlights);
159
160            let window_background_appearance = user_theme
161                .style
162                .window_background_appearance
163                .map(Into::into)
164                .unwrap_or_default();
165
166            Theme {
167                id: uuid::Uuid::new_v4().to_string(),
168                name: user_theme.name.into(),
169                appearance: match user_theme.appearance {
170                    AppearanceContent::Light => Appearance::Light,
171                    AppearanceContent::Dark => Appearance::Dark,
172                },
173                styles: ThemeStyles {
174                    system: SystemColors::default(),
175                    window_background_appearance,
176                    accents: accent_colors,
177                    colors: theme_colors,
178                    status: status_colors,
179                    player: player_colors,
180                    syntax: syntax_theme,
181                },
182            }
183        }));
184    }
185
186    /// Removes the themes with the given names from the registry.
187    pub fn remove_user_themes(&self, themes_to_remove: &[SharedString]) {
188        self.state
189            .write()
190            .themes
191            .retain(|name, _| !themes_to_remove.contains(name))
192    }
193
194    /// Removes all themes from the registry.
195    pub fn clear(&mut self) {
196        self.state.write().themes.clear();
197    }
198
199    /// Returns the names of all themes in the registry.
200    pub fn list_names(&self, _staff: bool) -> Vec<SharedString> {
201        let mut names = self.state.read().themes.keys().cloned().collect::<Vec<_>>();
202        names.sort();
203        names
204    }
205
206    /// Returns the metadata of all themes in the registry.
207    pub fn list(&self, _staff: bool) -> Vec<ThemeMeta> {
208        self.state
209            .read()
210            .themes
211            .values()
212            .map(|theme| ThemeMeta {
213                name: theme.name.clone(),
214                appearance: theme.appearance(),
215            })
216            .collect()
217    }
218
219    /// Returns the theme with the given name.
220    pub fn get(&self, name: &str) -> Result<Arc<Theme>> {
221        self.state
222            .read()
223            .themes
224            .get(name)
225            .ok_or_else(|| anyhow!("theme not found: {}", name))
226            .cloned()
227    }
228
229    /// Loads the themes bundled with the Zed binary and adds them to the registry.
230    pub fn load_bundled_themes(&self) {
231        let theme_paths = self
232            .assets
233            .list("themes/")
234            .expect("failed to list theme assets")
235            .into_iter()
236            .filter(|path| path.ends_with(".json"));
237
238        for path in theme_paths {
239            let Some(theme) = self.assets.load(&path).log_err().flatten() else {
240                continue;
241            };
242
243            let Some(theme_family) = serde_json::from_slice(&theme)
244                .with_context(|| format!("failed to parse theme at path \"{path}\""))
245                .log_err()
246            else {
247                continue;
248            };
249
250            self.insert_user_theme_families([theme_family]);
251        }
252    }
253
254    /// Loads the user themes from the specified directory and adds them to the registry.
255    pub async fn load_user_themes(&self, themes_path: &Path, fs: Arc<dyn Fs>) -> Result<()> {
256        let mut theme_paths = fs
257            .read_dir(themes_path)
258            .await
259            .with_context(|| format!("reading themes from {themes_path:?}"))?;
260
261        while let Some(theme_path) = theme_paths.next().await {
262            let Some(theme_path) = theme_path.log_err() else {
263                continue;
264            };
265
266            self.load_user_theme(&theme_path, fs.clone())
267                .await
268                .log_err();
269        }
270
271        Ok(())
272    }
273
274    /// Asynchronously reads the user theme from the specified path.
275    pub async fn read_user_theme(theme_path: &Path, fs: Arc<dyn Fs>) -> Result<ThemeFamilyContent> {
276        let reader = fs.open_sync(theme_path).await?;
277        let theme_family: ThemeFamilyContent = serde_json_lenient::from_reader(reader)?;
278
279        for theme in &theme_family.themes {
280            if theme
281                .style
282                .colors
283                .deprecated_scrollbar_thumb_background
284                .is_some()
285            {
286                log::warn!(
287                    r#"Theme "{theme_name}" is using a deprecated style property: scrollbar_thumb.background. Use `scrollbar.thumb.background` instead."#,
288                    theme_name = theme.name
289                )
290            }
291        }
292
293        Ok(theme_family)
294    }
295
296    /// Loads the user theme from the specified path and adds it to the registry.
297    pub async fn load_user_theme(&self, theme_path: &Path, fs: Arc<dyn Fs>) -> Result<()> {
298        let theme = Self::read_user_theme(theme_path, fs).await?;
299
300        self.insert_user_theme_families([theme]);
301
302        Ok(())
303    }
304}
305
306impl Default for ThemeRegistry {
307    fn default() -> Self {
308        Self::new(Box::new(()))
309    }
310}