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