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