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