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