settings_ui.rs

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