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