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