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, PlayerColor, 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            if !user_theme.style.players.is_empty() {
121                player_colors = PlayerColors(
122                    user_theme
123                        .style
124                        .players
125                        .into_iter()
126                        .map(|player| PlayerColor {
127                            cursor: player
128                                .cursor
129                                .as_ref()
130                                .and_then(|color| try_parse_color(&color).ok())
131                                .unwrap_or_default(),
132                            background: player
133                                .background
134                                .as_ref()
135                                .and_then(|color| try_parse_color(&color).ok())
136                                .unwrap_or_default(),
137                            selection: player
138                                .selection
139                                .as_ref()
140                                .and_then(|color| try_parse_color(&color).ok())
141                                .unwrap_or_default(),
142                        })
143                        .collect(),
144                );
145            }
146
147            let mut syntax_colors = match user_theme.appearance {
148                AppearanceContent::Light => SyntaxTheme::light(),
149                AppearanceContent::Dark => SyntaxTheme::dark(),
150            };
151            if !user_theme.style.syntax.is_empty() {
152                syntax_colors.highlights = user_theme
153                    .style
154                    .syntax
155                    .iter()
156                    .map(|(syntax_token, highlight)| {
157                        (
158                            syntax_token.clone(),
159                            HighlightStyle {
160                                color: highlight
161                                    .color
162                                    .as_ref()
163                                    .and_then(|color| try_parse_color(&color).ok()),
164                                font_style: highlight.font_style.map(Into::into),
165                                font_weight: highlight.font_weight.map(Into::into),
166                                ..Default::default()
167                            },
168                        )
169                    })
170                    .collect::<Vec<_>>();
171            }
172
173            Theme {
174                id: uuid::Uuid::new_v4().to_string(),
175                name: user_theme.name.into(),
176                appearance: match user_theme.appearance {
177                    AppearanceContent::Light => Appearance::Light,
178                    AppearanceContent::Dark => Appearance::Dark,
179                },
180                styles: ThemeStyles {
181                    system: SystemColors::default(),
182                    colors: theme_colors,
183                    status: status_colors,
184                    player: player_colors,
185                    syntax: Arc::new(syntax_colors),
186                    accents: Vec::new(),
187                },
188            }
189        }));
190    }
191
192    /// Removes the themes with the given names from the registry.
193    pub fn remove_user_themes(&self, themes_to_remove: &[SharedString]) {
194        self.state
195            .write()
196            .themes
197            .retain(|name, _| !themes_to_remove.contains(name))
198    }
199
200    pub fn clear(&mut self) {
201        self.state.write().themes.clear();
202    }
203
204    pub fn list_names(&self, _staff: bool) -> Vec<SharedString> {
205        let mut names = self.state.read().themes.keys().cloned().collect::<Vec<_>>();
206        names.sort();
207        names
208    }
209
210    pub fn list(&self, _staff: bool) -> Vec<ThemeMeta> {
211        self.state
212            .read()
213            .themes
214            .values()
215            .map(|theme| ThemeMeta {
216                name: theme.name.clone(),
217                appearance: theme.appearance(),
218            })
219            .collect()
220    }
221
222    pub fn get(&self, name: &str) -> Result<Arc<Theme>> {
223        self.state
224            .read()
225            .themes
226            .get(name)
227            .ok_or_else(|| anyhow!("theme not found: {}", name))
228            .cloned()
229    }
230
231    /// Loads the themes bundled with the Zed binary and adds them to the registry.
232    pub fn load_bundled_themes(&self) {
233        let theme_paths = self
234            .assets
235            .list("themes/")
236            .expect("failed to list theme assets")
237            .into_iter()
238            .filter(|path| path.ends_with(".json"));
239
240        for path in theme_paths {
241            let Some(theme) = self.assets.load(&path).log_err() else {
242                continue;
243            };
244
245            let Some(theme_family) = serde_json::from_slice(&theme)
246                .with_context(|| format!("failed to parse theme at path \"{path}\""))
247                .log_err()
248            else {
249                continue;
250            };
251
252            self.insert_user_theme_families([theme_family]);
253        }
254    }
255
256    /// Loads the user themes from the specified directory and adds them to the registry.
257    pub async fn load_user_themes(&self, themes_path: &Path, fs: Arc<dyn Fs>) -> Result<()> {
258        let mut theme_paths = fs
259            .read_dir(themes_path)
260            .await
261            .with_context(|| format!("reading themes from {themes_path:?}"))?;
262
263        while let Some(theme_path) = theme_paths.next().await {
264            let Some(theme_path) = theme_path.log_err() else {
265                continue;
266            };
267
268            self.load_user_theme(&theme_path, fs.clone())
269                .await
270                .log_err();
271        }
272
273        Ok(())
274    }
275
276    pub async fn read_user_theme(theme_path: &Path, fs: Arc<dyn Fs>) -> Result<ThemeFamilyContent> {
277        let reader = fs.open_sync(&theme_path).await?;
278        let theme = serde_json_lenient::from_reader(reader)?;
279
280        Ok(theme)
281    }
282
283    /// Loads the user theme from the specified path and adds it to the registry.
284    pub async fn load_user_theme(&self, theme_path: &Path, fs: Arc<dyn Fs>) -> Result<()> {
285        let theme = Self::read_user_theme(theme_path, fs).await?;
286
287        self.insert_user_theme_families([theme]);
288
289        Ok(())
290    }
291}
292
293impl Default for ThemeRegistry {
294    fn default() -> Self {
295        Self::new(Box::new(()))
296    }
297}