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