1use client::telemetry::Telemetry;
2use feature_flags::FeatureFlagAppExt;
3use fs::Fs;
4use fuzzy::{match_strings, StringMatch, StringMatchCandidate};
5use gpui::{
6 actions, AppContext, DismissEvent, EventEmitter, FocusableView, Render, View, ViewContext,
7 VisualContext, WeakView,
8};
9use picker::{Picker, PickerDelegate};
10use settings::{update_settings_file, SettingsStore};
11use std::sync::Arc;
12use theme::{Theme, ThemeMeta, ThemeRegistry, ThemeSettings};
13use ui::{prelude::*, v_stack, ListItem, ListItemSpacing};
14use util::ResultExt;
15use workspace::{ui::HighlightedLabel, ModalView, Workspace};
16
17actions!(theme_selector, [Toggle, Reload]);
18
19pub fn init(cx: &mut AppContext) {
20 cx.observe_new_views(
21 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
22 workspace.register_action(toggle);
23 },
24 )
25 .detach();
26}
27
28pub fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
29 let fs = workspace.app_state().fs.clone();
30 let telemetry = workspace.client().telemetry().clone();
31 workspace.toggle_modal(cx, |cx| {
32 ThemeSelector::new(
33 ThemeSelectorDelegate::new(cx.view().downgrade(), fs, telemetry, cx),
34 cx,
35 )
36 });
37}
38
39#[cfg(debug_assertions)]
40pub fn reload(cx: &mut AppContext) {
41 let current_theme_name = cx.theme().name.clone();
42 let current_theme = cx.update_global(|registry: &mut ThemeRegistry, _cx| {
43 registry.clear();
44 registry.get(¤t_theme_name)
45 });
46 match current_theme {
47 Ok(theme) => {
48 ThemeSelectorDelegate::set_theme(theme, cx);
49 log::info!("reloaded theme {}", current_theme_name);
50 }
51 Err(error) => {
52 log::error!("failed to load theme {}: {:?}", current_theme_name, error)
53 }
54 }
55}
56
57impl ModalView for ThemeSelector {}
58
59pub struct ThemeSelector {
60 picker: View<Picker<ThemeSelectorDelegate>>,
61}
62
63impl EventEmitter<DismissEvent> for ThemeSelector {}
64
65impl FocusableView for ThemeSelector {
66 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
67 self.picker.focus_handle(cx)
68 }
69}
70
71impl Render for ThemeSelector {
72 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
73 v_stack().w(rems(34.)).child(self.picker.clone())
74 }
75}
76
77impl ThemeSelector {
78 pub fn new(delegate: ThemeSelectorDelegate, cx: &mut ViewContext<Self>) -> Self {
79 let picker = cx.new_view(|cx| Picker::new(delegate, cx));
80 Self { picker }
81 }
82}
83
84pub struct ThemeSelectorDelegate {
85 fs: Arc<dyn Fs>,
86 themes: Vec<ThemeMeta>,
87 matches: Vec<StringMatch>,
88 original_theme: Arc<Theme>,
89 selection_completed: bool,
90 selected_index: usize,
91 telemetry: Arc<Telemetry>,
92 view: WeakView<ThemeSelector>,
93}
94
95impl ThemeSelectorDelegate {
96 fn new(
97 weak_view: WeakView<ThemeSelector>,
98 fs: Arc<dyn Fs>,
99 telemetry: Arc<Telemetry>,
100 cx: &mut ViewContext<ThemeSelector>,
101 ) -> Self {
102 let original_theme = cx.theme().clone();
103
104 let staff_mode = cx.is_staff();
105 let registry = cx.global::<ThemeRegistry>();
106 let mut themes = registry.list(staff_mode).collect::<Vec<_>>();
107 themes.sort_unstable_by(|a, b| {
108 a.appearance
109 .is_light()
110 .cmp(&b.appearance.is_light())
111 .then(a.name.cmp(&b.name))
112 });
113 let matches = themes
114 .iter()
115 .map(|meta| StringMatch {
116 candidate_id: 0,
117 score: 0.0,
118 positions: Default::default(),
119 string: meta.name.to_string(),
120 })
121 .collect();
122 let mut this = Self {
123 fs,
124 themes,
125 matches,
126 original_theme: original_theme.clone(),
127 selected_index: 0,
128 selection_completed: false,
129 telemetry,
130 view: weak_view,
131 };
132 this.select_if_matching(&original_theme.name);
133 this
134 }
135
136 fn show_selected_theme(&mut self, cx: &mut ViewContext<Picker<ThemeSelectorDelegate>>) {
137 if let Some(mat) = self.matches.get(self.selected_index) {
138 let registry = cx.global::<ThemeRegistry>();
139 match registry.get(&mat.string) {
140 Ok(theme) => {
141 Self::set_theme(theme, cx);
142 }
143 Err(error) => {
144 log::error!("error loading theme {}: {}", mat.string, error)
145 }
146 }
147 }
148 }
149
150 fn select_if_matching(&mut self, theme_name: &str) {
151 self.selected_index = self
152 .matches
153 .iter()
154 .position(|mat| mat.string == theme_name)
155 .unwrap_or(self.selected_index);
156 }
157
158 fn set_theme(theme: Arc<Theme>, cx: &mut AppContext) {
159 cx.update_global(|store: &mut SettingsStore, cx| {
160 let mut theme_settings = store.get::<ThemeSettings>(None).clone();
161 theme_settings.active_theme = theme;
162 store.override_global(theme_settings);
163 cx.refresh();
164 });
165 }
166}
167
168impl PickerDelegate for ThemeSelectorDelegate {
169 type ListItem = ui::ListItem;
170
171 fn placeholder_text(&self) -> Arc<str> {
172 "Select Theme...".into()
173 }
174
175 fn match_count(&self) -> usize {
176 self.matches.len()
177 }
178
179 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<ThemeSelectorDelegate>>) {
180 self.selection_completed = true;
181
182 let theme_name = cx.theme().name.clone();
183
184 self.telemetry
185 .report_setting_event("theme", theme_name.to_string());
186
187 update_settings_file::<ThemeSettings>(self.fs.clone(), cx, move |settings| {
188 settings.theme = Some(theme_name.to_string());
189 });
190
191 self.view
192 .update(cx, |_, cx| {
193 cx.emit(DismissEvent);
194 })
195 .ok();
196 }
197
198 fn dismissed(&mut self, cx: &mut ViewContext<Picker<ThemeSelectorDelegate>>) {
199 if !self.selection_completed {
200 Self::set_theme(self.original_theme.clone(), cx);
201 self.selection_completed = true;
202 }
203
204 self.view
205 .update(cx, |_, cx| cx.emit(DismissEvent))
206 .log_err();
207 }
208
209 fn selected_index(&self) -> usize {
210 self.selected_index
211 }
212
213 fn set_selected_index(
214 &mut self,
215 ix: usize,
216 cx: &mut ViewContext<Picker<ThemeSelectorDelegate>>,
217 ) {
218 self.selected_index = ix;
219 self.show_selected_theme(cx);
220 }
221
222 fn update_matches(
223 &mut self,
224 query: String,
225 cx: &mut ViewContext<Picker<ThemeSelectorDelegate>>,
226 ) -> gpui::Task<()> {
227 let background = cx.background_executor().clone();
228 let candidates = self
229 .themes
230 .iter()
231 .enumerate()
232 .map(|(id, meta)| StringMatchCandidate {
233 id,
234 char_bag: meta.name.as_ref().into(),
235 string: meta.name.to_string(),
236 })
237 .collect::<Vec<_>>();
238
239 cx.spawn(|this, mut cx| async move {
240 let matches = if query.is_empty() {
241 candidates
242 .into_iter()
243 .enumerate()
244 .map(|(index, candidate)| StringMatch {
245 candidate_id: index,
246 string: candidate.string,
247 positions: Vec::new(),
248 score: 0.0,
249 })
250 .collect()
251 } else {
252 match_strings(
253 &candidates,
254 &query,
255 false,
256 100,
257 &Default::default(),
258 background,
259 )
260 .await
261 };
262
263 this.update(&mut cx, |this, cx| {
264 this.delegate.matches = matches;
265 this.delegate.selected_index = this
266 .delegate
267 .selected_index
268 .min(this.delegate.matches.len().saturating_sub(1));
269 this.delegate.show_selected_theme(cx);
270 })
271 .log_err();
272 })
273 }
274
275 fn render_match(
276 &self,
277 ix: usize,
278 selected: bool,
279 _cx: &mut ViewContext<Picker<Self>>,
280 ) -> Option<Self::ListItem> {
281 let theme_match = &self.matches[ix];
282
283 Some(
284 ListItem::new(ix)
285 .inset(true)
286 .spacing(ListItemSpacing::Sparse)
287 .selected(selected)
288 .child(HighlightedLabel::new(
289 theme_match.string.clone(),
290 theme_match.positions.clone(),
291 )),
292 )
293 }
294}