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