settings_ui.rs

   1mod components;
   2mod page_data;
   3
   4use anyhow::Result;
   5use editor::{Editor, EditorEvent};
   6use feature_flags::FeatureFlag;
   7use fuzzy::StringMatchCandidate;
   8use gpui::{
   9    Action, App, Div, Entity, FocusHandle, Focusable, FontWeight, Global, ReadGlobal as _,
  10    ScrollHandle, Stateful, Subscription, Task, TitlebarOptions, UniformListScrollHandle, Window,
  11    WindowBounds, WindowHandle, WindowOptions, actions, div, point, prelude::*, px, size,
  12    uniform_list,
  13};
  14use heck::ToTitleCase as _;
  15use project::WorktreeId;
  16use schemars::JsonSchema;
  17use serde::Deserialize;
  18use settings::{SettingsContent, SettingsStore};
  19use std::{
  20    any::{Any, TypeId, type_name},
  21    cell::RefCell,
  22    collections::HashMap,
  23    num::{NonZero, NonZeroU32},
  24    ops::Range,
  25    rc::Rc,
  26    sync::{Arc, LazyLock, RwLock},
  27};
  28use title_bar::platform_title_bar::PlatformTitleBar;
  29use ui::{
  30    ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape, KeyBinding,
  31    KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem, WithScrollbar,
  32    prelude::*,
  33};
  34use ui_input::{NumberField, NumberFieldType};
  35use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
  36use workspace::{OpenOptions, OpenVisible, Workspace, client_side_decorations};
  37use zed_actions::OpenSettingsEditor;
  38
  39use crate::components::SettingsEditor;
  40
  41const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
  42const NAVBAR_GROUP_TAB_INDEX: isize = 1;
  43
  44const HEADER_CONTAINER_TAB_INDEX: isize = 2;
  45const HEADER_GROUP_TAB_INDEX: isize = 3;
  46
  47const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
  48const CONTENT_GROUP_TAB_INDEX: isize = 5;
  49
  50actions!(
  51    settings_editor,
  52    [
  53        /// Minimizes the settings UI window.
  54        Minimize,
  55        /// Toggles focus between the navbar and the main content.
  56        ToggleFocusNav,
  57        /// Expands the navigation entry.
  58        ExpandNavEntry,
  59        /// Collapses the navigation entry.
  60        CollapseNavEntry,
  61        /// Focuses the next file in the file list.
  62        FocusNextFile,
  63        /// Focuses the previous file in the file list.
  64        FocusPreviousFile,
  65        /// Opens an editor for the current file
  66        OpenCurrentFile,
  67        /// Focuses the previous root navigation entry.
  68        FocusPreviousRootNavEntry,
  69        /// Focuses the next root navigation entry.
  70        FocusNextRootNavEntry,
  71        /// Focuses the first navigation entry.
  72        FocusFirstNavEntry,
  73        /// Focuses the last navigation entry.
  74        FocusLastNavEntry,
  75        /// Focuses and opens the next navigation entry without moving focus to content.
  76        FocusNextNavEntry,
  77        /// Focuses and opens the previous navigation entry without moving focus to content.
  78        FocusPreviousNavEntry
  79    ]
  80);
  81
  82#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
  83#[action(namespace = settings_editor)]
  84struct FocusFile(pub u32);
  85
  86struct SettingField<T: 'static> {
  87    pick: fn(&SettingsContent) -> &Option<T>,
  88    pick_mut: fn(&mut SettingsContent) -> &mut Option<T>,
  89}
  90
  91impl<T: 'static> Clone for SettingField<T> {
  92    fn clone(&self) -> Self {
  93        *self
  94    }
  95}
  96
  97// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
  98impl<T: 'static> Copy for SettingField<T> {}
  99
 100/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
 101/// to keep the setting around in the UI with valid pick and pick_mut implementations, but don't actually try to render it.
 102/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
 103#[derive(Clone, Copy)]
 104struct UnimplementedSettingField;
 105
 106impl PartialEq for UnimplementedSettingField {
 107    fn eq(&self, _other: &Self) -> bool {
 108        true
 109    }
 110}
 111
 112impl<T: 'static> SettingField<T> {
 113    /// Helper for settings with types that are not yet implemented.
 114    #[allow(unused)]
 115    fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
 116        SettingField {
 117            pick: |_| &Some(UnimplementedSettingField),
 118            pick_mut: |_| unreachable!(),
 119        }
 120    }
 121}
 122
 123trait AnySettingField {
 124    fn as_any(&self) -> &dyn Any;
 125    fn type_name(&self) -> &'static str;
 126    fn type_id(&self) -> TypeId;
 127    // 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)
 128    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
 129    fn reset_to_default_fn(
 130        &self,
 131        current_file: &SettingsUiFile,
 132        file_set_in: &settings::SettingsFile,
 133        cx: &App,
 134    ) -> Option<Box<dyn Fn(&mut App)>>;
 135}
 136
 137impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
 138    fn as_any(&self) -> &dyn Any {
 139        self
 140    }
 141
 142    fn type_name(&self) -> &'static str {
 143        type_name::<T>()
 144    }
 145
 146    fn type_id(&self) -> TypeId {
 147        TypeId::of::<T>()
 148    }
 149
 150    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
 151        let (file, value) = cx
 152            .global::<SettingsStore>()
 153            .get_value_from_file(file.to_settings(), self.pick);
 154        return (file, value.is_some());
 155    }
 156
 157    fn reset_to_default_fn(
 158        &self,
 159        current_file: &SettingsUiFile,
 160        file_set_in: &settings::SettingsFile,
 161        cx: &App,
 162    ) -> Option<Box<dyn Fn(&mut App)>> {
 163        if file_set_in == &settings::SettingsFile::Default {
 164            return None;
 165        }
 166        let this = *self;
 167        let store = SettingsStore::global(cx);
 168        let default_value = (this.pick)(store.raw_default_settings());
 169        let is_default = store
 170            .get_content_for_file(file_set_in.clone())
 171            .map_or(&None, this.pick)
 172            == default_value;
 173        if is_default {
 174            return None;
 175        }
 176        let current_file = current_file.clone();
 177
 178        return Some(Box::new(move |cx| {
 179            let store = SettingsStore::global(cx);
 180            let default_value = (this.pick)(store.raw_default_settings());
 181            let is_set_somewhere_other_than_default = store
 182                .get_value_up_to_file(current_file.to_settings(), this.pick)
 183                .0
 184                != settings::SettingsFile::Default;
 185            let value_to_set = if is_set_somewhere_other_than_default {
 186                default_value.clone()
 187            } else {
 188                None
 189            };
 190            update_settings_file(current_file.clone(), cx, move |settings, _| {
 191                *(this.pick_mut)(settings) = value_to_set;
 192            })
 193            // todo(settings_ui): Don't log err
 194            .log_err();
 195        }));
 196    }
 197}
 198
 199#[derive(Default, Clone)]
 200struct SettingFieldRenderer {
 201    renderers: Rc<
 202        RefCell<
 203            HashMap<
 204                TypeId,
 205                Box<
 206                    dyn Fn(
 207                        &SettingsWindow,
 208                        &SettingItem,
 209                        SettingsUiFile,
 210                        Option<&SettingsFieldMetadata>,
 211                        &mut Window,
 212                        &mut Context<SettingsWindow>,
 213                    ) -> Stateful<Div>,
 214                >,
 215            >,
 216        >,
 217    >,
 218}
 219
 220impl Global for SettingFieldRenderer {}
 221
 222impl SettingFieldRenderer {
 223    fn add_basic_renderer<T: 'static>(
 224        &mut self,
 225        render_control: impl Fn(
 226            SettingField<T>,
 227            SettingsUiFile,
 228            Option<&SettingsFieldMetadata>,
 229            &mut Window,
 230            &mut App,
 231        ) -> AnyElement
 232        + 'static,
 233    ) -> &mut Self {
 234        self.add_renderer(
 235            move |settings_window: &SettingsWindow,
 236                  item: &SettingItem,
 237                  field: SettingField<T>,
 238                  settings_file: SettingsUiFile,
 239                  metadata: Option<&SettingsFieldMetadata>,
 240                  window: &mut Window,
 241                  cx: &mut Context<SettingsWindow>| {
 242                render_settings_item(
 243                    settings_window,
 244                    item,
 245                    settings_file.clone(),
 246                    render_control(field, settings_file, metadata, window, cx),
 247                    window,
 248                    cx,
 249                )
 250            },
 251        )
 252    }
 253
 254    fn add_renderer<T: 'static>(
 255        &mut self,
 256        renderer: impl Fn(
 257            &SettingsWindow,
 258            &SettingItem,
 259            SettingField<T>,
 260            SettingsUiFile,
 261            Option<&SettingsFieldMetadata>,
 262            &mut Window,
 263            &mut Context<SettingsWindow>,
 264        ) -> Stateful<Div>
 265        + 'static,
 266    ) -> &mut Self {
 267        let key = TypeId::of::<T>();
 268        let renderer = Box::new(
 269            move |settings_window: &SettingsWindow,
 270                  item: &SettingItem,
 271                  settings_file: SettingsUiFile,
 272                  metadata: Option<&SettingsFieldMetadata>,
 273                  window: &mut Window,
 274                  cx: &mut Context<SettingsWindow>| {
 275                let field = *item
 276                    .field
 277                    .as_ref()
 278                    .as_any()
 279                    .downcast_ref::<SettingField<T>>()
 280                    .unwrap();
 281                renderer(
 282                    settings_window,
 283                    item,
 284                    field,
 285                    settings_file,
 286                    metadata,
 287                    window,
 288                    cx,
 289                )
 290            },
 291        );
 292        self.renderers.borrow_mut().insert(key, renderer);
 293        self
 294    }
 295}
 296
 297struct NonFocusableHandle {
 298    handle: FocusHandle,
 299    _subscription: Subscription,
 300}
 301
 302impl NonFocusableHandle {
 303    fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
 304        let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
 305        Self::from_handle(handle, window, cx)
 306    }
 307
 308    fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
 309        cx.new(|cx| {
 310            let _subscription = cx.on_focus(&handle, window, {
 311                move |_, window, _| {
 312                    window.focus_next();
 313                }
 314            });
 315            Self {
 316                handle,
 317                _subscription,
 318            }
 319        })
 320    }
 321}
 322
 323impl Focusable for NonFocusableHandle {
 324    fn focus_handle(&self, _: &App) -> FocusHandle {
 325        self.handle.clone()
 326    }
 327}
 328
 329#[derive(Default)]
 330struct SettingsFieldMetadata {
 331    placeholder: Option<&'static str>,
 332    should_do_titlecase: Option<bool>,
 333}
 334
 335pub struct SettingsUiFeatureFlag;
 336
 337impl FeatureFlag for SettingsUiFeatureFlag {
 338    const NAME: &'static str = "settings-ui";
 339}
 340
 341pub fn init(cx: &mut App) {
 342    init_renderers(cx);
 343
 344    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 345        workspace.register_action(|workspace, _: &OpenSettingsEditor, window, cx| {
 346            let window_handle = window
 347                .window_handle()
 348                .downcast::<Workspace>()
 349                .expect("Workspaces are root Windows");
 350            open_settings_editor(workspace, window_handle, cx);
 351        });
 352    })
 353    .detach();
 354}
 355
 356fn init_renderers(cx: &mut App) {
 357    cx.default_global::<SettingFieldRenderer>()
 358        .add_basic_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
 359            Button::new("open-in-settings-file", "Edit in settings.json")
 360                .style(ButtonStyle::Outlined)
 361                .size(ButtonSize::Medium)
 362                .tab_index(0_isize)
 363                .on_click(|_, window, cx| {
 364                    window.dispatch_action(Box::new(OpenCurrentFile), cx);
 365                })
 366                .into_any_element()
 367        })
 368        .add_basic_renderer::<bool>(render_toggle_button)
 369        .add_basic_renderer::<String>(render_text_field)
 370        .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
 371        .add_basic_renderer::<settings::CursorShape>(render_dropdown)
 372        .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
 373        .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
 374        .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
 375        .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
 376        .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
 377        // todo(settings_ui): This needs custom ui
 378        // .add_renderer::<settings::BufferLineHeight>(|settings_field, file, _, window, cx| {
 379        //     // todo(settings_ui): Do we want to expose the custom variant of buffer line height?
 380        //     // right now there's a manual impl of strum::VariantArray
 381        //     render_dropdown(*settings_field, file, window, cx)
 382        // })
 383        .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
 384        .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
 385        .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
 386        .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
 387        .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
 388        .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
 389        .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
 390        .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
 391        .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
 392        .add_basic_renderer::<settings::DockSide>(render_dropdown)
 393        .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
 394        .add_basic_renderer::<settings::DockPosition>(render_dropdown)
 395        .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
 396        .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
 397        .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
 398        .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
 399        .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
 400        .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
 401        .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
 402        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 403        .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
 404        .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
 405        .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
 406        .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
 407        .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
 408        .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
 409        .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
 410        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 411        .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
 412        .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
 413        .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
 414        .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
 415        .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
 416        .add_basic_renderer::<f32>(render_number_field)
 417        .add_basic_renderer::<u32>(render_number_field)
 418        .add_basic_renderer::<u64>(render_number_field)
 419        .add_basic_renderer::<usize>(render_number_field)
 420        .add_basic_renderer::<NonZero<usize>>(render_number_field)
 421        .add_basic_renderer::<NonZeroU32>(render_number_field)
 422        .add_basic_renderer::<settings::CodeFade>(render_number_field)
 423        .add_basic_renderer::<FontWeight>(render_number_field)
 424        .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
 425        .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
 426        .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
 427        .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
 428        .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
 429        .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
 430        .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
 431        .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
 432        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 433        .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
 434        .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
 435        .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
 436        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 437        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 438        .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
 439    // please semicolon stay on next line
 440    ;
 441    // .add_renderer::<ThemeSelection>(|settings_field, file, _, window, cx| {
 442    //     render_dropdown(*settings_field, file, window, cx)
 443    // });
 444}
 445
 446pub fn open_settings_editor(
 447    _workspace: &mut Workspace,
 448    workspace_handle: WindowHandle<Workspace>,
 449    cx: &mut App,
 450) {
 451    let existing_window = cx
 452        .windows()
 453        .into_iter()
 454        .find_map(|window| window.downcast::<SettingsWindow>());
 455
 456    if let Some(existing_window) = existing_window {
 457        existing_window
 458            .update(cx, |settings_window, window, _| {
 459                settings_window.original_window = Some(workspace_handle);
 460                window.activate_window();
 461            })
 462            .ok();
 463        return;
 464    }
 465
 466    // We have to defer this to get the workspace off the stack.
 467
 468    cx.defer(move |cx| {
 469        cx.open_window(
 470            WindowOptions {
 471                titlebar: Some(TitlebarOptions {
 472                    title: Some("Settings Window".into()),
 473                    appears_transparent: true,
 474                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 475                }),
 476                focus: true,
 477                show: true,
 478                is_movable: true,
 479                kind: gpui::WindowKind::Floating,
 480                window_background: cx.theme().window_background_appearance(),
 481                window_min_size: Some(size(px(900.), px(750.))), // 4:3 Aspect Ratio
 482                window_bounds: Some(WindowBounds::centered(size(px(900.), px(750.)), cx)),
 483                ..Default::default()
 484            },
 485            |window, cx| cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx)),
 486        )
 487        .log_err();
 488    });
 489}
 490
 491/// The current sub page path that is selected.
 492/// If this is empty the selected page is rendered,
 493/// otherwise the last sub page gets rendered.
 494///
 495/// Global so that `pick` and `pick_mut` callbacks can access it
 496/// and use it to dynamically render sub pages (e.g. for language settings)
 497static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
 498
 499fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
 500    SUB_PAGE_STACK
 501        .read()
 502        .expect("SUB_PAGE_STACK is never poisoned")
 503}
 504
 505fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
 506    SUB_PAGE_STACK
 507        .write()
 508        .expect("SUB_PAGE_STACK is never poisoned")
 509}
 510
 511pub struct SettingsWindow {
 512    title_bar: Option<Entity<PlatformTitleBar>>,
 513    original_window: Option<WindowHandle<Workspace>>,
 514    files: Vec<(SettingsUiFile, FocusHandle)>,
 515    worktree_root_dirs: HashMap<WorktreeId, String>,
 516    current_file: SettingsUiFile,
 517    pages: Vec<SettingsPage>,
 518    search_bar: Entity<Editor>,
 519    search_task: Option<Task<()>>,
 520    /// Index into navbar_entries
 521    navbar_entry: usize,
 522    navbar_entries: Vec<NavBarEntry>,
 523    navbar_scroll_handle: UniformListScrollHandle,
 524    /// [page_index][page_item_index] will be false
 525    /// when the item is filtered out either by searches
 526    /// or by the current file
 527    navbar_focus_subscriptions: Vec<gpui::Subscription>,
 528    filter_table: Vec<Vec<bool>>,
 529    has_query: bool,
 530    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 531    page_scroll_handle: ScrollHandle,
 532    focus_handle: FocusHandle,
 533    navbar_focus_handle: Entity<NonFocusableHandle>,
 534    content_focus_handle: Entity<NonFocusableHandle>,
 535    files_focus_handle: FocusHandle,
 536    search_index: Option<Arc<SearchIndex>>,
 537}
 538
 539struct SearchIndex {
 540    bm25_engine: bm25::SearchEngine<usize>,
 541    fuzzy_match_candidates: Vec<StringMatchCandidate>,
 542    key_lut: Vec<SearchItemKey>,
 543}
 544
 545struct SearchItemKey {
 546    page_index: usize,
 547    header_index: usize,
 548    item_index: usize,
 549}
 550
 551struct SubPage {
 552    link: SubPageLink,
 553    section_header: &'static str,
 554}
 555
 556#[derive(Debug)]
 557struct NavBarEntry {
 558    title: &'static str,
 559    is_root: bool,
 560    expanded: bool,
 561    page_index: usize,
 562    item_index: Option<usize>,
 563    focus_handle: FocusHandle,
 564}
 565
 566struct SettingsPage {
 567    title: &'static str,
 568    items: Vec<SettingsPageItem>,
 569}
 570
 571#[derive(PartialEq)]
 572enum SettingsPageItem {
 573    SectionHeader(&'static str),
 574    SettingItem(SettingItem),
 575    SubPageLink(SubPageLink),
 576}
 577
 578impl std::fmt::Debug for SettingsPageItem {
 579    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 580        match self {
 581            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 582            SettingsPageItem::SettingItem(setting_item) => {
 583                write!(f, "SettingItem({})", setting_item.title)
 584            }
 585            SettingsPageItem::SubPageLink(sub_page_link) => {
 586                write!(f, "SubPageLink({})", sub_page_link.title)
 587            }
 588        }
 589    }
 590}
 591
 592impl SettingsPageItem {
 593    fn render(
 594        &self,
 595        settings_window: &SettingsWindow,
 596        section_header: &'static str,
 597        is_last: bool,
 598        window: &mut Window,
 599        cx: &mut Context<SettingsWindow>,
 600    ) -> AnyElement {
 601        let file = settings_window.current_file.clone();
 602        match self {
 603            SettingsPageItem::SectionHeader(header) => v_flex()
 604                .w_full()
 605                .gap_1p5()
 606                .child(
 607                    Label::new(SharedString::new_static(header))
 608                        .size(LabelSize::Small)
 609                        .color(Color::Muted)
 610                        .buffer_font(cx),
 611                )
 612                .child(Divider::horizontal().color(DividerColor::BorderFaded))
 613                .into_any_element(),
 614            SettingsPageItem::SettingItem(setting_item) => {
 615                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 616                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 617
 618                let renderers = renderer.renderers.borrow();
 619                let field_renderer =
 620                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 621                let field_renderer_or_warning =
 622                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 623                        if cfg!(debug_assertions) && !found {
 624                            Err("NO DEFAULT")
 625                        } else {
 626                            Ok(renderer)
 627                        }
 628                    });
 629
 630                let field = match field_renderer_or_warning {
 631                    Ok(field_renderer) => field_renderer(
 632                        settings_window,
 633                        setting_item,
 634                        file,
 635                        setting_item.metadata.as_deref(),
 636                        window,
 637                        cx,
 638                    ),
 639                    Err(warning) => render_settings_item(
 640                        settings_window,
 641                        setting_item,
 642                        file,
 643                        Button::new("error-warning", warning)
 644                            .style(ButtonStyle::Outlined)
 645                            .size(ButtonSize::Medium)
 646                            .icon(Some(IconName::Debug))
 647                            .icon_position(IconPosition::Start)
 648                            .icon_color(Color::Error)
 649                            .tab_index(0_isize)
 650                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 651                            .into_any_element(),
 652                        window,
 653                        cx,
 654                    ),
 655                };
 656
 657                field
 658                    .pt_4()
 659                    .map(|this| {
 660                        if is_last {
 661                            this.pb_10()
 662                        } else {
 663                            this.pb_4()
 664                                .border_b_1()
 665                                .border_color(cx.theme().colors().border_variant)
 666                        }
 667                    })
 668                    .into_any_element()
 669            }
 670            SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
 671                .id(sub_page_link.title.clone())
 672                .w_full()
 673                .min_w_0()
 674                .gap_2()
 675                .justify_between()
 676                .pt_4()
 677                .map(|this| {
 678                    if is_last {
 679                        this.pb_10()
 680                    } else {
 681                        this.pb_4()
 682                            .border_b_1()
 683                            .border_color(cx.theme().colors().border_variant)
 684                    }
 685                })
 686                .child(
 687                    v_flex()
 688                        .w_full()
 689                        .max_w_1_2()
 690                        .child(Label::new(sub_page_link.title.clone())),
 691                )
 692                .child(
 693                    Button::new(
 694                        ("sub-page".into(), sub_page_link.title.clone()),
 695                        "Configure",
 696                    )
 697                    .icon(IconName::ChevronRight)
 698                    .tab_index(0_isize)
 699                    .icon_position(IconPosition::End)
 700                    .icon_color(Color::Muted)
 701                    .icon_size(IconSize::Small)
 702                    .style(ButtonStyle::Outlined)
 703                    .size(ButtonSize::Medium)
 704                    .on_click({
 705                        let sub_page_link = sub_page_link.clone();
 706                        cx.listener(move |this, _, _, cx| {
 707                            this.push_sub_page(sub_page_link.clone(), section_header, cx)
 708                        })
 709                    }),
 710                )
 711                .into_any_element(),
 712        }
 713    }
 714}
 715
 716fn render_settings_item(
 717    settings_window: &SettingsWindow,
 718    setting_item: &SettingItem,
 719    file: SettingsUiFile,
 720    control: AnyElement,
 721    _window: &mut Window,
 722    cx: &mut Context<'_, SettingsWindow>,
 723) -> Stateful<Div> {
 724    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
 725    let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
 726
 727    h_flex()
 728        .id(setting_item.title)
 729        .min_w_0()
 730        .gap_2()
 731        .justify_between()
 732        .child(
 733            v_flex()
 734                .w_1_2()
 735                .child(
 736                    h_flex()
 737                        .w_full()
 738                        .gap_1()
 739                        .child(Label::new(SharedString::new_static(setting_item.title)))
 740                        .when_some(
 741                            setting_item
 742                                .field
 743                                .reset_to_default_fn(&file, &found_in_file, cx)
 744                                .filter(|_| file_set_in.as_ref() == Some(&file)),
 745                            |this, reset_to_default| {
 746                                this.child(
 747                                    IconButton::new("reset-to-default-btn", IconName::Undo)
 748                                        .icon_color(Color::Muted)
 749                                        .icon_size(IconSize::Small)
 750                                        .tooltip(Tooltip::text("Reset to Default"))
 751                                        .on_click({
 752                                            move |_, _, cx| {
 753                                                reset_to_default(cx);
 754                                            }
 755                                        }),
 756                                )
 757                            },
 758                        )
 759                        .when_some(
 760                            file_set_in.filter(|file_set_in| file_set_in != &file),
 761                            |this, file_set_in| {
 762                                this.child(
 763                                    Label::new(format!(
 764                                        "—  Modified in {}",
 765                                        settings_window
 766                                            .display_name(&file_set_in)
 767                                            .expect("File name should exist")
 768                                    ))
 769                                    .color(Color::Muted)
 770                                    .size(LabelSize::Small),
 771                                )
 772                            },
 773                        ),
 774                )
 775                .child(
 776                    Label::new(SharedString::new_static(setting_item.description))
 777                        .size(LabelSize::Small)
 778                        .color(Color::Muted),
 779                ),
 780        )
 781        .child(control)
 782}
 783
 784struct SettingItem {
 785    title: &'static str,
 786    description: &'static str,
 787    field: Box<dyn AnySettingField>,
 788    metadata: Option<Box<SettingsFieldMetadata>>,
 789    files: FileMask,
 790}
 791
 792#[derive(PartialEq, Eq, Clone, Copy)]
 793struct FileMask(u8);
 794
 795impl std::fmt::Debug for FileMask {
 796    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 797        write!(f, "FileMask(")?;
 798        let mut items = vec![];
 799
 800        if self.contains(USER) {
 801            items.push("USER");
 802        }
 803        if self.contains(LOCAL) {
 804            items.push("LOCAL");
 805        }
 806        if self.contains(SERVER) {
 807            items.push("SERVER");
 808        }
 809
 810        write!(f, "{})", items.join(" | "))
 811    }
 812}
 813
 814const USER: FileMask = FileMask(1 << 0);
 815const LOCAL: FileMask = FileMask(1 << 2);
 816const SERVER: FileMask = FileMask(1 << 3);
 817
 818impl std::ops::BitAnd for FileMask {
 819    type Output = Self;
 820
 821    fn bitand(self, other: Self) -> Self {
 822        Self(self.0 & other.0)
 823    }
 824}
 825
 826impl std::ops::BitOr for FileMask {
 827    type Output = Self;
 828
 829    fn bitor(self, other: Self) -> Self {
 830        Self(self.0 | other.0)
 831    }
 832}
 833
 834impl FileMask {
 835    fn contains(&self, other: FileMask) -> bool {
 836        self.0 & other.0 != 0
 837    }
 838}
 839
 840impl PartialEq for SettingItem {
 841    fn eq(&self, other: &Self) -> bool {
 842        self.title == other.title
 843            && self.description == other.description
 844            && (match (&self.metadata, &other.metadata) {
 845                (None, None) => true,
 846                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
 847                _ => false,
 848            })
 849    }
 850}
 851
 852#[derive(Clone)]
 853struct SubPageLink {
 854    title: SharedString,
 855    files: FileMask,
 856    render: Arc<
 857        dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
 858            + 'static
 859            + Send
 860            + Sync,
 861    >,
 862}
 863
 864impl PartialEq for SubPageLink {
 865    fn eq(&self, other: &Self) -> bool {
 866        self.title == other.title
 867    }
 868}
 869
 870fn all_language_names(cx: &App) -> Vec<SharedString> {
 871    workspace::AppState::global(cx)
 872        .upgrade()
 873        .map_or(vec![], |state| {
 874            state
 875                .languages
 876                .language_names()
 877                .into_iter()
 878                .filter(|name| name.as_ref() != "Zed Keybind Context")
 879                .map(Into::into)
 880                .collect()
 881        })
 882}
 883
 884#[allow(unused)]
 885#[derive(Clone, PartialEq)]
 886enum SettingsUiFile {
 887    User,                                // Uses all settings.
 888    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
 889    Server(&'static str),                // Uses a special name, and the user settings
 890}
 891
 892impl SettingsUiFile {
 893    fn is_server(&self) -> bool {
 894        matches!(self, SettingsUiFile::Server(_))
 895    }
 896
 897    fn worktree_id(&self) -> Option<WorktreeId> {
 898        match self {
 899            SettingsUiFile::User => None,
 900            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
 901            SettingsUiFile::Server(_) => None,
 902        }
 903    }
 904
 905    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
 906        Some(match file {
 907            settings::SettingsFile::User => SettingsUiFile::User,
 908            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
 909            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
 910            settings::SettingsFile::Default => return None,
 911        })
 912    }
 913
 914    fn to_settings(&self) -> settings::SettingsFile {
 915        match self {
 916            SettingsUiFile::User => settings::SettingsFile::User,
 917            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
 918            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
 919        }
 920    }
 921
 922    fn mask(&self) -> FileMask {
 923        match self {
 924            SettingsUiFile::User => USER,
 925            SettingsUiFile::Project(_) => LOCAL,
 926            SettingsUiFile::Server(_) => SERVER,
 927        }
 928    }
 929}
 930
 931impl SettingsWindow {
 932    pub fn new(
 933        original_window: Option<WindowHandle<Workspace>>,
 934        window: &mut Window,
 935        cx: &mut Context<Self>,
 936    ) -> Self {
 937        let font_family_cache = theme::FontFamilyCache::global(cx);
 938
 939        cx.spawn(async move |this, cx| {
 940            font_family_cache.prefetch(cx).await;
 941            this.update(cx, |_, cx| {
 942                cx.notify();
 943            })
 944        })
 945        .detach();
 946
 947        let current_file = SettingsUiFile::User;
 948        let search_bar = cx.new(|cx| {
 949            let mut editor = Editor::single_line(window, cx);
 950            editor.set_placeholder_text("Search settings…", window, cx);
 951            editor
 952        });
 953
 954        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
 955            let EditorEvent::Edited { transaction_id: _ } = event else {
 956                return;
 957            };
 958
 959            this.update_matches(cx);
 960        })
 961        .detach();
 962
 963        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
 964            this.fetch_files(window, cx);
 965            cx.notify();
 966        })
 967        .detach();
 968
 969        let title_bar = if !cfg!(target_os = "macos") {
 970            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
 971        } else {
 972            None
 973        };
 974
 975        let mut this = Self {
 976            title_bar,
 977            original_window,
 978            worktree_root_dirs: HashMap::default(),
 979            files: vec![],
 980            current_file: current_file,
 981            pages: vec![],
 982            navbar_entries: vec![],
 983            navbar_entry: 0,
 984            navbar_scroll_handle: UniformListScrollHandle::default(),
 985            search_bar,
 986            search_task: None,
 987            filter_table: vec![],
 988            has_query: false,
 989            content_handles: vec![],
 990            page_scroll_handle: ScrollHandle::new(),
 991            focus_handle: cx.focus_handle(),
 992            navbar_focus_handle: NonFocusableHandle::new(
 993                NAVBAR_CONTAINER_TAB_INDEX,
 994                false,
 995                window,
 996                cx,
 997            ),
 998            navbar_focus_subscriptions: vec![],
 999            content_focus_handle: NonFocusableHandle::new(
1000                CONTENT_CONTAINER_TAB_INDEX,
1001                false,
1002                window,
1003                cx,
1004            ),
1005            files_focus_handle: cx
1006                .focus_handle()
1007                .tab_index(HEADER_CONTAINER_TAB_INDEX)
1008                .tab_stop(false),
1009            search_index: None,
1010        };
1011
1012        this.fetch_files(window, cx);
1013        this.build_ui(window, cx);
1014        this.build_search_index();
1015
1016        this.search_bar.update(cx, |editor, cx| {
1017            editor.focus_handle(cx).focus(window);
1018        });
1019
1020        this
1021    }
1022
1023    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1024        // We can only toggle root entries
1025        if !self.navbar_entries[nav_entry_index].is_root {
1026            return;
1027        }
1028
1029        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1030        *expanded = !*expanded;
1031        let expanded = *expanded;
1032
1033        let toggle_page_index = self.page_index_from_navbar_index(nav_entry_index);
1034        let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
1035        // if currently selected page is a child of the parent page we are folding,
1036        // set the current page to the parent page
1037        if !expanded && selected_page_index == toggle_page_index {
1038            self.navbar_entry = nav_entry_index;
1039            // note: not opening page. Toggling does not change content just selected page
1040        }
1041    }
1042
1043    fn build_navbar(&mut self, cx: &App) {
1044        let mut navbar_entries = Vec::new();
1045
1046        for (page_index, page) in self.pages.iter().enumerate() {
1047            navbar_entries.push(NavBarEntry {
1048                title: page.title,
1049                is_root: true,
1050                expanded: false,
1051                page_index,
1052                item_index: None,
1053                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1054            });
1055
1056            for (item_index, item) in page.items.iter().enumerate() {
1057                let SettingsPageItem::SectionHeader(title) = item else {
1058                    continue;
1059                };
1060                navbar_entries.push(NavBarEntry {
1061                    title,
1062                    is_root: false,
1063                    expanded: false,
1064                    page_index,
1065                    item_index: Some(item_index),
1066                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1067                });
1068            }
1069        }
1070
1071        self.navbar_entries = navbar_entries;
1072    }
1073
1074    fn setup_navbar_focus_subscriptions(
1075        &mut self,
1076        window: &mut Window,
1077        cx: &mut Context<SettingsWindow>,
1078    ) {
1079        let mut focus_subscriptions = Vec::new();
1080
1081        for entry_index in 0..self.navbar_entries.len() {
1082            let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1083
1084            let subscription = cx.on_focus(
1085                &focus_handle,
1086                window,
1087                move |this: &mut SettingsWindow,
1088                      window: &mut Window,
1089                      cx: &mut Context<SettingsWindow>| {
1090                    this.open_and_scroll_to_navbar_entry(entry_index, window, cx, false);
1091                },
1092            );
1093            focus_subscriptions.push(subscription);
1094        }
1095        self.navbar_focus_subscriptions = focus_subscriptions;
1096    }
1097
1098    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1099        let mut index = 0;
1100        let entries = &self.navbar_entries;
1101        let search_matches = &self.filter_table;
1102        let has_query = self.has_query;
1103        std::iter::from_fn(move || {
1104            while index < entries.len() {
1105                let entry = &entries[index];
1106                let included_in_search = if let Some(item_index) = entry.item_index {
1107                    search_matches[entry.page_index][item_index]
1108                } else {
1109                    search_matches[entry.page_index].iter().any(|b| *b)
1110                        || search_matches[entry.page_index].is_empty()
1111                };
1112                if included_in_search {
1113                    break;
1114                }
1115                index += 1;
1116            }
1117            if index >= self.navbar_entries.len() {
1118                return None;
1119            }
1120            let entry = &entries[index];
1121            let entry_index = index;
1122
1123            index += 1;
1124            if entry.is_root && !entry.expanded && !has_query {
1125                while index < entries.len() {
1126                    if entries[index].is_root {
1127                        break;
1128                    }
1129                    index += 1;
1130                }
1131            }
1132
1133            return Some((entry_index, entry));
1134        })
1135    }
1136
1137    fn filter_matches_to_file(&mut self) {
1138        let current_file = self.current_file.mask();
1139        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1140            let mut header_index = 0;
1141            let mut any_found_since_last_header = true;
1142
1143            for (index, item) in page.items.iter().enumerate() {
1144                match item {
1145                    SettingsPageItem::SectionHeader(_) => {
1146                        if !any_found_since_last_header {
1147                            page_filter[header_index] = false;
1148                        }
1149                        header_index = index;
1150                        any_found_since_last_header = false;
1151                    }
1152                    SettingsPageItem::SettingItem(SettingItem { files, .. })
1153                    | SettingsPageItem::SubPageLink(SubPageLink { files, .. }) => {
1154                        if !files.contains(current_file) {
1155                            page_filter[index] = false;
1156                        } else {
1157                            any_found_since_last_header = true;
1158                        }
1159                    }
1160                }
1161            }
1162            if let Some(last_header) = page_filter.get_mut(header_index)
1163                && !any_found_since_last_header
1164            {
1165                *last_header = false;
1166            }
1167        }
1168    }
1169
1170    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1171        self.search_task.take();
1172        let query = self.search_bar.read(cx).text(cx);
1173        if query.is_empty() || self.search_index.is_none() {
1174            for page in &mut self.filter_table {
1175                page.fill(true);
1176            }
1177            self.has_query = false;
1178            self.filter_matches_to_file();
1179            cx.notify();
1180            return;
1181        }
1182
1183        let search_index = self.search_index.as_ref().unwrap().clone();
1184
1185        fn update_matches_inner(
1186            this: &mut SettingsWindow,
1187            search_index: &SearchIndex,
1188            match_indices: impl Iterator<Item = usize>,
1189            cx: &mut Context<SettingsWindow>,
1190        ) {
1191            for page in &mut this.filter_table {
1192                page.fill(false);
1193            }
1194
1195            for match_index in match_indices {
1196                let SearchItemKey {
1197                    page_index,
1198                    header_index,
1199                    item_index,
1200                } = search_index.key_lut[match_index];
1201                let page = &mut this.filter_table[page_index];
1202                page[header_index] = true;
1203                page[item_index] = true;
1204            }
1205            this.has_query = true;
1206            this.filter_matches_to_file();
1207            this.open_first_nav_page();
1208            cx.notify();
1209        }
1210
1211        self.search_task = Some(cx.spawn(async move |this, cx| {
1212            let bm25_task = cx.background_spawn({
1213                let search_index = search_index.clone();
1214                let max_results = search_index.key_lut.len();
1215                let query = query.clone();
1216                async move { search_index.bm25_engine.search(&query, max_results) }
1217            });
1218            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1219            let fuzzy_search_task = fuzzy::match_strings(
1220                search_index.fuzzy_match_candidates.as_slice(),
1221                &query,
1222                false,
1223                true,
1224                search_index.fuzzy_match_candidates.len(),
1225                &cancel_flag,
1226                cx.background_executor().clone(),
1227            );
1228
1229            let fuzzy_matches = fuzzy_search_task.await;
1230
1231            _ = this
1232                .update(cx, |this, cx| {
1233                    // For tuning the score threshold
1234                    // for fuzzy_match in &fuzzy_matches {
1235                    //     let SearchItemKey {
1236                    //         page_index,
1237                    //         header_index,
1238                    //         item_index,
1239                    //     } = search_index.key_lut[fuzzy_match.candidate_id];
1240                    //     let SettingsPageItem::SectionHeader(header) =
1241                    //         this.pages[page_index].items[header_index]
1242                    //     else {
1243                    //         continue;
1244                    //     };
1245                    //     let SettingsPageItem::SettingItem(SettingItem {
1246                    //         title, description, ..
1247                    //     }) = this.pages[page_index].items[item_index]
1248                    //     else {
1249                    //         continue;
1250                    //     };
1251                    //     let score = fuzzy_match.score;
1252                    //     eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1253                    // }
1254                    update_matches_inner(
1255                        this,
1256                        search_index.as_ref(),
1257                        fuzzy_matches
1258                            .into_iter()
1259                            // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1260                            // flexible enough to catch misspellings and <4 letter queries
1261                            // More flexible is good for us here because fuzzy matches will only be used for things that don't
1262                            // match using bm25
1263                            .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1264                            .map(|fuzzy_match| fuzzy_match.candidate_id),
1265                        cx,
1266                    );
1267                })
1268                .ok();
1269
1270            let bm25_matches = bm25_task.await;
1271
1272            _ = this
1273                .update(cx, |this, cx| {
1274                    if bm25_matches.is_empty() {
1275                        return;
1276                    }
1277                    update_matches_inner(
1278                        this,
1279                        search_index.as_ref(),
1280                        bm25_matches
1281                            .into_iter()
1282                            .map(|bm25_match| bm25_match.document.id),
1283                        cx,
1284                    );
1285                })
1286                .ok();
1287        }));
1288    }
1289
1290    fn build_filter_table(&mut self) {
1291        self.filter_table = self
1292            .pages
1293            .iter()
1294            .map(|page| vec![true; page.items.len()])
1295            .collect::<Vec<_>>();
1296    }
1297
1298    fn build_search_index(&mut self) {
1299        let mut key_lut: Vec<SearchItemKey> = vec![];
1300        let mut documents = Vec::default();
1301        let mut fuzzy_match_candidates = Vec::default();
1302
1303        fn push_candidates(
1304            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1305            key_index: usize,
1306            input: &str,
1307        ) {
1308            for word in input.split_ascii_whitespace() {
1309                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1310            }
1311        }
1312
1313        // PERF: We are currently searching all items even in project files
1314        // where many settings are filtered out, using the logic in filter_matches_to_file
1315        // we could only search relevant items based on the current file
1316        for (page_index, page) in self.pages.iter().enumerate() {
1317            let mut header_index = 0;
1318            let mut header_str = "";
1319            for (item_index, item) in page.items.iter().enumerate() {
1320                let key_index = key_lut.len();
1321                match item {
1322                    SettingsPageItem::SettingItem(item) => {
1323                        documents.push(bm25::Document {
1324                            id: key_index,
1325                            contents: [page.title, header_str, item.title, item.description]
1326                                .join("\n"),
1327                        });
1328                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1329                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1330                    }
1331                    SettingsPageItem::SectionHeader(header) => {
1332                        documents.push(bm25::Document {
1333                            id: key_index,
1334                            contents: header.to_string(),
1335                        });
1336                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
1337                        header_index = item_index;
1338                        header_str = *header;
1339                    }
1340                    SettingsPageItem::SubPageLink(sub_page_link) => {
1341                        documents.push(bm25::Document {
1342                            id: key_index,
1343                            contents: [page.title, header_str, sub_page_link.title.as_ref()]
1344                                .join("\n"),
1345                        });
1346                        push_candidates(
1347                            &mut fuzzy_match_candidates,
1348                            key_index,
1349                            sub_page_link.title.as_ref(),
1350                        );
1351                    }
1352                }
1353                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1354                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1355
1356                key_lut.push(SearchItemKey {
1357                    page_index,
1358                    header_index,
1359                    item_index,
1360                });
1361            }
1362        }
1363        let engine =
1364            bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1365        self.search_index = Some(Arc::new(SearchIndex {
1366            bm25_engine: engine,
1367            key_lut,
1368            fuzzy_match_candidates,
1369        }));
1370    }
1371
1372    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1373        self.content_handles = self
1374            .pages
1375            .iter()
1376            .map(|page| {
1377                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1378                    .take(page.items.len())
1379                    .collect()
1380            })
1381            .collect::<Vec<_>>();
1382    }
1383
1384    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1385        if self.pages.is_empty() {
1386            self.pages = page_data::settings_data(cx);
1387            self.build_navbar(cx);
1388            self.setup_navbar_focus_subscriptions(window, cx);
1389            self.build_content_handles(window, cx);
1390        }
1391        sub_page_stack_mut().clear();
1392        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1393        self.build_filter_table();
1394        self.update_matches(cx);
1395
1396        cx.notify();
1397    }
1398
1399    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1400        self.worktree_root_dirs.clear();
1401        let prev_files = self.files.clone();
1402        let settings_store = cx.global::<SettingsStore>();
1403        let mut ui_files = vec![];
1404        let all_files = settings_store.get_all_files();
1405        for file in all_files {
1406            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1407                continue;
1408            };
1409            if settings_ui_file.is_server() {
1410                continue;
1411            }
1412
1413            if let Some(worktree_id) = settings_ui_file.worktree_id() {
1414                let directory_name = all_projects(cx)
1415                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1416                    .and_then(|worktree| worktree.read(cx).root_dir())
1417                    .and_then(|root_dir| {
1418                        root_dir
1419                            .file_name()
1420                            .map(|os_string| os_string.to_string_lossy().to_string())
1421                    });
1422
1423                let Some(directory_name) = directory_name else {
1424                    log::error!(
1425                        "No directory name found for settings file at worktree ID: {}",
1426                        worktree_id
1427                    );
1428                    continue;
1429                };
1430
1431                self.worktree_root_dirs.insert(worktree_id, directory_name);
1432            }
1433
1434            let focus_handle = prev_files
1435                .iter()
1436                .find_map(|(prev_file, handle)| {
1437                    (prev_file == &settings_ui_file).then(|| handle.clone())
1438                })
1439                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1440            ui_files.push((settings_ui_file, focus_handle));
1441        }
1442        ui_files.reverse();
1443        self.files = ui_files;
1444        let current_file_still_exists = self
1445            .files
1446            .iter()
1447            .any(|(file, _)| file == &self.current_file);
1448        if !current_file_still_exists {
1449            self.change_file(0, window, cx);
1450        }
1451    }
1452
1453    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1454        if !self.is_nav_entry_visible(navbar_entry) {
1455            self.open_first_nav_page();
1456        }
1457        self.navbar_entry = navbar_entry;
1458        sub_page_stack_mut().clear();
1459    }
1460
1461    fn open_first_nav_page(&mut self) {
1462        let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
1463        else {
1464            return;
1465        };
1466        self.open_navbar_entry_page(first_navbar_entry_index);
1467    }
1468
1469    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1470        if ix >= self.files.len() {
1471            self.current_file = SettingsUiFile::User;
1472            self.build_ui(window, cx);
1473            return;
1474        }
1475        if self.files[ix].0 == self.current_file {
1476            return;
1477        }
1478        self.current_file = self.files[ix].0.clone();
1479
1480        self.build_ui(window, cx);
1481
1482        if self
1483            .visible_navbar_entries()
1484            .any(|(index, _)| index == self.navbar_entry)
1485        {
1486            self.open_and_scroll_to_navbar_entry(self.navbar_entry, window, cx, true);
1487        } else {
1488            self.open_first_nav_page();
1489        };
1490    }
1491
1492    fn render_files_header(
1493        &self,
1494        _window: &mut Window,
1495        cx: &mut Context<SettingsWindow>,
1496    ) -> impl IntoElement {
1497        h_flex()
1498            .w_full()
1499            .pb_4()
1500            .gap_1()
1501            .justify_between()
1502            .tab_group()
1503            .track_focus(&self.files_focus_handle)
1504            .tab_index(HEADER_GROUP_TAB_INDEX)
1505            .child(
1506                h_flex()
1507                    .id("file_buttons_container")
1508                    .w_64() // Temporary fix until long-term solution is a fixed set of buttons representing a file location (User, Project, and Remote)
1509                    .gap_1()
1510                    .overflow_x_scroll()
1511                    .children(
1512                        self.files
1513                            .iter()
1514                            .enumerate()
1515                            .map(|(ix, (file, focus_handle))| {
1516                                Button::new(
1517                                    ix,
1518                                    self.display_name(&file)
1519                                        .expect("Files should always have a name"),
1520                                )
1521                                .toggle_state(file == &self.current_file)
1522                                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1523                                .track_focus(focus_handle)
1524                                .on_click(cx.listener({
1525                                    let focus_handle = focus_handle.clone();
1526                                    move |this, _: &gpui::ClickEvent, window, cx| {
1527                                        this.change_file(ix, window, cx);
1528                                        focus_handle.focus(window);
1529                                    }
1530                                }))
1531                            }),
1532                    ),
1533            )
1534            .child(
1535                Button::new("edit-in-json", "Edit in settings.json")
1536                    .tab_index(0_isize)
1537                    .style(ButtonStyle::OutlinedGhost)
1538                    .on_click(cx.listener(|this, _, _, cx| {
1539                        this.open_current_settings_file(cx);
1540                    })),
1541            )
1542    }
1543
1544    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1545        match file {
1546            SettingsUiFile::User => Some("User".to_string()),
1547            SettingsUiFile::Project((worktree_id, path)) => self
1548                .worktree_root_dirs
1549                .get(&worktree_id)
1550                .map(|directory_name| {
1551                    let path_style = PathStyle::local();
1552                    if path.is_empty() {
1553                        directory_name.clone()
1554                    } else {
1555                        format!(
1556                            "{}{}{}",
1557                            directory_name,
1558                            path_style.separator(),
1559                            path.display(path_style)
1560                        )
1561                    }
1562                }),
1563            SettingsUiFile::Server(file) => Some(file.to_string()),
1564        }
1565    }
1566
1567    // TODO:
1568    //  Reconsider this after preview launch
1569    // fn file_location_str(&self) -> String {
1570    //     match &self.current_file {
1571    //         SettingsUiFile::User => "settings.json".to_string(),
1572    //         SettingsUiFile::Project((worktree_id, path)) => self
1573    //             .worktree_root_dirs
1574    //             .get(&worktree_id)
1575    //             .map(|directory_name| {
1576    //                 let path_style = PathStyle::local();
1577    //                 let file_path = path.join(paths::local_settings_file_relative_path());
1578    //                 format!(
1579    //                     "{}{}{}",
1580    //                     directory_name,
1581    //                     path_style.separator(),
1582    //                     file_path.display(path_style)
1583    //                 )
1584    //             })
1585    //             .expect("Current file should always be present in root dir map"),
1586    //         SettingsUiFile::Server(file) => file.to_string(),
1587    //     }
1588    // }
1589
1590    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1591        h_flex()
1592            .py_1()
1593            .px_1p5()
1594            .mb_3()
1595            .gap_1p5()
1596            .rounded_sm()
1597            .bg(cx.theme().colors().editor_background)
1598            .border_1()
1599            .border_color(cx.theme().colors().border)
1600            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1601            .child(self.search_bar.clone())
1602    }
1603
1604    fn render_nav(
1605        &self,
1606        window: &mut Window,
1607        cx: &mut Context<SettingsWindow>,
1608    ) -> impl IntoElement {
1609        let visible_count = self.visible_navbar_entries().count();
1610
1611        let focus_keybind_label = if self
1612            .navbar_focus_handle
1613            .read(cx)
1614            .handle
1615            .contains_focused(window, cx)
1616        {
1617            "Focus Content"
1618        } else {
1619            "Focus Navbar"
1620        };
1621
1622        v_flex()
1623            .w_64()
1624            .p_2p5()
1625            .when(cfg!(target_os = "macos"), |c| c.pt_10())
1626            .h_full()
1627            .flex_none()
1628            .border_r_1()
1629            .key_context("NavigationMenu")
1630            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1631                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1632                    return;
1633                };
1634                let focused_entry_parent = this.root_entry_containing(focused_entry);
1635                if this.navbar_entries[focused_entry_parent].expanded {
1636                    this.toggle_navbar_entry(focused_entry_parent);
1637                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1638                }
1639                cx.notify();
1640            }))
1641            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1642                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1643                    return;
1644                };
1645                if !this.navbar_entries[focused_entry].is_root {
1646                    return;
1647                }
1648                if !this.navbar_entries[focused_entry].expanded {
1649                    this.toggle_navbar_entry(focused_entry);
1650                }
1651                cx.notify();
1652            }))
1653            .on_action(
1654                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1655                    let entry_index = this
1656                        .focused_nav_entry(window, cx)
1657                        .unwrap_or(this.navbar_entry);
1658                    let mut root_index = None;
1659                    for (index, entry) in this.visible_navbar_entries() {
1660                        if index >= entry_index {
1661                            break;
1662                        }
1663                        if entry.is_root {
1664                            root_index = Some(index);
1665                        }
1666                    }
1667                    let Some(previous_root_index) = root_index else {
1668                        return;
1669                    };
1670                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
1671                }),
1672            )
1673            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
1674                let entry_index = this
1675                    .focused_nav_entry(window, cx)
1676                    .unwrap_or(this.navbar_entry);
1677                let mut root_index = None;
1678                for (index, entry) in this.visible_navbar_entries() {
1679                    if index <= entry_index {
1680                        continue;
1681                    }
1682                    if entry.is_root {
1683                        root_index = Some(index);
1684                        break;
1685                    }
1686                }
1687                let Some(next_root_index) = root_index else {
1688                    return;
1689                };
1690                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
1691            }))
1692            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
1693                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1694                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
1695                }
1696            }))
1697            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
1698                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1699                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
1700                }
1701            }))
1702            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
1703                let entry_index = this
1704                    .focused_nav_entry(window, cx)
1705                    .unwrap_or(this.navbar_entry);
1706                let mut next_index = None;
1707                for (index, _) in this.visible_navbar_entries() {
1708                    if index > entry_index {
1709                        next_index = Some(index);
1710                        break;
1711                    }
1712                }
1713                let Some(next_entry_index) = next_index else {
1714                    return;
1715                };
1716                this.open_and_scroll_to_navbar_entry(next_entry_index, window, cx, false);
1717            }))
1718            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
1719                let entry_index = this
1720                    .focused_nav_entry(window, cx)
1721                    .unwrap_or(this.navbar_entry);
1722                let mut prev_index = None;
1723                for (index, _) in this.visible_navbar_entries() {
1724                    if index >= entry_index {
1725                        break;
1726                    }
1727                    prev_index = Some(index);
1728                }
1729                let Some(prev_entry_index) = prev_index else {
1730                    return;
1731                };
1732                this.open_and_scroll_to_navbar_entry(prev_entry_index, window, cx, false);
1733            }))
1734            .border_color(cx.theme().colors().border)
1735            .bg(cx.theme().colors().panel_background)
1736            .child(self.render_search(window, cx))
1737            .child(
1738                v_flex()
1739                    .flex_1()
1740                    .overflow_hidden()
1741                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1742                    .tab_group()
1743                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
1744                    .child(
1745                        uniform_list(
1746                            "settings-ui-nav-bar",
1747                            visible_count + 1,
1748                            cx.processor(move |this, range: Range<usize>, _, cx| {
1749                                this.visible_navbar_entries()
1750                                    .skip(range.start.saturating_sub(1))
1751                                    .take(range.len())
1752                                    .map(|(ix, entry)| {
1753                                        TreeViewItem::new(
1754                                            ("settings-ui-navbar-entry", ix),
1755                                            entry.title,
1756                                        )
1757                                        .track_focus(&entry.focus_handle)
1758                                        .root_item(entry.is_root)
1759                                        .toggle_state(this.is_navbar_entry_selected(ix))
1760                                        .when(entry.is_root, |item| {
1761                                            item.expanded(entry.expanded || this.has_query)
1762                                                .on_toggle(cx.listener(
1763                                                    move |this, _, window, cx| {
1764                                                        this.toggle_navbar_entry(ix);
1765                                                        // Update selection state immediately before cx.notify
1766                                                        // to prevent double selection flash
1767                                                        this.navbar_entry = ix;
1768                                                        window.focus(
1769                                                            &this.navbar_entries[ix].focus_handle,
1770                                                        );
1771                                                        cx.notify();
1772                                                    },
1773                                                ))
1774                                        })
1775                                        .on_click(
1776                                            cx.listener(move |this, _, window, cx| {
1777                                                this.open_and_scroll_to_navbar_entry(
1778                                                    ix, window, cx, true,
1779                                                );
1780                                            }),
1781                                        )
1782                                    })
1783                                    .collect()
1784                            }),
1785                        )
1786                        .size_full()
1787                        .track_scroll(self.navbar_scroll_handle.clone()),
1788                    )
1789                    .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
1790            )
1791            .child(
1792                h_flex()
1793                    .w_full()
1794                    .h_8()
1795                    .p_2()
1796                    .pb_0p5()
1797                    .flex_shrink_0()
1798                    .border_t_1()
1799                    .border_color(cx.theme().colors().border_variant)
1800                    .children(
1801                        KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1802                            KeybindingHint::new(
1803                                this,
1804                                cx.theme().colors().surface_background.opacity(0.5),
1805                            )
1806                            .suffix(focus_keybind_label)
1807                        }),
1808                    ),
1809            )
1810    }
1811
1812    fn open_and_scroll_to_navbar_entry(
1813        &mut self,
1814        navbar_entry_index: usize,
1815        window: &mut Window,
1816        cx: &mut Context<Self>,
1817        focus_content: bool,
1818    ) {
1819        self.open_navbar_entry_page(navbar_entry_index);
1820        cx.notify();
1821
1822        if self.navbar_entries[navbar_entry_index].is_root
1823            || !self.is_nav_entry_visible(navbar_entry_index)
1824        {
1825            self.page_scroll_handle.set_offset(point(px(0.), px(0.)));
1826            if focus_content {
1827                let Some(first_item_index) =
1828                    self.visible_page_items().next().map(|(index, _)| index)
1829                else {
1830                    return;
1831                };
1832                self.focus_content_element(first_item_index, window, cx);
1833            } else {
1834                window.focus(&self.navbar_entries[navbar_entry_index].focus_handle);
1835            }
1836        } else {
1837            let entry_item_index = self.navbar_entries[navbar_entry_index]
1838                .item_index
1839                .expect("Non-root items should have an item index");
1840            let Some(selected_item_index) = self
1841                .visible_page_items()
1842                .position(|(index, _)| index == entry_item_index)
1843            else {
1844                return;
1845            };
1846            self.page_scroll_handle
1847                .scroll_to_top_of_item(selected_item_index + 1);
1848
1849            if focus_content {
1850                self.focus_content_element(entry_item_index, window, cx);
1851            } else {
1852                window.focus(&self.navbar_entries[navbar_entry_index].focus_handle);
1853            }
1854        }
1855
1856        // Page scroll handle updates the active item index
1857        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
1858        // The call after that updates the offset of the scroll handle. So to
1859        // ensure the scroll handle doesn't lag behind we need to render three frames
1860        // back to back.
1861        cx.on_next_frame(window, |_, window, cx| {
1862            cx.on_next_frame(window, |_, _, cx| {
1863                cx.notify();
1864            });
1865            cx.notify();
1866        });
1867        cx.notify();
1868    }
1869
1870    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
1871        self.visible_navbar_entries()
1872            .any(|(index, _)| index == nav_entry_index)
1873    }
1874
1875    fn focus_and_scroll_to_nav_entry(
1876        &self,
1877        nav_entry_index: usize,
1878        window: &mut Window,
1879        cx: &mut Context<Self>,
1880    ) {
1881        let Some(position) = self
1882            .visible_navbar_entries()
1883            .position(|(index, _)| index == nav_entry_index)
1884        else {
1885            return;
1886        };
1887        self.navbar_scroll_handle
1888            .scroll_to_item(position, gpui::ScrollStrategy::Top);
1889        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
1890        cx.notify();
1891    }
1892
1893    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1894        let page_idx = self.current_page_index();
1895
1896        self.current_page()
1897            .items
1898            .iter()
1899            .enumerate()
1900            .filter_map(move |(item_index, item)| {
1901                self.filter_table[page_idx][item_index].then_some((item_index, item))
1902            })
1903    }
1904
1905    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1906        let mut items = vec![];
1907        items.push(self.current_page().title.into());
1908        items.extend(
1909            sub_page_stack()
1910                .iter()
1911                .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
1912        );
1913
1914        let last = items.pop().unwrap();
1915        h_flex()
1916            .gap_1()
1917            .children(
1918                items
1919                    .into_iter()
1920                    .flat_map(|item| [item, "/".into()])
1921                    .map(|item| Label::new(item).color(Color::Muted)),
1922            )
1923            .child(Label::new(last))
1924    }
1925
1926    fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
1927        &self,
1928        items: Items,
1929        page_index: Option<usize>,
1930        window: &mut Window,
1931        cx: &mut Context<SettingsWindow>,
1932    ) -> impl IntoElement {
1933        let mut page_content = v_flex()
1934            .id("settings-ui-page")
1935            .size_full()
1936            .overflow_y_scroll()
1937            .track_scroll(&self.page_scroll_handle);
1938
1939        let items: Vec<_> = items.collect();
1940        let items_len = items.len();
1941        let mut section_header = None;
1942
1943        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1944        let has_no_results = items_len == 0 && has_active_search;
1945
1946        if has_no_results {
1947            let search_query = self.search_bar.read(cx).text(cx);
1948            page_content = page_content.child(
1949                v_flex()
1950                    .size_full()
1951                    .items_center()
1952                    .justify_center()
1953                    .gap_1()
1954                    .child(div().child("No Results"))
1955                    .child(
1956                        div()
1957                            .text_sm()
1958                            .text_color(cx.theme().colors().text_muted)
1959                            .child(format!("No settings match \"{}\"", search_query)),
1960                    ),
1961            )
1962        } else {
1963            let last_non_header_index = items
1964                .iter()
1965                .enumerate()
1966                .rev()
1967                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
1968                .map(|(index, _)| index);
1969
1970            let root_nav_label = self
1971                .navbar_entries
1972                .iter()
1973                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
1974                .map(|entry| entry.title);
1975
1976            page_content = page_content
1977                .when(sub_page_stack().is_empty(), |this| {
1978                    this.when_some(root_nav_label, |this, title| {
1979                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
1980                    })
1981                })
1982                .children(items.clone().into_iter().enumerate().map(
1983                    |(index, (actual_item_index, item))| {
1984                        let no_bottom_border = items
1985                            .get(index + 1)
1986                            .map(|(_, next_item)| {
1987                                matches!(next_item, SettingsPageItem::SectionHeader(_))
1988                            })
1989                            .unwrap_or(false);
1990                        let is_last = Some(index) == last_non_header_index;
1991
1992                        if let SettingsPageItem::SectionHeader(header) = item {
1993                            section_header = Some(*header);
1994                        }
1995                        v_flex()
1996                            .w_full()
1997                            .min_w_0()
1998                            .id(("settings-page-item", actual_item_index))
1999                            .when_some(page_index, |element, page_index| {
2000                                element.track_focus(
2001                                    &self.content_handles[page_index][actual_item_index]
2002                                        .focus_handle(cx),
2003                                )
2004                            })
2005                            .child(item.render(
2006                                self,
2007                                section_header.expect("All items rendered after a section header"),
2008                                no_bottom_border || is_last,
2009                                window,
2010                                cx,
2011                            ))
2012                    },
2013                ))
2014        }
2015        page_content
2016    }
2017
2018    fn render_page(
2019        &mut self,
2020        window: &mut Window,
2021        cx: &mut Context<SettingsWindow>,
2022    ) -> impl IntoElement {
2023        let page_header;
2024        let page_content;
2025
2026        if sub_page_stack().is_empty() {
2027            page_header = self.render_files_header(window, cx).into_any_element();
2028
2029            page_content = self
2030                .render_page_items(
2031                    self.visible_page_items(),
2032                    Some(self.current_page_index()),
2033                    window,
2034                    cx,
2035                )
2036                .into_any_element();
2037        } else {
2038            page_header = h_flex()
2039                .ml_neg_1p5()
2040                .pb_4()
2041                .gap_1()
2042                .child(
2043                    IconButton::new("back-btn", IconName::ArrowLeft)
2044                        .icon_size(IconSize::Small)
2045                        .shape(IconButtonShape::Square)
2046                        .on_click(cx.listener(|this, _, _, cx| {
2047                            this.pop_sub_page(cx);
2048                        })),
2049                )
2050                .child(self.render_sub_page_breadcrumbs())
2051                .into_any_element();
2052
2053            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2054            page_content = (active_page_render_fn)(self, window, cx);
2055        }
2056
2057        return v_flex()
2058            .size_full()
2059            .pt_6()
2060            .pb_8()
2061            .px_8()
2062            .bg(cx.theme().colors().editor_background)
2063            .child(page_header)
2064            .vertical_scrollbar_for(self.page_scroll_handle.clone(), window, cx)
2065            .track_focus(&self.content_focus_handle.focus_handle(cx))
2066            .child(
2067                div()
2068                    .size_full()
2069                    .tab_group()
2070                    .tab_index(CONTENT_GROUP_TAB_INDEX)
2071                    .child(page_content),
2072            );
2073    }
2074
2075    fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2076        match &self.current_file {
2077            SettingsUiFile::User => {
2078                let Some(original_window) = self.original_window else {
2079                    return;
2080                };
2081                original_window
2082                    .update(cx, |workspace, window, cx| {
2083                        workspace
2084                            .with_local_workspace(window, cx, |workspace, window, cx| {
2085                                let create_task = workspace.project().update(cx, |project, cx| {
2086                                    project.find_or_create_worktree(
2087                                        paths::config_dir().as_path(),
2088                                        false,
2089                                        cx,
2090                                    )
2091                                });
2092                                let open_task = workspace.open_paths(
2093                                    vec![paths::settings_file().to_path_buf()],
2094                                    OpenOptions {
2095                                        visible: Some(OpenVisible::None),
2096                                        ..Default::default()
2097                                    },
2098                                    None,
2099                                    window,
2100                                    cx,
2101                                );
2102
2103                                cx.spawn_in(window, async move |workspace, cx| {
2104                                    create_task.await.ok();
2105                                    open_task.await;
2106
2107                                    workspace.update_in(cx, |_, window, cx| {
2108                                        window.activate_window();
2109                                        cx.notify();
2110                                    })
2111                                })
2112                                .detach();
2113                            })
2114                            .detach();
2115                    })
2116                    .ok();
2117            }
2118            SettingsUiFile::Project((worktree_id, path)) => {
2119                let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
2120                let settings_path = path.join(paths::local_settings_file_relative_path());
2121                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2122                    return;
2123                };
2124                for workspace in app_state.workspace_store.read(cx).workspaces() {
2125                    let contains_settings_file = workspace
2126                        .read_with(cx, |workspace, cx| {
2127                            workspace.project().read(cx).contains_local_settings_file(
2128                                *worktree_id,
2129                                settings_path.as_ref(),
2130                                cx,
2131                            )
2132                        })
2133                        .ok();
2134                    if Some(true) == contains_settings_file {
2135                        corresponding_workspace = Some(*workspace);
2136
2137                        break;
2138                    }
2139                }
2140
2141                let Some(corresponding_workspace) = corresponding_workspace else {
2142                    log::error!(
2143                        "No corresponding workspace found for settings file {}",
2144                        settings_path.as_std_path().display()
2145                    );
2146
2147                    return;
2148                };
2149
2150                // TODO: move zed::open_local_file() APIs to this crate, and
2151                // re-implement the "initial_contents" behavior
2152                corresponding_workspace
2153                    .update(cx, |workspace, window, cx| {
2154                        let open_task = workspace.open_path(
2155                            (*worktree_id, settings_path.clone()),
2156                            None,
2157                            true,
2158                            window,
2159                            cx,
2160                        );
2161
2162                        cx.spawn_in(window, async move |workspace, cx| {
2163                            if open_task.await.log_err().is_some() {
2164                                workspace
2165                                    .update_in(cx, |_, window, cx| {
2166                                        window.activate_window();
2167                                        cx.notify();
2168                                    })
2169                                    .ok();
2170                            }
2171                        })
2172                        .detach();
2173                    })
2174                    .ok();
2175            }
2176            SettingsUiFile::Server(_) => {
2177                return;
2178            }
2179        };
2180    }
2181
2182    fn current_page_index(&self) -> usize {
2183        self.page_index_from_navbar_index(self.navbar_entry)
2184    }
2185
2186    fn current_page(&self) -> &SettingsPage {
2187        &self.pages[self.current_page_index()]
2188    }
2189
2190    fn page_index_from_navbar_index(&self, index: usize) -> usize {
2191        if self.navbar_entries.is_empty() {
2192            return 0;
2193        }
2194
2195        self.navbar_entries[index].page_index
2196    }
2197
2198    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2199        ix == self.navbar_entry
2200    }
2201
2202    fn push_sub_page(
2203        &mut self,
2204        sub_page_link: SubPageLink,
2205        section_header: &'static str,
2206        cx: &mut Context<SettingsWindow>,
2207    ) {
2208        sub_page_stack_mut().push(SubPage {
2209            link: sub_page_link,
2210            section_header,
2211        });
2212        cx.notify();
2213    }
2214
2215    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
2216        sub_page_stack_mut().pop();
2217        cx.notify();
2218    }
2219
2220    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
2221        if let Some((_, handle)) = self.files.get(index) {
2222            handle.focus(window);
2223        }
2224    }
2225
2226    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
2227        if self.files_focus_handle.contains_focused(window, cx)
2228            && let Some(index) = self
2229                .files
2230                .iter()
2231                .position(|(_, handle)| handle.is_focused(window))
2232        {
2233            return index;
2234        }
2235        if let Some(current_file_index) = self
2236            .files
2237            .iter()
2238            .position(|(file, _)| file == &self.current_file)
2239        {
2240            return current_file_index;
2241        }
2242        0
2243    }
2244
2245    fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
2246        if !sub_page_stack().is_empty() {
2247            return;
2248        }
2249        let page_index = self.current_page_index();
2250        window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
2251    }
2252
2253    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
2254        if !self
2255            .navbar_focus_handle
2256            .focus_handle(cx)
2257            .contains_focused(window, cx)
2258        {
2259            return None;
2260        }
2261        for (index, entry) in self.navbar_entries.iter().enumerate() {
2262            if entry.focus_handle.is_focused(window) {
2263                return Some(index);
2264            }
2265        }
2266        None
2267    }
2268
2269    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
2270        let mut index = Some(nav_entry_index);
2271        while let Some(prev_index) = index
2272            && !self.navbar_entries[prev_index].is_root
2273        {
2274            index = prev_index.checked_sub(1);
2275        }
2276        return index.expect("No root entry found");
2277    }
2278}
2279
2280impl Render for SettingsWindow {
2281    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2282        let ui_font = theme::setup_ui_font(window, cx);
2283
2284        client_side_decorations(
2285            v_flex()
2286                .text_color(cx.theme().colors().text)
2287                .size_full()
2288                .children(self.title_bar.clone())
2289                .child(
2290                    div()
2291                        .id("settings-window")
2292                        .key_context("SettingsWindow")
2293                        .track_focus(&self.focus_handle)
2294                        .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2295                            this.open_current_settings_file(cx);
2296                        }))
2297                        .on_action(|_: &Minimize, window, _cx| {
2298                            window.minimize_window();
2299                        })
2300                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2301                            this.search_bar.focus_handle(cx).focus(window);
2302                        }))
2303                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2304                            if this
2305                                .navbar_focus_handle
2306                                .focus_handle(cx)
2307                                .contains_focused(window, cx)
2308                            {
2309                                this.open_and_scroll_to_navbar_entry(
2310                                    this.navbar_entry,
2311                                    window,
2312                                    cx,
2313                                    true,
2314                                );
2315                            } else {
2316                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
2317                            }
2318                        }))
2319                        .on_action(cx.listener(
2320                            |this, FocusFile(file_index): &FocusFile, window, _| {
2321                                this.focus_file_at_index(*file_index as usize, window);
2322                            },
2323                        ))
2324                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2325                            let next_index = usize::min(
2326                                this.focused_file_index(window, cx) + 1,
2327                                this.files.len().saturating_sub(1),
2328                            );
2329                            this.focus_file_at_index(next_index, window);
2330                        }))
2331                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2332                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2333                            this.focus_file_at_index(prev_index, window);
2334                        }))
2335                        .on_action(|_: &menu::SelectNext, window, _| {
2336                            window.focus_next();
2337                        })
2338                        .on_action(|_: &menu::SelectPrevious, window, _| {
2339                            window.focus_prev();
2340                        })
2341                        .flex()
2342                        .flex_row()
2343                        .flex_1()
2344                        .min_h_0()
2345                        .font(ui_font)
2346                        .bg(cx.theme().colors().background)
2347                        .text_color(cx.theme().colors().text)
2348                        .child(self.render_nav(window, cx))
2349                        .child(self.render_page(window, cx)),
2350                ),
2351            window,
2352            cx,
2353        )
2354    }
2355}
2356
2357fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2358    workspace::AppState::global(cx)
2359        .upgrade()
2360        .map(|app_state| {
2361            app_state
2362                .workspace_store
2363                .read(cx)
2364                .workspaces()
2365                .iter()
2366                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2367        })
2368        .into_iter()
2369        .flatten()
2370}
2371
2372fn update_settings_file(
2373    file: SettingsUiFile,
2374    cx: &mut App,
2375    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2376) -> Result<()> {
2377    match file {
2378        SettingsUiFile::Project((worktree_id, rel_path)) => {
2379            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2380            let project = all_projects(cx).find(|project| {
2381                project.read_with(cx, |project, cx| {
2382                    project.contains_local_settings_file(worktree_id, &rel_path, cx)
2383                })
2384            });
2385            let Some(project) = project else {
2386                anyhow::bail!(
2387                    "Could not find worktree containing settings file: {}",
2388                    &rel_path.display(PathStyle::local())
2389                );
2390            };
2391            project.update(cx, |project, cx| {
2392                project.update_local_settings_file(worktree_id, rel_path, cx, update);
2393            });
2394            return Ok(());
2395        }
2396        SettingsUiFile::User => {
2397            // todo(settings_ui) error?
2398            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2399            Ok(())
2400        }
2401        SettingsUiFile::Server(_) => unimplemented!(),
2402    }
2403}
2404
2405fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2406    field: SettingField<T>,
2407    file: SettingsUiFile,
2408    metadata: Option<&SettingsFieldMetadata>,
2409    _window: &mut Window,
2410    cx: &mut App,
2411) -> AnyElement {
2412    let (_, initial_text) =
2413        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2414    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2415
2416    SettingsEditor::new()
2417        .tab_index(0)
2418        .when_some(initial_text, |editor, text| {
2419            editor.with_initial_text(text.as_ref().to_string())
2420        })
2421        .when_some(
2422            metadata.and_then(|metadata| metadata.placeholder),
2423            |editor, placeholder| editor.with_placeholder(placeholder),
2424        )
2425        .on_confirm({
2426            move |new_text, cx| {
2427                update_settings_file(file.clone(), cx, move |settings, _cx| {
2428                    *(field.pick_mut)(settings) = new_text.map(Into::into);
2429                })
2430                .log_err(); // todo(settings_ui) don't log err
2431            }
2432        })
2433        .into_any_element()
2434}
2435
2436fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2437    field: SettingField<B>,
2438    file: SettingsUiFile,
2439    _metadata: Option<&SettingsFieldMetadata>,
2440    _window: &mut Window,
2441    cx: &mut App,
2442) -> AnyElement {
2443    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2444
2445    let toggle_state = if value.copied().map_or(false, Into::into) {
2446        ToggleState::Selected
2447    } else {
2448        ToggleState::Unselected
2449    };
2450
2451    Switch::new("toggle_button", toggle_state)
2452        .color(ui::SwitchColor::Accent)
2453        .on_click({
2454            move |state, _window, cx| {
2455                let state = *state == ui::ToggleState::Selected;
2456                update_settings_file(file.clone(), cx, move |settings, _cx| {
2457                    *(field.pick_mut)(settings) = Some(state.into());
2458                })
2459                .log_err(); // todo(settings_ui) don't log err
2460            }
2461        })
2462        .tab_index(0_isize)
2463        .color(SwitchColor::Accent)
2464        .into_any_element()
2465}
2466
2467fn render_font_picker(
2468    field: SettingField<settings::FontFamilyName>,
2469    file: SettingsUiFile,
2470    _metadata: Option<&SettingsFieldMetadata>,
2471    window: &mut Window,
2472    cx: &mut App,
2473) -> AnyElement {
2474    let current_value = SettingsStore::global(cx)
2475        .get_value_from_file(file.to_settings(), field.pick)
2476        .1
2477        .cloned()
2478        .unwrap_or_else(|| SharedString::default().into());
2479
2480    let font_picker = cx.new(|cx| {
2481        ui_input::font_picker(
2482            current_value.clone().into(),
2483            move |font_name, cx| {
2484                update_settings_file(file.clone(), cx, move |settings, _cx| {
2485                    *(field.pick_mut)(settings) = Some(font_name.into());
2486                })
2487                .log_err(); // todo(settings_ui) don't log err
2488            },
2489            window,
2490            cx,
2491        )
2492    });
2493
2494    PopoverMenu::new("font-picker")
2495        .menu(move |_window, _cx| Some(font_picker.clone()))
2496        .trigger(
2497            Button::new("font-family-button", current_value)
2498                .tab_index(0_isize)
2499                .style(ButtonStyle::Outlined)
2500                .size(ButtonSize::Medium)
2501                .icon(IconName::ChevronUpDown)
2502                .icon_color(Color::Muted)
2503                .icon_size(IconSize::Small)
2504                .icon_position(IconPosition::End),
2505        )
2506        .anchor(gpui::Corner::TopLeft)
2507        .offset(gpui::Point {
2508            x: px(0.0),
2509            y: px(2.0),
2510        })
2511        .with_handle(ui::PopoverMenuHandle::default())
2512        .into_any_element()
2513}
2514
2515fn render_number_field<T: NumberFieldType + Send + Sync>(
2516    field: SettingField<T>,
2517    file: SettingsUiFile,
2518    _metadata: Option<&SettingsFieldMetadata>,
2519    window: &mut Window,
2520    cx: &mut App,
2521) -> AnyElement {
2522    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2523    let value = value.copied().unwrap_or_else(T::min_value);
2524    NumberField::new("numeric_stepper", value, window, cx)
2525        .on_change({
2526            move |value, _window, cx| {
2527                let value = *value;
2528                update_settings_file(file.clone(), cx, move |settings, _cx| {
2529                    *(field.pick_mut)(settings) = Some(value);
2530                })
2531                .log_err(); // todo(settings_ui) don't log err
2532            }
2533        })
2534        .into_any_element()
2535}
2536
2537fn render_dropdown<T>(
2538    field: SettingField<T>,
2539    file: SettingsUiFile,
2540    metadata: Option<&SettingsFieldMetadata>,
2541    window: &mut Window,
2542    cx: &mut App,
2543) -> AnyElement
2544where
2545    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2546{
2547    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2548    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2549    let should_do_titlecase = metadata
2550        .and_then(|metadata| metadata.should_do_titlecase)
2551        .unwrap_or(true);
2552
2553    let (_, current_value) =
2554        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2555    let current_value = current_value.copied().unwrap_or(variants()[0]);
2556
2557    let current_value_label =
2558        labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2559
2560    DropdownMenu::new(
2561        "dropdown",
2562        if should_do_titlecase {
2563            current_value_label.to_title_case()
2564        } else {
2565            current_value_label.to_string()
2566        },
2567        ContextMenu::build(window, cx, move |mut menu, _, _| {
2568            for (&value, &label) in std::iter::zip(variants(), labels()) {
2569                let file = file.clone();
2570                menu = menu.toggleable_entry(
2571                    if should_do_titlecase {
2572                        label.to_title_case()
2573                    } else {
2574                        label.to_string()
2575                    },
2576                    value == current_value,
2577                    IconPosition::End,
2578                    None,
2579                    move |_, cx| {
2580                        if value == current_value {
2581                            return;
2582                        }
2583                        update_settings_file(file.clone(), cx, move |settings, _cx| {
2584                            *(field.pick_mut)(settings) = Some(value);
2585                        })
2586                        .log_err(); // todo(settings_ui) don't log err
2587                    },
2588                );
2589            }
2590            menu
2591        }),
2592    )
2593    .trigger_size(ButtonSize::Medium)
2594    .style(DropdownStyle::Outlined)
2595    .offset(gpui::Point {
2596        x: px(0.0),
2597        y: px(2.0),
2598    })
2599    .tab_index(0)
2600    .into_any_element()
2601}
2602
2603#[cfg(test)]
2604mod test {
2605
2606    use super::*;
2607
2608    impl SettingsWindow {
2609        fn navbar_entry(&self) -> usize {
2610            self.navbar_entry
2611        }
2612    }
2613
2614    impl PartialEq for NavBarEntry {
2615        fn eq(&self, other: &Self) -> bool {
2616            self.title == other.title
2617                && self.is_root == other.is_root
2618                && self.expanded == other.expanded
2619                && self.page_index == other.page_index
2620                && self.item_index == other.item_index
2621            // ignoring focus_handle
2622        }
2623    }
2624
2625    fn register_settings(cx: &mut App) {
2626        settings::init(cx);
2627        theme::init(theme::LoadThemes::JustBase, cx);
2628        workspace::init_settings(cx);
2629        project::Project::init_settings(cx);
2630        language::init(cx);
2631        editor::init(cx);
2632        menu::init();
2633    }
2634
2635    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2636        let mut pages: Vec<SettingsPage> = Vec::new();
2637        let mut expanded_pages = Vec::new();
2638        let mut selected_idx = None;
2639        let mut index = 0;
2640        let mut in_expanded_section = false;
2641
2642        for mut line in input
2643            .lines()
2644            .map(|line| line.trim())
2645            .filter(|line| !line.is_empty())
2646        {
2647            if let Some(pre) = line.strip_suffix('*') {
2648                assert!(selected_idx.is_none(), "Only one selected entry allowed");
2649                selected_idx = Some(index);
2650                line = pre;
2651            }
2652            let (kind, title) = line.split_once(" ").unwrap();
2653            assert_eq!(kind.len(), 1);
2654            let kind = kind.chars().next().unwrap();
2655            if kind == 'v' {
2656                let page_idx = pages.len();
2657                expanded_pages.push(page_idx);
2658                pages.push(SettingsPage {
2659                    title,
2660                    items: vec![],
2661                });
2662                index += 1;
2663                in_expanded_section = true;
2664            } else if kind == '>' {
2665                pages.push(SettingsPage {
2666                    title,
2667                    items: vec![],
2668                });
2669                index += 1;
2670                in_expanded_section = false;
2671            } else if kind == '-' {
2672                pages
2673                    .last_mut()
2674                    .unwrap()
2675                    .items
2676                    .push(SettingsPageItem::SectionHeader(title));
2677                if selected_idx == Some(index) && !in_expanded_section {
2678                    panic!("Items in unexpanded sections cannot be selected");
2679                }
2680                index += 1;
2681            } else {
2682                panic!(
2683                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
2684                    line
2685                );
2686            }
2687        }
2688
2689        let mut settings_window = SettingsWindow {
2690            title_bar: None,
2691            original_window: None,
2692            worktree_root_dirs: HashMap::default(),
2693            files: Vec::default(),
2694            current_file: crate::SettingsUiFile::User,
2695            pages,
2696            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2697            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2698            navbar_entries: Vec::default(),
2699            navbar_scroll_handle: UniformListScrollHandle::default(),
2700            navbar_focus_subscriptions: vec![],
2701            filter_table: vec![],
2702            has_query: false,
2703            content_handles: vec![],
2704            search_task: None,
2705            page_scroll_handle: ScrollHandle::new(),
2706            focus_handle: cx.focus_handle(),
2707            navbar_focus_handle: NonFocusableHandle::new(
2708                NAVBAR_CONTAINER_TAB_INDEX,
2709                false,
2710                window,
2711                cx,
2712            ),
2713            content_focus_handle: NonFocusableHandle::new(
2714                CONTENT_CONTAINER_TAB_INDEX,
2715                false,
2716                window,
2717                cx,
2718            ),
2719            files_focus_handle: cx.focus_handle(),
2720            search_index: None,
2721        };
2722
2723        settings_window.build_filter_table();
2724        settings_window.build_navbar(cx);
2725        for expanded_page_index in expanded_pages {
2726            for entry in &mut settings_window.navbar_entries {
2727                if entry.page_index == expanded_page_index && entry.is_root {
2728                    entry.expanded = true;
2729                }
2730            }
2731        }
2732        settings_window
2733    }
2734
2735    #[track_caller]
2736    fn check_navbar_toggle(
2737        before: &'static str,
2738        toggle_page: &'static str,
2739        after: &'static str,
2740        window: &mut Window,
2741        cx: &mut App,
2742    ) {
2743        let mut settings_window = parse(before, window, cx);
2744        let toggle_page_idx = settings_window
2745            .pages
2746            .iter()
2747            .position(|page| page.title == toggle_page)
2748            .expect("page not found");
2749        let toggle_idx = settings_window
2750            .navbar_entries
2751            .iter()
2752            .position(|entry| entry.page_index == toggle_page_idx)
2753            .expect("page not found");
2754        settings_window.toggle_navbar_entry(toggle_idx);
2755
2756        let expected_settings_window = parse(after, window, cx);
2757
2758        pretty_assertions::assert_eq!(
2759            settings_window
2760                .visible_navbar_entries()
2761                .map(|(_, entry)| entry)
2762                .collect::<Vec<_>>(),
2763            expected_settings_window
2764                .visible_navbar_entries()
2765                .map(|(_, entry)| entry)
2766                .collect::<Vec<_>>(),
2767        );
2768        pretty_assertions::assert_eq!(
2769            settings_window.navbar_entries[settings_window.navbar_entry()],
2770            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2771        );
2772    }
2773
2774    macro_rules! check_navbar_toggle {
2775        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2776            #[gpui::test]
2777            fn $name(cx: &mut gpui::TestAppContext) {
2778                let window = cx.add_empty_window();
2779                window.update(|window, cx| {
2780                    register_settings(cx);
2781                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
2782                });
2783            }
2784        };
2785    }
2786
2787    check_navbar_toggle!(
2788        navbar_basic_open,
2789        before: r"
2790        v General
2791        - General
2792        - Privacy*
2793        v Project
2794        - Project Settings
2795        ",
2796        toggle_page: "General",
2797        after: r"
2798        > General*
2799        v Project
2800        - Project Settings
2801        "
2802    );
2803
2804    check_navbar_toggle!(
2805        navbar_basic_close,
2806        before: r"
2807        > General*
2808        - General
2809        - Privacy
2810        v Project
2811        - Project Settings
2812        ",
2813        toggle_page: "General",
2814        after: r"
2815        v General*
2816        - General
2817        - Privacy
2818        v Project
2819        - Project Settings
2820        "
2821    );
2822
2823    check_navbar_toggle!(
2824        navbar_basic_second_root_entry_close,
2825        before: r"
2826        > General
2827        - General
2828        - Privacy
2829        v Project
2830        - Project Settings*
2831        ",
2832        toggle_page: "Project",
2833        after: r"
2834        > General
2835        > Project*
2836        "
2837    );
2838
2839    check_navbar_toggle!(
2840        navbar_toggle_subroot,
2841        before: r"
2842        v General Page
2843        - General
2844        - Privacy
2845        v Project
2846        - Worktree Settings Content*
2847        v AI
2848        - General
2849        > Appearance & Behavior
2850        ",
2851        toggle_page: "Project",
2852        after: r"
2853        v General Page
2854        - General
2855        - Privacy
2856        > Project*
2857        v AI
2858        - General
2859        > Appearance & Behavior
2860        "
2861    );
2862
2863    check_navbar_toggle!(
2864        navbar_toggle_close_propagates_selected_index,
2865        before: r"
2866        v General Page
2867        - General
2868        - Privacy
2869        v Project
2870        - Worktree Settings Content
2871        v AI
2872        - General*
2873        > Appearance & Behavior
2874        ",
2875        toggle_page: "General Page",
2876        after: r"
2877        > General Page
2878        v Project
2879        - Worktree Settings Content
2880        v AI
2881        - General*
2882        > Appearance & Behavior
2883        "
2884    );
2885
2886    check_navbar_toggle!(
2887        navbar_toggle_expand_propagates_selected_index,
2888        before: r"
2889        > General Page
2890        - General
2891        - Privacy
2892        v Project
2893        - Worktree Settings Content
2894        v AI
2895        - General*
2896        > Appearance & Behavior
2897        ",
2898        toggle_page: "General Page",
2899        after: r"
2900        v General Page
2901        - General
2902        - Privacy
2903        v Project
2904        - Worktree Settings Content
2905        v AI
2906        - General*
2907        > Appearance & Behavior
2908        "
2909    );
2910}