settings_ui.rs

   1mod components;
   2mod page_data;
   3pub mod pages;
   4
   5use anyhow::{Context as _, Result};
   6use editor::{Editor, EditorEvent};
   7use futures::{StreamExt, channel::mpsc};
   8use fuzzy::StringMatchCandidate;
   9use gpui::{
  10    Action, App, AsyncApp, ClipboardItem, DEFAULT_ADDITIONAL_WINDOW_SIZE, Div, Entity, FocusHandle,
  11    Focusable, Global, KeyContext, ListState, ReadGlobal as _, ScrollHandle, Stateful,
  12    Subscription, Task, TitlebarOptions, UniformListScrollHandle, WeakEntity, Window, WindowBounds,
  13    WindowHandle, WindowOptions, actions, div, list, point, prelude::*, px, uniform_list,
  14};
  15
  16use language::Buffer;
  17use platform_title_bar::PlatformTitleBar;
  18use project::{Project, ProjectPath, Worktree, WorktreeId};
  19use release_channel::ReleaseChannel;
  20use schemars::JsonSchema;
  21use serde::Deserialize;
  22use settings::{
  23    IntoGpui, Settings, SettingsContent, SettingsStore, initial_project_settings_content,
  24};
  25use std::{
  26    any::{Any, TypeId, type_name},
  27    cell::RefCell,
  28    collections::{HashMap, HashSet},
  29    num::{NonZero, NonZeroU32},
  30    ops::Range,
  31    rc::Rc,
  32    sync::{Arc, LazyLock, RwLock},
  33    time::Duration,
  34};
  35use theme::ThemeSettings;
  36use ui::{
  37    Banner, ContextMenu, Divider, DropdownMenu, DropdownStyle, IconButtonShape, KeyBinding,
  38    KeybindingHint, PopoverMenu, Scrollbars, Switch, Tooltip, TreeViewItem, WithScrollbar,
  39    prelude::*,
  40};
  41
  42use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
  43use workspace::{AppState, OpenOptions, OpenVisible, Workspace, client_side_decorations};
  44use zed_actions::{OpenProjectSettings, OpenSettings, OpenSettingsAt};
  45
  46use crate::components::{
  47    EnumVariantDropdown, NumberField, NumberFieldMode, NumberFieldType, SettingsInputField,
  48    SettingsSectionHeader, font_picker, icon_theme_picker, render_ollama_model_picker,
  49    theme_picker,
  50};
  51
  52const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
  53const NAVBAR_GROUP_TAB_INDEX: isize = 1;
  54
  55const HEADER_CONTAINER_TAB_INDEX: isize = 2;
  56const HEADER_GROUP_TAB_INDEX: isize = 3;
  57
  58const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
  59const CONTENT_GROUP_TAB_INDEX: isize = 5;
  60
  61actions!(
  62    settings_editor,
  63    [
  64        /// Minimizes the settings UI window.
  65        Minimize,
  66        /// Toggles focus between the navbar and the main content.
  67        ToggleFocusNav,
  68        /// Expands the navigation entry.
  69        ExpandNavEntry,
  70        /// Collapses the navigation entry.
  71        CollapseNavEntry,
  72        /// Focuses the next file in the file list.
  73        FocusNextFile,
  74        /// Focuses the previous file in the file list.
  75        FocusPreviousFile,
  76        /// Opens an editor for the current file
  77        OpenCurrentFile,
  78        /// Focuses the previous root navigation entry.
  79        FocusPreviousRootNavEntry,
  80        /// Focuses the next root navigation entry.
  81        FocusNextRootNavEntry,
  82        /// Focuses the first navigation entry.
  83        FocusFirstNavEntry,
  84        /// Focuses the last navigation entry.
  85        FocusLastNavEntry,
  86        /// Focuses and opens the next navigation entry without moving focus to content.
  87        FocusNextNavEntry,
  88        /// Focuses and opens the previous navigation entry without moving focus to content.
  89        FocusPreviousNavEntry
  90    ]
  91);
  92
  93#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
  94#[action(namespace = settings_editor)]
  95struct FocusFile(pub u32);
  96
  97struct SettingField<T: 'static> {
  98    pick: fn(&SettingsContent) -> Option<&T>,
  99    write: fn(&mut SettingsContent, Option<T>),
 100
 101    /// A json-path-like string that gives a unique-ish string that identifies
 102    /// where in the JSON the setting is defined.
 103    ///
 104    /// The syntax is `jq`-like, but modified slightly to be URL-safe (and
 105    /// without the leading dot), e.g. `foo.bar`.
 106    ///
 107    /// They are URL-safe (this is important since links are the main use-case
 108    /// for these paths).
 109    ///
 110    /// There are a couple of special cases:
 111    /// - discrimminants are represented with a trailing `$`, for example
 112    /// `terminal.working_directory$`. This is to distinguish the discrimminant
 113    /// setting (i.e. the setting that changes whether the value is a string or
 114    /// an object) from the setting in the case that it is a string.
 115    /// - language-specific settings begin `languages.$(language)`. Links
 116    /// targeting these settings should take the form `languages/Rust/...`, for
 117    /// example, but are not currently supported.
 118    json_path: Option<&'static str>,
 119}
 120
 121impl<T: 'static> Clone for SettingField<T> {
 122    fn clone(&self) -> Self {
 123        *self
 124    }
 125}
 126
 127// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
 128impl<T: 'static> Copy for SettingField<T> {}
 129
 130/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
 131/// to keep the setting around in the UI with valid pick and write implementations, but don't actually try to render it.
 132/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
 133#[derive(Clone, Copy)]
 134struct UnimplementedSettingField;
 135
 136impl PartialEq for UnimplementedSettingField {
 137    fn eq(&self, _other: &Self) -> bool {
 138        true
 139    }
 140}
 141
 142impl<T: 'static> SettingField<T> {
 143    /// Helper for settings with types that are not yet implemented.
 144    #[allow(unused)]
 145    fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
 146        SettingField {
 147            pick: |_| Some(&UnimplementedSettingField),
 148            write: |_, _| unreachable!(),
 149            json_path: self.json_path,
 150        }
 151    }
 152}
 153
 154trait AnySettingField {
 155    fn as_any(&self) -> &dyn Any;
 156    fn type_name(&self) -> &'static str;
 157    fn type_id(&self) -> TypeId;
 158    // 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)
 159    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
 160    fn reset_to_default_fn(
 161        &self,
 162        current_file: &SettingsUiFile,
 163        file_set_in: &settings::SettingsFile,
 164        cx: &App,
 165    ) -> Option<Box<dyn Fn(&mut Window, &mut App)>>;
 166
 167    fn json_path(&self) -> Option<&'static str>;
 168}
 169
 170impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
 171    fn as_any(&self) -> &dyn Any {
 172        self
 173    }
 174
 175    fn type_name(&self) -> &'static str {
 176        type_name::<T>()
 177    }
 178
 179    fn type_id(&self) -> TypeId {
 180        TypeId::of::<T>()
 181    }
 182
 183    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
 184        let (file, value) = cx
 185            .global::<SettingsStore>()
 186            .get_value_from_file(file.to_settings(), self.pick);
 187        return (file, value.is_some());
 188    }
 189
 190    fn reset_to_default_fn(
 191        &self,
 192        current_file: &SettingsUiFile,
 193        file_set_in: &settings::SettingsFile,
 194        cx: &App,
 195    ) -> Option<Box<dyn Fn(&mut Window, &mut App)>> {
 196        if file_set_in == &settings::SettingsFile::Default {
 197            return None;
 198        }
 199        if file_set_in != &current_file.to_settings() {
 200            return None;
 201        }
 202        let this = *self;
 203        let store = SettingsStore::global(cx);
 204        let default_value = (this.pick)(store.raw_default_settings());
 205        let is_default = store
 206            .get_content_for_file(file_set_in.clone())
 207            .map_or(None, this.pick)
 208            == default_value;
 209        if is_default {
 210            return None;
 211        }
 212        let current_file = current_file.clone();
 213
 214        return Some(Box::new(move |window, cx| {
 215            let store = SettingsStore::global(cx);
 216            let default_value = (this.pick)(store.raw_default_settings());
 217            let is_set_somewhere_other_than_default = store
 218                .get_value_up_to_file(current_file.to_settings(), this.pick)
 219                .0
 220                != settings::SettingsFile::Default;
 221            let value_to_set = if is_set_somewhere_other_than_default {
 222                default_value.cloned()
 223            } else {
 224                None
 225            };
 226            update_settings_file(
 227                current_file.clone(),
 228                None,
 229                window,
 230                cx,
 231                move |settings, _| {
 232                    (this.write)(settings, value_to_set);
 233                },
 234            )
 235            // todo(settings_ui): Don't log err
 236            .log_err();
 237        }));
 238    }
 239
 240    fn json_path(&self) -> Option<&'static str> {
 241        self.json_path
 242    }
 243}
 244
 245#[derive(Default, Clone)]
 246struct SettingFieldRenderer {
 247    renderers: Rc<
 248        RefCell<
 249            HashMap<
 250                TypeId,
 251                Box<
 252                    dyn Fn(
 253                        &SettingsWindow,
 254                        &SettingItem,
 255                        SettingsUiFile,
 256                        Option<&SettingsFieldMetadata>,
 257                        bool,
 258                        &mut Window,
 259                        &mut Context<SettingsWindow>,
 260                    ) -> Stateful<Div>,
 261                >,
 262            >,
 263        >,
 264    >,
 265}
 266
 267impl Global for SettingFieldRenderer {}
 268
 269impl SettingFieldRenderer {
 270    fn add_basic_renderer<T: 'static>(
 271        &mut self,
 272        render_control: impl Fn(
 273            SettingField<T>,
 274            SettingsUiFile,
 275            Option<&SettingsFieldMetadata>,
 276            &mut Window,
 277            &mut App,
 278        ) -> AnyElement
 279        + 'static,
 280    ) -> &mut Self {
 281        self.add_renderer(
 282            move |settings_window: &SettingsWindow,
 283                  item: &SettingItem,
 284                  field: SettingField<T>,
 285                  settings_file: SettingsUiFile,
 286                  metadata: Option<&SettingsFieldMetadata>,
 287                  sub_field: bool,
 288                  window: &mut Window,
 289                  cx: &mut Context<SettingsWindow>| {
 290                render_settings_item(
 291                    settings_window,
 292                    item,
 293                    settings_file.clone(),
 294                    render_control(field, settings_file, metadata, window, cx),
 295                    sub_field,
 296                    cx,
 297                )
 298            },
 299        )
 300    }
 301
 302    fn add_renderer<T: 'static>(
 303        &mut self,
 304        renderer: impl Fn(
 305            &SettingsWindow,
 306            &SettingItem,
 307            SettingField<T>,
 308            SettingsUiFile,
 309            Option<&SettingsFieldMetadata>,
 310            bool,
 311            &mut Window,
 312            &mut Context<SettingsWindow>,
 313        ) -> Stateful<Div>
 314        + 'static,
 315    ) -> &mut Self {
 316        let key = TypeId::of::<T>();
 317        let renderer = Box::new(
 318            move |settings_window: &SettingsWindow,
 319                  item: &SettingItem,
 320                  settings_file: SettingsUiFile,
 321                  metadata: Option<&SettingsFieldMetadata>,
 322                  sub_field: bool,
 323                  window: &mut Window,
 324                  cx: &mut Context<SettingsWindow>| {
 325                let field = *item
 326                    .field
 327                    .as_ref()
 328                    .as_any()
 329                    .downcast_ref::<SettingField<T>>()
 330                    .unwrap();
 331                renderer(
 332                    settings_window,
 333                    item,
 334                    field,
 335                    settings_file,
 336                    metadata,
 337                    sub_field,
 338                    window,
 339                    cx,
 340                )
 341            },
 342        );
 343        self.renderers.borrow_mut().insert(key, renderer);
 344        self
 345    }
 346}
 347
 348struct NonFocusableHandle {
 349    handle: FocusHandle,
 350    _subscription: Subscription,
 351}
 352
 353impl NonFocusableHandle {
 354    fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
 355        let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
 356        Self::from_handle(handle, window, cx)
 357    }
 358
 359    fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
 360        cx.new(|cx| {
 361            let _subscription = cx.on_focus(&handle, window, {
 362                move |_, window, cx| {
 363                    window.focus_next(cx);
 364                }
 365            });
 366            Self {
 367                handle,
 368                _subscription,
 369            }
 370        })
 371    }
 372}
 373
 374impl Focusable for NonFocusableHandle {
 375    fn focus_handle(&self, _: &App) -> FocusHandle {
 376        self.handle.clone()
 377    }
 378}
 379
 380#[derive(Default)]
 381struct SettingsFieldMetadata {
 382    placeholder: Option<&'static str>,
 383    should_do_titlecase: Option<bool>,
 384}
 385
 386pub fn init(cx: &mut App) {
 387    init_renderers(cx);
 388    let queue = ProjectSettingsUpdateQueue::new(cx);
 389    cx.set_global(queue);
 390
 391    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 392        workspace
 393            .register_action(
 394                |workspace, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
 395                    let window_handle = window
 396                        .window_handle()
 397                        .downcast::<Workspace>()
 398                        .expect("Workspaces are root Windows");
 399                    open_settings_editor(workspace, Some(&path), false, window_handle, cx);
 400                },
 401            )
 402            .register_action(|workspace, _: &OpenSettings, window, cx| {
 403                let window_handle = window
 404                    .window_handle()
 405                    .downcast::<Workspace>()
 406                    .expect("Workspaces are root Windows");
 407                open_settings_editor(workspace, None, false, window_handle, cx);
 408            })
 409            .register_action(|workspace, _: &OpenProjectSettings, window, cx| {
 410                let window_handle = window
 411                    .window_handle()
 412                    .downcast::<Workspace>()
 413                    .expect("Workspaces are root Windows");
 414                open_settings_editor(workspace, None, true, window_handle, cx);
 415            });
 416    })
 417    .detach();
 418}
 419
 420fn init_renderers(cx: &mut App) {
 421    cx.default_global::<SettingFieldRenderer>()
 422        .add_renderer::<UnimplementedSettingField>(
 423            |settings_window, item, _, settings_file, _, sub_field, _, cx| {
 424                render_settings_item(
 425                    settings_window,
 426                    item,
 427                    settings_file,
 428                    Button::new("open-in-settings-file", "Edit in settings.json")
 429                        .style(ButtonStyle::Outlined)
 430                        .size(ButtonSize::Medium)
 431                        .tab_index(0_isize)
 432                        .tooltip(Tooltip::for_action_title_in(
 433                            "Edit in settings.json",
 434                            &OpenCurrentFile,
 435                            &settings_window.focus_handle,
 436                        ))
 437                        .on_click(cx.listener(|this, _, window, cx| {
 438                            this.open_current_settings_file(window, cx);
 439                        }))
 440                        .into_any_element(),
 441                    sub_field,
 442                    cx,
 443                )
 444            },
 445        )
 446        .add_basic_renderer::<bool>(render_toggle_button)
 447        .add_basic_renderer::<String>(render_text_field)
 448        .add_basic_renderer::<SharedString>(render_text_field)
 449        .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
 450        .add_basic_renderer::<settings::CursorShape>(render_dropdown)
 451        .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
 452        .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
 453        .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
 454        .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
 455        .add_basic_renderer::<settings::TextRenderingMode>(render_dropdown)
 456        .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
 457        .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
 458        .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
 459        .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
 460        .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
 461        .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
 462        .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
 463        .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
 464        .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
 465        .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
 466        .add_basic_renderer::<settings::DockSide>(render_dropdown)
 467        .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
 468        .add_basic_renderer::<settings::DockPosition>(render_dropdown)
 469        .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
 470        .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
 471        .add_basic_renderer::<settings::GitPathStyle>(render_dropdown)
 472        .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
 473        .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
 474        .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
 475        .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
 476        .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
 477        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 478        .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
 479        .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
 480        .add_basic_renderer::<settings::ProjectPanelSortMode>(render_dropdown)
 481        .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
 482        .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
 483        .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
 484        .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
 485        .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
 486        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 487        .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
 488        .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
 489        .add_basic_renderer::<settings::CompletionDetailAlignment>(render_dropdown)
 490        .add_basic_renderer::<settings::DiffViewStyle>(render_dropdown)
 491        .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
 492        .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
 493        .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
 494        .add_basic_renderer::<f32>(render_number_field)
 495        .add_basic_renderer::<u32>(render_number_field)
 496        .add_basic_renderer::<u64>(render_number_field)
 497        .add_basic_renderer::<usize>(render_number_field)
 498        .add_basic_renderer::<NonZero<usize>>(render_number_field)
 499        .add_basic_renderer::<NonZeroU32>(render_number_field)
 500        .add_basic_renderer::<settings::CodeFade>(render_number_field)
 501        .add_basic_renderer::<settings::DelayMs>(render_number_field)
 502        .add_basic_renderer::<settings::FontWeightContent>(render_number_field)
 503        .add_basic_renderer::<settings::CenteredPaddingSettings>(render_number_field)
 504        .add_basic_renderer::<settings::InactiveOpacity>(render_number_field)
 505        .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
 506        .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
 507        .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
 508        .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
 509        .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
 510        .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
 511        .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
 512        .add_basic_renderer::<settings::ModeContent>(render_dropdown)
 513        .add_basic_renderer::<settings::UseSystemClipboard>(render_dropdown)
 514        .add_basic_renderer::<settings::VimInsertModeCursorShape>(render_dropdown)
 515        .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
 516        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 517        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 518        .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
 519        .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
 520        .add_basic_renderer::<settings::EncodingDisplayOptions>(render_dropdown)
 521        .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
 522        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 523        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 524        .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
 525        .add_basic_renderer::<settings::ThemeSelectionDiscriminants>(render_dropdown)
 526        .add_basic_renderer::<settings::ThemeAppearanceMode>(render_dropdown)
 527        .add_basic_renderer::<settings::ThemeName>(render_theme_picker)
 528        .add_basic_renderer::<settings::IconThemeSelectionDiscriminants>(render_dropdown)
 529        .add_basic_renderer::<settings::IconThemeName>(render_icon_theme_picker)
 530        .add_basic_renderer::<settings::BufferLineHeightDiscriminants>(render_dropdown)
 531        .add_basic_renderer::<settings::AutosaveSettingDiscriminants>(render_dropdown)
 532        .add_basic_renderer::<settings::WorkingDirectoryDiscriminants>(render_dropdown)
 533        .add_basic_renderer::<settings::IncludeIgnoredContent>(render_dropdown)
 534        .add_basic_renderer::<settings::ShowIndentGuides>(render_dropdown)
 535        .add_basic_renderer::<settings::ShellDiscriminants>(render_dropdown)
 536        .add_basic_renderer::<settings::EditPredictionsMode>(render_dropdown)
 537        .add_basic_renderer::<settings::RelativeLineNumbers>(render_dropdown)
 538        .add_basic_renderer::<settings::WindowDecorations>(render_dropdown)
 539        .add_basic_renderer::<settings::FontSize>(render_editable_number_field)
 540        .add_basic_renderer::<settings::OllamaModelName>(render_ollama_model_picker)
 541        .add_basic_renderer::<settings::SemanticTokens>(render_dropdown)
 542        .add_basic_renderer::<settings::DocumentFoldingRanges>(render_dropdown)
 543        // please semicolon stay on next line
 544        ;
 545}
 546
 547pub fn open_settings_editor(
 548    _workspace: &mut Workspace,
 549    path: Option<&str>,
 550    open_project_settings: bool,
 551    workspace_handle: WindowHandle<Workspace>,
 552    cx: &mut App,
 553) {
 554    telemetry::event!("Settings Viewed");
 555
 556    /// Assumes a settings GUI window is already open
 557    fn open_path(
 558        path: &str,
 559        // Note: This option is unsupported right now
 560        _open_project_settings: bool,
 561        settings_window: &mut SettingsWindow,
 562        window: &mut Window,
 563        cx: &mut Context<SettingsWindow>,
 564    ) {
 565        if path.starts_with("languages.$(language)") {
 566            log::error!("language-specific settings links are not currently supported");
 567            return;
 568        }
 569
 570        let query = format!("#{path}");
 571        let indices = settings_window.filter_by_json_path(&query);
 572
 573        settings_window.opening_link = true;
 574        settings_window.search_bar.update(cx, |editor, cx| {
 575            editor.set_text(query, window, cx);
 576        });
 577        settings_window.apply_match_indices(indices.iter().copied());
 578
 579        if indices.len() == 1
 580            && let Some(search_index) = settings_window.search_index.as_ref()
 581        {
 582            let SearchKeyLUTEntry {
 583                page_index,
 584                item_index,
 585                header_index,
 586                ..
 587            } = search_index.key_lut[indices[0]];
 588            let page = &settings_window.pages[page_index];
 589            let item = &page.items[item_index];
 590
 591            if settings_window.filter_table[page_index][item_index]
 592                && let SettingsPageItem::SubPageLink(link) = item
 593                && let SettingsPageItem::SectionHeader(header) = page.items[header_index]
 594            {
 595                settings_window.push_sub_page(link.clone(), SharedString::from(header), window, cx);
 596            }
 597        }
 598
 599        cx.notify();
 600    }
 601
 602    let existing_window = cx
 603        .windows()
 604        .into_iter()
 605        .find_map(|window| window.downcast::<SettingsWindow>());
 606
 607    if let Some(existing_window) = existing_window {
 608        existing_window
 609            .update(cx, |settings_window, window, cx| {
 610                settings_window.original_window = Some(workspace_handle);
 611                window.activate_window();
 612                if let Some(path) = path {
 613                    open_path(path, open_project_settings, settings_window, window, cx);
 614                } else if open_project_settings {
 615                    if let Some(file_index) = settings_window
 616                        .files
 617                        .iter()
 618                        .position(|(file, _)| file.worktree_id().is_some())
 619                    {
 620                        settings_window.change_file(file_index, window, cx);
 621                    }
 622
 623                    cx.notify();
 624                }
 625            })
 626            .ok();
 627        return;
 628    }
 629
 630    // We have to defer this to get the workspace off the stack.
 631    let path = path.map(ToOwned::to_owned);
 632    cx.defer(move |cx| {
 633        let current_rem_size: f32 = theme::ThemeSettings::get_global(cx).ui_font_size(cx).into();
 634
 635        let default_bounds = DEFAULT_ADDITIONAL_WINDOW_SIZE;
 636        let default_rem_size = 16.0;
 637        let scale_factor = current_rem_size / default_rem_size;
 638        let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
 639
 640        let app_id = ReleaseChannel::global(cx).app_id();
 641        let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
 642            Ok(val) if val == "server" => gpui::WindowDecorations::Server,
 643            Ok(val) if val == "client" => gpui::WindowDecorations::Client,
 644            _ => gpui::WindowDecorations::Client,
 645        };
 646
 647        cx.open_window(
 648            WindowOptions {
 649                titlebar: Some(TitlebarOptions {
 650                    title: Some("Zed — Settings".into()),
 651                    appears_transparent: true,
 652                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 653                }),
 654                focus: true,
 655                show: true,
 656                is_movable: true,
 657                kind: gpui::WindowKind::Normal,
 658                window_background: cx.theme().window_background_appearance(),
 659                app_id: Some(app_id.to_owned()),
 660                window_decorations: Some(window_decorations),
 661                window_min_size: Some(gpui::Size {
 662                    // Don't make the settings window thinner than this,
 663                    // otherwise, it gets unusable. Users with smaller res monitors
 664                    // can customize the height, but not the width.
 665                    width: px(900.0),
 666                    height: px(240.0),
 667                }),
 668                window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
 669                ..Default::default()
 670            },
 671            |window, cx| {
 672                let settings_window =
 673                    cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx));
 674                settings_window.update(cx, |settings_window, cx| {
 675                    if let Some(path) = path {
 676                        open_path(&path, open_project_settings, settings_window, window, cx);
 677                    } else if open_project_settings {
 678                        if let Some(file_index) = settings_window
 679                            .files
 680                            .iter()
 681                            .position(|(file, _)| file.worktree_id().is_some())
 682                        {
 683                            settings_window.change_file(file_index, window, cx);
 684                        }
 685
 686                        settings_window.fetch_files(window, cx);
 687                    }
 688                });
 689
 690                settings_window
 691            },
 692        )
 693        .log_err();
 694    });
 695}
 696
 697/// The current sub page path that is selected.
 698/// If this is empty the selected page is rendered,
 699/// otherwise the last sub page gets rendered.
 700///
 701/// Global so that `pick` and `write` callbacks can access it
 702/// and use it to dynamically render sub pages (e.g. for language settings)
 703static ACTIVE_LANGUAGE: LazyLock<RwLock<Option<SharedString>>> =
 704    LazyLock::new(|| RwLock::new(Option::None));
 705
 706fn active_language() -> Option<SharedString> {
 707    ACTIVE_LANGUAGE
 708        .read()
 709        .ok()
 710        .and_then(|language| language.clone())
 711}
 712
 713fn active_language_mut() -> Option<std::sync::RwLockWriteGuard<'static, Option<SharedString>>> {
 714    ACTIVE_LANGUAGE.write().ok()
 715}
 716
 717pub struct SettingsWindow {
 718    title_bar: Option<Entity<PlatformTitleBar>>,
 719    original_window: Option<WindowHandle<Workspace>>,
 720    files: Vec<(SettingsUiFile, FocusHandle)>,
 721    worktree_root_dirs: HashMap<WorktreeId, String>,
 722    current_file: SettingsUiFile,
 723    pages: Vec<SettingsPage>,
 724    sub_page_stack: Vec<SubPage>,
 725    opening_link: bool,
 726    search_bar: Entity<Editor>,
 727    search_task: Option<Task<()>>,
 728    /// Cached settings file buffers to avoid repeated disk I/O on each settings change
 729    project_setting_file_buffers: HashMap<ProjectPath, Entity<Buffer>>,
 730    /// Index into navbar_entries
 731    navbar_entry: usize,
 732    navbar_entries: Vec<NavBarEntry>,
 733    navbar_scroll_handle: UniformListScrollHandle,
 734    /// [page_index][page_item_index] will be false
 735    /// when the item is filtered out either by searches
 736    /// or by the current file
 737    navbar_focus_subscriptions: Vec<gpui::Subscription>,
 738    filter_table: Vec<Vec<bool>>,
 739    has_query: bool,
 740    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 741    focus_handle: FocusHandle,
 742    navbar_focus_handle: Entity<NonFocusableHandle>,
 743    content_focus_handle: Entity<NonFocusableHandle>,
 744    files_focus_handle: FocusHandle,
 745    search_index: Option<Arc<SearchIndex>>,
 746    list_state: ListState,
 747    shown_errors: HashSet<String>,
 748    pub(crate) regex_validation_error: Option<String>,
 749}
 750
 751struct SearchIndex {
 752    bm25_engine: bm25::SearchEngine<usize>,
 753    fuzzy_match_candidates: Vec<StringMatchCandidate>,
 754    key_lut: Vec<SearchKeyLUTEntry>,
 755}
 756
 757struct SearchKeyLUTEntry {
 758    page_index: usize,
 759    header_index: usize,
 760    item_index: usize,
 761    json_path: Option<&'static str>,
 762}
 763
 764struct SubPage {
 765    link: SubPageLink,
 766    section_header: SharedString,
 767    scroll_handle: ScrollHandle,
 768}
 769
 770impl SubPage {
 771    fn new(link: SubPageLink, section_header: SharedString) -> Self {
 772        if link.r#type == SubPageType::Language
 773            && let Some(mut active_language_global) = active_language_mut()
 774        {
 775            active_language_global.replace(link.title.clone());
 776        }
 777
 778        SubPage {
 779            link,
 780            section_header,
 781            scroll_handle: ScrollHandle::new(),
 782        }
 783    }
 784}
 785
 786impl Drop for SubPage {
 787    fn drop(&mut self) {
 788        if self.link.r#type == SubPageType::Language
 789            && let Some(mut active_language_global) = active_language_mut()
 790            && active_language_global
 791                .as_ref()
 792                .is_some_and(|language_name| language_name == &self.link.title)
 793        {
 794            active_language_global.take();
 795        }
 796    }
 797}
 798
 799#[derive(Debug)]
 800struct NavBarEntry {
 801    title: &'static str,
 802    is_root: bool,
 803    expanded: bool,
 804    page_index: usize,
 805    item_index: Option<usize>,
 806    focus_handle: FocusHandle,
 807}
 808
 809struct SettingsPage {
 810    title: &'static str,
 811    items: Box<[SettingsPageItem]>,
 812}
 813
 814#[derive(PartialEq)]
 815enum SettingsPageItem {
 816    SectionHeader(&'static str),
 817    SettingItem(SettingItem),
 818    SubPageLink(SubPageLink),
 819    DynamicItem(DynamicItem),
 820    ActionLink(ActionLink),
 821}
 822
 823impl std::fmt::Debug for SettingsPageItem {
 824    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 825        match self {
 826            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 827            SettingsPageItem::SettingItem(setting_item) => {
 828                write!(f, "SettingItem({})", setting_item.title)
 829            }
 830            SettingsPageItem::SubPageLink(sub_page_link) => {
 831                write!(f, "SubPageLink({})", sub_page_link.title)
 832            }
 833            SettingsPageItem::DynamicItem(dynamic_item) => {
 834                write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
 835            }
 836            SettingsPageItem::ActionLink(action_link) => {
 837                write!(f, "ActionLink({})", action_link.title)
 838            }
 839        }
 840    }
 841}
 842
 843impl SettingsPageItem {
 844    fn header_text(&self) -> Option<&'static str> {
 845        match self {
 846            SettingsPageItem::SectionHeader(header) => Some(header),
 847            _ => None,
 848        }
 849    }
 850
 851    fn render(
 852        &self,
 853        settings_window: &SettingsWindow,
 854        item_index: usize,
 855        bottom_border: bool,
 856        extra_bottom_padding: bool,
 857        window: &mut Window,
 858        cx: &mut Context<SettingsWindow>,
 859    ) -> AnyElement {
 860        let file = settings_window.current_file.clone();
 861
 862        let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
 863            let element = element.pt_4();
 864            if extra_bottom_padding {
 865                element.pb_10()
 866            } else {
 867                element.pb_4()
 868            }
 869        };
 870
 871        let mut render_setting_item_inner =
 872            |setting_item: &SettingItem,
 873             padding: bool,
 874             sub_field: bool,
 875             cx: &mut Context<SettingsWindow>| {
 876                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 877                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 878
 879                let renderers = renderer.renderers.borrow();
 880
 881                let field_renderer =
 882                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 883                let field_renderer_or_warning =
 884                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 885                        if cfg!(debug_assertions) && !found {
 886                            Err("NO DEFAULT")
 887                        } else {
 888                            Ok(renderer)
 889                        }
 890                    });
 891
 892                let field = match field_renderer_or_warning {
 893                    Ok(field_renderer) => window.with_id(item_index, |window| {
 894                        field_renderer(
 895                            settings_window,
 896                            setting_item,
 897                            file.clone(),
 898                            setting_item.metadata.as_deref(),
 899                            sub_field,
 900                            window,
 901                            cx,
 902                        )
 903                    }),
 904                    Err(warning) => render_settings_item(
 905                        settings_window,
 906                        setting_item,
 907                        file.clone(),
 908                        Button::new("error-warning", warning)
 909                            .style(ButtonStyle::Outlined)
 910                            .size(ButtonSize::Medium)
 911                            .icon(Some(IconName::Debug))
 912                            .icon_position(IconPosition::Start)
 913                            .icon_color(Color::Error)
 914                            .tab_index(0_isize)
 915                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 916                            .into_any_element(),
 917                        sub_field,
 918                        cx,
 919                    ),
 920                };
 921
 922                let field = if padding {
 923                    field.map(apply_padding)
 924                } else {
 925                    field
 926                };
 927
 928                (field, field_renderer_or_warning.is_ok())
 929            };
 930
 931        match self {
 932            SettingsPageItem::SectionHeader(header) => {
 933                SettingsSectionHeader::new(SharedString::new_static(header)).into_any_element()
 934            }
 935            SettingsPageItem::SettingItem(setting_item) => {
 936                let (field_with_padding, _) =
 937                    render_setting_item_inner(setting_item, true, false, cx);
 938
 939                v_flex()
 940                    .group("setting-item")
 941                    .px_8()
 942                    .child(field_with_padding)
 943                    .when(bottom_border, |this| this.child(Divider::horizontal()))
 944                    .into_any_element()
 945            }
 946            SettingsPageItem::SubPageLink(sub_page_link) => v_flex()
 947                .group("setting-item")
 948                .px_8()
 949                .child(
 950                    h_flex()
 951                        .id(sub_page_link.title.clone())
 952                        .w_full()
 953                        .min_w_0()
 954                        .justify_between()
 955                        .map(apply_padding)
 956                        .child(
 957                            v_flex()
 958                                .relative()
 959                                .w_full()
 960                                .max_w_1_2()
 961                                .child(Label::new(sub_page_link.title.clone()))
 962                                .when_some(
 963                                    sub_page_link.description.as_ref(),
 964                                    |this, description| {
 965                                        this.child(
 966                                            Label::new(description.clone())
 967                                                .size(LabelSize::Small)
 968                                                .color(Color::Muted),
 969                                        )
 970                                    },
 971                                ),
 972                        )
 973                        .child(
 974                            Button::new(
 975                                ("sub-page".into(), sub_page_link.title.clone()),
 976                                "Configure",
 977                            )
 978                            .icon(IconName::ChevronRight)
 979                            .tab_index(0_isize)
 980                            .icon_position(IconPosition::End)
 981                            .icon_color(Color::Muted)
 982                            .icon_size(IconSize::Small)
 983                            .style(ButtonStyle::OutlinedGhost)
 984                            .size(ButtonSize::Medium)
 985                            .on_click({
 986                                let sub_page_link = sub_page_link.clone();
 987                                cx.listener(move |this, _, window, cx| {
 988                                    let header_text = this
 989                                        .sub_page_stack
 990                                        .last()
 991                                        .map(|sub_page| sub_page.link.title.clone())
 992                                        .or_else(|| {
 993                                            this.current_page()
 994                                                .items
 995                                                .iter()
 996                                                .take(item_index)
 997                                                .rev()
 998                                                .find_map(|item| {
 999                                                    item.header_text().map(SharedString::new_static)
1000                                                })
1001                                        });
1002
1003                                    let Some(header) = header_text else {
1004                                        unreachable!(
1005                                            "All items always have a section header above them"
1006                                        )
1007                                    };
1008
1009                                    this.push_sub_page(sub_page_link.clone(), header, window, cx)
1010                                })
1011                            }),
1012                        )
1013                        .child(render_settings_item_link(
1014                            sub_page_link.title.clone(),
1015                            sub_page_link.json_path,
1016                            false,
1017                            cx,
1018                        )),
1019                )
1020                .when(bottom_border, |this| this.child(Divider::horizontal()))
1021                .into_any_element(),
1022            SettingsPageItem::DynamicItem(DynamicItem {
1023                discriminant: discriminant_setting_item,
1024                pick_discriminant,
1025                fields,
1026            }) => {
1027                let file = file.to_settings();
1028                let discriminant = SettingsStore::global(cx)
1029                    .get_value_from_file(file, *pick_discriminant)
1030                    .1;
1031
1032                let (discriminant_element, rendered_ok) =
1033                    render_setting_item_inner(discriminant_setting_item, true, false, cx);
1034
1035                let has_sub_fields =
1036                    rendered_ok && discriminant.is_some_and(|d| !fields[d].is_empty());
1037
1038                let mut content = v_flex()
1039                    .id("dynamic-item")
1040                    .child(
1041                        div()
1042                            .group("setting-item")
1043                            .px_8()
1044                            .child(discriminant_element.when(has_sub_fields, |this| this.pb_4())),
1045                    )
1046                    .when(!has_sub_fields && bottom_border, |this| {
1047                        this.child(h_flex().px_8().child(Divider::horizontal()))
1048                    });
1049
1050                if rendered_ok {
1051                    let discriminant =
1052                        discriminant.expect("This should be Some if rendered_ok is true");
1053                    let sub_fields = &fields[discriminant];
1054                    let sub_field_count = sub_fields.len();
1055
1056                    for (index, field) in sub_fields.iter().enumerate() {
1057                        let is_last_sub_field = index == sub_field_count - 1;
1058                        let (raw_field, _) = render_setting_item_inner(field, false, true, cx);
1059
1060                        content = content.child(
1061                            raw_field
1062                                .group("setting-sub-item")
1063                                .mx_8()
1064                                .p_4()
1065                                .border_t_1()
1066                                .when(is_last_sub_field, |this| this.border_b_1())
1067                                .when(is_last_sub_field && extra_bottom_padding, |this| {
1068                                    this.mb_8()
1069                                })
1070                                .border_dashed()
1071                                .border_color(cx.theme().colors().border_variant)
1072                                .bg(cx.theme().colors().element_background.opacity(0.2)),
1073                        );
1074                    }
1075                }
1076
1077                return content.into_any_element();
1078            }
1079            SettingsPageItem::ActionLink(action_link) => v_flex()
1080                .group("setting-item")
1081                .px_8()
1082                .child(
1083                    h_flex()
1084                        .id(action_link.title.clone())
1085                        .w_full()
1086                        .min_w_0()
1087                        .justify_between()
1088                        .map(apply_padding)
1089                        .child(
1090                            v_flex()
1091                                .relative()
1092                                .w_full()
1093                                .max_w_1_2()
1094                                .child(Label::new(action_link.title.clone()))
1095                                .when_some(
1096                                    action_link.description.as_ref(),
1097                                    |this, description| {
1098                                        this.child(
1099                                            Label::new(description.clone())
1100                                                .size(LabelSize::Small)
1101                                                .color(Color::Muted),
1102                                        )
1103                                    },
1104                                ),
1105                        )
1106                        .child(
1107                            Button::new(
1108                                ("action-link".into(), action_link.title.clone()),
1109                                action_link.button_text.clone(),
1110                            )
1111                            .icon(IconName::ArrowUpRight)
1112                            .tab_index(0_isize)
1113                            .icon_position(IconPosition::End)
1114                            .icon_color(Color::Muted)
1115                            .icon_size(IconSize::Small)
1116                            .style(ButtonStyle::OutlinedGhost)
1117                            .size(ButtonSize::Medium)
1118                            .on_click({
1119                                let on_click = action_link.on_click.clone();
1120                                cx.listener(move |this, _, window, cx| {
1121                                    on_click(this, window, cx);
1122                                })
1123                            }),
1124                        ),
1125                )
1126                .when(bottom_border, |this| this.child(Divider::horizontal()))
1127                .into_any_element(),
1128        }
1129    }
1130}
1131
1132fn render_settings_item(
1133    settings_window: &SettingsWindow,
1134    setting_item: &SettingItem,
1135    file: SettingsUiFile,
1136    control: AnyElement,
1137    sub_field: bool,
1138    cx: &mut Context<'_, SettingsWindow>,
1139) -> Stateful<Div> {
1140    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
1141    let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
1142
1143    h_flex()
1144        .id(setting_item.title)
1145        .min_w_0()
1146        .justify_between()
1147        .child(
1148            v_flex()
1149                .relative()
1150                .w_3_4()
1151                .child(
1152                    h_flex()
1153                        .w_full()
1154                        .gap_1()
1155                        .child(Label::new(SharedString::new_static(setting_item.title)))
1156                        .when_some(
1157                            if sub_field {
1158                                None
1159                            } else {
1160                                setting_item
1161                                    .field
1162                                    .reset_to_default_fn(&file, &found_in_file, cx)
1163                            },
1164                            |this, reset_to_default| {
1165                                this.child(
1166                                    IconButton::new("reset-to-default-btn", IconName::Undo)
1167                                        .icon_color(Color::Muted)
1168                                        .icon_size(IconSize::Small)
1169                                        .tooltip(Tooltip::text("Reset to Default"))
1170                                        .on_click({
1171                                            move |_, window, cx| {
1172                                                reset_to_default(window, cx);
1173                                            }
1174                                        }),
1175                                )
1176                            },
1177                        )
1178                        .when_some(
1179                            file_set_in.filter(|file_set_in| file_set_in != &file),
1180                            |this, file_set_in| {
1181                                this.child(
1182                                    Label::new(format!(
1183                                        "—  Modified in {}",
1184                                        settings_window
1185                                            .display_name(&file_set_in)
1186                                            .expect("File name should exist")
1187                                    ))
1188                                    .color(Color::Muted)
1189                                    .size(LabelSize::Small),
1190                                )
1191                            },
1192                        ),
1193                )
1194                .child(
1195                    Label::new(SharedString::new_static(setting_item.description))
1196                        .size(LabelSize::Small)
1197                        .color(Color::Muted),
1198                ),
1199        )
1200        .child(control)
1201        .when(settings_window.sub_page_stack.is_empty(), |this| {
1202            this.child(render_settings_item_link(
1203                setting_item.description,
1204                setting_item.field.json_path(),
1205                sub_field,
1206                cx,
1207            ))
1208        })
1209}
1210
1211fn render_settings_item_link(
1212    id: impl Into<ElementId>,
1213    json_path: Option<&'static str>,
1214    sub_field: bool,
1215    cx: &mut Context<'_, SettingsWindow>,
1216) -> impl IntoElement {
1217    let clipboard_has_link = cx
1218        .read_from_clipboard()
1219        .and_then(|entry| entry.text())
1220        .map_or(false, |maybe_url| {
1221            json_path.is_some() && maybe_url.strip_prefix("zed://settings/") == json_path
1222        });
1223
1224    let (link_icon, link_icon_color) = if clipboard_has_link {
1225        (IconName::Check, Color::Success)
1226    } else {
1227        (IconName::Link, Color::Muted)
1228    };
1229
1230    div()
1231        .absolute()
1232        .top(rems_from_px(18.))
1233        .map(|this| {
1234            if sub_field {
1235                this.visible_on_hover("setting-sub-item")
1236                    .left(rems_from_px(-8.5))
1237            } else {
1238                this.visible_on_hover("setting-item")
1239                    .left(rems_from_px(-22.))
1240            }
1241        })
1242        .child(
1243            IconButton::new((id.into(), "copy-link-btn"), link_icon)
1244                .icon_color(link_icon_color)
1245                .icon_size(IconSize::Small)
1246                .shape(IconButtonShape::Square)
1247                .tooltip(Tooltip::text("Copy Link"))
1248                .when_some(json_path, |this, path| {
1249                    this.on_click(cx.listener(move |_, _, _, cx| {
1250                        let link = format!("zed://settings/{}", path);
1251                        cx.write_to_clipboard(ClipboardItem::new_string(link));
1252                        cx.notify();
1253                    }))
1254                }),
1255        )
1256}
1257
1258struct SettingItem {
1259    title: &'static str,
1260    description: &'static str,
1261    field: Box<dyn AnySettingField>,
1262    metadata: Option<Box<SettingsFieldMetadata>>,
1263    files: FileMask,
1264}
1265
1266struct DynamicItem {
1267    discriminant: SettingItem,
1268    pick_discriminant: fn(&SettingsContent) -> Option<usize>,
1269    fields: Vec<Vec<SettingItem>>,
1270}
1271
1272impl PartialEq for DynamicItem {
1273    fn eq(&self, other: &Self) -> bool {
1274        self.discriminant == other.discriminant && self.fields == other.fields
1275    }
1276}
1277
1278#[derive(PartialEq, Eq, Clone, Copy)]
1279struct FileMask(u8);
1280
1281impl std::fmt::Debug for FileMask {
1282    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1283        write!(f, "FileMask(")?;
1284        let mut items = vec![];
1285
1286        if self.contains(USER) {
1287            items.push("USER");
1288        }
1289        if self.contains(PROJECT) {
1290            items.push("LOCAL");
1291        }
1292        if self.contains(SERVER) {
1293            items.push("SERVER");
1294        }
1295
1296        write!(f, "{})", items.join(" | "))
1297    }
1298}
1299
1300const USER: FileMask = FileMask(1 << 0);
1301const PROJECT: FileMask = FileMask(1 << 2);
1302const SERVER: FileMask = FileMask(1 << 3);
1303
1304impl std::ops::BitAnd for FileMask {
1305    type Output = Self;
1306
1307    fn bitand(self, other: Self) -> Self {
1308        Self(self.0 & other.0)
1309    }
1310}
1311
1312impl std::ops::BitOr for FileMask {
1313    type Output = Self;
1314
1315    fn bitor(self, other: Self) -> Self {
1316        Self(self.0 | other.0)
1317    }
1318}
1319
1320impl FileMask {
1321    fn contains(&self, other: FileMask) -> bool {
1322        self.0 & other.0 != 0
1323    }
1324}
1325
1326impl PartialEq for SettingItem {
1327    fn eq(&self, other: &Self) -> bool {
1328        self.title == other.title
1329            && self.description == other.description
1330            && (match (&self.metadata, &other.metadata) {
1331                (None, None) => true,
1332                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1333                _ => false,
1334            })
1335    }
1336}
1337
1338#[derive(Clone, PartialEq, Default)]
1339enum SubPageType {
1340    Language,
1341    #[default]
1342    Other,
1343}
1344
1345#[derive(Clone)]
1346struct SubPageLink {
1347    title: SharedString,
1348    r#type: SubPageType,
1349    description: Option<SharedString>,
1350    /// See [`SettingField.json_path`]
1351    json_path: Option<&'static str>,
1352    /// Whether or not the settings in this sub page are configurable in settings.json
1353    /// Removes the "Edit in settings.json" button from the page.
1354    in_json: bool,
1355    files: FileMask,
1356    render:
1357        fn(&SettingsWindow, &ScrollHandle, &mut Window, &mut Context<SettingsWindow>) -> AnyElement,
1358}
1359
1360impl PartialEq for SubPageLink {
1361    fn eq(&self, other: &Self) -> bool {
1362        self.title == other.title
1363    }
1364}
1365
1366#[derive(Clone)]
1367struct ActionLink {
1368    title: SharedString,
1369    description: Option<SharedString>,
1370    button_text: SharedString,
1371    on_click: Arc<dyn Fn(&mut SettingsWindow, &mut Window, &mut App) + Send + Sync>,
1372}
1373
1374impl PartialEq for ActionLink {
1375    fn eq(&self, other: &Self) -> bool {
1376        self.title == other.title
1377    }
1378}
1379
1380fn all_language_names(cx: &App) -> Vec<SharedString> {
1381    workspace::AppState::global(cx)
1382        .upgrade()
1383        .map_or(vec![], |state| {
1384            state
1385                .languages
1386                .language_names()
1387                .into_iter()
1388                .filter(|name| name.as_ref() != "Zed Keybind Context")
1389                .map(Into::into)
1390                .collect()
1391        })
1392}
1393
1394#[allow(unused)]
1395#[derive(Clone, PartialEq, Debug)]
1396enum SettingsUiFile {
1397    User,                                // Uses all settings.
1398    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1399    Server(&'static str),                // Uses a special name, and the user settings
1400}
1401
1402impl SettingsUiFile {
1403    fn setting_type(&self) -> &'static str {
1404        match self {
1405            SettingsUiFile::User => "User",
1406            SettingsUiFile::Project(_) => "Project",
1407            SettingsUiFile::Server(_) => "Server",
1408        }
1409    }
1410
1411    fn is_server(&self) -> bool {
1412        matches!(self, SettingsUiFile::Server(_))
1413    }
1414
1415    fn worktree_id(&self) -> Option<WorktreeId> {
1416        match self {
1417            SettingsUiFile::User => None,
1418            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1419            SettingsUiFile::Server(_) => None,
1420        }
1421    }
1422
1423    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1424        Some(match file {
1425            settings::SettingsFile::User => SettingsUiFile::User,
1426            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1427            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1428            settings::SettingsFile::Default => return None,
1429            settings::SettingsFile::Global => return None,
1430        })
1431    }
1432
1433    fn to_settings(&self) -> settings::SettingsFile {
1434        match self {
1435            SettingsUiFile::User => settings::SettingsFile::User,
1436            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1437            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1438        }
1439    }
1440
1441    fn mask(&self) -> FileMask {
1442        match self {
1443            SettingsUiFile::User => USER,
1444            SettingsUiFile::Project(_) => PROJECT,
1445            SettingsUiFile::Server(_) => SERVER,
1446        }
1447    }
1448}
1449
1450impl SettingsWindow {
1451    fn new(
1452        original_window: Option<WindowHandle<Workspace>>,
1453        window: &mut Window,
1454        cx: &mut Context<Self>,
1455    ) -> Self {
1456        let font_family_cache = theme::FontFamilyCache::global(cx);
1457
1458        cx.spawn(async move |this, cx| {
1459            font_family_cache.prefetch(cx).await;
1460            this.update(cx, |_, cx| {
1461                cx.notify();
1462            })
1463        })
1464        .detach();
1465
1466        let current_file = SettingsUiFile::User;
1467        let search_bar = cx.new(|cx| {
1468            let mut editor = Editor::single_line(window, cx);
1469            editor.set_placeholder_text("Search settings…", window, cx);
1470            editor
1471        });
1472        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1473            let EditorEvent::Edited { transaction_id: _ } = event else {
1474                return;
1475            };
1476
1477            if this.opening_link {
1478                this.opening_link = false;
1479                return;
1480            }
1481            this.update_matches(cx);
1482        })
1483        .detach();
1484
1485        let mut ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1486        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1487            this.fetch_files(window, cx);
1488
1489            // Whenever settings are changed, it's possible that the changed
1490            // settings affects the rendering of the `SettingsWindow`, like is
1491            // the case with `ui_font_size`. When that happens, we need to
1492            // instruct the `ListState` to re-measure the list items, as the
1493            // list item heights may have changed depending on the new font
1494            // size.
1495            let new_ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1496            if new_ui_font_size != ui_font_size {
1497                this.list_state.remeasure();
1498                ui_font_size = new_ui_font_size;
1499            }
1500
1501            cx.notify();
1502        })
1503        .detach();
1504
1505        cx.on_window_closed(|cx| {
1506            if let Some(existing_window) = cx
1507                .windows()
1508                .into_iter()
1509                .find_map(|window| window.downcast::<SettingsWindow>())
1510                && cx.windows().len() == 1
1511            {
1512                cx.update_window(*existing_window, |_, window, _| {
1513                    window.remove_window();
1514                })
1515                .ok();
1516
1517                telemetry::event!("Settings Closed")
1518            }
1519        })
1520        .detach();
1521
1522        if let Some(app_state) = AppState::global(cx).upgrade() {
1523            for project in app_state
1524                .workspace_store
1525                .read(cx)
1526                .workspaces()
1527                .iter()
1528                .filter_map(|space| {
1529                    space
1530                        .read(cx)
1531                        .ok()
1532                        .map(|workspace| workspace.project().clone())
1533                })
1534                .collect::<Vec<_>>()
1535            {
1536                cx.observe_release_in(&project, window, |this, _, window, cx| {
1537                    this.fetch_files(window, cx)
1538                })
1539                .detach();
1540                cx.subscribe_in(&project, window, Self::handle_project_event)
1541                    .detach();
1542            }
1543
1544            for workspace in app_state
1545                .workspace_store
1546                .read(cx)
1547                .workspaces()
1548                .iter()
1549                .filter_map(|space| space.entity(cx).ok())
1550            {
1551                cx.observe_release_in(&workspace, window, |this, _, window, cx| {
1552                    this.fetch_files(window, cx)
1553                })
1554                .detach();
1555            }
1556        } else {
1557            log::error!("App state doesn't exist when creating a new settings window");
1558        }
1559
1560        let this_weak = cx.weak_entity();
1561        cx.observe_new::<Project>({
1562            let this_weak = this_weak.clone();
1563
1564            move |_, window, cx| {
1565                let project = cx.entity();
1566                let Some(window) = window else {
1567                    return;
1568                };
1569
1570                this_weak
1571                    .update(cx, |this, cx| {
1572                        this.fetch_files(window, cx);
1573                        cx.observe_release_in(&project, window, |_, _, window, cx| {
1574                            cx.defer_in(window, |this, window, cx| this.fetch_files(window, cx));
1575                        })
1576                        .detach();
1577
1578                        cx.subscribe_in(&project, window, Self::handle_project_event)
1579                            .detach();
1580                    })
1581                    .ok();
1582            }
1583        })
1584        .detach();
1585
1586        let handle = window.window_handle();
1587        cx.observe_new::<Workspace>(move |workspace, _, cx| {
1588            let project = workspace.project().clone();
1589            let this_weak = this_weak.clone();
1590
1591            // We defer on the settings window (via `handle`) rather than using
1592            // the workspace's window from observe_new. When window.defer() runs
1593            // its callback, it calls handle.update() which temporarily removes
1594            // that window from cx.windows. If we deferred on the workspace's
1595            // window, then when fetch_files() tries to read ALL workspaces from
1596            // the store (including the newly created one), it would fail with
1597            // "window not found" because that workspace's window would be
1598            // temporarily removed from cx.windows for the duration of our callback.
1599            handle
1600                .update(cx, move |_, window, cx| {
1601                    window.defer(cx, move |window, cx| {
1602                        this_weak
1603                            .update(cx, |this, cx| {
1604                                this.fetch_files(window, cx);
1605                                cx.observe_release_in(&project, window, |this, _, window, cx| {
1606                                    this.fetch_files(window, cx)
1607                                })
1608                                .detach();
1609                            })
1610                            .ok();
1611                    });
1612                })
1613                .ok();
1614        })
1615        .detach();
1616
1617        let title_bar = if !cfg!(target_os = "macos") {
1618            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1619        } else {
1620            None
1621        };
1622
1623        let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1624        list_state.set_scroll_handler(|_, _, _| {});
1625
1626        let mut this = Self {
1627            title_bar,
1628            original_window,
1629
1630            worktree_root_dirs: HashMap::default(),
1631            files: vec![],
1632
1633            current_file: current_file,
1634            project_setting_file_buffers: HashMap::default(),
1635            pages: vec![],
1636            sub_page_stack: vec![],
1637            opening_link: false,
1638            navbar_entries: vec![],
1639            navbar_entry: 0,
1640            navbar_scroll_handle: UniformListScrollHandle::default(),
1641            search_bar,
1642            search_task: None,
1643            filter_table: vec![],
1644            has_query: false,
1645            content_handles: vec![],
1646            focus_handle: cx.focus_handle(),
1647            navbar_focus_handle: NonFocusableHandle::new(
1648                NAVBAR_CONTAINER_TAB_INDEX,
1649                false,
1650                window,
1651                cx,
1652            ),
1653            navbar_focus_subscriptions: vec![],
1654            content_focus_handle: NonFocusableHandle::new(
1655                CONTENT_CONTAINER_TAB_INDEX,
1656                false,
1657                window,
1658                cx,
1659            ),
1660            files_focus_handle: cx
1661                .focus_handle()
1662                .tab_index(HEADER_CONTAINER_TAB_INDEX)
1663                .tab_stop(false),
1664            search_index: None,
1665            shown_errors: HashSet::default(),
1666            regex_validation_error: None,
1667            list_state,
1668        };
1669
1670        this.fetch_files(window, cx);
1671        this.build_ui(window, cx);
1672        this.build_search_index();
1673
1674        this.search_bar.update(cx, |editor, cx| {
1675            editor.focus_handle(cx).focus(window, cx);
1676        });
1677
1678        this
1679    }
1680
1681    fn handle_project_event(
1682        &mut self,
1683        _: &Entity<Project>,
1684        event: &project::Event,
1685        window: &mut Window,
1686        cx: &mut Context<SettingsWindow>,
1687    ) {
1688        match event {
1689            project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1690                cx.defer_in(window, |this, window, cx| {
1691                    this.fetch_files(window, cx);
1692                });
1693            }
1694            _ => {}
1695        }
1696    }
1697
1698    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1699        // We can only toggle root entries
1700        if !self.navbar_entries[nav_entry_index].is_root {
1701            return;
1702        }
1703
1704        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1705        *expanded = !*expanded;
1706        self.navbar_entry = nav_entry_index;
1707        self.reset_list_state();
1708    }
1709
1710    fn build_navbar(&mut self, cx: &App) {
1711        let mut navbar_entries = Vec::new();
1712
1713        for (page_index, page) in self.pages.iter().enumerate() {
1714            navbar_entries.push(NavBarEntry {
1715                title: page.title,
1716                is_root: true,
1717                expanded: false,
1718                page_index,
1719                item_index: None,
1720                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1721            });
1722
1723            for (item_index, item) in page.items.iter().enumerate() {
1724                let SettingsPageItem::SectionHeader(title) = item else {
1725                    continue;
1726                };
1727                navbar_entries.push(NavBarEntry {
1728                    title,
1729                    is_root: false,
1730                    expanded: false,
1731                    page_index,
1732                    item_index: Some(item_index),
1733                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1734                });
1735            }
1736        }
1737
1738        self.navbar_entries = navbar_entries;
1739    }
1740
1741    fn setup_navbar_focus_subscriptions(
1742        &mut self,
1743        window: &mut Window,
1744        cx: &mut Context<SettingsWindow>,
1745    ) {
1746        let mut focus_subscriptions = Vec::new();
1747
1748        for entry_index in 0..self.navbar_entries.len() {
1749            let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1750
1751            let subscription = cx.on_focus(
1752                &focus_handle,
1753                window,
1754                move |this: &mut SettingsWindow,
1755                      window: &mut Window,
1756                      cx: &mut Context<SettingsWindow>| {
1757                    this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1758                },
1759            );
1760            focus_subscriptions.push(subscription);
1761        }
1762        self.navbar_focus_subscriptions = focus_subscriptions;
1763    }
1764
1765    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1766        let mut index = 0;
1767        let entries = &self.navbar_entries;
1768        let search_matches = &self.filter_table;
1769        let has_query = self.has_query;
1770        std::iter::from_fn(move || {
1771            while index < entries.len() {
1772                let entry = &entries[index];
1773                let included_in_search = if let Some(item_index) = entry.item_index {
1774                    search_matches[entry.page_index][item_index]
1775                } else {
1776                    search_matches[entry.page_index].iter().any(|b| *b)
1777                        || search_matches[entry.page_index].is_empty()
1778                };
1779                if included_in_search {
1780                    break;
1781                }
1782                index += 1;
1783            }
1784            if index >= self.navbar_entries.len() {
1785                return None;
1786            }
1787            let entry = &entries[index];
1788            let entry_index = index;
1789
1790            index += 1;
1791            if entry.is_root && !entry.expanded && !has_query {
1792                while index < entries.len() {
1793                    if entries[index].is_root {
1794                        break;
1795                    }
1796                    index += 1;
1797                }
1798            }
1799
1800            return Some((entry_index, entry));
1801        })
1802    }
1803
1804    fn filter_matches_to_file(&mut self) {
1805        let current_file = self.current_file.mask();
1806        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1807            let mut header_index = 0;
1808            let mut any_found_since_last_header = true;
1809
1810            for (index, item) in page.items.iter().enumerate() {
1811                match item {
1812                    SettingsPageItem::SectionHeader(_) => {
1813                        if !any_found_since_last_header {
1814                            page_filter[header_index] = false;
1815                        }
1816                        header_index = index;
1817                        any_found_since_last_header = false;
1818                    }
1819                    SettingsPageItem::SettingItem(SettingItem { files, .. })
1820                    | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1821                    | SettingsPageItem::DynamicItem(DynamicItem {
1822                        discriminant: SettingItem { files, .. },
1823                        ..
1824                    }) => {
1825                        if !files.contains(current_file) {
1826                            page_filter[index] = false;
1827                        } else {
1828                            any_found_since_last_header = true;
1829                        }
1830                    }
1831                    SettingsPageItem::ActionLink(_) => {
1832                        any_found_since_last_header = true;
1833                    }
1834                }
1835            }
1836            if let Some(last_header) = page_filter.get_mut(header_index)
1837                && !any_found_since_last_header
1838            {
1839                *last_header = false;
1840            }
1841        }
1842    }
1843
1844    fn filter_by_json_path(&self, query: &str) -> Vec<usize> {
1845        let Some(path) = query.strip_prefix('#') else {
1846            return vec![];
1847        };
1848        let Some(search_index) = self.search_index.as_ref() else {
1849            return vec![];
1850        };
1851        let mut indices = vec![];
1852        for (index, SearchKeyLUTEntry { json_path, .. }) in search_index.key_lut.iter().enumerate()
1853        {
1854            let Some(json_path) = json_path else {
1855                continue;
1856            };
1857
1858            if let Some(post) = json_path.strip_prefix(path)
1859                && (post.is_empty() || post.starts_with('.'))
1860            {
1861                indices.push(index);
1862            }
1863        }
1864        indices
1865    }
1866
1867    fn apply_match_indices(&mut self, match_indices: impl Iterator<Item = usize>) {
1868        let Some(search_index) = self.search_index.as_ref() else {
1869            return;
1870        };
1871
1872        for page in &mut self.filter_table {
1873            page.fill(false);
1874        }
1875
1876        for match_index in match_indices {
1877            let SearchKeyLUTEntry {
1878                page_index,
1879                header_index,
1880                item_index,
1881                ..
1882            } = search_index.key_lut[match_index];
1883            let page = &mut self.filter_table[page_index];
1884            page[header_index] = true;
1885            page[item_index] = true;
1886        }
1887        self.has_query = true;
1888        self.filter_matches_to_file();
1889        self.open_first_nav_page();
1890        self.reset_list_state();
1891    }
1892
1893    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1894        self.search_task.take();
1895        let query = self.search_bar.read(cx).text(cx);
1896        if query.is_empty() || self.search_index.is_none() {
1897            for page in &mut self.filter_table {
1898                page.fill(true);
1899            }
1900            self.has_query = false;
1901            self.filter_matches_to_file();
1902            self.reset_list_state();
1903            cx.notify();
1904            return;
1905        }
1906
1907        let is_json_link_query = query.starts_with("#");
1908        if is_json_link_query {
1909            let indices = self.filter_by_json_path(&query);
1910            if !indices.is_empty() {
1911                self.apply_match_indices(indices.into_iter());
1912                cx.notify();
1913                return;
1914            }
1915        }
1916
1917        let search_index = self.search_index.as_ref().unwrap().clone();
1918
1919        self.search_task = Some(cx.spawn(async move |this, cx| {
1920            let bm25_task = cx.background_spawn({
1921                let search_index = search_index.clone();
1922                let max_results = search_index.key_lut.len();
1923                let query = query.clone();
1924                async move { search_index.bm25_engine.search(&query, max_results) }
1925            });
1926            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1927            let fuzzy_search_task = fuzzy::match_strings(
1928                search_index.fuzzy_match_candidates.as_slice(),
1929                &query,
1930                false,
1931                true,
1932                search_index.fuzzy_match_candidates.len(),
1933                &cancel_flag,
1934                cx.background_executor().clone(),
1935            );
1936
1937            let fuzzy_matches = fuzzy_search_task.await;
1938            // PERF:
1939            // If results are slow to appear, we should:
1940            // - return to the structure we had previously where we wait on fuzzy matches first (they resolve quickly) with a min match score of 0.3
1941            // - wait on bm25 and replace fuzzy matches with bm25 matches
1942            // - to deal with lack of fuzzyness with bm25 searches however, we should keep the fuzzy matches around, and merge fuzzy matches with high score (>0.75?) into bm25 results
1943            let bm25_matches = bm25_task.await;
1944
1945            _ = this
1946                .update(cx, |this, cx| {
1947                    // For tuning the score threshold
1948                    // for fuzzy_match in &fuzzy_matches {
1949                    //     let SearchItemKey {
1950                    //         page_index,
1951                    //         header_index,
1952                    //         item_index,
1953                    //     } = search_index.key_lut[fuzzy_match.candidate_id];
1954                    //     let SettingsPageItem::SectionHeader(header) =
1955                    //         this.pages[page_index].items[header_index]
1956                    //     else {
1957                    //         continue;
1958                    //     };
1959                    //     let SettingsPageItem::SettingItem(SettingItem {
1960                    //         title, description, ..
1961                    //     }) = this.pages[page_index].items[item_index]
1962                    //     else {
1963                    //         continue;
1964                    //     };
1965                    //     let score = fuzzy_match.score;
1966                    //     eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1967                    // }
1968                    let fuzzy_indices = fuzzy_matches
1969                        .into_iter()
1970                        // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1971                        // flexible enough to catch misspellings and <4 letter queries
1972                        .take_while(|fuzzy_match| fuzzy_match.score >= 0.5)
1973                        .map(|fuzzy_match| fuzzy_match.candidate_id);
1974                    let bm25_indices = bm25_matches
1975                        .into_iter()
1976                        .map(|bm25_match| bm25_match.document.id);
1977                    let merged_indices = bm25_indices.chain(fuzzy_indices);
1978
1979                    this.apply_match_indices(merged_indices);
1980                    cx.notify();
1981                })
1982                .ok();
1983
1984            cx.background_executor().timer(Duration::from_secs(1)).await;
1985            telemetry::event!("Settings Searched", query = query)
1986        }));
1987    }
1988
1989    fn build_filter_table(&mut self) {
1990        self.filter_table = self
1991            .pages
1992            .iter()
1993            .map(|page| vec![true; page.items.len()])
1994            .collect::<Vec<_>>();
1995    }
1996
1997    fn build_search_index(&mut self) {
1998        let mut key_lut: Vec<SearchKeyLUTEntry> = vec![];
1999        let mut documents = Vec::default();
2000        let mut fuzzy_match_candidates = Vec::default();
2001
2002        fn push_candidates(
2003            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
2004            key_index: usize,
2005            input: &str,
2006        ) {
2007            for word in input.split_ascii_whitespace() {
2008                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
2009            }
2010        }
2011
2012        // PERF: We are currently searching all items even in project files
2013        // where many settings are filtered out, using the logic in filter_matches_to_file
2014        // we could only search relevant items based on the current file
2015        for (page_index, page) in self.pages.iter().enumerate() {
2016            let mut header_index = 0;
2017            let mut header_str = "";
2018            for (item_index, item) in page.items.iter().enumerate() {
2019                let key_index = key_lut.len();
2020                let mut json_path = None;
2021                match item {
2022                    SettingsPageItem::DynamicItem(DynamicItem {
2023                        discriminant: item, ..
2024                    })
2025                    | SettingsPageItem::SettingItem(item) => {
2026                        json_path = item
2027                            .field
2028                            .json_path()
2029                            .map(|path| path.trim_end_matches('$'));
2030                        documents.push(bm25::Document {
2031                            id: key_index,
2032                            contents: [page.title, header_str, item.title, item.description]
2033                                .join("\n"),
2034                        });
2035                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
2036                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
2037                    }
2038                    SettingsPageItem::SectionHeader(header) => {
2039                        documents.push(bm25::Document {
2040                            id: key_index,
2041                            contents: header.to_string(),
2042                        });
2043                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
2044                        header_index = item_index;
2045                        header_str = *header;
2046                    }
2047                    SettingsPageItem::SubPageLink(sub_page_link) => {
2048                        json_path = sub_page_link.json_path;
2049                        documents.push(bm25::Document {
2050                            id: key_index,
2051                            contents: [page.title, header_str, sub_page_link.title.as_ref()]
2052                                .join("\n"),
2053                        });
2054                        push_candidates(
2055                            &mut fuzzy_match_candidates,
2056                            key_index,
2057                            sub_page_link.title.as_ref(),
2058                        );
2059                    }
2060                    SettingsPageItem::ActionLink(action_link) => {
2061                        documents.push(bm25::Document {
2062                            id: key_index,
2063                            contents: [page.title, header_str, action_link.title.as_ref()]
2064                                .join("\n"),
2065                        });
2066                        push_candidates(
2067                            &mut fuzzy_match_candidates,
2068                            key_index,
2069                            action_link.title.as_ref(),
2070                        );
2071                    }
2072                }
2073                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
2074                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
2075
2076                key_lut.push(SearchKeyLUTEntry {
2077                    page_index,
2078                    header_index,
2079                    item_index,
2080                    json_path,
2081                });
2082            }
2083        }
2084        let engine =
2085            bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
2086        self.search_index = Some(Arc::new(SearchIndex {
2087            bm25_engine: engine,
2088            key_lut,
2089            fuzzy_match_candidates,
2090        }));
2091    }
2092
2093    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2094        self.content_handles = self
2095            .pages
2096            .iter()
2097            .map(|page| {
2098                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
2099                    .take(page.items.len())
2100                    .collect()
2101            })
2102            .collect::<Vec<_>>();
2103    }
2104
2105    fn reset_list_state(&mut self) {
2106        let mut visible_items_count = self.visible_page_items().count();
2107
2108        if visible_items_count > 0 {
2109            // show page title if page is non empty
2110            visible_items_count += 1;
2111        }
2112
2113        self.list_state.reset(visible_items_count);
2114    }
2115
2116    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2117        if self.pages.is_empty() {
2118            self.pages = page_data::settings_data(cx);
2119            self.build_navbar(cx);
2120            self.setup_navbar_focus_subscriptions(window, cx);
2121            self.build_content_handles(window, cx);
2122        }
2123        self.sub_page_stack.clear();
2124        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
2125        self.build_filter_table();
2126        self.reset_list_state();
2127        self.update_matches(cx);
2128
2129        cx.notify();
2130    }
2131
2132    #[track_caller]
2133    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2134        self.worktree_root_dirs.clear();
2135        let prev_files = self.files.clone();
2136        let settings_store = cx.global::<SettingsStore>();
2137        let mut ui_files = vec![];
2138        let mut all_files = settings_store.get_all_files();
2139        if !all_files.contains(&settings::SettingsFile::User) {
2140            all_files.push(settings::SettingsFile::User);
2141        }
2142        for file in all_files {
2143            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
2144                continue;
2145            };
2146            if settings_ui_file.is_server() {
2147                continue;
2148            }
2149
2150            if let Some(worktree_id) = settings_ui_file.worktree_id() {
2151                let directory_name = all_projects(self.original_window.as_ref(), cx)
2152                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
2153                    .map(|worktree| worktree.read(cx).root_name());
2154
2155                let Some(directory_name) = directory_name else {
2156                    log::error!(
2157                        "No directory name found for settings file at worktree ID: {}",
2158                        worktree_id
2159                    );
2160                    continue;
2161                };
2162
2163                self.worktree_root_dirs
2164                    .insert(worktree_id, directory_name.as_unix_str().to_string());
2165            }
2166
2167            let focus_handle = prev_files
2168                .iter()
2169                .find_map(|(prev_file, handle)| {
2170                    (prev_file == &settings_ui_file).then(|| handle.clone())
2171                })
2172                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
2173            ui_files.push((settings_ui_file, focus_handle));
2174        }
2175
2176        ui_files.reverse();
2177
2178        let mut missing_worktrees = Vec::new();
2179
2180        for worktree in all_projects(self.original_window.as_ref(), cx)
2181            .flat_map(|project| project.read(cx).visible_worktrees(cx))
2182            .filter(|tree| !self.worktree_root_dirs.contains_key(&tree.read(cx).id()))
2183        {
2184            let worktree = worktree.read(cx);
2185            let worktree_id = worktree.id();
2186            let Some(directory_name) = worktree.root_dir().and_then(|file| {
2187                file.file_name()
2188                    .map(|os_string| os_string.to_string_lossy().to_string())
2189            }) else {
2190                continue;
2191            };
2192
2193            missing_worktrees.push((worktree_id, directory_name.clone()));
2194            let path = RelPath::empty().to_owned().into_arc();
2195
2196            let settings_ui_file = SettingsUiFile::Project((worktree_id, path));
2197
2198            let focus_handle = prev_files
2199                .iter()
2200                .find_map(|(prev_file, handle)| {
2201                    (prev_file == &settings_ui_file).then(|| handle.clone())
2202                })
2203                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
2204
2205            ui_files.push((settings_ui_file, focus_handle));
2206        }
2207
2208        self.worktree_root_dirs.extend(missing_worktrees);
2209
2210        self.files = ui_files;
2211        let current_file_still_exists = self
2212            .files
2213            .iter()
2214            .any(|(file, _)| file == &self.current_file);
2215        if !current_file_still_exists {
2216            self.change_file(0, window, cx);
2217        }
2218    }
2219
2220    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
2221        if !self.is_nav_entry_visible(navbar_entry) {
2222            self.open_first_nav_page();
2223        }
2224
2225        let is_new_page = self.navbar_entries[self.navbar_entry].page_index
2226            != self.navbar_entries[navbar_entry].page_index;
2227        self.navbar_entry = navbar_entry;
2228
2229        // We only need to reset visible items when updating matches
2230        // and selecting a new page
2231        if is_new_page {
2232            self.reset_list_state();
2233        }
2234
2235        self.sub_page_stack.clear();
2236    }
2237
2238    fn open_first_nav_page(&mut self) {
2239        let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
2240        else {
2241            return;
2242        };
2243        self.open_navbar_entry_page(first_navbar_entry_index);
2244    }
2245
2246    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2247        if ix >= self.files.len() {
2248            self.current_file = SettingsUiFile::User;
2249            self.build_ui(window, cx);
2250            return;
2251        }
2252
2253        if self.files[ix].0 == self.current_file {
2254            return;
2255        }
2256        self.current_file = self.files[ix].0.clone();
2257
2258        if let SettingsUiFile::Project((_, _)) = &self.current_file {
2259            telemetry::event!("Setting Project Clicked");
2260        }
2261
2262        self.build_ui(window, cx);
2263
2264        if self
2265            .visible_navbar_entries()
2266            .any(|(index, _)| index == self.navbar_entry)
2267        {
2268            self.open_and_scroll_to_navbar_entry(self.navbar_entry, None, true, window, cx);
2269        } else {
2270            self.open_first_nav_page();
2271        };
2272    }
2273
2274    fn render_files_header(
2275        &self,
2276        window: &mut Window,
2277        cx: &mut Context<SettingsWindow>,
2278    ) -> impl IntoElement {
2279        static OVERFLOW_LIMIT: usize = 1;
2280
2281        let file_button =
2282            |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
2283                Button::new(
2284                    ix,
2285                    self.display_name(&file)
2286                        .expect("Files should always have a name"),
2287                )
2288                .toggle_state(file == &self.current_file)
2289                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
2290                .track_focus(focus_handle)
2291                .on_click(cx.listener({
2292                    let focus_handle = focus_handle.clone();
2293                    move |this, _: &gpui::ClickEvent, window, cx| {
2294                        this.change_file(ix, window, cx);
2295                        focus_handle.focus(window, cx);
2296                    }
2297                }))
2298            };
2299
2300        let this = cx.entity();
2301
2302        let selected_file_ix = self
2303            .files
2304            .iter()
2305            .enumerate()
2306            .skip(OVERFLOW_LIMIT)
2307            .find_map(|(ix, (file, _))| {
2308                if file == &self.current_file {
2309                    Some(ix)
2310                } else {
2311                    None
2312                }
2313            })
2314            .unwrap_or(OVERFLOW_LIMIT);
2315        let edit_in_json_id = SharedString::new(format!("edit-in-json-{}", selected_file_ix));
2316
2317        h_flex()
2318            .w_full()
2319            .gap_1()
2320            .justify_between()
2321            .track_focus(&self.files_focus_handle)
2322            .tab_group()
2323            .tab_index(HEADER_GROUP_TAB_INDEX)
2324            .child(
2325                h_flex()
2326                    .gap_1()
2327                    .children(
2328                        self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
2329                            |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
2330                        ),
2331                    )
2332                    .when(self.files.len() > OVERFLOW_LIMIT, |div| {
2333                        let (file, focus_handle) = &self.files[selected_file_ix];
2334
2335                        div.child(file_button(selected_file_ix, file, focus_handle, cx))
2336                            .when(self.files.len() > OVERFLOW_LIMIT + 1, |div| {
2337                                div.child(
2338                                    DropdownMenu::new(
2339                                        "more-files",
2340                                        format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
2341                                        ContextMenu::build(window, cx, move |mut menu, _, _| {
2342                                            for (mut ix, (file, focus_handle)) in self
2343                                                .files
2344                                                .iter()
2345                                                .enumerate()
2346                                                .skip(OVERFLOW_LIMIT + 1)
2347                                            {
2348                                                let (display_name, focus_handle) =
2349                                                    if selected_file_ix == ix {
2350                                                        ix = OVERFLOW_LIMIT;
2351                                                        (
2352                                                            self.display_name(&self.files[ix].0),
2353                                                            self.files[ix].1.clone(),
2354                                                        )
2355                                                    } else {
2356                                                        (
2357                                                            self.display_name(&file),
2358                                                            focus_handle.clone(),
2359                                                        )
2360                                                    };
2361
2362                                                menu = menu.entry(
2363                                                    display_name
2364                                                        .expect("Files should always have a name"),
2365                                                    None,
2366                                                    {
2367                                                        let this = this.clone();
2368                                                        move |window, cx| {
2369                                                            this.update(cx, |this, cx| {
2370                                                                this.change_file(ix, window, cx);
2371                                                            });
2372                                                            focus_handle.focus(window, cx);
2373                                                        }
2374                                                    },
2375                                                );
2376                                            }
2377
2378                                            menu
2379                                        }),
2380                                    )
2381                                    .style(DropdownStyle::Subtle)
2382                                    .trigger_tooltip(Tooltip::text("View Other Projects"))
2383                                    .trigger_icon(IconName::ChevronDown)
2384                                    .attach(gpui::Corner::BottomLeft)
2385                                    .offset(gpui::Point {
2386                                        x: px(0.0),
2387                                        y: px(2.0),
2388                                    })
2389                                    .tab_index(0),
2390                                )
2391                            })
2392                    }),
2393            )
2394            .child(
2395                Button::new(edit_in_json_id, "Edit in settings.json")
2396                    .tab_index(0_isize)
2397                    .style(ButtonStyle::OutlinedGhost)
2398                    .tooltip(Tooltip::for_action_title_in(
2399                        "Edit in settings.json",
2400                        &OpenCurrentFile,
2401                        &self.focus_handle,
2402                    ))
2403                    .on_click(cx.listener(|this, _, window, cx| {
2404                        this.open_current_settings_file(window, cx);
2405                    })),
2406            )
2407    }
2408
2409    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
2410        match file {
2411            SettingsUiFile::User => Some("User".to_string()),
2412            SettingsUiFile::Project((worktree_id, path)) => self
2413                .worktree_root_dirs
2414                .get(&worktree_id)
2415                .map(|directory_name| {
2416                    let path_style = PathStyle::local();
2417                    if path.is_empty() {
2418                        directory_name.clone()
2419                    } else {
2420                        format!(
2421                            "{}{}{}",
2422                            directory_name,
2423                            path_style.primary_separator(),
2424                            path.display(path_style)
2425                        )
2426                    }
2427                }),
2428            SettingsUiFile::Server(file) => Some(file.to_string()),
2429        }
2430    }
2431
2432    // TODO:
2433    //  Reconsider this after preview launch
2434    // fn file_location_str(&self) -> String {
2435    //     match &self.current_file {
2436    //         SettingsUiFile::User => "settings.json".to_string(),
2437    //         SettingsUiFile::Project((worktree_id, path)) => self
2438    //             .worktree_root_dirs
2439    //             .get(&worktree_id)
2440    //             .map(|directory_name| {
2441    //                 let path_style = PathStyle::local();
2442    //                 let file_path = path.join(paths::local_settings_file_relative_path());
2443    //                 format!(
2444    //                     "{}{}{}",
2445    //                     directory_name,
2446    //                     path_style.separator(),
2447    //                     file_path.display(path_style)
2448    //                 )
2449    //             })
2450    //             .expect("Current file should always be present in root dir map"),
2451    //         SettingsUiFile::Server(file) => file.to_string(),
2452    //     }
2453    // }
2454
2455    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2456        h_flex()
2457            .py_1()
2458            .px_1p5()
2459            .mb_3()
2460            .gap_1p5()
2461            .rounded_sm()
2462            .bg(cx.theme().colors().editor_background)
2463            .border_1()
2464            .border_color(cx.theme().colors().border)
2465            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2466            .child(self.search_bar.clone())
2467    }
2468
2469    fn render_nav(
2470        &self,
2471        window: &mut Window,
2472        cx: &mut Context<SettingsWindow>,
2473    ) -> impl IntoElement {
2474        let visible_count = self.visible_navbar_entries().count();
2475
2476        let focus_keybind_label = if self
2477            .navbar_focus_handle
2478            .read(cx)
2479            .handle
2480            .contains_focused(window, cx)
2481            || self
2482                .visible_navbar_entries()
2483                .any(|(_, entry)| entry.focus_handle.is_focused(window))
2484        {
2485            "Focus Content"
2486        } else {
2487            "Focus Navbar"
2488        };
2489
2490        let mut key_context = KeyContext::new_with_defaults();
2491        key_context.add("NavigationMenu");
2492        key_context.add("menu");
2493        if self.search_bar.focus_handle(cx).is_focused(window) {
2494            key_context.add("search");
2495        }
2496
2497        v_flex()
2498            .key_context(key_context)
2499            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2500                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2501                    return;
2502                };
2503                let focused_entry_parent = this.root_entry_containing(focused_entry);
2504                if this.navbar_entries[focused_entry_parent].expanded {
2505                    this.toggle_navbar_entry(focused_entry_parent);
2506                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle, cx);
2507                }
2508                cx.notify();
2509            }))
2510            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2511                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2512                    return;
2513                };
2514                if !this.navbar_entries[focused_entry].is_root {
2515                    return;
2516                }
2517                if !this.navbar_entries[focused_entry].expanded {
2518                    this.toggle_navbar_entry(focused_entry);
2519                }
2520                cx.notify();
2521            }))
2522            .on_action(
2523                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2524                    let entry_index = this
2525                        .focused_nav_entry(window, cx)
2526                        .unwrap_or(this.navbar_entry);
2527                    let mut root_index = None;
2528                    for (index, entry) in this.visible_navbar_entries() {
2529                        if index >= entry_index {
2530                            break;
2531                        }
2532                        if entry.is_root {
2533                            root_index = Some(index);
2534                        }
2535                    }
2536                    let Some(previous_root_index) = root_index else {
2537                        return;
2538                    };
2539                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2540                }),
2541            )
2542            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2543                let entry_index = this
2544                    .focused_nav_entry(window, cx)
2545                    .unwrap_or(this.navbar_entry);
2546                let mut root_index = None;
2547                for (index, entry) in this.visible_navbar_entries() {
2548                    if index <= entry_index {
2549                        continue;
2550                    }
2551                    if entry.is_root {
2552                        root_index = Some(index);
2553                        break;
2554                    }
2555                }
2556                let Some(next_root_index) = root_index else {
2557                    return;
2558                };
2559                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2560            }))
2561            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2562                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2563                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2564                }
2565            }))
2566            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2567                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2568                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2569                }
2570            }))
2571            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2572                let entry_index = this
2573                    .focused_nav_entry(window, cx)
2574                    .unwrap_or(this.navbar_entry);
2575                let mut next_index = None;
2576                for (index, _) in this.visible_navbar_entries() {
2577                    if index > entry_index {
2578                        next_index = Some(index);
2579                        break;
2580                    }
2581                }
2582                let Some(next_entry_index) = next_index else {
2583                    return;
2584                };
2585                this.open_and_scroll_to_navbar_entry(
2586                    next_entry_index,
2587                    Some(gpui::ScrollStrategy::Bottom),
2588                    false,
2589                    window,
2590                    cx,
2591                );
2592            }))
2593            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2594                let entry_index = this
2595                    .focused_nav_entry(window, cx)
2596                    .unwrap_or(this.navbar_entry);
2597                let mut prev_index = None;
2598                for (index, _) in this.visible_navbar_entries() {
2599                    if index >= entry_index {
2600                        break;
2601                    }
2602                    prev_index = Some(index);
2603                }
2604                let Some(prev_entry_index) = prev_index else {
2605                    return;
2606                };
2607                this.open_and_scroll_to_navbar_entry(
2608                    prev_entry_index,
2609                    Some(gpui::ScrollStrategy::Top),
2610                    false,
2611                    window,
2612                    cx,
2613                );
2614            }))
2615            .w_56()
2616            .h_full()
2617            .p_2p5()
2618            .when(cfg!(target_os = "macos"), |this| this.pt_10())
2619            .flex_none()
2620            .border_r_1()
2621            .border_color(cx.theme().colors().border)
2622            .bg(cx.theme().colors().panel_background)
2623            .child(self.render_search(window, cx))
2624            .child(
2625                v_flex()
2626                    .flex_1()
2627                    .overflow_hidden()
2628                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2629                    .tab_group()
2630                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
2631                    .child(
2632                        uniform_list(
2633                            "settings-ui-nav-bar",
2634                            visible_count + 1,
2635                            cx.processor(move |this, range: Range<usize>, _, cx| {
2636                                this.visible_navbar_entries()
2637                                    .skip(range.start.saturating_sub(1))
2638                                    .take(range.len())
2639                                    .map(|(entry_index, entry)| {
2640                                        TreeViewItem::new(
2641                                            ("settings-ui-navbar-entry", entry_index),
2642                                            entry.title,
2643                                        )
2644                                        .track_focus(&entry.focus_handle)
2645                                        .root_item(entry.is_root)
2646                                        .toggle_state(this.is_navbar_entry_selected(entry_index))
2647                                        .when(entry.is_root, |item| {
2648                                            item.expanded(entry.expanded || this.has_query)
2649                                                .on_toggle(cx.listener(
2650                                                    move |this, _, window, cx| {
2651                                                        this.toggle_navbar_entry(entry_index);
2652                                                        window.focus(
2653                                                            &this.navbar_entries[entry_index]
2654                                                                .focus_handle,
2655                                                            cx,
2656                                                        );
2657                                                        cx.notify();
2658                                                    },
2659                                                ))
2660                                        })
2661                                        .on_click({
2662                                            let category = this.pages[entry.page_index].title;
2663                                            let subcategory =
2664                                                (!entry.is_root).then_some(entry.title);
2665
2666                                            cx.listener(move |this, _, window, cx| {
2667                                                telemetry::event!(
2668                                                    "Settings Navigation Clicked",
2669                                                    category = category,
2670                                                    subcategory = subcategory
2671                                                );
2672
2673                                                this.open_and_scroll_to_navbar_entry(
2674                                                    entry_index,
2675                                                    None,
2676                                                    true,
2677                                                    window,
2678                                                    cx,
2679                                                );
2680                                            })
2681                                        })
2682                                    })
2683                                    .collect()
2684                            }),
2685                        )
2686                        .size_full()
2687                        .track_scroll(&self.navbar_scroll_handle),
2688                    )
2689                    .vertical_scrollbar_for(&self.navbar_scroll_handle, window, cx),
2690            )
2691            .child(
2692                h_flex()
2693                    .w_full()
2694                    .h_8()
2695                    .p_2()
2696                    .pb_0p5()
2697                    .flex_shrink_0()
2698                    .border_t_1()
2699                    .border_color(cx.theme().colors().border_variant)
2700                    .child(
2701                        KeybindingHint::new(
2702                            KeyBinding::for_action_in(
2703                                &ToggleFocusNav,
2704                                &self.navbar_focus_handle.focus_handle(cx),
2705                                cx,
2706                            ),
2707                            cx.theme().colors().surface_background.opacity(0.5),
2708                        )
2709                        .suffix(focus_keybind_label),
2710                    ),
2711            )
2712    }
2713
2714    fn open_and_scroll_to_navbar_entry(
2715        &mut self,
2716        navbar_entry_index: usize,
2717        scroll_strategy: Option<gpui::ScrollStrategy>,
2718        focus_content: bool,
2719        window: &mut Window,
2720        cx: &mut Context<Self>,
2721    ) {
2722        self.open_navbar_entry_page(navbar_entry_index);
2723        cx.notify();
2724
2725        let mut handle_to_focus = None;
2726
2727        if self.navbar_entries[navbar_entry_index].is_root
2728            || !self.is_nav_entry_visible(navbar_entry_index)
2729        {
2730            if let Some(scroll_handle) = self.current_sub_page_scroll_handle() {
2731                scroll_handle.set_offset(point(px(0.), px(0.)));
2732            }
2733
2734            if focus_content {
2735                let Some(first_item_index) =
2736                    self.visible_page_items().next().map(|(index, _)| index)
2737                else {
2738                    return;
2739                };
2740                handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2741            } else if !self.is_nav_entry_visible(navbar_entry_index) {
2742                let Some(first_visible_nav_entry_index) =
2743                    self.visible_navbar_entries().next().map(|(index, _)| index)
2744                else {
2745                    return;
2746                };
2747                self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2748            } else {
2749                handle_to_focus =
2750                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2751            }
2752        } else {
2753            let entry_item_index = self.navbar_entries[navbar_entry_index]
2754                .item_index
2755                .expect("Non-root items should have an item index");
2756            self.scroll_to_content_item(entry_item_index, window, cx);
2757            if focus_content {
2758                handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2759            } else {
2760                handle_to_focus =
2761                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2762            }
2763        }
2764
2765        if let Some(scroll_strategy) = scroll_strategy
2766            && let Some(logical_entry_index) = self
2767                .visible_navbar_entries()
2768                .into_iter()
2769                .position(|(index, _)| index == navbar_entry_index)
2770        {
2771            self.navbar_scroll_handle
2772                .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2773        }
2774
2775        // Page scroll handle updates the active item index
2776        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2777        // The call after that updates the offset of the scroll handle. So to
2778        // ensure the scroll handle doesn't lag behind we need to render three frames
2779        // back to back.
2780        cx.on_next_frame(window, move |_, window, cx| {
2781            if let Some(handle) = handle_to_focus.as_ref() {
2782                window.focus(handle, cx);
2783            }
2784
2785            cx.on_next_frame(window, |_, _, cx| {
2786                cx.notify();
2787            });
2788            cx.notify();
2789        });
2790        cx.notify();
2791    }
2792
2793    fn scroll_to_content_item(
2794        &self,
2795        content_item_index: usize,
2796        _window: &mut Window,
2797        cx: &mut Context<Self>,
2798    ) {
2799        let index = self
2800            .visible_page_items()
2801            .position(|(index, _)| index == content_item_index)
2802            .unwrap_or(0);
2803        if index == 0 {
2804            if let Some(scroll_handle) = self.current_sub_page_scroll_handle() {
2805                scroll_handle.set_offset(point(px(0.), px(0.)));
2806            }
2807
2808            self.list_state.scroll_to(gpui::ListOffset {
2809                item_ix: 0,
2810                offset_in_item: px(0.),
2811            });
2812            return;
2813        }
2814        self.list_state.scroll_to(gpui::ListOffset {
2815            item_ix: index + 1,
2816            offset_in_item: px(0.),
2817        });
2818        cx.notify();
2819    }
2820
2821    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2822        self.visible_navbar_entries()
2823            .any(|(index, _)| index == nav_entry_index)
2824    }
2825
2826    fn focus_and_scroll_to_first_visible_nav_entry(
2827        &self,
2828        window: &mut Window,
2829        cx: &mut Context<Self>,
2830    ) {
2831        if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2832        {
2833            self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2834        }
2835    }
2836
2837    fn focus_and_scroll_to_nav_entry(
2838        &self,
2839        nav_entry_index: usize,
2840        window: &mut Window,
2841        cx: &mut Context<Self>,
2842    ) {
2843        let Some(position) = self
2844            .visible_navbar_entries()
2845            .position(|(index, _)| index == nav_entry_index)
2846        else {
2847            return;
2848        };
2849        self.navbar_scroll_handle
2850            .scroll_to_item(position, gpui::ScrollStrategy::Top);
2851        window.focus(&self.navbar_entries[nav_entry_index].focus_handle, cx);
2852        cx.notify();
2853    }
2854
2855    fn current_sub_page_scroll_handle(&self) -> Option<&ScrollHandle> {
2856        self.sub_page_stack.last().map(|page| &page.scroll_handle)
2857    }
2858
2859    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2860        let page_idx = self.current_page_index();
2861
2862        self.current_page()
2863            .items
2864            .iter()
2865            .enumerate()
2866            .filter(move |&(item_index, _)| self.filter_table[page_idx][item_index])
2867    }
2868
2869    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2870        h_flex().gap_1().children(
2871            itertools::intersperse(
2872                std::iter::once(self.current_page().title.into()).chain(
2873                    self.sub_page_stack
2874                        .iter()
2875                        .enumerate()
2876                        .flat_map(|(index, page)| {
2877                            (index == 0)
2878                                .then(|| page.section_header.clone())
2879                                .into_iter()
2880                                .chain(std::iter::once(page.link.title.clone()))
2881                        }),
2882                ),
2883                "/".into(),
2884            )
2885            .map(|item| Label::new(item).color(Color::Muted)),
2886        )
2887    }
2888
2889    fn render_no_results(&self, cx: &App) -> impl IntoElement {
2890        let search_query = self.search_bar.read(cx).text(cx);
2891
2892        v_flex()
2893            .size_full()
2894            .items_center()
2895            .justify_center()
2896            .gap_1()
2897            .child(Label::new("No Results"))
2898            .child(
2899                Label::new(format!("No settings match \"{}\"", search_query))
2900                    .size(LabelSize::Small)
2901                    .color(Color::Muted),
2902            )
2903    }
2904
2905    fn render_current_page_items(
2906        &mut self,
2907        _window: &mut Window,
2908        cx: &mut Context<SettingsWindow>,
2909    ) -> impl IntoElement {
2910        let current_page_index = self.current_page_index();
2911        let mut page_content = v_flex().id("settings-ui-page").size_full();
2912
2913        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2914        let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2915
2916        if has_no_results {
2917            page_content = page_content.child(self.render_no_results(cx))
2918        } else {
2919            let last_non_header_index = self
2920                .visible_page_items()
2921                .filter_map(|(index, item)| {
2922                    (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2923                })
2924                .last();
2925
2926            let root_nav_label = self
2927                .navbar_entries
2928                .iter()
2929                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2930                .map(|entry| entry.title);
2931
2932            let list_content = list(
2933                self.list_state.clone(),
2934                cx.processor(move |this, index, window, cx| {
2935                    if index == 0 {
2936                        return div()
2937                            .px_8()
2938                            .when(this.sub_page_stack.is_empty(), |this| {
2939                                this.when_some(root_nav_label, |this, title| {
2940                                    this.child(
2941                                        Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2942                                    )
2943                                })
2944                            })
2945                            .into_any_element();
2946                    }
2947
2948                    let mut visible_items = this.visible_page_items();
2949                    let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2950                        return gpui::Empty.into_any_element();
2951                    };
2952
2953                    let next_is_header = visible_items
2954                        .next()
2955                        .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2956                        .unwrap_or(false);
2957
2958                    let is_last = Some(actual_item_index) == last_non_header_index;
2959                    let is_last_in_section = next_is_header || is_last;
2960
2961                    let bottom_border = !is_last_in_section;
2962                    let extra_bottom_padding = is_last_in_section;
2963
2964                    let item_focus_handle = this.content_handles[current_page_index]
2965                        [actual_item_index]
2966                        .focus_handle(cx);
2967
2968                    v_flex()
2969                        .id(("settings-page-item", actual_item_index))
2970                        .track_focus(&item_focus_handle)
2971                        .w_full()
2972                        .min_w_0()
2973                        .child(item.render(
2974                            this,
2975                            actual_item_index,
2976                            bottom_border,
2977                            extra_bottom_padding,
2978                            window,
2979                            cx,
2980                        ))
2981                        .into_any_element()
2982                }),
2983            );
2984
2985            page_content = page_content.child(list_content.size_full())
2986        }
2987        page_content
2988    }
2989
2990    fn render_sub_page_items<'a, Items>(
2991        &self,
2992        items: Items,
2993        scroll_handle: &ScrollHandle,
2994        window: &mut Window,
2995        cx: &mut Context<SettingsWindow>,
2996    ) -> impl IntoElement
2997    where
2998        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
2999    {
3000        let page_content = v_flex()
3001            .id("settings-ui-page")
3002            .size_full()
3003            .overflow_y_scroll()
3004            .track_scroll(scroll_handle);
3005        self.render_sub_page_items_in(page_content, items, false, window, cx)
3006    }
3007
3008    fn render_sub_page_items_section<'a, Items>(
3009        &self,
3010        items: Items,
3011        is_inline_section: bool,
3012        window: &mut Window,
3013        cx: &mut Context<SettingsWindow>,
3014    ) -> impl IntoElement
3015    where
3016        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
3017    {
3018        let page_content = v_flex().id("settings-ui-sub-page-section").size_full();
3019        self.render_sub_page_items_in(page_content, items, is_inline_section, window, cx)
3020    }
3021
3022    fn render_sub_page_items_in<'a, Items>(
3023        &self,
3024        page_content: Stateful<Div>,
3025        items: Items,
3026        is_inline_section: bool,
3027        window: &mut Window,
3028        cx: &mut Context<SettingsWindow>,
3029    ) -> impl IntoElement
3030    where
3031        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
3032    {
3033        let items: Vec<_> = items.collect();
3034        let items_len = items.len();
3035
3036        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
3037        let has_no_results = items_len == 0 && has_active_search;
3038
3039        if has_no_results {
3040            page_content.child(self.render_no_results(cx))
3041        } else {
3042            let last_non_header_index = items
3043                .iter()
3044                .enumerate()
3045                .rev()
3046                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
3047                .map(|(index, _)| index);
3048
3049            let root_nav_label = self
3050                .navbar_entries
3051                .iter()
3052                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
3053                .map(|entry| entry.title);
3054
3055            page_content
3056                .when(self.sub_page_stack.is_empty(), |this| {
3057                    this.when_some(root_nav_label, |this, title| {
3058                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
3059                    })
3060                })
3061                .children(items.clone().into_iter().enumerate().map(
3062                    |(index, (actual_item_index, item))| {
3063                        let is_last_item = Some(index) == last_non_header_index;
3064                        let next_is_header = items.get(index + 1).is_some_and(|(_, next_item)| {
3065                            matches!(next_item, SettingsPageItem::SectionHeader(_))
3066                        });
3067                        let bottom_border = !is_inline_section && !next_is_header && !is_last_item;
3068
3069                        let extra_bottom_padding =
3070                            !is_inline_section && (next_is_header || is_last_item);
3071
3072                        v_flex()
3073                            .w_full()
3074                            .min_w_0()
3075                            .id(("settings-page-item", actual_item_index))
3076                            .child(item.render(
3077                                self,
3078                                actual_item_index,
3079                                bottom_border,
3080                                extra_bottom_padding,
3081                                window,
3082                                cx,
3083                            ))
3084                    },
3085                ))
3086        }
3087    }
3088
3089    fn render_page(
3090        &mut self,
3091        window: &mut Window,
3092        cx: &mut Context<SettingsWindow>,
3093    ) -> impl IntoElement {
3094        let page_header;
3095        let page_content;
3096
3097        if let Some(current_sub_page) = self.sub_page_stack.last() {
3098            page_header = h_flex()
3099                .w_full()
3100                .justify_between()
3101                .child(
3102                    h_flex()
3103                        .ml_neg_1p5()
3104                        .gap_1()
3105                        .child(
3106                            IconButton::new("back-btn", IconName::ArrowLeft)
3107                                .icon_size(IconSize::Small)
3108                                .shape(IconButtonShape::Square)
3109                                .on_click(cx.listener(|this, _, window, cx| {
3110                                    this.pop_sub_page(window, cx);
3111                                })),
3112                        )
3113                        .child(self.render_sub_page_breadcrumbs()),
3114                )
3115                .when(current_sub_page.link.in_json, |this| {
3116                    this.child(
3117                        Button::new("open-in-settings-file", "Edit in settings.json")
3118                            .tab_index(0_isize)
3119                            .style(ButtonStyle::OutlinedGhost)
3120                            .tooltip(Tooltip::for_action_title_in(
3121                                "Edit in settings.json",
3122                                &OpenCurrentFile,
3123                                &self.focus_handle,
3124                            ))
3125                            .on_click(cx.listener(|this, _, window, cx| {
3126                                this.open_current_settings_file(window, cx);
3127                            })),
3128                    )
3129                })
3130                .into_any_element();
3131
3132            let active_page_render_fn = &current_sub_page.link.render;
3133            page_content =
3134                (active_page_render_fn)(self, &current_sub_page.scroll_handle, window, cx);
3135        } else {
3136            page_header = self.render_files_header(window, cx).into_any_element();
3137
3138            page_content = self
3139                .render_current_page_items(window, cx)
3140                .into_any_element();
3141        }
3142
3143        let current_sub_page = self.sub_page_stack.last();
3144
3145        let mut warning_banner = gpui::Empty.into_any_element();
3146        if let Some(error) =
3147            SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
3148        {
3149            fn banner(
3150                label: &'static str,
3151                error: String,
3152                shown_errors: &mut HashSet<String>,
3153                cx: &mut Context<SettingsWindow>,
3154            ) -> impl IntoElement {
3155                if shown_errors.insert(error.clone()) {
3156                    telemetry::event!("Settings Error Shown", label = label, error = &error);
3157                }
3158                Banner::new()
3159                    .severity(Severity::Warning)
3160                    .child(
3161                        v_flex()
3162                            .my_0p5()
3163                            .gap_0p5()
3164                            .child(Label::new(label))
3165                            .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
3166                    )
3167                    .action_slot(
3168                        div().pr_1().pb_1().child(
3169                            Button::new("fix-in-json", "Fix in settings.json")
3170                                .tab_index(0_isize)
3171                                .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3172                                .on_click(cx.listener(|this, _, window, cx| {
3173                                    this.open_current_settings_file(window, cx);
3174                                })),
3175                        ),
3176                    )
3177            }
3178
3179            let parse_error = error.parse_error();
3180            let parse_failed = parse_error.is_some();
3181
3182            warning_banner = v_flex()
3183                .gap_2()
3184                .when_some(parse_error, |this, err| {
3185                    this.child(banner(
3186                        "Failed to load your settings. Some values may be incorrect and changes may be lost.",
3187                        err,
3188                        &mut self.shown_errors,
3189                        cx,
3190                    ))
3191                })
3192                .map(|this| match &error.migration_status {
3193                    settings::MigrationStatus::Succeeded => this.child(banner(
3194                        "Your settings are out of date, and need to be updated.",
3195                        match &self.current_file {
3196                            SettingsUiFile::User => "They can be automatically migrated to the latest version.",
3197                            SettingsUiFile::Server(_) | SettingsUiFile::Project(_)  => "They must be manually migrated to the latest version."
3198                        }.to_string(),
3199                        &mut self.shown_errors,
3200                        cx,
3201                    )),
3202                    settings::MigrationStatus::Failed { error: err } if !parse_failed => this
3203                        .child(banner(
3204                            "Your settings file is out of date, automatic migration failed",
3205                            err.clone(),
3206                            &mut self.shown_errors,
3207                            cx,
3208                        )),
3209                    _ => this,
3210                })
3211                .into_any_element()
3212        }
3213
3214        v_flex()
3215            .id("settings-ui-page")
3216            .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3217                if !this.sub_page_stack.is_empty() {
3218                    window.focus_next(cx);
3219                    return;
3220                }
3221                for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
3222                    let handle = this.content_handles[this.current_page_index()][actual_index]
3223                        .focus_handle(cx);
3224                    let mut offset = 1; // for page header
3225
3226                    if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
3227                        && matches!(next_item, SettingsPageItem::SectionHeader(_))
3228                    {
3229                        offset += 1;
3230                    }
3231                    if handle.contains_focused(window, cx) {
3232                        let next_logical_index = logical_index + offset + 1;
3233                        this.list_state.scroll_to_reveal_item(next_logical_index);
3234                        // We need to render the next item to ensure it's focus handle is in the element tree
3235                        cx.on_next_frame(window, |_, window, cx| {
3236                            cx.notify();
3237                            cx.on_next_frame(window, |_, window, cx| {
3238                                window.focus_next(cx);
3239                                cx.notify();
3240                            });
3241                        });
3242                        cx.notify();
3243                        return;
3244                    }
3245                }
3246                window.focus_next(cx);
3247            }))
3248            .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
3249                if !this.sub_page_stack.is_empty() {
3250                    window.focus_prev(cx);
3251                    return;
3252                }
3253                let mut prev_was_header = false;
3254                for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
3255                    let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
3256                    let handle = this.content_handles[this.current_page_index()][actual_index]
3257                        .focus_handle(cx);
3258                    let mut offset = 1; // for page header
3259
3260                    if prev_was_header {
3261                        offset -= 1;
3262                    }
3263                    if handle.contains_focused(window, cx) {
3264                        let next_logical_index = logical_index + offset - 1;
3265                        this.list_state.scroll_to_reveal_item(next_logical_index);
3266                        // We need to render the next item to ensure it's focus handle is in the element tree
3267                        cx.on_next_frame(window, |_, window, cx| {
3268                            cx.notify();
3269                            cx.on_next_frame(window, |_, window, cx| {
3270                                window.focus_prev(cx);
3271                                cx.notify();
3272                            });
3273                        });
3274                        cx.notify();
3275                        return;
3276                    }
3277                    prev_was_header = is_header;
3278                }
3279                window.focus_prev(cx);
3280            }))
3281            .when(current_sub_page.is_none(), |this| {
3282                this.vertical_scrollbar_for(&self.list_state, window, cx)
3283            })
3284            .when_some(current_sub_page, |this, current_sub_page| {
3285                this.custom_scrollbars(
3286                    Scrollbars::new(ui::ScrollAxes::Vertical)
3287                        .tracked_scroll_handle(&current_sub_page.scroll_handle)
3288                        .id((current_sub_page.link.title.clone(), 42)),
3289                    window,
3290                    cx,
3291                )
3292            })
3293            .track_focus(&self.content_focus_handle.focus_handle(cx))
3294            .pt_6()
3295            .gap_4()
3296            .flex_1()
3297            .bg(cx.theme().colors().editor_background)
3298            .child(
3299                v_flex()
3300                    .px_8()
3301                    .gap_2()
3302                    .child(page_header)
3303                    .child(warning_banner),
3304            )
3305            .child(
3306                div()
3307                    .flex_1()
3308                    .min_h_0()
3309                    .size_full()
3310                    .tab_group()
3311                    .tab_index(CONTENT_GROUP_TAB_INDEX)
3312                    .child(page_content),
3313            )
3314    }
3315
3316    /// This function will create a new settings file if one doesn't exist
3317    /// if the current file is a project settings with a valid worktree id
3318    /// We do this because the settings ui allows initializing project settings
3319    fn open_current_settings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3320        match &self.current_file {
3321            SettingsUiFile::User => {
3322                let Some(original_window) = self.original_window else {
3323                    return;
3324                };
3325                original_window
3326                    .update(cx, |workspace, window, cx| {
3327                        workspace
3328                            .with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
3329                                let project = workspace.project().clone();
3330
3331                                cx.spawn_in(window, async move |workspace, cx| {
3332                                    let (config_dir, settings_file) =
3333                                        project.update(cx, |project, cx| {
3334                                            (
3335                                                project.try_windows_path_to_wsl(
3336                                                    paths::config_dir().as_path(),
3337                                                    cx,
3338                                                ),
3339                                                project.try_windows_path_to_wsl(
3340                                                    paths::settings_file().as_path(),
3341                                                    cx,
3342                                                ),
3343                                            )
3344                                        });
3345                                    let config_dir = config_dir.await?;
3346                                    let settings_file = settings_file.await?;
3347                                    project
3348                                        .update(cx, |project, cx| {
3349                                            project.find_or_create_worktree(&config_dir, false, cx)
3350                                        })
3351                                        .await
3352                                        .ok();
3353                                    workspace
3354                                        .update_in(cx, |workspace, window, cx| {
3355                                            workspace.open_paths(
3356                                                vec![settings_file],
3357                                                OpenOptions {
3358                                                    visible: Some(OpenVisible::None),
3359                                                    ..Default::default()
3360                                                },
3361                                                None,
3362                                                window,
3363                                                cx,
3364                                            )
3365                                        })?
3366                                        .await;
3367
3368                                    workspace.update_in(cx, |_, window, cx| {
3369                                        window.activate_window();
3370                                        cx.notify();
3371                                    })
3372                                })
3373                                .detach();
3374                            })
3375                            .detach();
3376                    })
3377                    .ok();
3378
3379                window.remove_window();
3380            }
3381            SettingsUiFile::Project((worktree_id, path)) => {
3382                let settings_path = path.join(paths::local_settings_file_relative_path());
3383                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
3384                    return;
3385                };
3386
3387                let Some((worktree, corresponding_workspace)) = app_state
3388                    .workspace_store
3389                    .read(cx)
3390                    .workspaces()
3391                    .iter()
3392                    .find_map(|workspace| {
3393                        workspace
3394                            .read_with(cx, |workspace, cx| {
3395                                workspace
3396                                    .project()
3397                                    .read(cx)
3398                                    .worktree_for_id(*worktree_id, cx)
3399                            })
3400                            .ok()
3401                            .flatten()
3402                            .zip(Some(*workspace))
3403                    })
3404                else {
3405                    log::error!(
3406                        "No corresponding workspace contains worktree id: {}",
3407                        worktree_id
3408                    );
3409
3410                    return;
3411                };
3412
3413                let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3414                    None
3415                } else {
3416                    Some(worktree.update(cx, |tree, cx| {
3417                        tree.create_entry(
3418                            settings_path.clone(),
3419                            false,
3420                            Some(initial_project_settings_content().as_bytes().to_vec()),
3421                            cx,
3422                        )
3423                    }))
3424                };
3425
3426                let worktree_id = *worktree_id;
3427
3428                // TODO: move zed::open_local_file() APIs to this crate, and
3429                // re-implement the "initial_contents" behavior
3430                corresponding_workspace
3431                    .update(cx, |_, window, cx| {
3432                        cx.spawn_in(window, async move |workspace, cx| {
3433                            if let Some(create_task) = create_task {
3434                                create_task.await.ok()?;
3435                            };
3436
3437                            workspace
3438                                .update_in(cx, |workspace, window, cx| {
3439                                    workspace.open_path(
3440                                        (worktree_id, settings_path.clone()),
3441                                        None,
3442                                        true,
3443                                        window,
3444                                        cx,
3445                                    )
3446                                })
3447                                .ok()?
3448                                .await
3449                                .log_err()?;
3450
3451                            workspace
3452                                .update_in(cx, |_, window, cx| {
3453                                    window.activate_window();
3454                                    cx.notify();
3455                                })
3456                                .ok();
3457
3458                            Some(())
3459                        })
3460                        .detach();
3461                    })
3462                    .ok();
3463
3464                window.remove_window();
3465            }
3466            SettingsUiFile::Server(_) => {
3467                // Server files are not editable
3468                return;
3469            }
3470        };
3471    }
3472
3473    fn current_page_index(&self) -> usize {
3474        if self.navbar_entries.is_empty() {
3475            return 0;
3476        }
3477
3478        self.navbar_entries[self.navbar_entry].page_index
3479    }
3480
3481    fn current_page(&self) -> &SettingsPage {
3482        &self.pages[self.current_page_index()]
3483    }
3484
3485    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3486        ix == self.navbar_entry
3487    }
3488
3489    fn push_sub_page(
3490        &mut self,
3491        sub_page_link: SubPageLink,
3492        section_header: SharedString,
3493        window: &mut Window,
3494        cx: &mut Context<SettingsWindow>,
3495    ) {
3496        self.sub_page_stack
3497            .push(SubPage::new(sub_page_link, section_header));
3498        self.content_focus_handle.focus_handle(cx).focus(window, cx);
3499        cx.notify();
3500    }
3501
3502    /// Push a dynamically-created sub-page with a custom render function.
3503    /// This is useful for nested sub-pages that aren't defined in the main pages list.
3504    pub fn push_dynamic_sub_page(
3505        &mut self,
3506        title: impl Into<SharedString>,
3507        section_header: impl Into<SharedString>,
3508        json_path: Option<&'static str>,
3509        render: fn(
3510            &SettingsWindow,
3511            &ScrollHandle,
3512            &mut Window,
3513            &mut Context<SettingsWindow>,
3514        ) -> AnyElement,
3515        window: &mut Window,
3516        cx: &mut Context<SettingsWindow>,
3517    ) {
3518        self.regex_validation_error = None;
3519        let sub_page_link = SubPageLink {
3520            title: title.into(),
3521            r#type: SubPageType::default(),
3522            description: None,
3523            json_path,
3524            in_json: true,
3525            files: USER,
3526            render,
3527        };
3528        self.push_sub_page(sub_page_link, section_header.into(), window, cx);
3529    }
3530
3531    /// Navigate to a sub-page by its json_path.
3532    /// Returns true if the sub-page was found and pushed, false otherwise.
3533    pub fn navigate_to_sub_page(
3534        &mut self,
3535        json_path: &str,
3536        window: &mut Window,
3537        cx: &mut Context<SettingsWindow>,
3538    ) -> bool {
3539        for page in &self.pages {
3540            for (item_index, item) in page.items.iter().enumerate() {
3541                if let SettingsPageItem::SubPageLink(sub_page_link) = item {
3542                    if sub_page_link.json_path == Some(json_path) {
3543                        let section_header = page
3544                            .items
3545                            .iter()
3546                            .take(item_index)
3547                            .rev()
3548                            .find_map(|item| item.header_text().map(SharedString::new_static))
3549                            .unwrap_or_else(|| "Settings".into());
3550
3551                        self.push_sub_page(sub_page_link.clone(), section_header, window, cx);
3552                        return true;
3553                    }
3554                }
3555            }
3556        }
3557        false
3558    }
3559
3560    /// Navigate to a setting by its json_path.
3561    /// Clears the sub-page stack and scrolls to the setting item.
3562    /// Returns true if the setting was found, false otherwise.
3563    pub fn navigate_to_setting(
3564        &mut self,
3565        json_path: &str,
3566        window: &mut Window,
3567        cx: &mut Context<SettingsWindow>,
3568    ) -> bool {
3569        self.sub_page_stack.clear();
3570
3571        for (page_index, page) in self.pages.iter().enumerate() {
3572            for (item_index, item) in page.items.iter().enumerate() {
3573                let item_json_path = match item {
3574                    SettingsPageItem::SettingItem(setting_item) => setting_item.field.json_path(),
3575                    SettingsPageItem::DynamicItem(dynamic_item) => {
3576                        dynamic_item.discriminant.field.json_path()
3577                    }
3578                    _ => None,
3579                };
3580                if item_json_path == Some(json_path) {
3581                    if let Some(navbar_entry_index) = self
3582                        .navbar_entries
3583                        .iter()
3584                        .position(|e| e.page_index == page_index && e.is_root)
3585                    {
3586                        self.open_and_scroll_to_navbar_entry(
3587                            navbar_entry_index,
3588                            None,
3589                            false,
3590                            window,
3591                            cx,
3592                        );
3593                        self.scroll_to_content_item(item_index, window, cx);
3594                        return true;
3595                    }
3596                }
3597            }
3598        }
3599        false
3600    }
3601
3602    fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
3603        self.regex_validation_error = None;
3604        self.sub_page_stack.pop();
3605        self.content_focus_handle.focus_handle(cx).focus(window, cx);
3606        cx.notify();
3607    }
3608
3609    fn focus_file_at_index(&mut self, index: usize, window: &mut Window, cx: &mut App) {
3610        if let Some((_, handle)) = self.files.get(index) {
3611            handle.focus(window, cx);
3612        }
3613    }
3614
3615    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3616        if self.files_focus_handle.contains_focused(window, cx)
3617            && let Some(index) = self
3618                .files
3619                .iter()
3620                .position(|(_, handle)| handle.is_focused(window))
3621        {
3622            return index;
3623        }
3624        if let Some(current_file_index) = self
3625            .files
3626            .iter()
3627            .position(|(file, _)| file == &self.current_file)
3628        {
3629            return current_file_index;
3630        }
3631        0
3632    }
3633
3634    fn focus_handle_for_content_element(
3635        &self,
3636        actual_item_index: usize,
3637        cx: &Context<Self>,
3638    ) -> FocusHandle {
3639        let page_index = self.current_page_index();
3640        self.content_handles[page_index][actual_item_index].focus_handle(cx)
3641    }
3642
3643    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3644        if !self
3645            .navbar_focus_handle
3646            .focus_handle(cx)
3647            .contains_focused(window, cx)
3648        {
3649            return None;
3650        }
3651        for (index, entry) in self.navbar_entries.iter().enumerate() {
3652            if entry.focus_handle.is_focused(window) {
3653                return Some(index);
3654            }
3655        }
3656        None
3657    }
3658
3659    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3660        let mut index = Some(nav_entry_index);
3661        while let Some(prev_index) = index
3662            && !self.navbar_entries[prev_index].is_root
3663        {
3664            index = prev_index.checked_sub(1);
3665        }
3666        return index.expect("No root entry found");
3667    }
3668}
3669
3670impl Render for SettingsWindow {
3671    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3672        let ui_font = theme::setup_ui_font(window, cx);
3673
3674        client_side_decorations(
3675            v_flex()
3676                .text_color(cx.theme().colors().text)
3677                .size_full()
3678                .children(self.title_bar.clone())
3679                .child(
3680                    div()
3681                        .id("settings-window")
3682                        .key_context("SettingsWindow")
3683                        .track_focus(&self.focus_handle)
3684                        .on_action(cx.listener(|this, _: &OpenCurrentFile, window, cx| {
3685                            this.open_current_settings_file(window, cx);
3686                        }))
3687                        .on_action(|_: &Minimize, window, _cx| {
3688                            window.minimize_window();
3689                        })
3690                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3691                            this.search_bar.focus_handle(cx).focus(window, cx);
3692                        }))
3693                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3694                            if this
3695                                .navbar_focus_handle
3696                                .focus_handle(cx)
3697                                .contains_focused(window, cx)
3698                            {
3699                                this.open_and_scroll_to_navbar_entry(
3700                                    this.navbar_entry,
3701                                    None,
3702                                    true,
3703                                    window,
3704                                    cx,
3705                                );
3706                            } else {
3707                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3708                            }
3709                        }))
3710                        .on_action(cx.listener(
3711                            |this, FocusFile(file_index): &FocusFile, window, cx| {
3712                                this.focus_file_at_index(*file_index as usize, window, cx);
3713                            },
3714                        ))
3715                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3716                            let next_index = usize::min(
3717                                this.focused_file_index(window, cx) + 1,
3718                                this.files.len().saturating_sub(1),
3719                            );
3720                            this.focus_file_at_index(next_index, window, cx);
3721                        }))
3722                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3723                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3724                            this.focus_file_at_index(prev_index, window, cx);
3725                        }))
3726                        .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3727                            if this
3728                                .search_bar
3729                                .focus_handle(cx)
3730                                .contains_focused(window, cx)
3731                            {
3732                                this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3733                            } else {
3734                                window.focus_next(cx);
3735                            }
3736                        }))
3737                        .on_action(|_: &menu::SelectPrevious, window, cx| {
3738                            window.focus_prev(cx);
3739                        })
3740                        .flex()
3741                        .flex_row()
3742                        .flex_1()
3743                        .min_h_0()
3744                        .font(ui_font)
3745                        .bg(cx.theme().colors().background)
3746                        .text_color(cx.theme().colors().text)
3747                        .when(!cfg!(target_os = "macos"), |this| {
3748                            this.border_t_1().border_color(cx.theme().colors().border)
3749                        })
3750                        .child(self.render_nav(window, cx))
3751                        .child(self.render_page(window, cx)),
3752                ),
3753            window,
3754            cx,
3755        )
3756    }
3757}
3758
3759fn all_projects(
3760    window: Option<&WindowHandle<Workspace>>,
3761    cx: &App,
3762) -> impl Iterator<Item = Entity<Project>> {
3763    let mut seen_project_ids = std::collections::HashSet::new();
3764    workspace::AppState::global(cx)
3765        .upgrade()
3766        .map(|app_state| {
3767            app_state
3768                .workspace_store
3769                .read(cx)
3770                .workspaces()
3771                .iter()
3772                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
3773                .chain(
3774                    window.and_then(|workspace| Some(workspace.read(cx).ok()?.project().clone())),
3775                )
3776                .filter(move |project| seen_project_ids.insert(project.entity_id()))
3777        })
3778        .into_iter()
3779        .flatten()
3780}
3781
3782fn update_settings_file(
3783    file: SettingsUiFile,
3784    file_name: Option<&'static str>,
3785    window: &mut Window,
3786    cx: &mut App,
3787    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3788) -> Result<()> {
3789    telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3790
3791    match file {
3792        SettingsUiFile::Project((worktree_id, rel_path)) => {
3793            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3794            let Some(settings_window) = window.root::<SettingsWindow>().flatten() else {
3795                anyhow::bail!("No settings window found");
3796            };
3797
3798            update_project_setting_file(worktree_id, rel_path, update, settings_window, cx)
3799        }
3800        SettingsUiFile::User => {
3801            // todo(settings_ui) error?
3802            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3803            Ok(())
3804        }
3805        SettingsUiFile::Server(_) => unimplemented!(),
3806    }
3807}
3808
3809struct ProjectSettingsUpdateEntry {
3810    worktree_id: WorktreeId,
3811    rel_path: Arc<RelPath>,
3812    settings_window: WeakEntity<SettingsWindow>,
3813    project: WeakEntity<Project>,
3814    worktree: WeakEntity<Worktree>,
3815    update: Box<dyn FnOnce(&mut SettingsContent, &App)>,
3816}
3817
3818struct ProjectSettingsUpdateQueue {
3819    tx: mpsc::UnboundedSender<ProjectSettingsUpdateEntry>,
3820    _task: Task<()>,
3821}
3822
3823impl Global for ProjectSettingsUpdateQueue {}
3824
3825impl ProjectSettingsUpdateQueue {
3826    fn new(cx: &mut App) -> Self {
3827        let (tx, mut rx) = mpsc::unbounded();
3828        let task = cx.spawn(async move |mut cx| {
3829            while let Some(entry) = rx.next().await {
3830                if let Err(err) = Self::process_entry(entry, &mut cx).await {
3831                    log::error!("Failed to update project settings: {err:?}");
3832                }
3833            }
3834        });
3835        Self { tx, _task: task }
3836    }
3837
3838    fn enqueue(cx: &mut App, entry: ProjectSettingsUpdateEntry) {
3839        cx.update_global::<Self, _>(|queue, _cx| {
3840            if let Err(err) = queue.tx.unbounded_send(entry) {
3841                log::error!("Failed to enqueue project settings update: {err}");
3842            }
3843        });
3844    }
3845
3846    async fn process_entry(entry: ProjectSettingsUpdateEntry, cx: &mut AsyncApp) -> Result<()> {
3847        let ProjectSettingsUpdateEntry {
3848            worktree_id,
3849            rel_path,
3850            settings_window,
3851            project,
3852            worktree,
3853            update,
3854        } = entry;
3855
3856        let project_path = ProjectPath {
3857            worktree_id,
3858            path: rel_path.clone(),
3859        };
3860
3861        let needs_creation = worktree.read_with(cx, |worktree, _| {
3862            worktree.entry_for_path(&rel_path).is_none()
3863        })?;
3864
3865        if needs_creation {
3866            worktree
3867                .update(cx, |worktree, cx| {
3868                    worktree.create_entry(rel_path.clone(), false, None, cx)
3869                })?
3870                .await?;
3871        }
3872
3873        let buffer_store = project.read_with(cx, |project, _cx| project.buffer_store().clone())?;
3874
3875        let cached_buffer = settings_window
3876            .read_with(cx, |settings_window, _| {
3877                settings_window
3878                    .project_setting_file_buffers
3879                    .get(&project_path)
3880                    .cloned()
3881            })
3882            .unwrap_or_default();
3883
3884        let buffer = if let Some(cached_buffer) = cached_buffer {
3885            let needs_reload = cached_buffer.read_with(cx, |buffer, _| buffer.has_conflict());
3886            if needs_reload {
3887                cached_buffer
3888                    .update(cx, |buffer, cx| buffer.reload(cx))
3889                    .await
3890                    .context("Failed to reload settings file")?;
3891            }
3892            cached_buffer
3893        } else {
3894            let buffer = buffer_store
3895                .update(cx, |store, cx| store.open_buffer(project_path.clone(), cx))
3896                .await
3897                .context("Failed to open settings file")?;
3898
3899            let _ = settings_window.update(cx, |this, _cx| {
3900                this.project_setting_file_buffers
3901                    .insert(project_path, buffer.clone());
3902            });
3903
3904            buffer
3905        };
3906
3907        buffer.update(cx, |buffer, cx| {
3908            let current_text = buffer.text();
3909            let new_text = cx
3910                .global::<SettingsStore>()
3911                .new_text_for_update(current_text, |settings| update(settings, cx));
3912            buffer.edit([(0..buffer.len(), new_text)], None, cx);
3913        });
3914
3915        buffer_store
3916            .update(cx, |store, cx| store.save_buffer(buffer, cx))
3917            .await
3918            .context("Failed to save settings file")?;
3919
3920        Ok(())
3921    }
3922}
3923
3924fn update_project_setting_file(
3925    worktree_id: WorktreeId,
3926    rel_path: Arc<RelPath>,
3927    update: impl 'static + FnOnce(&mut SettingsContent, &App),
3928    settings_window: Entity<SettingsWindow>,
3929    cx: &mut App,
3930) -> Result<()> {
3931    let Some((worktree, project)) =
3932        all_projects(settings_window.read(cx).original_window.as_ref(), cx).find_map(|project| {
3933            project
3934                .read(cx)
3935                .worktree_for_id(worktree_id, cx)
3936                .zip(Some(project))
3937        })
3938    else {
3939        anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3940    };
3941
3942    let entry = ProjectSettingsUpdateEntry {
3943        worktree_id,
3944        rel_path,
3945        settings_window: settings_window.downgrade(),
3946        project: project.downgrade(),
3947        worktree: worktree.downgrade(),
3948        update: Box::new(update),
3949    };
3950
3951    ProjectSettingsUpdateQueue::enqueue(cx, entry);
3952
3953    Ok(())
3954}
3955
3956fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3957    field: SettingField<T>,
3958    file: SettingsUiFile,
3959    metadata: Option<&SettingsFieldMetadata>,
3960    _window: &mut Window,
3961    cx: &mut App,
3962) -> AnyElement {
3963    let (_, initial_text) =
3964        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3965    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3966
3967    SettingsInputField::new()
3968        .tab_index(0)
3969        .when_some(initial_text, |editor, text| {
3970            editor.with_initial_text(text.as_ref().to_string())
3971        })
3972        .when_some(
3973            metadata.and_then(|metadata| metadata.placeholder),
3974            |editor, placeholder| editor.with_placeholder(placeholder),
3975        )
3976        .on_confirm({
3977            move |new_text, window, cx| {
3978                update_settings_file(
3979                    file.clone(),
3980                    field.json_path,
3981                    window,
3982                    cx,
3983                    move |settings, _cx| {
3984                        (field.write)(settings, new_text.map(Into::into));
3985                    },
3986                )
3987                .log_err(); // todo(settings_ui) don't log err
3988            }
3989        })
3990        .into_any_element()
3991}
3992
3993fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3994    field: SettingField<B>,
3995    file: SettingsUiFile,
3996    _metadata: Option<&SettingsFieldMetadata>,
3997    _window: &mut Window,
3998    cx: &mut App,
3999) -> AnyElement {
4000    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4001
4002    let toggle_state = if value.copied().map_or(false, Into::into) {
4003        ToggleState::Selected
4004    } else {
4005        ToggleState::Unselected
4006    };
4007
4008    Switch::new("toggle_button", toggle_state)
4009        .tab_index(0_isize)
4010        .on_click({
4011            move |state, window, cx| {
4012                telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());
4013
4014                let state = *state == ui::ToggleState::Selected;
4015                update_settings_file(file.clone(), field.json_path, window, cx, move |settings, _cx| {
4016                    (field.write)(settings, Some(state.into()));
4017                })
4018                .log_err(); // todo(settings_ui) don't log err
4019            }
4020        })
4021        .into_any_element()
4022}
4023
4024fn render_number_field<T: NumberFieldType + Send + Sync>(
4025    field: SettingField<T>,
4026    file: SettingsUiFile,
4027    _metadata: Option<&SettingsFieldMetadata>,
4028    window: &mut Window,
4029    cx: &mut App,
4030) -> AnyElement {
4031    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4032    let value = value.copied().unwrap_or_else(T::min_value);
4033
4034    let id = field
4035        .json_path
4036        .map(|p| format!("numeric_stepper_{}", p))
4037        .unwrap_or_else(|| "numeric_stepper".to_string());
4038
4039    NumberField::new(id, value, window, cx)
4040        .tab_index(0_isize)
4041        .on_change({
4042            move |value, window, cx| {
4043                let value = *value;
4044                update_settings_file(
4045                    file.clone(),
4046                    field.json_path,
4047                    window,
4048                    cx,
4049                    move |settings, _cx| {
4050                        (field.write)(settings, Some(value));
4051                    },
4052                )
4053                .log_err(); // todo(settings_ui) don't log err
4054            }
4055        })
4056        .into_any_element()
4057}
4058
4059fn render_editable_number_field<T: NumberFieldType + Send + Sync>(
4060    field: SettingField<T>,
4061    file: SettingsUiFile,
4062    _metadata: Option<&SettingsFieldMetadata>,
4063    window: &mut Window,
4064    cx: &mut App,
4065) -> AnyElement {
4066    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4067    let value = value.copied().unwrap_or_else(T::min_value);
4068
4069    let id = field
4070        .json_path
4071        .map(|p| format!("numeric_stepper_{}", p))
4072        .unwrap_or_else(|| "numeric_stepper".to_string());
4073
4074    NumberField::new(id, value, window, cx)
4075        .mode(NumberFieldMode::Edit, cx)
4076        .tab_index(0_isize)
4077        .on_change({
4078            move |value, window, cx| {
4079                let value = *value;
4080                update_settings_file(
4081                    file.clone(),
4082                    field.json_path,
4083                    window,
4084                    cx,
4085                    move |settings, _cx| {
4086                        (field.write)(settings, Some(value));
4087                    },
4088                )
4089                .log_err(); // todo(settings_ui) don't log err
4090            }
4091        })
4092        .into_any_element()
4093}
4094
4095fn render_dropdown<T>(
4096    field: SettingField<T>,
4097    file: SettingsUiFile,
4098    metadata: Option<&SettingsFieldMetadata>,
4099    _window: &mut Window,
4100    cx: &mut App,
4101) -> AnyElement
4102where
4103    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
4104{
4105    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
4106    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
4107    let should_do_titlecase = metadata
4108        .and_then(|metadata| metadata.should_do_titlecase)
4109        .unwrap_or(true);
4110
4111    let (_, current_value) =
4112        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4113    let current_value = current_value.copied().unwrap_or(variants()[0]);
4114
4115    EnumVariantDropdown::new("dropdown", current_value, variants(), labels(), {
4116        move |value, window, cx| {
4117            if value == current_value {
4118                return;
4119            }
4120            update_settings_file(
4121                file.clone(),
4122                field.json_path,
4123                window,
4124                cx,
4125                move |settings, _cx| {
4126                    (field.write)(settings, Some(value));
4127                },
4128            )
4129            .log_err(); // todo(settings_ui) don't log err
4130        }
4131    })
4132    .tab_index(0)
4133    .title_case(should_do_titlecase)
4134    .into_any_element()
4135}
4136
4137fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
4138    Button::new(id, label)
4139        .tab_index(0_isize)
4140        .style(ButtonStyle::Outlined)
4141        .size(ButtonSize::Medium)
4142        .icon(IconName::ChevronUpDown)
4143        .icon_color(Color::Muted)
4144        .icon_size(IconSize::Small)
4145        .icon_position(IconPosition::End)
4146}
4147
4148fn render_font_picker(
4149    field: SettingField<settings::FontFamilyName>,
4150    file: SettingsUiFile,
4151    _metadata: Option<&SettingsFieldMetadata>,
4152    _window: &mut Window,
4153    cx: &mut App,
4154) -> AnyElement {
4155    let current_value = SettingsStore::global(cx)
4156        .get_value_from_file(file.to_settings(), field.pick)
4157        .1
4158        .cloned()
4159        .map_or_else(|| SharedString::default(), |value| value.into_gpui());
4160
4161    PopoverMenu::new("font-picker")
4162        .trigger(render_picker_trigger_button(
4163            "font_family_picker_trigger".into(),
4164            current_value.clone(),
4165        ))
4166        .menu(move |window, cx| {
4167            let file = file.clone();
4168            let current_value = current_value.clone();
4169
4170            Some(cx.new(move |cx| {
4171                font_picker(
4172                    current_value,
4173                    move |font_name, window, cx| {
4174                        update_settings_file(
4175                            file.clone(),
4176                            field.json_path,
4177                            window,
4178                            cx,
4179                            move |settings, _cx| {
4180                                (field.write)(settings, Some(font_name.to_string().into()));
4181                            },
4182                        )
4183                        .log_err(); // todo(settings_ui) don't log err
4184                    },
4185                    window,
4186                    cx,
4187                )
4188            }))
4189        })
4190        .anchor(gpui::Corner::TopLeft)
4191        .offset(gpui::Point {
4192            x: px(0.0),
4193            y: px(2.0),
4194        })
4195        .with_handle(ui::PopoverMenuHandle::default())
4196        .into_any_element()
4197}
4198
4199fn render_theme_picker(
4200    field: SettingField<settings::ThemeName>,
4201    file: SettingsUiFile,
4202    _metadata: Option<&SettingsFieldMetadata>,
4203    _window: &mut Window,
4204    cx: &mut App,
4205) -> AnyElement {
4206    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4207    let current_value = value
4208        .cloned()
4209        .map(|theme_name| theme_name.0.into())
4210        .unwrap_or_else(|| cx.theme().name.clone());
4211
4212    PopoverMenu::new("theme-picker")
4213        .trigger(render_picker_trigger_button(
4214            "theme_picker_trigger".into(),
4215            current_value.clone(),
4216        ))
4217        .menu(move |window, cx| {
4218            Some(cx.new(|cx| {
4219                let file = file.clone();
4220                let current_value = current_value.clone();
4221                theme_picker(
4222                    current_value,
4223                    move |theme_name, window, cx| {
4224                        update_settings_file(
4225                            file.clone(),
4226                            field.json_path,
4227                            window,
4228                            cx,
4229                            move |settings, _cx| {
4230                                (field.write)(
4231                                    settings,
4232                                    Some(settings::ThemeName(theme_name.into())),
4233                                );
4234                            },
4235                        )
4236                        .log_err(); // todo(settings_ui) don't log err
4237                    },
4238                    window,
4239                    cx,
4240                )
4241            }))
4242        })
4243        .anchor(gpui::Corner::TopLeft)
4244        .offset(gpui::Point {
4245            x: px(0.0),
4246            y: px(2.0),
4247        })
4248        .with_handle(ui::PopoverMenuHandle::default())
4249        .into_any_element()
4250}
4251
4252fn render_icon_theme_picker(
4253    field: SettingField<settings::IconThemeName>,
4254    file: SettingsUiFile,
4255    _metadata: Option<&SettingsFieldMetadata>,
4256    _window: &mut Window,
4257    cx: &mut App,
4258) -> AnyElement {
4259    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4260    let current_value = value
4261        .cloned()
4262        .map(|theme_name| theme_name.0.into())
4263        .unwrap_or_else(|| cx.theme().name.clone());
4264
4265    PopoverMenu::new("icon-theme-picker")
4266        .trigger(render_picker_trigger_button(
4267            "icon_theme_picker_trigger".into(),
4268            current_value.clone(),
4269        ))
4270        .menu(move |window, cx| {
4271            Some(cx.new(|cx| {
4272                let file = file.clone();
4273                let current_value = current_value.clone();
4274                icon_theme_picker(
4275                    current_value,
4276                    move |theme_name, window, cx| {
4277                        update_settings_file(
4278                            file.clone(),
4279                            field.json_path,
4280                            window,
4281                            cx,
4282                            move |settings, _cx| {
4283                                (field.write)(
4284                                    settings,
4285                                    Some(settings::IconThemeName(theme_name.into())),
4286                                );
4287                            },
4288                        )
4289                        .log_err(); // todo(settings_ui) don't log err
4290                    },
4291                    window,
4292                    cx,
4293                )
4294            }))
4295        })
4296        .anchor(gpui::Corner::TopLeft)
4297        .offset(gpui::Point {
4298            x: px(0.0),
4299            y: px(2.0),
4300        })
4301        .with_handle(ui::PopoverMenuHandle::default())
4302        .into_any_element()
4303}
4304
4305#[cfg(test)]
4306pub mod test {
4307
4308    use super::*;
4309
4310    impl SettingsWindow {
4311        fn navbar_entry(&self) -> usize {
4312            self.navbar_entry
4313        }
4314
4315        #[cfg(any(test, feature = "test-support"))]
4316        pub fn test(window: &mut Window, cx: &mut Context<Self>) -> Self {
4317            let search_bar = cx.new(|cx| Editor::single_line(window, cx));
4318            let dummy_page = SettingsPage {
4319                title: "Test",
4320                items: Box::new([]),
4321            };
4322            Self {
4323                title_bar: None,
4324                original_window: None,
4325                worktree_root_dirs: HashMap::default(),
4326                files: Vec::default(),
4327                current_file: SettingsUiFile::User,
4328                project_setting_file_buffers: HashMap::default(),
4329                pages: vec![dummy_page],
4330                search_bar,
4331                navbar_entry: 0,
4332                navbar_entries: Vec::default(),
4333                navbar_scroll_handle: UniformListScrollHandle::default(),
4334                navbar_focus_subscriptions: Vec::default(),
4335                filter_table: Vec::default(),
4336                has_query: false,
4337                content_handles: Vec::default(),
4338                search_task: None,
4339                sub_page_stack: Vec::default(),
4340                opening_link: false,
4341                focus_handle: cx.focus_handle(),
4342                navbar_focus_handle: NonFocusableHandle::new(
4343                    NAVBAR_CONTAINER_TAB_INDEX,
4344                    false,
4345                    window,
4346                    cx,
4347                ),
4348                content_focus_handle: NonFocusableHandle::new(
4349                    CONTENT_CONTAINER_TAB_INDEX,
4350                    false,
4351                    window,
4352                    cx,
4353                ),
4354                files_focus_handle: cx.focus_handle(),
4355                search_index: None,
4356                list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4357                shown_errors: HashSet::default(),
4358                regex_validation_error: None,
4359            }
4360        }
4361    }
4362
4363    impl PartialEq for NavBarEntry {
4364        fn eq(&self, other: &Self) -> bool {
4365            self.title == other.title
4366                && self.is_root == other.is_root
4367                && self.expanded == other.expanded
4368                && self.page_index == other.page_index
4369                && self.item_index == other.item_index
4370            // ignoring focus_handle
4371        }
4372    }
4373
4374    pub fn register_settings(cx: &mut App) {
4375        settings::init(cx);
4376        theme::init(theme::LoadThemes::JustBase, cx);
4377        editor::init(cx);
4378        menu::init();
4379    }
4380
4381    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
4382        struct PageBuilder {
4383            title: &'static str,
4384            items: Vec<SettingsPageItem>,
4385        }
4386        let mut page_builders: Vec<PageBuilder> = Vec::new();
4387        let mut expanded_pages = Vec::new();
4388        let mut selected_idx = None;
4389        let mut index = 0;
4390        let mut in_expanded_section = false;
4391
4392        for mut line in input
4393            .lines()
4394            .map(|line| line.trim())
4395            .filter(|line| !line.is_empty())
4396        {
4397            if let Some(pre) = line.strip_suffix('*') {
4398                assert!(selected_idx.is_none(), "Only one selected entry allowed");
4399                selected_idx = Some(index);
4400                line = pre;
4401            }
4402            let (kind, title) = line.split_once(" ").unwrap();
4403            assert_eq!(kind.len(), 1);
4404            let kind = kind.chars().next().unwrap();
4405            if kind == 'v' {
4406                let page_idx = page_builders.len();
4407                expanded_pages.push(page_idx);
4408                page_builders.push(PageBuilder {
4409                    title,
4410                    items: vec![],
4411                });
4412                index += 1;
4413                in_expanded_section = true;
4414            } else if kind == '>' {
4415                page_builders.push(PageBuilder {
4416                    title,
4417                    items: vec![],
4418                });
4419                index += 1;
4420                in_expanded_section = false;
4421            } else if kind == '-' {
4422                page_builders
4423                    .last_mut()
4424                    .unwrap()
4425                    .items
4426                    .push(SettingsPageItem::SectionHeader(title));
4427                if selected_idx == Some(index) && !in_expanded_section {
4428                    panic!("Items in unexpanded sections cannot be selected");
4429                }
4430                index += 1;
4431            } else {
4432                panic!(
4433                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
4434                    line
4435                );
4436            }
4437        }
4438
4439        let pages: Vec<SettingsPage> = page_builders
4440            .into_iter()
4441            .map(|builder| SettingsPage {
4442                title: builder.title,
4443                items: builder.items.into_boxed_slice(),
4444            })
4445            .collect();
4446
4447        let mut settings_window = SettingsWindow {
4448            title_bar: None,
4449            original_window: None,
4450            worktree_root_dirs: HashMap::default(),
4451            files: Vec::default(),
4452            current_file: crate::SettingsUiFile::User,
4453            project_setting_file_buffers: HashMap::default(),
4454            pages,
4455            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
4456            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
4457            navbar_entries: Vec::default(),
4458            navbar_scroll_handle: UniformListScrollHandle::default(),
4459            navbar_focus_subscriptions: vec![],
4460            filter_table: vec![],
4461            sub_page_stack: vec![],
4462            opening_link: false,
4463            has_query: false,
4464            content_handles: vec![],
4465            search_task: None,
4466            focus_handle: cx.focus_handle(),
4467            navbar_focus_handle: NonFocusableHandle::new(
4468                NAVBAR_CONTAINER_TAB_INDEX,
4469                false,
4470                window,
4471                cx,
4472            ),
4473            content_focus_handle: NonFocusableHandle::new(
4474                CONTENT_CONTAINER_TAB_INDEX,
4475                false,
4476                window,
4477                cx,
4478            ),
4479            files_focus_handle: cx.focus_handle(),
4480            search_index: None,
4481            list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4482            shown_errors: HashSet::default(),
4483            regex_validation_error: None,
4484        };
4485
4486        settings_window.build_filter_table();
4487        settings_window.build_navbar(cx);
4488        for expanded_page_index in expanded_pages {
4489            for entry in &mut settings_window.navbar_entries {
4490                if entry.page_index == expanded_page_index && entry.is_root {
4491                    entry.expanded = true;
4492                }
4493            }
4494        }
4495        settings_window
4496    }
4497
4498    #[track_caller]
4499    fn check_navbar_toggle(
4500        before: &'static str,
4501        toggle_page: &'static str,
4502        after: &'static str,
4503        window: &mut Window,
4504        cx: &mut App,
4505    ) {
4506        let mut settings_window = parse(before, window, cx);
4507        let toggle_page_idx = settings_window
4508            .pages
4509            .iter()
4510            .position(|page| page.title == toggle_page)
4511            .expect("page not found");
4512        let toggle_idx = settings_window
4513            .navbar_entries
4514            .iter()
4515            .position(|entry| entry.page_index == toggle_page_idx)
4516            .expect("page not found");
4517        settings_window.toggle_navbar_entry(toggle_idx);
4518
4519        let expected_settings_window = parse(after, window, cx);
4520
4521        pretty_assertions::assert_eq!(
4522            settings_window
4523                .visible_navbar_entries()
4524                .map(|(_, entry)| entry)
4525                .collect::<Vec<_>>(),
4526            expected_settings_window
4527                .visible_navbar_entries()
4528                .map(|(_, entry)| entry)
4529                .collect::<Vec<_>>(),
4530        );
4531        pretty_assertions::assert_eq!(
4532            settings_window.navbar_entries[settings_window.navbar_entry()],
4533            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
4534        );
4535    }
4536
4537    macro_rules! check_navbar_toggle {
4538        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
4539            #[gpui::test]
4540            fn $name(cx: &mut gpui::TestAppContext) {
4541                let window = cx.add_empty_window();
4542                window.update(|window, cx| {
4543                    register_settings(cx);
4544                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
4545                });
4546            }
4547        };
4548    }
4549
4550    check_navbar_toggle!(
4551        navbar_basic_open,
4552        before: r"
4553        v General
4554        - General
4555        - Privacy*
4556        v Project
4557        - Project Settings
4558        ",
4559        toggle_page: "General",
4560        after: r"
4561        > General*
4562        v Project
4563        - Project Settings
4564        "
4565    );
4566
4567    check_navbar_toggle!(
4568        navbar_basic_close,
4569        before: r"
4570        > General*
4571        - General
4572        - Privacy
4573        v Project
4574        - Project Settings
4575        ",
4576        toggle_page: "General",
4577        after: r"
4578        v General*
4579        - General
4580        - Privacy
4581        v Project
4582        - Project Settings
4583        "
4584    );
4585
4586    check_navbar_toggle!(
4587        navbar_basic_second_root_entry_close,
4588        before: r"
4589        > General
4590        - General
4591        - Privacy
4592        v Project
4593        - Project Settings*
4594        ",
4595        toggle_page: "Project",
4596        after: r"
4597        > General
4598        > Project*
4599        "
4600    );
4601
4602    check_navbar_toggle!(
4603        navbar_toggle_subroot,
4604        before: r"
4605        v General Page
4606        - General
4607        - Privacy
4608        v Project
4609        - Worktree Settings Content*
4610        v AI
4611        - General
4612        > Appearance & Behavior
4613        ",
4614        toggle_page: "Project",
4615        after: r"
4616        v General Page
4617        - General
4618        - Privacy
4619        > Project*
4620        v AI
4621        - General
4622        > Appearance & Behavior
4623        "
4624    );
4625
4626    check_navbar_toggle!(
4627        navbar_toggle_close_propagates_selected_index,
4628        before: r"
4629        v General Page
4630        - General
4631        - Privacy
4632        v Project
4633        - Worktree Settings Content
4634        v AI
4635        - General*
4636        > Appearance & Behavior
4637        ",
4638        toggle_page: "General Page",
4639        after: r"
4640        > General Page*
4641        v Project
4642        - Worktree Settings Content
4643        v AI
4644        - General
4645        > Appearance & Behavior
4646        "
4647    );
4648
4649    check_navbar_toggle!(
4650        navbar_toggle_expand_propagates_selected_index,
4651        before: r"
4652        > General Page
4653        - General
4654        - Privacy
4655        v Project
4656        - Worktree Settings Content
4657        v AI
4658        - General*
4659        > Appearance & Behavior
4660        ",
4661        toggle_page: "General Page",
4662        after: r"
4663        v General Page*
4664        - General
4665        - Privacy
4666        v Project
4667        - Worktree Settings Content
4668        v AI
4669        - General
4670        > Appearance & Behavior
4671        "
4672    );
4673
4674    #[gpui::test]
4675    async fn test_settings_window_shows_worktrees_from_multiple_workspaces(
4676        cx: &mut gpui::TestAppContext,
4677    ) {
4678        use project::Project;
4679        use serde_json::json;
4680
4681        cx.update(|cx| {
4682            register_settings(cx);
4683        });
4684
4685        let app_state = cx.update(|cx| {
4686            let app_state = AppState::test(cx);
4687            AppState::set_global(Arc::downgrade(&app_state), cx);
4688            app_state
4689        });
4690
4691        let fake_fs = app_state.fs.as_fake();
4692
4693        fake_fs
4694            .insert_tree(
4695                "/workspace1",
4696                json!({
4697                    "worktree_a": {
4698                        "file1.rs": "fn main() {}"
4699                    },
4700                    "worktree_b": {
4701                        "file2.rs": "fn test() {}"
4702                    }
4703                }),
4704            )
4705            .await;
4706
4707        fake_fs
4708            .insert_tree(
4709                "/workspace2",
4710                json!({
4711                    "worktree_c": {
4712                        "file3.rs": "fn foo() {}"
4713                    }
4714                }),
4715            )
4716            .await;
4717
4718        let project1 = cx.update(|cx| {
4719            Project::local(
4720                app_state.client.clone(),
4721                app_state.node_runtime.clone(),
4722                app_state.user_store.clone(),
4723                app_state.languages.clone(),
4724                app_state.fs.clone(),
4725                None,
4726                project::LocalProjectFlags::default(),
4727                cx,
4728            )
4729        });
4730
4731        project1
4732            .update(cx, |project, cx| {
4733                project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4734            })
4735            .await
4736            .expect("Failed to create worktree_a");
4737        project1
4738            .update(cx, |project, cx| {
4739                project.find_or_create_worktree("/workspace1/worktree_b", true, cx)
4740            })
4741            .await
4742            .expect("Failed to create worktree_b");
4743
4744        let project2 = cx.update(|cx| {
4745            Project::local(
4746                app_state.client.clone(),
4747                app_state.node_runtime.clone(),
4748                app_state.user_store.clone(),
4749                app_state.languages.clone(),
4750                app_state.fs.clone(),
4751                None,
4752                project::LocalProjectFlags::default(),
4753                cx,
4754            )
4755        });
4756
4757        project2
4758            .update(cx, |project, cx| {
4759                project.find_or_create_worktree("/workspace2/worktree_c", true, cx)
4760            })
4761            .await
4762            .expect("Failed to create worktree_c");
4763
4764        let (_workspace1, cx) = cx.add_window_view(|window, cx| {
4765            Workspace::new(
4766                Default::default(),
4767                project1.clone(),
4768                app_state.clone(),
4769                window,
4770                cx,
4771            )
4772        });
4773
4774        let _workspace1_handle = cx.window_handle().downcast::<Workspace>().unwrap();
4775
4776        let (_workspace2, cx) = cx.add_window_view(|window, cx| {
4777            Workspace::new(
4778                Default::default(),
4779                project2.clone(),
4780                app_state.clone(),
4781                window,
4782                cx,
4783            )
4784        });
4785
4786        let workspace2_handle = cx.window_handle().downcast::<Workspace>().unwrap();
4787
4788        cx.run_until_parked();
4789
4790        let (settings_window, cx) = cx
4791            .add_window_view(|window, cx| SettingsWindow::new(Some(workspace2_handle), window, cx));
4792
4793        cx.run_until_parked();
4794
4795        settings_window.read_with(cx, |settings_window, _| {
4796            let worktree_names: Vec<_> = settings_window
4797                .worktree_root_dirs
4798                .values()
4799                .cloned()
4800                .collect();
4801
4802            assert!(
4803                worktree_names.iter().any(|name| name == "worktree_a"),
4804                "Should contain worktree_a from workspace1, but found: {:?}",
4805                worktree_names
4806            );
4807            assert!(
4808                worktree_names.iter().any(|name| name == "worktree_b"),
4809                "Should contain worktree_b from workspace1, but found: {:?}",
4810                worktree_names
4811            );
4812            assert!(
4813                worktree_names.iter().any(|name| name == "worktree_c"),
4814                "Should contain worktree_c from workspace2, but found: {:?}",
4815                worktree_names
4816            );
4817
4818            assert_eq!(
4819                worktree_names.len(),
4820                3,
4821                "Should have exactly 3 worktrees from both workspaces, but found: {:?}",
4822                worktree_names
4823            );
4824
4825            let project_files: Vec<_> = settings_window
4826                .files
4827                .iter()
4828                .filter_map(|(f, _)| match f {
4829                    SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
4830                    _ => None,
4831                })
4832                .collect();
4833
4834            let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
4835            assert_eq!(
4836                project_files.len(),
4837                unique_project_files.len(),
4838                "Should have no duplicate project files, but found duplicates. All files: {:?}",
4839                project_files
4840            );
4841        });
4842    }
4843
4844    #[gpui::test]
4845    async fn test_settings_window_updates_when_new_workspace_created(
4846        cx: &mut gpui::TestAppContext,
4847    ) {
4848        use project::Project;
4849        use serde_json::json;
4850
4851        cx.update(|cx| {
4852            register_settings(cx);
4853        });
4854
4855        let app_state = cx.update(|cx| {
4856            let app_state = AppState::test(cx);
4857            AppState::set_global(Arc::downgrade(&app_state), cx);
4858            app_state
4859        });
4860
4861        let fake_fs = app_state.fs.as_fake();
4862
4863        fake_fs
4864            .insert_tree(
4865                "/workspace1",
4866                json!({
4867                    "worktree_a": {
4868                        "file1.rs": "fn main() {}"
4869                    }
4870                }),
4871            )
4872            .await;
4873
4874        fake_fs
4875            .insert_tree(
4876                "/workspace2",
4877                json!({
4878                    "worktree_b": {
4879                        "file2.rs": "fn test() {}"
4880                    }
4881                }),
4882            )
4883            .await;
4884
4885        let project1 = cx.update(|cx| {
4886            Project::local(
4887                app_state.client.clone(),
4888                app_state.node_runtime.clone(),
4889                app_state.user_store.clone(),
4890                app_state.languages.clone(),
4891                app_state.fs.clone(),
4892                None,
4893                project::LocalProjectFlags::default(),
4894                cx,
4895            )
4896        });
4897
4898        project1
4899            .update(cx, |project, cx| {
4900                project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4901            })
4902            .await
4903            .expect("Failed to create worktree_a");
4904
4905        let (_workspace1, cx) = cx.add_window_view(|window, cx| {
4906            Workspace::new(
4907                Default::default(),
4908                project1.clone(),
4909                app_state.clone(),
4910                window,
4911                cx,
4912            )
4913        });
4914
4915        let workspace1_handle = cx.window_handle().downcast::<Workspace>().unwrap();
4916
4917        cx.run_until_parked();
4918
4919        let (settings_window, cx) = cx
4920            .add_window_view(|window, cx| SettingsWindow::new(Some(workspace1_handle), window, cx));
4921
4922        cx.run_until_parked();
4923
4924        settings_window.read_with(cx, |settings_window, _| {
4925            assert_eq!(
4926                settings_window.worktree_root_dirs.len(),
4927                1,
4928                "Should have 1 worktree initially"
4929            );
4930        });
4931
4932        let project2 = cx.update(|_, cx| {
4933            Project::local(
4934                app_state.client.clone(),
4935                app_state.node_runtime.clone(),
4936                app_state.user_store.clone(),
4937                app_state.languages.clone(),
4938                app_state.fs.clone(),
4939                None,
4940                project::LocalProjectFlags::default(),
4941                cx,
4942            )
4943        });
4944
4945        project2
4946            .update(&mut cx.cx, |project, cx| {
4947                project.find_or_create_worktree("/workspace2/worktree_b", true, cx)
4948            })
4949            .await
4950            .expect("Failed to create worktree_b");
4951
4952        let (_workspace2, cx) = cx.add_window_view(|window, cx| {
4953            Workspace::new(
4954                Default::default(),
4955                project2.clone(),
4956                app_state.clone(),
4957                window,
4958                cx,
4959            )
4960        });
4961
4962        cx.run_until_parked();
4963
4964        settings_window.read_with(cx, |settings_window, _| {
4965            let worktree_names: Vec<_> = settings_window
4966                .worktree_root_dirs
4967                .values()
4968                .cloned()
4969                .collect();
4970
4971            assert!(
4972                worktree_names.iter().any(|name| name == "worktree_a"),
4973                "Should contain worktree_a, but found: {:?}",
4974                worktree_names
4975            );
4976            assert!(
4977                worktree_names.iter().any(|name| name == "worktree_b"),
4978                "Should contain worktree_b from newly created workspace, but found: {:?}",
4979                worktree_names
4980            );
4981
4982            assert_eq!(
4983                worktree_names.len(),
4984                2,
4985                "Should have 2 worktrees after new workspace created, but found: {:?}",
4986                worktree_names
4987            );
4988
4989            let project_files: Vec<_> = settings_window
4990                .files
4991                .iter()
4992                .filter_map(|(f, _)| match f {
4993                    SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
4994                    _ => None,
4995                })
4996                .collect();
4997
4998            let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
4999            assert_eq!(
5000                project_files.len(),
5001                unique_project_files.len(),
5002                "Should have no duplicate project files, but found duplicates. All files: {:?}",
5003                project_files
5004            );
5005        });
5006    }
5007}
5008
5009#[cfg(test)]
5010mod project_settings_update_tests {
5011    use super::*;
5012    use fs::{FakeFs, Fs as _};
5013    use gpui::TestAppContext;
5014    use project::Project;
5015    use serde_json::json;
5016    use std::sync::atomic::{AtomicUsize, Ordering};
5017
5018    struct TestSetup {
5019        fs: Arc<FakeFs>,
5020        project: Entity<Project>,
5021        worktree_id: WorktreeId,
5022        worktree: WeakEntity<Worktree>,
5023        rel_path: Arc<RelPath>,
5024        project_path: ProjectPath,
5025    }
5026
5027    async fn init_test(cx: &mut TestAppContext, initial_settings: Option<&str>) -> TestSetup {
5028        cx.update(|cx| {
5029            let store = settings::SettingsStore::test(cx);
5030            cx.set_global(store);
5031            theme::init(theme::LoadThemes::JustBase, cx);
5032            editor::init(cx);
5033            menu::init();
5034            let queue = ProjectSettingsUpdateQueue::new(cx);
5035            cx.set_global(queue);
5036        });
5037
5038        let fs = FakeFs::new(cx.executor());
5039        let tree = if let Some(settings_content) = initial_settings {
5040            json!({
5041                ".zed": {
5042                    "settings.json": settings_content
5043                },
5044                "src": { "main.rs": "" }
5045            })
5046        } else {
5047            json!({ "src": { "main.rs": "" } })
5048        };
5049        fs.insert_tree("/project", tree).await;
5050
5051        let project = Project::test(fs.clone(), ["/project".as_ref()], cx).await;
5052
5053        let (worktree_id, worktree) = project.read_with(cx, |project, cx| {
5054            let worktree = project.worktrees(cx).next().unwrap();
5055            (worktree.read(cx).id(), worktree.downgrade())
5056        });
5057
5058        let rel_path: Arc<RelPath> = RelPath::unix(".zed/settings.json")
5059            .expect("valid path")
5060            .into_arc();
5061        let project_path = ProjectPath {
5062            worktree_id,
5063            path: rel_path.clone(),
5064        };
5065
5066        TestSetup {
5067            fs,
5068            project,
5069            worktree_id,
5070            worktree,
5071            rel_path,
5072            project_path,
5073        }
5074    }
5075
5076    #[gpui::test]
5077    async fn test_creates_settings_file_if_missing(cx: &mut TestAppContext) {
5078        let setup = init_test(cx, None).await;
5079
5080        let entry = ProjectSettingsUpdateEntry {
5081            worktree_id: setup.worktree_id,
5082            rel_path: setup.rel_path.clone(),
5083            settings_window: WeakEntity::new_invalid(),
5084            project: setup.project.downgrade(),
5085            worktree: setup.worktree,
5086            update: Box::new(|content, _cx| {
5087                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5088            }),
5089        };
5090
5091        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5092        cx.executor().run_until_parked();
5093
5094        let buffer_store = setup
5095            .project
5096            .read_with(cx, |project, _| project.buffer_store().clone());
5097        let buffer = buffer_store
5098            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5099            .await
5100            .expect("buffer should exist");
5101
5102        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5103        assert!(
5104            text.contains("\"tab_size\": 4"),
5105            "Expected tab_size setting in: {}",
5106            text
5107        );
5108    }
5109
5110    #[gpui::test]
5111    async fn test_updates_existing_settings_file(cx: &mut TestAppContext) {
5112        let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5113
5114        let entry = ProjectSettingsUpdateEntry {
5115            worktree_id: setup.worktree_id,
5116            rel_path: setup.rel_path.clone(),
5117            settings_window: WeakEntity::new_invalid(),
5118            project: setup.project.downgrade(),
5119            worktree: setup.worktree,
5120            update: Box::new(|content, _cx| {
5121                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(8).unwrap());
5122            }),
5123        };
5124
5125        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5126        cx.executor().run_until_parked();
5127
5128        let buffer_store = setup
5129            .project
5130            .read_with(cx, |project, _| project.buffer_store().clone());
5131        let buffer = buffer_store
5132            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5133            .await
5134            .expect("buffer should exist");
5135
5136        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5137        assert!(
5138            text.contains("\"tab_size\": 8"),
5139            "Expected updated tab_size in: {}",
5140            text
5141        );
5142    }
5143
5144    #[gpui::test]
5145    async fn test_updates_are_serialized(cx: &mut TestAppContext) {
5146        let setup = init_test(cx, Some("{}")).await;
5147
5148        let update_order = Arc::new(std::sync::Mutex::new(Vec::new()));
5149
5150        for i in 1..=3 {
5151            let update_order = update_order.clone();
5152            let entry = ProjectSettingsUpdateEntry {
5153                worktree_id: setup.worktree_id,
5154                rel_path: setup.rel_path.clone(),
5155                settings_window: WeakEntity::new_invalid(),
5156                project: setup.project.downgrade(),
5157                worktree: setup.worktree.clone(),
5158                update: Box::new(move |content, _cx| {
5159                    update_order.lock().unwrap().push(i);
5160                    content.project.all_languages.defaults.tab_size =
5161                        Some(NonZeroU32::new(i).unwrap());
5162                }),
5163            };
5164            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5165        }
5166
5167        cx.executor().run_until_parked();
5168
5169        let order = update_order.lock().unwrap().clone();
5170        assert_eq!(order, vec![1, 2, 3], "Updates should be processed in order");
5171
5172        let buffer_store = setup
5173            .project
5174            .read_with(cx, |project, _| project.buffer_store().clone());
5175        let buffer = buffer_store
5176            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5177            .await
5178            .expect("buffer should exist");
5179
5180        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5181        assert!(
5182            text.contains("\"tab_size\": 3"),
5183            "Final tab_size should be 3: {}",
5184            text
5185        );
5186    }
5187
5188    #[gpui::test]
5189    async fn test_queue_continues_after_failure(cx: &mut TestAppContext) {
5190        let setup = init_test(cx, Some("{}")).await;
5191
5192        let successful_updates = Arc::new(AtomicUsize::new(0));
5193
5194        {
5195            let successful_updates = successful_updates.clone();
5196            let entry = ProjectSettingsUpdateEntry {
5197                worktree_id: setup.worktree_id,
5198                rel_path: setup.rel_path.clone(),
5199                settings_window: WeakEntity::new_invalid(),
5200                project: setup.project.downgrade(),
5201                worktree: setup.worktree.clone(),
5202                update: Box::new(move |content, _cx| {
5203                    successful_updates.fetch_add(1, Ordering::SeqCst);
5204                    content.project.all_languages.defaults.tab_size =
5205                        Some(NonZeroU32::new(2).unwrap());
5206                }),
5207            };
5208            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5209        }
5210
5211        {
5212            let entry = ProjectSettingsUpdateEntry {
5213                worktree_id: setup.worktree_id,
5214                rel_path: setup.rel_path.clone(),
5215                settings_window: WeakEntity::new_invalid(),
5216                project: WeakEntity::new_invalid(),
5217                worktree: setup.worktree.clone(),
5218                update: Box::new(|content, _cx| {
5219                    content.project.all_languages.defaults.tab_size =
5220                        Some(NonZeroU32::new(99).unwrap());
5221                }),
5222            };
5223            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5224        }
5225
5226        {
5227            let successful_updates = successful_updates.clone();
5228            let entry = ProjectSettingsUpdateEntry {
5229                worktree_id: setup.worktree_id,
5230                rel_path: setup.rel_path.clone(),
5231                settings_window: WeakEntity::new_invalid(),
5232                project: setup.project.downgrade(),
5233                worktree: setup.worktree.clone(),
5234                update: Box::new(move |content, _cx| {
5235                    successful_updates.fetch_add(1, Ordering::SeqCst);
5236                    content.project.all_languages.defaults.tab_size =
5237                        Some(NonZeroU32::new(4).unwrap());
5238                }),
5239            };
5240            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5241        }
5242
5243        cx.executor().run_until_parked();
5244
5245        assert_eq!(
5246            successful_updates.load(Ordering::SeqCst),
5247            2,
5248            "Two updates should have succeeded despite middle failure"
5249        );
5250
5251        let buffer_store = setup
5252            .project
5253            .read_with(cx, |project, _| project.buffer_store().clone());
5254        let buffer = buffer_store
5255            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5256            .await
5257            .expect("buffer should exist");
5258
5259        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5260        assert!(
5261            text.contains("\"tab_size\": 4"),
5262            "Final tab_size should be 4 (third update): {}",
5263            text
5264        );
5265    }
5266
5267    #[gpui::test]
5268    async fn test_handles_dropped_worktree(cx: &mut TestAppContext) {
5269        let setup = init_test(cx, Some("{}")).await;
5270
5271        let entry = ProjectSettingsUpdateEntry {
5272            worktree_id: setup.worktree_id,
5273            rel_path: setup.rel_path.clone(),
5274            settings_window: WeakEntity::new_invalid(),
5275            project: setup.project.downgrade(),
5276            worktree: WeakEntity::new_invalid(),
5277            update: Box::new(|content, _cx| {
5278                content.project.all_languages.defaults.tab_size =
5279                    Some(NonZeroU32::new(99).unwrap());
5280            }),
5281        };
5282
5283        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5284        cx.executor().run_until_parked();
5285
5286        let file_content = setup
5287            .fs
5288            .load("/project/.zed/settings.json".as_ref())
5289            .await
5290            .unwrap();
5291        assert_eq!(
5292            file_content, "{}",
5293            "File should be unchanged when worktree is dropped"
5294        );
5295    }
5296
5297    #[gpui::test]
5298    async fn test_reloads_conflicted_buffer(cx: &mut TestAppContext) {
5299        let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5300
5301        let buffer_store = setup
5302            .project
5303            .read_with(cx, |project, _| project.buffer_store().clone());
5304        let buffer = buffer_store
5305            .update(cx, |store, cx| {
5306                store.open_buffer(setup.project_path.clone(), cx)
5307            })
5308            .await
5309            .expect("buffer should exist");
5310
5311        buffer.update(cx, |buffer, cx| {
5312            buffer.edit([(0..0, "// comment\n")], None, cx);
5313        });
5314
5315        let has_unsaved_edits = buffer.read_with(cx, |buffer, _| buffer.has_unsaved_edits());
5316        assert!(has_unsaved_edits, "Buffer should have unsaved edits");
5317
5318        setup
5319            .fs
5320            .save(
5321                "/project/.zed/settings.json".as_ref(),
5322                &r#"{ "tab_size": 99 }"#.into(),
5323                Default::default(),
5324            )
5325            .await
5326            .expect("save should succeed");
5327
5328        cx.executor().run_until_parked();
5329
5330        let has_conflict = buffer.read_with(cx, |buffer, _| buffer.has_conflict());
5331        assert!(
5332            has_conflict,
5333            "Buffer should have conflict after external modification"
5334        );
5335
5336        let (settings_window, _) = cx.add_window_view(|window, cx| {
5337            let mut sw = SettingsWindow::test(window, cx);
5338            sw.project_setting_file_buffers
5339                .insert(setup.project_path.clone(), buffer.clone());
5340            sw
5341        });
5342
5343        let entry = ProjectSettingsUpdateEntry {
5344            worktree_id: setup.worktree_id,
5345            rel_path: setup.rel_path.clone(),
5346            settings_window: settings_window.downgrade(),
5347            project: setup.project.downgrade(),
5348            worktree: setup.worktree.clone(),
5349            update: Box::new(|content, _cx| {
5350                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5351            }),
5352        };
5353
5354        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5355        cx.executor().run_until_parked();
5356
5357        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5358        assert!(
5359            text.contains("\"tab_size\": 4"),
5360            "Buffer should have the new tab_size after reload and update: {}",
5361            text
5362        );
5363        assert!(
5364            !text.contains("// comment"),
5365            "Buffer should not contain the unsaved edit after reload: {}",
5366            text
5367        );
5368        assert!(
5369            !text.contains("99"),
5370            "Buffer should not contain the external modification value: {}",
5371            text
5372        );
5373    }
5374}