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