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