settings_profile_selector.rs

  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};
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 (workspace, cx) =
324            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
325
326        cx.update(|_, cx| {
327            assert!(!cx.has_global::<ActiveSettingsProfileName>());
328            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
329        });
330
331        (workspace, cx)
332    }
333
334    #[track_caller]
335    fn active_settings_profile_picker(
336        workspace: &Entity<Workspace>,
337        cx: &mut VisualTestContext,
338    ) -> Entity<Picker<SettingsProfileSelectorDelegate>> {
339        workspace.update(cx, |workspace, cx| {
340            workspace
341                .active_modal::<SettingsProfileSelector>(cx)
342                .expect("settings profile selector is not open")
343                .read(cx)
344                .picker
345                .clone()
346        })
347    }
348
349    #[gpui::test]
350    async fn test_settings_profile_selector_state(cx: &mut TestAppContext) {
351        let classroom_and_streaming_profile_name = "Classroom / Streaming".to_string();
352        let demo_videos_profile_name = "Demo Videos".to_string();
353
354        let profiles_json = json!({
355            classroom_and_streaming_profile_name.clone(): {
356                "buffer_font_size": 20.0,
357            },
358            demo_videos_profile_name.clone(): {
359                "buffer_font_size": 15.0
360            }
361        });
362        let (workspace, cx) = init_test(profiles_json.clone(), cx).await;
363
364        cx.dispatch_action(settings_profile_selector::Toggle);
365        let picker = active_settings_profile_picker(&workspace, cx);
366
367        picker.read_with(cx, |picker, cx| {
368            assert_eq!(picker.delegate.matches.len(), 3);
369            assert_eq!(picker.delegate.matches[0].string, display_name(&None));
370            assert_eq!(
371                picker.delegate.matches[1].string,
372                classroom_and_streaming_profile_name
373            );
374            assert_eq!(picker.delegate.matches[2].string, demo_videos_profile_name);
375            assert_eq!(picker.delegate.matches.get(3), None);
376
377            assert_eq!(picker.delegate.selected_index, 0);
378            assert_eq!(picker.delegate.selected_profile_name, None);
379
380            assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
381            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
382        });
383
384        cx.dispatch_action(Confirm);
385
386        cx.update(|_, cx| {
387            assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
388        });
389
390        cx.dispatch_action(settings_profile_selector::Toggle);
391        let picker = active_settings_profile_picker(&workspace, cx);
392        cx.dispatch_action(SelectNext);
393
394        picker.read_with(cx, |picker, cx| {
395            assert_eq!(picker.delegate.selected_index, 1);
396            assert_eq!(
397                picker.delegate.selected_profile_name,
398                Some(classroom_and_streaming_profile_name.clone())
399            );
400
401            assert_eq!(
402                cx.try_global::<ActiveSettingsProfileName>()
403                    .map(|p| p.0.clone()),
404                Some(classroom_and_streaming_profile_name.clone())
405            );
406
407            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
408        });
409
410        cx.dispatch_action(Cancel);
411
412        cx.update(|_, cx| {
413            assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
414            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
415        });
416
417        cx.dispatch_action(settings_profile_selector::Toggle);
418        let picker = active_settings_profile_picker(&workspace, cx);
419
420        cx.dispatch_action(SelectNext);
421
422        picker.read_with(cx, |picker, cx| {
423            assert_eq!(picker.delegate.selected_index, 1);
424            assert_eq!(
425                picker.delegate.selected_profile_name,
426                Some(classroom_and_streaming_profile_name.clone())
427            );
428
429            assert_eq!(
430                cx.try_global::<ActiveSettingsProfileName>()
431                    .map(|p| p.0.clone()),
432                Some(classroom_and_streaming_profile_name.clone())
433            );
434
435            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
436        });
437
438        cx.dispatch_action(SelectNext);
439
440        picker.read_with(cx, |picker, cx| {
441            assert_eq!(picker.delegate.selected_index, 2);
442            assert_eq!(
443                picker.delegate.selected_profile_name,
444                Some(demo_videos_profile_name.clone())
445            );
446
447            assert_eq!(
448                cx.try_global::<ActiveSettingsProfileName>()
449                    .map(|p| p.0.clone()),
450                Some(demo_videos_profile_name.clone())
451            );
452
453            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
454        });
455
456        cx.dispatch_action(Confirm);
457
458        cx.update(|_, cx| {
459            assert_eq!(
460                cx.try_global::<ActiveSettingsProfileName>()
461                    .map(|p| p.0.clone()),
462                Some(demo_videos_profile_name.clone())
463            );
464            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
465        });
466
467        cx.dispatch_action(settings_profile_selector::Toggle);
468        let picker = active_settings_profile_picker(&workspace, cx);
469
470        picker.read_with(cx, |picker, cx| {
471            assert_eq!(picker.delegate.selected_index, 2);
472            assert_eq!(
473                picker.delegate.selected_profile_name,
474                Some(demo_videos_profile_name.clone())
475            );
476
477            assert_eq!(
478                cx.try_global::<ActiveSettingsProfileName>()
479                    .map(|p| p.0.clone()),
480                Some(demo_videos_profile_name.clone())
481            );
482            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
483        });
484
485        cx.dispatch_action(SelectPrevious);
486
487        picker.read_with(cx, |picker, cx| {
488            assert_eq!(picker.delegate.selected_index, 1);
489            assert_eq!(
490                picker.delegate.selected_profile_name,
491                Some(classroom_and_streaming_profile_name.clone())
492            );
493
494            assert_eq!(
495                cx.try_global::<ActiveSettingsProfileName>()
496                    .map(|p| p.0.clone()),
497                Some(classroom_and_streaming_profile_name.clone())
498            );
499
500            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
501        });
502
503        cx.dispatch_action(Cancel);
504
505        cx.update(|_, cx| {
506            assert_eq!(
507                cx.try_global::<ActiveSettingsProfileName>()
508                    .map(|p| p.0.clone()),
509                Some(demo_videos_profile_name.clone())
510            );
511
512            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
513        });
514
515        cx.dispatch_action(settings_profile_selector::Toggle);
516        let picker = active_settings_profile_picker(&workspace, cx);
517
518        picker.read_with(cx, |picker, cx| {
519            assert_eq!(picker.delegate.selected_index, 2);
520            assert_eq!(
521                picker.delegate.selected_profile_name,
522                Some(demo_videos_profile_name.clone())
523            );
524
525            assert_eq!(
526                cx.try_global::<ActiveSettingsProfileName>()
527                    .map(|p| p.0.clone()),
528                Some(demo_videos_profile_name)
529            );
530
531            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(15.0));
532        });
533
534        cx.dispatch_action(SelectPrevious);
535
536        picker.read_with(cx, |picker, cx| {
537            assert_eq!(picker.delegate.selected_index, 1);
538            assert_eq!(
539                picker.delegate.selected_profile_name,
540                Some(classroom_and_streaming_profile_name.clone())
541            );
542
543            assert_eq!(
544                cx.try_global::<ActiveSettingsProfileName>()
545                    .map(|p| p.0.clone()),
546                Some(classroom_and_streaming_profile_name)
547            );
548
549            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(20.0));
550        });
551
552        cx.dispatch_action(SelectPrevious);
553
554        picker.read_with(cx, |picker, cx| {
555            assert_eq!(picker.delegate.selected_index, 0);
556            assert_eq!(picker.delegate.selected_profile_name, None);
557
558            assert_eq!(
559                cx.try_global::<ActiveSettingsProfileName>()
560                    .map(|p| p.0.clone()),
561                None
562            );
563
564            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
565        });
566
567        cx.dispatch_action(Confirm);
568
569        cx.update(|_, cx| {
570            assert_eq!(cx.try_global::<ActiveSettingsProfileName>(), None);
571            assert_eq!(ThemeSettings::get_global(cx).buffer_font_size(cx), px(10.0));
572        });
573    }
574
575    #[gpui::test]
576    async fn test_settings_profile_selector_is_in_user_configuration_order(
577        cx: &mut TestAppContext,
578    ) {
579        // Must be unique names (HashMap)
580        let profiles_json = json!({
581            "z": {},
582            "e": {},
583            "d": {},
584            " ": {},
585            "r": {},
586            "u": {},
587            "l": {},
588            "3": {},
589            "s": {},
590            "!": {},
591        });
592        let (workspace, cx) = init_test(profiles_json.clone(), cx).await;
593
594        cx.dispatch_action(settings_profile_selector::Toggle);
595        let picker = active_settings_profile_picker(&workspace, cx);
596
597        picker.read_with(cx, |picker, _| {
598            assert_eq!(picker.delegate.matches.len(), 11);
599            assert_eq!(picker.delegate.matches[0].string, display_name(&None));
600            assert_eq!(picker.delegate.matches[1].string, "z");
601            assert_eq!(picker.delegate.matches[2].string, "e");
602            assert_eq!(picker.delegate.matches[3].string, "d");
603            assert_eq!(picker.delegate.matches[4].string, " ");
604            assert_eq!(picker.delegate.matches[5].string, "r");
605            assert_eq!(picker.delegate.matches[6].string, "u");
606            assert_eq!(picker.delegate.matches[7].string, "l");
607            assert_eq!(picker.delegate.matches[8].string, "3");
608            assert_eq!(picker.delegate.matches[9].string, "s");
609            assert_eq!(picker.delegate.matches[10].string, "!");
610        });
611    }
612}