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