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)
 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(SharedString::new_static(sub_page_link.title))),
 621                )
 622                .child(
 623                    Button::new(("sub-page".into(), sub_page_link.title), "Configure")
 624                        .icon(IconName::ChevronRight)
 625                        .tab_index(0_isize)
 626                        .icon_position(IconPosition::End)
 627                        .icon_color(Color::Muted)
 628                        .icon_size(IconSize::Small)
 629                        .style(ButtonStyle::Outlined)
 630                        .size(ButtonSize::Medium),
 631                )
 632                .on_click({
 633                    let sub_page_link = sub_page_link.clone();
 634                    cx.listener(move |this, _, _, cx| {
 635                        this.push_sub_page(sub_page_link.clone(), section_header, cx)
 636                    })
 637                })
 638                .into_any_element(),
 639        }
 640    }
 641}
 642
 643fn render_settings_item(
 644    settings_window: &SettingsWindow,
 645    setting_item: &SettingItem,
 646    file: SettingsUiFile,
 647    control: AnyElement,
 648    _window: &mut Window,
 649    cx: &mut Context<'_, SettingsWindow>,
 650) -> Stateful<Div> {
 651    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
 652    let file_set_in = SettingsUiFile::from_settings(found_in_file);
 653
 654    h_flex()
 655        .id(setting_item.title)
 656        .min_w_0()
 657        .gap_2()
 658        .justify_between()
 659        .child(
 660            v_flex()
 661                .w_1_2()
 662                .child(
 663                    h_flex()
 664                        .w_full()
 665                        .gap_1()
 666                        .child(Label::new(SharedString::new_static(setting_item.title)))
 667                        .when_some(
 668                            file_set_in.filter(|file_set_in| file_set_in != &file),
 669                            |this, file_set_in| {
 670                                this.child(
 671                                    Label::new(format!(
 672                                        "— set in {}",
 673                                        settings_window
 674                                            .display_name(&file_set_in)
 675                                            .expect("File name should exist")
 676                                    ))
 677                                    .color(Color::Muted)
 678                                    .size(LabelSize::Small),
 679                                )
 680                            },
 681                        ),
 682                )
 683                .child(
 684                    Label::new(SharedString::new_static(setting_item.description))
 685                        .size(LabelSize::Small)
 686                        .color(Color::Muted),
 687                ),
 688        )
 689        .child(control)
 690}
 691
 692struct SettingItem {
 693    title: &'static str,
 694    description: &'static str,
 695    field: Box<dyn AnySettingField>,
 696    metadata: Option<Box<SettingsFieldMetadata>>,
 697    files: FileMask,
 698}
 699
 700#[derive(PartialEq, Eq, Clone, Copy)]
 701struct FileMask(u8);
 702
 703impl std::fmt::Debug for FileMask {
 704    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 705        write!(f, "FileMask(")?;
 706        let mut items = vec![];
 707
 708        if self.contains(USER) {
 709            items.push("USER");
 710        }
 711        if self.contains(LOCAL) {
 712            items.push("LOCAL");
 713        }
 714        if self.contains(SERVER) {
 715            items.push("SERVER");
 716        }
 717
 718        write!(f, "{})", items.join(" | "))
 719    }
 720}
 721
 722const USER: FileMask = FileMask(1 << 0);
 723const LOCAL: FileMask = FileMask(1 << 2);
 724const SERVER: FileMask = FileMask(1 << 3);
 725
 726impl std::ops::BitAnd for FileMask {
 727    type Output = Self;
 728
 729    fn bitand(self, other: Self) -> Self {
 730        Self(self.0 & other.0)
 731    }
 732}
 733
 734impl std::ops::BitOr for FileMask {
 735    type Output = Self;
 736
 737    fn bitor(self, other: Self) -> Self {
 738        Self(self.0 | other.0)
 739    }
 740}
 741
 742impl FileMask {
 743    fn contains(&self, other: FileMask) -> bool {
 744        self.0 & other.0 != 0
 745    }
 746}
 747
 748impl PartialEq for SettingItem {
 749    fn eq(&self, other: &Self) -> bool {
 750        self.title == other.title
 751            && self.description == other.description
 752            && (match (&self.metadata, &other.metadata) {
 753                (None, None) => true,
 754                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
 755                _ => false,
 756            })
 757    }
 758}
 759
 760#[derive(Clone)]
 761struct SubPageLink {
 762    title: &'static str,
 763    files: FileMask,
 764    render: Arc<
 765        dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
 766            + 'static
 767            + Send
 768            + Sync,
 769    >,
 770}
 771
 772impl PartialEq for SubPageLink {
 773    fn eq(&self, other: &Self) -> bool {
 774        self.title == other.title
 775    }
 776}
 777
 778#[allow(unused)]
 779#[derive(Clone, PartialEq)]
 780enum SettingsUiFile {
 781    User,                                // Uses all settings.
 782    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
 783    Server(&'static str),                // Uses a special name, and the user settings
 784}
 785
 786impl SettingsUiFile {
 787    fn is_server(&self) -> bool {
 788        matches!(self, SettingsUiFile::Server(_))
 789    }
 790
 791    fn worktree_id(&self) -> Option<WorktreeId> {
 792        match self {
 793            SettingsUiFile::User => None,
 794            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
 795            SettingsUiFile::Server(_) => None,
 796        }
 797    }
 798
 799    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
 800        Some(match file {
 801            settings::SettingsFile::User => SettingsUiFile::User,
 802            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
 803            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
 804            settings::SettingsFile::Default => return None,
 805        })
 806    }
 807
 808    fn to_settings(&self) -> settings::SettingsFile {
 809        match self {
 810            SettingsUiFile::User => settings::SettingsFile::User,
 811            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
 812            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
 813        }
 814    }
 815
 816    fn mask(&self) -> FileMask {
 817        match self {
 818            SettingsUiFile::User => USER,
 819            SettingsUiFile::Project(_) => LOCAL,
 820            SettingsUiFile::Server(_) => SERVER,
 821        }
 822    }
 823}
 824
 825impl SettingsWindow {
 826    pub fn new(
 827        original_window: Option<WindowHandle<Workspace>>,
 828        window: &mut Window,
 829        cx: &mut Context<Self>,
 830    ) -> Self {
 831        let font_family_cache = theme::FontFamilyCache::global(cx);
 832
 833        cx.spawn(async move |this, cx| {
 834            font_family_cache.prefetch(cx).await;
 835            this.update(cx, |_, cx| {
 836                cx.notify();
 837            })
 838        })
 839        .detach();
 840
 841        let current_file = SettingsUiFile::User;
 842        let search_bar = cx.new(|cx| {
 843            let mut editor = Editor::single_line(window, cx);
 844            editor.set_placeholder_text("Search settings…", window, cx);
 845            editor
 846        });
 847
 848        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
 849            let EditorEvent::Edited { transaction_id: _ } = event else {
 850                return;
 851            };
 852
 853            this.update_matches(cx);
 854        })
 855        .detach();
 856
 857        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
 858            this.fetch_files(window, cx);
 859            cx.notify();
 860        })
 861        .detach();
 862
 863        let title_bar = if !cfg!(target_os = "macos") {
 864            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
 865        } else {
 866            None
 867        };
 868
 869        let mut this = Self {
 870            title_bar,
 871            original_window,
 872            worktree_root_dirs: HashMap::default(),
 873            files: vec![],
 874            current_file: current_file,
 875            pages: vec![],
 876            navbar_entries: vec![],
 877            navbar_entry: 0,
 878            navbar_scroll_handle: UniformListScrollHandle::default(),
 879            search_bar,
 880            search_task: None,
 881            filter_table: vec![],
 882            has_query: false,
 883            content_handles: vec![],
 884            page_scroll_handle: ScrollHandle::new(),
 885            focus_handle: cx.focus_handle(),
 886            navbar_focus_handle: NonFocusableHandle::new(
 887                NAVBAR_CONTAINER_TAB_INDEX,
 888                false,
 889                window,
 890                cx,
 891            ),
 892            content_focus_handle: NonFocusableHandle::new(
 893                CONTENT_CONTAINER_TAB_INDEX,
 894                false,
 895                window,
 896                cx,
 897            ),
 898            files_focus_handle: cx
 899                .focus_handle()
 900                .tab_index(HEADER_CONTAINER_TAB_INDEX)
 901                .tab_stop(false),
 902            search_index: None,
 903        };
 904
 905        this.fetch_files(window, cx);
 906        this.build_ui(window, cx);
 907        this.build_search_index();
 908
 909        this.search_bar.update(cx, |editor, cx| {
 910            editor.focus_handle(cx).focus(window);
 911        });
 912
 913        this
 914    }
 915
 916    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
 917        // We can only toggle root entries
 918        if !self.navbar_entries[nav_entry_index].is_root {
 919            return;
 920        }
 921
 922        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
 923        *expanded = !*expanded;
 924        let expanded = *expanded;
 925
 926        let toggle_page_index = self.page_index_from_navbar_index(nav_entry_index);
 927        let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
 928        // if currently selected page is a child of the parent page we are folding,
 929        // set the current page to the parent page
 930        if !expanded && selected_page_index == toggle_page_index {
 931            self.navbar_entry = nav_entry_index;
 932            // note: not opening page. Toggling does not change content just selected page
 933        }
 934    }
 935
 936    fn build_navbar(&mut self, cx: &App) {
 937        let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
 938        for (page_index, page) in self.pages.iter().enumerate() {
 939            navbar_entries.push(NavBarEntry {
 940                title: page.title,
 941                is_root: true,
 942                expanded: false,
 943                page_index,
 944                item_index: None,
 945                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
 946            });
 947
 948            for (item_index, item) in page.items.iter().enumerate() {
 949                let SettingsPageItem::SectionHeader(title) = item else {
 950                    continue;
 951                };
 952                navbar_entries.push(NavBarEntry {
 953                    title,
 954                    is_root: false,
 955                    expanded: false,
 956                    page_index,
 957                    item_index: Some(item_index),
 958                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
 959                });
 960            }
 961        }
 962
 963        self.navbar_entries = navbar_entries;
 964    }
 965
 966    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
 967        let mut index = 0;
 968        let entries = &self.navbar_entries;
 969        let search_matches = &self.filter_table;
 970        let has_query = self.has_query;
 971        std::iter::from_fn(move || {
 972            while index < entries.len() {
 973                let entry = &entries[index];
 974                let included_in_search = if let Some(item_index) = entry.item_index {
 975                    search_matches[entry.page_index][item_index]
 976                } else {
 977                    search_matches[entry.page_index].iter().any(|b| *b)
 978                        || search_matches[entry.page_index].is_empty()
 979                };
 980                if included_in_search {
 981                    break;
 982                }
 983                index += 1;
 984            }
 985            if index >= self.navbar_entries.len() {
 986                return None;
 987            }
 988            let entry = &entries[index];
 989            let entry_index = index;
 990
 991            index += 1;
 992            if entry.is_root && !entry.expanded && !has_query {
 993                while index < entries.len() {
 994                    if entries[index].is_root {
 995                        break;
 996                    }
 997                    index += 1;
 998                }
 999            }
1000
1001            return Some((entry_index, entry));
1002        })
1003    }
1004
1005    fn filter_matches_to_file(&mut self) {
1006        let current_file = self.current_file.mask();
1007        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1008            let mut header_index = 0;
1009            let mut any_found_since_last_header = true;
1010
1011            for (index, item) in page.items.iter().enumerate() {
1012                match item {
1013                    SettingsPageItem::SectionHeader(_) => {
1014                        if !any_found_since_last_header {
1015                            page_filter[header_index] = false;
1016                        }
1017                        header_index = index;
1018                        any_found_since_last_header = false;
1019                    }
1020                    SettingsPageItem::SettingItem(setting_item) => {
1021                        if !setting_item.files.contains(current_file) {
1022                            page_filter[index] = false;
1023                        } else {
1024                            any_found_since_last_header = true;
1025                        }
1026                    }
1027                    SettingsPageItem::SubPageLink(sub_page_link) => {
1028                        if !sub_page_link.files.contains(current_file) {
1029                            page_filter[index] = false;
1030                        } else {
1031                            any_found_since_last_header = true;
1032                        }
1033                    }
1034                }
1035            }
1036            if let Some(last_header) = page_filter.get_mut(header_index)
1037                && !any_found_since_last_header
1038            {
1039                *last_header = false;
1040            }
1041        }
1042    }
1043
1044    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1045        self.search_task.take();
1046        let query = self.search_bar.read(cx).text(cx);
1047        if query.is_empty() || self.search_index.is_none() {
1048            for page in &mut self.filter_table {
1049                page.fill(true);
1050            }
1051            self.has_query = false;
1052            self.filter_matches_to_file();
1053            cx.notify();
1054            return;
1055        }
1056
1057        let search_index = self.search_index.as_ref().unwrap().clone();
1058
1059        fn update_matches_inner(
1060            this: &mut SettingsWindow,
1061            search_index: &SearchIndex,
1062            match_indices: impl Iterator<Item = usize>,
1063            cx: &mut Context<SettingsWindow>,
1064        ) {
1065            for page in &mut this.filter_table {
1066                page.fill(false);
1067            }
1068
1069            for match_index in match_indices {
1070                let SearchItemKey {
1071                    page_index,
1072                    header_index,
1073                    item_index,
1074                } = search_index.key_lut[match_index];
1075                let page = &mut this.filter_table[page_index];
1076                page[header_index] = true;
1077                page[item_index] = true;
1078            }
1079            this.has_query = true;
1080            this.filter_matches_to_file();
1081            this.open_first_nav_page();
1082            cx.notify();
1083        }
1084
1085        self.search_task = Some(cx.spawn(async move |this, cx| {
1086            let bm25_task = cx.background_spawn({
1087                let search_index = search_index.clone();
1088                let max_results = search_index.key_lut.len();
1089                let query = query.clone();
1090                async move { search_index.bm25_engine.search(&query, max_results) }
1091            });
1092            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1093            let fuzzy_search_task = fuzzy::match_strings(
1094                search_index.fuzzy_match_candidates.as_slice(),
1095                &query,
1096                false,
1097                true,
1098                search_index.fuzzy_match_candidates.len(),
1099                &cancel_flag,
1100                cx.background_executor().clone(),
1101            );
1102
1103            let fuzzy_matches = fuzzy_search_task.await;
1104
1105            _ = this
1106                .update(cx, |this, cx| {
1107                    // For tuning the score threshold
1108                    // for fuzzy_match in &fuzzy_matches {
1109                    //     let SearchItemKey {
1110                    //         page_index,
1111                    //         header_index,
1112                    //         item_index,
1113                    //     } = search_index.key_lut[fuzzy_match.candidate_id];
1114                    //     let SettingsPageItem::SectionHeader(header) =
1115                    //         this.pages[page_index].items[header_index]
1116                    //     else {
1117                    //         continue;
1118                    //     };
1119                    //     let SettingsPageItem::SettingItem(SettingItem {
1120                    //         title, description, ..
1121                    //     }) = this.pages[page_index].items[item_index]
1122                    //     else {
1123                    //         continue;
1124                    //     };
1125                    //     let score = fuzzy_match.score;
1126                    //     eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1127                    // }
1128                    update_matches_inner(
1129                        this,
1130                        search_index.as_ref(),
1131                        fuzzy_matches
1132                            .into_iter()
1133                            // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1134                            // flexible enough to catch misspellings and <4 letter queries
1135                            // More flexible is good for us here because fuzzy matches will only be used for things that don't
1136                            // match using bm25
1137                            .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1138                            .map(|fuzzy_match| fuzzy_match.candidate_id),
1139                        cx,
1140                    );
1141                })
1142                .ok();
1143
1144            let bm25_matches = bm25_task.await;
1145
1146            _ = this
1147                .update(cx, |this, cx| {
1148                    if bm25_matches.is_empty() {
1149                        return;
1150                    }
1151                    update_matches_inner(
1152                        this,
1153                        search_index.as_ref(),
1154                        bm25_matches
1155                            .into_iter()
1156                            .map(|bm25_match| bm25_match.document.id),
1157                        cx,
1158                    );
1159                })
1160                .ok();
1161        }));
1162    }
1163
1164    fn build_filter_table(&mut self) {
1165        self.filter_table = self
1166            .pages
1167            .iter()
1168            .map(|page| vec![true; page.items.len()])
1169            .collect::<Vec<_>>();
1170    }
1171
1172    fn build_search_index(&mut self) {
1173        let mut key_lut: Vec<SearchItemKey> = vec![];
1174        let mut documents = Vec::default();
1175        let mut fuzzy_match_candidates = Vec::default();
1176
1177        fn push_candidates(
1178            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1179            key_index: usize,
1180            input: &str,
1181        ) {
1182            for word in input.split_ascii_whitespace() {
1183                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1184            }
1185        }
1186
1187        // PERF: We are currently searching all items even in project files
1188        // where many settings are filtered out, using the logic in filter_matches_to_file
1189        // we could only search relevant items based on the current file
1190        for (page_index, page) in self.pages.iter().enumerate() {
1191            let mut header_index = 0;
1192            let mut header_str = "";
1193            for (item_index, item) in page.items.iter().enumerate() {
1194                let key_index = key_lut.len();
1195                match item {
1196                    SettingsPageItem::SettingItem(item) => {
1197                        documents.push(bm25::Document {
1198                            id: key_index,
1199                            contents: [page.title, header_str, item.title, item.description]
1200                                .join("\n"),
1201                        });
1202                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1203                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1204                    }
1205                    SettingsPageItem::SectionHeader(header) => {
1206                        documents.push(bm25::Document {
1207                            id: key_index,
1208                            contents: header.to_string(),
1209                        });
1210                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
1211                        header_index = item_index;
1212                        header_str = *header;
1213                    }
1214                    SettingsPageItem::SubPageLink(sub_page_link) => {
1215                        documents.push(bm25::Document {
1216                            id: key_index,
1217                            contents: [page.title, header_str, sub_page_link.title].join("\n"),
1218                        });
1219                        push_candidates(
1220                            &mut fuzzy_match_candidates,
1221                            key_index,
1222                            sub_page_link.title,
1223                        );
1224                    }
1225                }
1226                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1227                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1228
1229                key_lut.push(SearchItemKey {
1230                    page_index,
1231                    header_index,
1232                    item_index,
1233                });
1234            }
1235        }
1236        let engine =
1237            bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1238        self.search_index = Some(Arc::new(SearchIndex {
1239            bm25_engine: engine,
1240            key_lut,
1241            fuzzy_match_candidates,
1242        }));
1243    }
1244
1245    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1246        self.content_handles = self
1247            .pages
1248            .iter()
1249            .map(|page| {
1250                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1251                    .take(page.items.len())
1252                    .collect()
1253            })
1254            .collect::<Vec<_>>();
1255    }
1256
1257    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1258        if self.pages.is_empty() {
1259            self.pages = page_data::settings_data();
1260            self.build_navbar(cx);
1261            self.build_content_handles(window, cx);
1262        }
1263        sub_page_stack_mut().clear();
1264        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1265        self.build_filter_table();
1266        self.update_matches(cx);
1267
1268        cx.notify();
1269    }
1270
1271    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1272        self.worktree_root_dirs.clear();
1273        let prev_files = self.files.clone();
1274        let settings_store = cx.global::<SettingsStore>();
1275        let mut ui_files = vec![];
1276        let all_files = settings_store.get_all_files();
1277        for file in all_files {
1278            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1279                continue;
1280            };
1281            if settings_ui_file.is_server() {
1282                continue;
1283            }
1284
1285            if let Some(worktree_id) = settings_ui_file.worktree_id() {
1286                let directory_name = all_projects(cx)
1287                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1288                    .and_then(|worktree| worktree.read(cx).root_dir())
1289                    .and_then(|root_dir| {
1290                        root_dir
1291                            .file_name()
1292                            .map(|os_string| os_string.to_string_lossy().to_string())
1293                    });
1294
1295                let Some(directory_name) = directory_name else {
1296                    log::error!(
1297                        "No directory name found for settings file at worktree ID: {}",
1298                        worktree_id
1299                    );
1300                    continue;
1301                };
1302
1303                self.worktree_root_dirs.insert(worktree_id, directory_name);
1304            }
1305
1306            let focus_handle = prev_files
1307                .iter()
1308                .find_map(|(prev_file, handle)| {
1309                    (prev_file == &settings_ui_file).then(|| handle.clone())
1310                })
1311                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1312            ui_files.push((settings_ui_file, focus_handle));
1313        }
1314        ui_files.reverse();
1315        self.files = ui_files;
1316        let current_file_still_exists = self
1317            .files
1318            .iter()
1319            .any(|(file, _)| file == &self.current_file);
1320        if !current_file_still_exists {
1321            self.change_file(0, window, cx);
1322        }
1323    }
1324
1325    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1326        if !self.is_nav_entry_visible(navbar_entry) {
1327            self.open_first_nav_page();
1328        }
1329        self.navbar_entry = navbar_entry;
1330        sub_page_stack_mut().clear();
1331    }
1332
1333    fn open_first_nav_page(&mut self) {
1334        let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
1335        else {
1336            return;
1337        };
1338        self.open_navbar_entry_page(first_navbar_entry_index);
1339    }
1340
1341    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1342        if ix >= self.files.len() {
1343            self.current_file = SettingsUiFile::User;
1344            self.build_ui(window, cx);
1345            return;
1346        }
1347        if self.files[ix].0 == self.current_file {
1348            return;
1349        }
1350        self.current_file = self.files[ix].0.clone();
1351
1352        self.build_ui(window, cx);
1353
1354        if self
1355            .visible_navbar_entries()
1356            .any(|(index, _)| index == self.navbar_entry)
1357        {
1358            self.open_and_scroll_to_navbar_entry(self.navbar_entry, window, cx);
1359        } else {
1360            self.open_first_nav_page();
1361        };
1362    }
1363
1364    fn render_files_header(
1365        &self,
1366        _window: &mut Window,
1367        cx: &mut Context<SettingsWindow>,
1368    ) -> impl IntoElement {
1369        h_flex()
1370            .w_full()
1371            .pb_4()
1372            .gap_1()
1373            .justify_between()
1374            .tab_group()
1375            .track_focus(&self.files_focus_handle)
1376            .tab_index(HEADER_GROUP_TAB_INDEX)
1377            .child(
1378                h_flex()
1379                    .id("file_buttons_container")
1380                    .w_64() // Temporary fix until long-term solution is a fixed set of buttons representing a file location (User, Project, and Remote)
1381                    .gap_1()
1382                    .overflow_x_scroll()
1383                    .children(
1384                        self.files
1385                            .iter()
1386                            .enumerate()
1387                            .map(|(ix, (file, focus_handle))| {
1388                                Button::new(
1389                                    ix,
1390                                    self.display_name(&file)
1391                                        .expect("Files should always have a name"),
1392                                )
1393                                .toggle_state(file == &self.current_file)
1394                                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1395                                .track_focus(focus_handle)
1396                                .on_click(cx.listener({
1397                                    let focus_handle = focus_handle.clone();
1398                                    move |this, _: &gpui::ClickEvent, window, cx| {
1399                                        this.change_file(ix, window, cx);
1400                                        focus_handle.focus(window);
1401                                    }
1402                                }))
1403                            }),
1404                    ),
1405            )
1406            .child(
1407                Button::new("edit-in-json", "Edit in settings.json")
1408                    .tab_index(0_isize)
1409                    .style(ButtonStyle::OutlinedGhost)
1410                    .on_click(cx.listener(|this, _, _, cx| {
1411                        this.open_current_settings_file(cx);
1412                    })),
1413            )
1414    }
1415
1416    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1417        match file {
1418            SettingsUiFile::User => Some("User".to_string()),
1419            SettingsUiFile::Project((worktree_id, path)) => self
1420                .worktree_root_dirs
1421                .get(&worktree_id)
1422                .map(|directory_name| {
1423                    let path_style = PathStyle::local();
1424                    if path.is_empty() {
1425                        directory_name.clone()
1426                    } else {
1427                        format!(
1428                            "{}{}{}",
1429                            directory_name,
1430                            path_style.separator(),
1431                            path.display(path_style)
1432                        )
1433                    }
1434                }),
1435            SettingsUiFile::Server(file) => Some(file.to_string()),
1436        }
1437    }
1438
1439    // TODO:
1440    //  Reconsider this after preview launch
1441    // fn file_location_str(&self) -> String {
1442    //     match &self.current_file {
1443    //         SettingsUiFile::User => "settings.json".to_string(),
1444    //         SettingsUiFile::Project((worktree_id, path)) => self
1445    //             .worktree_root_dirs
1446    //             .get(&worktree_id)
1447    //             .map(|directory_name| {
1448    //                 let path_style = PathStyle::local();
1449    //                 let file_path = path.join(paths::local_settings_file_relative_path());
1450    //                 format!(
1451    //                     "{}{}{}",
1452    //                     directory_name,
1453    //                     path_style.separator(),
1454    //                     file_path.display(path_style)
1455    //                 )
1456    //             })
1457    //             .expect("Current file should always be present in root dir map"),
1458    //         SettingsUiFile::Server(file) => file.to_string(),
1459    //     }
1460    // }
1461
1462    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1463        h_flex()
1464            .py_1()
1465            .px_1p5()
1466            .mb_3()
1467            .gap_1p5()
1468            .rounded_sm()
1469            .bg(cx.theme().colors().editor_background)
1470            .border_1()
1471            .border_color(cx.theme().colors().border)
1472            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1473            .child(self.search_bar.clone())
1474    }
1475
1476    fn render_nav(
1477        &self,
1478        window: &mut Window,
1479        cx: &mut Context<SettingsWindow>,
1480    ) -> impl IntoElement {
1481        let visible_count = self.visible_navbar_entries().count();
1482
1483        let focus_keybind_label = if self
1484            .navbar_focus_handle
1485            .read(cx)
1486            .handle
1487            .contains_focused(window, cx)
1488        {
1489            "Focus Content"
1490        } else {
1491            "Focus Navbar"
1492        };
1493
1494        v_flex()
1495            .w_64()
1496            .p_2p5()
1497            .when(cfg!(target_os = "macos"), |c| c.pt_10())
1498            .h_full()
1499            .flex_none()
1500            .border_r_1()
1501            .key_context("NavigationMenu")
1502            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1503                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1504                    return;
1505                };
1506                let focused_entry_parent = this.root_entry_containing(focused_entry);
1507                if this.navbar_entries[focused_entry_parent].expanded {
1508                    this.toggle_navbar_entry(focused_entry_parent);
1509                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1510                }
1511                cx.notify();
1512            }))
1513            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1514                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1515                    return;
1516                };
1517                if !this.navbar_entries[focused_entry].is_root {
1518                    return;
1519                }
1520                if !this.navbar_entries[focused_entry].expanded {
1521                    this.toggle_navbar_entry(focused_entry);
1522                }
1523                cx.notify();
1524            }))
1525            .on_action(
1526                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1527                    let entry_index = this
1528                        .focused_nav_entry(window, cx)
1529                        .unwrap_or(this.navbar_entry);
1530                    let mut root_index = None;
1531                    for (index, entry) in this.visible_navbar_entries() {
1532                        if index >= entry_index {
1533                            break;
1534                        }
1535                        if entry.is_root {
1536                            root_index = Some(index);
1537                        }
1538                    }
1539                    let Some(previous_root_index) = root_index else {
1540                        return;
1541                    };
1542                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
1543                }),
1544            )
1545            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
1546                let entry_index = this
1547                    .focused_nav_entry(window, cx)
1548                    .unwrap_or(this.navbar_entry);
1549                let mut root_index = None;
1550                for (index, entry) in this.visible_navbar_entries() {
1551                    if index <= entry_index {
1552                        continue;
1553                    }
1554                    if entry.is_root {
1555                        root_index = Some(index);
1556                        break;
1557                    }
1558                }
1559                let Some(next_root_index) = root_index else {
1560                    return;
1561                };
1562                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
1563            }))
1564            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
1565                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1566                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
1567                }
1568            }))
1569            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
1570                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1571                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
1572                }
1573            }))
1574            .border_color(cx.theme().colors().border)
1575            .bg(cx.theme().colors().panel_background)
1576            .child(self.render_search(window, cx))
1577            .child(
1578                v_flex()
1579                    .flex_1()
1580                    .overflow_hidden()
1581                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1582                    .tab_group()
1583                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
1584                    .child(
1585                        uniform_list(
1586                            "settings-ui-nav-bar",
1587                            visible_count + 1,
1588                            cx.processor(move |this, range: Range<usize>, _, cx| {
1589                                this.visible_navbar_entries()
1590                                    .skip(range.start.saturating_sub(1))
1591                                    .take(range.len())
1592                                    .map(|(ix, entry)| {
1593                                        TreeViewItem::new(
1594                                            ("settings-ui-navbar-entry", ix),
1595                                            entry.title,
1596                                        )
1597                                        .track_focus(&entry.focus_handle)
1598                                        .root_item(entry.is_root)
1599                                        .toggle_state(this.is_navbar_entry_selected(ix))
1600                                        .when(entry.is_root, |item| {
1601                                            item.expanded(entry.expanded || this.has_query)
1602                                                .on_toggle(cx.listener(
1603                                                    move |this, _, window, cx| {
1604                                                        this.toggle_navbar_entry(ix);
1605                                                        window.focus(
1606                                                            &this.navbar_entries[ix].focus_handle,
1607                                                        );
1608                                                        cx.notify();
1609                                                    },
1610                                                ))
1611                                        })
1612                                        .on_click(
1613                                            cx.listener(move |this, _, window, cx| {
1614                                                this.open_and_scroll_to_navbar_entry(
1615                                                    ix, window, cx,
1616                                                );
1617                                            }),
1618                                        )
1619                                    })
1620                                    .collect()
1621                            }),
1622                        )
1623                        .size_full()
1624                        .track_scroll(self.navbar_scroll_handle.clone()),
1625                    )
1626                    .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
1627            )
1628            .child(
1629                h_flex()
1630                    .w_full()
1631                    .h_8()
1632                    .p_2()
1633                    .pb_0p5()
1634                    .flex_shrink_0()
1635                    .border_t_1()
1636                    .border_color(cx.theme().colors().border_variant)
1637                    .children(
1638                        KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1639                            KeybindingHint::new(
1640                                this,
1641                                cx.theme().colors().surface_background.opacity(0.5),
1642                            )
1643                            .suffix(focus_keybind_label)
1644                        }),
1645                    ),
1646            )
1647    }
1648
1649    fn open_and_scroll_to_navbar_entry(
1650        &mut self,
1651        navbar_entry_index: usize,
1652        window: &mut Window,
1653        cx: &mut Context<Self>,
1654    ) {
1655        self.open_navbar_entry_page(navbar_entry_index);
1656        cx.notify();
1657
1658        if self.navbar_entries[navbar_entry_index].is_root
1659            || !self.is_nav_entry_visible(navbar_entry_index)
1660        {
1661            let Some(first_item_index) = self.visible_page_items().next().map(|(index, _)| index)
1662            else {
1663                return;
1664            };
1665            self.focus_content_element(first_item_index, window, cx);
1666            self.page_scroll_handle.set_offset(point(px(0.), px(0.)));
1667        } else {
1668            let entry_item_index = self.navbar_entries[navbar_entry_index]
1669                .item_index
1670                .expect("Non-root items should have an item index");
1671            let Some(selected_item_index) = self
1672                .visible_page_items()
1673                .position(|(index, _)| index == entry_item_index)
1674            else {
1675                return;
1676            };
1677            self.page_scroll_handle
1678                .scroll_to_top_of_item(selected_item_index);
1679            self.focus_content_element(entry_item_index, window, cx);
1680        }
1681
1682        // Page scroll handle updates the active item index
1683        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
1684        // The call after that updates the offset of the scroll handle. So to
1685        // ensure the scroll handle doesn't lag behind we need to render three frames
1686        // back to back.
1687        cx.on_next_frame(window, |_, window, cx| {
1688            cx.on_next_frame(window, |_, _, cx| {
1689                cx.notify();
1690            });
1691            cx.notify();
1692        });
1693        cx.notify();
1694    }
1695
1696    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
1697        self.visible_navbar_entries()
1698            .any(|(index, _)| index == nav_entry_index)
1699    }
1700
1701    fn focus_and_scroll_to_nav_entry(
1702        &self,
1703        nav_entry_index: usize,
1704        window: &mut Window,
1705        cx: &mut Context<Self>,
1706    ) {
1707        let Some(position) = self
1708            .visible_navbar_entries()
1709            .position(|(index, _)| index == nav_entry_index)
1710        else {
1711            return;
1712        };
1713        self.navbar_scroll_handle
1714            .scroll_to_item(position, gpui::ScrollStrategy::Top);
1715        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
1716        cx.notify();
1717    }
1718
1719    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1720        let page_idx = self.current_page_index();
1721
1722        self.current_page()
1723            .items
1724            .iter()
1725            .enumerate()
1726            .filter_map(move |(item_index, item)| {
1727                self.filter_table[page_idx][item_index].then_some((item_index, item))
1728            })
1729    }
1730
1731    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1732        let mut items = vec![];
1733        items.push(self.current_page().title);
1734        items.extend(
1735            sub_page_stack()
1736                .iter()
1737                .flat_map(|page| [page.section_header, page.link.title]),
1738        );
1739
1740        let last = items.pop().unwrap();
1741        h_flex()
1742            .gap_1()
1743            .children(
1744                items
1745                    .into_iter()
1746                    .flat_map(|item| [item, "/"])
1747                    .map(|item| Label::new(item).color(Color::Muted)),
1748            )
1749            .child(Label::new(last))
1750    }
1751
1752    fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
1753        &self,
1754        items: Items,
1755        page_index: Option<usize>,
1756        window: &mut Window,
1757        cx: &mut Context<SettingsWindow>,
1758    ) -> impl IntoElement {
1759        let mut page_content = v_flex()
1760            .id("settings-ui-page")
1761            .size_full()
1762            .overflow_y_scroll()
1763            .track_scroll(&self.page_scroll_handle);
1764
1765        let items: Vec<_> = items.collect();
1766        let items_len = items.len();
1767        let mut section_header = None;
1768
1769        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1770        let has_no_results = items_len == 0 && has_active_search;
1771
1772        if has_no_results {
1773            let search_query = self.search_bar.read(cx).text(cx);
1774            page_content = page_content.child(
1775                v_flex()
1776                    .size_full()
1777                    .items_center()
1778                    .justify_center()
1779                    .gap_1()
1780                    .child(div().child("No Results"))
1781                    .child(
1782                        div()
1783                            .text_sm()
1784                            .text_color(cx.theme().colors().text_muted)
1785                            .child(format!("No settings match \"{}\"", search_query)),
1786                    ),
1787            )
1788        } else {
1789            let last_non_header_index = items
1790                .iter()
1791                .enumerate()
1792                .rev()
1793                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
1794                .map(|(index, _)| index);
1795
1796            page_content = page_content.children(items.clone().into_iter().enumerate().map(
1797                |(index, (actual_item_index, item))| {
1798                    let no_bottom_border = items
1799                        .get(index + 1)
1800                        .map(|(_, next_item)| {
1801                            matches!(next_item, SettingsPageItem::SectionHeader(_))
1802                        })
1803                        .unwrap_or(false);
1804                    let is_last = Some(index) == last_non_header_index;
1805
1806                    if let SettingsPageItem::SectionHeader(header) = item {
1807                        section_header = Some(*header);
1808                    }
1809                    v_flex()
1810                        .w_full()
1811                        .min_w_0()
1812                        .id(("settings-page-item", actual_item_index))
1813                        .when_some(page_index, |element, page_index| {
1814                            element.track_focus(
1815                                &self.content_handles[page_index][actual_item_index]
1816                                    .focus_handle(cx),
1817                            )
1818                        })
1819                        .child(item.render(
1820                            self,
1821                            section_header.expect("All items rendered after a section header"),
1822                            no_bottom_border || is_last,
1823                            window,
1824                            cx,
1825                        ))
1826                },
1827            ))
1828        }
1829        page_content
1830    }
1831
1832    fn render_page(
1833        &mut self,
1834        window: &mut Window,
1835        cx: &mut Context<SettingsWindow>,
1836    ) -> impl IntoElement {
1837        let page_header;
1838        let page_content;
1839
1840        if sub_page_stack().is_empty() {
1841            page_header = self.render_files_header(window, cx).into_any_element();
1842
1843            page_content = self
1844                .render_page_items(
1845                    self.visible_page_items(),
1846                    Some(self.current_page_index()),
1847                    window,
1848                    cx,
1849                )
1850                .into_any_element();
1851        } else {
1852            page_header = h_flex()
1853                .ml_neg_1p5()
1854                .pb_4()
1855                .gap_1()
1856                .child(
1857                    IconButton::new("back-btn", IconName::ArrowLeft)
1858                        .icon_size(IconSize::Small)
1859                        .shape(IconButtonShape::Square)
1860                        .on_click(cx.listener(|this, _, _, cx| {
1861                            this.pop_sub_page(cx);
1862                        })),
1863                )
1864                .child(self.render_sub_page_breadcrumbs())
1865                .into_any_element();
1866
1867            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1868            page_content = (active_page_render_fn)(self, window, cx);
1869        }
1870
1871        return v_flex()
1872            .size_full()
1873            .pt_6()
1874            .pb_8()
1875            .px_8()
1876            .bg(cx.theme().colors().editor_background)
1877            .child(page_header)
1878            .vertical_scrollbar_for(self.page_scroll_handle.clone(), window, cx)
1879            .track_focus(&self.content_focus_handle.focus_handle(cx))
1880            .child(
1881                div()
1882                    .size_full()
1883                    .tab_group()
1884                    .tab_index(CONTENT_GROUP_TAB_INDEX)
1885                    .child(page_content),
1886            );
1887    }
1888
1889    fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
1890        match &self.current_file {
1891            SettingsUiFile::User => {
1892                let Some(original_window) = self.original_window else {
1893                    return;
1894                };
1895                original_window
1896                    .update(cx, |workspace, window, cx| {
1897                        workspace
1898                            .with_local_workspace(window, cx, |workspace, window, cx| {
1899                                let create_task = workspace.project().update(cx, |project, cx| {
1900                                    project.find_or_create_worktree(
1901                                        paths::config_dir().as_path(),
1902                                        false,
1903                                        cx,
1904                                    )
1905                                });
1906                                let open_task = workspace.open_paths(
1907                                    vec![paths::settings_file().to_path_buf()],
1908                                    OpenOptions {
1909                                        visible: Some(OpenVisible::None),
1910                                        ..Default::default()
1911                                    },
1912                                    None,
1913                                    window,
1914                                    cx,
1915                                );
1916
1917                                cx.spawn_in(window, async move |workspace, cx| {
1918                                    create_task.await.ok();
1919                                    open_task.await;
1920
1921                                    workspace.update_in(cx, |_, window, cx| {
1922                                        window.activate_window();
1923                                        cx.notify();
1924                                    })
1925                                })
1926                                .detach();
1927                            })
1928                            .detach();
1929                    })
1930                    .ok();
1931            }
1932            SettingsUiFile::Project((worktree_id, path)) => {
1933                let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
1934                let settings_path = path.join(paths::local_settings_file_relative_path());
1935                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
1936                    return;
1937                };
1938                for workspace in app_state.workspace_store.read(cx).workspaces() {
1939                    let contains_settings_file = workspace
1940                        .read_with(cx, |workspace, cx| {
1941                            workspace.project().read(cx).contains_local_settings_file(
1942                                *worktree_id,
1943                                settings_path.as_ref(),
1944                                cx,
1945                            )
1946                        })
1947                        .ok();
1948                    if Some(true) == contains_settings_file {
1949                        corresponding_workspace = Some(*workspace);
1950
1951                        break;
1952                    }
1953                }
1954
1955                let Some(corresponding_workspace) = corresponding_workspace else {
1956                    log::error!(
1957                        "No corresponding workspace found for settings file {}",
1958                        settings_path.as_std_path().display()
1959                    );
1960
1961                    return;
1962                };
1963
1964                // TODO: move zed::open_local_file() APIs to this crate, and
1965                // re-implement the "initial_contents" behavior
1966                corresponding_workspace
1967                    .update(cx, |workspace, window, cx| {
1968                        let open_task = workspace.open_path(
1969                            (*worktree_id, settings_path.clone()),
1970                            None,
1971                            true,
1972                            window,
1973                            cx,
1974                        );
1975
1976                        cx.spawn_in(window, async move |workspace, cx| {
1977                            if open_task.await.log_err().is_some() {
1978                                workspace
1979                                    .update_in(cx, |_, window, cx| {
1980                                        window.activate_window();
1981                                        cx.notify();
1982                                    })
1983                                    .ok();
1984                            }
1985                        })
1986                        .detach();
1987                    })
1988                    .ok();
1989            }
1990            SettingsUiFile::Server(_) => {
1991                return;
1992            }
1993        };
1994    }
1995
1996    fn current_page_index(&self) -> usize {
1997        self.page_index_from_navbar_index(self.navbar_entry)
1998    }
1999
2000    fn current_page(&self) -> &SettingsPage {
2001        &self.pages[self.current_page_index()]
2002    }
2003
2004    fn page_index_from_navbar_index(&self, index: usize) -> usize {
2005        if self.navbar_entries.is_empty() {
2006            return 0;
2007        }
2008
2009        self.navbar_entries[index].page_index
2010    }
2011
2012    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2013        ix == self.navbar_entry
2014    }
2015
2016    fn push_sub_page(
2017        &mut self,
2018        sub_page_link: SubPageLink,
2019        section_header: &'static str,
2020        cx: &mut Context<SettingsWindow>,
2021    ) {
2022        sub_page_stack_mut().push(SubPage {
2023            link: sub_page_link,
2024            section_header,
2025        });
2026        cx.notify();
2027    }
2028
2029    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
2030        sub_page_stack_mut().pop();
2031        cx.notify();
2032    }
2033
2034    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
2035        if let Some((_, handle)) = self.files.get(index) {
2036            handle.focus(window);
2037        }
2038    }
2039
2040    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
2041        if self.files_focus_handle.contains_focused(window, cx)
2042            && let Some(index) = self
2043                .files
2044                .iter()
2045                .position(|(_, handle)| handle.is_focused(window))
2046        {
2047            return index;
2048        }
2049        if let Some(current_file_index) = self
2050            .files
2051            .iter()
2052            .position(|(file, _)| file == &self.current_file)
2053        {
2054            return current_file_index;
2055        }
2056        0
2057    }
2058
2059    fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
2060        if !sub_page_stack().is_empty() {
2061            return;
2062        }
2063        let page_index = self.current_page_index();
2064        window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
2065    }
2066
2067    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
2068        if !self
2069            .navbar_focus_handle
2070            .focus_handle(cx)
2071            .contains_focused(window, cx)
2072        {
2073            return None;
2074        }
2075        for (index, entry) in self.navbar_entries.iter().enumerate() {
2076            if entry.focus_handle.is_focused(window) {
2077                return Some(index);
2078            }
2079        }
2080        None
2081    }
2082
2083    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
2084        let mut index = Some(nav_entry_index);
2085        while let Some(prev_index) = index
2086            && !self.navbar_entries[prev_index].is_root
2087        {
2088            index = prev_index.checked_sub(1);
2089        }
2090        return index.expect("No root entry found");
2091    }
2092}
2093
2094impl Render for SettingsWindow {
2095    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2096        let ui_font = theme::setup_ui_font(window, cx);
2097
2098        client_side_decorations(
2099            v_flex()
2100                .text_color(cx.theme().colors().text)
2101                .size_full()
2102                .children(self.title_bar.clone())
2103                .child(
2104                    div()
2105                        .id("settings-window")
2106                        .key_context("SettingsWindow")
2107                        .track_focus(&self.focus_handle)
2108                        .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2109                            this.open_current_settings_file(cx);
2110                        }))
2111                        .on_action(|_: &Minimize, window, _cx| {
2112                            window.minimize_window();
2113                        })
2114                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2115                            this.search_bar.focus_handle(cx).focus(window);
2116                        }))
2117                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2118                            if this
2119                                .navbar_focus_handle
2120                                .focus_handle(cx)
2121                                .contains_focused(window, cx)
2122                            {
2123                                this.open_and_scroll_to_navbar_entry(this.navbar_entry, window, cx);
2124                            } else {
2125                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
2126                            }
2127                        }))
2128                        .on_action(cx.listener(
2129                            |this, FocusFile(file_index): &FocusFile, window, _| {
2130                                this.focus_file_at_index(*file_index as usize, window);
2131                            },
2132                        ))
2133                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2134                            let next_index = usize::min(
2135                                this.focused_file_index(window, cx) + 1,
2136                                this.files.len().saturating_sub(1),
2137                            );
2138                            this.focus_file_at_index(next_index, window);
2139                        }))
2140                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2141                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2142                            this.focus_file_at_index(prev_index, window);
2143                        }))
2144                        .on_action(|_: &menu::SelectNext, window, _| {
2145                            window.focus_next();
2146                        })
2147                        .on_action(|_: &menu::SelectPrevious, window, _| {
2148                            window.focus_prev();
2149                        })
2150                        .flex()
2151                        .flex_row()
2152                        .flex_1()
2153                        .min_h_0()
2154                        .font(ui_font)
2155                        .bg(cx.theme().colors().background)
2156                        .text_color(cx.theme().colors().text)
2157                        .child(self.render_nav(window, cx))
2158                        .child(self.render_page(window, cx)),
2159                ),
2160            window,
2161            cx,
2162        )
2163    }
2164}
2165
2166fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2167    workspace::AppState::global(cx)
2168        .upgrade()
2169        .map(|app_state| {
2170            app_state
2171                .workspace_store
2172                .read(cx)
2173                .workspaces()
2174                .iter()
2175                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2176        })
2177        .into_iter()
2178        .flatten()
2179}
2180
2181fn update_settings_file(
2182    file: SettingsUiFile,
2183    cx: &mut App,
2184    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2185) -> Result<()> {
2186    match file {
2187        SettingsUiFile::Project((worktree_id, rel_path)) => {
2188            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2189            let project = all_projects(cx).find(|project| {
2190                project.read_with(cx, |project, cx| {
2191                    project.contains_local_settings_file(worktree_id, &rel_path, cx)
2192                })
2193            });
2194            let Some(project) = project else {
2195                anyhow::bail!(
2196                    "Could not find worktree containing settings file: {}",
2197                    &rel_path.display(PathStyle::local())
2198                );
2199            };
2200            project.update(cx, |project, cx| {
2201                project.update_local_settings_file(worktree_id, rel_path, cx, update);
2202            });
2203            return Ok(());
2204        }
2205        SettingsUiFile::User => {
2206            // todo(settings_ui) error?
2207            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2208            Ok(())
2209        }
2210        SettingsUiFile::Server(_) => unimplemented!(),
2211    }
2212}
2213
2214fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2215    field: SettingField<T>,
2216    file: SettingsUiFile,
2217    metadata: Option<&SettingsFieldMetadata>,
2218    _window: &mut Window,
2219    cx: &mut App,
2220) -> AnyElement {
2221    let (_, initial_text) =
2222        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2223    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2224
2225    SettingsEditor::new()
2226        .tab_index(0)
2227        .when_some(initial_text, |editor, text| {
2228            editor.with_initial_text(text.as_ref().to_string())
2229        })
2230        .when_some(
2231            metadata.and_then(|metadata| metadata.placeholder),
2232            |editor, placeholder| editor.with_placeholder(placeholder),
2233        )
2234        .on_confirm({
2235            move |new_text, cx| {
2236                update_settings_file(file.clone(), cx, move |settings, _cx| {
2237                    *(field.pick_mut)(settings) = new_text.map(Into::into);
2238                })
2239                .log_err(); // todo(settings_ui) don't log err
2240            }
2241        })
2242        .into_any_element()
2243}
2244
2245fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2246    field: SettingField<B>,
2247    file: SettingsUiFile,
2248    _metadata: Option<&SettingsFieldMetadata>,
2249    _window: &mut Window,
2250    cx: &mut App,
2251) -> AnyElement {
2252    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2253
2254    let toggle_state = if value.copied().map_or(false, Into::into) {
2255        ToggleState::Selected
2256    } else {
2257        ToggleState::Unselected
2258    };
2259
2260    Switch::new("toggle_button", toggle_state)
2261        .color(ui::SwitchColor::Accent)
2262        .on_click({
2263            move |state, _window, cx| {
2264                let state = *state == ui::ToggleState::Selected;
2265                update_settings_file(file.clone(), cx, move |settings, _cx| {
2266                    *(field.pick_mut)(settings) = Some(state.into());
2267                })
2268                .log_err(); // todo(settings_ui) don't log err
2269            }
2270        })
2271        .tab_index(0_isize)
2272        .color(SwitchColor::Accent)
2273        .into_any_element()
2274}
2275
2276fn render_font_picker(
2277    field: SettingField<settings::FontFamilyName>,
2278    file: SettingsUiFile,
2279    _metadata: Option<&SettingsFieldMetadata>,
2280    window: &mut Window,
2281    cx: &mut App,
2282) -> AnyElement {
2283    let current_value = SettingsStore::global(cx)
2284        .get_value_from_file(file.to_settings(), field.pick)
2285        .1
2286        .cloned()
2287        .unwrap_or_else(|| SharedString::default().into());
2288
2289    let font_picker = cx.new(|cx| {
2290        ui_input::font_picker(
2291            current_value.clone().into(),
2292            move |font_name, cx| {
2293                update_settings_file(file.clone(), cx, move |settings, _cx| {
2294                    *(field.pick_mut)(settings) = Some(font_name.into());
2295                })
2296                .log_err(); // todo(settings_ui) don't log err
2297            },
2298            window,
2299            cx,
2300        )
2301    });
2302
2303    PopoverMenu::new("font-picker")
2304        .menu(move |_window, _cx| Some(font_picker.clone()))
2305        .trigger(
2306            Button::new("font-family-button", current_value)
2307                .tab_index(0_isize)
2308                .style(ButtonStyle::Outlined)
2309                .size(ButtonSize::Medium)
2310                .icon(IconName::ChevronUpDown)
2311                .icon_color(Color::Muted)
2312                .icon_size(IconSize::Small)
2313                .icon_position(IconPosition::End),
2314        )
2315        .anchor(gpui::Corner::TopLeft)
2316        .offset(gpui::Point {
2317            x: px(0.0),
2318            y: px(2.0),
2319        })
2320        .with_handle(ui::PopoverMenuHandle::default())
2321        .into_any_element()
2322}
2323
2324fn render_number_field<T: NumberFieldType + Send + Sync>(
2325    field: SettingField<T>,
2326    file: SettingsUiFile,
2327    _metadata: Option<&SettingsFieldMetadata>,
2328    window: &mut Window,
2329    cx: &mut App,
2330) -> AnyElement {
2331    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2332    let value = value.copied().unwrap_or_else(T::min_value);
2333    NumberField::new("numeric_stepper", value, window, cx)
2334        .on_change({
2335            move |value, _window, cx| {
2336                let value = *value;
2337                update_settings_file(file.clone(), cx, move |settings, _cx| {
2338                    *(field.pick_mut)(settings) = Some(value);
2339                })
2340                .log_err(); // todo(settings_ui) don't log err
2341            }
2342        })
2343        .into_any_element()
2344}
2345
2346fn render_dropdown<T>(
2347    field: SettingField<T>,
2348    file: SettingsUiFile,
2349    _metadata: Option<&SettingsFieldMetadata>,
2350    window: &mut Window,
2351    cx: &mut App,
2352) -> AnyElement
2353where
2354    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2355{
2356    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2357    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2358
2359    let (_, current_value) =
2360        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2361    let current_value = current_value.copied().unwrap_or(variants()[0]);
2362
2363    let current_value_label =
2364        labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2365
2366    DropdownMenu::new(
2367        "dropdown",
2368        current_value_label.to_title_case(),
2369        ContextMenu::build(window, cx, move |mut menu, _, _| {
2370            for (&value, &label) in std::iter::zip(variants(), labels()) {
2371                let file = file.clone();
2372                menu = menu.toggleable_entry(
2373                    label.to_title_case(),
2374                    value == current_value,
2375                    IconPosition::End,
2376                    None,
2377                    move |_, cx| {
2378                        if value == current_value {
2379                            return;
2380                        }
2381                        update_settings_file(file.clone(), cx, move |settings, _cx| {
2382                            *(field.pick_mut)(settings) = Some(value);
2383                        })
2384                        .log_err(); // todo(settings_ui) don't log err
2385                    },
2386                );
2387            }
2388            menu
2389        }),
2390    )
2391    .trigger_size(ButtonSize::Medium)
2392    .style(DropdownStyle::Outlined)
2393    .offset(gpui::Point {
2394        x: px(0.0),
2395        y: px(2.0),
2396    })
2397    .tab_index(0)
2398    .into_any_element()
2399}
2400
2401#[cfg(test)]
2402mod test {
2403
2404    use super::*;
2405
2406    impl SettingsWindow {
2407        fn navbar_entry(&self) -> usize {
2408            self.navbar_entry
2409        }
2410    }
2411
2412    impl PartialEq for NavBarEntry {
2413        fn eq(&self, other: &Self) -> bool {
2414            self.title == other.title
2415                && self.is_root == other.is_root
2416                && self.expanded == other.expanded
2417                && self.page_index == other.page_index
2418                && self.item_index == other.item_index
2419            // ignoring focus_handle
2420        }
2421    }
2422
2423    fn register_settings(cx: &mut App) {
2424        settings::init(cx);
2425        theme::init(theme::LoadThemes::JustBase, cx);
2426        workspace::init_settings(cx);
2427        project::Project::init_settings(cx);
2428        language::init(cx);
2429        editor::init(cx);
2430        menu::init();
2431    }
2432
2433    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2434        let mut pages: Vec<SettingsPage> = Vec::new();
2435        let mut expanded_pages = Vec::new();
2436        let mut selected_idx = None;
2437        let mut index = 0;
2438        let mut in_expanded_section = false;
2439
2440        for mut line in input
2441            .lines()
2442            .map(|line| line.trim())
2443            .filter(|line| !line.is_empty())
2444        {
2445            if let Some(pre) = line.strip_suffix('*') {
2446                assert!(selected_idx.is_none(), "Only one selected entry allowed");
2447                selected_idx = Some(index);
2448                line = pre;
2449            }
2450            let (kind, title) = line.split_once(" ").unwrap();
2451            assert_eq!(kind.len(), 1);
2452            let kind = kind.chars().next().unwrap();
2453            if kind == 'v' {
2454                let page_idx = pages.len();
2455                expanded_pages.push(page_idx);
2456                pages.push(SettingsPage {
2457                    title,
2458                    items: vec![],
2459                });
2460                index += 1;
2461                in_expanded_section = true;
2462            } else if kind == '>' {
2463                pages.push(SettingsPage {
2464                    title,
2465                    items: vec![],
2466                });
2467                index += 1;
2468                in_expanded_section = false;
2469            } else if kind == '-' {
2470                pages
2471                    .last_mut()
2472                    .unwrap()
2473                    .items
2474                    .push(SettingsPageItem::SectionHeader(title));
2475                if selected_idx == Some(index) && !in_expanded_section {
2476                    panic!("Items in unexpanded sections cannot be selected");
2477                }
2478                index += 1;
2479            } else {
2480                panic!(
2481                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
2482                    line
2483                );
2484            }
2485        }
2486
2487        let mut settings_window = SettingsWindow {
2488            title_bar: None,
2489            original_window: None,
2490            worktree_root_dirs: HashMap::default(),
2491            files: Vec::default(),
2492            current_file: crate::SettingsUiFile::User,
2493            pages,
2494            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2495            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2496            navbar_entries: Vec::default(),
2497            navbar_scroll_handle: UniformListScrollHandle::default(),
2498            filter_table: vec![],
2499            has_query: false,
2500            content_handles: vec![],
2501            search_task: None,
2502            page_scroll_handle: ScrollHandle::new(),
2503            focus_handle: cx.focus_handle(),
2504            navbar_focus_handle: NonFocusableHandle::new(
2505                NAVBAR_CONTAINER_TAB_INDEX,
2506                false,
2507                window,
2508                cx,
2509            ),
2510            content_focus_handle: NonFocusableHandle::new(
2511                CONTENT_CONTAINER_TAB_INDEX,
2512                false,
2513                window,
2514                cx,
2515            ),
2516            files_focus_handle: cx.focus_handle(),
2517            search_index: None,
2518        };
2519
2520        settings_window.build_filter_table();
2521        settings_window.build_navbar(cx);
2522        for expanded_page_index in expanded_pages {
2523            for entry in &mut settings_window.navbar_entries {
2524                if entry.page_index == expanded_page_index && entry.is_root {
2525                    entry.expanded = true;
2526                }
2527            }
2528        }
2529        settings_window
2530    }
2531
2532    #[track_caller]
2533    fn check_navbar_toggle(
2534        before: &'static str,
2535        toggle_page: &'static str,
2536        after: &'static str,
2537        window: &mut Window,
2538        cx: &mut App,
2539    ) {
2540        let mut settings_window = parse(before, window, cx);
2541        let toggle_page_idx = settings_window
2542            .pages
2543            .iter()
2544            .position(|page| page.title == toggle_page)
2545            .expect("page not found");
2546        let toggle_idx = settings_window
2547            .navbar_entries
2548            .iter()
2549            .position(|entry| entry.page_index == toggle_page_idx)
2550            .expect("page not found");
2551        settings_window.toggle_navbar_entry(toggle_idx);
2552
2553        let expected_settings_window = parse(after, window, cx);
2554
2555        pretty_assertions::assert_eq!(
2556            settings_window
2557                .visible_navbar_entries()
2558                .map(|(_, entry)| entry)
2559                .collect::<Vec<_>>(),
2560            expected_settings_window
2561                .visible_navbar_entries()
2562                .map(|(_, entry)| entry)
2563                .collect::<Vec<_>>(),
2564        );
2565        pretty_assertions::assert_eq!(
2566            settings_window.navbar_entries[settings_window.navbar_entry()],
2567            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2568        );
2569    }
2570
2571    macro_rules! check_navbar_toggle {
2572        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2573            #[gpui::test]
2574            fn $name(cx: &mut gpui::TestAppContext) {
2575                let window = cx.add_empty_window();
2576                window.update(|window, cx| {
2577                    register_settings(cx);
2578                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
2579                });
2580            }
2581        };
2582    }
2583
2584    check_navbar_toggle!(
2585        navbar_basic_open,
2586        before: r"
2587        v General
2588        - General
2589        - Privacy*
2590        v Project
2591        - Project Settings
2592        ",
2593        toggle_page: "General",
2594        after: r"
2595        > General*
2596        v Project
2597        - Project Settings
2598        "
2599    );
2600
2601    check_navbar_toggle!(
2602        navbar_basic_close,
2603        before: r"
2604        > General*
2605        - General
2606        - Privacy
2607        v Project
2608        - Project Settings
2609        ",
2610        toggle_page: "General",
2611        after: r"
2612        v General*
2613        - General
2614        - Privacy
2615        v Project
2616        - Project Settings
2617        "
2618    );
2619
2620    check_navbar_toggle!(
2621        navbar_basic_second_root_entry_close,
2622        before: r"
2623        > General
2624        - General
2625        - Privacy
2626        v Project
2627        - Project Settings*
2628        ",
2629        toggle_page: "Project",
2630        after: r"
2631        > General
2632        > Project*
2633        "
2634    );
2635
2636    check_navbar_toggle!(
2637        navbar_toggle_subroot,
2638        before: r"
2639        v General Page
2640        - General
2641        - Privacy
2642        v Project
2643        - Worktree Settings Content*
2644        v AI
2645        - General
2646        > Appearance & Behavior
2647        ",
2648        toggle_page: "Project",
2649        after: r"
2650        v General Page
2651        - General
2652        - Privacy
2653        > Project*
2654        v AI
2655        - General
2656        > Appearance & Behavior
2657        "
2658    );
2659
2660    check_navbar_toggle!(
2661        navbar_toggle_close_propagates_selected_index,
2662        before: r"
2663        v General Page
2664        - General
2665        - Privacy
2666        v Project
2667        - Worktree Settings Content
2668        v AI
2669        - General*
2670        > Appearance & Behavior
2671        ",
2672        toggle_page: "General Page",
2673        after: r"
2674        > General Page
2675        v Project
2676        - Worktree Settings Content
2677        v AI
2678        - General*
2679        > Appearance & Behavior
2680        "
2681    );
2682
2683    check_navbar_toggle!(
2684        navbar_toggle_expand_propagates_selected_index,
2685        before: r"
2686        > General Page
2687        - General
2688        - Privacy
2689        v Project
2690        - Worktree Settings Content
2691        v AI
2692        - General*
2693        > Appearance & Behavior
2694        ",
2695        toggle_page: "General Page",
2696        after: r"
2697        v General Page
2698        - General
2699        - Privacy
2700        v Project
2701        - Worktree Settings Content
2702        v AI
2703        - General*
2704        > Appearance & Behavior
2705        "
2706    );
2707}