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