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 calculate_navbar_entry_from_scroll_position(&mut self) {
947 let scroll_index = self.scroll_handle.logical_scroll_top().0;
948 let mut page_index = self.navbar_entry;
949
950 while !self.navbar_entries[page_index].is_root {
951 page_index -= 1;
952 }
953
954 if self.navbar_entries[page_index].expanded {
955 let section_index = self
956 .page_items()
957 .take(scroll_index + 1)
958 .filter(|item| matches!(item, SettingsPageItem::SectionHeader(_)))
959 .count();
960
961 self.navbar_entry = section_index + page_index;
962 }
963 }
964
965 fn fetch_files(&mut self, cx: &mut Context<SettingsWindow>) {
966 let prev_files = self.files.clone();
967 let settings_store = cx.global::<SettingsStore>();
968 let mut ui_files = vec![];
969 let all_files = settings_store.get_all_files();
970 for file in all_files {
971 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
972 continue;
973 };
974 let focus_handle = prev_files
975 .iter()
976 .find_map(|(prev_file, handle)| {
977 (prev_file == &settings_ui_file).then(|| handle.clone())
978 })
979 .unwrap_or_else(|| cx.focus_handle());
980 ui_files.push((settings_ui_file, focus_handle));
981 }
982 ui_files.reverse();
983 self.files = ui_files;
984 let current_file_still_exists = self
985 .files
986 .iter()
987 .any(|(file, _)| file == &self.current_file);
988 if !current_file_still_exists {
989 self.change_file(0, cx);
990 }
991 }
992
993 fn change_file(&mut self, ix: usize, cx: &mut Context<SettingsWindow>) {
994 if ix >= self.files.len() {
995 self.current_file = SettingsUiFile::User;
996 return;
997 }
998 if self.files[ix].0 == self.current_file {
999 return;
1000 }
1001 self.current_file = self.files[ix].0.clone();
1002 self.navbar_entry = 0;
1003 self.build_ui(cx);
1004 }
1005
1006 fn render_files(&self, _window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
1007 h_flex().gap_1().children(self.files.iter().enumerate().map(
1008 |(ix, (file, focus_handle))| {
1009 Button::new(ix, file.name())
1010 .toggle_state(file == &self.current_file)
1011 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1012 .track_focus(focus_handle)
1013 .on_click(
1014 cx.listener(move |this, evt: &gpui::ClickEvent, window, cx| {
1015 this.change_file(ix, cx);
1016 if evt.is_keyboard() {
1017 this.focus_first_nav_item(window, cx);
1018 }
1019 }),
1020 )
1021 },
1022 ))
1023 }
1024
1025 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1026 h_flex()
1027 .py_1()
1028 .px_1p5()
1029 .gap_1p5()
1030 .rounded_sm()
1031 .bg(cx.theme().colors().editor_background)
1032 .border_1()
1033 .border_color(cx.theme().colors().border)
1034 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1035 .child(self.search_bar.clone())
1036 }
1037
1038 fn render_nav(
1039 &self,
1040 window: &mut Window,
1041 cx: &mut Context<SettingsWindow>,
1042 ) -> impl IntoElement {
1043 let visible_count = self.visible_navbar_entries().count();
1044 let nav_background = cx.theme().colors().panel_background;
1045
1046 v_flex()
1047 .w_64()
1048 .p_2p5()
1049 .pt_10()
1050 .gap_3()
1051 .flex_none()
1052 .border_r_1()
1053 .border_color(cx.theme().colors().border)
1054 .bg(nav_background)
1055 .child(self.render_search(window, cx))
1056 .child(
1057 v_flex()
1058 .flex_grow()
1059 .track_focus(&self.navbar_focus_handle)
1060 .tab_group()
1061 .tab_index(NAVBAR_GROUP_TAB_INDEX)
1062 .child(
1063 uniform_list(
1064 "settings-ui-nav-bar",
1065 visible_count,
1066 cx.processor(move |this, range: Range<usize>, _, cx| {
1067 let entries: Vec<_> = this.visible_navbar_entries().collect();
1068 range
1069 .filter_map(|ix| entries.get(ix).copied())
1070 .map(|(ix, entry)| {
1071 TreeViewItem::new(
1072 ("settings-ui-navbar-entry", ix),
1073 entry.title,
1074 )
1075 .tab_index(0)
1076 .root_item(entry.is_root)
1077 .toggle_state(this.is_navbar_entry_selected(ix))
1078 .when(entry.is_root, |item| {
1079 item.expanded(entry.expanded).on_toggle(cx.listener(
1080 move |this, _, _, cx| {
1081 this.toggle_navbar_entry(ix);
1082 cx.notify();
1083 },
1084 ))
1085 })
1086 .on_click(cx.listener(
1087 move |this, evt: &gpui::ClickEvent, window, cx| {
1088 this.navbar_entry = ix;
1089
1090 if !this.navbar_entries[ix].is_root {
1091 let mut selected_page_ix = ix;
1092
1093 while !this.navbar_entries[selected_page_ix]
1094 .is_root
1095 {
1096 selected_page_ix -= 1;
1097 }
1098
1099 let section_header = ix - selected_page_ix;
1100
1101 if let Some(section_index) = this
1102 .page_items()
1103 .enumerate()
1104 .filter(|item| {
1105 matches!(
1106 item.1,
1107 SettingsPageItem::SectionHeader(_)
1108 )
1109 })
1110 .take(section_header)
1111 .last()
1112 .map(|pair| pair.0)
1113 {
1114 this.scroll_handle
1115 .scroll_to_top_of_item(section_index);
1116 }
1117 }
1118
1119 if evt.is_keyboard() {
1120 // todo(settings_ui): Focus the actual item and scroll to it
1121 this.focus_first_content_item(window, cx);
1122 }
1123 cx.notify();
1124 },
1125 ))
1126 .into_any_element()
1127 })
1128 .collect()
1129 }),
1130 )
1131 .track_scroll(self.list_handle.clone())
1132 .flex_grow(),
1133 )
1134 .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1135 )
1136 .child(
1137 h_flex().w_full().justify_center().bg(nav_background).child(
1138 Button::new(
1139 "nav-key-hint",
1140 if self.navbar_focus_handle.contains_focused(window, cx) {
1141 "Focus Content"
1142 } else {
1143 "Focus Navbar"
1144 },
1145 )
1146 .key_binding(ui::KeyBinding::for_action_in(
1147 &ToggleFocusNav,
1148 &self.navbar_focus_handle,
1149 window,
1150 cx,
1151 ))
1152 .key_binding_position(KeybindingPosition::Start),
1153 ),
1154 )
1155 }
1156
1157 fn focus_first_nav_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1158 self.navbar_focus_handle.focus(window);
1159 window.focus_next();
1160 cx.notify();
1161 }
1162
1163 fn focus_first_content_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1164 self.content_focus_handle.focus(window);
1165 window.focus_next();
1166 cx.notify();
1167 }
1168
1169 fn page_items(&self) -> impl Iterator<Item = &SettingsPageItem> {
1170 let page_idx = self.current_page_index();
1171
1172 self.current_page()
1173 .items
1174 .iter()
1175 .enumerate()
1176 .filter_map(move |(item_index, item)| {
1177 self.search_matches[page_idx][item_index].then_some(item)
1178 })
1179 }
1180
1181 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1182 let mut items = vec![];
1183 items.push(self.current_page().title);
1184 items.extend(
1185 sub_page_stack()
1186 .iter()
1187 .flat_map(|page| [page.section_header, page.link.title]),
1188 );
1189
1190 let last = items.pop().unwrap();
1191 h_flex()
1192 .gap_1()
1193 .children(
1194 items
1195 .into_iter()
1196 .flat_map(|item| [item, "/"])
1197 .map(|item| Label::new(item).color(Color::Muted)),
1198 )
1199 .child(Label::new(last))
1200 }
1201
1202 fn render_page_items<'a, Items: Iterator<Item = &'a SettingsPageItem>>(
1203 &self,
1204 items: Items,
1205 window: &mut Window,
1206 cx: &mut Context<SettingsWindow>,
1207 ) -> impl IntoElement {
1208 let mut page_content = v_flex()
1209 .id("settings-ui-page")
1210 .size_full()
1211 .gap_4()
1212 .overflow_y_scroll()
1213 .track_scroll(&self.scroll_handle);
1214
1215 let items: Vec<_> = items.collect();
1216 let items_len = items.len();
1217 let mut section_header = None;
1218
1219 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1220 let has_no_results = items_len == 0 && has_active_search;
1221
1222 if has_no_results {
1223 let search_query = self.search_bar.read(cx).text(cx);
1224 page_content = page_content.child(
1225 v_flex()
1226 .size_full()
1227 .items_center()
1228 .justify_center()
1229 .gap_1()
1230 .child(div().child("No Results"))
1231 .child(
1232 div()
1233 .text_sm()
1234 .text_color(cx.theme().colors().text_muted)
1235 .child(format!("No settings match \"{}\"", search_query)),
1236 ),
1237 )
1238 } else {
1239 let last_non_header_index = items
1240 .iter()
1241 .enumerate()
1242 .rev()
1243 .find(|(_, item)| !matches!(item, SettingsPageItem::SectionHeader(_)))
1244 .map(|(index, _)| index);
1245
1246 page_content =
1247 page_content.children(items.clone().into_iter().enumerate().map(|(index, item)| {
1248 let no_bottom_border = items
1249 .get(index + 1)
1250 .map(|next_item| matches!(next_item, SettingsPageItem::SectionHeader(_)))
1251 .unwrap_or(false);
1252 let is_last = Some(index) == last_non_header_index;
1253
1254 if let SettingsPageItem::SectionHeader(header) = item {
1255 section_header = Some(*header);
1256 }
1257 item.render(
1258 self.current_file.clone(),
1259 section_header.expect("All items rendered after a section header"),
1260 no_bottom_border || is_last,
1261 window,
1262 cx,
1263 )
1264 }))
1265 }
1266 page_content
1267 }
1268
1269 fn render_page(
1270 &mut self,
1271 window: &mut Window,
1272 cx: &mut Context<SettingsWindow>,
1273 ) -> impl IntoElement {
1274 let page_header;
1275 let page_content;
1276
1277 if sub_page_stack().len() == 0 {
1278 page_header = self.render_files(window, cx);
1279 page_content = self
1280 .render_page_items(self.page_items(), window, cx)
1281 .into_any_element();
1282 } else {
1283 page_header = h_flex()
1284 .ml_neg_1p5()
1285 .gap_1()
1286 .child(
1287 IconButton::new("back-btn", IconName::ArrowLeft)
1288 .icon_size(IconSize::Small)
1289 .shape(IconButtonShape::Square)
1290 .on_click(cx.listener(|this, _, _, cx| {
1291 this.pop_sub_page(cx);
1292 })),
1293 )
1294 .child(self.render_sub_page_breadcrumbs());
1295
1296 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1297 page_content = (active_page_render_fn)(self, window, cx);
1298 }
1299
1300 return v_flex()
1301 .w_full()
1302 .pt_4()
1303 .pb_6()
1304 .px_6()
1305 .gap_4()
1306 .track_focus(&self.content_focus_handle)
1307 .bg(cx.theme().colors().editor_background)
1308 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1309 .child(page_header)
1310 .child(
1311 div()
1312 .size_full()
1313 .track_focus(&self.content_focus_handle)
1314 .tab_group()
1315 .tab_index(CONTENT_GROUP_TAB_INDEX)
1316 .child(page_content),
1317 );
1318 }
1319
1320 fn current_page_index(&self) -> usize {
1321 self.page_index_from_navbar_index(self.navbar_entry)
1322 }
1323
1324 fn current_page(&self) -> &SettingsPage {
1325 &self.pages[self.current_page_index()]
1326 }
1327
1328 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1329 if self.navbar_entries.is_empty() {
1330 return 0;
1331 }
1332
1333 self.navbar_entries[index].page_index
1334 }
1335
1336 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1337 ix == self.navbar_entry
1338 }
1339
1340 fn push_sub_page(
1341 &mut self,
1342 sub_page_link: SubPageLink,
1343 section_header: &'static str,
1344 cx: &mut Context<SettingsWindow>,
1345 ) {
1346 sub_page_stack_mut().push(SubPage {
1347 link: sub_page_link,
1348 section_header,
1349 });
1350 cx.notify();
1351 }
1352
1353 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1354 sub_page_stack_mut().pop();
1355 cx.notify();
1356 }
1357
1358 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1359 if let Some((_, handle)) = self.files.get(index) {
1360 handle.focus(window);
1361 }
1362 }
1363
1364 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1365 if self.files_focus_handle.contains_focused(window, cx)
1366 && let Some(index) = self
1367 .files
1368 .iter()
1369 .position(|(_, handle)| handle.is_focused(window))
1370 {
1371 return index;
1372 }
1373 if let Some(current_file_index) = self
1374 .files
1375 .iter()
1376 .position(|(file, _)| file == &self.current_file)
1377 {
1378 return current_file_index;
1379 }
1380 0
1381 }
1382}
1383
1384impl Render for SettingsWindow {
1385 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1386 let ui_font = theme::setup_ui_font(window, cx);
1387 self.calculate_navbar_entry_from_scroll_position();
1388
1389 div()
1390 .id("settings-window")
1391 .key_context("SettingsWindow")
1392 .flex()
1393 .flex_row()
1394 .size_full()
1395 .font(ui_font)
1396 .bg(cx.theme().colors().background)
1397 .text_color(cx.theme().colors().text)
1398 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
1399 this.search_bar.focus_handle(cx).focus(window);
1400 }))
1401 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
1402 if this.navbar_focus_handle.contains_focused(window, cx) {
1403 this.focus_first_content_item(window, cx);
1404 } else {
1405 this.focus_first_nav_item(window, cx);
1406 }
1407 }))
1408 .on_action(
1409 cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
1410 this.focus_file_at_index(*file_index as usize, window);
1411 }),
1412 )
1413 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
1414 let next_index = usize::min(
1415 this.focused_file_index(window, cx) + 1,
1416 this.files.len().saturating_sub(1),
1417 );
1418 this.focus_file_at_index(next_index, window);
1419 }))
1420 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
1421 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
1422 this.focus_file_at_index(prev_index, window);
1423 }))
1424 .on_action(|_: &menu::SelectNext, window, _| {
1425 window.focus_next();
1426 })
1427 .on_action(|_: &menu::SelectPrevious, window, _| {
1428 window.focus_prev();
1429 })
1430 .child(self.render_nav(window, cx))
1431 .child(self.render_page(window, cx))
1432 }
1433}
1434
1435fn update_settings_file(
1436 file: SettingsUiFile,
1437 cx: &mut App,
1438 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
1439) -> Result<()> {
1440 match file {
1441 SettingsUiFile::Local((worktree_id, rel_path)) => {
1442 fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
1443 workspace::AppState::global(cx)
1444 .upgrade()
1445 .map(|app_state| {
1446 app_state
1447 .workspace_store
1448 .read(cx)
1449 .workspaces()
1450 .iter()
1451 .filter_map(|workspace| {
1452 Some(workspace.read(cx).ok()?.project().clone())
1453 })
1454 })
1455 .into_iter()
1456 .flatten()
1457 }
1458 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
1459 let project = all_projects(cx).find(|project| {
1460 project.read_with(cx, |project, cx| {
1461 project.contains_local_settings_file(worktree_id, &rel_path, cx)
1462 })
1463 });
1464 let Some(project) = project else {
1465 anyhow::bail!(
1466 "Could not find worktree containing settings file: {}",
1467 &rel_path.display(PathStyle::local())
1468 );
1469 };
1470 project.update(cx, |project, cx| {
1471 project.update_local_settings_file(worktree_id, rel_path, cx, update);
1472 });
1473 return Ok(());
1474 }
1475 SettingsUiFile::User => {
1476 // todo(settings_ui) error?
1477 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
1478 Ok(())
1479 }
1480 SettingsUiFile::Server(_) => unimplemented!(),
1481 }
1482}
1483
1484fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
1485 field: SettingField<T>,
1486 file: SettingsUiFile,
1487 metadata: Option<&SettingsFieldMetadata>,
1488 cx: &mut App,
1489) -> AnyElement {
1490 let (_, initial_text) =
1491 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1492 let initial_text = Some(initial_text.clone()).filter(|s| !s.as_ref().is_empty());
1493
1494 SettingsEditor::new()
1495 .tab_index(0)
1496 .when_some(initial_text, |editor, text| {
1497 editor.with_initial_text(text.into())
1498 })
1499 .when_some(
1500 metadata.and_then(|metadata| metadata.placeholder),
1501 |editor, placeholder| editor.with_placeholder(placeholder),
1502 )
1503 .on_confirm({
1504 move |new_text, cx| {
1505 update_settings_file(file.clone(), cx, move |settings, _cx| {
1506 *(field.pick_mut)(settings) = new_text.map(Into::into);
1507 })
1508 .log_err(); // todo(settings_ui) don't log err
1509 }
1510 })
1511 .into_any_element()
1512}
1513
1514fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
1515 field: SettingField<B>,
1516 file: SettingsUiFile,
1517 cx: &mut App,
1518) -> AnyElement {
1519 let (_, &value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1520
1521 let toggle_state = if value.into() {
1522 ToggleState::Selected
1523 } else {
1524 ToggleState::Unselected
1525 };
1526
1527 Switch::new("toggle_button", toggle_state)
1528 .color(ui::SwitchColor::Accent)
1529 .on_click({
1530 move |state, _window, cx| {
1531 let state = *state == ui::ToggleState::Selected;
1532 update_settings_file(file.clone(), cx, move |settings, _cx| {
1533 *(field.pick_mut)(settings) = Some(state.into());
1534 })
1535 .log_err(); // todo(settings_ui) don't log err
1536 }
1537 })
1538 .tab_index(0_isize)
1539 .color(SwitchColor::Accent)
1540 .into_any_element()
1541}
1542
1543fn render_font_picker(
1544 field: SettingField<settings::FontFamilyName>,
1545 file: SettingsUiFile,
1546 window: &mut Window,
1547 cx: &mut App,
1548) -> AnyElement {
1549 let current_value = SettingsStore::global(cx)
1550 .get_value_from_file(file.to_settings(), field.pick)
1551 .1
1552 .clone();
1553
1554 let font_picker = cx.new(|cx| {
1555 ui_input::font_picker(
1556 current_value.clone().into(),
1557 move |font_name, cx| {
1558 update_settings_file(file.clone(), cx, move |settings, _cx| {
1559 *(field.pick_mut)(settings) = Some(font_name.into());
1560 })
1561 .log_err(); // todo(settings_ui) don't log err
1562 },
1563 window,
1564 cx,
1565 )
1566 });
1567
1568 div()
1569 .child(
1570 PopoverMenu::new("font-picker")
1571 .menu(move |_window, _cx| Some(font_picker.clone()))
1572 .trigger(
1573 ButtonLike::new("font-family-button")
1574 .style(ButtonStyle::Outlined)
1575 .size(ButtonSize::Medium)
1576 .full_width()
1577 .tab_index(0_isize)
1578 .child(
1579 h_flex()
1580 .w_full()
1581 .justify_between()
1582 .child(Label::new(current_value))
1583 .child(
1584 Icon::new(IconName::ChevronUpDown)
1585 .color(Color::Muted)
1586 .size(IconSize::XSmall),
1587 ),
1588 ),
1589 )
1590 .full_width(true)
1591 .anchor(gpui::Corner::TopLeft)
1592 .offset(gpui::Point {
1593 x: px(0.0),
1594 y: px(4.0),
1595 })
1596 .with_handle(ui::PopoverMenuHandle::default()),
1597 )
1598 .into_any_element()
1599}
1600
1601fn render_numeric_stepper<T: NumericStepperType + Send + Sync>(
1602 field: SettingField<T>,
1603 file: SettingsUiFile,
1604 window: &mut Window,
1605 cx: &mut App,
1606) -> AnyElement {
1607 let (_, &value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1608
1609 NumericStepper::new("numeric_stepper", value, window, cx)
1610 .on_change({
1611 move |value, _window, cx| {
1612 let value = *value;
1613 update_settings_file(file.clone(), cx, move |settings, _cx| {
1614 *(field.pick_mut)(settings) = Some(value);
1615 })
1616 .log_err(); // todo(settings_ui) don't log err
1617 }
1618 })
1619 .tab_index(0)
1620 .style(NumericStepperStyle::Outlined)
1621 .into_any_element()
1622}
1623
1624fn render_dropdown<T>(
1625 field: SettingField<T>,
1626 file: SettingsUiFile,
1627 window: &mut Window,
1628 cx: &mut App,
1629) -> AnyElement
1630where
1631 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
1632{
1633 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
1634 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
1635
1636 let (_, ¤t_value) =
1637 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1638
1639 let current_value_label =
1640 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
1641
1642 DropdownMenu::new(
1643 "dropdown",
1644 current_value_label,
1645 ContextMenu::build(window, cx, move |mut menu, _, _| {
1646 for (&value, &label) in std::iter::zip(variants(), labels()) {
1647 let file = file.clone();
1648 menu = menu.toggleable_entry(
1649 label,
1650 value == current_value,
1651 IconPosition::Start,
1652 None,
1653 move |_, cx| {
1654 if value == current_value {
1655 return;
1656 }
1657 update_settings_file(file.clone(), cx, move |settings, _cx| {
1658 *(field.pick_mut)(settings) = Some(value);
1659 })
1660 .log_err(); // todo(settings_ui) don't log err
1661 },
1662 );
1663 }
1664 menu
1665 }),
1666 )
1667 .trigger_size(ButtonSize::Medium)
1668 .style(DropdownStyle::Outlined)
1669 .offset(gpui::Point {
1670 x: px(0.0),
1671 y: px(2.0),
1672 })
1673 .tab_index(0)
1674 .into_any_element()
1675}
1676
1677#[cfg(test)]
1678mod test {
1679
1680 use super::*;
1681
1682 impl SettingsWindow {
1683 fn navbar_entry(&self) -> usize {
1684 self.navbar_entry
1685 }
1686
1687 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
1688 let mut this = Self::new(window, cx);
1689 this.navbar_entries.clear();
1690 this.pages.clear();
1691 this
1692 }
1693
1694 fn build(mut self) -> Self {
1695 self.build_search_matches();
1696 self.build_navbar();
1697 self
1698 }
1699
1700 fn add_page(
1701 mut self,
1702 title: &'static str,
1703 build_page: impl Fn(SettingsPage) -> SettingsPage,
1704 ) -> Self {
1705 let page = SettingsPage {
1706 title,
1707 items: Vec::default(),
1708 };
1709
1710 self.pages.push(build_page(page));
1711 self
1712 }
1713
1714 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
1715 self.search_task.take();
1716 self.search_bar.update(cx, |editor, cx| {
1717 editor.set_text(search_query, window, cx);
1718 });
1719 self.update_matches(cx);
1720 }
1721
1722 fn assert_search_results(&self, other: &Self) {
1723 // page index could be different because of filtered out pages
1724 #[derive(Debug, PartialEq)]
1725 struct EntryMinimal {
1726 is_root: bool,
1727 title: &'static str,
1728 }
1729 pretty_assertions::assert_eq!(
1730 other
1731 .visible_navbar_entries()
1732 .map(|(_, entry)| EntryMinimal {
1733 is_root: entry.is_root,
1734 title: entry.title,
1735 })
1736 .collect::<Vec<_>>(),
1737 self.visible_navbar_entries()
1738 .map(|(_, entry)| EntryMinimal {
1739 is_root: entry.is_root,
1740 title: entry.title,
1741 })
1742 .collect::<Vec<_>>(),
1743 );
1744 assert_eq!(
1745 self.current_page().items.iter().collect::<Vec<_>>(),
1746 other.page_items().collect::<Vec<_>>()
1747 );
1748 }
1749 }
1750
1751 impl SettingsPage {
1752 fn item(mut self, item: SettingsPageItem) -> Self {
1753 self.items.push(item);
1754 self
1755 }
1756 }
1757
1758 impl SettingsPageItem {
1759 fn basic_item(title: &'static str, description: &'static str) -> Self {
1760 SettingsPageItem::SettingItem(SettingItem {
1761 title,
1762 description,
1763 field: Box::new(SettingField {
1764 pick: |settings_content| &settings_content.auto_update,
1765 pick_mut: |settings_content| &mut settings_content.auto_update,
1766 }),
1767 metadata: None,
1768 })
1769 }
1770 }
1771
1772 fn register_settings(cx: &mut App) {
1773 settings::init(cx);
1774 theme::init(theme::LoadThemes::JustBase, cx);
1775 workspace::init_settings(cx);
1776 project::Project::init_settings(cx);
1777 language::init(cx);
1778 editor::init(cx);
1779 menu::init();
1780 }
1781
1782 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
1783 let mut pages: Vec<SettingsPage> = Vec::new();
1784 let mut expanded_pages = Vec::new();
1785 let mut selected_idx = None;
1786 let mut index = 0;
1787 let mut in_expanded_section = false;
1788
1789 for mut line in input
1790 .lines()
1791 .map(|line| line.trim())
1792 .filter(|line| !line.is_empty())
1793 {
1794 if let Some(pre) = line.strip_suffix('*') {
1795 assert!(selected_idx.is_none(), "Only one selected entry allowed");
1796 selected_idx = Some(index);
1797 line = pre;
1798 }
1799 let (kind, title) = line.split_once(" ").unwrap();
1800 assert_eq!(kind.len(), 1);
1801 let kind = kind.chars().next().unwrap();
1802 if kind == 'v' {
1803 let page_idx = pages.len();
1804 expanded_pages.push(page_idx);
1805 pages.push(SettingsPage {
1806 title,
1807 items: vec![],
1808 });
1809 index += 1;
1810 in_expanded_section = true;
1811 } else if kind == '>' {
1812 pages.push(SettingsPage {
1813 title,
1814 items: vec![],
1815 });
1816 index += 1;
1817 in_expanded_section = false;
1818 } else if kind == '-' {
1819 pages
1820 .last_mut()
1821 .unwrap()
1822 .items
1823 .push(SettingsPageItem::SectionHeader(title));
1824 if selected_idx == Some(index) && !in_expanded_section {
1825 panic!("Items in unexpanded sections cannot be selected");
1826 }
1827 index += 1;
1828 } else {
1829 panic!(
1830 "Entries must start with one of 'v', '>', or '-'\n line: {}",
1831 line
1832 );
1833 }
1834 }
1835
1836 let mut settings_window = SettingsWindow {
1837 files: Vec::default(),
1838 current_file: crate::SettingsUiFile::User,
1839 pages,
1840 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
1841 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
1842 navbar_entries: Vec::default(),
1843 list_handle: UniformListScrollHandle::default(),
1844 search_matches: vec![],
1845 search_task: None,
1846 scroll_handle: ScrollHandle::new(),
1847 navbar_focus_handle: cx.focus_handle(),
1848 content_focus_handle: cx.focus_handle(),
1849 files_focus_handle: cx.focus_handle(),
1850 };
1851
1852 settings_window.build_search_matches();
1853 settings_window.build_navbar();
1854 for expanded_page_index in expanded_pages {
1855 for entry in &mut settings_window.navbar_entries {
1856 if entry.page_index == expanded_page_index && entry.is_root {
1857 entry.expanded = true;
1858 }
1859 }
1860 }
1861 settings_window
1862 }
1863
1864 #[track_caller]
1865 fn check_navbar_toggle(
1866 before: &'static str,
1867 toggle_page: &'static str,
1868 after: &'static str,
1869 window: &mut Window,
1870 cx: &mut App,
1871 ) {
1872 let mut settings_window = parse(before, window, cx);
1873 let toggle_page_idx = settings_window
1874 .pages
1875 .iter()
1876 .position(|page| page.title == toggle_page)
1877 .expect("page not found");
1878 let toggle_idx = settings_window
1879 .navbar_entries
1880 .iter()
1881 .position(|entry| entry.page_index == toggle_page_idx)
1882 .expect("page not found");
1883 settings_window.toggle_navbar_entry(toggle_idx);
1884
1885 let expected_settings_window = parse(after, window, cx);
1886
1887 pretty_assertions::assert_eq!(
1888 settings_window
1889 .visible_navbar_entries()
1890 .map(|(_, entry)| entry)
1891 .collect::<Vec<_>>(),
1892 expected_settings_window
1893 .visible_navbar_entries()
1894 .map(|(_, entry)| entry)
1895 .collect::<Vec<_>>(),
1896 );
1897 pretty_assertions::assert_eq!(
1898 settings_window.navbar_entries[settings_window.navbar_entry()],
1899 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
1900 );
1901 }
1902
1903 macro_rules! check_navbar_toggle {
1904 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
1905 #[gpui::test]
1906 fn $name(cx: &mut gpui::TestAppContext) {
1907 let window = cx.add_empty_window();
1908 window.update(|window, cx| {
1909 register_settings(cx);
1910 check_navbar_toggle($before, $toggle_page, $after, window, cx);
1911 });
1912 }
1913 };
1914 }
1915
1916 check_navbar_toggle!(
1917 navbar_basic_open,
1918 before: r"
1919 v General
1920 - General
1921 - Privacy*
1922 v Project
1923 - Project Settings
1924 ",
1925 toggle_page: "General",
1926 after: r"
1927 > General*
1928 v Project
1929 - Project Settings
1930 "
1931 );
1932
1933 check_navbar_toggle!(
1934 navbar_basic_close,
1935 before: r"
1936 > General*
1937 - General
1938 - Privacy
1939 v Project
1940 - Project Settings
1941 ",
1942 toggle_page: "General",
1943 after: r"
1944 v General*
1945 - General
1946 - Privacy
1947 v Project
1948 - Project Settings
1949 "
1950 );
1951
1952 check_navbar_toggle!(
1953 navbar_basic_second_root_entry_close,
1954 before: r"
1955 > General
1956 - General
1957 - Privacy
1958 v Project
1959 - Project Settings*
1960 ",
1961 toggle_page: "Project",
1962 after: r"
1963 > General
1964 > Project*
1965 "
1966 );
1967
1968 check_navbar_toggle!(
1969 navbar_toggle_subroot,
1970 before: r"
1971 v General Page
1972 - General
1973 - Privacy
1974 v Project
1975 - Worktree Settings Content*
1976 v AI
1977 - General
1978 > Appearance & Behavior
1979 ",
1980 toggle_page: "Project",
1981 after: r"
1982 v General Page
1983 - General
1984 - Privacy
1985 > Project*
1986 v AI
1987 - General
1988 > Appearance & Behavior
1989 "
1990 );
1991
1992 check_navbar_toggle!(
1993 navbar_toggle_close_propagates_selected_index,
1994 before: r"
1995 v General Page
1996 - General
1997 - Privacy
1998 v Project
1999 - Worktree Settings Content
2000 v AI
2001 - General*
2002 > Appearance & Behavior
2003 ",
2004 toggle_page: "General Page",
2005 after: r"
2006 > General Page
2007 v Project
2008 - Worktree Settings Content
2009 v AI
2010 - General*
2011 > Appearance & Behavior
2012 "
2013 );
2014
2015 check_navbar_toggle!(
2016 navbar_toggle_expand_propagates_selected_index,
2017 before: r"
2018 > General Page
2019 - General
2020 - Privacy
2021 v Project
2022 - Worktree Settings Content
2023 v AI
2024 - General*
2025 > Appearance & Behavior
2026 ",
2027 toggle_page: "General Page",
2028 after: r"
2029 v General Page
2030 - General
2031 - Privacy
2032 v Project
2033 - Worktree Settings Content
2034 v AI
2035 - General*
2036 > Appearance & Behavior
2037 "
2038 );
2039
2040 #[gpui::test]
2041 fn test_basic_search(cx: &mut gpui::TestAppContext) {
2042 let cx = cx.add_empty_window();
2043 let (actual, expected) = cx.update(|window, cx| {
2044 register_settings(cx);
2045
2046 let expected = cx.new(|cx| {
2047 SettingsWindow::new_builder(window, cx)
2048 .add_page("General", |page| {
2049 page.item(SettingsPageItem::SectionHeader("General settings"))
2050 .item(SettingsPageItem::basic_item("test title", "General test"))
2051 })
2052 .build()
2053 });
2054
2055 let actual = cx.new(|cx| {
2056 SettingsWindow::new_builder(window, cx)
2057 .add_page("General", |page| {
2058 page.item(SettingsPageItem::SectionHeader("General settings"))
2059 .item(SettingsPageItem::basic_item("test title", "General test"))
2060 })
2061 .add_page("Theme", |page| {
2062 page.item(SettingsPageItem::SectionHeader("Theme settings"))
2063 })
2064 .build()
2065 });
2066
2067 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2068
2069 (actual, expected)
2070 });
2071
2072 cx.cx.run_until_parked();
2073
2074 cx.update(|_window, cx| {
2075 let expected = expected.read(cx);
2076 let actual = actual.read(cx);
2077 expected.assert_search_results(&actual);
2078 })
2079 }
2080
2081 #[gpui::test]
2082 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2083 let cx = cx.add_empty_window();
2084 let (actual, expected) = cx.update(|window, cx| {
2085 register_settings(cx);
2086
2087 let actual = cx.new(|cx| {
2088 SettingsWindow::new_builder(window, cx)
2089 .add_page("General", |page| {
2090 page.item(SettingsPageItem::SectionHeader("General settings"))
2091 .item(SettingsPageItem::basic_item(
2092 "Confirm Quit",
2093 "Whether to confirm before quitting Zed",
2094 ))
2095 .item(SettingsPageItem::basic_item(
2096 "Auto Update",
2097 "Automatically update Zed",
2098 ))
2099 })
2100 .add_page("AI", |page| {
2101 page.item(SettingsPageItem::basic_item(
2102 "Disable AI",
2103 "Whether to disable all AI features in Zed",
2104 ))
2105 })
2106 .add_page("Appearance & Behavior", |page| {
2107 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2108 SettingsPageItem::basic_item(
2109 "Cursor Shape",
2110 "Cursor shape for the editor",
2111 ),
2112 )
2113 })
2114 .build()
2115 });
2116
2117 let expected = cx.new(|cx| {
2118 SettingsWindow::new_builder(window, cx)
2119 .add_page("Appearance & Behavior", |page| {
2120 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2121 SettingsPageItem::basic_item(
2122 "Cursor Shape",
2123 "Cursor shape for the editor",
2124 ),
2125 )
2126 })
2127 .build()
2128 });
2129
2130 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2131
2132 (actual, expected)
2133 });
2134
2135 cx.cx.run_until_parked();
2136
2137 cx.update(|_window, cx| {
2138 let expected = expected.read(cx);
2139 let actual = actual.read(cx);
2140 expected.assert_search_results(&actual);
2141 })
2142 }
2143}