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        let this = cx.entity();
1537        h_flex()
1538            .w_full()
1539            .pb_4()
1540            .gap_1()
1541            .justify_between()
1542            .tab_group()
1543            .track_focus(&self.files_focus_handle)
1544            .tab_index(HEADER_GROUP_TAB_INDEX)
1545            .child(
1546                h_flex()
1547                    .id("file_buttons_container")
1548                    .gap_1()
1549                    .overflow_x_scroll()
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::Ghost)
1609                                    .tab_index(0)
1610                                    .no_chevron(),
1611                                )
1612                            },
1613                        )
1614                    }),
1615            )
1616            .child(
1617                Button::new("edit-in-json", "Edit in settings.json")
1618                    .tab_index(0_isize)
1619                    .style(ButtonStyle::OutlinedGhost)
1620                    .on_click(cx.listener(|this, _, _, cx| {
1621                        this.open_current_settings_file(cx);
1622                    })),
1623            )
1624    }
1625
1626    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1627        match file {
1628            SettingsUiFile::User => Some("User".to_string()),
1629            SettingsUiFile::Project((worktree_id, path)) => self
1630                .worktree_root_dirs
1631                .get(&worktree_id)
1632                .map(|directory_name| {
1633                    let path_style = PathStyle::local();
1634                    if path.is_empty() {
1635                        directory_name.clone()
1636                    } else {
1637                        format!(
1638                            "{}{}{}",
1639                            directory_name,
1640                            path_style.separator(),
1641                            path.display(path_style)
1642                        )
1643                    }
1644                }),
1645            SettingsUiFile::Server(file) => Some(file.to_string()),
1646        }
1647    }
1648
1649    // TODO:
1650    //  Reconsider this after preview launch
1651    // fn file_location_str(&self) -> String {
1652    //     match &self.current_file {
1653    //         SettingsUiFile::User => "settings.json".to_string(),
1654    //         SettingsUiFile::Project((worktree_id, path)) => self
1655    //             .worktree_root_dirs
1656    //             .get(&worktree_id)
1657    //             .map(|directory_name| {
1658    //                 let path_style = PathStyle::local();
1659    //                 let file_path = path.join(paths::local_settings_file_relative_path());
1660    //                 format!(
1661    //                     "{}{}{}",
1662    //                     directory_name,
1663    //                     path_style.separator(),
1664    //                     file_path.display(path_style)
1665    //                 )
1666    //             })
1667    //             .expect("Current file should always be present in root dir map"),
1668    //         SettingsUiFile::Server(file) => file.to_string(),
1669    //     }
1670    // }
1671
1672    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1673        h_flex()
1674            .py_1()
1675            .px_1p5()
1676            .mb_3()
1677            .gap_1p5()
1678            .rounded_sm()
1679            .bg(cx.theme().colors().editor_background)
1680            .border_1()
1681            .border_color(cx.theme().colors().border)
1682            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1683            .child(self.search_bar.clone())
1684    }
1685
1686    fn render_nav(
1687        &self,
1688        window: &mut Window,
1689        cx: &mut Context<SettingsWindow>,
1690    ) -> impl IntoElement {
1691        let visible_count = self.visible_navbar_entries().count();
1692
1693        let focus_keybind_label = if self
1694            .navbar_focus_handle
1695            .read(cx)
1696            .handle
1697            .contains_focused(window, cx)
1698        {
1699            "Focus Content"
1700        } else {
1701            "Focus Navbar"
1702        };
1703
1704        v_flex()
1705            .w_56()
1706            .p_2p5()
1707            .when(cfg!(target_os = "macos"), |c| c.pt_10())
1708            .h_full()
1709            .flex_none()
1710            .border_r_1()
1711            .key_context("NavigationMenu")
1712            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1713                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1714                    return;
1715                };
1716                let focused_entry_parent = this.root_entry_containing(focused_entry);
1717                if this.navbar_entries[focused_entry_parent].expanded {
1718                    this.toggle_navbar_entry(focused_entry_parent);
1719                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1720                }
1721                cx.notify();
1722            }))
1723            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1724                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1725                    return;
1726                };
1727                if !this.navbar_entries[focused_entry].is_root {
1728                    return;
1729                }
1730                if !this.navbar_entries[focused_entry].expanded {
1731                    this.toggle_navbar_entry(focused_entry);
1732                }
1733                cx.notify();
1734            }))
1735            .on_action(
1736                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1737                    let entry_index = this
1738                        .focused_nav_entry(window, cx)
1739                        .unwrap_or(this.navbar_entry);
1740                    let mut root_index = None;
1741                    for (index, entry) in this.visible_navbar_entries() {
1742                        if index >= entry_index {
1743                            break;
1744                        }
1745                        if entry.is_root {
1746                            root_index = Some(index);
1747                        }
1748                    }
1749                    let Some(previous_root_index) = root_index else {
1750                        return;
1751                    };
1752                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
1753                }),
1754            )
1755            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
1756                let entry_index = this
1757                    .focused_nav_entry(window, cx)
1758                    .unwrap_or(this.navbar_entry);
1759                let mut root_index = None;
1760                for (index, entry) in this.visible_navbar_entries() {
1761                    if index <= entry_index {
1762                        continue;
1763                    }
1764                    if entry.is_root {
1765                        root_index = Some(index);
1766                        break;
1767                    }
1768                }
1769                let Some(next_root_index) = root_index else {
1770                    return;
1771                };
1772                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
1773            }))
1774            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
1775                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1776                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
1777                }
1778            }))
1779            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
1780                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1781                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
1782                }
1783            }))
1784            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
1785                let entry_index = this
1786                    .focused_nav_entry(window, cx)
1787                    .unwrap_or(this.navbar_entry);
1788                let mut next_index = None;
1789                for (index, _) in this.visible_navbar_entries() {
1790                    if index > entry_index {
1791                        next_index = Some(index);
1792                        break;
1793                    }
1794                }
1795                let Some(next_entry_index) = next_index else {
1796                    return;
1797                };
1798                this.open_and_scroll_to_navbar_entry(next_entry_index, window, cx, false);
1799            }))
1800            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
1801                let entry_index = this
1802                    .focused_nav_entry(window, cx)
1803                    .unwrap_or(this.navbar_entry);
1804                let mut prev_index = None;
1805                for (index, _) in this.visible_navbar_entries() {
1806                    if index >= entry_index {
1807                        break;
1808                    }
1809                    prev_index = Some(index);
1810                }
1811                let Some(prev_entry_index) = prev_index else {
1812                    return;
1813                };
1814                this.open_and_scroll_to_navbar_entry(prev_entry_index, window, cx, false);
1815            }))
1816            .border_color(cx.theme().colors().border)
1817            .bg(cx.theme().colors().panel_background)
1818            .child(self.render_search(window, cx))
1819            .child(
1820                v_flex()
1821                    .flex_1()
1822                    .overflow_hidden()
1823                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1824                    .tab_group()
1825                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
1826                    .child(
1827                        uniform_list(
1828                            "settings-ui-nav-bar",
1829                            visible_count + 1,
1830                            cx.processor(move |this, range: Range<usize>, _, cx| {
1831                                this.visible_navbar_entries()
1832                                    .skip(range.start.saturating_sub(1))
1833                                    .take(range.len())
1834                                    .map(|(ix, entry)| {
1835                                        TreeViewItem::new(
1836                                            ("settings-ui-navbar-entry", ix),
1837                                            entry.title,
1838                                        )
1839                                        .track_focus(&entry.focus_handle)
1840                                        .root_item(entry.is_root)
1841                                        .toggle_state(this.is_navbar_entry_selected(ix))
1842                                        .when(entry.is_root, |item| {
1843                                            item.expanded(entry.expanded || this.has_query)
1844                                                .on_toggle(cx.listener(
1845                                                    move |this, _, window, cx| {
1846                                                        this.toggle_navbar_entry(ix);
1847                                                        // Update selection state immediately before cx.notify
1848                                                        // to prevent double selection flash
1849                                                        this.navbar_entry = ix;
1850                                                        window.focus(
1851                                                            &this.navbar_entries[ix].focus_handle,
1852                                                        );
1853                                                        cx.notify();
1854                                                    },
1855                                                ))
1856                                        })
1857                                        .on_click(
1858                                            cx.listener(move |this, _, window, cx| {
1859                                                this.open_and_scroll_to_navbar_entry(
1860                                                    ix, window, cx, true,
1861                                                );
1862                                            }),
1863                                        )
1864                                    })
1865                                    .collect()
1866                            }),
1867                        )
1868                        .size_full()
1869                        .track_scroll(self.navbar_scroll_handle.clone()),
1870                    )
1871                    .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
1872            )
1873            .child(
1874                h_flex()
1875                    .w_full()
1876                    .h_8()
1877                    .p_2()
1878                    .pb_0p5()
1879                    .flex_shrink_0()
1880                    .border_t_1()
1881                    .border_color(cx.theme().colors().border_variant)
1882                    .children(
1883                        KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1884                            KeybindingHint::new(
1885                                this,
1886                                cx.theme().colors().surface_background.opacity(0.5),
1887                            )
1888                            .suffix(focus_keybind_label)
1889                        }),
1890                    ),
1891            )
1892    }
1893
1894    fn open_and_scroll_to_navbar_entry(
1895        &mut self,
1896        navbar_entry_index: usize,
1897        window: &mut Window,
1898        cx: &mut Context<Self>,
1899        focus_content: bool,
1900    ) {
1901        self.open_navbar_entry_page(navbar_entry_index);
1902        cx.notify();
1903
1904        if self.navbar_entries[navbar_entry_index].is_root
1905            || !self.is_nav_entry_visible(navbar_entry_index)
1906        {
1907            self.page_scroll_handle.set_offset(point(px(0.), px(0.)));
1908            if focus_content {
1909                let Some(first_item_index) =
1910                    self.visible_page_items().next().map(|(index, _)| index)
1911                else {
1912                    return;
1913                };
1914                self.focus_content_element(first_item_index, window, cx);
1915            } else {
1916                window.focus(&self.navbar_entries[navbar_entry_index].focus_handle);
1917            }
1918        } else {
1919            let entry_item_index = self.navbar_entries[navbar_entry_index]
1920                .item_index
1921                .expect("Non-root items should have an item index");
1922            let Some(selected_item_index) = self
1923                .visible_page_items()
1924                .position(|(index, _)| index == entry_item_index)
1925            else {
1926                return;
1927            };
1928            self.page_scroll_handle
1929                .scroll_to_top_of_item(selected_item_index + 1);
1930
1931            if focus_content {
1932                self.focus_content_element(entry_item_index, window, cx);
1933            } else {
1934                window.focus(&self.navbar_entries[navbar_entry_index].focus_handle);
1935            }
1936        }
1937
1938        // Page scroll handle updates the active item index
1939        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
1940        // The call after that updates the offset of the scroll handle. So to
1941        // ensure the scroll handle doesn't lag behind we need to render three frames
1942        // back to back.
1943        cx.on_next_frame(window, |_, window, cx| {
1944            cx.on_next_frame(window, |_, _, cx| {
1945                cx.notify();
1946            });
1947            cx.notify();
1948        });
1949        cx.notify();
1950    }
1951
1952    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
1953        self.visible_navbar_entries()
1954            .any(|(index, _)| index == nav_entry_index)
1955    }
1956
1957    fn focus_and_scroll_to_nav_entry(
1958        &self,
1959        nav_entry_index: usize,
1960        window: &mut Window,
1961        cx: &mut Context<Self>,
1962    ) {
1963        let Some(position) = self
1964            .visible_navbar_entries()
1965            .position(|(index, _)| index == nav_entry_index)
1966        else {
1967            return;
1968        };
1969        self.navbar_scroll_handle
1970            .scroll_to_item(position, gpui::ScrollStrategy::Top);
1971        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
1972        cx.notify();
1973    }
1974
1975    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1976        let page_idx = self.current_page_index();
1977
1978        self.current_page()
1979            .items
1980            .iter()
1981            .enumerate()
1982            .filter_map(move |(item_index, item)| {
1983                self.filter_table[page_idx][item_index].then_some((item_index, item))
1984            })
1985    }
1986
1987    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1988        let mut items = vec![];
1989        items.push(self.current_page().title.into());
1990        items.extend(
1991            sub_page_stack()
1992                .iter()
1993                .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
1994        );
1995
1996        let last = items.pop().unwrap();
1997        h_flex()
1998            .gap_1()
1999            .children(
2000                items
2001                    .into_iter()
2002                    .flat_map(|item| [item, "/".into()])
2003                    .map(|item| Label::new(item).color(Color::Muted)),
2004            )
2005            .child(Label::new(last))
2006    }
2007
2008    fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2009        &self,
2010        items: Items,
2011        page_index: Option<usize>,
2012        window: &mut Window,
2013        cx: &mut Context<SettingsWindow>,
2014    ) -> impl IntoElement {
2015        let mut page_content = v_flex()
2016            .id("settings-ui-page")
2017            .size_full()
2018            .overflow_y_scroll()
2019            .track_scroll(&self.page_scroll_handle);
2020
2021        let items: Vec<_> = items.collect();
2022        let items_len = items.len();
2023        let mut section_header = None;
2024
2025        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2026        let has_no_results = items_len == 0 && has_active_search;
2027
2028        if has_no_results {
2029            let search_query = self.search_bar.read(cx).text(cx);
2030            page_content = page_content.child(
2031                v_flex()
2032                    .size_full()
2033                    .items_center()
2034                    .justify_center()
2035                    .gap_1()
2036                    .child(div().child("No Results"))
2037                    .child(
2038                        div()
2039                            .text_sm()
2040                            .text_color(cx.theme().colors().text_muted)
2041                            .child(format!("No settings match \"{}\"", search_query)),
2042                    ),
2043            )
2044        } else {
2045            let last_non_header_index = items
2046                .iter()
2047                .enumerate()
2048                .rev()
2049                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2050                .map(|(index, _)| index);
2051
2052            let root_nav_label = self
2053                .navbar_entries
2054                .iter()
2055                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2056                .map(|entry| entry.title);
2057
2058            page_content = page_content
2059                .when(sub_page_stack().is_empty(), |this| {
2060                    this.when_some(root_nav_label, |this, title| {
2061                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2062                    })
2063                })
2064                .children(items.clone().into_iter().enumerate().map(
2065                    |(index, (actual_item_index, item))| {
2066                        let no_bottom_border = items
2067                            .get(index + 1)
2068                            .map(|(_, next_item)| {
2069                                matches!(next_item, SettingsPageItem::SectionHeader(_))
2070                            })
2071                            .unwrap_or(false);
2072                        let is_last = Some(index) == last_non_header_index;
2073
2074                        if let SettingsPageItem::SectionHeader(header) = item {
2075                            section_header = Some(*header);
2076                        }
2077                        v_flex()
2078                            .w_full()
2079                            .min_w_0()
2080                            .id(("settings-page-item", actual_item_index))
2081                            .when_some(page_index, |element, page_index| {
2082                                element.track_focus(
2083                                    &self.content_handles[page_index][actual_item_index]
2084                                        .focus_handle(cx),
2085                                )
2086                            })
2087                            .child(item.render(
2088                                self,
2089                                section_header.expect("All items rendered after a section header"),
2090                                no_bottom_border || is_last,
2091                                window,
2092                                cx,
2093                            ))
2094                    },
2095                ))
2096        }
2097        page_content
2098    }
2099
2100    fn render_page(
2101        &mut self,
2102        window: &mut Window,
2103        cx: &mut Context<SettingsWindow>,
2104    ) -> impl IntoElement {
2105        let page_header;
2106        let page_content;
2107
2108        if sub_page_stack().is_empty() {
2109            page_header = self.render_files_header(window, cx).into_any_element();
2110
2111            page_content = self
2112                .render_page_items(
2113                    self.visible_page_items(),
2114                    Some(self.current_page_index()),
2115                    window,
2116                    cx,
2117                )
2118                .into_any_element();
2119        } else {
2120            page_header = h_flex()
2121                .ml_neg_1p5()
2122                .pb_4()
2123                .gap_1()
2124                .child(
2125                    IconButton::new("back-btn", IconName::ArrowLeft)
2126                        .icon_size(IconSize::Small)
2127                        .shape(IconButtonShape::Square)
2128                        .on_click(cx.listener(|this, _, _, cx| {
2129                            this.pop_sub_page(cx);
2130                        })),
2131                )
2132                .child(self.render_sub_page_breadcrumbs())
2133                .into_any_element();
2134
2135            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2136            page_content = (active_page_render_fn)(self, window, cx);
2137        }
2138
2139        return v_flex()
2140            .flex_1()
2141            .pt_6()
2142            .pb_8()
2143            .px_8()
2144            .bg(cx.theme().colors().editor_background)
2145            .child(page_header)
2146            .vertical_scrollbar_for(self.page_scroll_handle.clone(), window, cx)
2147            .track_focus(&self.content_focus_handle.focus_handle(cx))
2148            .child(
2149                div()
2150                    .size_full()
2151                    .tab_group()
2152                    .tab_index(CONTENT_GROUP_TAB_INDEX)
2153                    .child(page_content),
2154            );
2155    }
2156
2157    fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2158        match &self.current_file {
2159            SettingsUiFile::User => {
2160                let Some(original_window) = self.original_window else {
2161                    return;
2162                };
2163                original_window
2164                    .update(cx, |workspace, window, cx| {
2165                        workspace
2166                            .with_local_workspace(window, cx, |workspace, window, cx| {
2167                                let create_task = workspace.project().update(cx, |project, cx| {
2168                                    project.find_or_create_worktree(
2169                                        paths::config_dir().as_path(),
2170                                        false,
2171                                        cx,
2172                                    )
2173                                });
2174                                let open_task = workspace.open_paths(
2175                                    vec![paths::settings_file().to_path_buf()],
2176                                    OpenOptions {
2177                                        visible: Some(OpenVisible::None),
2178                                        ..Default::default()
2179                                    },
2180                                    None,
2181                                    window,
2182                                    cx,
2183                                );
2184
2185                                cx.spawn_in(window, async move |workspace, cx| {
2186                                    create_task.await.ok();
2187                                    open_task.await;
2188
2189                                    workspace.update_in(cx, |_, window, cx| {
2190                                        window.activate_window();
2191                                        cx.notify();
2192                                    })
2193                                })
2194                                .detach();
2195                            })
2196                            .detach();
2197                    })
2198                    .ok();
2199            }
2200            SettingsUiFile::Project((worktree_id, path)) => {
2201                let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
2202                let settings_path = path.join(paths::local_settings_file_relative_path());
2203                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2204                    return;
2205                };
2206                for workspace in app_state.workspace_store.read(cx).workspaces() {
2207                    let contains_settings_file = workspace
2208                        .read_with(cx, |workspace, cx| {
2209                            workspace.project().read(cx).contains_local_settings_file(
2210                                *worktree_id,
2211                                settings_path.as_ref(),
2212                                cx,
2213                            )
2214                        })
2215                        .ok();
2216                    if Some(true) == contains_settings_file {
2217                        corresponding_workspace = Some(*workspace);
2218
2219                        break;
2220                    }
2221                }
2222
2223                let Some(corresponding_workspace) = corresponding_workspace else {
2224                    log::error!(
2225                        "No corresponding workspace found for settings file {}",
2226                        settings_path.as_std_path().display()
2227                    );
2228
2229                    return;
2230                };
2231
2232                // TODO: move zed::open_local_file() APIs to this crate, and
2233                // re-implement the "initial_contents" behavior
2234                corresponding_workspace
2235                    .update(cx, |workspace, window, cx| {
2236                        let open_task = workspace.open_path(
2237                            (*worktree_id, settings_path.clone()),
2238                            None,
2239                            true,
2240                            window,
2241                            cx,
2242                        );
2243
2244                        cx.spawn_in(window, async move |workspace, cx| {
2245                            if open_task.await.log_err().is_some() {
2246                                workspace
2247                                    .update_in(cx, |_, window, cx| {
2248                                        window.activate_window();
2249                                        cx.notify();
2250                                    })
2251                                    .ok();
2252                            }
2253                        })
2254                        .detach();
2255                    })
2256                    .ok();
2257            }
2258            SettingsUiFile::Server(_) => {
2259                return;
2260            }
2261        };
2262    }
2263
2264    fn current_page_index(&self) -> usize {
2265        self.page_index_from_navbar_index(self.navbar_entry)
2266    }
2267
2268    fn current_page(&self) -> &SettingsPage {
2269        &self.pages[self.current_page_index()]
2270    }
2271
2272    fn page_index_from_navbar_index(&self, index: usize) -> usize {
2273        if self.navbar_entries.is_empty() {
2274            return 0;
2275        }
2276
2277        self.navbar_entries[index].page_index
2278    }
2279
2280    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2281        ix == self.navbar_entry
2282    }
2283
2284    fn push_sub_page(
2285        &mut self,
2286        sub_page_link: SubPageLink,
2287        section_header: &'static str,
2288        cx: &mut Context<SettingsWindow>,
2289    ) {
2290        sub_page_stack_mut().push(SubPage {
2291            link: sub_page_link,
2292            section_header,
2293        });
2294        cx.notify();
2295    }
2296
2297    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
2298        sub_page_stack_mut().pop();
2299        cx.notify();
2300    }
2301
2302    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
2303        if let Some((_, handle)) = self.files.get(index) {
2304            handle.focus(window);
2305        }
2306    }
2307
2308    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
2309        if self.files_focus_handle.contains_focused(window, cx)
2310            && let Some(index) = self
2311                .files
2312                .iter()
2313                .position(|(_, handle)| handle.is_focused(window))
2314        {
2315            return index;
2316        }
2317        if let Some(current_file_index) = self
2318            .files
2319            .iter()
2320            .position(|(file, _)| file == &self.current_file)
2321        {
2322            return current_file_index;
2323        }
2324        0
2325    }
2326
2327    fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
2328        if !sub_page_stack().is_empty() {
2329            return;
2330        }
2331        let page_index = self.current_page_index();
2332        window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
2333    }
2334
2335    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
2336        if !self
2337            .navbar_focus_handle
2338            .focus_handle(cx)
2339            .contains_focused(window, cx)
2340        {
2341            return None;
2342        }
2343        for (index, entry) in self.navbar_entries.iter().enumerate() {
2344            if entry.focus_handle.is_focused(window) {
2345                return Some(index);
2346            }
2347        }
2348        None
2349    }
2350
2351    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
2352        let mut index = Some(nav_entry_index);
2353        while let Some(prev_index) = index
2354            && !self.navbar_entries[prev_index].is_root
2355        {
2356            index = prev_index.checked_sub(1);
2357        }
2358        return index.expect("No root entry found");
2359    }
2360}
2361
2362impl Render for SettingsWindow {
2363    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2364        let ui_font = theme::setup_ui_font(window, cx);
2365
2366        client_side_decorations(
2367            v_flex()
2368                .text_color(cx.theme().colors().text)
2369                .size_full()
2370                .children(self.title_bar.clone())
2371                .child(
2372                    div()
2373                        .id("settings-window")
2374                        .key_context("SettingsWindow")
2375                        .track_focus(&self.focus_handle)
2376                        .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2377                            this.open_current_settings_file(cx);
2378                        }))
2379                        .on_action(|_: &Minimize, window, _cx| {
2380                            window.minimize_window();
2381                        })
2382                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2383                            this.search_bar.focus_handle(cx).focus(window);
2384                        }))
2385                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2386                            if this
2387                                .navbar_focus_handle
2388                                .focus_handle(cx)
2389                                .contains_focused(window, cx)
2390                            {
2391                                this.open_and_scroll_to_navbar_entry(
2392                                    this.navbar_entry,
2393                                    window,
2394                                    cx,
2395                                    true,
2396                                );
2397                            } else {
2398                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
2399                            }
2400                        }))
2401                        .on_action(cx.listener(
2402                            |this, FocusFile(file_index): &FocusFile, window, _| {
2403                                this.focus_file_at_index(*file_index as usize, window);
2404                            },
2405                        ))
2406                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2407                            let next_index = usize::min(
2408                                this.focused_file_index(window, cx) + 1,
2409                                this.files.len().saturating_sub(1),
2410                            );
2411                            this.focus_file_at_index(next_index, window);
2412                        }))
2413                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2414                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2415                            this.focus_file_at_index(prev_index, window);
2416                        }))
2417                        .on_action(|_: &menu::SelectNext, window, _| {
2418                            window.focus_next();
2419                        })
2420                        .on_action(|_: &menu::SelectPrevious, window, _| {
2421                            window.focus_prev();
2422                        })
2423                        .flex()
2424                        .flex_row()
2425                        .flex_1()
2426                        .min_h_0()
2427                        .font(ui_font)
2428                        .bg(cx.theme().colors().background)
2429                        .text_color(cx.theme().colors().text)
2430                        .child(self.render_nav(window, cx))
2431                        .child(self.render_page(window, cx)),
2432                ),
2433            window,
2434            cx,
2435        )
2436    }
2437}
2438
2439fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2440    workspace::AppState::global(cx)
2441        .upgrade()
2442        .map(|app_state| {
2443            app_state
2444                .workspace_store
2445                .read(cx)
2446                .workspaces()
2447                .iter()
2448                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2449        })
2450        .into_iter()
2451        .flatten()
2452}
2453
2454fn update_settings_file(
2455    file: SettingsUiFile,
2456    cx: &mut App,
2457    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2458) -> Result<()> {
2459    match file {
2460        SettingsUiFile::Project((worktree_id, rel_path)) => {
2461            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2462            let project = all_projects(cx).find(|project| {
2463                project.read_with(cx, |project, cx| {
2464                    project.contains_local_settings_file(worktree_id, &rel_path, cx)
2465                })
2466            });
2467            let Some(project) = project else {
2468                anyhow::bail!(
2469                    "Could not find worktree containing settings file: {}",
2470                    &rel_path.display(PathStyle::local())
2471                );
2472            };
2473            project.update(cx, |project, cx| {
2474                project.update_local_settings_file(worktree_id, rel_path, cx, update);
2475            });
2476            return Ok(());
2477        }
2478        SettingsUiFile::User => {
2479            // todo(settings_ui) error?
2480            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2481            Ok(())
2482        }
2483        SettingsUiFile::Server(_) => unimplemented!(),
2484    }
2485}
2486
2487fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2488    field: SettingField<T>,
2489    file: SettingsUiFile,
2490    metadata: Option<&SettingsFieldMetadata>,
2491    _window: &mut Window,
2492    cx: &mut App,
2493) -> AnyElement {
2494    let (_, initial_text) =
2495        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2496    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2497
2498    SettingsEditor::new()
2499        .tab_index(0)
2500        .when_some(initial_text, |editor, text| {
2501            editor.with_initial_text(text.as_ref().to_string())
2502        })
2503        .when_some(
2504            metadata.and_then(|metadata| metadata.placeholder),
2505            |editor, placeholder| editor.with_placeholder(placeholder),
2506        )
2507        .on_confirm({
2508            move |new_text, cx| {
2509                update_settings_file(file.clone(), cx, move |settings, _cx| {
2510                    *(field.pick_mut)(settings) = new_text.map(Into::into);
2511                })
2512                .log_err(); // todo(settings_ui) don't log err
2513            }
2514        })
2515        .into_any_element()
2516}
2517
2518fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2519    field: SettingField<B>,
2520    file: SettingsUiFile,
2521    _metadata: Option<&SettingsFieldMetadata>,
2522    _window: &mut Window,
2523    cx: &mut App,
2524) -> AnyElement {
2525    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2526
2527    let toggle_state = if value.copied().map_or(false, Into::into) {
2528        ToggleState::Selected
2529    } else {
2530        ToggleState::Unselected
2531    };
2532
2533    Switch::new("toggle_button", toggle_state)
2534        .color(ui::SwitchColor::Accent)
2535        .on_click({
2536            move |state, _window, cx| {
2537                let state = *state == ui::ToggleState::Selected;
2538                update_settings_file(file.clone(), cx, move |settings, _cx| {
2539                    *(field.pick_mut)(settings) = Some(state.into());
2540                })
2541                .log_err(); // todo(settings_ui) don't log err
2542            }
2543        })
2544        .tab_index(0_isize)
2545        .color(SwitchColor::Accent)
2546        .into_any_element()
2547}
2548
2549fn render_font_picker(
2550    field: SettingField<settings::FontFamilyName>,
2551    file: SettingsUiFile,
2552    _metadata: Option<&SettingsFieldMetadata>,
2553    window: &mut Window,
2554    cx: &mut App,
2555) -> AnyElement {
2556    let current_value = SettingsStore::global(cx)
2557        .get_value_from_file(file.to_settings(), field.pick)
2558        .1
2559        .cloned()
2560        .unwrap_or_else(|| SharedString::default().into());
2561
2562    let font_picker = cx.new(|cx| {
2563        ui_input::font_picker(
2564            current_value.clone().into(),
2565            move |font_name, cx| {
2566                update_settings_file(file.clone(), cx, move |settings, _cx| {
2567                    *(field.pick_mut)(settings) = Some(font_name.into());
2568                })
2569                .log_err(); // todo(settings_ui) don't log err
2570            },
2571            window,
2572            cx,
2573        )
2574    });
2575
2576    PopoverMenu::new("font-picker")
2577        .menu(move |_window, _cx| Some(font_picker.clone()))
2578        .trigger(
2579            Button::new("font-family-button", current_value)
2580                .tab_index(0_isize)
2581                .style(ButtonStyle::Outlined)
2582                .size(ButtonSize::Medium)
2583                .icon(IconName::ChevronUpDown)
2584                .icon_color(Color::Muted)
2585                .icon_size(IconSize::Small)
2586                .icon_position(IconPosition::End),
2587        )
2588        .anchor(gpui::Corner::TopLeft)
2589        .offset(gpui::Point {
2590            x: px(0.0),
2591            y: px(2.0),
2592        })
2593        .with_handle(ui::PopoverMenuHandle::default())
2594        .into_any_element()
2595}
2596
2597fn render_number_field<T: NumberFieldType + Send + Sync>(
2598    field: SettingField<T>,
2599    file: SettingsUiFile,
2600    _metadata: Option<&SettingsFieldMetadata>,
2601    window: &mut Window,
2602    cx: &mut App,
2603) -> AnyElement {
2604    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2605    let value = value.copied().unwrap_or_else(T::min_value);
2606    NumberField::new("numeric_stepper", value, window, cx)
2607        .on_change({
2608            move |value, _window, cx| {
2609                let value = *value;
2610                update_settings_file(file.clone(), cx, move |settings, _cx| {
2611                    *(field.pick_mut)(settings) = Some(value);
2612                })
2613                .log_err(); // todo(settings_ui) don't log err
2614            }
2615        })
2616        .into_any_element()
2617}
2618
2619fn render_dropdown<T>(
2620    field: SettingField<T>,
2621    file: SettingsUiFile,
2622    metadata: Option<&SettingsFieldMetadata>,
2623    window: &mut Window,
2624    cx: &mut App,
2625) -> AnyElement
2626where
2627    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2628{
2629    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2630    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2631    let should_do_titlecase = metadata
2632        .and_then(|metadata| metadata.should_do_titlecase)
2633        .unwrap_or(true);
2634
2635    let (_, current_value) =
2636        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2637    let current_value = current_value.copied().unwrap_or(variants()[0]);
2638
2639    let current_value_label =
2640        labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2641
2642    DropdownMenu::new(
2643        "dropdown",
2644        if should_do_titlecase {
2645            current_value_label.to_title_case()
2646        } else {
2647            current_value_label.to_string()
2648        },
2649        ContextMenu::build(window, cx, move |mut menu, _, _| {
2650            for (&value, &label) in std::iter::zip(variants(), labels()) {
2651                let file = file.clone();
2652                menu = menu.toggleable_entry(
2653                    if should_do_titlecase {
2654                        label.to_title_case()
2655                    } else {
2656                        label.to_string()
2657                    },
2658                    value == current_value,
2659                    IconPosition::End,
2660                    None,
2661                    move |_, cx| {
2662                        if value == current_value {
2663                            return;
2664                        }
2665                        update_settings_file(file.clone(), cx, move |settings, _cx| {
2666                            *(field.pick_mut)(settings) = Some(value);
2667                        })
2668                        .log_err(); // todo(settings_ui) don't log err
2669                    },
2670                );
2671            }
2672            menu
2673        }),
2674    )
2675    .trigger_size(ButtonSize::Medium)
2676    .style(DropdownStyle::Outlined)
2677    .offset(gpui::Point {
2678        x: px(0.0),
2679        y: px(2.0),
2680    })
2681    .tab_index(0)
2682    .into_any_element()
2683}
2684
2685#[cfg(test)]
2686mod test {
2687
2688    use super::*;
2689
2690    impl SettingsWindow {
2691        fn navbar_entry(&self) -> usize {
2692            self.navbar_entry
2693        }
2694    }
2695
2696    impl PartialEq for NavBarEntry {
2697        fn eq(&self, other: &Self) -> bool {
2698            self.title == other.title
2699                && self.is_root == other.is_root
2700                && self.expanded == other.expanded
2701                && self.page_index == other.page_index
2702                && self.item_index == other.item_index
2703            // ignoring focus_handle
2704        }
2705    }
2706
2707    fn register_settings(cx: &mut App) {
2708        settings::init(cx);
2709        theme::init(theme::LoadThemes::JustBase, cx);
2710        workspace::init_settings(cx);
2711        project::Project::init_settings(cx);
2712        language::init(cx);
2713        editor::init(cx);
2714        menu::init();
2715    }
2716
2717    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2718        let mut pages: Vec<SettingsPage> = Vec::new();
2719        let mut expanded_pages = Vec::new();
2720        let mut selected_idx = None;
2721        let mut index = 0;
2722        let mut in_expanded_section = false;
2723
2724        for mut line in input
2725            .lines()
2726            .map(|line| line.trim())
2727            .filter(|line| !line.is_empty())
2728        {
2729            if let Some(pre) = line.strip_suffix('*') {
2730                assert!(selected_idx.is_none(), "Only one selected entry allowed");
2731                selected_idx = Some(index);
2732                line = pre;
2733            }
2734            let (kind, title) = line.split_once(" ").unwrap();
2735            assert_eq!(kind.len(), 1);
2736            let kind = kind.chars().next().unwrap();
2737            if kind == 'v' {
2738                let page_idx = pages.len();
2739                expanded_pages.push(page_idx);
2740                pages.push(SettingsPage {
2741                    title,
2742                    items: vec![],
2743                });
2744                index += 1;
2745                in_expanded_section = true;
2746            } else if kind == '>' {
2747                pages.push(SettingsPage {
2748                    title,
2749                    items: vec![],
2750                });
2751                index += 1;
2752                in_expanded_section = false;
2753            } else if kind == '-' {
2754                pages
2755                    .last_mut()
2756                    .unwrap()
2757                    .items
2758                    .push(SettingsPageItem::SectionHeader(title));
2759                if selected_idx == Some(index) && !in_expanded_section {
2760                    panic!("Items in unexpanded sections cannot be selected");
2761                }
2762                index += 1;
2763            } else {
2764                panic!(
2765                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
2766                    line
2767                );
2768            }
2769        }
2770
2771        let mut settings_window = SettingsWindow {
2772            title_bar: None,
2773            original_window: None,
2774            worktree_root_dirs: HashMap::default(),
2775            files: Vec::default(),
2776            current_file: crate::SettingsUiFile::User,
2777            drop_down_file: None,
2778            pages,
2779            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2780            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2781            navbar_entries: Vec::default(),
2782            navbar_scroll_handle: UniformListScrollHandle::default(),
2783            navbar_focus_subscriptions: vec![],
2784            filter_table: vec![],
2785            has_query: false,
2786            content_handles: vec![],
2787            search_task: None,
2788            page_scroll_handle: ScrollHandle::new(),
2789            focus_handle: cx.focus_handle(),
2790            navbar_focus_handle: NonFocusableHandle::new(
2791                NAVBAR_CONTAINER_TAB_INDEX,
2792                false,
2793                window,
2794                cx,
2795            ),
2796            content_focus_handle: NonFocusableHandle::new(
2797                CONTENT_CONTAINER_TAB_INDEX,
2798                false,
2799                window,
2800                cx,
2801            ),
2802            files_focus_handle: cx.focus_handle(),
2803            search_index: None,
2804        };
2805
2806        settings_window.build_filter_table();
2807        settings_window.build_navbar(cx);
2808        for expanded_page_index in expanded_pages {
2809            for entry in &mut settings_window.navbar_entries {
2810                if entry.page_index == expanded_page_index && entry.is_root {
2811                    entry.expanded = true;
2812                }
2813            }
2814        }
2815        settings_window
2816    }
2817
2818    #[track_caller]
2819    fn check_navbar_toggle(
2820        before: &'static str,
2821        toggle_page: &'static str,
2822        after: &'static str,
2823        window: &mut Window,
2824        cx: &mut App,
2825    ) {
2826        let mut settings_window = parse(before, window, cx);
2827        let toggle_page_idx = settings_window
2828            .pages
2829            .iter()
2830            .position(|page| page.title == toggle_page)
2831            .expect("page not found");
2832        let toggle_idx = settings_window
2833            .navbar_entries
2834            .iter()
2835            .position(|entry| entry.page_index == toggle_page_idx)
2836            .expect("page not found");
2837        settings_window.toggle_navbar_entry(toggle_idx);
2838
2839        let expected_settings_window = parse(after, window, cx);
2840
2841        pretty_assertions::assert_eq!(
2842            settings_window
2843                .visible_navbar_entries()
2844                .map(|(_, entry)| entry)
2845                .collect::<Vec<_>>(),
2846            expected_settings_window
2847                .visible_navbar_entries()
2848                .map(|(_, entry)| entry)
2849                .collect::<Vec<_>>(),
2850        );
2851        pretty_assertions::assert_eq!(
2852            settings_window.navbar_entries[settings_window.navbar_entry()],
2853            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2854        );
2855    }
2856
2857    macro_rules! check_navbar_toggle {
2858        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2859            #[gpui::test]
2860            fn $name(cx: &mut gpui::TestAppContext) {
2861                let window = cx.add_empty_window();
2862                window.update(|window, cx| {
2863                    register_settings(cx);
2864                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
2865                });
2866            }
2867        };
2868    }
2869
2870    check_navbar_toggle!(
2871        navbar_basic_open,
2872        before: r"
2873        v General
2874        - General
2875        - Privacy*
2876        v Project
2877        - Project Settings
2878        ",
2879        toggle_page: "General",
2880        after: r"
2881        > General*
2882        v Project
2883        - Project Settings
2884        "
2885    );
2886
2887    check_navbar_toggle!(
2888        navbar_basic_close,
2889        before: r"
2890        > General*
2891        - General
2892        - Privacy
2893        v Project
2894        - Project Settings
2895        ",
2896        toggle_page: "General",
2897        after: r"
2898        v General*
2899        - General
2900        - Privacy
2901        v Project
2902        - Project Settings
2903        "
2904    );
2905
2906    check_navbar_toggle!(
2907        navbar_basic_second_root_entry_close,
2908        before: r"
2909        > General
2910        - General
2911        - Privacy
2912        v Project
2913        - Project Settings*
2914        ",
2915        toggle_page: "Project",
2916        after: r"
2917        > General
2918        > Project*
2919        "
2920    );
2921
2922    check_navbar_toggle!(
2923        navbar_toggle_subroot,
2924        before: r"
2925        v General Page
2926        - General
2927        - Privacy
2928        v Project
2929        - Worktree Settings Content*
2930        v AI
2931        - General
2932        > Appearance & Behavior
2933        ",
2934        toggle_page: "Project",
2935        after: r"
2936        v General Page
2937        - General
2938        - Privacy
2939        > Project*
2940        v AI
2941        - General
2942        > Appearance & Behavior
2943        "
2944    );
2945
2946    check_navbar_toggle!(
2947        navbar_toggle_close_propagates_selected_index,
2948        before: r"
2949        v General Page
2950        - General
2951        - Privacy
2952        v Project
2953        - Worktree Settings Content
2954        v AI
2955        - General*
2956        > Appearance & Behavior
2957        ",
2958        toggle_page: "General Page",
2959        after: r"
2960        > General Page
2961        v Project
2962        - Worktree Settings Content
2963        v AI
2964        - General*
2965        > Appearance & Behavior
2966        "
2967    );
2968
2969    check_navbar_toggle!(
2970        navbar_toggle_expand_propagates_selected_index,
2971        before: r"
2972        > General Page
2973        - General
2974        - Privacy
2975        v Project
2976        - Worktree Settings Content
2977        v AI
2978        - General*
2979        > Appearance & Behavior
2980        ",
2981        toggle_page: "General Page",
2982        after: r"
2983        v General Page
2984        - General
2985        - Privacy
2986        v Project
2987        - Worktree Settings Content
2988        v AI
2989        - General*
2990        > Appearance & Behavior
2991        "
2992    );
2993}