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 self.state.read().themes.keys().cloned().collect()
198 }
199
200 pub fn list(&self, _staff: bool) -> Vec<ThemeMeta> {
201 self.state
202 .read()
203 .themes
204 .values()
205 .map(|theme| ThemeMeta {
206 name: theme.name.clone(),
207 appearance: theme.appearance(),
208 })
209 .collect()
210 }
211
212 pub fn get(&self, name: &str) -> Result<Arc<Theme>> {
213 self.state
214 .read()
215 .themes
216 .get(name)
217 .ok_or_else(|| anyhow!("theme not found: {}", name))
218 .cloned()
219 }
220
221 /// Loads the themes bundled with the Zed binary and adds them to the registry.
222 pub fn load_bundled_themes(&self) {
223 let theme_paths = self
224 .assets
225 .list("themes/")
226 .expect("failed to list theme assets")
227 .into_iter()
228 .filter(|path| path.ends_with(".json"));
229
230 for path in theme_paths {
231 let Some(theme) = self.assets.load(&path).log_err() else {
232 continue;
233 };
234
235 let Some(theme_family) = serde_json::from_slice(&theme)
236 .with_context(|| format!("failed to parse theme at path \"{path}\""))
237 .log_err()
238 else {
239 continue;
240 };
241
242 self.insert_user_theme_families([theme_family]);
243 }
244 }
245
246 /// Loads the user themes from the specified directory and adds them to the registry.
247 pub async fn load_user_themes(&self, themes_path: &Path, fs: Arc<dyn Fs>) -> Result<()> {
248 let mut theme_paths = fs
249 .read_dir(themes_path)
250 .await
251 .with_context(|| format!("reading themes from {themes_path:?}"))?;
252
253 while let Some(theme_path) = theme_paths.next().await {
254 let Some(theme_path) = theme_path.log_err() else {
255 continue;
256 };
257
258 self.load_user_theme(&theme_path, fs.clone())
259 .await
260 .log_err();
261 }
262
263 Ok(())
264 }
265
266 /// Loads the user theme from the specified path and adds it to the registry.
267 pub async fn load_user_theme(&self, theme_path: &Path, fs: Arc<dyn Fs>) -> Result<()> {
268 let reader = fs.open_sync(&theme_path).await?;
269 let theme = serde_json_lenient::from_reader(reader)?;
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}