settings_ui.rs

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