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