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