settings_ui.rs

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