settings_ui.rs

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