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