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