settings_ui.rs

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