settings_ui.rs

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