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