settings_ui.rs

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