1//! # settings_ui
2mod components;
3mod page_data;
4
5use anyhow::Result;
6use editor::{Editor, EditorEvent};
7use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
8use fuzzy::StringMatchCandidate;
9use gpui::{
10 Action, App, Div, Entity, FocusHandle, Focusable, FontWeight, Global, ReadGlobal as _,
11 ScrollHandle, Task, TitlebarOptions, UniformListScrollHandle, Window, WindowHandle,
12 WindowOptions, actions, div, point, prelude::*, px, size, uniform_list,
13};
14use project::WorktreeId;
15use schemars::JsonSchema;
16use serde::Deserialize;
17use settings::{
18 BottomDockLayout, CloseWindowWhenNoItems, CodeFade, CursorShape, OnLastWindowClosed,
19 RestoreOnStartupBehavior, SaturatingBool, SettingsContent, SettingsStore,
20};
21use std::{
22 any::{Any, TypeId, type_name},
23 cell::RefCell,
24 collections::HashMap,
25 num::{NonZero, NonZeroU32},
26 ops::Range,
27 rc::Rc,
28 sync::{Arc, LazyLock, RwLock, atomic::AtomicBool},
29};
30use ui::{
31 ButtonLike, ContextMenu, Divider, DropdownMenu, DropdownStyle, IconButtonShape,
32 KeybindingPosition, PopoverMenu, Switch, SwitchColor, TreeViewItem, WithScrollbar, prelude::*,
33};
34use ui_input::{NumericStepper, NumericStepperStyle, NumericStepperType};
35use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
36use zed_actions::OpenSettingsEditor;
37
38use crate::components::SettingsEditor;
39
40const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
41const NAVBAR_GROUP_TAB_INDEX: isize = 1;
42const CONTENT_CONTAINER_TAB_INDEX: isize = 2;
43const CONTENT_GROUP_TAB_INDEX: isize = 3;
44
45actions!(
46 settings_editor,
47 [
48 /// Toggles focus between the navbar and the main content.
49 ToggleFocusNav,
50 /// Focuses the next file in the file list.
51 FocusNextFile,
52 /// Focuses the previous file in the file list.
53 FocusPreviousFile
54 ]
55);
56
57#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
58#[action(namespace = settings_editor)]
59struct FocusFile(pub u32);
60
61#[derive(Clone, Copy)]
62struct SettingField<T: 'static> {
63 pick: fn(&SettingsContent) -> &Option<T>,
64 pick_mut: fn(&mut SettingsContent) -> &mut Option<T>,
65}
66
67/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
68/// to keep the setting around in the UI with valid pick and pick_mut implementations, but don't actually try to render it.
69/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
70struct UnimplementedSettingField;
71
72impl<T: 'static> SettingField<T> {
73 /// Helper for settings with types that are not yet implemented.
74 #[allow(unused)]
75 fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
76 SettingField {
77 pick: |_| &None,
78 pick_mut: |_| unreachable!(),
79 }
80 }
81}
82
83trait AnySettingField {
84 fn as_any(&self) -> &dyn Any;
85 fn type_name(&self) -> &'static str;
86 fn type_id(&self) -> TypeId;
87 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> settings::SettingsFile;
88}
89
90impl<T> AnySettingField for SettingField<T> {
91 fn as_any(&self) -> &dyn Any {
92 self
93 }
94
95 fn type_name(&self) -> &'static str {
96 type_name::<T>()
97 }
98
99 fn type_id(&self) -> TypeId {
100 TypeId::of::<T>()
101 }
102
103 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> settings::SettingsFile {
104 if AnySettingField::type_id(self) == TypeId::of::<UnimplementedSettingField>() {
105 return file.to_settings();
106 }
107
108 let (file, _) = cx.global::<SettingsStore>().get_value_from_file(
109 file.to_settings(),
110 self.pick,
111 self.type_name(),
112 );
113 return file;
114 }
115}
116
117#[derive(Default, Clone)]
118struct SettingFieldRenderer {
119 renderers: Rc<
120 RefCell<
121 HashMap<
122 TypeId,
123 Box<
124 dyn Fn(
125 &dyn AnySettingField,
126 SettingsUiFile,
127 Option<&SettingsFieldMetadata>,
128 &mut Window,
129 &mut App,
130 ) -> AnyElement,
131 >,
132 >,
133 >,
134 >,
135}
136
137impl Global for SettingFieldRenderer {}
138
139impl SettingFieldRenderer {
140 fn add_renderer<T: 'static>(
141 &mut self,
142 renderer: impl Fn(
143 &SettingField<T>,
144 SettingsUiFile,
145 Option<&SettingsFieldMetadata>,
146 &mut Window,
147 &mut App,
148 ) -> AnyElement
149 + 'static,
150 ) -> &mut Self {
151 let key = TypeId::of::<T>();
152 let renderer = Box::new(
153 move |any_setting_field: &dyn AnySettingField,
154 settings_file: SettingsUiFile,
155 metadata: Option<&SettingsFieldMetadata>,
156 window: &mut Window,
157 cx: &mut App| {
158 let field = any_setting_field
159 .as_any()
160 .downcast_ref::<SettingField<T>>()
161 .unwrap();
162 renderer(field, settings_file, metadata, window, cx)
163 },
164 );
165 self.renderers.borrow_mut().insert(key, renderer);
166 self
167 }
168
169 fn render(
170 &self,
171 any_setting_field: &dyn AnySettingField,
172 settings_file: SettingsUiFile,
173 metadata: Option<&SettingsFieldMetadata>,
174 window: &mut Window,
175 cx: &mut App,
176 ) -> AnyElement {
177 let key = any_setting_field.type_id();
178 if let Some(renderer) = self.renderers.borrow().get(&key) {
179 renderer(any_setting_field, settings_file, metadata, window, cx)
180 } else {
181 panic!(
182 "No renderer found for type: {}",
183 any_setting_field.type_name()
184 )
185 }
186 }
187}
188
189struct SettingsFieldMetadata {
190 placeholder: Option<&'static str>,
191}
192
193pub struct SettingsUiFeatureFlag;
194
195impl FeatureFlag for SettingsUiFeatureFlag {
196 const NAME: &'static str = "settings-ui";
197}
198
199pub fn init(cx: &mut App) {
200 init_renderers(cx);
201
202 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
203 workspace.register_action_renderer(|div, _, _, cx| {
204 let settings_ui_actions = [
205 TypeId::of::<OpenSettingsEditor>(),
206 TypeId::of::<ToggleFocusNav>(),
207 TypeId::of::<FocusFile>(),
208 TypeId::of::<FocusNextFile>(),
209 TypeId::of::<FocusPreviousFile>(),
210 ];
211 let has_flag = cx.has_flag::<SettingsUiFeatureFlag>();
212 command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _| {
213 if has_flag {
214 filter.show_action_types(&settings_ui_actions);
215 } else {
216 filter.hide_action_types(&settings_ui_actions);
217 }
218 });
219 if has_flag {
220 div.on_action(cx.listener(|_, _: &OpenSettingsEditor, _, cx| {
221 open_settings_editor(cx).ok();
222 }))
223 } else {
224 div
225 }
226 });
227 })
228 .detach();
229}
230
231fn init_renderers(cx: &mut App) {
232 // fn (field: SettingsField, current_file: SettingsFile, cx) -> (currently_set_in: SettingsFile, overridden_in: Vec<SettingsFile>)
233 cx.default_global::<SettingFieldRenderer>()
234 .add_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
235 // TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
236 Button::new("unimplemented-field", "UNIMPLEMENTED")
237 .size(ButtonSize::Medium)
238 .icon(IconName::XCircle)
239 .icon_position(IconPosition::Start)
240 .icon_color(Color::Error)
241 .icon_size(IconSize::Small)
242 .style(ButtonStyle::Outlined)
243 .into_any_element()
244 })
245 .add_renderer::<bool>(|settings_field, file, _, _, cx| {
246 render_toggle_button(*settings_field, file, cx).into_any_element()
247 })
248 .add_renderer::<String>(|settings_field, file, metadata, _, cx| {
249 render_text_field(settings_field.clone(), file, metadata, cx)
250 })
251 .add_renderer::<SaturatingBool>(|settings_field, file, _, _, cx| {
252 render_toggle_button(*settings_field, file, cx)
253 })
254 .add_renderer::<CursorShape>(|settings_field, file, _, window, cx| {
255 render_dropdown(*settings_field, file, window, cx)
256 })
257 .add_renderer::<RestoreOnStartupBehavior>(|settings_field, file, _, window, cx| {
258 render_dropdown(*settings_field, file, window, cx)
259 })
260 .add_renderer::<BottomDockLayout>(|settings_field, file, _, window, cx| {
261 render_dropdown(*settings_field, file, window, cx)
262 })
263 .add_renderer::<OnLastWindowClosed>(|settings_field, file, _, window, cx| {
264 render_dropdown(*settings_field, file, window, cx)
265 })
266 .add_renderer::<CloseWindowWhenNoItems>(|settings_field, file, _, window, cx| {
267 render_dropdown(*settings_field, file, window, cx)
268 })
269 .add_renderer::<settings::FontFamilyName>(|settings_field, file, _, window, cx| {
270 // todo(settings_ui): We need to pass in a validator for this to ensure that users that type in invalid font names
271 render_font_picker(settings_field.clone(), file, window, cx)
272 })
273 // todo(settings_ui): This needs custom ui
274 // .add_renderer::<settings::BufferLineHeight>(|settings_field, file, _, window, cx| {
275 // // todo(settings_ui): Do we want to expose the custom variant of buffer line height?
276 // // right now there's a manual impl of strum::VariantArray
277 // render_dropdown(*settings_field, file, window, cx)
278 // })
279 .add_renderer::<settings::BaseKeymapContent>(|settings_field, file, _, window, cx| {
280 render_dropdown(*settings_field, file, window, cx)
281 })
282 .add_renderer::<settings::MultiCursorModifier>(|settings_field, file, _, window, cx| {
283 render_dropdown(*settings_field, file, window, cx)
284 })
285 .add_renderer::<settings::HideMouseMode>(|settings_field, file, _, window, cx| {
286 render_dropdown(*settings_field, file, window, cx)
287 })
288 .add_renderer::<settings::CurrentLineHighlight>(|settings_field, file, _, window, cx| {
289 render_dropdown(*settings_field, file, window, cx)
290 })
291 .add_renderer::<settings::ShowWhitespaceSetting>(|settings_field, file, _, window, cx| {
292 render_dropdown(*settings_field, file, window, cx)
293 })
294 .add_renderer::<settings::SoftWrap>(|settings_field, file, _, window, cx| {
295 render_dropdown(*settings_field, file, window, cx)
296 })
297 .add_renderer::<settings::ScrollBeyondLastLine>(|settings_field, file, _, window, cx| {
298 render_dropdown(*settings_field, file, window, cx)
299 })
300 .add_renderer::<settings::SnippetSortOrder>(|settings_field, file, _, window, cx| {
301 render_dropdown(*settings_field, file, window, cx)
302 })
303 .add_renderer::<settings::ClosePosition>(|settings_field, file, _, window, cx| {
304 render_dropdown(*settings_field, file, window, cx)
305 })
306 .add_renderer::<settings::DockSide>(|settings_field, file, _, window, cx| {
307 render_dropdown(*settings_field, file, window, cx)
308 })
309 .add_renderer::<settings::TerminalDockPosition>(|settings_field, file, _, window, cx| {
310 render_dropdown(*settings_field, file, window, cx)
311 })
312 .add_renderer::<settings::DockPosition>(|settings_field, file, _, window, cx| {
313 render_dropdown(*settings_field, file, window, cx)
314 })
315 .add_renderer::<settings::GitGutterSetting>(|settings_field, file, _, window, cx| {
316 render_dropdown(*settings_field, file, window, cx)
317 })
318 .add_renderer::<settings::GitHunkStyleSetting>(|settings_field, file, _, window, cx| {
319 render_dropdown(*settings_field, file, window, cx)
320 })
321 .add_renderer::<settings::DiagnosticSeverityContent>(
322 |settings_field, file, _, window, cx| {
323 render_dropdown(*settings_field, file, window, cx)
324 },
325 )
326 .add_renderer::<settings::SeedQuerySetting>(|settings_field, file, _, window, cx| {
327 render_dropdown(*settings_field, file, window, cx)
328 })
329 .add_renderer::<settings::DoubleClickInMultibuffer>(
330 |settings_field, file, _, window, cx| {
331 render_dropdown(*settings_field, file, window, cx)
332 },
333 )
334 .add_renderer::<settings::GoToDefinitionFallback>(|settings_field, file, _, window, cx| {
335 render_dropdown(*settings_field, file, window, cx)
336 })
337 .add_renderer::<settings::ActivateOnClose>(|settings_field, file, _, window, cx| {
338 render_dropdown(*settings_field, file, window, cx)
339 })
340 .add_renderer::<settings::ShowDiagnostics>(|settings_field, file, _, window, cx| {
341 render_dropdown(*settings_field, file, window, cx)
342 })
343 .add_renderer::<settings::ShowCloseButton>(|settings_field, file, _, window, cx| {
344 render_dropdown(*settings_field, file, window, cx)
345 })
346 .add_renderer::<settings::ProjectPanelEntrySpacing>(
347 |settings_field, file, _, window, cx| {
348 render_dropdown(*settings_field, file, window, cx)
349 },
350 )
351 .add_renderer::<settings::RewrapBehavior>(|settings_field, file, _, window, cx| {
352 render_dropdown(*settings_field, file, window, cx)
353 })
354 .add_renderer::<settings::FormatOnSave>(|settings_field, file, _, window, cx| {
355 render_dropdown(*settings_field, file, window, cx)
356 })
357 .add_renderer::<settings::IndentGuideColoring>(|settings_field, file, _, window, cx| {
358 render_dropdown(*settings_field, file, window, cx)
359 })
360 .add_renderer::<settings::IndentGuideBackgroundColoring>(
361 |settings_field, file, _, window, cx| {
362 render_dropdown(*settings_field, file, window, cx)
363 },
364 )
365 .add_renderer::<settings::FileFinderWidthContent>(|settings_field, file, _, window, cx| {
366 render_dropdown(*settings_field, file, window, cx)
367 })
368 .add_renderer::<settings::ShowDiagnostics>(|settings_field, file, _, window, cx| {
369 render_dropdown(*settings_field, file, window, cx)
370 })
371 .add_renderer::<settings::WordsCompletionMode>(|settings_field, file, _, window, cx| {
372 render_dropdown(*settings_field, file, window, cx)
373 })
374 .add_renderer::<settings::LspInsertMode>(|settings_field, file, _, window, cx| {
375 render_dropdown(*settings_field, file, window, cx)
376 })
377 .add_renderer::<f32>(|settings_field, file, _, window, cx| {
378 render_numeric_stepper(*settings_field, file, window, cx)
379 })
380 .add_renderer::<u32>(|settings_field, file, _, window, cx| {
381 render_numeric_stepper(*settings_field, file, window, cx)
382 })
383 .add_renderer::<u64>(|settings_field, file, _, window, cx| {
384 render_numeric_stepper(*settings_field, file, window, cx)
385 })
386 .add_renderer::<usize>(|settings_field, file, _, window, cx| {
387 render_numeric_stepper(*settings_field, file, window, cx)
388 })
389 .add_renderer::<NonZero<usize>>(|settings_field, file, _, window, cx| {
390 render_numeric_stepper(*settings_field, file, window, cx)
391 })
392 .add_renderer::<NonZeroU32>(|settings_field, file, _, window, cx| {
393 render_numeric_stepper(*settings_field, file, window, cx)
394 })
395 .add_renderer::<CodeFade>(|settings_field, file, _, window, cx| {
396 render_numeric_stepper(*settings_field, file, window, cx)
397 })
398 .add_renderer::<FontWeight>(|settings_field, file, _, window, cx| {
399 render_numeric_stepper(*settings_field, file, window, cx)
400 })
401 .add_renderer::<settings::MinimumContrast>(|settings_field, file, _, window, cx| {
402 render_numeric_stepper(*settings_field, file, window, cx)
403 })
404 .add_renderer::<settings::ShowScrollbar>(|settings_field, file, _, window, cx| {
405 render_dropdown(*settings_field, file, window, cx)
406 })
407 .add_renderer::<settings::ScrollbarDiagnostics>(|settings_field, file, _, window, cx| {
408 render_dropdown(*settings_field, file, window, cx)
409 })
410 .add_renderer::<settings::ShowMinimap>(|settings_field, file, _, window, cx| {
411 render_dropdown(*settings_field, file, window, cx)
412 })
413 .add_renderer::<settings::DisplayIn>(|settings_field, file, _, window, cx| {
414 render_dropdown(*settings_field, file, window, cx)
415 })
416 .add_renderer::<settings::MinimapThumb>(|settings_field, file, _, window, cx| {
417 render_dropdown(*settings_field, file, window, cx)
418 })
419 .add_renderer::<settings::MinimapThumbBorder>(|settings_field, file, _, window, cx| {
420 render_dropdown(*settings_field, file, window, cx)
421 })
422 .add_renderer::<settings::SteppingGranularity>(|settings_field, file, _, window, cx| {
423 render_dropdown(*settings_field, file, window, cx)
424 });
425
426 // todo(settings_ui): Figure out how we want to handle discriminant unions
427 // .add_renderer::<ThemeSelection>(|settings_field, file, _, window, cx| {
428 // render_dropdown(*settings_field, file, window, cx)
429 // });
430}
431
432pub fn open_settings_editor(cx: &mut App) -> anyhow::Result<WindowHandle<SettingsWindow>> {
433 cx.open_window(
434 WindowOptions {
435 titlebar: Some(TitlebarOptions {
436 title: Some("Settings Window".into()),
437 appears_transparent: true,
438 traffic_light_position: Some(point(px(12.0), px(12.0))),
439 }),
440 focus: true,
441 show: true,
442 kind: gpui::WindowKind::Normal,
443 window_background: cx.theme().window_background_appearance(),
444 window_min_size: Some(size(px(800.), px(600.))), // 4:3 Aspect Ratio
445 ..Default::default()
446 },
447 |window, cx| cx.new(|cx| SettingsWindow::new(window, cx)),
448 )
449}
450
451/// The current sub page path that is selected.
452/// If this is empty the selected page is rendered,
453/// otherwise the last sub page gets rendered.
454///
455/// Global so that `pick` and `pick_mut` callbacks can access it
456/// and use it to dynamically render sub pages (e.g. for language settings)
457static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
458
459fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
460 SUB_PAGE_STACK
461 .read()
462 .expect("SUB_PAGE_STACK is never poisoned")
463}
464
465fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
466 SUB_PAGE_STACK
467 .write()
468 .expect("SUB_PAGE_STACK is never poisoned")
469}
470
471pub struct SettingsWindow {
472 files: Vec<(SettingsUiFile, FocusHandle)>,
473 current_file: SettingsUiFile,
474 pages: Vec<SettingsPage>,
475 search_bar: Entity<Editor>,
476 search_task: Option<Task<()>>,
477 navbar_entry: usize, // Index into pages - should probably be (usize, Option<usize>) for section + page
478 navbar_entries: Vec<NavBarEntry>,
479 list_handle: UniformListScrollHandle,
480 search_matches: Vec<Vec<bool>>,
481 scroll_handle: ScrollHandle,
482 navbar_focus_handle: FocusHandle,
483 content_focus_handle: FocusHandle,
484 files_focus_handle: FocusHandle,
485}
486
487struct SubPage {
488 link: SubPageLink,
489 section_header: &'static str,
490}
491
492#[derive(PartialEq, Debug)]
493struct NavBarEntry {
494 title: &'static str,
495 is_root: bool,
496 expanded: bool,
497 page_index: usize,
498 item_index: Option<usize>,
499}
500
501struct SettingsPage {
502 title: &'static str,
503 items: Vec<SettingsPageItem>,
504}
505
506#[derive(PartialEq)]
507enum SettingsPageItem {
508 SectionHeader(&'static str),
509 SettingItem(SettingItem),
510 SubPageLink(SubPageLink),
511}
512
513impl std::fmt::Debug for SettingsPageItem {
514 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515 match self {
516 SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
517 SettingsPageItem::SettingItem(setting_item) => {
518 write!(f, "SettingItem({})", setting_item.title)
519 }
520 SettingsPageItem::SubPageLink(sub_page_link) => {
521 write!(f, "SubPageLink({})", sub_page_link.title)
522 }
523 }
524 }
525}
526
527impl SettingsPageItem {
528 fn render(
529 &self,
530 file: SettingsUiFile,
531 section_header: &'static str,
532 is_last: bool,
533 window: &mut Window,
534 cx: &mut Context<SettingsWindow>,
535 ) -> AnyElement {
536 match self {
537 SettingsPageItem::SectionHeader(header) => v_flex()
538 .w_full()
539 .gap_1()
540 .child(
541 Label::new(SharedString::new_static(header))
542 .size(LabelSize::XSmall)
543 .color(Color::Muted)
544 .buffer_font(cx),
545 )
546 .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
547 .into_any_element(),
548 SettingsPageItem::SettingItem(setting_item) => {
549 let renderer = cx.default_global::<SettingFieldRenderer>().clone();
550 let file_set_in =
551 SettingsUiFile::from_settings(setting_item.field.file_set_in(file.clone(), cx));
552
553 h_flex()
554 .id(setting_item.title)
555 .w_full()
556 .gap_2()
557 .flex_wrap()
558 .justify_between()
559 .map(|this| {
560 if is_last {
561 this.pb_6()
562 } else {
563 this.pb_4()
564 .border_b_1()
565 .border_color(cx.theme().colors().border_variant)
566 }
567 })
568 .child(
569 v_flex()
570 .max_w_1_2()
571 .flex_shrink()
572 .child(
573 h_flex()
574 .w_full()
575 .gap_1()
576 .child(Label::new(SharedString::new_static(setting_item.title)))
577 .when_some(
578 file_set_in.filter(|file_set_in| file_set_in != &file),
579 |this, file_set_in| {
580 this.child(
581 Label::new(format!(
582 "— set in {}",
583 file_set_in.name()
584 ))
585 .color(Color::Muted)
586 .size(LabelSize::Small),
587 )
588 },
589 ),
590 )
591 .child(
592 Label::new(SharedString::new_static(setting_item.description))
593 .size(LabelSize::Small)
594 .color(Color::Muted),
595 ),
596 )
597 .child(renderer.render(
598 setting_item.field.as_ref(),
599 file,
600 setting_item.metadata.as_deref(),
601 window,
602 cx,
603 ))
604 .into_any_element()
605 }
606 SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
607 .id(sub_page_link.title)
608 .w_full()
609 .gap_2()
610 .flex_wrap()
611 .justify_between()
612 .when(!is_last, |this| {
613 this.pb_4()
614 .border_b_1()
615 .border_color(cx.theme().colors().border_variant)
616 })
617 .child(
618 v_flex()
619 .max_w_1_2()
620 .flex_shrink()
621 .child(Label::new(SharedString::new_static(sub_page_link.title))),
622 )
623 .child(
624 Button::new(("sub-page".into(), sub_page_link.title), "Configure")
625 .size(ButtonSize::Medium)
626 .icon(IconName::ChevronRight)
627 .icon_position(IconPosition::End)
628 .icon_color(Color::Muted)
629 .icon_size(IconSize::Small)
630 .style(ButtonStyle::Outlined),
631 )
632 .on_click({
633 let sub_page_link = sub_page_link.clone();
634 cx.listener(move |this, _, _, cx| {
635 this.push_sub_page(sub_page_link.clone(), section_header, cx)
636 })
637 })
638 .into_any_element(),
639 }
640 }
641}
642
643struct SettingItem {
644 title: &'static str,
645 description: &'static str,
646 field: Box<dyn AnySettingField>,
647 metadata: Option<Box<SettingsFieldMetadata>>,
648}
649
650impl PartialEq for SettingItem {
651 fn eq(&self, other: &Self) -> bool {
652 self.title == other.title
653 && self.description == other.description
654 && (match (&self.metadata, &other.metadata) {
655 (None, None) => true,
656 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
657 _ => false,
658 })
659 }
660}
661
662#[derive(Clone)]
663struct SubPageLink {
664 title: &'static str,
665 render: Arc<
666 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
667 + 'static
668 + Send
669 + Sync,
670 >,
671}
672
673impl PartialEq for SubPageLink {
674 fn eq(&self, other: &Self) -> bool {
675 self.title == other.title
676 }
677}
678
679#[allow(unused)]
680#[derive(Clone, PartialEq)]
681enum SettingsUiFile {
682 User, // Uses all settings.
683 Local((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
684 Server(&'static str), // Uses a special name, and the user settings
685}
686
687impl SettingsUiFile {
688 fn pages(&self) -> Vec<SettingsPage> {
689 match self {
690 SettingsUiFile::User => page_data::user_settings_data(),
691 SettingsUiFile::Local(_) => page_data::project_settings_data(),
692 SettingsUiFile::Server(_) => page_data::user_settings_data(),
693 }
694 }
695
696 fn name(&self) -> SharedString {
697 match self {
698 SettingsUiFile::User => SharedString::new_static("User"),
699 // TODO is PathStyle::local() ever not appropriate?
700 SettingsUiFile::Local((_, path)) => {
701 format!("Local ({})", path.display(PathStyle::local())).into()
702 }
703 SettingsUiFile::Server(file) => format!("Server ({})", file).into(),
704 }
705 }
706
707 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
708 Some(match file {
709 settings::SettingsFile::User => SettingsUiFile::User,
710 settings::SettingsFile::Local(location) => SettingsUiFile::Local(location),
711 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
712 settings::SettingsFile::Default => return None,
713 })
714 }
715
716 fn to_settings(&self) -> settings::SettingsFile {
717 match self {
718 SettingsUiFile::User => settings::SettingsFile::User,
719 SettingsUiFile::Local(location) => settings::SettingsFile::Local(location.clone()),
720 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
721 }
722 }
723}
724
725impl SettingsWindow {
726 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
727 let font_family_cache = theme::FontFamilyCache::global(cx);
728
729 cx.spawn(async move |this, cx| {
730 font_family_cache.prefetch(cx).await;
731 this.update(cx, |_, cx| {
732 cx.notify();
733 })
734 })
735 .detach();
736
737 let current_file = SettingsUiFile::User;
738 let search_bar = cx.new(|cx| {
739 let mut editor = Editor::single_line(window, cx);
740 editor.set_placeholder_text("Search settings…", window, cx);
741 editor
742 });
743
744 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
745 let EditorEvent::Edited { transaction_id: _ } = event else {
746 return;
747 };
748
749 this.update_matches(cx);
750 })
751 .detach();
752
753 cx.observe_global_in::<SettingsStore>(window, move |this, _, cx| {
754 this.fetch_files(cx);
755 cx.notify();
756 })
757 .detach();
758
759 let mut this = Self {
760 files: vec![],
761 current_file: current_file,
762 pages: vec![],
763 navbar_entries: vec![],
764 navbar_entry: 0,
765 list_handle: UniformListScrollHandle::default(),
766 search_bar,
767 search_task: None,
768 search_matches: vec![],
769 scroll_handle: ScrollHandle::new(),
770 navbar_focus_handle: cx
771 .focus_handle()
772 .tab_index(NAVBAR_CONTAINER_TAB_INDEX)
773 .tab_stop(false),
774 content_focus_handle: cx
775 .focus_handle()
776 .tab_index(CONTENT_CONTAINER_TAB_INDEX)
777 .tab_stop(false),
778 files_focus_handle: cx.focus_handle().tab_stop(false),
779 };
780
781 this.fetch_files(cx);
782 this.build_ui(cx);
783
784 this.search_bar.update(cx, |editor, cx| {
785 editor.focus_handle(cx).focus(window);
786 });
787
788 this
789 }
790
791 fn toggle_navbar_entry(&mut self, ix: usize) {
792 // We can only toggle root entries
793 if !self.navbar_entries[ix].is_root {
794 return;
795 }
796
797 let toggle_page_index = self.page_index_from_navbar_index(ix);
798 let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
799
800 let expanded = &mut self.navbar_entries[ix].expanded;
801 *expanded = !*expanded;
802 // if currently selected page is a child of the parent page we are folding,
803 // set the current page to the parent page
804 if !*expanded && selected_page_index == toggle_page_index {
805 self.navbar_entry = ix;
806 }
807 }
808
809 fn build_navbar(&mut self) {
810 let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
811 for (page_index, page) in self.pages.iter().enumerate() {
812 navbar_entries.push(NavBarEntry {
813 title: page.title,
814 is_root: true,
815 expanded: false,
816 page_index,
817 item_index: None,
818 });
819
820 for (item_index, item) in page.items.iter().enumerate() {
821 let SettingsPageItem::SectionHeader(title) = item else {
822 continue;
823 };
824 navbar_entries.push(NavBarEntry {
825 title,
826 is_root: false,
827 expanded: false,
828 page_index,
829 item_index: Some(item_index),
830 });
831 }
832 }
833 self.navbar_entries = navbar_entries;
834 }
835
836 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
837 let mut index = 0;
838 let entries = &self.navbar_entries;
839 let search_matches = &self.search_matches;
840 std::iter::from_fn(move || {
841 while index < entries.len() {
842 let entry = &entries[index];
843 let included_in_search = if let Some(item_index) = entry.item_index {
844 search_matches[entry.page_index][item_index]
845 } else {
846 search_matches[entry.page_index].iter().any(|b| *b)
847 || search_matches[entry.page_index].is_empty()
848 };
849 if included_in_search {
850 break;
851 }
852 index += 1;
853 }
854 if index >= self.navbar_entries.len() {
855 return None;
856 }
857 let entry = &entries[index];
858 let entry_index = index;
859
860 index += 1;
861 if entry.is_root && !entry.expanded {
862 while index < entries.len() {
863 if entries[index].is_root {
864 break;
865 }
866 index += 1;
867 }
868 }
869
870 return Some((entry_index, entry));
871 })
872 }
873
874 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
875 self.search_task.take();
876 let query = self.search_bar.read(cx).text(cx);
877 if query.is_empty() {
878 for page in &mut self.search_matches {
879 page.fill(true);
880 }
881 cx.notify();
882 return;
883 }
884
885 struct ItemKey {
886 page_index: usize,
887 header_index: usize,
888 item_index: usize,
889 }
890 let mut key_lut: Vec<ItemKey> = vec![];
891 let mut candidates = Vec::default();
892
893 for (page_index, page) in self.pages.iter().enumerate() {
894 let mut header_index = 0;
895 for (item_index, item) in page.items.iter().enumerate() {
896 let key_index = key_lut.len();
897 match item {
898 SettingsPageItem::SettingItem(item) => {
899 candidates.push(StringMatchCandidate::new(key_index, item.title));
900 candidates.push(StringMatchCandidate::new(key_index, item.description));
901 }
902 SettingsPageItem::SectionHeader(header) => {
903 candidates.push(StringMatchCandidate::new(key_index, header));
904 header_index = item_index;
905 }
906 SettingsPageItem::SubPageLink(sub_page_link) => {
907 candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
908 }
909 }
910 key_lut.push(ItemKey {
911 page_index,
912 header_index,
913 item_index,
914 });
915 }
916 }
917 let atomic_bool = AtomicBool::new(false);
918
919 self.search_task = Some(cx.spawn(async move |this, cx| {
920 let string_matches = fuzzy::match_strings(
921 candidates.as_slice(),
922 &query,
923 false,
924 true,
925 candidates.len(),
926 &atomic_bool,
927 cx.background_executor().clone(),
928 );
929 let string_matches = string_matches.await;
930
931 this.update(cx, |this, cx| {
932 for page in &mut this.search_matches {
933 page.fill(false);
934 }
935
936 for string_match in string_matches {
937 let ItemKey {
938 page_index,
939 header_index,
940 item_index,
941 } = key_lut[string_match.candidate_id];
942 let page = &mut this.search_matches[page_index];
943 page[header_index] = true;
944 page[item_index] = true;
945 }
946 let first_navbar_entry_index = this
947 .visible_navbar_entries()
948 .next()
949 .map(|e| e.0)
950 .unwrap_or(0);
951 this.navbar_entry = first_navbar_entry_index;
952 cx.notify();
953 })
954 .ok();
955 }));
956 }
957
958 fn build_search_matches(&mut self) {
959 self.search_matches = self
960 .pages
961 .iter()
962 .map(|page| vec![true; page.items.len()])
963 .collect::<Vec<_>>();
964 }
965
966 fn build_ui(&mut self, cx: &mut Context<SettingsWindow>) {
967 self.pages = self.current_file.pages();
968 self.build_search_matches();
969 self.build_navbar();
970
971 if !self.search_bar.read(cx).is_empty(cx) {
972 self.update_matches(cx);
973 }
974
975 cx.notify();
976 }
977
978 fn fetch_files(&mut self, cx: &mut Context<SettingsWindow>) {
979 let prev_files = self.files.clone();
980 let settings_store = cx.global::<SettingsStore>();
981 let mut ui_files = vec![];
982 let all_files = settings_store.get_all_files();
983 for file in all_files {
984 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
985 continue;
986 };
987 let focus_handle = prev_files
988 .iter()
989 .find_map(|(prev_file, handle)| {
990 (prev_file == &settings_ui_file).then(|| handle.clone())
991 })
992 .unwrap_or_else(|| cx.focus_handle());
993 ui_files.push((settings_ui_file, focus_handle));
994 }
995 ui_files.reverse();
996 self.files = ui_files;
997 let current_file_still_exists = self
998 .files
999 .iter()
1000 .any(|(file, _)| file == &self.current_file);
1001 if !current_file_still_exists {
1002 self.change_file(0, cx);
1003 }
1004 }
1005
1006 fn change_file(&mut self, ix: usize, cx: &mut Context<SettingsWindow>) {
1007 if ix >= self.files.len() {
1008 self.current_file = SettingsUiFile::User;
1009 return;
1010 }
1011 if self.files[ix].0 == self.current_file {
1012 return;
1013 }
1014 self.current_file = self.files[ix].0.clone();
1015 self.navbar_entry = 0;
1016 self.build_ui(cx);
1017 }
1018
1019 fn render_files(&self, _window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
1020 h_flex().gap_1().children(self.files.iter().enumerate().map(
1021 |(ix, (file, focus_handle))| {
1022 Button::new(ix, file.name())
1023 .toggle_state(file == &self.current_file)
1024 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1025 .track_focus(focus_handle)
1026 .on_click(
1027 cx.listener(move |this, evt: &gpui::ClickEvent, window, cx| {
1028 this.change_file(ix, cx);
1029 if evt.is_keyboard() {
1030 this.focus_first_nav_item(window, cx);
1031 }
1032 }),
1033 )
1034 },
1035 ))
1036 }
1037
1038 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1039 h_flex()
1040 .py_1()
1041 .px_1p5()
1042 .gap_1p5()
1043 .rounded_sm()
1044 .bg(cx.theme().colors().editor_background)
1045 .border_1()
1046 .border_color(cx.theme().colors().border)
1047 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1048 .child(self.search_bar.clone())
1049 }
1050
1051 fn render_nav(
1052 &self,
1053 window: &mut Window,
1054 cx: &mut Context<SettingsWindow>,
1055 ) -> impl IntoElement {
1056 let visible_entries: Vec<_> = self.visible_navbar_entries().collect();
1057 let visible_count = visible_entries.len();
1058
1059 let nav_background = cx.theme().colors().panel_background;
1060
1061 v_flex()
1062 .w_64()
1063 .p_2p5()
1064 .pt_10()
1065 .gap_3()
1066 .flex_none()
1067 .border_r_1()
1068 .border_color(cx.theme().colors().border)
1069 .bg(nav_background)
1070 .child(self.render_search(window, cx))
1071 .child(
1072 v_flex()
1073 .flex_grow()
1074 .track_focus(&self.navbar_focus_handle)
1075 .tab_group()
1076 .tab_index(NAVBAR_GROUP_TAB_INDEX)
1077 .child(
1078 uniform_list(
1079 "settings-ui-nav-bar",
1080 visible_count,
1081 cx.processor(move |this, range: Range<usize>, _, cx| {
1082 let entries: Vec<_> = this.visible_navbar_entries().collect();
1083 range
1084 .filter_map(|ix| entries.get(ix).copied())
1085 .map(|(ix, entry)| {
1086 TreeViewItem::new(
1087 ("settings-ui-navbar-entry", ix),
1088 entry.title,
1089 )
1090 .tab_index(0)
1091 .root_item(entry.is_root)
1092 .toggle_state(this.is_navbar_entry_selected(ix))
1093 .when(entry.is_root, |item| {
1094 item.expanded(entry.expanded).on_toggle(cx.listener(
1095 move |this, _, _, cx| {
1096 this.toggle_navbar_entry(ix);
1097 cx.notify();
1098 },
1099 ))
1100 })
1101 .on_click(cx.listener(
1102 move |this, evt: &gpui::ClickEvent, window, cx| {
1103 this.navbar_entry = ix;
1104 if evt.is_keyboard() {
1105 // todo(settings_ui): Focus the actual item and scroll to it
1106 this.focus_first_content_item(window, cx);
1107 }
1108 cx.notify();
1109 },
1110 ))
1111 .into_any_element()
1112 })
1113 .collect()
1114 }),
1115 )
1116 .track_scroll(self.list_handle.clone())
1117 .flex_grow(),
1118 )
1119 .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1120 )
1121 .child(
1122 h_flex().w_full().justify_center().bg(nav_background).child(
1123 Button::new(
1124 "nav-key-hint",
1125 if self.navbar_focus_handle.contains_focused(window, cx) {
1126 "Focus Content"
1127 } else {
1128 "Focus Navbar"
1129 },
1130 )
1131 .key_binding(ui::KeyBinding::for_action_in(
1132 &ToggleFocusNav,
1133 &self.navbar_focus_handle,
1134 window,
1135 cx,
1136 ))
1137 .key_binding_position(KeybindingPosition::Start),
1138 ),
1139 )
1140 }
1141
1142 fn focus_first_nav_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1143 self.navbar_focus_handle.focus(window);
1144 window.focus_next();
1145 cx.notify();
1146 }
1147
1148 fn focus_first_content_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1149 self.content_focus_handle.focus(window);
1150 window.focus_next();
1151 cx.notify();
1152 }
1153
1154 fn page_items(&self) -> impl Iterator<Item = &SettingsPageItem> {
1155 let page_idx = self.current_page_index();
1156
1157 self.current_page()
1158 .items
1159 .iter()
1160 .enumerate()
1161 .filter_map(move |(item_index, item)| {
1162 self.search_matches[page_idx][item_index].then_some(item)
1163 })
1164 }
1165
1166 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1167 let mut items = vec![];
1168 items.push(self.current_page().title);
1169 items.extend(
1170 sub_page_stack()
1171 .iter()
1172 .flat_map(|page| [page.section_header, page.link.title]),
1173 );
1174
1175 let last = items.pop().unwrap();
1176 h_flex()
1177 .gap_1()
1178 .children(
1179 items
1180 .into_iter()
1181 .flat_map(|item| [item, "/"])
1182 .map(|item| Label::new(item).color(Color::Muted)),
1183 )
1184 .child(Label::new(last))
1185 }
1186
1187 fn render_page_items<'a, Items: Iterator<Item = &'a SettingsPageItem>>(
1188 &self,
1189 items: Items,
1190 window: &mut Window,
1191 cx: &mut Context<SettingsWindow>,
1192 ) -> impl IntoElement {
1193 let mut page_content = v_flex()
1194 .id("settings-ui-page")
1195 .size_full()
1196 .gap_4()
1197 .overflow_y_scroll()
1198 .track_scroll(&self.scroll_handle);
1199
1200 let items: Vec<_> = items.collect();
1201 let items_len = items.len();
1202 let mut section_header = None;
1203
1204 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1205 let has_no_results = items_len == 0 && has_active_search;
1206
1207 if has_no_results {
1208 let search_query = self.search_bar.read(cx).text(cx);
1209 page_content = page_content.child(
1210 v_flex()
1211 .size_full()
1212 .items_center()
1213 .justify_center()
1214 .gap_1()
1215 .child(div().child("No Results"))
1216 .child(
1217 div()
1218 .text_sm()
1219 .text_color(cx.theme().colors().text_muted)
1220 .child(format!("No settings match \"{}\"", search_query)),
1221 ),
1222 )
1223 } else {
1224 let last_non_header_index = items
1225 .iter()
1226 .enumerate()
1227 .rev()
1228 .find(|(_, item)| !matches!(item, SettingsPageItem::SectionHeader(_)))
1229 .map(|(index, _)| index);
1230
1231 page_content =
1232 page_content.children(items.clone().into_iter().enumerate().map(|(index, item)| {
1233 let no_bottom_border = items
1234 .get(index + 1)
1235 .map(|next_item| matches!(next_item, SettingsPageItem::SectionHeader(_)))
1236 .unwrap_or(false);
1237 let is_last = Some(index) == last_non_header_index;
1238
1239 if let SettingsPageItem::SectionHeader(header) = item {
1240 section_header = Some(*header);
1241 }
1242 item.render(
1243 self.current_file.clone(),
1244 section_header.expect("All items rendered after a section header"),
1245 no_bottom_border || is_last,
1246 window,
1247 cx,
1248 )
1249 }))
1250 }
1251 page_content
1252 }
1253
1254 fn render_page(
1255 &mut self,
1256 window: &mut Window,
1257 cx: &mut Context<SettingsWindow>,
1258 ) -> impl IntoElement {
1259 let page_header;
1260 let page_content;
1261
1262 if sub_page_stack().len() == 0 {
1263 page_header = self.render_files(window, cx);
1264 page_content = self
1265 .render_page_items(self.page_items(), window, cx)
1266 .into_any_element();
1267 } else {
1268 page_header = h_flex()
1269 .ml_neg_1p5()
1270 .gap_1()
1271 .child(
1272 IconButton::new("back-btn", IconName::ArrowLeft)
1273 .icon_size(IconSize::Small)
1274 .shape(IconButtonShape::Square)
1275 .on_click(cx.listener(|this, _, _, cx| {
1276 this.pop_sub_page(cx);
1277 })),
1278 )
1279 .child(self.render_sub_page_breadcrumbs());
1280
1281 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1282 page_content = (active_page_render_fn)(self, window, cx);
1283 }
1284
1285 return v_flex()
1286 .w_full()
1287 .pt_4()
1288 .pb_6()
1289 .px_6()
1290 .gap_4()
1291 .track_focus(&self.content_focus_handle)
1292 .bg(cx.theme().colors().editor_background)
1293 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1294 .child(page_header)
1295 .child(
1296 div()
1297 .size_full()
1298 .track_focus(&self.content_focus_handle)
1299 .tab_group()
1300 .tab_index(CONTENT_GROUP_TAB_INDEX)
1301 .child(page_content),
1302 );
1303 }
1304
1305 fn current_page_index(&self) -> usize {
1306 self.page_index_from_navbar_index(self.navbar_entry)
1307 }
1308
1309 fn current_page(&self) -> &SettingsPage {
1310 &self.pages[self.current_page_index()]
1311 }
1312
1313 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1314 if self.navbar_entries.is_empty() {
1315 return 0;
1316 }
1317
1318 self.navbar_entries[index].page_index
1319 }
1320
1321 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1322 ix == self.navbar_entry
1323 }
1324
1325 fn push_sub_page(
1326 &mut self,
1327 sub_page_link: SubPageLink,
1328 section_header: &'static str,
1329 cx: &mut Context<SettingsWindow>,
1330 ) {
1331 sub_page_stack_mut().push(SubPage {
1332 link: sub_page_link,
1333 section_header,
1334 });
1335 cx.notify();
1336 }
1337
1338 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1339 sub_page_stack_mut().pop();
1340 cx.notify();
1341 }
1342
1343 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1344 if let Some((_, handle)) = self.files.get(index) {
1345 handle.focus(window);
1346 }
1347 }
1348
1349 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1350 if self.files_focus_handle.contains_focused(window, cx)
1351 && let Some(index) = self
1352 .files
1353 .iter()
1354 .position(|(_, handle)| handle.is_focused(window))
1355 {
1356 return index;
1357 }
1358 if let Some(current_file_index) = self
1359 .files
1360 .iter()
1361 .position(|(file, _)| file == &self.current_file)
1362 {
1363 return current_file_index;
1364 }
1365 0
1366 }
1367}
1368
1369impl Render for SettingsWindow {
1370 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1371 let ui_font = theme::setup_ui_font(window, cx);
1372
1373 div()
1374 .id("settings-window")
1375 .key_context("SettingsWindow")
1376 .flex()
1377 .flex_row()
1378 .size_full()
1379 .font(ui_font)
1380 .bg(cx.theme().colors().background)
1381 .text_color(cx.theme().colors().text)
1382 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
1383 this.search_bar.focus_handle(cx).focus(window);
1384 }))
1385 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
1386 if this.navbar_focus_handle.contains_focused(window, cx) {
1387 this.focus_first_content_item(window, cx);
1388 } else {
1389 this.focus_first_nav_item(window, cx);
1390 }
1391 }))
1392 .on_action(
1393 cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
1394 this.focus_file_at_index(*file_index as usize, window);
1395 }),
1396 )
1397 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
1398 let next_index = usize::min(
1399 this.focused_file_index(window, cx) + 1,
1400 this.files.len().saturating_sub(1),
1401 );
1402 this.focus_file_at_index(next_index, window);
1403 }))
1404 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
1405 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
1406 this.focus_file_at_index(prev_index, window);
1407 }))
1408 .on_action(|_: &menu::SelectNext, window, _| {
1409 window.focus_next();
1410 })
1411 .on_action(|_: &menu::SelectPrevious, window, _| {
1412 window.focus_prev();
1413 })
1414 .child(self.render_nav(window, cx))
1415 .child(self.render_page(window, cx))
1416 }
1417}
1418
1419fn update_settings_file(
1420 file: SettingsUiFile,
1421 cx: &mut App,
1422 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
1423) -> Result<()> {
1424 match file {
1425 SettingsUiFile::Local((worktree_id, rel_path)) => {
1426 fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
1427 workspace::AppState::global(cx)
1428 .upgrade()
1429 .map(|app_state| {
1430 app_state
1431 .workspace_store
1432 .read(cx)
1433 .workspaces()
1434 .iter()
1435 .filter_map(|workspace| {
1436 Some(workspace.read(cx).ok()?.project().clone())
1437 })
1438 })
1439 .into_iter()
1440 .flatten()
1441 }
1442 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
1443 let project = all_projects(cx).find(|project| {
1444 project.read_with(cx, |project, cx| {
1445 project.contains_local_settings_file(worktree_id, &rel_path, cx)
1446 })
1447 });
1448 let Some(project) = project else {
1449 anyhow::bail!(
1450 "Could not find worktree containing settings file: {}",
1451 &rel_path.display(PathStyle::local())
1452 );
1453 };
1454 project.update(cx, |project, cx| {
1455 project.update_local_settings_file(worktree_id, rel_path, cx, update);
1456 });
1457 return Ok(());
1458 }
1459 SettingsUiFile::User => {
1460 // todo(settings_ui) error?
1461 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
1462 Ok(())
1463 }
1464 SettingsUiFile::Server(_) => unimplemented!(),
1465 }
1466}
1467
1468fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
1469 field: SettingField<T>,
1470 file: SettingsUiFile,
1471 metadata: Option<&SettingsFieldMetadata>,
1472 cx: &mut App,
1473) -> AnyElement {
1474 let (_, initial_text) = SettingsStore::global(cx).get_value_from_file(
1475 file.to_settings(),
1476 field.pick,
1477 field.type_name(),
1478 );
1479 let initial_text = Some(initial_text.clone()).filter(|s| !s.as_ref().is_empty());
1480
1481 SettingsEditor::new()
1482 .tab_index(0)
1483 .when_some(initial_text, |editor, text| {
1484 editor.with_initial_text(text.into())
1485 })
1486 .when_some(
1487 metadata.and_then(|metadata| metadata.placeholder),
1488 |editor, placeholder| editor.with_placeholder(placeholder),
1489 )
1490 .on_confirm({
1491 move |new_text, cx| {
1492 update_settings_file(file.clone(), cx, move |settings, _cx| {
1493 *(field.pick_mut)(settings) = new_text.map(Into::into);
1494 })
1495 .log_err(); // todo(settings_ui) don't log err
1496 }
1497 })
1498 .into_any_element()
1499}
1500
1501fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
1502 field: SettingField<B>,
1503 file: SettingsUiFile,
1504 cx: &mut App,
1505) -> AnyElement {
1506 let (_, &value) = SettingsStore::global(cx).get_value_from_file(
1507 file.to_settings(),
1508 field.pick,
1509 field.type_name(),
1510 );
1511
1512 let toggle_state = if value.into() {
1513 ToggleState::Selected
1514 } else {
1515 ToggleState::Unselected
1516 };
1517
1518 Switch::new("toggle_button", toggle_state)
1519 .color(ui::SwitchColor::Accent)
1520 .on_click({
1521 move |state, _window, cx| {
1522 let state = *state == ui::ToggleState::Selected;
1523 update_settings_file(file.clone(), cx, move |settings, _cx| {
1524 *(field.pick_mut)(settings) = Some(state.into());
1525 })
1526 .log_err(); // todo(settings_ui) don't log err
1527 }
1528 })
1529 .tab_index(0_isize)
1530 .color(SwitchColor::Accent)
1531 .into_any_element()
1532}
1533
1534fn render_font_picker(
1535 field: SettingField<settings::FontFamilyName>,
1536 file: SettingsUiFile,
1537 window: &mut Window,
1538 cx: &mut App,
1539) -> AnyElement {
1540 let current_value = SettingsStore::global(cx)
1541 .get_value_from_file(file.to_settings(), field.pick, field.type_name())
1542 .1
1543 .clone();
1544
1545 let font_picker = cx.new(|cx| {
1546 ui_input::font_picker(
1547 current_value.clone().into(),
1548 move |font_name, cx| {
1549 update_settings_file(file.clone(), cx, move |settings, _cx| {
1550 *(field.pick_mut)(settings) = Some(font_name.into());
1551 })
1552 .log_err(); // todo(settings_ui) don't log err
1553 },
1554 window,
1555 cx,
1556 )
1557 });
1558
1559 div()
1560 .child(
1561 PopoverMenu::new("font-picker")
1562 .menu(move |_window, _cx| Some(font_picker.clone()))
1563 .trigger(
1564 ButtonLike::new("font-family-button")
1565 .style(ButtonStyle::Outlined)
1566 .size(ButtonSize::Medium)
1567 .full_width()
1568 .tab_index(0_isize)
1569 .child(
1570 h_flex()
1571 .w_full()
1572 .justify_between()
1573 .child(Label::new(current_value))
1574 .child(
1575 Icon::new(IconName::ChevronUpDown)
1576 .color(Color::Muted)
1577 .size(IconSize::XSmall),
1578 ),
1579 ),
1580 )
1581 .full_width(true)
1582 .anchor(gpui::Corner::TopLeft)
1583 .offset(gpui::Point {
1584 x: px(0.0),
1585 y: px(4.0),
1586 })
1587 .with_handle(ui::PopoverMenuHandle::default()),
1588 )
1589 .into_any_element()
1590}
1591
1592fn render_numeric_stepper<T: NumericStepperType + Send + Sync>(
1593 field: SettingField<T>,
1594 file: SettingsUiFile,
1595 window: &mut Window,
1596 cx: &mut App,
1597) -> AnyElement {
1598 let (_, &value) = SettingsStore::global(cx).get_value_from_file(
1599 file.to_settings(),
1600 field.pick,
1601 field.type_name(),
1602 );
1603
1604 NumericStepper::new("numeric_stepper", value, window, cx)
1605 .on_change({
1606 move |value, _window, cx| {
1607 let value = *value;
1608 update_settings_file(file.clone(), cx, move |settings, _cx| {
1609 *(field.pick_mut)(settings) = Some(value);
1610 })
1611 .log_err(); // todo(settings_ui) don't log err
1612 }
1613 })
1614 .tab_index(0)
1615 .style(NumericStepperStyle::Outlined)
1616 .into_any_element()
1617}
1618
1619fn render_dropdown<T>(
1620 field: SettingField<T>,
1621 file: SettingsUiFile,
1622 window: &mut Window,
1623 cx: &mut App,
1624) -> AnyElement
1625where
1626 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
1627{
1628 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
1629 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
1630
1631 let (_, ¤t_value) = SettingsStore::global(cx).get_value_from_file(
1632 file.to_settings(),
1633 field.pick,
1634 field.type_name(),
1635 );
1636
1637 let current_value_label =
1638 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
1639
1640 DropdownMenu::new(
1641 "dropdown",
1642 current_value_label,
1643 ContextMenu::build(window, cx, move |mut menu, _, _| {
1644 for (&value, &label) in std::iter::zip(variants(), labels()) {
1645 let file = file.clone();
1646 menu = menu.toggleable_entry(
1647 label,
1648 value == current_value,
1649 IconPosition::Start,
1650 None,
1651 move |_, cx| {
1652 if value == current_value {
1653 return;
1654 }
1655 update_settings_file(file.clone(), cx, move |settings, _cx| {
1656 *(field.pick_mut)(settings) = Some(value);
1657 })
1658 .log_err(); // todo(settings_ui) don't log err
1659 },
1660 );
1661 }
1662 menu
1663 }),
1664 )
1665 .trigger_size(ButtonSize::Medium)
1666 .style(DropdownStyle::Outlined)
1667 .offset(gpui::Point {
1668 x: px(0.0),
1669 y: px(2.0),
1670 })
1671 .tab_index(0)
1672 .into_any_element()
1673}
1674
1675#[cfg(test)]
1676mod test {
1677
1678 use super::*;
1679
1680 impl SettingsWindow {
1681 fn navbar_entry(&self) -> usize {
1682 self.navbar_entry
1683 }
1684
1685 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
1686 let mut this = Self::new(window, cx);
1687 this.navbar_entries.clear();
1688 this.pages.clear();
1689 this
1690 }
1691
1692 fn build(mut self) -> Self {
1693 self.build_search_matches();
1694 self.build_navbar();
1695 self
1696 }
1697
1698 fn add_page(
1699 mut self,
1700 title: &'static str,
1701 build_page: impl Fn(SettingsPage) -> SettingsPage,
1702 ) -> Self {
1703 let page = SettingsPage {
1704 title,
1705 items: Vec::default(),
1706 };
1707
1708 self.pages.push(build_page(page));
1709 self
1710 }
1711
1712 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
1713 self.search_task.take();
1714 self.search_bar.update(cx, |editor, cx| {
1715 editor.set_text(search_query, window, cx);
1716 });
1717 self.update_matches(cx);
1718 }
1719
1720 fn assert_search_results(&self, other: &Self) {
1721 // page index could be different because of filtered out pages
1722 #[derive(Debug, PartialEq)]
1723 struct EntryMinimal {
1724 is_root: bool,
1725 title: &'static str,
1726 }
1727 pretty_assertions::assert_eq!(
1728 other
1729 .visible_navbar_entries()
1730 .map(|(_, entry)| EntryMinimal {
1731 is_root: entry.is_root,
1732 title: entry.title,
1733 })
1734 .collect::<Vec<_>>(),
1735 self.visible_navbar_entries()
1736 .map(|(_, entry)| EntryMinimal {
1737 is_root: entry.is_root,
1738 title: entry.title,
1739 })
1740 .collect::<Vec<_>>(),
1741 );
1742 assert_eq!(
1743 self.current_page().items.iter().collect::<Vec<_>>(),
1744 other.page_items().collect::<Vec<_>>()
1745 );
1746 }
1747 }
1748
1749 impl SettingsPage {
1750 fn item(mut self, item: SettingsPageItem) -> Self {
1751 self.items.push(item);
1752 self
1753 }
1754 }
1755
1756 impl SettingsPageItem {
1757 fn basic_item(title: &'static str, description: &'static str) -> Self {
1758 SettingsPageItem::SettingItem(SettingItem {
1759 title,
1760 description,
1761 field: Box::new(SettingField {
1762 pick: |settings_content| &settings_content.auto_update,
1763 pick_mut: |settings_content| &mut settings_content.auto_update,
1764 }),
1765 metadata: None,
1766 })
1767 }
1768 }
1769
1770 fn register_settings(cx: &mut App) {
1771 settings::init(cx);
1772 theme::init(theme::LoadThemes::JustBase, cx);
1773 workspace::init_settings(cx);
1774 project::Project::init_settings(cx);
1775 language::init(cx);
1776 editor::init(cx);
1777 menu::init();
1778 }
1779
1780 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
1781 let mut pages: Vec<SettingsPage> = Vec::new();
1782 let mut expanded_pages = Vec::new();
1783 let mut selected_idx = None;
1784 let mut index = 0;
1785 let mut in_expanded_section = false;
1786
1787 for mut line in input
1788 .lines()
1789 .map(|line| line.trim())
1790 .filter(|line| !line.is_empty())
1791 {
1792 if let Some(pre) = line.strip_suffix('*') {
1793 assert!(selected_idx.is_none(), "Only one selected entry allowed");
1794 selected_idx = Some(index);
1795 line = pre;
1796 }
1797 let (kind, title) = line.split_once(" ").unwrap();
1798 assert_eq!(kind.len(), 1);
1799 let kind = kind.chars().next().unwrap();
1800 if kind == 'v' {
1801 let page_idx = pages.len();
1802 expanded_pages.push(page_idx);
1803 pages.push(SettingsPage {
1804 title,
1805 items: vec![],
1806 });
1807 index += 1;
1808 in_expanded_section = true;
1809 } else if kind == '>' {
1810 pages.push(SettingsPage {
1811 title,
1812 items: vec![],
1813 });
1814 index += 1;
1815 in_expanded_section = false;
1816 } else if kind == '-' {
1817 pages
1818 .last_mut()
1819 .unwrap()
1820 .items
1821 .push(SettingsPageItem::SectionHeader(title));
1822 if selected_idx == Some(index) && !in_expanded_section {
1823 panic!("Items in unexpanded sections cannot be selected");
1824 }
1825 index += 1;
1826 } else {
1827 panic!(
1828 "Entries must start with one of 'v', '>', or '-'\n line: {}",
1829 line
1830 );
1831 }
1832 }
1833
1834 let mut settings_window = SettingsWindow {
1835 files: Vec::default(),
1836 current_file: crate::SettingsUiFile::User,
1837 pages,
1838 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
1839 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
1840 navbar_entries: Vec::default(),
1841 list_handle: UniformListScrollHandle::default(),
1842 search_matches: vec![],
1843 search_task: None,
1844 scroll_handle: ScrollHandle::new(),
1845 navbar_focus_handle: cx.focus_handle(),
1846 content_focus_handle: cx.focus_handle(),
1847 files_focus_handle: cx.focus_handle(),
1848 };
1849
1850 settings_window.build_search_matches();
1851 settings_window.build_navbar();
1852 for expanded_page_index in expanded_pages {
1853 for entry in &mut settings_window.navbar_entries {
1854 if entry.page_index == expanded_page_index && entry.is_root {
1855 entry.expanded = true;
1856 }
1857 }
1858 }
1859 settings_window
1860 }
1861
1862 #[track_caller]
1863 fn check_navbar_toggle(
1864 before: &'static str,
1865 toggle_page: &'static str,
1866 after: &'static str,
1867 window: &mut Window,
1868 cx: &mut App,
1869 ) {
1870 let mut settings_window = parse(before, window, cx);
1871 let toggle_page_idx = settings_window
1872 .pages
1873 .iter()
1874 .position(|page| page.title == toggle_page)
1875 .expect("page not found");
1876 let toggle_idx = settings_window
1877 .navbar_entries
1878 .iter()
1879 .position(|entry| entry.page_index == toggle_page_idx)
1880 .expect("page not found");
1881 settings_window.toggle_navbar_entry(toggle_idx);
1882
1883 let expected_settings_window = parse(after, window, cx);
1884
1885 pretty_assertions::assert_eq!(
1886 settings_window
1887 .visible_navbar_entries()
1888 .map(|(_, entry)| entry)
1889 .collect::<Vec<_>>(),
1890 expected_settings_window
1891 .visible_navbar_entries()
1892 .map(|(_, entry)| entry)
1893 .collect::<Vec<_>>(),
1894 );
1895 pretty_assertions::assert_eq!(
1896 settings_window.navbar_entries[settings_window.navbar_entry()],
1897 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
1898 );
1899 }
1900
1901 macro_rules! check_navbar_toggle {
1902 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
1903 #[gpui::test]
1904 fn $name(cx: &mut gpui::TestAppContext) {
1905 let window = cx.add_empty_window();
1906 window.update(|window, cx| {
1907 register_settings(cx);
1908 check_navbar_toggle($before, $toggle_page, $after, window, cx);
1909 });
1910 }
1911 };
1912 }
1913
1914 check_navbar_toggle!(
1915 navbar_basic_open,
1916 before: r"
1917 v General
1918 - General
1919 - Privacy*
1920 v Project
1921 - Project Settings
1922 ",
1923 toggle_page: "General",
1924 after: r"
1925 > General*
1926 v Project
1927 - Project Settings
1928 "
1929 );
1930
1931 check_navbar_toggle!(
1932 navbar_basic_close,
1933 before: r"
1934 > General*
1935 - General
1936 - Privacy
1937 v Project
1938 - Project Settings
1939 ",
1940 toggle_page: "General",
1941 after: r"
1942 v General*
1943 - General
1944 - Privacy
1945 v Project
1946 - Project Settings
1947 "
1948 );
1949
1950 check_navbar_toggle!(
1951 navbar_basic_second_root_entry_close,
1952 before: r"
1953 > General
1954 - General
1955 - Privacy
1956 v Project
1957 - Project Settings*
1958 ",
1959 toggle_page: "Project",
1960 after: r"
1961 > General
1962 > Project*
1963 "
1964 );
1965
1966 check_navbar_toggle!(
1967 navbar_toggle_subroot,
1968 before: r"
1969 v General Page
1970 - General
1971 - Privacy
1972 v Project
1973 - Worktree Settings Content*
1974 v AI
1975 - General
1976 > Appearance & Behavior
1977 ",
1978 toggle_page: "Project",
1979 after: r"
1980 v General Page
1981 - General
1982 - Privacy
1983 > Project*
1984 v AI
1985 - General
1986 > Appearance & Behavior
1987 "
1988 );
1989
1990 check_navbar_toggle!(
1991 navbar_toggle_close_propagates_selected_index,
1992 before: r"
1993 v General Page
1994 - General
1995 - Privacy
1996 v Project
1997 - Worktree Settings Content
1998 v AI
1999 - General*
2000 > Appearance & Behavior
2001 ",
2002 toggle_page: "General Page",
2003 after: r"
2004 > General Page
2005 v Project
2006 - Worktree Settings Content
2007 v AI
2008 - General*
2009 > Appearance & Behavior
2010 "
2011 );
2012
2013 check_navbar_toggle!(
2014 navbar_toggle_expand_propagates_selected_index,
2015 before: r"
2016 > General Page
2017 - General
2018 - Privacy
2019 v Project
2020 - Worktree Settings Content
2021 v AI
2022 - General*
2023 > Appearance & Behavior
2024 ",
2025 toggle_page: "General Page",
2026 after: r"
2027 v General Page
2028 - General
2029 - Privacy
2030 v Project
2031 - Worktree Settings Content
2032 v AI
2033 - General*
2034 > Appearance & Behavior
2035 "
2036 );
2037
2038 #[gpui::test]
2039 fn test_basic_search(cx: &mut gpui::TestAppContext) {
2040 let cx = cx.add_empty_window();
2041 let (actual, expected) = cx.update(|window, cx| {
2042 register_settings(cx);
2043
2044 let expected = cx.new(|cx| {
2045 SettingsWindow::new_builder(window, cx)
2046 .add_page("General", |page| {
2047 page.item(SettingsPageItem::SectionHeader("General settings"))
2048 .item(SettingsPageItem::basic_item("test title", "General test"))
2049 })
2050 .build()
2051 });
2052
2053 let actual = cx.new(|cx| {
2054 SettingsWindow::new_builder(window, cx)
2055 .add_page("General", |page| {
2056 page.item(SettingsPageItem::SectionHeader("General settings"))
2057 .item(SettingsPageItem::basic_item("test title", "General test"))
2058 })
2059 .add_page("Theme", |page| {
2060 page.item(SettingsPageItem::SectionHeader("Theme settings"))
2061 })
2062 .build()
2063 });
2064
2065 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2066
2067 (actual, expected)
2068 });
2069
2070 cx.cx.run_until_parked();
2071
2072 cx.update(|_window, cx| {
2073 let expected = expected.read(cx);
2074 let actual = actual.read(cx);
2075 expected.assert_search_results(&actual);
2076 })
2077 }
2078
2079 #[gpui::test]
2080 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2081 let cx = cx.add_empty_window();
2082 let (actual, expected) = cx.update(|window, cx| {
2083 register_settings(cx);
2084
2085 let actual = cx.new(|cx| {
2086 SettingsWindow::new_builder(window, cx)
2087 .add_page("General", |page| {
2088 page.item(SettingsPageItem::SectionHeader("General settings"))
2089 .item(SettingsPageItem::basic_item(
2090 "Confirm Quit",
2091 "Whether to confirm before quitting Zed",
2092 ))
2093 .item(SettingsPageItem::basic_item(
2094 "Auto Update",
2095 "Automatically update Zed",
2096 ))
2097 })
2098 .add_page("AI", |page| {
2099 page.item(SettingsPageItem::basic_item(
2100 "Disable AI",
2101 "Whether to disable all AI features in Zed",
2102 ))
2103 })
2104 .add_page("Appearance & Behavior", |page| {
2105 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2106 SettingsPageItem::basic_item(
2107 "Cursor Shape",
2108 "Cursor shape for the editor",
2109 ),
2110 )
2111 })
2112 .build()
2113 });
2114
2115 let expected = cx.new(|cx| {
2116 SettingsWindow::new_builder(window, cx)
2117 .add_page("Appearance & Behavior", |page| {
2118 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2119 SettingsPageItem::basic_item(
2120 "Cursor Shape",
2121 "Cursor shape for the editor",
2122 ),
2123 )
2124 })
2125 .build()
2126 });
2127
2128 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2129
2130 (actual, expected)
2131 });
2132
2133 cx.cx.run_until_parked();
2134
2135 cx.update(|_window, cx| {
2136 let expected = expected.read(cx);
2137 let actual = actual.read(cx);
2138 expected.assert_search_results(&actual);
2139 })
2140 }
2141}