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