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