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