registry.rs

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