settings_ui.rs

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