settings_ui.rs

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