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