settings_ui.rs

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