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