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