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