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