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