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