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