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 heck::ToTitleCase as _;
15use project::WorktreeId;
16use schemars::JsonSchema;
17use serde::Deserialize;
18use settings::{
19 BottomDockLayout, CloseWindowWhenNoItems, CodeFade, CursorShape, OnLastWindowClosed,
20 RestoreOnStartupBehavior, SaturatingBool, SettingsContent, SettingsStore,
21};
22use std::{
23 any::{Any, TypeId, type_name},
24 cell::RefCell,
25 collections::HashMap,
26 num::{NonZero, NonZeroU32},
27 ops::Range,
28 rc::Rc,
29 sync::{Arc, LazyLock, RwLock, atomic::AtomicBool},
30};
31use ui::{
32 ButtonLike, ContextMenu, Divider, DropdownMenu, DropdownStyle, IconButtonShape,
33 KeybindingPosition, PopoverMenu, Switch, SwitchColor, TreeViewItem, WithScrollbar, prelude::*,
34};
35use ui_input::{NumericStepper, NumericStepperStyle, NumericStepperType};
36use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
37use zed_actions::OpenSettingsEditor;
38
39use crate::components::SettingsEditor;
40
41const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
42const NAVBAR_GROUP_TAB_INDEX: isize = 1;
43const CONTENT_CONTAINER_TAB_INDEX: isize = 2;
44const CONTENT_GROUP_TAB_INDEX: isize = 3;
45
46actions!(
47 settings_editor,
48 [
49 /// Toggles focus between the navbar and the main content.
50 ToggleFocusNav,
51 /// Focuses the next file in the file list.
52 FocusNextFile,
53 /// Focuses the previous file in the file list.
54 FocusPreviousFile
55 ]
56);
57
58#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
59#[action(namespace = settings_editor)]
60struct FocusFile(pub u32);
61
62#[derive(Clone, Copy)]
63struct SettingField<T: 'static> {
64 pick: fn(&SettingsContent) -> &Option<T>,
65 pick_mut: fn(&mut SettingsContent) -> &mut Option<T>,
66}
67
68/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
69/// to keep the setting around in the UI with valid pick and pick_mut implementations, but don't actually try to render it.
70/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
71struct UnimplementedSettingField;
72
73impl<T: 'static> SettingField<T> {
74 /// Helper for settings with types that are not yet implemented.
75 #[allow(unused)]
76 fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
77 SettingField {
78 pick: |_| &None,
79 pick_mut: |_| unreachable!(),
80 }
81 }
82}
83
84trait AnySettingField {
85 fn as_any(&self) -> &dyn Any;
86 fn type_name(&self) -> &'static str;
87 fn type_id(&self) -> TypeId;
88 // Returns the file this value was set in and true, or File::Default and false to indicate it was not found in any file (missing default)
89 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
90}
91
92impl<T> AnySettingField for SettingField<T> {
93 fn as_any(&self) -> &dyn Any {
94 self
95 }
96
97 fn type_name(&self) -> &'static str {
98 type_name::<T>()
99 }
100
101 fn type_id(&self) -> TypeId {
102 TypeId::of::<T>()
103 }
104
105 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
106 if AnySettingField::type_id(self) == TypeId::of::<UnimplementedSettingField>() {
107 return (file.to_settings(), true);
108 }
109
110 let (file, value) = cx
111 .global::<SettingsStore>()
112 .get_value_from_file(file.to_settings(), self.pick);
113 return (file, value.is_some());
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 (found_in_file, found) = setting_item.field.file_set_in(file.clone(), cx);
551 let file_set_in = SettingsUiFile::from_settings(found_in_file);
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(if cfg!(debug_assertions) && !found {
598 Button::new("no-default-field", "NO DEFAULT")
599 .size(ButtonSize::Medium)
600 .icon(IconName::XCircle)
601 .icon_position(IconPosition::Start)
602 .icon_color(Color::Error)
603 .icon_size(IconSize::Small)
604 .style(ButtonStyle::Outlined)
605 .into_any_element()
606 } else {
607 renderer.render(
608 setting_item.field.as_ref(),
609 file,
610 setting_item.metadata.as_deref(),
611 window,
612 cx,
613 )
614 })
615 .into_any_element()
616 }
617 SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
618 .id(sub_page_link.title)
619 .w_full()
620 .gap_2()
621 .flex_wrap()
622 .justify_between()
623 .when(!is_last, |this| {
624 this.pb_4()
625 .border_b_1()
626 .border_color(cx.theme().colors().border_variant)
627 })
628 .child(
629 v_flex()
630 .max_w_1_2()
631 .flex_shrink()
632 .child(Label::new(SharedString::new_static(sub_page_link.title))),
633 )
634 .child(
635 Button::new(("sub-page".into(), sub_page_link.title), "Configure")
636 .size(ButtonSize::Medium)
637 .icon(IconName::ChevronRight)
638 .icon_position(IconPosition::End)
639 .icon_color(Color::Muted)
640 .icon_size(IconSize::Small)
641 .style(ButtonStyle::Outlined),
642 )
643 .on_click({
644 let sub_page_link = sub_page_link.clone();
645 cx.listener(move |this, _, _, cx| {
646 this.push_sub_page(sub_page_link.clone(), section_header, cx)
647 })
648 })
649 .into_any_element(),
650 }
651 }
652}
653
654struct SettingItem {
655 title: &'static str,
656 description: &'static str,
657 field: Box<dyn AnySettingField>,
658 metadata: Option<Box<SettingsFieldMetadata>>,
659}
660
661impl PartialEq for SettingItem {
662 fn eq(&self, other: &Self) -> bool {
663 self.title == other.title
664 && self.description == other.description
665 && (match (&self.metadata, &other.metadata) {
666 (None, None) => true,
667 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
668 _ => false,
669 })
670 }
671}
672
673#[derive(Clone)]
674struct SubPageLink {
675 title: &'static str,
676 render: Arc<
677 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
678 + 'static
679 + Send
680 + Sync,
681 >,
682}
683
684impl PartialEq for SubPageLink {
685 fn eq(&self, other: &Self) -> bool {
686 self.title == other.title
687 }
688}
689
690#[allow(unused)]
691#[derive(Clone, PartialEq)]
692enum SettingsUiFile {
693 User, // Uses all settings.
694 Local((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
695 Server(&'static str), // Uses a special name, and the user settings
696}
697
698impl SettingsUiFile {
699 fn pages(&self) -> Vec<SettingsPage> {
700 match self {
701 SettingsUiFile::User => page_data::user_settings_data(),
702 SettingsUiFile::Local(_) => page_data::project_settings_data(),
703 SettingsUiFile::Server(_) => page_data::user_settings_data(),
704 }
705 }
706
707 fn name(&self) -> SharedString {
708 match self {
709 SettingsUiFile::User => SharedString::new_static("User"),
710 // TODO is PathStyle::local() ever not appropriate?
711 SettingsUiFile::Local((_, path)) => {
712 format!("Local ({})", path.display(PathStyle::local())).into()
713 }
714 SettingsUiFile::Server(file) => format!("Server ({})", file).into(),
715 }
716 }
717
718 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
719 Some(match file {
720 settings::SettingsFile::User => SettingsUiFile::User,
721 settings::SettingsFile::Local(location) => SettingsUiFile::Local(location),
722 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
723 settings::SettingsFile::Default => return None,
724 })
725 }
726
727 fn to_settings(&self) -> settings::SettingsFile {
728 match self {
729 SettingsUiFile::User => settings::SettingsFile::User,
730 SettingsUiFile::Local(location) => settings::SettingsFile::Local(location.clone()),
731 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
732 }
733 }
734}
735
736impl SettingsWindow {
737 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
738 let font_family_cache = theme::FontFamilyCache::global(cx);
739
740 cx.spawn(async move |this, cx| {
741 font_family_cache.prefetch(cx).await;
742 this.update(cx, |_, cx| {
743 cx.notify();
744 })
745 })
746 .detach();
747
748 let current_file = SettingsUiFile::User;
749 let search_bar = cx.new(|cx| {
750 let mut editor = Editor::single_line(window, cx);
751 editor.set_placeholder_text("Search settings…", window, cx);
752 editor
753 });
754
755 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
756 let EditorEvent::Edited { transaction_id: _ } = event else {
757 return;
758 };
759
760 this.update_matches(cx);
761 })
762 .detach();
763
764 cx.observe_global_in::<SettingsStore>(window, move |this, _, cx| {
765 this.fetch_files(cx);
766 cx.notify();
767 })
768 .detach();
769
770 let mut this = Self {
771 files: vec![],
772 current_file: current_file,
773 pages: vec![],
774 navbar_entries: vec![],
775 navbar_entry: 0,
776 list_handle: UniformListScrollHandle::default(),
777 search_bar,
778 search_task: None,
779 search_matches: vec![],
780 scroll_handle: ScrollHandle::new(),
781 navbar_focus_handle: cx
782 .focus_handle()
783 .tab_index(NAVBAR_CONTAINER_TAB_INDEX)
784 .tab_stop(false),
785 content_focus_handle: cx
786 .focus_handle()
787 .tab_index(CONTENT_CONTAINER_TAB_INDEX)
788 .tab_stop(false),
789 files_focus_handle: cx.focus_handle().tab_stop(false),
790 };
791
792 this.fetch_files(cx);
793 this.build_ui(cx);
794
795 this.search_bar.update(cx, |editor, cx| {
796 editor.focus_handle(cx).focus(window);
797 });
798
799 this
800 }
801
802 fn toggle_navbar_entry(&mut self, ix: usize) {
803 // We can only toggle root entries
804 if !self.navbar_entries[ix].is_root {
805 return;
806 }
807
808 let toggle_page_index = self.page_index_from_navbar_index(ix);
809 let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
810
811 let expanded = &mut self.navbar_entries[ix].expanded;
812 *expanded = !*expanded;
813 // if currently selected page is a child of the parent page we are folding,
814 // set the current page to the parent page
815 if !*expanded && selected_page_index == toggle_page_index {
816 self.navbar_entry = ix;
817 }
818 }
819
820 fn build_navbar(&mut self) {
821 let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
822 for (page_index, page) in self.pages.iter().enumerate() {
823 navbar_entries.push(NavBarEntry {
824 title: page.title,
825 is_root: true,
826 expanded: false,
827 page_index,
828 item_index: None,
829 });
830
831 for (item_index, item) in page.items.iter().enumerate() {
832 let SettingsPageItem::SectionHeader(title) = item else {
833 continue;
834 };
835 navbar_entries.push(NavBarEntry {
836 title,
837 is_root: false,
838 expanded: false,
839 page_index,
840 item_index: Some(item_index),
841 });
842 }
843 }
844 self.navbar_entries = navbar_entries;
845 }
846
847 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
848 let mut index = 0;
849 let entries = &self.navbar_entries;
850 let search_matches = &self.search_matches;
851 std::iter::from_fn(move || {
852 while index < entries.len() {
853 let entry = &entries[index];
854 let included_in_search = if let Some(item_index) = entry.item_index {
855 search_matches[entry.page_index][item_index]
856 } else {
857 search_matches[entry.page_index].iter().any(|b| *b)
858 || search_matches[entry.page_index].is_empty()
859 };
860 if included_in_search {
861 break;
862 }
863 index += 1;
864 }
865 if index >= self.navbar_entries.len() {
866 return None;
867 }
868 let entry = &entries[index];
869 let entry_index = index;
870
871 index += 1;
872 if entry.is_root && !entry.expanded {
873 while index < entries.len() {
874 if entries[index].is_root {
875 break;
876 }
877 index += 1;
878 }
879 }
880
881 return Some((entry_index, entry));
882 })
883 }
884
885 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
886 self.search_task.take();
887 let query = self.search_bar.read(cx).text(cx);
888 if query.is_empty() {
889 for page in &mut self.search_matches {
890 page.fill(true);
891 }
892 cx.notify();
893 return;
894 }
895
896 struct ItemKey {
897 page_index: usize,
898 header_index: usize,
899 item_index: usize,
900 }
901 let mut key_lut: Vec<ItemKey> = vec![];
902 let mut candidates = Vec::default();
903
904 for (page_index, page) in self.pages.iter().enumerate() {
905 let mut header_index = 0;
906 for (item_index, item) in page.items.iter().enumerate() {
907 let key_index = key_lut.len();
908 match item {
909 SettingsPageItem::SettingItem(item) => {
910 candidates.push(StringMatchCandidate::new(key_index, item.title));
911 candidates.push(StringMatchCandidate::new(key_index, item.description));
912 }
913 SettingsPageItem::SectionHeader(header) => {
914 candidates.push(StringMatchCandidate::new(key_index, header));
915 header_index = item_index;
916 }
917 SettingsPageItem::SubPageLink(sub_page_link) => {
918 candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
919 }
920 }
921 key_lut.push(ItemKey {
922 page_index,
923 header_index,
924 item_index,
925 });
926 }
927 }
928 let atomic_bool = AtomicBool::new(false);
929
930 self.search_task = Some(cx.spawn(async move |this, cx| {
931 let string_matches = fuzzy::match_strings(
932 candidates.as_slice(),
933 &query,
934 false,
935 true,
936 candidates.len(),
937 &atomic_bool,
938 cx.background_executor().clone(),
939 );
940 let string_matches = string_matches.await;
941
942 this.update(cx, |this, cx| {
943 for page in &mut this.search_matches {
944 page.fill(false);
945 }
946
947 for string_match in string_matches {
948 let ItemKey {
949 page_index,
950 header_index,
951 item_index,
952 } = key_lut[string_match.candidate_id];
953 let page = &mut this.search_matches[page_index];
954 page[header_index] = true;
955 page[item_index] = true;
956 }
957 let first_navbar_entry_index = this
958 .visible_navbar_entries()
959 .next()
960 .map(|e| e.0)
961 .unwrap_or(0);
962 this.navbar_entry = first_navbar_entry_index;
963 cx.notify();
964 })
965 .ok();
966 }));
967 }
968
969 fn build_search_matches(&mut self) {
970 self.search_matches = self
971 .pages
972 .iter()
973 .map(|page| vec![true; page.items.len()])
974 .collect::<Vec<_>>();
975 }
976
977 fn build_ui(&mut self, cx: &mut Context<SettingsWindow>) {
978 self.pages = self.current_file.pages();
979 self.build_search_matches();
980 self.build_navbar();
981
982 if !self.search_bar.read(cx).is_empty(cx) {
983 self.update_matches(cx);
984 }
985
986 cx.notify();
987 }
988
989 fn fetch_files(&mut self, cx: &mut Context<SettingsWindow>) {
990 let prev_files = self.files.clone();
991 let settings_store = cx.global::<SettingsStore>();
992 let mut ui_files = vec![];
993 let all_files = settings_store.get_all_files();
994 for file in all_files {
995 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
996 continue;
997 };
998 let focus_handle = prev_files
999 .iter()
1000 .find_map(|(prev_file, handle)| {
1001 (prev_file == &settings_ui_file).then(|| handle.clone())
1002 })
1003 .unwrap_or_else(|| cx.focus_handle());
1004 ui_files.push((settings_ui_file, focus_handle));
1005 }
1006 ui_files.reverse();
1007 self.files = ui_files;
1008 let current_file_still_exists = self
1009 .files
1010 .iter()
1011 .any(|(file, _)| file == &self.current_file);
1012 if !current_file_still_exists {
1013 self.change_file(0, cx);
1014 }
1015 }
1016
1017 fn change_file(&mut self, ix: usize, cx: &mut Context<SettingsWindow>) {
1018 if ix >= self.files.len() {
1019 self.current_file = SettingsUiFile::User;
1020 return;
1021 }
1022 if self.files[ix].0 == self.current_file {
1023 return;
1024 }
1025 self.current_file = self.files[ix].0.clone();
1026 self.navbar_entry = 0;
1027 self.build_ui(cx);
1028 }
1029
1030 fn render_files(&self, _window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
1031 h_flex().gap_1().children(self.files.iter().enumerate().map(
1032 |(ix, (file, focus_handle))| {
1033 Button::new(ix, file.name())
1034 .toggle_state(file == &self.current_file)
1035 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1036 .track_focus(focus_handle)
1037 .on_click(
1038 cx.listener(move |this, evt: &gpui::ClickEvent, window, cx| {
1039 this.change_file(ix, cx);
1040 if evt.is_keyboard() {
1041 this.focus_first_nav_item(window, cx);
1042 }
1043 }),
1044 )
1045 },
1046 ))
1047 }
1048
1049 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1050 h_flex()
1051 .py_1()
1052 .px_1p5()
1053 .gap_1p5()
1054 .rounded_sm()
1055 .bg(cx.theme().colors().editor_background)
1056 .border_1()
1057 .border_color(cx.theme().colors().border)
1058 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1059 .child(self.search_bar.clone())
1060 }
1061
1062 fn render_nav(
1063 &self,
1064 window: &mut Window,
1065 cx: &mut Context<SettingsWindow>,
1066 ) -> impl IntoElement {
1067 let visible_entries: Vec<_> = self.visible_navbar_entries().collect();
1068 let visible_count = visible_entries.len();
1069
1070 let nav_background = cx.theme().colors().panel_background;
1071
1072 v_flex()
1073 .w_64()
1074 .p_2p5()
1075 .pt_10()
1076 .gap_3()
1077 .flex_none()
1078 .border_r_1()
1079 .border_color(cx.theme().colors().border)
1080 .bg(nav_background)
1081 .child(self.render_search(window, cx))
1082 .child(
1083 v_flex()
1084 .flex_grow()
1085 .track_focus(&self.navbar_focus_handle)
1086 .tab_group()
1087 .tab_index(NAVBAR_GROUP_TAB_INDEX)
1088 .child(
1089 uniform_list(
1090 "settings-ui-nav-bar",
1091 visible_count,
1092 cx.processor(move |this, range: Range<usize>, _, cx| {
1093 let entries: Vec<_> = this.visible_navbar_entries().collect();
1094 range
1095 .filter_map(|ix| entries.get(ix).copied())
1096 .map(|(ix, entry)| {
1097 TreeViewItem::new(
1098 ("settings-ui-navbar-entry", ix),
1099 entry.title,
1100 )
1101 .tab_index(0)
1102 .root_item(entry.is_root)
1103 .toggle_state(this.is_navbar_entry_selected(ix))
1104 .when(entry.is_root, |item| {
1105 item.expanded(entry.expanded).on_toggle(cx.listener(
1106 move |this, _, _, cx| {
1107 this.toggle_navbar_entry(ix);
1108 cx.notify();
1109 },
1110 ))
1111 })
1112 .on_click(cx.listener(
1113 move |this, evt: &gpui::ClickEvent, window, cx| {
1114 this.navbar_entry = ix;
1115 if evt.is_keyboard() {
1116 // todo(settings_ui): Focus the actual item and scroll to it
1117 this.focus_first_content_item(window, cx);
1118 }
1119 cx.notify();
1120 },
1121 ))
1122 .into_any_element()
1123 })
1124 .collect()
1125 }),
1126 )
1127 .track_scroll(self.list_handle.clone())
1128 .flex_grow(),
1129 )
1130 .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1131 )
1132 .child(
1133 h_flex().w_full().justify_center().bg(nav_background).child(
1134 Button::new(
1135 "nav-key-hint",
1136 if self.navbar_focus_handle.contains_focused(window, cx) {
1137 "Focus Content"
1138 } else {
1139 "Focus Navbar"
1140 },
1141 )
1142 .key_binding(ui::KeyBinding::for_action_in(
1143 &ToggleFocusNav,
1144 &self.navbar_focus_handle,
1145 window,
1146 cx,
1147 ))
1148 .key_binding_position(KeybindingPosition::Start),
1149 ),
1150 )
1151 }
1152
1153 fn focus_first_nav_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1154 self.navbar_focus_handle.focus(window);
1155 window.focus_next();
1156 cx.notify();
1157 }
1158
1159 fn focus_first_content_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1160 self.content_focus_handle.focus(window);
1161 window.focus_next();
1162 cx.notify();
1163 }
1164
1165 fn page_items(&self) -> impl Iterator<Item = &SettingsPageItem> {
1166 let page_idx = self.current_page_index();
1167
1168 self.current_page()
1169 .items
1170 .iter()
1171 .enumerate()
1172 .filter_map(move |(item_index, item)| {
1173 self.search_matches[page_idx][item_index].then_some(item)
1174 })
1175 }
1176
1177 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1178 let mut items = vec![];
1179 items.push(self.current_page().title);
1180 items.extend(
1181 sub_page_stack()
1182 .iter()
1183 .flat_map(|page| [page.section_header, page.link.title]),
1184 );
1185
1186 let last = items.pop().unwrap();
1187 h_flex()
1188 .gap_1()
1189 .children(
1190 items
1191 .into_iter()
1192 .flat_map(|item| [item, "/"])
1193 .map(|item| Label::new(item).color(Color::Muted)),
1194 )
1195 .child(Label::new(last))
1196 }
1197
1198 fn render_page_items<'a, Items: Iterator<Item = &'a SettingsPageItem>>(
1199 &self,
1200 items: Items,
1201 window: &mut Window,
1202 cx: &mut Context<SettingsWindow>,
1203 ) -> impl IntoElement {
1204 let mut page_content = v_flex()
1205 .id("settings-ui-page")
1206 .size_full()
1207 .gap_4()
1208 .overflow_y_scroll()
1209 .track_scroll(&self.scroll_handle);
1210
1211 let items: Vec<_> = items.collect();
1212 let items_len = items.len();
1213 let mut section_header = None;
1214
1215 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1216 let has_no_results = items_len == 0 && has_active_search;
1217
1218 if has_no_results {
1219 let search_query = self.search_bar.read(cx).text(cx);
1220 page_content = page_content.child(
1221 v_flex()
1222 .size_full()
1223 .items_center()
1224 .justify_center()
1225 .gap_1()
1226 .child(div().child("No Results"))
1227 .child(
1228 div()
1229 .text_sm()
1230 .text_color(cx.theme().colors().text_muted)
1231 .child(format!("No settings match \"{}\"", search_query)),
1232 ),
1233 )
1234 } else {
1235 let last_non_header_index = items
1236 .iter()
1237 .enumerate()
1238 .rev()
1239 .find(|(_, item)| !matches!(item, SettingsPageItem::SectionHeader(_)))
1240 .map(|(index, _)| index);
1241
1242 page_content =
1243 page_content.children(items.clone().into_iter().enumerate().map(|(index, item)| {
1244 let no_bottom_border = items
1245 .get(index + 1)
1246 .map(|next_item| matches!(next_item, SettingsPageItem::SectionHeader(_)))
1247 .unwrap_or(false);
1248 let is_last = Some(index) == last_non_header_index;
1249
1250 if let SettingsPageItem::SectionHeader(header) = item {
1251 section_header = Some(*header);
1252 }
1253 item.render(
1254 self.current_file.clone(),
1255 section_header.expect("All items rendered after a section header"),
1256 no_bottom_border || is_last,
1257 window,
1258 cx,
1259 )
1260 }))
1261 }
1262 page_content
1263 }
1264
1265 fn render_page(
1266 &mut self,
1267 window: &mut Window,
1268 cx: &mut Context<SettingsWindow>,
1269 ) -> impl IntoElement {
1270 let page_header;
1271 let page_content;
1272
1273 if sub_page_stack().len() == 0 {
1274 page_header = self.render_files(window, cx);
1275 page_content = self
1276 .render_page_items(self.page_items(), window, cx)
1277 .into_any_element();
1278 } else {
1279 page_header = h_flex()
1280 .ml_neg_1p5()
1281 .gap_1()
1282 .child(
1283 IconButton::new("back-btn", IconName::ArrowLeft)
1284 .icon_size(IconSize::Small)
1285 .shape(IconButtonShape::Square)
1286 .on_click(cx.listener(|this, _, _, cx| {
1287 this.pop_sub_page(cx);
1288 })),
1289 )
1290 .child(self.render_sub_page_breadcrumbs());
1291
1292 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1293 page_content = (active_page_render_fn)(self, window, cx);
1294 }
1295
1296 return v_flex()
1297 .w_full()
1298 .pt_4()
1299 .pb_6()
1300 .px_6()
1301 .gap_4()
1302 .track_focus(&self.content_focus_handle)
1303 .bg(cx.theme().colors().editor_background)
1304 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1305 .child(page_header)
1306 .child(
1307 div()
1308 .size_full()
1309 .track_focus(&self.content_focus_handle)
1310 .tab_group()
1311 .tab_index(CONTENT_GROUP_TAB_INDEX)
1312 .child(page_content),
1313 );
1314 }
1315
1316 fn current_page_index(&self) -> usize {
1317 self.page_index_from_navbar_index(self.navbar_entry)
1318 }
1319
1320 fn current_page(&self) -> &SettingsPage {
1321 &self.pages[self.current_page_index()]
1322 }
1323
1324 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1325 if self.navbar_entries.is_empty() {
1326 return 0;
1327 }
1328
1329 self.navbar_entries[index].page_index
1330 }
1331
1332 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1333 ix == self.navbar_entry
1334 }
1335
1336 fn push_sub_page(
1337 &mut self,
1338 sub_page_link: SubPageLink,
1339 section_header: &'static str,
1340 cx: &mut Context<SettingsWindow>,
1341 ) {
1342 sub_page_stack_mut().push(SubPage {
1343 link: sub_page_link,
1344 section_header,
1345 });
1346 cx.notify();
1347 }
1348
1349 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1350 sub_page_stack_mut().pop();
1351 cx.notify();
1352 }
1353
1354 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1355 if let Some((_, handle)) = self.files.get(index) {
1356 handle.focus(window);
1357 }
1358 }
1359
1360 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1361 if self.files_focus_handle.contains_focused(window, cx)
1362 && let Some(index) = self
1363 .files
1364 .iter()
1365 .position(|(_, handle)| handle.is_focused(window))
1366 {
1367 return index;
1368 }
1369 if let Some(current_file_index) = self
1370 .files
1371 .iter()
1372 .position(|(file, _)| file == &self.current_file)
1373 {
1374 return current_file_index;
1375 }
1376 0
1377 }
1378}
1379
1380impl Render for SettingsWindow {
1381 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1382 let ui_font = theme::setup_ui_font(window, cx);
1383
1384 div()
1385 .id("settings-window")
1386 .key_context("SettingsWindow")
1387 .flex()
1388 .flex_row()
1389 .size_full()
1390 .font(ui_font)
1391 .bg(cx.theme().colors().background)
1392 .text_color(cx.theme().colors().text)
1393 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
1394 this.search_bar.focus_handle(cx).focus(window);
1395 }))
1396 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
1397 if this.navbar_focus_handle.contains_focused(window, cx) {
1398 this.focus_first_content_item(window, cx);
1399 } else {
1400 this.focus_first_nav_item(window, cx);
1401 }
1402 }))
1403 .on_action(
1404 cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
1405 this.focus_file_at_index(*file_index as usize, window);
1406 }),
1407 )
1408 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
1409 let next_index = usize::min(
1410 this.focused_file_index(window, cx) + 1,
1411 this.files.len().saturating_sub(1),
1412 );
1413 this.focus_file_at_index(next_index, window);
1414 }))
1415 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
1416 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
1417 this.focus_file_at_index(prev_index, window);
1418 }))
1419 .on_action(|_: &menu::SelectNext, window, _| {
1420 window.focus_next();
1421 })
1422 .on_action(|_: &menu::SelectPrevious, window, _| {
1423 window.focus_prev();
1424 })
1425 .child(self.render_nav(window, cx))
1426 .child(self.render_page(window, cx))
1427 }
1428}
1429
1430fn update_settings_file(
1431 file: SettingsUiFile,
1432 cx: &mut App,
1433 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
1434) -> Result<()> {
1435 match file {
1436 SettingsUiFile::Local((worktree_id, rel_path)) => {
1437 fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
1438 workspace::AppState::global(cx)
1439 .upgrade()
1440 .map(|app_state| {
1441 app_state
1442 .workspace_store
1443 .read(cx)
1444 .workspaces()
1445 .iter()
1446 .filter_map(|workspace| {
1447 Some(workspace.read(cx).ok()?.project().clone())
1448 })
1449 })
1450 .into_iter()
1451 .flatten()
1452 }
1453 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
1454 let project = all_projects(cx).find(|project| {
1455 project.read_with(cx, |project, cx| {
1456 project.contains_local_settings_file(worktree_id, &rel_path, cx)
1457 })
1458 });
1459 let Some(project) = project else {
1460 anyhow::bail!(
1461 "Could not find worktree containing settings file: {}",
1462 &rel_path.display(PathStyle::local())
1463 );
1464 };
1465 project.update(cx, |project, cx| {
1466 project.update_local_settings_file(worktree_id, rel_path, cx, update);
1467 });
1468 return Ok(());
1469 }
1470 SettingsUiFile::User => {
1471 // todo(settings_ui) error?
1472 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
1473 Ok(())
1474 }
1475 SettingsUiFile::Server(_) => unimplemented!(),
1476 }
1477}
1478
1479fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
1480 field: SettingField<T>,
1481 file: SettingsUiFile,
1482 metadata: Option<&SettingsFieldMetadata>,
1483 cx: &mut App,
1484) -> AnyElement {
1485 let (_, initial_text) =
1486 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1487 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
1488
1489 SettingsEditor::new()
1490 .tab_index(0)
1491 .when_some(initial_text, |editor, text| {
1492 editor.with_initial_text(text.as_ref().to_string())
1493 })
1494 .when_some(
1495 metadata.and_then(|metadata| metadata.placeholder),
1496 |editor, placeholder| editor.with_placeholder(placeholder),
1497 )
1498 .on_confirm({
1499 move |new_text, cx| {
1500 update_settings_file(file.clone(), cx, move |settings, _cx| {
1501 *(field.pick_mut)(settings) = new_text.map(Into::into);
1502 })
1503 .log_err(); // todo(settings_ui) don't log err
1504 }
1505 })
1506 .into_any_element()
1507}
1508
1509fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
1510 field: SettingField<B>,
1511 file: SettingsUiFile,
1512 cx: &mut App,
1513) -> AnyElement {
1514 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1515
1516 let toggle_state = if value.copied().map_or(false, Into::into) {
1517 ToggleState::Selected
1518 } else {
1519 ToggleState::Unselected
1520 };
1521
1522 Switch::new("toggle_button", toggle_state)
1523 .color(ui::SwitchColor::Accent)
1524 .on_click({
1525 move |state, _window, cx| {
1526 let state = *state == ui::ToggleState::Selected;
1527 update_settings_file(file.clone(), cx, move |settings, _cx| {
1528 *(field.pick_mut)(settings) = Some(state.into());
1529 })
1530 .log_err(); // todo(settings_ui) don't log err
1531 }
1532 })
1533 .tab_index(0_isize)
1534 .color(SwitchColor::Accent)
1535 .into_any_element()
1536}
1537
1538fn render_font_picker(
1539 field: SettingField<settings::FontFamilyName>,
1540 file: SettingsUiFile,
1541 window: &mut Window,
1542 cx: &mut App,
1543) -> AnyElement {
1544 let current_value = SettingsStore::global(cx)
1545 .get_value_from_file(file.to_settings(), field.pick)
1546 .1
1547 .cloned()
1548 .unwrap_or_else(|| SharedString::default().into());
1549
1550 let font_picker = cx.new(|cx| {
1551 ui_input::font_picker(
1552 current_value.clone().into(),
1553 move |font_name, cx| {
1554 update_settings_file(file.clone(), cx, move |settings, _cx| {
1555 *(field.pick_mut)(settings) = Some(font_name.into());
1556 })
1557 .log_err(); // todo(settings_ui) don't log err
1558 },
1559 window,
1560 cx,
1561 )
1562 });
1563
1564 div()
1565 .child(
1566 PopoverMenu::new("font-picker")
1567 .menu(move |_window, _cx| Some(font_picker.clone()))
1568 .trigger(
1569 ButtonLike::new("font-family-button")
1570 .style(ButtonStyle::Outlined)
1571 .size(ButtonSize::Medium)
1572 .full_width()
1573 .tab_index(0_isize)
1574 .child(
1575 h_flex()
1576 .w_full()
1577 .justify_between()
1578 .child(Label::new(current_value))
1579 .child(
1580 Icon::new(IconName::ChevronUpDown)
1581 .color(Color::Muted)
1582 .size(IconSize::XSmall),
1583 ),
1584 ),
1585 )
1586 .full_width(true)
1587 .anchor(gpui::Corner::TopLeft)
1588 .offset(gpui::Point {
1589 x: px(0.0),
1590 y: px(4.0),
1591 })
1592 .with_handle(ui::PopoverMenuHandle::default()),
1593 )
1594 .into_any_element()
1595}
1596
1597fn render_numeric_stepper<T: NumericStepperType + Send + Sync>(
1598 field: SettingField<T>,
1599 file: SettingsUiFile,
1600 window: &mut Window,
1601 cx: &mut App,
1602) -> AnyElement {
1603 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1604 let value = value.copied().unwrap_or_else(T::min_value);
1605 NumericStepper::new("numeric_stepper", value, window, cx)
1606 .on_change({
1607 move |value, _window, cx| {
1608 let value = *value;
1609 update_settings_file(file.clone(), cx, move |settings, _cx| {
1610 *(field.pick_mut)(settings) = Some(value);
1611 })
1612 .log_err(); // todo(settings_ui) don't log err
1613 }
1614 })
1615 .tab_index(0)
1616 .style(NumericStepperStyle::Outlined)
1617 .into_any_element()
1618}
1619
1620fn render_dropdown<T>(
1621 field: SettingField<T>,
1622 file: SettingsUiFile,
1623 window: &mut Window,
1624 cx: &mut App,
1625) -> AnyElement
1626where
1627 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
1628{
1629 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
1630 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
1631
1632 let (_, current_value) =
1633 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1634 let current_value = current_value.copied().unwrap_or(variants()[0]);
1635
1636 let current_value_label =
1637 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
1638
1639 DropdownMenu::new(
1640 "dropdown",
1641 current_value_label.to_title_case(),
1642 ContextMenu::build(window, cx, move |mut menu, _, _| {
1643 for (&value, &label) in std::iter::zip(variants(), labels()) {
1644 let file = file.clone();
1645 menu = menu.toggleable_entry(
1646 label.to_title_case(),
1647 value == current_value,
1648 IconPosition::Start,
1649 None,
1650 move |_, cx| {
1651 if value == current_value {
1652 return;
1653 }
1654 update_settings_file(file.clone(), cx, move |settings, _cx| {
1655 *(field.pick_mut)(settings) = Some(value);
1656 })
1657 .log_err(); // todo(settings_ui) don't log err
1658 },
1659 );
1660 }
1661 menu
1662 }),
1663 )
1664 .trigger_size(ButtonSize::Medium)
1665 .style(DropdownStyle::Outlined)
1666 .offset(gpui::Point {
1667 x: px(0.0),
1668 y: px(2.0),
1669 })
1670 .tab_index(0)
1671 .into_any_element()
1672}
1673
1674#[cfg(test)]
1675mod test {
1676
1677 use super::*;
1678
1679 impl SettingsWindow {
1680 fn navbar_entry(&self) -> usize {
1681 self.navbar_entry
1682 }
1683
1684 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
1685 let mut this = Self::new(window, cx);
1686 this.navbar_entries.clear();
1687 this.pages.clear();
1688 this
1689 }
1690
1691 fn build(mut self) -> Self {
1692 self.build_search_matches();
1693 self.build_navbar();
1694 self
1695 }
1696
1697 fn add_page(
1698 mut self,
1699 title: &'static str,
1700 build_page: impl Fn(SettingsPage) -> SettingsPage,
1701 ) -> Self {
1702 let page = SettingsPage {
1703 title,
1704 items: Vec::default(),
1705 };
1706
1707 self.pages.push(build_page(page));
1708 self
1709 }
1710
1711 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
1712 self.search_task.take();
1713 self.search_bar.update(cx, |editor, cx| {
1714 editor.set_text(search_query, window, cx);
1715 });
1716 self.update_matches(cx);
1717 }
1718
1719 fn assert_search_results(&self, other: &Self) {
1720 // page index could be different because of filtered out pages
1721 #[derive(Debug, PartialEq)]
1722 struct EntryMinimal {
1723 is_root: bool,
1724 title: &'static str,
1725 }
1726 pretty_assertions::assert_eq!(
1727 other
1728 .visible_navbar_entries()
1729 .map(|(_, entry)| EntryMinimal {
1730 is_root: entry.is_root,
1731 title: entry.title,
1732 })
1733 .collect::<Vec<_>>(),
1734 self.visible_navbar_entries()
1735 .map(|(_, entry)| EntryMinimal {
1736 is_root: entry.is_root,
1737 title: entry.title,
1738 })
1739 .collect::<Vec<_>>(),
1740 );
1741 assert_eq!(
1742 self.current_page().items.iter().collect::<Vec<_>>(),
1743 other.page_items().collect::<Vec<_>>()
1744 );
1745 }
1746 }
1747
1748 impl SettingsPage {
1749 fn item(mut self, item: SettingsPageItem) -> Self {
1750 self.items.push(item);
1751 self
1752 }
1753 }
1754
1755 impl SettingsPageItem {
1756 fn basic_item(title: &'static str, description: &'static str) -> Self {
1757 SettingsPageItem::SettingItem(SettingItem {
1758 title,
1759 description,
1760 field: Box::new(SettingField {
1761 pick: |settings_content| &settings_content.auto_update,
1762 pick_mut: |settings_content| &mut settings_content.auto_update,
1763 }),
1764 metadata: None,
1765 })
1766 }
1767 }
1768
1769 fn register_settings(cx: &mut App) {
1770 settings::init(cx);
1771 theme::init(theme::LoadThemes::JustBase, cx);
1772 workspace::init_settings(cx);
1773 project::Project::init_settings(cx);
1774 language::init(cx);
1775 editor::init(cx);
1776 menu::init();
1777 }
1778
1779 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
1780 let mut pages: Vec<SettingsPage> = Vec::new();
1781 let mut expanded_pages = Vec::new();
1782 let mut selected_idx = None;
1783 let mut index = 0;
1784 let mut in_expanded_section = false;
1785
1786 for mut line in input
1787 .lines()
1788 .map(|line| line.trim())
1789 .filter(|line| !line.is_empty())
1790 {
1791 if let Some(pre) = line.strip_suffix('*') {
1792 assert!(selected_idx.is_none(), "Only one selected entry allowed");
1793 selected_idx = Some(index);
1794 line = pre;
1795 }
1796 let (kind, title) = line.split_once(" ").unwrap();
1797 assert_eq!(kind.len(), 1);
1798 let kind = kind.chars().next().unwrap();
1799 if kind == 'v' {
1800 let page_idx = pages.len();
1801 expanded_pages.push(page_idx);
1802 pages.push(SettingsPage {
1803 title,
1804 items: vec![],
1805 });
1806 index += 1;
1807 in_expanded_section = true;
1808 } else if kind == '>' {
1809 pages.push(SettingsPage {
1810 title,
1811 items: vec![],
1812 });
1813 index += 1;
1814 in_expanded_section = false;
1815 } else if kind == '-' {
1816 pages
1817 .last_mut()
1818 .unwrap()
1819 .items
1820 .push(SettingsPageItem::SectionHeader(title));
1821 if selected_idx == Some(index) && !in_expanded_section {
1822 panic!("Items in unexpanded sections cannot be selected");
1823 }
1824 index += 1;
1825 } else {
1826 panic!(
1827 "Entries must start with one of 'v', '>', or '-'\n line: {}",
1828 line
1829 );
1830 }
1831 }
1832
1833 let mut settings_window = SettingsWindow {
1834 files: Vec::default(),
1835 current_file: crate::SettingsUiFile::User,
1836 pages,
1837 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
1838 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
1839 navbar_entries: Vec::default(),
1840 list_handle: UniformListScrollHandle::default(),
1841 search_matches: vec![],
1842 search_task: None,
1843 scroll_handle: ScrollHandle::new(),
1844 navbar_focus_handle: cx.focus_handle(),
1845 content_focus_handle: cx.focus_handle(),
1846 files_focus_handle: cx.focus_handle(),
1847 };
1848
1849 settings_window.build_search_matches();
1850 settings_window.build_navbar();
1851 for expanded_page_index in expanded_pages {
1852 for entry in &mut settings_window.navbar_entries {
1853 if entry.page_index == expanded_page_index && entry.is_root {
1854 entry.expanded = true;
1855 }
1856 }
1857 }
1858 settings_window
1859 }
1860
1861 #[track_caller]
1862 fn check_navbar_toggle(
1863 before: &'static str,
1864 toggle_page: &'static str,
1865 after: &'static str,
1866 window: &mut Window,
1867 cx: &mut App,
1868 ) {
1869 let mut settings_window = parse(before, window, cx);
1870 let toggle_page_idx = settings_window
1871 .pages
1872 .iter()
1873 .position(|page| page.title == toggle_page)
1874 .expect("page not found");
1875 let toggle_idx = settings_window
1876 .navbar_entries
1877 .iter()
1878 .position(|entry| entry.page_index == toggle_page_idx)
1879 .expect("page not found");
1880 settings_window.toggle_navbar_entry(toggle_idx);
1881
1882 let expected_settings_window = parse(after, window, cx);
1883
1884 pretty_assertions::assert_eq!(
1885 settings_window
1886 .visible_navbar_entries()
1887 .map(|(_, entry)| entry)
1888 .collect::<Vec<_>>(),
1889 expected_settings_window
1890 .visible_navbar_entries()
1891 .map(|(_, entry)| entry)
1892 .collect::<Vec<_>>(),
1893 );
1894 pretty_assertions::assert_eq!(
1895 settings_window.navbar_entries[settings_window.navbar_entry()],
1896 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
1897 );
1898 }
1899
1900 macro_rules! check_navbar_toggle {
1901 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
1902 #[gpui::test]
1903 fn $name(cx: &mut gpui::TestAppContext) {
1904 let window = cx.add_empty_window();
1905 window.update(|window, cx| {
1906 register_settings(cx);
1907 check_navbar_toggle($before, $toggle_page, $after, window, cx);
1908 });
1909 }
1910 };
1911 }
1912
1913 check_navbar_toggle!(
1914 navbar_basic_open,
1915 before: r"
1916 v General
1917 - General
1918 - Privacy*
1919 v Project
1920 - Project Settings
1921 ",
1922 toggle_page: "General",
1923 after: r"
1924 > General*
1925 v Project
1926 - Project Settings
1927 "
1928 );
1929
1930 check_navbar_toggle!(
1931 navbar_basic_close,
1932 before: r"
1933 > General*
1934 - General
1935 - Privacy
1936 v Project
1937 - Project Settings
1938 ",
1939 toggle_page: "General",
1940 after: r"
1941 v General*
1942 - General
1943 - Privacy
1944 v Project
1945 - Project Settings
1946 "
1947 );
1948
1949 check_navbar_toggle!(
1950 navbar_basic_second_root_entry_close,
1951 before: r"
1952 > General
1953 - General
1954 - Privacy
1955 v Project
1956 - Project Settings*
1957 ",
1958 toggle_page: "Project",
1959 after: r"
1960 > General
1961 > Project*
1962 "
1963 );
1964
1965 check_navbar_toggle!(
1966 navbar_toggle_subroot,
1967 before: r"
1968 v General Page
1969 - General
1970 - Privacy
1971 v Project
1972 - Worktree Settings Content*
1973 v AI
1974 - General
1975 > Appearance & Behavior
1976 ",
1977 toggle_page: "Project",
1978 after: r"
1979 v General Page
1980 - General
1981 - Privacy
1982 > Project*
1983 v AI
1984 - General
1985 > Appearance & Behavior
1986 "
1987 );
1988
1989 check_navbar_toggle!(
1990 navbar_toggle_close_propagates_selected_index,
1991 before: r"
1992 v General Page
1993 - General
1994 - Privacy
1995 v Project
1996 - Worktree Settings Content
1997 v AI
1998 - General*
1999 > Appearance & Behavior
2000 ",
2001 toggle_page: "General Page",
2002 after: r"
2003 > General Page
2004 v Project
2005 - Worktree Settings Content
2006 v AI
2007 - General*
2008 > Appearance & Behavior
2009 "
2010 );
2011
2012 check_navbar_toggle!(
2013 navbar_toggle_expand_propagates_selected_index,
2014 before: r"
2015 > General Page
2016 - General
2017 - Privacy
2018 v Project
2019 - Worktree Settings Content
2020 v AI
2021 - General*
2022 > Appearance & Behavior
2023 ",
2024 toggle_page: "General Page",
2025 after: r"
2026 v General Page
2027 - General
2028 - Privacy
2029 v Project
2030 - Worktree Settings Content
2031 v AI
2032 - General*
2033 > Appearance & Behavior
2034 "
2035 );
2036
2037 #[gpui::test]
2038 fn test_basic_search(cx: &mut gpui::TestAppContext) {
2039 let cx = cx.add_empty_window();
2040 let (actual, expected) = cx.update(|window, cx| {
2041 register_settings(cx);
2042
2043 let expected = cx.new(|cx| {
2044 SettingsWindow::new_builder(window, cx)
2045 .add_page("General", |page| {
2046 page.item(SettingsPageItem::SectionHeader("General settings"))
2047 .item(SettingsPageItem::basic_item("test title", "General test"))
2048 })
2049 .build()
2050 });
2051
2052 let actual = cx.new(|cx| {
2053 SettingsWindow::new_builder(window, cx)
2054 .add_page("General", |page| {
2055 page.item(SettingsPageItem::SectionHeader("General settings"))
2056 .item(SettingsPageItem::basic_item("test title", "General test"))
2057 })
2058 .add_page("Theme", |page| {
2059 page.item(SettingsPageItem::SectionHeader("Theme settings"))
2060 })
2061 .build()
2062 });
2063
2064 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2065
2066 (actual, expected)
2067 });
2068
2069 cx.cx.run_until_parked();
2070
2071 cx.update(|_window, cx| {
2072 let expected = expected.read(cx);
2073 let actual = actual.read(cx);
2074 expected.assert_search_results(&actual);
2075 })
2076 }
2077
2078 #[gpui::test]
2079 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2080 let cx = cx.add_empty_window();
2081 let (actual, expected) = cx.update(|window, cx| {
2082 register_settings(cx);
2083
2084 let actual = cx.new(|cx| {
2085 SettingsWindow::new_builder(window, cx)
2086 .add_page("General", |page| {
2087 page.item(SettingsPageItem::SectionHeader("General settings"))
2088 .item(SettingsPageItem::basic_item(
2089 "Confirm Quit",
2090 "Whether to confirm before quitting Zed",
2091 ))
2092 .item(SettingsPageItem::basic_item(
2093 "Auto Update",
2094 "Automatically update Zed",
2095 ))
2096 })
2097 .add_page("AI", |page| {
2098 page.item(SettingsPageItem::basic_item(
2099 "Disable AI",
2100 "Whether to disable all AI features in Zed",
2101 ))
2102 })
2103 .add_page("Appearance & Behavior", |page| {
2104 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2105 SettingsPageItem::basic_item(
2106 "Cursor Shape",
2107 "Cursor shape for the editor",
2108 ),
2109 )
2110 })
2111 .build()
2112 });
2113
2114 let expected = cx.new(|cx| {
2115 SettingsWindow::new_builder(window, cx)
2116 .add_page("Appearance & Behavior", |page| {
2117 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2118 SettingsPageItem::basic_item(
2119 "Cursor Shape",
2120 "Cursor shape for the editor",
2121 ),
2122 )
2123 })
2124 .build()
2125 });
2126
2127 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2128
2129 (actual, expected)
2130 });
2131
2132 cx.cx.run_until_parked();
2133
2134 cx.update(|_window, cx| {
2135 let expected = expected.read(cx);
2136 let actual = actual.read(cx);
2137 expected.assert_search_results(&actual);
2138 })
2139 }
2140}