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