settings_ui.rs

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