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::NewThreadLocation>(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                            .start_icon(Icon::new(IconName::Debug).color(Color::Error))
 929                            .tab_index(0_isize)
 930                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 931                            .into_any_element(),
 932                        sub_field,
 933                        cx,
 934                    ),
 935                };
 936
 937                let field = if padding {
 938                    field.map(apply_padding)
 939                } else {
 940                    field
 941                };
 942
 943                (field, field_renderer_or_warning.is_ok())
 944            };
 945
 946        match self {
 947            SettingsPageItem::SectionHeader(header) => {
 948                SettingsSectionHeader::new(SharedString::new_static(header)).into_any_element()
 949            }
 950            SettingsPageItem::SettingItem(setting_item) => {
 951                let (field_with_padding, _) =
 952                    render_setting_item_inner(setting_item, true, false, cx);
 953
 954                v_flex()
 955                    .group("setting-item")
 956                    .px_8()
 957                    .child(field_with_padding)
 958                    .when(bottom_border, |this| this.child(Divider::horizontal()))
 959                    .into_any_element()
 960            }
 961            SettingsPageItem::SubPageLink(sub_page_link) => v_flex()
 962                .group("setting-item")
 963                .px_8()
 964                .child(
 965                    h_flex()
 966                        .id(sub_page_link.title.clone())
 967                        .w_full()
 968                        .min_w_0()
 969                        .justify_between()
 970                        .map(apply_padding)
 971                        .child(
 972                            v_flex()
 973                                .relative()
 974                                .w_full()
 975                                .max_w_1_2()
 976                                .child(Label::new(sub_page_link.title.clone()))
 977                                .when_some(
 978                                    sub_page_link.description.as_ref(),
 979                                    |this, description| {
 980                                        this.child(
 981                                            Label::new(description.clone())
 982                                                .size(LabelSize::Small)
 983                                                .color(Color::Muted),
 984                                        )
 985                                    },
 986                                ),
 987                        )
 988                        .child(
 989                            Button::new(
 990                                ("sub-page".into(), sub_page_link.title.clone()),
 991                                "Configure",
 992                            )
 993                            .tab_index(0_isize)
 994                            .end_icon(
 995                                Icon::new(IconName::ChevronRight)
 996                                    .size(IconSize::Small)
 997                                    .color(Color::Muted),
 998                            )
 999                            .style(ButtonStyle::OutlinedGhost)
1000                            .size(ButtonSize::Medium)
1001                            .on_click({
1002                                let sub_page_link = sub_page_link.clone();
1003                                cx.listener(move |this, _, window, cx| {
1004                                    let header_text = this
1005                                        .sub_page_stack
1006                                        .last()
1007                                        .map(|sub_page| sub_page.link.title.clone())
1008                                        .or_else(|| {
1009                                            this.current_page()
1010                                                .items
1011                                                .iter()
1012                                                .take(item_index)
1013                                                .rev()
1014                                                .find_map(|item| {
1015                                                    item.header_text().map(SharedString::new_static)
1016                                                })
1017                                        });
1018
1019                                    let Some(header) = header_text else {
1020                                        unreachable!(
1021                                            "All items always have a section header above them"
1022                                        )
1023                                    };
1024
1025                                    this.push_sub_page(sub_page_link.clone(), header, window, cx)
1026                                })
1027                            }),
1028                        )
1029                        .child(render_settings_item_link(
1030                            sub_page_link.title.clone(),
1031                            sub_page_link.json_path,
1032                            false,
1033                            cx,
1034                        )),
1035                )
1036                .when(bottom_border, |this| this.child(Divider::horizontal()))
1037                .into_any_element(),
1038            SettingsPageItem::DynamicItem(DynamicItem {
1039                discriminant: discriminant_setting_item,
1040                pick_discriminant,
1041                fields,
1042            }) => {
1043                let file = file.to_settings();
1044                let discriminant = SettingsStore::global(cx)
1045                    .get_value_from_file(file, *pick_discriminant)
1046                    .1;
1047
1048                let (discriminant_element, rendered_ok) =
1049                    render_setting_item_inner(discriminant_setting_item, true, false, cx);
1050
1051                let has_sub_fields =
1052                    rendered_ok && discriminant.is_some_and(|d| !fields[d].is_empty());
1053
1054                let mut content = v_flex()
1055                    .id("dynamic-item")
1056                    .child(
1057                        div()
1058                            .group("setting-item")
1059                            .px_8()
1060                            .child(discriminant_element.when(has_sub_fields, |this| this.pb_4())),
1061                    )
1062                    .when(!has_sub_fields && bottom_border, |this| {
1063                        this.child(h_flex().px_8().child(Divider::horizontal()))
1064                    });
1065
1066                if rendered_ok {
1067                    let discriminant =
1068                        discriminant.expect("This should be Some if rendered_ok is true");
1069                    let sub_fields = &fields[discriminant];
1070                    let sub_field_count = sub_fields.len();
1071
1072                    for (index, field) in sub_fields.iter().enumerate() {
1073                        let is_last_sub_field = index == sub_field_count - 1;
1074                        let (raw_field, _) = render_setting_item_inner(field, false, true, cx);
1075
1076                        content = content.child(
1077                            raw_field
1078                                .group("setting-sub-item")
1079                                .mx_8()
1080                                .p_4()
1081                                .border_t_1()
1082                                .when(is_last_sub_field, |this| this.border_b_1())
1083                                .when(is_last_sub_field && extra_bottom_padding, |this| {
1084                                    this.mb_8()
1085                                })
1086                                .border_dashed()
1087                                .border_color(cx.theme().colors().border_variant)
1088                                .bg(cx.theme().colors().element_background.opacity(0.2)),
1089                        );
1090                    }
1091                }
1092
1093                return content.into_any_element();
1094            }
1095            SettingsPageItem::ActionLink(action_link) => v_flex()
1096                .group("setting-item")
1097                .px_8()
1098                .child(
1099                    h_flex()
1100                        .id(action_link.title.clone())
1101                        .w_full()
1102                        .min_w_0()
1103                        .justify_between()
1104                        .map(apply_padding)
1105                        .child(
1106                            v_flex()
1107                                .relative()
1108                                .w_full()
1109                                .max_w_1_2()
1110                                .child(Label::new(action_link.title.clone()))
1111                                .when_some(
1112                                    action_link.description.as_ref(),
1113                                    |this, description| {
1114                                        this.child(
1115                                            Label::new(description.clone())
1116                                                .size(LabelSize::Small)
1117                                                .color(Color::Muted),
1118                                        )
1119                                    },
1120                                ),
1121                        )
1122                        .child(
1123                            Button::new(
1124                                ("action-link".into(), action_link.title.clone()),
1125                                action_link.button_text.clone(),
1126                            )
1127                            .tab_index(0_isize)
1128                            .end_icon(
1129                                Icon::new(IconName::ArrowUpRight)
1130                                    .size(IconSize::Small)
1131                                    .color(Color::Muted),
1132                            )
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        .end_icon(
4178            Icon::new(IconName::ChevronUpDown)
4179                .size(IconSize::Small)
4180                .color(Color::Muted),
4181        )
4182}
4183
4184fn render_font_picker(
4185    field: SettingField<settings::FontFamilyName>,
4186    file: SettingsUiFile,
4187    _metadata: Option<&SettingsFieldMetadata>,
4188    _window: &mut Window,
4189    cx: &mut App,
4190) -> AnyElement {
4191    let current_value = SettingsStore::global(cx)
4192        .get_value_from_file(file.to_settings(), field.pick)
4193        .1
4194        .cloned()
4195        .map_or_else(|| SharedString::default(), |value| value.into_gpui());
4196
4197    PopoverMenu::new("font-picker")
4198        .trigger(render_picker_trigger_button(
4199            "font_family_picker_trigger".into(),
4200            current_value.clone(),
4201        ))
4202        .menu(move |window, cx| {
4203            let file = file.clone();
4204            let current_value = current_value.clone();
4205
4206            Some(cx.new(move |cx| {
4207                font_picker(
4208                    current_value,
4209                    move |font_name, window, cx| {
4210                        update_settings_file(
4211                            file.clone(),
4212                            field.json_path,
4213                            window,
4214                            cx,
4215                            move |settings, _cx| {
4216                                (field.write)(settings, Some(font_name.to_string().into()));
4217                            },
4218                        )
4219                        .log_err(); // todo(settings_ui) don't log err
4220                    },
4221                    window,
4222                    cx,
4223                )
4224            }))
4225        })
4226        .anchor(gpui::Corner::TopLeft)
4227        .offset(gpui::Point {
4228            x: px(0.0),
4229            y: px(2.0),
4230        })
4231        .with_handle(ui::PopoverMenuHandle::default())
4232        .into_any_element()
4233}
4234
4235fn render_theme_picker(
4236    field: SettingField<settings::ThemeName>,
4237    file: SettingsUiFile,
4238    _metadata: Option<&SettingsFieldMetadata>,
4239    _window: &mut Window,
4240    cx: &mut App,
4241) -> AnyElement {
4242    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4243    let current_value = value
4244        .cloned()
4245        .map(|theme_name| theme_name.0.into())
4246        .unwrap_or_else(|| cx.theme().name.clone());
4247
4248    PopoverMenu::new("theme-picker")
4249        .trigger(render_picker_trigger_button(
4250            "theme_picker_trigger".into(),
4251            current_value.clone(),
4252        ))
4253        .menu(move |window, cx| {
4254            Some(cx.new(|cx| {
4255                let file = file.clone();
4256                let current_value = current_value.clone();
4257                theme_picker(
4258                    current_value,
4259                    move |theme_name, window, cx| {
4260                        update_settings_file(
4261                            file.clone(),
4262                            field.json_path,
4263                            window,
4264                            cx,
4265                            move |settings, _cx| {
4266                                (field.write)(
4267                                    settings,
4268                                    Some(settings::ThemeName(theme_name.into())),
4269                                );
4270                            },
4271                        )
4272                        .log_err(); // todo(settings_ui) don't log err
4273                    },
4274                    window,
4275                    cx,
4276                )
4277            }))
4278        })
4279        .anchor(gpui::Corner::TopLeft)
4280        .offset(gpui::Point {
4281            x: px(0.0),
4282            y: px(2.0),
4283        })
4284        .with_handle(ui::PopoverMenuHandle::default())
4285        .into_any_element()
4286}
4287
4288fn render_icon_theme_picker(
4289    field: SettingField<settings::IconThemeName>,
4290    file: SettingsUiFile,
4291    _metadata: Option<&SettingsFieldMetadata>,
4292    _window: &mut Window,
4293    cx: &mut App,
4294) -> AnyElement {
4295    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4296    let current_value = value
4297        .cloned()
4298        .map(|theme_name| theme_name.0.into())
4299        .unwrap_or_else(|| cx.theme().name.clone());
4300
4301    PopoverMenu::new("icon-theme-picker")
4302        .trigger(render_picker_trigger_button(
4303            "icon_theme_picker_trigger".into(),
4304            current_value.clone(),
4305        ))
4306        .menu(move |window, cx| {
4307            Some(cx.new(|cx| {
4308                let file = file.clone();
4309                let current_value = current_value.clone();
4310                icon_theme_picker(
4311                    current_value,
4312                    move |theme_name, window, cx| {
4313                        update_settings_file(
4314                            file.clone(),
4315                            field.json_path,
4316                            window,
4317                            cx,
4318                            move |settings, _cx| {
4319                                (field.write)(
4320                                    settings,
4321                                    Some(settings::IconThemeName(theme_name.into())),
4322                                );
4323                            },
4324                        )
4325                        .log_err(); // todo(settings_ui) don't log err
4326                    },
4327                    window,
4328                    cx,
4329                )
4330            }))
4331        })
4332        .anchor(gpui::Corner::TopLeft)
4333        .offset(gpui::Point {
4334            x: px(0.0),
4335            y: px(2.0),
4336        })
4337        .with_handle(ui::PopoverMenuHandle::default())
4338        .into_any_element()
4339}
4340
4341#[cfg(test)]
4342pub mod test {
4343
4344    use super::*;
4345
4346    impl SettingsWindow {
4347        fn navbar_entry(&self) -> usize {
4348            self.navbar_entry
4349        }
4350
4351        #[cfg(any(test, feature = "test-support"))]
4352        pub fn test(window: &mut Window, cx: &mut Context<Self>) -> Self {
4353            let search_bar = cx.new(|cx| Editor::single_line(window, cx));
4354            let dummy_page = SettingsPage {
4355                title: "Test",
4356                items: Box::new([]),
4357            };
4358            Self {
4359                title_bar: None,
4360                original_window: None,
4361                worktree_root_dirs: HashMap::default(),
4362                files: Vec::default(),
4363                current_file: SettingsUiFile::User,
4364                project_setting_file_buffers: HashMap::default(),
4365                pages: vec![dummy_page],
4366                search_bar,
4367                navbar_entry: 0,
4368                navbar_entries: Vec::default(),
4369                navbar_scroll_handle: UniformListScrollHandle::default(),
4370                navbar_focus_subscriptions: Vec::default(),
4371                filter_table: Vec::default(),
4372                has_query: false,
4373                content_handles: Vec::default(),
4374                search_task: None,
4375                sub_page_stack: Vec::default(),
4376                opening_link: false,
4377                focus_handle: cx.focus_handle(),
4378                navbar_focus_handle: NonFocusableHandle::new(
4379                    NAVBAR_CONTAINER_TAB_INDEX,
4380                    false,
4381                    window,
4382                    cx,
4383                ),
4384                content_focus_handle: NonFocusableHandle::new(
4385                    CONTENT_CONTAINER_TAB_INDEX,
4386                    false,
4387                    window,
4388                    cx,
4389                ),
4390                files_focus_handle: cx.focus_handle(),
4391                search_index: None,
4392                list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4393                shown_errors: HashSet::default(),
4394                regex_validation_error: None,
4395            }
4396        }
4397    }
4398
4399    impl PartialEq for NavBarEntry {
4400        fn eq(&self, other: &Self) -> bool {
4401            self.title == other.title
4402                && self.is_root == other.is_root
4403                && self.expanded == other.expanded
4404                && self.page_index == other.page_index
4405                && self.item_index == other.item_index
4406            // ignoring focus_handle
4407        }
4408    }
4409
4410    pub fn register_settings(cx: &mut App) {
4411        settings::init(cx);
4412        theme::init(theme::LoadThemes::JustBase, cx);
4413        editor::init(cx);
4414        menu::init();
4415    }
4416
4417    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
4418        struct PageBuilder {
4419            title: &'static str,
4420            items: Vec<SettingsPageItem>,
4421        }
4422        let mut page_builders: Vec<PageBuilder> = Vec::new();
4423        let mut expanded_pages = Vec::new();
4424        let mut selected_idx = None;
4425        let mut index = 0;
4426        let mut in_expanded_section = false;
4427
4428        for mut line in input
4429            .lines()
4430            .map(|line| line.trim())
4431            .filter(|line| !line.is_empty())
4432        {
4433            if let Some(pre) = line.strip_suffix('*') {
4434                assert!(selected_idx.is_none(), "Only one selected entry allowed");
4435                selected_idx = Some(index);
4436                line = pre;
4437            }
4438            let (kind, title) = line.split_once(" ").unwrap();
4439            assert_eq!(kind.len(), 1);
4440            let kind = kind.chars().next().unwrap();
4441            if kind == 'v' {
4442                let page_idx = page_builders.len();
4443                expanded_pages.push(page_idx);
4444                page_builders.push(PageBuilder {
4445                    title,
4446                    items: vec![],
4447                });
4448                index += 1;
4449                in_expanded_section = true;
4450            } else if kind == '>' {
4451                page_builders.push(PageBuilder {
4452                    title,
4453                    items: vec![],
4454                });
4455                index += 1;
4456                in_expanded_section = false;
4457            } else if kind == '-' {
4458                page_builders
4459                    .last_mut()
4460                    .unwrap()
4461                    .items
4462                    .push(SettingsPageItem::SectionHeader(title));
4463                if selected_idx == Some(index) && !in_expanded_section {
4464                    panic!("Items in unexpanded sections cannot be selected");
4465                }
4466                index += 1;
4467            } else {
4468                panic!(
4469                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
4470                    line
4471                );
4472            }
4473        }
4474
4475        let pages: Vec<SettingsPage> = page_builders
4476            .into_iter()
4477            .map(|builder| SettingsPage {
4478                title: builder.title,
4479                items: builder.items.into_boxed_slice(),
4480            })
4481            .collect();
4482
4483        let mut settings_window = SettingsWindow {
4484            title_bar: None,
4485            original_window: None,
4486            worktree_root_dirs: HashMap::default(),
4487            files: Vec::default(),
4488            current_file: crate::SettingsUiFile::User,
4489            project_setting_file_buffers: HashMap::default(),
4490            pages,
4491            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
4492            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
4493            navbar_entries: Vec::default(),
4494            navbar_scroll_handle: UniformListScrollHandle::default(),
4495            navbar_focus_subscriptions: vec![],
4496            filter_table: vec![],
4497            sub_page_stack: vec![],
4498            opening_link: false,
4499            has_query: false,
4500            content_handles: vec![],
4501            search_task: None,
4502            focus_handle: cx.focus_handle(),
4503            navbar_focus_handle: NonFocusableHandle::new(
4504                NAVBAR_CONTAINER_TAB_INDEX,
4505                false,
4506                window,
4507                cx,
4508            ),
4509            content_focus_handle: NonFocusableHandle::new(
4510                CONTENT_CONTAINER_TAB_INDEX,
4511                false,
4512                window,
4513                cx,
4514            ),
4515            files_focus_handle: cx.focus_handle(),
4516            search_index: None,
4517            list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4518            shown_errors: HashSet::default(),
4519            regex_validation_error: None,
4520        };
4521
4522        settings_window.build_filter_table();
4523        settings_window.build_navbar(cx);
4524        for expanded_page_index in expanded_pages {
4525            for entry in &mut settings_window.navbar_entries {
4526                if entry.page_index == expanded_page_index && entry.is_root {
4527                    entry.expanded = true;
4528                }
4529            }
4530        }
4531        settings_window
4532    }
4533
4534    #[track_caller]
4535    fn check_navbar_toggle(
4536        before: &'static str,
4537        toggle_page: &'static str,
4538        after: &'static str,
4539        window: &mut Window,
4540        cx: &mut App,
4541    ) {
4542        let mut settings_window = parse(before, window, cx);
4543        let toggle_page_idx = settings_window
4544            .pages
4545            .iter()
4546            .position(|page| page.title == toggle_page)
4547            .expect("page not found");
4548        let toggle_idx = settings_window
4549            .navbar_entries
4550            .iter()
4551            .position(|entry| entry.page_index == toggle_page_idx)
4552            .expect("page not found");
4553        settings_window.toggle_navbar_entry(toggle_idx);
4554
4555        let expected_settings_window = parse(after, window, cx);
4556
4557        pretty_assertions::assert_eq!(
4558            settings_window
4559                .visible_navbar_entries()
4560                .map(|(_, entry)| entry)
4561                .collect::<Vec<_>>(),
4562            expected_settings_window
4563                .visible_navbar_entries()
4564                .map(|(_, entry)| entry)
4565                .collect::<Vec<_>>(),
4566        );
4567        pretty_assertions::assert_eq!(
4568            settings_window.navbar_entries[settings_window.navbar_entry()],
4569            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
4570        );
4571    }
4572
4573    macro_rules! check_navbar_toggle {
4574        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
4575            #[gpui::test]
4576            fn $name(cx: &mut gpui::TestAppContext) {
4577                let window = cx.add_empty_window();
4578                window.update(|window, cx| {
4579                    register_settings(cx);
4580                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
4581                });
4582            }
4583        };
4584    }
4585
4586    check_navbar_toggle!(
4587        navbar_basic_open,
4588        before: r"
4589        v General
4590        - General
4591        - Privacy*
4592        v Project
4593        - Project Settings
4594        ",
4595        toggle_page: "General",
4596        after: r"
4597        > General*
4598        v Project
4599        - Project Settings
4600        "
4601    );
4602
4603    check_navbar_toggle!(
4604        navbar_basic_close,
4605        before: r"
4606        > General*
4607        - General
4608        - Privacy
4609        v Project
4610        - Project Settings
4611        ",
4612        toggle_page: "General",
4613        after: r"
4614        v General*
4615        - General
4616        - Privacy
4617        v Project
4618        - Project Settings
4619        "
4620    );
4621
4622    check_navbar_toggle!(
4623        navbar_basic_second_root_entry_close,
4624        before: r"
4625        > General
4626        - General
4627        - Privacy
4628        v Project
4629        - Project Settings*
4630        ",
4631        toggle_page: "Project",
4632        after: r"
4633        > General
4634        > Project*
4635        "
4636    );
4637
4638    check_navbar_toggle!(
4639        navbar_toggle_subroot,
4640        before: r"
4641        v General Page
4642        - General
4643        - Privacy
4644        v Project
4645        - Worktree Settings Content*
4646        v AI
4647        - General
4648        > Appearance & Behavior
4649        ",
4650        toggle_page: "Project",
4651        after: r"
4652        v General Page
4653        - General
4654        - Privacy
4655        > Project*
4656        v AI
4657        - General
4658        > Appearance & Behavior
4659        "
4660    );
4661
4662    check_navbar_toggle!(
4663        navbar_toggle_close_propagates_selected_index,
4664        before: r"
4665        v General Page
4666        - General
4667        - Privacy
4668        v Project
4669        - Worktree Settings Content
4670        v AI
4671        - General*
4672        > Appearance & Behavior
4673        ",
4674        toggle_page: "General Page",
4675        after: r"
4676        > General Page*
4677        v Project
4678        - Worktree Settings Content
4679        v AI
4680        - General
4681        > Appearance & Behavior
4682        "
4683    );
4684
4685    check_navbar_toggle!(
4686        navbar_toggle_expand_propagates_selected_index,
4687        before: r"
4688        > General Page
4689        - General
4690        - Privacy
4691        v Project
4692        - Worktree Settings Content
4693        v AI
4694        - General*
4695        > Appearance & Behavior
4696        ",
4697        toggle_page: "General Page",
4698        after: r"
4699        v General Page*
4700        - General
4701        - Privacy
4702        v Project
4703        - Worktree Settings Content
4704        v AI
4705        - General
4706        > Appearance & Behavior
4707        "
4708    );
4709
4710    #[gpui::test]
4711    async fn test_settings_window_shows_worktrees_from_multiple_workspaces(
4712        cx: &mut gpui::TestAppContext,
4713    ) {
4714        use project::Project;
4715        use serde_json::json;
4716
4717        cx.update(|cx| {
4718            register_settings(cx);
4719        });
4720
4721        let app_state = cx.update(|cx| {
4722            let app_state = AppState::test(cx);
4723            AppState::set_global(Arc::downgrade(&app_state), cx);
4724            app_state
4725        });
4726
4727        let fake_fs = app_state.fs.as_fake();
4728
4729        fake_fs
4730            .insert_tree(
4731                "/workspace1",
4732                json!({
4733                    "worktree_a": {
4734                        "file1.rs": "fn main() {}"
4735                    },
4736                    "worktree_b": {
4737                        "file2.rs": "fn test() {}"
4738                    }
4739                }),
4740            )
4741            .await;
4742
4743        fake_fs
4744            .insert_tree(
4745                "/workspace2",
4746                json!({
4747                    "worktree_c": {
4748                        "file3.rs": "fn foo() {}"
4749                    }
4750                }),
4751            )
4752            .await;
4753
4754        let project1 = cx.update(|cx| {
4755            Project::local(
4756                app_state.client.clone(),
4757                app_state.node_runtime.clone(),
4758                app_state.user_store.clone(),
4759                app_state.languages.clone(),
4760                app_state.fs.clone(),
4761                None,
4762                project::LocalProjectFlags::default(),
4763                cx,
4764            )
4765        });
4766
4767        project1
4768            .update(cx, |project, cx| {
4769                project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4770            })
4771            .await
4772            .expect("Failed to create worktree_a");
4773        project1
4774            .update(cx, |project, cx| {
4775                project.find_or_create_worktree("/workspace1/worktree_b", true, cx)
4776            })
4777            .await
4778            .expect("Failed to create worktree_b");
4779
4780        let project2 = cx.update(|cx| {
4781            Project::local(
4782                app_state.client.clone(),
4783                app_state.node_runtime.clone(),
4784                app_state.user_store.clone(),
4785                app_state.languages.clone(),
4786                app_state.fs.clone(),
4787                None,
4788                project::LocalProjectFlags::default(),
4789                cx,
4790            )
4791        });
4792
4793        project2
4794            .update(cx, |project, cx| {
4795                project.find_or_create_worktree("/workspace2/worktree_c", true, cx)
4796            })
4797            .await
4798            .expect("Failed to create worktree_c");
4799
4800        let (_multi_workspace1, cx) = cx.add_window_view(|window, cx| {
4801            let workspace = cx.new(|cx| {
4802                Workspace::new(
4803                    Default::default(),
4804                    project1.clone(),
4805                    app_state.clone(),
4806                    window,
4807                    cx,
4808                )
4809            });
4810            MultiWorkspace::new(workspace, window, cx)
4811        });
4812
4813        let (_multi_workspace2, cx) = cx.add_window_view(|window, cx| {
4814            let workspace = cx.new(|cx| {
4815                Workspace::new(
4816                    Default::default(),
4817                    project2.clone(),
4818                    app_state.clone(),
4819                    window,
4820                    cx,
4821                )
4822            });
4823            MultiWorkspace::new(workspace, window, cx)
4824        });
4825
4826        let workspace2_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
4827
4828        cx.run_until_parked();
4829
4830        let (settings_window, cx) = cx
4831            .add_window_view(|window, cx| SettingsWindow::new(Some(workspace2_handle), window, cx));
4832
4833        cx.run_until_parked();
4834
4835        settings_window.read_with(cx, |settings_window, _| {
4836            let worktree_names: Vec<_> = settings_window
4837                .worktree_root_dirs
4838                .values()
4839                .cloned()
4840                .collect();
4841
4842            assert!(
4843                worktree_names.iter().any(|name| name == "worktree_a"),
4844                "Should contain worktree_a from workspace1, but found: {:?}",
4845                worktree_names
4846            );
4847            assert!(
4848                worktree_names.iter().any(|name| name == "worktree_b"),
4849                "Should contain worktree_b from workspace1, but found: {:?}",
4850                worktree_names
4851            );
4852            assert!(
4853                worktree_names.iter().any(|name| name == "worktree_c"),
4854                "Should contain worktree_c from workspace2, but found: {:?}",
4855                worktree_names
4856            );
4857
4858            assert_eq!(
4859                worktree_names.len(),
4860                3,
4861                "Should have exactly 3 worktrees from both workspaces, but found: {:?}",
4862                worktree_names
4863            );
4864
4865            let project_files: Vec<_> = settings_window
4866                .files
4867                .iter()
4868                .filter_map(|(f, _)| match f {
4869                    SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
4870                    _ => None,
4871                })
4872                .collect();
4873
4874            let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
4875            assert_eq!(
4876                project_files.len(),
4877                unique_project_files.len(),
4878                "Should have no duplicate project files, but found duplicates. All files: {:?}",
4879                project_files
4880            );
4881        });
4882    }
4883
4884    #[gpui::test]
4885    async fn test_settings_window_updates_when_new_workspace_created(
4886        cx: &mut gpui::TestAppContext,
4887    ) {
4888        use project::Project;
4889        use serde_json::json;
4890
4891        cx.update(|cx| {
4892            register_settings(cx);
4893        });
4894
4895        let app_state = cx.update(|cx| {
4896            let app_state = AppState::test(cx);
4897            AppState::set_global(Arc::downgrade(&app_state), cx);
4898            app_state
4899        });
4900
4901        let fake_fs = app_state.fs.as_fake();
4902
4903        fake_fs
4904            .insert_tree(
4905                "/workspace1",
4906                json!({
4907                    "worktree_a": {
4908                        "file1.rs": "fn main() {}"
4909                    }
4910                }),
4911            )
4912            .await;
4913
4914        fake_fs
4915            .insert_tree(
4916                "/workspace2",
4917                json!({
4918                    "worktree_b": {
4919                        "file2.rs": "fn test() {}"
4920                    }
4921                }),
4922            )
4923            .await;
4924
4925        let project1 = cx.update(|cx| {
4926            Project::local(
4927                app_state.client.clone(),
4928                app_state.node_runtime.clone(),
4929                app_state.user_store.clone(),
4930                app_state.languages.clone(),
4931                app_state.fs.clone(),
4932                None,
4933                project::LocalProjectFlags::default(),
4934                cx,
4935            )
4936        });
4937
4938        project1
4939            .update(cx, |project, cx| {
4940                project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4941            })
4942            .await
4943            .expect("Failed to create worktree_a");
4944
4945        let (_multi_workspace1, cx) = cx.add_window_view(|window, cx| {
4946            let workspace = cx.new(|cx| {
4947                Workspace::new(
4948                    Default::default(),
4949                    project1.clone(),
4950                    app_state.clone(),
4951                    window,
4952                    cx,
4953                )
4954            });
4955            MultiWorkspace::new(workspace, window, cx)
4956        });
4957
4958        let workspace1_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
4959
4960        cx.run_until_parked();
4961
4962        let (settings_window, cx) = cx
4963            .add_window_view(|window, cx| SettingsWindow::new(Some(workspace1_handle), window, cx));
4964
4965        cx.run_until_parked();
4966
4967        settings_window.read_with(cx, |settings_window, _| {
4968            assert_eq!(
4969                settings_window.worktree_root_dirs.len(),
4970                1,
4971                "Should have 1 worktree initially"
4972            );
4973        });
4974
4975        let project2 = cx.update(|_, cx| {
4976            Project::local(
4977                app_state.client.clone(),
4978                app_state.node_runtime.clone(),
4979                app_state.user_store.clone(),
4980                app_state.languages.clone(),
4981                app_state.fs.clone(),
4982                None,
4983                project::LocalProjectFlags::default(),
4984                cx,
4985            )
4986        });
4987
4988        project2
4989            .update(&mut cx.cx, |project, cx| {
4990                project.find_or_create_worktree("/workspace2/worktree_b", true, cx)
4991            })
4992            .await
4993            .expect("Failed to create worktree_b");
4994
4995        let (_multi_workspace2, cx) = cx.add_window_view(|window, cx| {
4996            let workspace = cx.new(|cx| {
4997                Workspace::new(
4998                    Default::default(),
4999                    project2.clone(),
5000                    app_state.clone(),
5001                    window,
5002                    cx,
5003                )
5004            });
5005            MultiWorkspace::new(workspace, window, cx)
5006        });
5007
5008        cx.run_until_parked();
5009
5010        settings_window.read_with(cx, |settings_window, _| {
5011            let worktree_names: Vec<_> = settings_window
5012                .worktree_root_dirs
5013                .values()
5014                .cloned()
5015                .collect();
5016
5017            assert!(
5018                worktree_names.iter().any(|name| name == "worktree_a"),
5019                "Should contain worktree_a, but found: {:?}",
5020                worktree_names
5021            );
5022            assert!(
5023                worktree_names.iter().any(|name| name == "worktree_b"),
5024                "Should contain worktree_b from newly created workspace, but found: {:?}",
5025                worktree_names
5026            );
5027
5028            assert_eq!(
5029                worktree_names.len(),
5030                2,
5031                "Should have 2 worktrees after new workspace created, but found: {:?}",
5032                worktree_names
5033            );
5034
5035            let project_files: Vec<_> = settings_window
5036                .files
5037                .iter()
5038                .filter_map(|(f, _)| match f {
5039                    SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
5040                    _ => None,
5041                })
5042                .collect();
5043
5044            let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
5045            assert_eq!(
5046                project_files.len(),
5047                unique_project_files.len(),
5048                "Should have no duplicate project files, but found duplicates. All files: {:?}",
5049                project_files
5050            );
5051        });
5052    }
5053}
5054
5055#[cfg(test)]
5056mod project_settings_update_tests {
5057    use super::*;
5058    use fs::{FakeFs, Fs as _};
5059    use gpui::TestAppContext;
5060    use project::Project;
5061    use serde_json::json;
5062    use std::sync::atomic::{AtomicUsize, Ordering};
5063
5064    struct TestSetup {
5065        fs: Arc<FakeFs>,
5066        project: Entity<Project>,
5067        worktree_id: WorktreeId,
5068        worktree: WeakEntity<Worktree>,
5069        rel_path: Arc<RelPath>,
5070        project_path: ProjectPath,
5071    }
5072
5073    async fn init_test(cx: &mut TestAppContext, initial_settings: Option<&str>) -> TestSetup {
5074        cx.update(|cx| {
5075            let store = settings::SettingsStore::test(cx);
5076            cx.set_global(store);
5077            theme::init(theme::LoadThemes::JustBase, cx);
5078            editor::init(cx);
5079            menu::init();
5080            let queue = ProjectSettingsUpdateQueue::new(cx);
5081            cx.set_global(queue);
5082        });
5083
5084        let fs = FakeFs::new(cx.executor());
5085        let tree = if let Some(settings_content) = initial_settings {
5086            json!({
5087                ".zed": {
5088                    "settings.json": settings_content
5089                },
5090                "src": { "main.rs": "" }
5091            })
5092        } else {
5093            json!({ "src": { "main.rs": "" } })
5094        };
5095        fs.insert_tree("/project", tree).await;
5096
5097        let project = Project::test(fs.clone(), ["/project".as_ref()], cx).await;
5098
5099        let (worktree_id, worktree) = project.read_with(cx, |project, cx| {
5100            let worktree = project.worktrees(cx).next().unwrap();
5101            (worktree.read(cx).id(), worktree.downgrade())
5102        });
5103
5104        let rel_path: Arc<RelPath> = RelPath::unix(".zed/settings.json")
5105            .expect("valid path")
5106            .into_arc();
5107        let project_path = ProjectPath {
5108            worktree_id,
5109            path: rel_path.clone(),
5110        };
5111
5112        TestSetup {
5113            fs,
5114            project,
5115            worktree_id,
5116            worktree,
5117            rel_path,
5118            project_path,
5119        }
5120    }
5121
5122    #[gpui::test]
5123    async fn test_creates_settings_file_if_missing(cx: &mut TestAppContext) {
5124        let setup = init_test(cx, None).await;
5125
5126        let entry = ProjectSettingsUpdateEntry {
5127            worktree_id: setup.worktree_id,
5128            rel_path: setup.rel_path.clone(),
5129            settings_window: WeakEntity::new_invalid(),
5130            project: setup.project.downgrade(),
5131            worktree: setup.worktree,
5132            update: Box::new(|content, _cx| {
5133                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5134            }),
5135        };
5136
5137        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5138        cx.executor().run_until_parked();
5139
5140        let buffer_store = setup
5141            .project
5142            .read_with(cx, |project, _| project.buffer_store().clone());
5143        let buffer = buffer_store
5144            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5145            .await
5146            .expect("buffer should exist");
5147
5148        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5149        assert!(
5150            text.contains("\"tab_size\": 4"),
5151            "Expected tab_size setting in: {}",
5152            text
5153        );
5154    }
5155
5156    #[gpui::test]
5157    async fn test_updates_existing_settings_file(cx: &mut TestAppContext) {
5158        let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5159
5160        let entry = ProjectSettingsUpdateEntry {
5161            worktree_id: setup.worktree_id,
5162            rel_path: setup.rel_path.clone(),
5163            settings_window: WeakEntity::new_invalid(),
5164            project: setup.project.downgrade(),
5165            worktree: setup.worktree,
5166            update: Box::new(|content, _cx| {
5167                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(8).unwrap());
5168            }),
5169        };
5170
5171        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5172        cx.executor().run_until_parked();
5173
5174        let buffer_store = setup
5175            .project
5176            .read_with(cx, |project, _| project.buffer_store().clone());
5177        let buffer = buffer_store
5178            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5179            .await
5180            .expect("buffer should exist");
5181
5182        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5183        assert!(
5184            text.contains("\"tab_size\": 8"),
5185            "Expected updated tab_size in: {}",
5186            text
5187        );
5188    }
5189
5190    #[gpui::test]
5191    async fn test_updates_are_serialized(cx: &mut TestAppContext) {
5192        let setup = init_test(cx, Some("{}")).await;
5193
5194        let update_order = Arc::new(std::sync::Mutex::new(Vec::new()));
5195
5196        for i in 1..=3 {
5197            let update_order = update_order.clone();
5198            let entry = ProjectSettingsUpdateEntry {
5199                worktree_id: setup.worktree_id,
5200                rel_path: setup.rel_path.clone(),
5201                settings_window: WeakEntity::new_invalid(),
5202                project: setup.project.downgrade(),
5203                worktree: setup.worktree.clone(),
5204                update: Box::new(move |content, _cx| {
5205                    update_order.lock().unwrap().push(i);
5206                    content.project.all_languages.defaults.tab_size =
5207                        Some(NonZeroU32::new(i).unwrap());
5208                }),
5209            };
5210            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5211        }
5212
5213        cx.executor().run_until_parked();
5214
5215        let order = update_order.lock().unwrap().clone();
5216        assert_eq!(order, vec![1, 2, 3], "Updates should be processed in order");
5217
5218        let buffer_store = setup
5219            .project
5220            .read_with(cx, |project, _| project.buffer_store().clone());
5221        let buffer = buffer_store
5222            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5223            .await
5224            .expect("buffer should exist");
5225
5226        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5227        assert!(
5228            text.contains("\"tab_size\": 3"),
5229            "Final tab_size should be 3: {}",
5230            text
5231        );
5232    }
5233
5234    #[gpui::test]
5235    async fn test_queue_continues_after_failure(cx: &mut TestAppContext) {
5236        let setup = init_test(cx, Some("{}")).await;
5237
5238        let successful_updates = Arc::new(AtomicUsize::new(0));
5239
5240        {
5241            let successful_updates = successful_updates.clone();
5242            let entry = ProjectSettingsUpdateEntry {
5243                worktree_id: setup.worktree_id,
5244                rel_path: setup.rel_path.clone(),
5245                settings_window: WeakEntity::new_invalid(),
5246                project: setup.project.downgrade(),
5247                worktree: setup.worktree.clone(),
5248                update: Box::new(move |content, _cx| {
5249                    successful_updates.fetch_add(1, Ordering::SeqCst);
5250                    content.project.all_languages.defaults.tab_size =
5251                        Some(NonZeroU32::new(2).unwrap());
5252                }),
5253            };
5254            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5255        }
5256
5257        {
5258            let entry = ProjectSettingsUpdateEntry {
5259                worktree_id: setup.worktree_id,
5260                rel_path: setup.rel_path.clone(),
5261                settings_window: WeakEntity::new_invalid(),
5262                project: WeakEntity::new_invalid(),
5263                worktree: setup.worktree.clone(),
5264                update: Box::new(|content, _cx| {
5265                    content.project.all_languages.defaults.tab_size =
5266                        Some(NonZeroU32::new(99).unwrap());
5267                }),
5268            };
5269            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5270        }
5271
5272        {
5273            let successful_updates = successful_updates.clone();
5274            let entry = ProjectSettingsUpdateEntry {
5275                worktree_id: setup.worktree_id,
5276                rel_path: setup.rel_path.clone(),
5277                settings_window: WeakEntity::new_invalid(),
5278                project: setup.project.downgrade(),
5279                worktree: setup.worktree.clone(),
5280                update: Box::new(move |content, _cx| {
5281                    successful_updates.fetch_add(1, Ordering::SeqCst);
5282                    content.project.all_languages.defaults.tab_size =
5283                        Some(NonZeroU32::new(4).unwrap());
5284                }),
5285            };
5286            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5287        }
5288
5289        cx.executor().run_until_parked();
5290
5291        assert_eq!(
5292            successful_updates.load(Ordering::SeqCst),
5293            2,
5294            "Two updates should have succeeded despite middle failure"
5295        );
5296
5297        let buffer_store = setup
5298            .project
5299            .read_with(cx, |project, _| project.buffer_store().clone());
5300        let buffer = buffer_store
5301            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5302            .await
5303            .expect("buffer should exist");
5304
5305        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5306        assert!(
5307            text.contains("\"tab_size\": 4"),
5308            "Final tab_size should be 4 (third update): {}",
5309            text
5310        );
5311    }
5312
5313    #[gpui::test]
5314    async fn test_handles_dropped_worktree(cx: &mut TestAppContext) {
5315        let setup = init_test(cx, Some("{}")).await;
5316
5317        let entry = ProjectSettingsUpdateEntry {
5318            worktree_id: setup.worktree_id,
5319            rel_path: setup.rel_path.clone(),
5320            settings_window: WeakEntity::new_invalid(),
5321            project: setup.project.downgrade(),
5322            worktree: WeakEntity::new_invalid(),
5323            update: Box::new(|content, _cx| {
5324                content.project.all_languages.defaults.tab_size =
5325                    Some(NonZeroU32::new(99).unwrap());
5326            }),
5327        };
5328
5329        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5330        cx.executor().run_until_parked();
5331
5332        let file_content = setup
5333            .fs
5334            .load("/project/.zed/settings.json".as_ref())
5335            .await
5336            .unwrap();
5337        assert_eq!(
5338            file_content, "{}",
5339            "File should be unchanged when worktree is dropped"
5340        );
5341    }
5342
5343    #[gpui::test]
5344    async fn test_reloads_conflicted_buffer(cx: &mut TestAppContext) {
5345        let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5346
5347        let buffer_store = setup
5348            .project
5349            .read_with(cx, |project, _| project.buffer_store().clone());
5350        let buffer = buffer_store
5351            .update(cx, |store, cx| {
5352                store.open_buffer(setup.project_path.clone(), cx)
5353            })
5354            .await
5355            .expect("buffer should exist");
5356
5357        buffer.update(cx, |buffer, cx| {
5358            buffer.edit([(0..0, "// comment\n")], None, cx);
5359        });
5360
5361        let has_unsaved_edits = buffer.read_with(cx, |buffer, _| buffer.has_unsaved_edits());
5362        assert!(has_unsaved_edits, "Buffer should have unsaved edits");
5363
5364        setup
5365            .fs
5366            .save(
5367                "/project/.zed/settings.json".as_ref(),
5368                &r#"{ "tab_size": 99 }"#.into(),
5369                Default::default(),
5370            )
5371            .await
5372            .expect("save should succeed");
5373
5374        cx.executor().run_until_parked();
5375
5376        let has_conflict = buffer.read_with(cx, |buffer, _| buffer.has_conflict());
5377        assert!(
5378            has_conflict,
5379            "Buffer should have conflict after external modification"
5380        );
5381
5382        let (settings_window, _) = cx.add_window_view(|window, cx| {
5383            let mut sw = SettingsWindow::test(window, cx);
5384            sw.project_setting_file_buffers
5385                .insert(setup.project_path.clone(), buffer.clone());
5386            sw
5387        });
5388
5389        let entry = ProjectSettingsUpdateEntry {
5390            worktree_id: setup.worktree_id,
5391            rel_path: setup.rel_path.clone(),
5392            settings_window: settings_window.downgrade(),
5393            project: setup.project.downgrade(),
5394            worktree: setup.worktree.clone(),
5395            update: Box::new(|content, _cx| {
5396                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5397            }),
5398        };
5399
5400        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5401        cx.executor().run_until_parked();
5402
5403        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5404        assert!(
5405            text.contains("\"tab_size\": 4"),
5406            "Buffer should have the new tab_size after reload and update: {}",
5407            text
5408        );
5409        assert!(
5410            !text.contains("// comment"),
5411            "Buffer should not contain the unsaved edit after reload: {}",
5412            text
5413        );
5414        assert!(
5415            !text.contains("99"),
5416            "Buffer should not contain the external modification value: {}",
5417            text
5418        );
5419    }
5420}