1use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
2use gpui::{
3 App, Context, DismissEvent, Entity, EventEmitter, Focusable, Render, Task, WeakEntity, Window,
4};
5use picker::{Picker, PickerDelegate};
6use settings::{ActiveSettingsProfileName, SettingsStore};
7use ui::{HighlightedLabel, ListItem, ListItemSpacing, prelude::*};
8use workspace::{ModalView, Workspace};
9
10pub fn init(cx: &mut App) {
11 cx.on_action(|_: &zed_actions::settings_profile_selector::Toggle, cx| {
12 workspace::with_active_or_new_workspace(cx, |workspace, window, cx| {
13 toggle_settings_profile_selector(workspace, window, cx);
14 });
15 });
16}
17
18fn toggle_settings_profile_selector(
19 workspace: &mut Workspace,
20 window: &mut Window,
21 cx: &mut Context<Workspace>,
22) {
23 workspace.toggle_modal(window, cx, |window, cx| {
24 let delegate = SettingsProfileSelectorDelegate::new(cx.entity().downgrade(), window, cx);
25 SettingsProfileSelector::new(delegate, window, cx)
26 });
27}
28
29pub struct SettingsProfileSelector {
30 picker: Entity<Picker<SettingsProfileSelectorDelegate>>,
31}
32
33impl ModalView for SettingsProfileSelector {}
34
35impl EventEmitter<DismissEvent> for SettingsProfileSelector {}
36
37impl Focusable for SettingsProfileSelector {
38 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
39 self.picker.focus_handle(cx)
40 }
41}
42
43impl Render for SettingsProfileSelector {
44 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
45 v_flex().w(rems(22.)).child(self.picker.clone())
46 }
47}
48
49impl SettingsProfileSelector {
50 pub fn new(
51 delegate: SettingsProfileSelectorDelegate,
52 window: &mut Window,
53 cx: &mut Context<Self>,
54 ) -> Self {
55 let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
56 Self { picker }
57 }
58}
59
60pub struct SettingsProfileSelectorDelegate {
61 matches: Vec<StringMatch>,
62 profile_names: Vec<Option<String>>,
63 original_profile_name: Option<String>,
64 selected_profile_name: Option<String>,
65 selected_index: usize,
66 selection_completed: bool,
67 selector: WeakEntity<SettingsProfileSelector>,
68}
69
70impl SettingsProfileSelectorDelegate {
71 fn new(
72 selector: WeakEntity<SettingsProfileSelector>,
73 _: &mut Window,
74 cx: &mut Context<SettingsProfileSelector>,
75 ) -> Self {
76 let settings_store = cx.global::<SettingsStore>();
77 let mut profile_names: Vec<Option<String>> = settings_store
78 .configured_settings_profiles()
79 .map(|s| Some(s.to_string()))
80 .collect();
81 profile_names.insert(0, None);
82
83 let matches = profile_names
84 .iter()
85 .enumerate()
86 .map(|(ix, profile_name)| StringMatch {
87 candidate_id: ix,
88 score: 0.0,
89 positions: Default::default(),
90 string: display_name(profile_name),
91 })
92 .collect();
93
94 let profile_name = cx
95 .try_global::<ActiveSettingsProfileName>()
96 .map(|p| p.0.clone());
97
98 let mut this = Self {
99 matches,
100 profile_names,
101 original_profile_name: profile_name.clone(),
102 selected_profile_name: None,
103 selected_index: 0,
104 selection_completed: false,
105 selector,
106 };
107
108 if let Some(profile_name) = profile_name {
109 this.select_if_matching(&profile_name);
110 }
111
112 this
113 }
114
115 fn select_if_matching(&mut self, profile_name: &str) {
116 self.selected_index = self
117 .matches
118 .iter()
119 .position(|mat| mat.string == profile_name)
120 .unwrap_or(self.selected_index);
121 }
122
123 fn set_selected_profile(
124 &self,
125 cx: &mut Context<Picker<SettingsProfileSelectorDelegate>>,
126 ) -> Option<String> {
127 let mat = self.matches.get(self.selected_index)?;
128 let profile_name = self.profile_names.get(mat.candidate_id)?;
129 Self::update_active_profile_name_global(profile_name.clone(), cx)
130 }
131
132 fn update_active_profile_name_global(
133 profile_name: Option<String>,
134 cx: &mut Context<Picker<SettingsProfileSelectorDelegate>>,
135 ) -> Option<String> {
136 if let Some(profile_name) = profile_name {
137 cx.set_global(ActiveSettingsProfileName(profile_name.clone()));
138 return Some(profile_name);
139 }
140
141 if cx.has_global::<ActiveSettingsProfileName>() {
142 cx.remove_global::<ActiveSettingsProfileName>();
143 }
144
145 None
146 }
147}
148
149impl PickerDelegate for SettingsProfileSelectorDelegate {
150 type ListItem = ListItem;
151
152 fn placeholder_text(&self, _: &mut Window, _: &mut App) -> std::sync::Arc<str> {
153 "Select a settings profile...".into()
154 }
155
156 fn match_count(&self) -> usize {
157 self.matches.len()
158 }
159
160 fn selected_index(&self) -> usize {
161 self.selected_index
162 }
163
164 fn set_selected_index(
165 &mut self,
166 ix: usize,
167 _: &mut Window,
168 cx: &mut Context<Picker<SettingsProfileSelectorDelegate>>,
169 ) {
170 self.selected_index = ix;
171 self.selected_profile_name = self.set_selected_profile(cx);
172 }
173
174 fn update_matches(
175 &mut self,
176 query: String,
177 window: &mut Window,
178 cx: &mut Context<Picker<SettingsProfileSelectorDelegate>>,
179 ) -> Task<()> {
180 let background = cx.background_executor().clone();
181 let candidates = self
182 .profile_names
183 .iter()
184 .enumerate()
185 .map(|(id, profile_name)| StringMatchCandidate::new(id, &display_name(profile_name)))
186 .collect::<Vec<_>>();
187
188 cx.spawn_in(window, async move |this, cx| {
189 let matches = if query.is_empty() {
190 candidates
191 .into_iter()
192 .enumerate()
193 .map(|(index, candidate)| StringMatch {
194 candidate_id: index,
195 string: candidate.string,
196 positions: Vec::new(),
197 score: 0.0,
198 })
199 .collect()
200 } else {
201 match_strings(
202 &candidates,
203 &query,
204 false,
205 true,
206 100,
207 &Default::default(),
208 background,
209 )
210 .await
211 };
212
213 this.update_in(cx, |this, _, cx| {
214 this.delegate.matches = matches;
215 this.delegate.selected_index = this
216 .delegate
217 .selected_index
218 .min(this.delegate.matches.len().saturating_sub(1));
219 this.delegate.selected_profile_name = this.delegate.set_selected_profile(cx);
220 })
221 .ok();
222 })
223 }
224
225 fn confirm(
226 &mut self,
227 _: bool,
228 _: &mut Window,
229 cx: &mut Context<Picker<SettingsProfileSelectorDelegate>>,
230 ) {
231 self.selection_completed = true;
232 self.selector
233 .update(cx, |_, cx| {
234 cx.emit(DismissEvent);
235 })
236 .ok();
237 }
238
239 fn dismissed(
240 &mut self,
241 _: &mut Window,
242 cx: &mut Context<Picker<SettingsProfileSelectorDelegate>>,
243 ) {
244 if !self.selection_completed {
245 SettingsProfileSelectorDelegate::update_active_profile_name_global(
246 self.original_profile_name.clone(),
247 cx,
248 );
249 }
250 self.selector.update(cx, |_, cx| cx.emit(DismissEvent)).ok();
251 }
252
253 fn render_match(
254 &self,
255 ix: usize,
256 selected: bool,
257 _: &mut Window,
258 _: &mut Context<Picker<Self>>,
259 ) -> Option<Self::ListItem> {
260 let mat = &self.matches.get(ix)?;
261 let profile_name = &self.profile_names.get(mat.candidate_id)?;
262
263 Some(
264 ListItem::new(ix)
265 .inset(true)
266 .spacing(ListItemSpacing::Sparse)
267 .toggle_state(selected)
268 .child(HighlightedLabel::new(
269 display_name(profile_name),
270 mat.positions.clone(),
271 )),
272 )
273 }
274}
275
276fn display_name(profile_name: &Option<String>) -> String {
277 profile_name.clone().unwrap_or("Disabled".into())
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283 use editor;
284 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
285 use menu::{Cancel, Confirm, SelectNext, SelectPrevious};
286 use project::{FakeFs, Project};
287 use serde_json::json;
288 use settings::Settings;
289 use theme::{self, ThemeSettings};
290 use workspace::{self, AppState, MultiWorkspace};
291 use zed_actions::settings_profile_selector;
292
293 async fn init_test(
294 profiles_json: serde_json::Value,
295 cx: &mut TestAppContext,
296 ) -> (Entity<Workspace>, &mut VisualTestContext) {
297 cx.update(|cx| {
298 let state = AppState::test(cx);
299 let settings_store = SettingsStore::test(cx);
300 cx.set_global(settings_store);
301 settings::init(cx);
302 theme::init(theme::LoadThemes::JustBase, cx);
303 super::init(cx);
304 editor::init(cx);
305 state
306 });
307
308 cx.update(|cx| {
309 SettingsStore::update_global(cx, |store, cx| {
310 let settings_json = json!({
311 "buffer_font_size": 10.0,
312 "profiles": profiles_json,
313 });
314
315 store
316 .set_user_settings(&settings_json.to_string(), cx)
317 .unwrap();
318 });
319 });
320
321 let fs = FakeFs::new(cx.executor());
322 let project = Project::test(fs, ["/test".as_ref()], cx).await;
323 let window = cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
324 let cx = VisualTestContext::from_window(*window, cx).into_mut();
325 let workspace = window
326 .read_with(cx, |mw, _| mw.workspace().clone())
327 .unwrap();
328
329 cx.update(|_, cx| {
330 assert!(!cx.has_global::<ActiveSettingsProfileName>());
331 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
332 });
333
334 (workspace, cx)
335 }
336
337 #[track_caller]
338 fn active_settings_profile_picker(
339 workspace: &Entity<Workspace>,
340 cx: &mut VisualTestContext,
341 ) -> Entity<Picker<SettingsProfileSelectorDelegate>> {
342 workspace.update(cx, |workspace, cx| {
343 workspace
344 .active_modal::<SettingsProfileSelector>(cx)
345 .expect("settings profile selector is not open")
346 .read(cx)
347 .picker
348 .clone()
349 })
350 }
351
352 #[gpui::test]
353 async fn test_settings_profile_selector_state(cx: &mut TestAppContext) {
354 let classroom_and_streaming_profile_name = "Classroom / Streaming".to_string();
355 let demo_videos_profile_name = "Demo Videos".to_string();
356
357 let profiles_json = json!({
358 classroom_and_streaming_profile_name.clone(): {
359 "buffer_font_size": 20.0,
360 },
361 demo_videos_profile_name.clone(): {
362 "buffer_font_size": 15.0
363 }
364 });
365 let (workspace, cx) = init_test(profiles_json.clone(), cx).await;
366
367 cx.dispatch_action(settings_profile_selector::Toggle);
368 let picker = active_settings_profile_picker(&workspace, cx);
369
370 picker.read_with(cx, |picker, cx| {
371 assert_eq!(picker.delegate.matches.len(), 3);
372 assert_eq!(picker.delegate.matches[0].string, display_name(&None));
373 assert_eq!(
374 picker.delegate.matches[1].string,
375 classroom_and_streaming_profile_name
376 );
377 assert_eq!(picker.delegate.matches[2].string, demo_videos_profile_name);
378 assert_eq!(picker.delegate.matches.get(3), None);
379
380 assert_eq!(picker.delegate.selected_index, 0);
381 assert_eq!(picker.delegate.selected_profile_name, None);
382
383 assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
384 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
385 });
386
387 cx.dispatch_action(Confirm);
388
389 cx.update(|_, cx| {
390 assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
391 });
392
393 cx.dispatch_action(settings_profile_selector::Toggle);
394 let picker = active_settings_profile_picker(&workspace, cx);
395 cx.dispatch_action(SelectNext);
396
397 picker.read_with(cx, |picker, cx| {
398 assert_eq!(picker.delegate.selected_index, 1);
399 assert_eq!(
400 picker.delegate.selected_profile_name,
401 Some(classroom_and_streaming_profile_name.clone())
402 );
403
404 assert_eq!(
405 cx.try_global::<ActiveSettingsProfileName>()
406 .map(|p| p.0.clone()),
407 Some(classroom_and_streaming_profile_name.clone())
408 );
409
410 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
411 });
412
413 cx.dispatch_action(Cancel);
414
415 cx.update(|_, cx| {
416 assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
417 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
418 });
419
420 cx.dispatch_action(settings_profile_selector::Toggle);
421 let picker = active_settings_profile_picker(&workspace, cx);
422
423 cx.dispatch_action(SelectNext);
424
425 picker.read_with(cx, |picker, cx| {
426 assert_eq!(picker.delegate.selected_index, 1);
427 assert_eq!(
428 picker.delegate.selected_profile_name,
429 Some(classroom_and_streaming_profile_name.clone())
430 );
431
432 assert_eq!(
433 cx.try_global::<ActiveSettingsProfileName>()
434 .map(|p| p.0.clone()),
435 Some(classroom_and_streaming_profile_name.clone())
436 );
437
438 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
439 });
440
441 cx.dispatch_action(SelectNext);
442
443 picker.read_with(cx, |picker, cx| {
444 assert_eq!(picker.delegate.selected_index, 2);
445 assert_eq!(
446 picker.delegate.selected_profile_name,
447 Some(demo_videos_profile_name.clone())
448 );
449
450 assert_eq!(
451 cx.try_global::<ActiveSettingsProfileName>()
452 .map(|p| p.0.clone()),
453 Some(demo_videos_profile_name.clone())
454 );
455
456 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
457 });
458
459 cx.dispatch_action(Confirm);
460
461 cx.update(|_, cx| {
462 assert_eq!(
463 cx.try_global::<ActiveSettingsProfileName>()
464 .map(|p| p.0.clone()),
465 Some(demo_videos_profile_name.clone())
466 );
467 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
468 });
469
470 cx.dispatch_action(settings_profile_selector::Toggle);
471 let picker = active_settings_profile_picker(&workspace, cx);
472
473 picker.read_with(cx, |picker, cx| {
474 assert_eq!(picker.delegate.selected_index, 2);
475 assert_eq!(
476 picker.delegate.selected_profile_name,
477 Some(demo_videos_profile_name.clone())
478 );
479
480 assert_eq!(
481 cx.try_global::<ActiveSettingsProfileName>()
482 .map(|p| p.0.clone()),
483 Some(demo_videos_profile_name.clone())
484 );
485 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
486 });
487
488 cx.dispatch_action(SelectPrevious);
489
490 picker.read_with(cx, |picker, cx| {
491 assert_eq!(picker.delegate.selected_index, 1);
492 assert_eq!(
493 picker.delegate.selected_profile_name,
494 Some(classroom_and_streaming_profile_name.clone())
495 );
496
497 assert_eq!(
498 cx.try_global::<ActiveSettingsProfileName>()
499 .map(|p| p.0.clone()),
500 Some(classroom_and_streaming_profile_name.clone())
501 );
502
503 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
504 });
505
506 cx.dispatch_action(Cancel);
507
508 cx.update(|_, cx| {
509 assert_eq!(
510 cx.try_global::<ActiveSettingsProfileName>()
511 .map(|p| p.0.clone()),
512 Some(demo_videos_profile_name.clone())
513 );
514
515 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
516 });
517
518 cx.dispatch_action(settings_profile_selector::Toggle);
519 let picker = active_settings_profile_picker(&workspace, cx);
520
521 picker.read_with(cx, |picker, cx| {
522 assert_eq!(picker.delegate.selected_index, 2);
523 assert_eq!(
524 picker.delegate.selected_profile_name,
525 Some(demo_videos_profile_name.clone())
526 );
527
528 assert_eq!(
529 cx.try_global::<ActiveSettingsProfileName>()
530 .map(|p| p.0.clone()),
531 Some(demo_videos_profile_name)
532 );
533
534 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
535 });
536
537 cx.dispatch_action(SelectPrevious);
538
539 picker.read_with(cx, |picker, cx| {
540 assert_eq!(picker.delegate.selected_index, 1);
541 assert_eq!(
542 picker.delegate.selected_profile_name,
543 Some(classroom_and_streaming_profile_name.clone())
544 );
545
546 assert_eq!(
547 cx.try_global::<ActiveSettingsProfileName>()
548 .map(|p| p.0.clone()),
549 Some(classroom_and_streaming_profile_name)
550 );
551
552 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
553 });
554
555 cx.dispatch_action(SelectPrevious);
556
557 picker.read_with(cx, |picker, cx| {
558 assert_eq!(picker.delegate.selected_index, 0);
559 assert_eq!(picker.delegate.selected_profile_name, None);
560
561 assert_eq!(
562 cx.try_global::<ActiveSettingsProfileName>()
563 .map(|p| p.0.clone()),
564 None
565 );
566
567 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
568 });
569
570 cx.dispatch_action(Confirm);
571
572 cx.update(|_, cx| {
573 assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
574 assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
575 });
576 }
577
578 #[gpui::test]
579 async fn test_settings_profile_selector_is_in_user_configuration_order(
580 cx: &mut TestAppContext,
581 ) {
582 // Must be unique names (HashMap)
583 let profiles_json = json!({
584 "z": {},
585 "e": {},
586 "d": {},
587 " ": {},
588 "r": {},
589 "u": {},
590 "l": {},
591 "3": {},
592 "s": {},
593 "!": {},
594 });
595 let (workspace, cx) = init_test(profiles_json.clone(), cx).await;
596
597 cx.dispatch_action(settings_profile_selector::Toggle);
598 let picker = active_settings_profile_picker(&workspace, cx);
599
600 picker.read_with(cx, |picker, _| {
601 assert_eq!(picker.delegate.matches.len(), 11);
602 assert_eq!(picker.delegate.matches[0].string, display_name(&None));
603 assert_eq!(picker.delegate.matches[1].string, "z");
604 assert_eq!(picker.delegate.matches[2].string, "e");
605 assert_eq!(picker.delegate.matches[3].string, "d");
606 assert_eq!(picker.delegate.matches[4].string, " ");
607 assert_eq!(picker.delegate.matches[5].string, "r");
608 assert_eq!(picker.delegate.matches[6].string, "u");
609 assert_eq!(picker.delegate.matches[7].string, "l");
610 assert_eq!(picker.delegate.matches[8].string, "3");
611 assert_eq!(picker.delegate.matches[9].string, "s");
612 assert_eq!(picker.delegate.matches[10].string, "!");
613 });
614 }
615}