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
23impl ThemeRegistry {
24 pub fn new(source: impl AssetSource, font_cache: Arc<FontCache>) -> Arc<Self> {
25 Arc::new(Self {
26 assets: Box::new(source),
27 themes: Default::default(),
28 theme_data: Default::default(),
29 next_theme_id: Default::default(),
30 font_cache,
31 })
32 }
33
34 pub fn list(&self, staff: bool) -> impl Iterator<Item = ThemeMeta> + '_ {
35 let mut dirs = self.assets.list("themes/");
36
37 if !staff {
38 dirs = dirs
39 .into_iter()
40 .filter(|path| !path.starts_with("themes/staff"))
41 .collect()
42 }
43
44 dirs.into_iter().filter_map(|path| {
45 let filename = path.strip_prefix("themes/")?;
46 let theme_name = filename.strip_suffix(".json")?;
47 self.get(theme_name).ok().map(|theme| theme.meta.clone())
48 })
49 }
50
51 pub fn clear(&self) {
52 self.theme_data.lock().clear();
53 self.themes.lock().clear();
54 }
55
56 pub fn get(&self, name: &str) -> Result<Arc<Theme>> {
57 if let Some(theme) = self.themes.lock().get(name) {
58 return Ok(theme.clone());
59 }
60
61 let asset_path = format!("themes/{}.json", name);
62 let theme_json = self
63 .assets
64 .load(&asset_path)
65 .with_context(|| format!("failed to load theme file {}", asset_path))?;
66
67 // Allocate into the heap directly, the Theme struct is too large to fit in the stack.
68 let mut theme = fonts::with_font_cache(self.font_cache.clone(), || {
69 let mut theme = Box::new(Theme::default());
70 let mut deserializer = serde_json::Deserializer::from_slice(&theme_json);
71 let result = Theme::deserialize_in_place(&mut deserializer, &mut theme);
72 result.map(|_| theme)
73 })?;
74
75 // Reset name to be the file path, so that we can use it to access the stored themes
76 theme.meta.name = name.into();
77 theme.meta.id = self.next_theme_id.fetch_add(1, SeqCst);
78 let theme: Arc<Theme> = theme.into();
79 self.themes.lock().insert(name.to_string(), theme.clone());
80 Ok(theme)
81 }
82}