theme_registry.rs

 1use crate::{Theme, ThemeMeta};
 2use anyhow::{Context, Result};
 3use gpui::{fonts, AssetSource, FontCache};
 4use parking_lot::Mutex;
 5use serde::Deserialize;
 6use serde_json::Value;
 7use std::{
 8    collections::HashMap,
 9    sync::{
10        atomic::{AtomicUsize, Ordering::SeqCst},
11        Arc,
12    },
13};
14
15pub struct ThemeRegistry {
16    assets: Box<dyn AssetSource>,
17    themes: Mutex<HashMap<String, Arc<Theme>>>,
18    theme_data: Mutex<HashMap<String, Arc<Value>>>,
19    font_cache: Arc<FontCache>,
20    next_theme_id: AtomicUsize,
21}
22
23#[cfg(any(test, feature = "test-support"))]
24pub const EMPTY_THEME_NAME: &'static str = "empty-theme";
25
26impl ThemeRegistry {
27    pub fn new(source: impl AssetSource, font_cache: Arc<FontCache>) -> Arc<Self> {
28        let this = Arc::new(Self {
29            assets: Box::new(source),
30            themes: Default::default(),
31            theme_data: Default::default(),
32            next_theme_id: Default::default(),
33            font_cache,
34        });
35
36        #[cfg(any(test, feature = "test-support"))]
37        this.themes.lock().insert(
38            EMPTY_THEME_NAME.to_string(),
39            gpui::fonts::with_font_cache(this.font_cache.clone(), || Arc::new(Theme::default())),
40        );
41
42        this
43    }
44
45    pub fn list(&self, staff: bool) -> impl Iterator<Item = ThemeMeta> + '_ {
46        let mut dirs = self.assets.list("themes/");
47
48        if !staff {
49            dirs = dirs
50                .into_iter()
51                .filter(|path| !path.starts_with("themes/staff"))
52                .collect()
53        }
54
55        dirs.into_iter().filter_map(|path| {
56            let filename = path.strip_prefix("themes/")?;
57            let theme_name = filename.strip_suffix(".json")?;
58            self.get(theme_name).ok().map(|theme| theme.meta.clone())
59        })
60    }
61
62    pub fn clear(&self) {
63        self.theme_data.lock().clear();
64        self.themes.lock().clear();
65    }
66
67    pub fn get(&self, name: &str) -> Result<Arc<Theme>> {
68        if let Some(theme) = self.themes.lock().get(name) {
69            return Ok(theme.clone());
70        }
71
72        let asset_path = format!("themes/{}.json", name);
73        let theme_json = self
74            .assets
75            .load(&asset_path)
76            .with_context(|| format!("failed to load theme file {}", asset_path))?;
77
78        // Allocate into the heap directly, the Theme struct is too large to fit in the stack.
79        let mut theme = fonts::with_font_cache(self.font_cache.clone(), || {
80            let mut theme = Box::new(Theme::default());
81            let mut deserializer = serde_json::Deserializer::from_slice(&theme_json);
82            let result = Theme::deserialize_in_place(&mut deserializer, &mut theme);
83            result.map(|_| theme)
84        })?;
85
86        // Reset name to be the file path, so that we can use it to access the stored themes
87        theme.meta.name = name.into();
88        theme.meta.id = self.next_theme_id.fetch_add(1, SeqCst);
89        let theme: Arc<Theme> = theme.into();
90        self.themes.lock().insert(name.to_string(), theme.clone());
91        Ok(theme)
92    }
93}