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