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