1mod components;
   2mod page_data;
   3
   4use anyhow::Result;
   5use editor::{Editor, EditorEvent};
   6use feature_flags::FeatureFlag;
   7use fuzzy::StringMatchCandidate;
   8use gpui::{
   9    Action, App, Div, Entity, FocusHandle, Focusable, Global, ListState, ReadGlobal as _,
  10    ScrollHandle, Stateful, Subscription, Task, TitlebarOptions, UniformListScrollHandle, Window,
  11    WindowBounds, WindowHandle, WindowOptions, actions, div, list, point, prelude::*, px, size,
  12    uniform_list,
  13};
  14use heck::ToTitleCase as _;
  15use project::WorktreeId;
  16use schemars::JsonSchema;
  17use serde::Deserialize;
  18use settings::{Settings, SettingsContent, SettingsStore};
  19use std::{
  20    any::{Any, TypeId, type_name},
  21    cell::RefCell,
  22    collections::HashMap,
  23    num::{NonZero, NonZeroU32},
  24    ops::Range,
  25    rc::Rc,
  26    sync::{Arc, LazyLock, RwLock},
  27};
  28use title_bar::platform_title_bar::PlatformTitleBar;
  29use ui::{
  30    Banner, ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape,
  31    KeyBinding, KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem,
  32    WithScrollbar, prelude::*,
  33};
  34use ui_input::{NumberField, NumberFieldType};
  35use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
  36use workspace::{OpenOptions, OpenVisible, Workspace, client_side_decorations};
  37use zed_actions::{OpenSettings, OpenSettingsAt};
  38
  39use crate::components::{SettingsInputField, font_picker, icon_theme_picker, theme_picker};
  40
  41const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
  42const NAVBAR_GROUP_TAB_INDEX: isize = 1;
  43
  44const HEADER_CONTAINER_TAB_INDEX: isize = 2;
  45const HEADER_GROUP_TAB_INDEX: isize = 3;
  46
  47const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
  48const CONTENT_GROUP_TAB_INDEX: isize = 5;
  49
  50actions!(
  51    settings_editor,
  52    [
  53        /// Minimizes the settings UI window.
  54        Minimize,
  55        /// Toggles focus between the navbar and the main content.
  56        ToggleFocusNav,
  57        /// Expands the navigation entry.
  58        ExpandNavEntry,
  59        /// Collapses the navigation entry.
  60        CollapseNavEntry,
  61        /// Focuses the next file in the file list.
  62        FocusNextFile,
  63        /// Focuses the previous file in the file list.
  64        FocusPreviousFile,
  65        /// Opens an editor for the current file
  66        OpenCurrentFile,
  67        /// Focuses the previous root navigation entry.
  68        FocusPreviousRootNavEntry,
  69        /// Focuses the next root navigation entry.
  70        FocusNextRootNavEntry,
  71        /// Focuses the first navigation entry.
  72        FocusFirstNavEntry,
  73        /// Focuses the last navigation entry.
  74        FocusLastNavEntry,
  75        /// Focuses and opens the next navigation entry without moving focus to content.
  76        FocusNextNavEntry,
  77        /// Focuses and opens the previous navigation entry without moving focus to content.
  78        FocusPreviousNavEntry
  79    ]
  80);
  81
  82#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
  83#[action(namespace = settings_editor)]
  84struct FocusFile(pub u32);
  85
  86struct SettingField<T: 'static> {
  87    pick: fn(&SettingsContent) -> Option<&T>,
  88    write: fn(&mut SettingsContent, Option<T>),
  89
  90    /// A json-path-like string that gives a unique-ish string that identifies
  91    /// where in the JSON the setting is defined.
  92    ///
  93    /// The syntax is `jq`-like, but modified slightly to be URL-safe (and
  94    /// without the leading dot), e.g. `foo.bar`.
  95    ///
  96    /// They are URL-safe (this is important since links are the main use-case
  97    /// for these paths).
  98    ///
  99    /// There are a couple of special cases:
 100    /// - discrimminants are represented with a trailing `$`, for example
 101    /// `terminal.working_directory$`. This is to distinguish the discrimminant
 102    /// setting (i.e. the setting that changes whether the value is a string or
 103    /// an object) from the setting in the case that it is a string.
 104    /// - language-specific settings begin `languages.$(language)`. Links
 105    /// targeting these settings should take the form `languages/Rust/...`, for
 106    /// example, but are not currently supported.
 107    json_path: Option<&'static str>,
 108}
 109
 110impl<T: 'static> Clone for SettingField<T> {
 111    fn clone(&self) -> Self {
 112        *self
 113    }
 114}
 115
 116// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
 117impl<T: 'static> Copy for SettingField<T> {}
 118
 119/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
 120/// to keep the setting around in the UI with valid pick and write implementations, but don't actually try to render it.
 121/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
 122#[derive(Clone, Copy)]
 123struct UnimplementedSettingField;
 124
 125impl PartialEq for UnimplementedSettingField {
 126    fn eq(&self, _other: &Self) -> bool {
 127        true
 128    }
 129}
 130
 131impl<T: 'static> SettingField<T> {
 132    /// Helper for settings with types that are not yet implemented.
 133    #[allow(unused)]
 134    fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
 135        SettingField {
 136            pick: |_| Some(&UnimplementedSettingField),
 137            write: |_, _| unreachable!(),
 138            json_path: None,
 139        }
 140    }
 141}
 142
 143trait AnySettingField {
 144    fn as_any(&self) -> &dyn Any;
 145    fn type_name(&self) -> &'static str;
 146    fn type_id(&self) -> TypeId;
 147    // 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)
 148    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
 149    fn reset_to_default_fn(
 150        &self,
 151        current_file: &SettingsUiFile,
 152        file_set_in: &settings::SettingsFile,
 153        cx: &App,
 154    ) -> Option<Box<dyn Fn(&mut App)>>;
 155
 156    fn json_path(&self) -> Option<&'static str>;
 157}
 158
 159impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
 160    fn as_any(&self) -> &dyn Any {
 161        self
 162    }
 163
 164    fn type_name(&self) -> &'static str {
 165        type_name::<T>()
 166    }
 167
 168    fn type_id(&self) -> TypeId {
 169        TypeId::of::<T>()
 170    }
 171
 172    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
 173        let (file, value) = cx
 174            .global::<SettingsStore>()
 175            .get_value_from_file(file.to_settings(), self.pick);
 176        return (file, value.is_some());
 177    }
 178
 179    fn reset_to_default_fn(
 180        &self,
 181        current_file: &SettingsUiFile,
 182        file_set_in: &settings::SettingsFile,
 183        cx: &App,
 184    ) -> Option<Box<dyn Fn(&mut App)>> {
 185        if file_set_in == &settings::SettingsFile::Default {
 186            return None;
 187        }
 188        if file_set_in != ¤t_file.to_settings() {
 189            return None;
 190        }
 191        let this = *self;
 192        let store = SettingsStore::global(cx);
 193        let default_value = (this.pick)(store.raw_default_settings());
 194        let is_default = store
 195            .get_content_for_file(file_set_in.clone())
 196            .map_or(None, this.pick)
 197            == default_value;
 198        if is_default {
 199            return None;
 200        }
 201        let current_file = current_file.clone();
 202
 203        return Some(Box::new(move |cx| {
 204            let store = SettingsStore::global(cx);
 205            let default_value = (this.pick)(store.raw_default_settings());
 206            let is_set_somewhere_other_than_default = store
 207                .get_value_up_to_file(current_file.to_settings(), this.pick)
 208                .0
 209                != settings::SettingsFile::Default;
 210            let value_to_set = if is_set_somewhere_other_than_default {
 211                default_value.cloned()
 212            } else {
 213                None
 214            };
 215            update_settings_file(current_file.clone(), cx, move |settings, _| {
 216                (this.write)(settings, value_to_set);
 217            })
 218            // todo(settings_ui): Don't log err
 219            .log_err();
 220        }));
 221    }
 222
 223    fn json_path(&self) -> Option<&'static str> {
 224        self.json_path
 225    }
 226}
 227
 228#[derive(Default, Clone)]
 229struct SettingFieldRenderer {
 230    renderers: Rc<
 231        RefCell<
 232            HashMap<
 233                TypeId,
 234                Box<
 235                    dyn Fn(
 236                        &SettingsWindow,
 237                        &SettingItem,
 238                        SettingsUiFile,
 239                        Option<&SettingsFieldMetadata>,
 240                        &mut Window,
 241                        &mut Context<SettingsWindow>,
 242                    ) -> Stateful<Div>,
 243                >,
 244            >,
 245        >,
 246    >,
 247}
 248
 249impl Global for SettingFieldRenderer {}
 250
 251impl SettingFieldRenderer {
 252    fn add_basic_renderer<T: 'static>(
 253        &mut self,
 254        render_control: impl Fn(
 255            SettingField<T>,
 256            SettingsUiFile,
 257            Option<&SettingsFieldMetadata>,
 258            &mut Window,
 259            &mut App,
 260        ) -> AnyElement
 261        + 'static,
 262    ) -> &mut Self {
 263        self.add_renderer(
 264            move |settings_window: &SettingsWindow,
 265                  item: &SettingItem,
 266                  field: SettingField<T>,
 267                  settings_file: SettingsUiFile,
 268                  metadata: Option<&SettingsFieldMetadata>,
 269                  window: &mut Window,
 270                  cx: &mut Context<SettingsWindow>| {
 271                render_settings_item(
 272                    settings_window,
 273                    item,
 274                    settings_file.clone(),
 275                    render_control(field, settings_file, metadata, window, cx),
 276                    window,
 277                    cx,
 278                )
 279            },
 280        )
 281    }
 282
 283    fn add_renderer<T: 'static>(
 284        &mut self,
 285        renderer: impl Fn(
 286            &SettingsWindow,
 287            &SettingItem,
 288            SettingField<T>,
 289            SettingsUiFile,
 290            Option<&SettingsFieldMetadata>,
 291            &mut Window,
 292            &mut Context<SettingsWindow>,
 293        ) -> Stateful<Div>
 294        + 'static,
 295    ) -> &mut Self {
 296        let key = TypeId::of::<T>();
 297        let renderer = Box::new(
 298            move |settings_window: &SettingsWindow,
 299                  item: &SettingItem,
 300                  settings_file: SettingsUiFile,
 301                  metadata: Option<&SettingsFieldMetadata>,
 302                  window: &mut Window,
 303                  cx: &mut Context<SettingsWindow>| {
 304                let field = *item
 305                    .field
 306                    .as_ref()
 307                    .as_any()
 308                    .downcast_ref::<SettingField<T>>()
 309                    .unwrap();
 310                renderer(
 311                    settings_window,
 312                    item,
 313                    field,
 314                    settings_file,
 315                    metadata,
 316                    window,
 317                    cx,
 318                )
 319            },
 320        );
 321        self.renderers.borrow_mut().insert(key, renderer);
 322        self
 323    }
 324}
 325
 326struct NonFocusableHandle {
 327    handle: FocusHandle,
 328    _subscription: Subscription,
 329}
 330
 331impl NonFocusableHandle {
 332    fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
 333        let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
 334        Self::from_handle(handle, window, cx)
 335    }
 336
 337    fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
 338        cx.new(|cx| {
 339            let _subscription = cx.on_focus(&handle, window, {
 340                move |_, window, _| {
 341                    window.focus_next();
 342                }
 343            });
 344            Self {
 345                handle,
 346                _subscription,
 347            }
 348        })
 349    }
 350}
 351
 352impl Focusable for NonFocusableHandle {
 353    fn focus_handle(&self, _: &App) -> FocusHandle {
 354        self.handle.clone()
 355    }
 356}
 357
 358#[derive(Default)]
 359struct SettingsFieldMetadata {
 360    placeholder: Option<&'static str>,
 361    should_do_titlecase: Option<bool>,
 362}
 363
 364pub struct SettingsUiFeatureFlag;
 365
 366impl FeatureFlag for SettingsUiFeatureFlag {
 367    const NAME: &'static str = "settings-ui";
 368}
 369
 370pub fn init(cx: &mut App) {
 371    init_renderers(cx);
 372
 373    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 374        workspace.register_action(
 375            |workspace, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
 376                let window_handle = window
 377                    .window_handle()
 378                    .downcast::<Workspace>()
 379                    .expect("Workspaces are root Windows");
 380                open_settings_editor(workspace, Some(&path), window_handle, cx);
 381            },
 382        );
 383    })
 384    .detach();
 385
 386    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 387        workspace.register_action(|workspace, _: &OpenSettings, window, cx| {
 388            let window_handle = window
 389                .window_handle()
 390                .downcast::<Workspace>()
 391                .expect("Workspaces are root Windows");
 392            open_settings_editor(workspace, None, window_handle, cx);
 393        });
 394    })
 395    .detach();
 396}
 397
 398fn init_renderers(cx: &mut App) {
 399    cx.default_global::<SettingFieldRenderer>()
 400        .add_basic_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
 401            Button::new("open-in-settings-file", "Edit in settings.json")
 402                .style(ButtonStyle::Outlined)
 403                .size(ButtonSize::Medium)
 404                .tab_index(0_isize)
 405                .on_click(|_, window, cx| {
 406                    window.dispatch_action(Box::new(OpenCurrentFile), cx);
 407                })
 408                .into_any_element()
 409        })
 410        .add_basic_renderer::<bool>(render_toggle_button)
 411        .add_basic_renderer::<String>(render_text_field)
 412        .add_basic_renderer::<SharedString>(render_text_field)
 413        .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
 414        .add_basic_renderer::<settings::CursorShape>(render_dropdown)
 415        .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
 416        .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
 417        .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
 418        .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
 419        .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
 420        .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
 421        .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
 422        .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
 423        .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
 424        .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
 425        .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
 426        .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
 427        .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
 428        .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
 429        .add_basic_renderer::<settings::DockSide>(render_dropdown)
 430        .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
 431        .add_basic_renderer::<settings::DockPosition>(render_dropdown)
 432        .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
 433        .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
 434        .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
 435        .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
 436        .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
 437        .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
 438        .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
 439        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 440        .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
 441        .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
 442        .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
 443        .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
 444        .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
 445        .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
 446        .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
 447        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 448        .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
 449        .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
 450        .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
 451        .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
 452        .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
 453        .add_basic_renderer::<f32>(render_number_field)
 454        .add_basic_renderer::<u32>(render_number_field)
 455        .add_basic_renderer::<u64>(render_number_field)
 456        .add_basic_renderer::<usize>(render_number_field)
 457        .add_basic_renderer::<NonZero<usize>>(render_number_field)
 458        .add_basic_renderer::<NonZeroU32>(render_number_field)
 459        .add_basic_renderer::<settings::CodeFade>(render_number_field)
 460        .add_basic_renderer::<settings::DelayMs>(render_number_field)
 461        .add_basic_renderer::<gpui::FontWeight>(render_number_field)
 462        .add_basic_renderer::<settings::CenteredPaddingSettings>(render_number_field)
 463        .add_basic_renderer::<settings::InactiveOpacity>(render_number_field)
 464        .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
 465        .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
 466        .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
 467        .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
 468        .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
 469        .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
 470        .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
 471        .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
 472        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 473        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 474        .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
 475        .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
 476        .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
 477        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 478        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 479        .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
 480        .add_basic_renderer::<settings::ThemeSelectionDiscriminants>(render_dropdown)
 481        .add_basic_renderer::<settings::ThemeMode>(render_dropdown)
 482        .add_basic_renderer::<settings::ThemeName>(render_theme_picker)
 483        .add_basic_renderer::<settings::IconThemeSelectionDiscriminants>(render_dropdown)
 484        .add_basic_renderer::<settings::IconThemeName>(render_icon_theme_picker)
 485        .add_basic_renderer::<settings::BufferLineHeightDiscriminants>(render_dropdown)
 486        .add_basic_renderer::<settings::AutosaveSettingDiscriminants>(render_dropdown)
 487        .add_basic_renderer::<settings::WorkingDirectoryDiscriminants>(render_dropdown)
 488        .add_basic_renderer::<settings::MaybeDiscriminants>(render_dropdown)
 489        .add_basic_renderer::<settings::IncludeIgnoredContent>(render_dropdown)
 490        .add_basic_renderer::<settings::ShowIndentGuides>(render_dropdown)
 491        .add_basic_renderer::<settings::ShellDiscriminants>(render_dropdown)
 492        // please semicolon stay on next line
 493        ;
 494}
 495
 496pub fn open_settings_editor(
 497    _workspace: &mut Workspace,
 498    path: Option<&str>,
 499    workspace_handle: WindowHandle<Workspace>,
 500    cx: &mut App,
 501) {
 502    /// Assumes a settings GUI window is already open
 503    fn open_path(
 504        path: &str,
 505        settings_window: &mut SettingsWindow,
 506        window: &mut Window,
 507        cx: &mut Context<SettingsWindow>,
 508    ) {
 509        if path.starts_with("languages.$(language)") {
 510            log::error!("language-specific settings links are not currently supported");
 511            return;
 512        }
 513
 514        settings_window.current_file = SettingsUiFile::User;
 515        settings_window.build_ui(window, cx);
 516
 517        let mut item_info = None;
 518        'search: for (nav_entry_index, entry) in settings_window.navbar_entries.iter().enumerate() {
 519            if entry.is_root {
 520                continue;
 521            }
 522            let page_index = entry.page_index;
 523            let header_index = entry
 524                .item_index
 525                .expect("non-root entries should have an item index");
 526            for item_index in header_index + 1..settings_window.pages[page_index].items.len() {
 527                let item = &settings_window.pages[page_index].items[item_index];
 528                if let SettingsPageItem::SectionHeader(_) = item {
 529                    break;
 530                }
 531                if let SettingsPageItem::SettingItem(item) = item {
 532                    if item.field.json_path() == Some(path) {
 533                        if !item.files.contains(USER) {
 534                            log::error!("Found item {}, but it is not a user setting", path);
 535                            return;
 536                        }
 537                        item_info = Some((item_index, nav_entry_index));
 538                        break 'search;
 539                    }
 540                }
 541            }
 542        }
 543        let Some((item_index, navbar_entry_index)) = item_info else {
 544            log::error!("Failed to find item for {}", path);
 545            return;
 546        };
 547
 548        settings_window.open_navbar_entry_page(navbar_entry_index);
 549        window.focus(&settings_window.focus_handle_for_content_element(item_index, cx));
 550        settings_window.scroll_to_content_item(item_index, window, cx);
 551    }
 552
 553    let existing_window = cx
 554        .windows()
 555        .into_iter()
 556        .find_map(|window| window.downcast::<SettingsWindow>());
 557
 558    if let Some(existing_window) = existing_window {
 559        existing_window
 560            .update(cx, |settings_window, window, cx| {
 561                settings_window.original_window = Some(workspace_handle);
 562                settings_window.observe_last_window_close(cx);
 563                window.activate_window();
 564                if let Some(path) = path {
 565                    open_path(path, settings_window, window, cx);
 566                }
 567            })
 568            .ok();
 569        return;
 570    }
 571
 572    // We have to defer this to get the workspace off the stack.
 573
 574    let path = path.map(ToOwned::to_owned);
 575    cx.defer(move |cx| {
 576        let current_rem_size: f32 = theme::ThemeSettings::get_global(cx).ui_font_size(cx).into();
 577
 578        let default_bounds = size(px(900.), px(750.)); // 4:3 Aspect Ratio
 579        let default_rem_size = 16.0;
 580        let scale_factor = current_rem_size / default_rem_size;
 581        let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
 582
 583        let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
 584            Ok(val) if val == "server" => gpui::WindowDecorations::Server,
 585            Ok(val) if val == "client" => gpui::WindowDecorations::Client,
 586            _ => gpui::WindowDecorations::Client,
 587        };
 588
 589        cx.open_window(
 590            WindowOptions {
 591                titlebar: Some(TitlebarOptions {
 592                    title: Some("Settings Window".into()),
 593                    appears_transparent: true,
 594                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 595                }),
 596                focus: true,
 597                show: true,
 598                is_movable: true,
 599                kind: gpui::WindowKind::Floating,
 600                window_background: cx.theme().window_background_appearance(),
 601                window_decorations: Some(window_decorations),
 602                window_min_size: Some(scaled_bounds),
 603                window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
 604                ..Default::default()
 605            },
 606            |window, cx| {
 607                let settings_window =
 608                    cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx));
 609                settings_window.update(cx, |settings_window, cx| {
 610                    if let Some(path) = path {
 611                        open_path(&path, settings_window, window, cx);
 612                    }
 613                });
 614
 615                settings_window
 616            },
 617        )
 618        .log_err();
 619    });
 620}
 621
 622/// The current sub page path that is selected.
 623/// If this is empty the selected page is rendered,
 624/// otherwise the last sub page gets rendered.
 625///
 626/// Global so that `pick` and `write` callbacks can access it
 627/// and use it to dynamically render sub pages (e.g. for language settings)
 628static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
 629
 630fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
 631    SUB_PAGE_STACK
 632        .read()
 633        .expect("SUB_PAGE_STACK is never poisoned")
 634}
 635
 636fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
 637    SUB_PAGE_STACK
 638        .write()
 639        .expect("SUB_PAGE_STACK is never poisoned")
 640}
 641
 642pub struct SettingsWindow {
 643    title_bar: Option<Entity<PlatformTitleBar>>,
 644    original_window: Option<WindowHandle<Workspace>>,
 645    files: Vec<(SettingsUiFile, FocusHandle)>,
 646    drop_down_file: Option<usize>,
 647    worktree_root_dirs: HashMap<WorktreeId, String>,
 648    current_file: SettingsUiFile,
 649    pages: Vec<SettingsPage>,
 650    search_bar: Entity<Editor>,
 651    search_task: Option<Task<()>>,
 652    /// Index into navbar_entries
 653    navbar_entry: usize,
 654    navbar_entries: Vec<NavBarEntry>,
 655    navbar_scroll_handle: UniformListScrollHandle,
 656    /// [page_index][page_item_index] will be false
 657    /// when the item is filtered out either by searches
 658    /// or by the current file
 659    navbar_focus_subscriptions: Vec<gpui::Subscription>,
 660    filter_table: Vec<Vec<bool>>,
 661    has_query: bool,
 662    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 663    sub_page_scroll_handle: ScrollHandle,
 664    focus_handle: FocusHandle,
 665    navbar_focus_handle: Entity<NonFocusableHandle>,
 666    content_focus_handle: Entity<NonFocusableHandle>,
 667    files_focus_handle: FocusHandle,
 668    search_index: Option<Arc<SearchIndex>>,
 669    list_state: ListState,
 670}
 671
 672struct SearchIndex {
 673    bm25_engine: bm25::SearchEngine<usize>,
 674    fuzzy_match_candidates: Vec<StringMatchCandidate>,
 675    key_lut: Vec<SearchItemKey>,
 676}
 677
 678struct SearchItemKey {
 679    page_index: usize,
 680    header_index: usize,
 681    item_index: usize,
 682}
 683
 684struct SubPage {
 685    link: SubPageLink,
 686    section_header: &'static str,
 687}
 688
 689#[derive(Debug)]
 690struct NavBarEntry {
 691    title: &'static str,
 692    is_root: bool,
 693    expanded: bool,
 694    page_index: usize,
 695    item_index: Option<usize>,
 696    focus_handle: FocusHandle,
 697}
 698
 699struct SettingsPage {
 700    title: &'static str,
 701    items: Vec<SettingsPageItem>,
 702}
 703
 704#[derive(PartialEq)]
 705enum SettingsPageItem {
 706    SectionHeader(&'static str),
 707    SettingItem(SettingItem),
 708    SubPageLink(SubPageLink),
 709    DynamicItem(DynamicItem),
 710}
 711
 712impl std::fmt::Debug for SettingsPageItem {
 713    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 714        match self {
 715            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 716            SettingsPageItem::SettingItem(setting_item) => {
 717                write!(f, "SettingItem({})", setting_item.title)
 718            }
 719            SettingsPageItem::SubPageLink(sub_page_link) => {
 720                write!(f, "SubPageLink({})", sub_page_link.title)
 721            }
 722            SettingsPageItem::DynamicItem(dynamic_item) => {
 723                write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
 724            }
 725        }
 726    }
 727}
 728
 729impl SettingsPageItem {
 730    fn render(
 731        &self,
 732        settings_window: &SettingsWindow,
 733        item_index: usize,
 734        is_last: bool,
 735        window: &mut Window,
 736        cx: &mut Context<SettingsWindow>,
 737    ) -> AnyElement {
 738        let file = settings_window.current_file.clone();
 739
 740        let border_variant = cx.theme().colors().border_variant;
 741        let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
 742            let element = element.pt_4();
 743            if is_last {
 744                element.pb_10()
 745            } else {
 746                element.pb_4().border_b_1().border_color(border_variant)
 747            }
 748        };
 749
 750        let mut render_setting_item_inner =
 751            |setting_item: &SettingItem, padding: bool, cx: &mut Context<SettingsWindow>| {
 752                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 753                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 754
 755                let renderers = renderer.renderers.borrow();
 756
 757                let field_renderer =
 758                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 759                let field_renderer_or_warning =
 760                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 761                        if cfg!(debug_assertions) && !found {
 762                            Err("NO DEFAULT")
 763                        } else {
 764                            Ok(renderer)
 765                        }
 766                    });
 767
 768                let field = match field_renderer_or_warning {
 769                    Ok(field_renderer) => field_renderer(
 770                        settings_window,
 771                        setting_item,
 772                        file.clone(),
 773                        setting_item.metadata.as_deref(),
 774                        window,
 775                        cx,
 776                    ),
 777                    Err(warning) => render_settings_item(
 778                        settings_window,
 779                        setting_item,
 780                        file.clone(),
 781                        Button::new("error-warning", warning)
 782                            .style(ButtonStyle::Outlined)
 783                            .size(ButtonSize::Medium)
 784                            .icon(Some(IconName::Debug))
 785                            .icon_position(IconPosition::Start)
 786                            .icon_color(Color::Error)
 787                            .tab_index(0_isize)
 788                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 789                            .into_any_element(),
 790                        window,
 791                        cx,
 792                    ),
 793                };
 794
 795                let field = if padding {
 796                    field.map(apply_padding)
 797                } else {
 798                    field
 799                };
 800
 801                (field, field_renderer_or_warning.is_ok())
 802            };
 803
 804        match self {
 805            SettingsPageItem::SectionHeader(header) => v_flex()
 806                .w_full()
 807                .gap_1p5()
 808                .child(
 809                    Label::new(SharedString::new_static(header))
 810                        .size(LabelSize::Small)
 811                        .color(Color::Muted)
 812                        .buffer_font(cx),
 813                )
 814                .child(Divider::horizontal().color(DividerColor::BorderFaded))
 815                .into_any_element(),
 816            SettingsPageItem::SettingItem(setting_item) => {
 817                let (field_with_padding, _) = render_setting_item_inner(setting_item, true, cx);
 818                field_with_padding.into_any_element()
 819            }
 820            SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
 821                .id(sub_page_link.title.clone())
 822                .w_full()
 823                .min_w_0()
 824                .justify_between()
 825                .map(apply_padding)
 826                .child(
 827                    v_flex()
 828                        .w_full()
 829                        .max_w_1_2()
 830                        .child(Label::new(sub_page_link.title.clone())),
 831                )
 832                .child(
 833                    Button::new(
 834                        ("sub-page".into(), sub_page_link.title.clone()),
 835                        "Configure",
 836                    )
 837                    .icon(IconName::ChevronRight)
 838                    .tab_index(0_isize)
 839                    .icon_position(IconPosition::End)
 840                    .icon_color(Color::Muted)
 841                    .icon_size(IconSize::Small)
 842                    .style(ButtonStyle::OutlinedGhost)
 843                    .size(ButtonSize::Medium)
 844                    .on_click({
 845                        let sub_page_link = sub_page_link.clone();
 846                        cx.listener(move |this, _, _, cx| {
 847                            let mut section_index = item_index;
 848                            let current_page = this.current_page();
 849
 850                            while !matches!(
 851                                current_page.items[section_index],
 852                                SettingsPageItem::SectionHeader(_)
 853                            ) {
 854                                section_index -= 1;
 855                            }
 856
 857                            let SettingsPageItem::SectionHeader(header) =
 858                                current_page.items[section_index]
 859                            else {
 860                                unreachable!("All items always have a section header above them")
 861                            };
 862
 863                            this.push_sub_page(sub_page_link.clone(), header, cx)
 864                        })
 865                    }),
 866                )
 867                .into_any_element(),
 868            SettingsPageItem::DynamicItem(DynamicItem {
 869                discriminant: discriminant_setting_item,
 870                pick_discriminant,
 871                fields,
 872            }) => {
 873                let file = file.to_settings();
 874                let discriminant = SettingsStore::global(cx)
 875                    .get_value_from_file(file, *pick_discriminant)
 876                    .1;
 877
 878                let (discriminant_element, rendered_ok) =
 879                    render_setting_item_inner(discriminant_setting_item, true, cx);
 880
 881                let has_sub_fields =
 882                    rendered_ok && discriminant.map(|d| !fields[d].is_empty()).unwrap_or(false);
 883
 884                let discriminant_element = if has_sub_fields {
 885                    discriminant_element.pb_4().border_b_0()
 886                } else {
 887                    discriminant_element
 888                };
 889
 890                let mut content = v_flex().id("dynamic-item").child(discriminant_element);
 891
 892                if rendered_ok {
 893                    let discriminant =
 894                        discriminant.expect("This should be Some if rendered_ok is true");
 895                    let sub_fields = &fields[discriminant];
 896                    let sub_field_count = sub_fields.len();
 897
 898                    for (index, field) in sub_fields.iter().enumerate() {
 899                        let is_last_sub_field = index == sub_field_count - 1;
 900                        let (raw_field, _) = render_setting_item_inner(field, false, cx);
 901
 902                        content = content.child(
 903                            raw_field
 904                                .p_4()
 905                                .border_x_1()
 906                                .border_t_1()
 907                                .when(is_last_sub_field, |this| this.border_b_1())
 908                                .when(is_last_sub_field && is_last, |this| this.mb_8())
 909                                .border_dashed()
 910                                .border_color(cx.theme().colors().border_variant)
 911                                .bg(cx.theme().colors().element_background.opacity(0.2)),
 912                        );
 913                    }
 914                }
 915
 916                return content.into_any_element();
 917            }
 918        }
 919    }
 920}
 921
 922fn render_settings_item(
 923    settings_window: &SettingsWindow,
 924    setting_item: &SettingItem,
 925    file: SettingsUiFile,
 926    control: AnyElement,
 927    _window: &mut Window,
 928    cx: &mut Context<'_, SettingsWindow>,
 929) -> Stateful<Div> {
 930    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
 931    let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
 932
 933    h_flex()
 934        .id(setting_item.title)
 935        .min_w_0()
 936        .justify_between()
 937        .child(
 938            v_flex()
 939                .w_1_2()
 940                .child(
 941                    h_flex()
 942                        .w_full()
 943                        .gap_1()
 944                        .child(Label::new(SharedString::new_static(setting_item.title)))
 945                        .when_some(
 946                            setting_item
 947                                .field
 948                                .reset_to_default_fn(&file, &found_in_file, cx),
 949                            |this, reset_to_default| {
 950                                this.child(
 951                                    IconButton::new("reset-to-default-btn", IconName::Undo)
 952                                        .icon_color(Color::Muted)
 953                                        .icon_size(IconSize::Small)
 954                                        .tooltip(Tooltip::text("Reset to Default"))
 955                                        .on_click({
 956                                            move |_, _, cx| {
 957                                                reset_to_default(cx);
 958                                            }
 959                                        }),
 960                                )
 961                            },
 962                        )
 963                        .when_some(
 964                            file_set_in.filter(|file_set_in| file_set_in != &file),
 965                            |this, file_set_in| {
 966                                this.child(
 967                                    Label::new(format!(
 968                                        "—  Modified in {}",
 969                                        settings_window
 970                                            .display_name(&file_set_in)
 971                                            .expect("File name should exist")
 972                                    ))
 973                                    .color(Color::Muted)
 974                                    .size(LabelSize::Small),
 975                                )
 976                            },
 977                        ),
 978                )
 979                .child(
 980                    Label::new(SharedString::new_static(setting_item.description))
 981                        .size(LabelSize::Small)
 982                        .color(Color::Muted),
 983                ),
 984        )
 985        .child(control)
 986}
 987
 988struct SettingItem {
 989    title: &'static str,
 990    description: &'static str,
 991    field: Box<dyn AnySettingField>,
 992    metadata: Option<Box<SettingsFieldMetadata>>,
 993    files: FileMask,
 994}
 995
 996struct DynamicItem {
 997    discriminant: SettingItem,
 998    pick_discriminant: fn(&SettingsContent) -> Option<usize>,
 999    fields: Vec<Vec<SettingItem>>,
1000}
1001
1002impl PartialEq for DynamicItem {
1003    fn eq(&self, other: &Self) -> bool {
1004        self.discriminant == other.discriminant && self.fields == other.fields
1005    }
1006}
1007
1008#[derive(PartialEq, Eq, Clone, Copy)]
1009struct FileMask(u8);
1010
1011impl std::fmt::Debug for FileMask {
1012    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1013        write!(f, "FileMask(")?;
1014        let mut items = vec![];
1015
1016        if self.contains(USER) {
1017            items.push("USER");
1018        }
1019        if self.contains(LOCAL) {
1020            items.push("LOCAL");
1021        }
1022        if self.contains(SERVER) {
1023            items.push("SERVER");
1024        }
1025
1026        write!(f, "{})", items.join(" | "))
1027    }
1028}
1029
1030const USER: FileMask = FileMask(1 << 0);
1031const LOCAL: FileMask = FileMask(1 << 2);
1032const SERVER: FileMask = FileMask(1 << 3);
1033
1034impl std::ops::BitAnd for FileMask {
1035    type Output = Self;
1036
1037    fn bitand(self, other: Self) -> Self {
1038        Self(self.0 & other.0)
1039    }
1040}
1041
1042impl std::ops::BitOr for FileMask {
1043    type Output = Self;
1044
1045    fn bitor(self, other: Self) -> Self {
1046        Self(self.0 | other.0)
1047    }
1048}
1049
1050impl FileMask {
1051    fn contains(&self, other: FileMask) -> bool {
1052        self.0 & other.0 != 0
1053    }
1054}
1055
1056impl PartialEq for SettingItem {
1057    fn eq(&self, other: &Self) -> bool {
1058        self.title == other.title
1059            && self.description == other.description
1060            && (match (&self.metadata, &other.metadata) {
1061                (None, None) => true,
1062                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1063                _ => false,
1064            })
1065    }
1066}
1067
1068#[derive(Clone)]
1069struct SubPageLink {
1070    title: SharedString,
1071    files: FileMask,
1072    render: Arc<
1073        dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
1074            + 'static
1075            + Send
1076            + Sync,
1077    >,
1078}
1079
1080impl PartialEq for SubPageLink {
1081    fn eq(&self, other: &Self) -> bool {
1082        self.title == other.title
1083    }
1084}
1085
1086fn all_language_names(cx: &App) -> Vec<SharedString> {
1087    workspace::AppState::global(cx)
1088        .upgrade()
1089        .map_or(vec![], |state| {
1090            state
1091                .languages
1092                .language_names()
1093                .into_iter()
1094                .filter(|name| name.as_ref() != "Zed Keybind Context")
1095                .map(Into::into)
1096                .collect()
1097        })
1098}
1099
1100#[allow(unused)]
1101#[derive(Clone, PartialEq)]
1102enum SettingsUiFile {
1103    User,                                // Uses all settings.
1104    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1105    Server(&'static str),                // Uses a special name, and the user settings
1106}
1107
1108impl SettingsUiFile {
1109    fn is_server(&self) -> bool {
1110        matches!(self, SettingsUiFile::Server(_))
1111    }
1112
1113    fn worktree_id(&self) -> Option<WorktreeId> {
1114        match self {
1115            SettingsUiFile::User => None,
1116            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1117            SettingsUiFile::Server(_) => None,
1118        }
1119    }
1120
1121    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1122        Some(match file {
1123            settings::SettingsFile::User => SettingsUiFile::User,
1124            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1125            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1126            settings::SettingsFile::Default => return None,
1127        })
1128    }
1129
1130    fn to_settings(&self) -> settings::SettingsFile {
1131        match self {
1132            SettingsUiFile::User => settings::SettingsFile::User,
1133            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1134            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1135        }
1136    }
1137
1138    fn mask(&self) -> FileMask {
1139        match self {
1140            SettingsUiFile::User => USER,
1141            SettingsUiFile::Project(_) => LOCAL,
1142            SettingsUiFile::Server(_) => SERVER,
1143        }
1144    }
1145}
1146
1147impl SettingsWindow {
1148    pub fn new(
1149        original_window: Option<WindowHandle<Workspace>>,
1150        window: &mut Window,
1151        cx: &mut Context<Self>,
1152    ) -> Self {
1153        let font_family_cache = theme::FontFamilyCache::global(cx);
1154
1155        cx.spawn(async move |this, cx| {
1156            font_family_cache.prefetch(cx).await;
1157            this.update(cx, |_, cx| {
1158                cx.notify();
1159            })
1160        })
1161        .detach();
1162
1163        let current_file = SettingsUiFile::User;
1164        let search_bar = cx.new(|cx| {
1165            let mut editor = Editor::single_line(window, cx);
1166            editor.set_placeholder_text("Search settings…", window, cx);
1167            editor
1168        });
1169
1170        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1171            let EditorEvent::Edited { transaction_id: _ } = event else {
1172                return;
1173            };
1174
1175            this.update_matches(cx);
1176        })
1177        .detach();
1178
1179        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1180            this.fetch_files(window, cx);
1181            cx.notify();
1182        })
1183        .detach();
1184
1185        let title_bar = if !cfg!(target_os = "macos") {
1186            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1187        } else {
1188            None
1189        };
1190
1191        // high overdraw value so the list scrollbar len doesn't change too much
1192        let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1193        list_state.set_scroll_handler(|_, _, _| {});
1194
1195        let mut this = Self {
1196            title_bar,
1197            original_window,
1198
1199            worktree_root_dirs: HashMap::default(),
1200            files: vec![],
1201            drop_down_file: None,
1202            current_file: current_file,
1203            pages: vec![],
1204            navbar_entries: vec![],
1205            navbar_entry: 0,
1206            navbar_scroll_handle: UniformListScrollHandle::default(),
1207            search_bar,
1208            search_task: None,
1209            filter_table: vec![],
1210            has_query: false,
1211            content_handles: vec![],
1212            sub_page_scroll_handle: ScrollHandle::new(),
1213            focus_handle: cx.focus_handle(),
1214            navbar_focus_handle: NonFocusableHandle::new(
1215                NAVBAR_CONTAINER_TAB_INDEX,
1216                false,
1217                window,
1218                cx,
1219            ),
1220            navbar_focus_subscriptions: vec![],
1221            content_focus_handle: NonFocusableHandle::new(
1222                CONTENT_CONTAINER_TAB_INDEX,
1223                false,
1224                window,
1225                cx,
1226            ),
1227            files_focus_handle: cx
1228                .focus_handle()
1229                .tab_index(HEADER_CONTAINER_TAB_INDEX)
1230                .tab_stop(false),
1231            search_index: None,
1232            list_state,
1233        };
1234
1235        this.observe_last_window_close(cx);
1236
1237        this.fetch_files(window, cx);
1238        this.build_ui(window, cx);
1239        this.build_search_index();
1240
1241        this.search_bar.update(cx, |editor, cx| {
1242            editor.focus_handle(cx).focus(window);
1243        });
1244
1245        this
1246    }
1247
1248    fn observe_last_window_close(&mut self, cx: &mut App) {
1249        cx.on_window_closed(|cx| {
1250            if let Some(existing_window) = cx
1251                .windows()
1252                .into_iter()
1253                .find_map(|window| window.downcast::<SettingsWindow>())
1254                && cx.windows().len() == 1
1255            {
1256                cx.update_window(*existing_window, |_, window, _| {
1257                    window.remove_window();
1258                })
1259                .ok();
1260            }
1261        })
1262        .detach();
1263    }
1264
1265    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1266        // We can only toggle root entries
1267        if !self.navbar_entries[nav_entry_index].is_root {
1268            return;
1269        }
1270
1271        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1272        *expanded = !*expanded;
1273        self.navbar_entry = nav_entry_index;
1274        self.reset_list_state();
1275    }
1276
1277    fn build_navbar(&mut self, cx: &App) {
1278        let mut navbar_entries = Vec::new();
1279
1280        for (page_index, page) in self.pages.iter().enumerate() {
1281            navbar_entries.push(NavBarEntry {
1282                title: page.title,
1283                is_root: true,
1284                expanded: false,
1285                page_index,
1286                item_index: None,
1287                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1288            });
1289
1290            for (item_index, item) in page.items.iter().enumerate() {
1291                let SettingsPageItem::SectionHeader(title) = item else {
1292                    continue;
1293                };
1294                navbar_entries.push(NavBarEntry {
1295                    title,
1296                    is_root: false,
1297                    expanded: false,
1298                    page_index,
1299                    item_index: Some(item_index),
1300                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1301                });
1302            }
1303        }
1304
1305        self.navbar_entries = navbar_entries;
1306    }
1307
1308    fn setup_navbar_focus_subscriptions(
1309        &mut self,
1310        window: &mut Window,
1311        cx: &mut Context<SettingsWindow>,
1312    ) {
1313        let mut focus_subscriptions = Vec::new();
1314
1315        for entry_index in 0..self.navbar_entries.len() {
1316            let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1317
1318            let subscription = cx.on_focus(
1319                &focus_handle,
1320                window,
1321                move |this: &mut SettingsWindow,
1322                      window: &mut Window,
1323                      cx: &mut Context<SettingsWindow>| {
1324                    this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1325                },
1326            );
1327            focus_subscriptions.push(subscription);
1328        }
1329        self.navbar_focus_subscriptions = focus_subscriptions;
1330    }
1331
1332    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1333        let mut index = 0;
1334        let entries = &self.navbar_entries;
1335        let search_matches = &self.filter_table;
1336        let has_query = self.has_query;
1337        std::iter::from_fn(move || {
1338            while index < entries.len() {
1339                let entry = &entries[index];
1340                let included_in_search = if let Some(item_index) = entry.item_index {
1341                    search_matches[entry.page_index][item_index]
1342                } else {
1343                    search_matches[entry.page_index].iter().any(|b| *b)
1344                        || search_matches[entry.page_index].is_empty()
1345                };
1346                if included_in_search {
1347                    break;
1348                }
1349                index += 1;
1350            }
1351            if index >= self.navbar_entries.len() {
1352                return None;
1353            }
1354            let entry = &entries[index];
1355            let entry_index = index;
1356
1357            index += 1;
1358            if entry.is_root && !entry.expanded && !has_query {
1359                while index < entries.len() {
1360                    if entries[index].is_root {
1361                        break;
1362                    }
1363                    index += 1;
1364                }
1365            }
1366
1367            return Some((entry_index, entry));
1368        })
1369    }
1370
1371    fn filter_matches_to_file(&mut self) {
1372        let current_file = self.current_file.mask();
1373        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1374            let mut header_index = 0;
1375            let mut any_found_since_last_header = true;
1376
1377            for (index, item) in page.items.iter().enumerate() {
1378                match item {
1379                    SettingsPageItem::SectionHeader(_) => {
1380                        if !any_found_since_last_header {
1381                            page_filter[header_index] = false;
1382                        }
1383                        header_index = index;
1384                        any_found_since_last_header = false;
1385                    }
1386                    SettingsPageItem::SettingItem(SettingItem { files, .. })
1387                    | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1388                    | SettingsPageItem::DynamicItem(DynamicItem {
1389                        discriminant: SettingItem { files, .. },
1390                        ..
1391                    }) => {
1392                        if !files.contains(current_file) {
1393                            page_filter[index] = false;
1394                        } else {
1395                            any_found_since_last_header = true;
1396                        }
1397                    }
1398                }
1399            }
1400            if let Some(last_header) = page_filter.get_mut(header_index)
1401                && !any_found_since_last_header
1402            {
1403                *last_header = false;
1404            }
1405        }
1406    }
1407
1408    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1409        self.search_task.take();
1410        let query = self.search_bar.read(cx).text(cx);
1411        if query.is_empty() || self.search_index.is_none() {
1412            for page in &mut self.filter_table {
1413                page.fill(true);
1414            }
1415            self.has_query = false;
1416            self.filter_matches_to_file();
1417            self.reset_list_state();
1418            cx.notify();
1419            return;
1420        }
1421
1422        let search_index = self.search_index.as_ref().unwrap().clone();
1423
1424        fn update_matches_inner(
1425            this: &mut SettingsWindow,
1426            search_index: &SearchIndex,
1427            match_indices: impl Iterator<Item = usize>,
1428            cx: &mut Context<SettingsWindow>,
1429        ) {
1430            for page in &mut this.filter_table {
1431                page.fill(false);
1432            }
1433
1434            for match_index in match_indices {
1435                let SearchItemKey {
1436                    page_index,
1437                    header_index,
1438                    item_index,
1439                } = search_index.key_lut[match_index];
1440                let page = &mut this.filter_table[page_index];
1441                page[header_index] = true;
1442                page[item_index] = true;
1443            }
1444            this.has_query = true;
1445            this.filter_matches_to_file();
1446            this.open_first_nav_page();
1447            this.reset_list_state();
1448            cx.notify();
1449        }
1450
1451        self.search_task = Some(cx.spawn(async move |this, cx| {
1452            let bm25_task = cx.background_spawn({
1453                let search_index = search_index.clone();
1454                let max_results = search_index.key_lut.len();
1455                let query = query.clone();
1456                async move { search_index.bm25_engine.search(&query, max_results) }
1457            });
1458            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1459            let fuzzy_search_task = fuzzy::match_strings(
1460                search_index.fuzzy_match_candidates.as_slice(),
1461                &query,
1462                false,
1463                true,
1464                search_index.fuzzy_match_candidates.len(),
1465                &cancel_flag,
1466                cx.background_executor().clone(),
1467            );
1468
1469            let fuzzy_matches = fuzzy_search_task.await;
1470
1471            _ = this
1472                .update(cx, |this, cx| {
1473                    // For tuning the score threshold
1474                    // for fuzzy_match in &fuzzy_matches {
1475                    //     let SearchItemKey {
1476                    //         page_index,
1477                    //         header_index,
1478                    //         item_index,
1479                    //     } = search_index.key_lut[fuzzy_match.candidate_id];
1480                    //     let SettingsPageItem::SectionHeader(header) =
1481                    //         this.pages[page_index].items[header_index]
1482                    //     else {
1483                    //         continue;
1484                    //     };
1485                    //     let SettingsPageItem::SettingItem(SettingItem {
1486                    //         title, description, ..
1487                    //     }) = this.pages[page_index].items[item_index]
1488                    //     else {
1489                    //         continue;
1490                    //     };
1491                    //     let score = fuzzy_match.score;
1492                    //     eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1493                    // }
1494                    update_matches_inner(
1495                        this,
1496                        search_index.as_ref(),
1497                        fuzzy_matches
1498                            .into_iter()
1499                            // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1500                            // flexible enough to catch misspellings and <4 letter queries
1501                            // More flexible is good for us here because fuzzy matches will only be used for things that don't
1502                            // match using bm25
1503                            .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1504                            .map(|fuzzy_match| fuzzy_match.candidate_id),
1505                        cx,
1506                    );
1507                })
1508                .ok();
1509
1510            let bm25_matches = bm25_task.await;
1511
1512            _ = this
1513                .update(cx, |this, cx| {
1514                    if bm25_matches.is_empty() {
1515                        return;
1516                    }
1517                    update_matches_inner(
1518                        this,
1519                        search_index.as_ref(),
1520                        bm25_matches
1521                            .into_iter()
1522                            .map(|bm25_match| bm25_match.document.id),
1523                        cx,
1524                    );
1525                })
1526                .ok();
1527        }));
1528    }
1529
1530    fn build_filter_table(&mut self) {
1531        self.filter_table = self
1532            .pages
1533            .iter()
1534            .map(|page| vec![true; page.items.len()])
1535            .collect::<Vec<_>>();
1536    }
1537
1538    fn build_search_index(&mut self) {
1539        let mut key_lut: Vec<SearchItemKey> = vec![];
1540        let mut documents = Vec::default();
1541        let mut fuzzy_match_candidates = Vec::default();
1542
1543        fn push_candidates(
1544            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1545            key_index: usize,
1546            input: &str,
1547        ) {
1548            for word in input.split_ascii_whitespace() {
1549                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1550            }
1551        }
1552
1553        // PERF: We are currently searching all items even in project files
1554        // where many settings are filtered out, using the logic in filter_matches_to_file
1555        // we could only search relevant items based on the current file
1556        for (page_index, page) in self.pages.iter().enumerate() {
1557            let mut header_index = 0;
1558            let mut header_str = "";
1559            for (item_index, item) in page.items.iter().enumerate() {
1560                let key_index = key_lut.len();
1561                match item {
1562                    SettingsPageItem::DynamicItem(DynamicItem {
1563                        discriminant: item, ..
1564                    })
1565                    | SettingsPageItem::SettingItem(item) => {
1566                        documents.push(bm25::Document {
1567                            id: key_index,
1568                            contents: [page.title, header_str, item.title, item.description]
1569                                .join("\n"),
1570                        });
1571                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1572                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1573                    }
1574                    SettingsPageItem::SectionHeader(header) => {
1575                        documents.push(bm25::Document {
1576                            id: key_index,
1577                            contents: header.to_string(),
1578                        });
1579                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
1580                        header_index = item_index;
1581                        header_str = *header;
1582                    }
1583                    SettingsPageItem::SubPageLink(sub_page_link) => {
1584                        documents.push(bm25::Document {
1585                            id: key_index,
1586                            contents: [page.title, header_str, sub_page_link.title.as_ref()]
1587                                .join("\n"),
1588                        });
1589                        push_candidates(
1590                            &mut fuzzy_match_candidates,
1591                            key_index,
1592                            sub_page_link.title.as_ref(),
1593                        );
1594                    }
1595                }
1596                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1597                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1598
1599                key_lut.push(SearchItemKey {
1600                    page_index,
1601                    header_index,
1602                    item_index,
1603                });
1604            }
1605        }
1606        let engine =
1607            bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1608        self.search_index = Some(Arc::new(SearchIndex {
1609            bm25_engine: engine,
1610            key_lut,
1611            fuzzy_match_candidates,
1612        }));
1613    }
1614
1615    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1616        self.content_handles = self
1617            .pages
1618            .iter()
1619            .map(|page| {
1620                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1621                    .take(page.items.len())
1622                    .collect()
1623            })
1624            .collect::<Vec<_>>();
1625    }
1626
1627    fn reset_list_state(&mut self) {
1628        // plus one for the title
1629        let mut visible_items_count = self.visible_page_items().count();
1630
1631        if visible_items_count > 0 {
1632            // show page title if page is non empty
1633            visible_items_count += 1;
1634        }
1635
1636        self.list_state.reset(visible_items_count);
1637    }
1638
1639    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1640        if self.pages.is_empty() {
1641            self.pages = page_data::settings_data(cx);
1642            self.build_navbar(cx);
1643            self.setup_navbar_focus_subscriptions(window, cx);
1644            self.build_content_handles(window, cx);
1645        }
1646        sub_page_stack_mut().clear();
1647        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1648        self.build_filter_table();
1649        self.reset_list_state();
1650        self.update_matches(cx);
1651
1652        cx.notify();
1653    }
1654
1655    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1656        self.worktree_root_dirs.clear();
1657        let prev_files = self.files.clone();
1658        let settings_store = cx.global::<SettingsStore>();
1659        let mut ui_files = vec![];
1660        let all_files = settings_store.get_all_files();
1661        for file in all_files {
1662            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1663                continue;
1664            };
1665            if settings_ui_file.is_server() {
1666                continue;
1667            }
1668
1669            if let Some(worktree_id) = settings_ui_file.worktree_id() {
1670                let directory_name = all_projects(cx)
1671                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1672                    .and_then(|worktree| worktree.read(cx).root_dir())
1673                    .and_then(|root_dir| {
1674                        root_dir
1675                            .file_name()
1676                            .map(|os_string| os_string.to_string_lossy().to_string())
1677                    });
1678
1679                let Some(directory_name) = directory_name else {
1680                    log::error!(
1681                        "No directory name found for settings file at worktree ID: {}",
1682                        worktree_id
1683                    );
1684                    continue;
1685                };
1686
1687                self.worktree_root_dirs.insert(worktree_id, directory_name);
1688            }
1689
1690            let focus_handle = prev_files
1691                .iter()
1692                .find_map(|(prev_file, handle)| {
1693                    (prev_file == &settings_ui_file).then(|| handle.clone())
1694                })
1695                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1696            ui_files.push((settings_ui_file, focus_handle));
1697        }
1698        ui_files.reverse();
1699        self.files = ui_files;
1700        let current_file_still_exists = self
1701            .files
1702            .iter()
1703            .any(|(file, _)| file == &self.current_file);
1704        if !current_file_still_exists {
1705            self.change_file(0, false, window, cx);
1706        }
1707    }
1708
1709    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1710        if !self.is_nav_entry_visible(navbar_entry) {
1711            self.open_first_nav_page();
1712        }
1713
1714        let is_new_page = self.navbar_entries[self.navbar_entry].page_index
1715            != self.navbar_entries[navbar_entry].page_index;
1716        self.navbar_entry = navbar_entry;
1717
1718        // We only need to reset visible items when updating matches
1719        // and selecting a new page
1720        if is_new_page {
1721            self.reset_list_state();
1722        }
1723
1724        sub_page_stack_mut().clear();
1725    }
1726
1727    fn open_first_nav_page(&mut self) {
1728        let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
1729        else {
1730            return;
1731        };
1732        self.open_navbar_entry_page(first_navbar_entry_index);
1733    }
1734
1735    fn change_file(
1736        &mut self,
1737        ix: usize,
1738        drop_down_file: bool,
1739        window: &mut Window,
1740        cx: &mut Context<SettingsWindow>,
1741    ) {
1742        if ix >= self.files.len() {
1743            self.current_file = SettingsUiFile::User;
1744            self.build_ui(window, cx);
1745            return;
1746        }
1747        if drop_down_file {
1748            self.drop_down_file = Some(ix);
1749        }
1750
1751        if self.files[ix].0 == self.current_file {
1752            return;
1753        }
1754        self.current_file = self.files[ix].0.clone();
1755
1756        self.build_ui(window, cx);
1757
1758        if self
1759            .visible_navbar_entries()
1760            .any(|(index, _)| index == self.navbar_entry)
1761        {
1762            self.open_and_scroll_to_navbar_entry(self.navbar_entry, None, true, window, cx);
1763        } else {
1764            self.open_first_nav_page();
1765        };
1766    }
1767
1768    fn render_files_header(
1769        &self,
1770        window: &mut Window,
1771        cx: &mut Context<SettingsWindow>,
1772    ) -> impl IntoElement {
1773        const OVERFLOW_LIMIT: usize = 1;
1774
1775        let file_button =
1776            |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
1777                Button::new(
1778                    ix,
1779                    self.display_name(&file)
1780                        .expect("Files should always have a name"),
1781                )
1782                .toggle_state(file == &self.current_file)
1783                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1784                .track_focus(focus_handle)
1785                .on_click(cx.listener({
1786                    let focus_handle = focus_handle.clone();
1787                    move |this, _: &gpui::ClickEvent, window, cx| {
1788                        this.change_file(ix, false, window, cx);
1789                        focus_handle.focus(window);
1790                    }
1791                }))
1792            };
1793
1794        let this = cx.entity();
1795
1796        h_flex()
1797            .w_full()
1798            .pb_4()
1799            .gap_1()
1800            .justify_between()
1801            .track_focus(&self.files_focus_handle)
1802            .tab_group()
1803            .tab_index(HEADER_GROUP_TAB_INDEX)
1804            .child(
1805                h_flex()
1806                    .gap_1()
1807                    .children(
1808                        self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
1809                            |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
1810                        ),
1811                    )
1812                    .when(self.files.len() > OVERFLOW_LIMIT, |div| {
1813                        div.children(
1814                            self.files
1815                                .iter()
1816                                .enumerate()
1817                                .skip(OVERFLOW_LIMIT)
1818                                .find(|(_, (file, _))| file == &self.current_file)
1819                                .map(|(ix, (file, focus_handle))| {
1820                                    file_button(ix, file, focus_handle, cx)
1821                                })
1822                                .or_else(|| {
1823                                    let ix = self.drop_down_file.unwrap_or(OVERFLOW_LIMIT);
1824                                    self.files.get(ix).map(|(file, focus_handle)| {
1825                                        file_button(ix, file, focus_handle, cx)
1826                                    })
1827                                }),
1828                        )
1829                        .when(
1830                            self.files.len() > OVERFLOW_LIMIT + 1,
1831                            |div| {
1832                                div.child(
1833                                    DropdownMenu::new(
1834                                        "more-files",
1835                                        format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
1836                                        ContextMenu::build(window, cx, move |mut menu, _, _| {
1837                                            for (mut ix, (file, focus_handle)) in self
1838                                                .files
1839                                                .iter()
1840                                                .enumerate()
1841                                                .skip(OVERFLOW_LIMIT + 1)
1842                                            {
1843                                                let (display_name, focus_handle) = if self
1844                                                    .drop_down_file
1845                                                    .is_some_and(|drop_down_ix| drop_down_ix == ix)
1846                                                {
1847                                                    ix = OVERFLOW_LIMIT;
1848                                                    (
1849                                                        self.display_name(&self.files[ix].0),
1850                                                        self.files[ix].1.clone(),
1851                                                    )
1852                                                } else {
1853                                                    (self.display_name(&file), focus_handle.clone())
1854                                                };
1855
1856                                                menu = menu.entry(
1857                                                    display_name
1858                                                        .expect("Files should always have a name"),
1859                                                    None,
1860                                                    {
1861                                                        let this = this.clone();
1862                                                        move |window, cx| {
1863                                                            this.update(cx, |this, cx| {
1864                                                                this.change_file(
1865                                                                    ix, true, window, cx,
1866                                                                );
1867                                                            });
1868                                                            focus_handle.focus(window);
1869                                                        }
1870                                                    },
1871                                                );
1872                                            }
1873
1874                                            menu
1875                                        }),
1876                                    )
1877                                    .style(DropdownStyle::Subtle)
1878                                    .trigger_tooltip(Tooltip::text("View Other Projects"))
1879                                    .trigger_icon(IconName::ChevronDown)
1880                                    .attach(gpui::Corner::BottomLeft)
1881                                    .offset(gpui::Point {
1882                                        x: px(0.0),
1883                                        y: px(2.0),
1884                                    })
1885                                    .tab_index(0),
1886                                )
1887                            },
1888                        )
1889                    }),
1890            )
1891            .child(
1892                Button::new("edit-in-json", "Edit in settings.json")
1893                    .tab_index(0_isize)
1894                    .style(ButtonStyle::OutlinedGhost)
1895                    .on_click(cx.listener(|this, _, _, cx| {
1896                        this.open_current_settings_file(cx);
1897                    })),
1898            )
1899    }
1900
1901    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1902        match file {
1903            SettingsUiFile::User => Some("User".to_string()),
1904            SettingsUiFile::Project((worktree_id, path)) => self
1905                .worktree_root_dirs
1906                .get(&worktree_id)
1907                .map(|directory_name| {
1908                    let path_style = PathStyle::local();
1909                    if path.is_empty() {
1910                        directory_name.clone()
1911                    } else {
1912                        format!(
1913                            "{}{}{}",
1914                            directory_name,
1915                            path_style.separator(),
1916                            path.display(path_style)
1917                        )
1918                    }
1919                }),
1920            SettingsUiFile::Server(file) => Some(file.to_string()),
1921        }
1922    }
1923
1924    // TODO:
1925    //  Reconsider this after preview launch
1926    // fn file_location_str(&self) -> String {
1927    //     match &self.current_file {
1928    //         SettingsUiFile::User => "settings.json".to_string(),
1929    //         SettingsUiFile::Project((worktree_id, path)) => self
1930    //             .worktree_root_dirs
1931    //             .get(&worktree_id)
1932    //             .map(|directory_name| {
1933    //                 let path_style = PathStyle::local();
1934    //                 let file_path = path.join(paths::local_settings_file_relative_path());
1935    //                 format!(
1936    //                     "{}{}{}",
1937    //                     directory_name,
1938    //                     path_style.separator(),
1939    //                     file_path.display(path_style)
1940    //                 )
1941    //             })
1942    //             .expect("Current file should always be present in root dir map"),
1943    //         SettingsUiFile::Server(file) => file.to_string(),
1944    //     }
1945    // }
1946
1947    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1948        h_flex()
1949            .py_1()
1950            .px_1p5()
1951            .mb_3()
1952            .gap_1p5()
1953            .rounded_sm()
1954            .bg(cx.theme().colors().editor_background)
1955            .border_1()
1956            .border_color(cx.theme().colors().border)
1957            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1958            .child(self.search_bar.clone())
1959    }
1960
1961    fn render_nav(
1962        &self,
1963        window: &mut Window,
1964        cx: &mut Context<SettingsWindow>,
1965    ) -> impl IntoElement {
1966        let visible_count = self.visible_navbar_entries().count();
1967
1968        let focus_keybind_label = if self
1969            .navbar_focus_handle
1970            .read(cx)
1971            .handle
1972            .contains_focused(window, cx)
1973            || self
1974                .visible_navbar_entries()
1975                .any(|(_, entry)| entry.focus_handle.is_focused(window))
1976        {
1977            "Focus Content"
1978        } else {
1979            "Focus Navbar"
1980        };
1981
1982        v_flex()
1983            .key_context("NavigationMenu")
1984            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1985                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1986                    return;
1987                };
1988                let focused_entry_parent = this.root_entry_containing(focused_entry);
1989                if this.navbar_entries[focused_entry_parent].expanded {
1990                    this.toggle_navbar_entry(focused_entry_parent);
1991                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1992                }
1993                cx.notify();
1994            }))
1995            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1996                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1997                    return;
1998                };
1999                if !this.navbar_entries[focused_entry].is_root {
2000                    return;
2001                }
2002                if !this.navbar_entries[focused_entry].expanded {
2003                    this.toggle_navbar_entry(focused_entry);
2004                }
2005                cx.notify();
2006            }))
2007            .on_action(
2008                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2009                    let entry_index = this
2010                        .focused_nav_entry(window, cx)
2011                        .unwrap_or(this.navbar_entry);
2012                    let mut root_index = None;
2013                    for (index, entry) in this.visible_navbar_entries() {
2014                        if index >= entry_index {
2015                            break;
2016                        }
2017                        if entry.is_root {
2018                            root_index = Some(index);
2019                        }
2020                    }
2021                    let Some(previous_root_index) = root_index else {
2022                        return;
2023                    };
2024                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2025                }),
2026            )
2027            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2028                let entry_index = this
2029                    .focused_nav_entry(window, cx)
2030                    .unwrap_or(this.navbar_entry);
2031                let mut root_index = None;
2032                for (index, entry) in this.visible_navbar_entries() {
2033                    if index <= entry_index {
2034                        continue;
2035                    }
2036                    if entry.is_root {
2037                        root_index = Some(index);
2038                        break;
2039                    }
2040                }
2041                let Some(next_root_index) = root_index else {
2042                    return;
2043                };
2044                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2045            }))
2046            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2047                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2048                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2049                }
2050            }))
2051            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2052                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2053                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2054                }
2055            }))
2056            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2057                let entry_index = this
2058                    .focused_nav_entry(window, cx)
2059                    .unwrap_or(this.navbar_entry);
2060                let mut next_index = None;
2061                for (index, _) in this.visible_navbar_entries() {
2062                    if index > entry_index {
2063                        next_index = Some(index);
2064                        break;
2065                    }
2066                }
2067                let Some(next_entry_index) = next_index else {
2068                    return;
2069                };
2070                this.open_and_scroll_to_navbar_entry(
2071                    next_entry_index,
2072                    Some(gpui::ScrollStrategy::Bottom),
2073                    false,
2074                    window,
2075                    cx,
2076                );
2077            }))
2078            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2079                let entry_index = this
2080                    .focused_nav_entry(window, cx)
2081                    .unwrap_or(this.navbar_entry);
2082                let mut prev_index = None;
2083                for (index, _) in this.visible_navbar_entries() {
2084                    if index >= entry_index {
2085                        break;
2086                    }
2087                    prev_index = Some(index);
2088                }
2089                let Some(prev_entry_index) = prev_index else {
2090                    return;
2091                };
2092                this.open_and_scroll_to_navbar_entry(
2093                    prev_entry_index,
2094                    Some(gpui::ScrollStrategy::Top),
2095                    false,
2096                    window,
2097                    cx,
2098                );
2099            }))
2100            .w_56()
2101            .h_full()
2102            .p_2p5()
2103            .when(cfg!(target_os = "macos"), |this| this.pt_10())
2104            .flex_none()
2105            .border_r_1()
2106            .border_color(cx.theme().colors().border)
2107            .bg(cx.theme().colors().panel_background)
2108            .child(self.render_search(window, cx))
2109            .child(
2110                v_flex()
2111                    .flex_1()
2112                    .overflow_hidden()
2113                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2114                    .tab_group()
2115                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
2116                    .child(
2117                        uniform_list(
2118                            "settings-ui-nav-bar",
2119                            visible_count + 1,
2120                            cx.processor(move |this, range: Range<usize>, _, cx| {
2121                                this.visible_navbar_entries()
2122                                    .skip(range.start.saturating_sub(1))
2123                                    .take(range.len())
2124                                    .map(|(entry_index, entry)| {
2125                                        TreeViewItem::new(
2126                                            ("settings-ui-navbar-entry", entry_index),
2127                                            entry.title,
2128                                        )
2129                                        .track_focus(&entry.focus_handle)
2130                                        .root_item(entry.is_root)
2131                                        .toggle_state(this.is_navbar_entry_selected(entry_index))
2132                                        .when(entry.is_root, |item| {
2133                                            item.expanded(entry.expanded || this.has_query)
2134                                                .on_toggle(cx.listener(
2135                                                    move |this, _, window, cx| {
2136                                                        this.toggle_navbar_entry(entry_index);
2137                                                        window.focus(
2138                                                            &this.navbar_entries[entry_index]
2139                                                                .focus_handle,
2140                                                        );
2141                                                        cx.notify();
2142                                                    },
2143                                                ))
2144                                        })
2145                                        .on_click(
2146                                            cx.listener(move |this, _, window, cx| {
2147                                                this.open_and_scroll_to_navbar_entry(
2148                                                    entry_index,
2149                                                    None,
2150                                                    true,
2151                                                    window,
2152                                                    cx,
2153                                                );
2154                                            }),
2155                                        )
2156                                    })
2157                                    .collect()
2158                            }),
2159                        )
2160                        .size_full()
2161                        .track_scroll(self.navbar_scroll_handle.clone()),
2162                    )
2163                    .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
2164            )
2165            .child(
2166                h_flex()
2167                    .w_full()
2168                    .h_8()
2169                    .p_2()
2170                    .pb_0p5()
2171                    .flex_shrink_0()
2172                    .border_t_1()
2173                    .border_color(cx.theme().colors().border_variant)
2174                    .child(
2175                        KeybindingHint::new(
2176                            KeyBinding::for_action_in(
2177                                &ToggleFocusNav,
2178                                &self.navbar_focus_handle.focus_handle(cx),
2179                                cx,
2180                            ),
2181                            cx.theme().colors().surface_background.opacity(0.5),
2182                        )
2183                        .suffix(focus_keybind_label),
2184                    ),
2185            )
2186    }
2187
2188    fn open_and_scroll_to_navbar_entry(
2189        &mut self,
2190        navbar_entry_index: usize,
2191        scroll_strategy: Option<gpui::ScrollStrategy>,
2192        focus_content: bool,
2193        window: &mut Window,
2194        cx: &mut Context<Self>,
2195    ) {
2196        self.open_navbar_entry_page(navbar_entry_index);
2197        cx.notify();
2198
2199        let mut handle_to_focus = None;
2200
2201        if self.navbar_entries[navbar_entry_index].is_root
2202            || !self.is_nav_entry_visible(navbar_entry_index)
2203        {
2204            self.sub_page_scroll_handle
2205                .set_offset(point(px(0.), px(0.)));
2206            if focus_content {
2207                let Some(first_item_index) =
2208                    self.visible_page_items().next().map(|(index, _)| index)
2209                else {
2210                    return;
2211                };
2212                handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2213            } else if !self.is_nav_entry_visible(navbar_entry_index) {
2214                let Some(first_visible_nav_entry_index) =
2215                    self.visible_navbar_entries().next().map(|(index, _)| index)
2216                else {
2217                    return;
2218                };
2219                self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2220            } else {
2221                handle_to_focus =
2222                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2223            }
2224        } else {
2225            let entry_item_index = self.navbar_entries[navbar_entry_index]
2226                .item_index
2227                .expect("Non-root items should have an item index");
2228            self.scroll_to_content_item(entry_item_index, window, cx);
2229            if focus_content {
2230                handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2231            } else {
2232                handle_to_focus =
2233                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2234            }
2235        }
2236
2237        if let Some(scroll_strategy) = scroll_strategy
2238            && let Some(logical_entry_index) = self
2239                .visible_navbar_entries()
2240                .into_iter()
2241                .position(|(index, _)| index == navbar_entry_index)
2242        {
2243            self.navbar_scroll_handle
2244                .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2245        }
2246
2247        // Page scroll handle updates the active item index
2248        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2249        // The call after that updates the offset of the scroll handle. So to
2250        // ensure the scroll handle doesn't lag behind we need to render three frames
2251        // back to back.
2252        cx.on_next_frame(window, move |_, window, cx| {
2253            if let Some(handle) = handle_to_focus.as_ref() {
2254                window.focus(handle);
2255            }
2256
2257            cx.on_next_frame(window, |_, _, cx| {
2258                cx.notify();
2259            });
2260            cx.notify();
2261        });
2262        cx.notify();
2263    }
2264
2265    fn scroll_to_content_item(
2266        &self,
2267        content_item_index: usize,
2268        _window: &mut Window,
2269        cx: &mut Context<Self>,
2270    ) {
2271        let index = self
2272            .visible_page_items()
2273            .position(|(index, _)| index == content_item_index)
2274            .unwrap_or(0);
2275        if index == 0 {
2276            self.sub_page_scroll_handle
2277                .set_offset(point(px(0.), px(0.)));
2278            self.list_state.scroll_to(gpui::ListOffset {
2279                item_ix: 0,
2280                offset_in_item: px(0.),
2281            });
2282            return;
2283        }
2284        self.list_state.scroll_to(gpui::ListOffset {
2285            item_ix: index + 1,
2286            offset_in_item: px(0.),
2287        });
2288        cx.notify();
2289    }
2290
2291    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2292        self.visible_navbar_entries()
2293            .any(|(index, _)| index == nav_entry_index)
2294    }
2295
2296    fn focus_and_scroll_to_first_visible_nav_entry(
2297        &self,
2298        window: &mut Window,
2299        cx: &mut Context<Self>,
2300    ) {
2301        if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2302        {
2303            self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2304        }
2305    }
2306
2307    fn focus_and_scroll_to_nav_entry(
2308        &self,
2309        nav_entry_index: usize,
2310        window: &mut Window,
2311        cx: &mut Context<Self>,
2312    ) {
2313        let Some(position) = self
2314            .visible_navbar_entries()
2315            .position(|(index, _)| index == nav_entry_index)
2316        else {
2317            return;
2318        };
2319        self.navbar_scroll_handle
2320            .scroll_to_item(position, gpui::ScrollStrategy::Top);
2321        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2322        cx.notify();
2323    }
2324
2325    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2326        let page_idx = self.current_page_index();
2327
2328        self.current_page()
2329            .items
2330            .iter()
2331            .enumerate()
2332            .filter_map(move |(item_index, item)| {
2333                self.filter_table[page_idx][item_index].then_some((item_index, item))
2334            })
2335    }
2336
2337    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2338        let mut items = vec![];
2339        items.push(self.current_page().title.into());
2340        items.extend(
2341            sub_page_stack()
2342                .iter()
2343                .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2344        );
2345
2346        let last = items.pop().unwrap();
2347        h_flex()
2348            .gap_1()
2349            .children(
2350                items
2351                    .into_iter()
2352                    .flat_map(|item| [item, "/".into()])
2353                    .map(|item| Label::new(item).color(Color::Muted)),
2354            )
2355            .child(Label::new(last))
2356    }
2357
2358    fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2359        v_flex()
2360            .size_full()
2361            .items_center()
2362            .justify_center()
2363            .gap_1()
2364            .child(Label::new("No Results"))
2365            .child(
2366                Label::new(search_query)
2367                    .size(LabelSize::Small)
2368                    .color(Color::Muted),
2369            )
2370    }
2371
2372    fn render_page_items(
2373        &mut self,
2374        page_index: usize,
2375        _window: &mut Window,
2376        cx: &mut Context<SettingsWindow>,
2377    ) -> impl IntoElement {
2378        let mut page_content = v_flex().id("settings-ui-page").size_full();
2379
2380        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2381        let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2382
2383        if has_no_results {
2384            let search_query = self.search_bar.read(cx).text(cx);
2385            page_content = page_content.child(
2386                self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2387            )
2388        } else {
2389            let last_non_header_index = self
2390                .visible_page_items()
2391                .filter_map(|(index, item)| {
2392                    (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2393                })
2394                .last();
2395
2396            let root_nav_label = self
2397                .navbar_entries
2398                .iter()
2399                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2400                .map(|entry| entry.title);
2401
2402            let list_content = list(
2403                self.list_state.clone(),
2404                cx.processor(move |this, index, window, cx| {
2405                    if index == 0 {
2406                        return div()
2407                            .when(sub_page_stack().is_empty(), |this| {
2408                                this.when_some(root_nav_label, |this, title| {
2409                                    this.child(
2410                                        Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2411                                    )
2412                                })
2413                            })
2414                            .into_any_element();
2415                    }
2416
2417                    let mut visible_items = this.visible_page_items();
2418                    let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2419                        return gpui::Empty.into_any_element();
2420                    };
2421
2422                    let no_bottom_border = visible_items
2423                        .next()
2424                        .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2425                        .unwrap_or(false);
2426
2427                    let is_last = Some(actual_item_index) == last_non_header_index;
2428
2429                    let item_focus_handle =
2430                        this.content_handles[page_index][actual_item_index].focus_handle(cx);
2431
2432                    v_flex()
2433                        .id(("settings-page-item", actual_item_index))
2434                        .w_full()
2435                        .min_w_0()
2436                        .track_focus(&item_focus_handle)
2437                        .child(item.render(
2438                            this,
2439                            actual_item_index,
2440                            no_bottom_border || is_last,
2441                            window,
2442                            cx,
2443                        ))
2444                        .into_any_element()
2445                }),
2446            );
2447
2448            page_content = page_content.child(list_content.size_full())
2449        }
2450        page_content
2451    }
2452
2453    fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2454        &self,
2455        items: Items,
2456        page_index: Option<usize>,
2457        window: &mut Window,
2458        cx: &mut Context<SettingsWindow>,
2459    ) -> impl IntoElement {
2460        let mut page_content = v_flex()
2461            .id("settings-ui-page")
2462            .size_full()
2463            .overflow_y_scroll()
2464            .track_scroll(&self.sub_page_scroll_handle);
2465
2466        let items: Vec<_> = items.collect();
2467        let items_len = items.len();
2468        let mut section_header = None;
2469
2470        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2471        let has_no_results = items_len == 0 && has_active_search;
2472
2473        if has_no_results {
2474            let search_query = self.search_bar.read(cx).text(cx);
2475            page_content = page_content.child(
2476                self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2477            )
2478        } else {
2479            let last_non_header_index = items
2480                .iter()
2481                .enumerate()
2482                .rev()
2483                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2484                .map(|(index, _)| index);
2485
2486            let root_nav_label = self
2487                .navbar_entries
2488                .iter()
2489                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2490                .map(|entry| entry.title);
2491
2492            page_content = page_content
2493                .when(sub_page_stack().is_empty(), |this| {
2494                    this.when_some(root_nav_label, |this, title| {
2495                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2496                    })
2497                })
2498                .children(items.clone().into_iter().enumerate().map(
2499                    |(index, (actual_item_index, item))| {
2500                        let no_bottom_border = items
2501                            .get(index + 1)
2502                            .map(|(_, next_item)| {
2503                                matches!(next_item, SettingsPageItem::SectionHeader(_))
2504                            })
2505                            .unwrap_or(false);
2506                        let is_last = Some(index) == last_non_header_index;
2507
2508                        if let SettingsPageItem::SectionHeader(header) = item {
2509                            section_header = Some(*header);
2510                        }
2511                        v_flex()
2512                            .w_full()
2513                            .min_w_0()
2514                            .id(("settings-page-item", actual_item_index))
2515                            .when_some(page_index, |element, page_index| {
2516                                element.track_focus(
2517                                    &self.content_handles[page_index][actual_item_index]
2518                                        .focus_handle(cx),
2519                                )
2520                            })
2521                            .child(item.render(
2522                                self,
2523                                actual_item_index,
2524                                no_bottom_border || is_last,
2525                                window,
2526                                cx,
2527                            ))
2528                    },
2529                ))
2530        }
2531        page_content
2532    }
2533
2534    fn render_page(
2535        &mut self,
2536        window: &mut Window,
2537        cx: &mut Context<SettingsWindow>,
2538    ) -> impl IntoElement {
2539        let page_header;
2540        let page_content;
2541
2542        if sub_page_stack().is_empty() {
2543            page_header = self.render_files_header(window, cx).into_any_element();
2544
2545            page_content = self
2546                .render_page_items(self.current_page_index(), window, cx)
2547                .into_any_element();
2548        } else {
2549            page_header = h_flex()
2550                .ml_neg_1p5()
2551                .pb_4()
2552                .gap_1()
2553                .child(
2554                    IconButton::new("back-btn", IconName::ArrowLeft)
2555                        .icon_size(IconSize::Small)
2556                        .shape(IconButtonShape::Square)
2557                        .on_click(cx.listener(|this, _, _, cx| {
2558                            this.pop_sub_page(cx);
2559                        })),
2560                )
2561                .child(self.render_sub_page_breadcrumbs())
2562                .into_any_element();
2563
2564            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2565            page_content = (active_page_render_fn)(self, window, cx);
2566        }
2567
2568        let mut warning_banner = gpui::Empty.into_any_element();
2569        if let Some(error) =
2570            SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2571        {
2572            warning_banner = v_flex()
2573                .pb_4()
2574                .child(
2575                    Banner::new()
2576                        .severity(Severity::Warning)
2577                        .child(
2578                            Label::new("Your Settings File is in an Invalid State. Setting Values May Be Incorrect, and Changes May Be Lost")
2579                                .size(LabelSize::Large),
2580                        )
2581                        .child(Label::new(error).size(LabelSize::Small).color(Color::Muted))
2582                        .action_slot(
2583                            Button::new("fix-in-json", "Fix in settings.json")
2584                                .tab_index(0_isize)
2585                                .style(ButtonStyle::OutlinedGhost)
2586                                .on_click(cx.listener(|this, _, _, cx| {
2587                                    this.open_current_settings_file(cx);
2588                                })),
2589                        ),
2590                )
2591                .into_any_element()
2592        }
2593
2594        return v_flex()
2595            .id("Settings-ui-page")
2596            .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2597                if !sub_page_stack().is_empty() {
2598                    window.focus_next();
2599                    return;
2600                }
2601                for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2602                    let handle = this.content_handles[this.current_page_index()][actual_index]
2603                        .focus_handle(cx);
2604                    let mut offset = 1; // for page header
2605
2606                    if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2607                        && matches!(next_item, SettingsPageItem::SectionHeader(_))
2608                    {
2609                        offset += 1;
2610                    }
2611                    if handle.contains_focused(window, cx) {
2612                        let next_logical_index = logical_index + offset + 1;
2613                        this.list_state.scroll_to_reveal_item(next_logical_index);
2614                        // We need to render the next item to ensure it's focus handle is in the element tree
2615                        cx.on_next_frame(window, |_, window, cx| {
2616                            window.focus_next();
2617                            cx.notify();
2618                        });
2619                        cx.notify();
2620                        return;
2621                    }
2622                }
2623                window.focus_next();
2624            }))
2625            .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2626                if !sub_page_stack().is_empty() {
2627                    window.focus_prev();
2628                    return;
2629                }
2630                let mut prev_was_header = false;
2631                for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
2632                    let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
2633                    let handle = this.content_handles[this.current_page_index()][actual_index]
2634                        .focus_handle(cx);
2635                    let mut offset = 1; // for page header
2636
2637                    if prev_was_header {
2638                        offset -= 1;
2639                    }
2640                    if handle.contains_focused(window, cx) {
2641                        let next_logical_index = logical_index + offset - 1;
2642                        this.list_state.scroll_to_reveal_item(next_logical_index);
2643                        // We need to render the next item to ensure it's focus handle is in the element tree
2644                        cx.on_next_frame(window, |_, window, cx| {
2645                            window.focus_prev();
2646                            cx.notify();
2647                        });
2648                        cx.notify();
2649                        return;
2650                    }
2651                    prev_was_header = is_header;
2652                }
2653                window.focus_prev();
2654            }))
2655            .child(warning_banner)
2656            .child(page_header)
2657            .when(sub_page_stack().is_empty(), |this| {
2658                this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2659            })
2660            .when(!sub_page_stack().is_empty(), |this| {
2661                this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2662            })
2663            .track_focus(&self.content_focus_handle.focus_handle(cx))
2664            .flex_1()
2665            .pt_6()
2666            .px_8()
2667            .bg(cx.theme().colors().editor_background)
2668            .child(
2669                div()
2670                    .size_full()
2671                    .tab_group()
2672                    .tab_index(CONTENT_GROUP_TAB_INDEX)
2673                    .child(page_content),
2674            );
2675    }
2676
2677    fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2678        match &self.current_file {
2679            SettingsUiFile::User => {
2680                let Some(original_window) = self.original_window else {
2681                    return;
2682                };
2683                original_window
2684                    .update(cx, |workspace, window, cx| {
2685                        workspace
2686                            .with_local_workspace(window, cx, |workspace, window, cx| {
2687                                let create_task = workspace.project().update(cx, |project, cx| {
2688                                    project.find_or_create_worktree(
2689                                        paths::config_dir().as_path(),
2690                                        false,
2691                                        cx,
2692                                    )
2693                                });
2694                                let open_task = workspace.open_paths(
2695                                    vec![paths::settings_file().to_path_buf()],
2696                                    OpenOptions {
2697                                        visible: Some(OpenVisible::None),
2698                                        ..Default::default()
2699                                    },
2700                                    None,
2701                                    window,
2702                                    cx,
2703                                );
2704
2705                                cx.spawn_in(window, async move |workspace, cx| {
2706                                    create_task.await.ok();
2707                                    open_task.await;
2708
2709                                    workspace.update_in(cx, |_, window, cx| {
2710                                        window.activate_window();
2711                                        cx.notify();
2712                                    })
2713                                })
2714                                .detach();
2715                            })
2716                            .detach();
2717                    })
2718                    .ok();
2719            }
2720            SettingsUiFile::Project((worktree_id, path)) => {
2721                let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
2722                let settings_path = path.join(paths::local_settings_file_relative_path());
2723                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2724                    return;
2725                };
2726                for workspace in app_state.workspace_store.read(cx).workspaces() {
2727                    let contains_settings_file = workspace
2728                        .read_with(cx, |workspace, cx| {
2729                            workspace.project().read(cx).contains_local_settings_file(
2730                                *worktree_id,
2731                                settings_path.as_ref(),
2732                                cx,
2733                            )
2734                        })
2735                        .ok();
2736                    if Some(true) == contains_settings_file {
2737                        corresponding_workspace = Some(*workspace);
2738
2739                        break;
2740                    }
2741                }
2742
2743                let Some(corresponding_workspace) = corresponding_workspace else {
2744                    log::error!(
2745                        "No corresponding workspace found for settings file {}",
2746                        settings_path.as_std_path().display()
2747                    );
2748
2749                    return;
2750                };
2751
2752                // TODO: move zed::open_local_file() APIs to this crate, and
2753                // re-implement the "initial_contents" behavior
2754                corresponding_workspace
2755                    .update(cx, |workspace, window, cx| {
2756                        let open_task = workspace.open_path(
2757                            (*worktree_id, settings_path.clone()),
2758                            None,
2759                            true,
2760                            window,
2761                            cx,
2762                        );
2763
2764                        cx.spawn_in(window, async move |workspace, cx| {
2765                            if open_task.await.log_err().is_some() {
2766                                workspace
2767                                    .update_in(cx, |_, window, cx| {
2768                                        window.activate_window();
2769                                        cx.notify();
2770                                    })
2771                                    .ok();
2772                            }
2773                        })
2774                        .detach();
2775                    })
2776                    .ok();
2777            }
2778            SettingsUiFile::Server(_) => {
2779                return;
2780            }
2781        };
2782    }
2783
2784    fn current_page_index(&self) -> usize {
2785        self.page_index_from_navbar_index(self.navbar_entry)
2786    }
2787
2788    fn current_page(&self) -> &SettingsPage {
2789        &self.pages[self.current_page_index()]
2790    }
2791
2792    fn page_index_from_navbar_index(&self, index: usize) -> usize {
2793        if self.navbar_entries.is_empty() {
2794            return 0;
2795        }
2796
2797        self.navbar_entries[index].page_index
2798    }
2799
2800    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2801        ix == self.navbar_entry
2802    }
2803
2804    fn push_sub_page(
2805        &mut self,
2806        sub_page_link: SubPageLink,
2807        section_header: &'static str,
2808        cx: &mut Context<SettingsWindow>,
2809    ) {
2810        sub_page_stack_mut().push(SubPage {
2811            link: sub_page_link,
2812            section_header,
2813        });
2814        cx.notify();
2815    }
2816
2817    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
2818        sub_page_stack_mut().pop();
2819        cx.notify();
2820    }
2821
2822    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
2823        if let Some((_, handle)) = self.files.get(index) {
2824            handle.focus(window);
2825        }
2826    }
2827
2828    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
2829        if self.files_focus_handle.contains_focused(window, cx)
2830            && let Some(index) = self
2831                .files
2832                .iter()
2833                .position(|(_, handle)| handle.is_focused(window))
2834        {
2835            return index;
2836        }
2837        if let Some(current_file_index) = self
2838            .files
2839            .iter()
2840            .position(|(file, _)| file == &self.current_file)
2841        {
2842            return current_file_index;
2843        }
2844        0
2845    }
2846
2847    fn focus_handle_for_content_element(
2848        &self,
2849        actual_item_index: usize,
2850        cx: &Context<Self>,
2851    ) -> FocusHandle {
2852        let page_index = self.current_page_index();
2853        self.content_handles[page_index][actual_item_index].focus_handle(cx)
2854    }
2855
2856    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
2857        if !self
2858            .navbar_focus_handle
2859            .focus_handle(cx)
2860            .contains_focused(window, cx)
2861        {
2862            return None;
2863        }
2864        for (index, entry) in self.navbar_entries.iter().enumerate() {
2865            if entry.focus_handle.is_focused(window) {
2866                return Some(index);
2867            }
2868        }
2869        None
2870    }
2871
2872    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
2873        let mut index = Some(nav_entry_index);
2874        while let Some(prev_index) = index
2875            && !self.navbar_entries[prev_index].is_root
2876        {
2877            index = prev_index.checked_sub(1);
2878        }
2879        return index.expect("No root entry found");
2880    }
2881}
2882
2883impl Render for SettingsWindow {
2884    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2885        let ui_font = theme::setup_ui_font(window, cx);
2886
2887        client_side_decorations(
2888            v_flex()
2889                .text_color(cx.theme().colors().text)
2890                .size_full()
2891                .children(self.title_bar.clone())
2892                .child(
2893                    div()
2894                        .id("settings-window")
2895                        .key_context("SettingsWindow")
2896                        .track_focus(&self.focus_handle)
2897                        .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2898                            this.open_current_settings_file(cx);
2899                        }))
2900                        .on_action(|_: &Minimize, window, _cx| {
2901                            window.minimize_window();
2902                        })
2903                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2904                            this.search_bar.focus_handle(cx).focus(window);
2905                        }))
2906                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2907                            if this
2908                                .navbar_focus_handle
2909                                .focus_handle(cx)
2910                                .contains_focused(window, cx)
2911                            {
2912                                this.open_and_scroll_to_navbar_entry(
2913                                    this.navbar_entry,
2914                                    None,
2915                                    true,
2916                                    window,
2917                                    cx,
2918                                );
2919                            } else {
2920                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
2921                            }
2922                        }))
2923                        .on_action(cx.listener(
2924                            |this, FocusFile(file_index): &FocusFile, window, _| {
2925                                this.focus_file_at_index(*file_index as usize, window);
2926                            },
2927                        ))
2928                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2929                            let next_index = usize::min(
2930                                this.focused_file_index(window, cx) + 1,
2931                                this.files.len().saturating_sub(1),
2932                            );
2933                            this.focus_file_at_index(next_index, window);
2934                        }))
2935                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2936                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2937                            this.focus_file_at_index(prev_index, window);
2938                        }))
2939                        .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2940                            if this
2941                                .search_bar
2942                                .focus_handle(cx)
2943                                .contains_focused(window, cx)
2944                            {
2945                                this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
2946                            } else {
2947                                window.focus_next();
2948                            }
2949                        }))
2950                        .on_action(|_: &menu::SelectPrevious, window, _| {
2951                            window.focus_prev();
2952                        })
2953                        .flex()
2954                        .flex_row()
2955                        .flex_1()
2956                        .min_h_0()
2957                        .font(ui_font)
2958                        .bg(cx.theme().colors().background)
2959                        .text_color(cx.theme().colors().text)
2960                        .child(self.render_nav(window, cx))
2961                        .child(self.render_page(window, cx)),
2962                ),
2963            window,
2964            cx,
2965        )
2966    }
2967}
2968
2969fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2970    workspace::AppState::global(cx)
2971        .upgrade()
2972        .map(|app_state| {
2973            app_state
2974                .workspace_store
2975                .read(cx)
2976                .workspaces()
2977                .iter()
2978                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2979        })
2980        .into_iter()
2981        .flatten()
2982}
2983
2984fn update_settings_file(
2985    file: SettingsUiFile,
2986    cx: &mut App,
2987    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2988) -> Result<()> {
2989    match file {
2990        SettingsUiFile::Project((worktree_id, rel_path)) => {
2991            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2992            let project = all_projects(cx).find(|project| {
2993                project.read_with(cx, |project, cx| {
2994                    project.contains_local_settings_file(worktree_id, &rel_path, cx)
2995                })
2996            });
2997            let Some(project) = project else {
2998                anyhow::bail!(
2999                    "Could not find worktree containing settings file: {}",
3000                    &rel_path.display(PathStyle::local())
3001                );
3002            };
3003            project.update(cx, |project, cx| {
3004                project.update_local_settings_file(worktree_id, rel_path, cx, update);
3005            });
3006            return Ok(());
3007        }
3008        SettingsUiFile::User => {
3009            // todo(settings_ui) error?
3010            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3011            Ok(())
3012        }
3013        SettingsUiFile::Server(_) => unimplemented!(),
3014    }
3015}
3016
3017fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3018    field: SettingField<T>,
3019    file: SettingsUiFile,
3020    metadata: Option<&SettingsFieldMetadata>,
3021    _window: &mut Window,
3022    cx: &mut App,
3023) -> AnyElement {
3024    let (_, initial_text) =
3025        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3026    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3027
3028    SettingsInputField::new()
3029        .tab_index(0)
3030        .when_some(initial_text, |editor, text| {
3031            editor.with_initial_text(text.as_ref().to_string())
3032        })
3033        .when_some(
3034            metadata.and_then(|metadata| metadata.placeholder),
3035            |editor, placeholder| editor.with_placeholder(placeholder),
3036        )
3037        .on_confirm({
3038            move |new_text, cx| {
3039                update_settings_file(file.clone(), cx, move |settings, _cx| {
3040                    (field.write)(settings, new_text.map(Into::into));
3041                })
3042                .log_err(); // todo(settings_ui) don't log err
3043            }
3044        })
3045        .into_any_element()
3046}
3047
3048fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3049    field: SettingField<B>,
3050    file: SettingsUiFile,
3051    _metadata: Option<&SettingsFieldMetadata>,
3052    _window: &mut Window,
3053    cx: &mut App,
3054) -> AnyElement {
3055    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3056
3057    let toggle_state = if value.copied().map_or(false, Into::into) {
3058        ToggleState::Selected
3059    } else {
3060        ToggleState::Unselected
3061    };
3062
3063    Switch::new("toggle_button", toggle_state)
3064        .color(ui::SwitchColor::Accent)
3065        .on_click({
3066            move |state, _window, cx| {
3067                let state = *state == ui::ToggleState::Selected;
3068                update_settings_file(file.clone(), cx, move |settings, _cx| {
3069                    (field.write)(settings, Some(state.into()));
3070                })
3071                .log_err(); // todo(settings_ui) don't log err
3072            }
3073        })
3074        .tab_index(0_isize)
3075        .color(SwitchColor::Accent)
3076        .into_any_element()
3077}
3078
3079fn render_number_field<T: NumberFieldType + Send + Sync>(
3080    field: SettingField<T>,
3081    file: SettingsUiFile,
3082    _metadata: Option<&SettingsFieldMetadata>,
3083    window: &mut Window,
3084    cx: &mut App,
3085) -> AnyElement {
3086    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3087    let value = value.copied().unwrap_or_else(T::min_value);
3088    NumberField::new("numeric_stepper", value, window, cx)
3089        .on_change({
3090            move |value, _window, cx| {
3091                let value = *value;
3092                update_settings_file(file.clone(), cx, move |settings, _cx| {
3093                    (field.write)(settings, Some(value));
3094                })
3095                .log_err(); // todo(settings_ui) don't log err
3096            }
3097        })
3098        .into_any_element()
3099}
3100
3101fn render_dropdown<T>(
3102    field: SettingField<T>,
3103    file: SettingsUiFile,
3104    metadata: Option<&SettingsFieldMetadata>,
3105    window: &mut Window,
3106    cx: &mut App,
3107) -> AnyElement
3108where
3109    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3110{
3111    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3112    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3113    let should_do_titlecase = metadata
3114        .and_then(|metadata| metadata.should_do_titlecase)
3115        .unwrap_or(true);
3116
3117    let (_, current_value) =
3118        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3119    let current_value = current_value.copied().unwrap_or(variants()[0]);
3120
3121    let current_value_label =
3122        labels()[variants().iter().position(|v| *v == current_value).unwrap()];
3123
3124    DropdownMenu::new(
3125        "dropdown",
3126        if should_do_titlecase {
3127            current_value_label.to_title_case()
3128        } else {
3129            current_value_label.to_string()
3130        },
3131        ContextMenu::build(window, cx, move |mut menu, _, _| {
3132            for (&value, &label) in std::iter::zip(variants(), labels()) {
3133                let file = file.clone();
3134                menu = menu.toggleable_entry(
3135                    if should_do_titlecase {
3136                        label.to_title_case()
3137                    } else {
3138                        label.to_string()
3139                    },
3140                    value == current_value,
3141                    IconPosition::End,
3142                    None,
3143                    move |_, cx| {
3144                        if value == current_value {
3145                            return;
3146                        }
3147                        update_settings_file(file.clone(), cx, move |settings, _cx| {
3148                            (field.write)(settings, Some(value));
3149                        })
3150                        .log_err(); // todo(settings_ui) don't log err
3151                    },
3152                );
3153            }
3154            menu
3155        }),
3156    )
3157    .trigger_size(ButtonSize::Medium)
3158    .style(DropdownStyle::Outlined)
3159    .offset(gpui::Point {
3160        x: px(0.0),
3161        y: px(2.0),
3162    })
3163    .tab_index(0)
3164    .into_any_element()
3165}
3166
3167fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3168    Button::new(id, label)
3169        .tab_index(0_isize)
3170        .style(ButtonStyle::Outlined)
3171        .size(ButtonSize::Medium)
3172        .icon(IconName::ChevronUpDown)
3173        .icon_color(Color::Muted)
3174        .icon_size(IconSize::Small)
3175        .icon_position(IconPosition::End)
3176}
3177
3178fn render_font_picker(
3179    field: SettingField<settings::FontFamilyName>,
3180    file: SettingsUiFile,
3181    _metadata: Option<&SettingsFieldMetadata>,
3182    window: &mut Window,
3183    cx: &mut App,
3184) -> AnyElement {
3185    let current_value = SettingsStore::global(cx)
3186        .get_value_from_file(file.to_settings(), field.pick)
3187        .1
3188        .cloned()
3189        .unwrap_or_else(|| SharedString::default().into());
3190
3191    let font_picker = cx.new(|cx| {
3192        font_picker(
3193            current_value.clone().into(),
3194            move |font_name, cx| {
3195                update_settings_file(file.clone(), cx, move |settings, _cx| {
3196                    (field.write)(settings, Some(font_name.into()));
3197                })
3198                .log_err(); // todo(settings_ui) don't log err
3199            },
3200            window,
3201            cx,
3202        )
3203    });
3204
3205    PopoverMenu::new("font-picker")
3206        .menu(move |_window, _cx| Some(font_picker.clone()))
3207        .trigger(render_picker_trigger_button(
3208            "font_family_picker_trigger".into(),
3209            current_value.into(),
3210        ))
3211        .anchor(gpui::Corner::TopLeft)
3212        .offset(gpui::Point {
3213            x: px(0.0),
3214            y: px(2.0),
3215        })
3216        .with_handle(ui::PopoverMenuHandle::default())
3217        .into_any_element()
3218}
3219
3220fn render_theme_picker(
3221    field: SettingField<settings::ThemeName>,
3222    file: SettingsUiFile,
3223    _metadata: Option<&SettingsFieldMetadata>,
3224    window: &mut Window,
3225    cx: &mut App,
3226) -> AnyElement {
3227    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3228    let current_value = value
3229        .cloned()
3230        .map(|theme_name| theme_name.0.into())
3231        .unwrap_or_else(|| cx.theme().name.clone());
3232
3233    let theme_picker = cx.new(|cx| {
3234        theme_picker(
3235            current_value.clone(),
3236            move |theme_name, cx| {
3237                update_settings_file(file.clone(), cx, move |settings, _cx| {
3238                    (field.write)(settings, Some(settings::ThemeName(theme_name.into())));
3239                })
3240                .log_err(); // todo(settings_ui) don't log err
3241            },
3242            window,
3243            cx,
3244        )
3245    });
3246
3247    PopoverMenu::new("theme-picker")
3248        .menu(move |_window, _cx| Some(theme_picker.clone()))
3249        .trigger(render_picker_trigger_button(
3250            "theme_picker_trigger".into(),
3251            current_value,
3252        ))
3253        .anchor(gpui::Corner::TopLeft)
3254        .offset(gpui::Point {
3255            x: px(0.0),
3256            y: px(2.0),
3257        })
3258        .with_handle(ui::PopoverMenuHandle::default())
3259        .into_any_element()
3260}
3261
3262fn render_icon_theme_picker(
3263    field: SettingField<settings::IconThemeName>,
3264    file: SettingsUiFile,
3265    _metadata: Option<&SettingsFieldMetadata>,
3266    window: &mut Window,
3267    cx: &mut App,
3268) -> AnyElement {
3269    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3270    let current_value = value
3271        .cloned()
3272        .map(|theme_name| theme_name.0.into())
3273        .unwrap_or_else(|| cx.theme().name.clone());
3274
3275    let icon_theme_picker = cx.new(|cx| {
3276        icon_theme_picker(
3277            current_value.clone(),
3278            move |theme_name, cx| {
3279                update_settings_file(file.clone(), cx, move |settings, _cx| {
3280                    (field.write)(settings, Some(settings::IconThemeName(theme_name.into())));
3281                })
3282                .log_err(); // todo(settings_ui) don't log err
3283            },
3284            window,
3285            cx,
3286        )
3287    });
3288
3289    PopoverMenu::new("icon-theme-picker")
3290        .menu(move |_window, _cx| Some(icon_theme_picker.clone()))
3291        .trigger(render_picker_trigger_button(
3292            "icon_theme_picker_trigger".into(),
3293            current_value,
3294        ))
3295        .anchor(gpui::Corner::TopLeft)
3296        .offset(gpui::Point {
3297            x: px(0.0),
3298            y: px(2.0),
3299        })
3300        .with_handle(ui::PopoverMenuHandle::default())
3301        .into_any_element()
3302}
3303
3304#[cfg(test)]
3305pub mod test {
3306
3307    use super::*;
3308
3309    impl SettingsWindow {
3310        fn navbar_entry(&self) -> usize {
3311            self.navbar_entry
3312        }
3313    }
3314
3315    impl PartialEq for NavBarEntry {
3316        fn eq(&self, other: &Self) -> bool {
3317            self.title == other.title
3318                && self.is_root == other.is_root
3319                && self.expanded == other.expanded
3320                && self.page_index == other.page_index
3321                && self.item_index == other.item_index
3322            // ignoring focus_handle
3323        }
3324    }
3325
3326    pub fn register_settings(cx: &mut App) {
3327        settings::init(cx);
3328        theme::init(theme::LoadThemes::JustBase, cx);
3329        workspace::init_settings(cx);
3330        project::Project::init_settings(cx);
3331        language::init(cx);
3332        editor::init(cx);
3333        menu::init();
3334    }
3335
3336    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3337        let mut pages: Vec<SettingsPage> = Vec::new();
3338        let mut expanded_pages = Vec::new();
3339        let mut selected_idx = None;
3340        let mut index = 0;
3341        let mut in_expanded_section = false;
3342
3343        for mut line in input
3344            .lines()
3345            .map(|line| line.trim())
3346            .filter(|line| !line.is_empty())
3347        {
3348            if let Some(pre) = line.strip_suffix('*') {
3349                assert!(selected_idx.is_none(), "Only one selected entry allowed");
3350                selected_idx = Some(index);
3351                line = pre;
3352            }
3353            let (kind, title) = line.split_once(" ").unwrap();
3354            assert_eq!(kind.len(), 1);
3355            let kind = kind.chars().next().unwrap();
3356            if kind == 'v' {
3357                let page_idx = pages.len();
3358                expanded_pages.push(page_idx);
3359                pages.push(SettingsPage {
3360                    title,
3361                    items: vec![],
3362                });
3363                index += 1;
3364                in_expanded_section = true;
3365            } else if kind == '>' {
3366                pages.push(SettingsPage {
3367                    title,
3368                    items: vec![],
3369                });
3370                index += 1;
3371                in_expanded_section = false;
3372            } else if kind == '-' {
3373                pages
3374                    .last_mut()
3375                    .unwrap()
3376                    .items
3377                    .push(SettingsPageItem::SectionHeader(title));
3378                if selected_idx == Some(index) && !in_expanded_section {
3379                    panic!("Items in unexpanded sections cannot be selected");
3380                }
3381                index += 1;
3382            } else {
3383                panic!(
3384                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
3385                    line
3386                );
3387            }
3388        }
3389
3390        let mut settings_window = SettingsWindow {
3391            title_bar: None,
3392            original_window: None,
3393            worktree_root_dirs: HashMap::default(),
3394            files: Vec::default(),
3395            current_file: crate::SettingsUiFile::User,
3396            drop_down_file: None,
3397            pages,
3398            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3399            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3400            navbar_entries: Vec::default(),
3401            navbar_scroll_handle: UniformListScrollHandle::default(),
3402            navbar_focus_subscriptions: vec![],
3403            filter_table: vec![],
3404            has_query: false,
3405            content_handles: vec![],
3406            search_task: None,
3407            sub_page_scroll_handle: ScrollHandle::new(),
3408            focus_handle: cx.focus_handle(),
3409            navbar_focus_handle: NonFocusableHandle::new(
3410                NAVBAR_CONTAINER_TAB_INDEX,
3411                false,
3412                window,
3413                cx,
3414            ),
3415            content_focus_handle: NonFocusableHandle::new(
3416                CONTENT_CONTAINER_TAB_INDEX,
3417                false,
3418                window,
3419                cx,
3420            ),
3421            files_focus_handle: cx.focus_handle(),
3422            search_index: None,
3423            list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3424        };
3425
3426        settings_window.build_filter_table();
3427        settings_window.build_navbar(cx);
3428        for expanded_page_index in expanded_pages {
3429            for entry in &mut settings_window.navbar_entries {
3430                if entry.page_index == expanded_page_index && entry.is_root {
3431                    entry.expanded = true;
3432                }
3433            }
3434        }
3435        settings_window
3436    }
3437
3438    #[track_caller]
3439    fn check_navbar_toggle(
3440        before: &'static str,
3441        toggle_page: &'static str,
3442        after: &'static str,
3443        window: &mut Window,
3444        cx: &mut App,
3445    ) {
3446        let mut settings_window = parse(before, window, cx);
3447        let toggle_page_idx = settings_window
3448            .pages
3449            .iter()
3450            .position(|page| page.title == toggle_page)
3451            .expect("page not found");
3452        let toggle_idx = settings_window
3453            .navbar_entries
3454            .iter()
3455            .position(|entry| entry.page_index == toggle_page_idx)
3456            .expect("page not found");
3457        settings_window.toggle_navbar_entry(toggle_idx);
3458
3459        let expected_settings_window = parse(after, window, cx);
3460
3461        pretty_assertions::assert_eq!(
3462            settings_window
3463                .visible_navbar_entries()
3464                .map(|(_, entry)| entry)
3465                .collect::<Vec<_>>(),
3466            expected_settings_window
3467                .visible_navbar_entries()
3468                .map(|(_, entry)| entry)
3469                .collect::<Vec<_>>(),
3470        );
3471        pretty_assertions::assert_eq!(
3472            settings_window.navbar_entries[settings_window.navbar_entry()],
3473            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3474        );
3475    }
3476
3477    macro_rules! check_navbar_toggle {
3478        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3479            #[gpui::test]
3480            fn $name(cx: &mut gpui::TestAppContext) {
3481                let window = cx.add_empty_window();
3482                window.update(|window, cx| {
3483                    register_settings(cx);
3484                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
3485                });
3486            }
3487        };
3488    }
3489
3490    check_navbar_toggle!(
3491        navbar_basic_open,
3492        before: r"
3493        v General
3494        - General
3495        - Privacy*
3496        v Project
3497        - Project Settings
3498        ",
3499        toggle_page: "General",
3500        after: r"
3501        > General*
3502        v Project
3503        - Project Settings
3504        "
3505    );
3506
3507    check_navbar_toggle!(
3508        navbar_basic_close,
3509        before: r"
3510        > General*
3511        - General
3512        - Privacy
3513        v Project
3514        - Project Settings
3515        ",
3516        toggle_page: "General",
3517        after: r"
3518        v General*
3519        - General
3520        - Privacy
3521        v Project
3522        - Project Settings
3523        "
3524    );
3525
3526    check_navbar_toggle!(
3527        navbar_basic_second_root_entry_close,
3528        before: r"
3529        > General
3530        - General
3531        - Privacy
3532        v Project
3533        - Project Settings*
3534        ",
3535        toggle_page: "Project",
3536        after: r"
3537        > General
3538        > Project*
3539        "
3540    );
3541
3542    check_navbar_toggle!(
3543        navbar_toggle_subroot,
3544        before: r"
3545        v General Page
3546        - General
3547        - Privacy
3548        v Project
3549        - Worktree Settings Content*
3550        v AI
3551        - General
3552        > Appearance & Behavior
3553        ",
3554        toggle_page: "Project",
3555        after: r"
3556        v General Page
3557        - General
3558        - Privacy
3559        > Project*
3560        v AI
3561        - General
3562        > Appearance & Behavior
3563        "
3564    );
3565
3566    check_navbar_toggle!(
3567        navbar_toggle_close_propagates_selected_index,
3568        before: r"
3569        v General Page
3570        - General
3571        - Privacy
3572        v Project
3573        - Worktree Settings Content
3574        v AI
3575        - General*
3576        > Appearance & Behavior
3577        ",
3578        toggle_page: "General Page",
3579        after: r"
3580        > General Page*
3581        v Project
3582        - Worktree Settings Content
3583        v AI
3584        - General
3585        > Appearance & Behavior
3586        "
3587    );
3588
3589    check_navbar_toggle!(
3590        navbar_toggle_expand_propagates_selected_index,
3591        before: r"
3592        > General Page
3593        - General
3594        - Privacy
3595        v Project
3596        - Worktree Settings Content
3597        v AI
3598        - General*
3599        > Appearance & Behavior
3600        ",
3601        toggle_page: "General Page",
3602        after: r"
3603        v General Page*
3604        - General
3605        - Privacy
3606        v Project
3607        - Worktree Settings Content
3608        v AI
3609        - General
3610        > Appearance & Behavior
3611        "
3612    );
3613}