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_settings::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.on_action(|_: &OpenSettings, cx| {
 396        open_settings_editor(None, None, None, cx);
 397    });
 398
 399    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 400        workspace
 401            .register_action(|_, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
 402                let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 403                open_settings_editor(Some(&path), None, window_handle, cx);
 404            })
 405            .register_action(|_, _: &OpenSettings, window, cx| {
 406                let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 407                open_settings_editor(None, None, window_handle, cx);
 408            })
 409            .register_action(|workspace, _: &OpenProjectSettings, window, cx| {
 410                let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 411                let target_worktree_id = workspace
 412                    .project()
 413                    .read(cx)
 414                    .visible_worktrees(cx)
 415                    .find_map(|tree| {
 416                        tree.read(cx)
 417                            .root_entry()?
 418                            .is_dir()
 419                            .then_some(tree.read(cx).id())
 420                    });
 421                open_settings_editor(None, target_worktree_id, window_handle, cx);
 422            });
 423    })
 424    .detach();
 425}
 426
 427fn init_renderers(cx: &mut App) {
 428    cx.default_global::<SettingFieldRenderer>()
 429        .add_renderer::<UnimplementedSettingField>(
 430            |settings_window, item, _, settings_file, _, sub_field, _, cx| {
 431                render_settings_item(
 432                    settings_window,
 433                    item,
 434                    settings_file,
 435                    Button::new("open-in-settings-file", "Edit in settings.json")
 436                        .style(ButtonStyle::Outlined)
 437                        .size(ButtonSize::Medium)
 438                        .tab_index(0_isize)
 439                        .tooltip(Tooltip::for_action_title_in(
 440                            "Edit in settings.json",
 441                            &OpenCurrentFile,
 442                            &settings_window.focus_handle,
 443                        ))
 444                        .on_click(cx.listener(|this, _, window, cx| {
 445                            this.open_current_settings_file(window, cx);
 446                        }))
 447                        .into_any_element(),
 448                    sub_field,
 449                    cx,
 450                )
 451            },
 452        )
 453        .add_basic_renderer::<bool>(render_toggle_button)
 454        .add_basic_renderer::<String>(render_text_field)
 455        .add_basic_renderer::<SharedString>(render_text_field)
 456        .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
 457        .add_basic_renderer::<settings::CursorShape>(render_dropdown)
 458        .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
 459        .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
 460        .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
 461        .add_basic_renderer::<settings::CliDefaultOpenBehavior>(render_dropdown)
 462        .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
 463        .add_basic_renderer::<settings::TextRenderingMode>(render_dropdown)
 464        .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
 465        .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
 466        .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
 467        .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
 468        .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
 469        .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
 470        .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
 471        .add_basic_renderer::<settings::AutoIndentMode>(render_dropdown)
 472        .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
 473        .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
 474        .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
 475        .add_basic_renderer::<settings::DockSide>(render_dropdown)
 476        .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
 477        .add_basic_renderer::<settings::DockPosition>(render_dropdown)
 478        .add_basic_renderer::<settings::SidebarDockPosition>(render_dropdown)
 479        .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
 480        .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
 481        .add_basic_renderer::<settings::GitPathStyle>(render_dropdown)
 482        .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
 483        .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
 484        .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
 485        .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
 486        .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
 487        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 488        .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
 489        .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
 490        .add_basic_renderer::<settings::ProjectPanelSortMode>(render_dropdown)
 491        .add_basic_renderer::<settings::ProjectPanelSortOrder>(render_dropdown)
 492        .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
 493        .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
 494        .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
 495        .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
 496        .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
 497        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 498        .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
 499        .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
 500        .add_basic_renderer::<settings::CompletionDetailAlignment>(render_dropdown)
 501        .add_basic_renderer::<settings::DiffViewStyle>(render_dropdown)
 502        .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
 503        .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
 504        .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
 505        .add_basic_renderer::<settings::EditPredictionPromptFormat>(render_dropdown)
 506        .add_basic_renderer::<f32>(render_editable_number_field)
 507        .add_basic_renderer::<u32>(render_editable_number_field)
 508        .add_basic_renderer::<u64>(render_editable_number_field)
 509        .add_basic_renderer::<usize>(render_editable_number_field)
 510        .add_basic_renderer::<NonZero<usize>>(render_editable_number_field)
 511        .add_basic_renderer::<NonZeroU32>(render_editable_number_field)
 512        .add_basic_renderer::<settings::CodeFade>(render_editable_number_field)
 513        .add_basic_renderer::<settings::DelayMs>(render_editable_number_field)
 514        .add_basic_renderer::<settings::FontWeightContent>(render_editable_number_field)
 515        .add_basic_renderer::<settings::CenteredPaddingSettings>(render_editable_number_field)
 516        .add_basic_renderer::<settings::InactiveOpacity>(render_editable_number_field)
 517        .add_basic_renderer::<settings::MinimumContrast>(render_editable_number_field)
 518        .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
 519        .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
 520        .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
 521        .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
 522        .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
 523        .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
 524        .add_basic_renderer::<settings::ModeContent>(render_dropdown)
 525        .add_basic_renderer::<settings::UseSystemClipboard>(render_dropdown)
 526        .add_basic_renderer::<settings::VimInsertModeCursorShape>(render_dropdown)
 527        .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
 528        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 529        .add_basic_renderer::<settings::PlaySoundWhenAgentDone>(render_dropdown)
 530        .add_basic_renderer::<settings::NewThreadLocation>(render_dropdown)
 531        .add_basic_renderer::<settings::ThinkingBlockDisplay>(render_dropdown)
 532        .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
 533        .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
 534        .add_basic_renderer::<settings::EncodingDisplayOptions>(render_dropdown)
 535        .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
 536        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 537        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 538        .add_basic_renderer::<settings::CodeLens>(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::WindowButtonLayoutContentDiscriminants>(render_dropdown)
 555        .add_basic_renderer::<settings::FontSize>(render_editable_number_field)
 556        .add_basic_renderer::<settings::OllamaModelName>(render_ollama_model_picker)
 557        .add_basic_renderer::<settings::SemanticTokens>(render_dropdown)
 558        .add_basic_renderer::<settings::DocumentFoldingRanges>(render_dropdown)
 559        .add_basic_renderer::<settings::DocumentSymbols>(render_dropdown)
 560        .add_basic_renderer::<settings::AudioInputDeviceName>(render_input_audio_device_dropdown)
 561        .add_basic_renderer::<settings::AudioOutputDeviceName>(render_output_audio_device_dropdown)
 562        // please semicolon stay on next line
 563        ;
 564}
 565
 566pub fn open_settings_editor(
 567    path: Option<&str>,
 568    target_worktree_id: Option<WorktreeId>,
 569    workspace_handle: Option<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 = workspace_handle;
 627
 628                window.activate_window();
 629                if let Some(path) = path {
 630                    open_path(path, settings_window, window, cx);
 631                } else if let Some(target_id) = target_worktree_id
 632                    && let Some(file_index) = settings_window
 633                        .files
 634                        .iter()
 635                        .position(|(file, _)| file.worktree_id() == Some(target_id))
 636                {
 637                    settings_window.change_file(file_index, window, cx);
 638                    cx.notify();
 639                }
 640            })
 641            .ok();
 642        return;
 643    }
 644
 645    // We have to defer this to get the workspace off the stack.
 646    let path = path.map(ToOwned::to_owned);
 647    cx.defer(move |cx| {
 648        let current_rem_size: f32 = theme_settings::ThemeSettings::get_global(cx)
 649            .ui_font_size(cx)
 650            .into();
 651
 652        let default_bounds = DEFAULT_ADDITIONAL_WINDOW_SIZE;
 653        let default_rem_size = 16.0;
 654        let scale_factor = current_rem_size / default_rem_size;
 655        let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
 656
 657        let app_id = ReleaseChannel::global(cx).app_id();
 658        let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
 659            Ok(val) if val == "server" => gpui::WindowDecorations::Server,
 660            Ok(val) if val == "client" => gpui::WindowDecorations::Client,
 661            _ => gpui::WindowDecorations::Client,
 662        };
 663
 664        cx.open_window(
 665            WindowOptions {
 666                titlebar: Some(TitlebarOptions {
 667                    title: Some("Zed — Settings".into()),
 668                    appears_transparent: true,
 669                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 670                }),
 671                focus: true,
 672                show: true,
 673                is_movable: true,
 674                kind: gpui::WindowKind::Normal,
 675                window_background: cx.theme().window_background_appearance(),
 676                app_id: Some(app_id.to_owned()),
 677                window_decorations: Some(window_decorations),
 678                window_min_size: Some(gpui::Size {
 679                    // Don't make the settings window thinner than this,
 680                    // otherwise, it gets unusable. Users with smaller res monitors
 681                    // can customize the height, but not the width.
 682                    width: px(900.0),
 683                    height: px(240.0),
 684                }),
 685                window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
 686                ..Default::default()
 687            },
 688            |window, cx| {
 689                let settings_window =
 690                    cx.new(|cx| SettingsWindow::new(workspace_handle, window, cx));
 691                settings_window.update(cx, |settings_window, cx| {
 692                    if let Some(path) = path {
 693                        open_path(&path, settings_window, window, cx);
 694                    } else if let Some(target_id) = target_worktree_id
 695                        && let Some(file_index) = settings_window
 696                            .files
 697                            .iter()
 698                            .position(|(file, _)| file.worktree_id() == Some(target_id))
 699                    {
 700                        settings_window.change_file(file_index, window, cx);
 701                    }
 702                });
 703
 704                settings_window
 705            },
 706        )
 707        .log_err();
 708    });
 709}
 710
 711/// The current sub page path that is selected.
 712/// If this is empty the selected page is rendered,
 713/// otherwise the last sub page gets rendered.
 714///
 715/// Global so that `pick` and `write` callbacks can access it
 716/// and use it to dynamically render sub pages (e.g. for language settings)
 717static ACTIVE_LANGUAGE: LazyLock<RwLock<Option<SharedString>>> =
 718    LazyLock::new(|| RwLock::new(Option::None));
 719
 720fn active_language() -> Option<SharedString> {
 721    ACTIVE_LANGUAGE
 722        .read()
 723        .ok()
 724        .and_then(|language| language.clone())
 725}
 726
 727fn active_language_mut() -> Option<std::sync::RwLockWriteGuard<'static, Option<SharedString>>> {
 728    ACTIVE_LANGUAGE.write().ok()
 729}
 730
 731pub struct SettingsWindow {
 732    title_bar: Option<Entity<PlatformTitleBar>>,
 733    original_window: Option<WindowHandle<MultiWorkspace>>,
 734    files: Vec<(SettingsUiFile, FocusHandle)>,
 735    worktree_root_dirs: HashMap<WorktreeId, String>,
 736    current_file: SettingsUiFile,
 737    pages: Vec<SettingsPage>,
 738    sub_page_stack: Vec<SubPage>,
 739    opening_link: bool,
 740    search_bar: Entity<Editor>,
 741    search_task: Option<Task<()>>,
 742    /// Cached settings file buffers to avoid repeated disk I/O on each settings change
 743    project_setting_file_buffers: HashMap<ProjectPath, Entity<Buffer>>,
 744    /// Index into navbar_entries
 745    navbar_entry: usize,
 746    navbar_entries: Vec<NavBarEntry>,
 747    navbar_scroll_handle: UniformListScrollHandle,
 748    /// [page_index][page_item_index] will be false
 749    /// when the item is filtered out either by searches
 750    /// or by the current file
 751    navbar_focus_subscriptions: Vec<gpui::Subscription>,
 752    filter_table: Vec<Vec<bool>>,
 753    has_query: bool,
 754    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 755    focus_handle: FocusHandle,
 756    navbar_focus_handle: Entity<NonFocusableHandle>,
 757    content_focus_handle: Entity<NonFocusableHandle>,
 758    files_focus_handle: FocusHandle,
 759    search_index: Option<Arc<SearchIndex>>,
 760    list_state: ListState,
 761    shown_errors: HashSet<String>,
 762    pub(crate) regex_validation_error: Option<String>,
 763}
 764
 765struct SearchDocument {
 766    id: usize,
 767    words: Vec<String>,
 768}
 769
 770struct SearchIndex {
 771    documents: Vec<SearchDocument>,
 772    fuzzy_match_candidates: Vec<StringMatchCandidate>,
 773    key_lut: Vec<SearchKeyLUTEntry>,
 774}
 775
 776struct SearchKeyLUTEntry {
 777    page_index: usize,
 778    header_index: usize,
 779    item_index: usize,
 780    json_path: Option<&'static str>,
 781}
 782
 783struct SubPage {
 784    link: SubPageLink,
 785    section_header: SharedString,
 786    scroll_handle: ScrollHandle,
 787}
 788
 789impl SubPage {
 790    fn new(link: SubPageLink, section_header: SharedString) -> Self {
 791        if link.r#type == SubPageType::Language
 792            && let Some(mut active_language_global) = active_language_mut()
 793        {
 794            active_language_global.replace(link.title.clone());
 795        }
 796
 797        SubPage {
 798            link,
 799            section_header,
 800            scroll_handle: ScrollHandle::new(),
 801        }
 802    }
 803}
 804
 805impl Drop for SubPage {
 806    fn drop(&mut self) {
 807        if self.link.r#type == SubPageType::Language
 808            && let Some(mut active_language_global) = active_language_mut()
 809            && active_language_global
 810                .as_ref()
 811                .is_some_and(|language_name| language_name == &self.link.title)
 812        {
 813            active_language_global.take();
 814        }
 815    }
 816}
 817
 818#[derive(Debug)]
 819struct NavBarEntry {
 820    title: &'static str,
 821    is_root: bool,
 822    expanded: bool,
 823    page_index: usize,
 824    item_index: Option<usize>,
 825    focus_handle: FocusHandle,
 826}
 827
 828struct SettingsPage {
 829    title: &'static str,
 830    items: Box<[SettingsPageItem]>,
 831}
 832
 833#[derive(PartialEq)]
 834enum SettingsPageItem {
 835    SectionHeader(&'static str),
 836    SettingItem(SettingItem),
 837    SubPageLink(SubPageLink),
 838    DynamicItem(DynamicItem),
 839    ActionLink(ActionLink),
 840}
 841
 842impl std::fmt::Debug for SettingsPageItem {
 843    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 844        match self {
 845            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 846            SettingsPageItem::SettingItem(setting_item) => {
 847                write!(f, "SettingItem({})", setting_item.title)
 848            }
 849            SettingsPageItem::SubPageLink(sub_page_link) => {
 850                write!(f, "SubPageLink({})", sub_page_link.title)
 851            }
 852            SettingsPageItem::DynamicItem(dynamic_item) => {
 853                write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
 854            }
 855            SettingsPageItem::ActionLink(action_link) => {
 856                write!(f, "ActionLink({})", action_link.title)
 857            }
 858        }
 859    }
 860}
 861
 862impl SettingsPageItem {
 863    fn header_text(&self) -> Option<&'static str> {
 864        match self {
 865            SettingsPageItem::SectionHeader(header) => Some(header),
 866            _ => None,
 867        }
 868    }
 869
 870    fn render(
 871        &self,
 872        settings_window: &SettingsWindow,
 873        item_index: usize,
 874        bottom_border: bool,
 875        extra_bottom_padding: bool,
 876        window: &mut Window,
 877        cx: &mut Context<SettingsWindow>,
 878    ) -> AnyElement {
 879        let file = settings_window.current_file.clone();
 880
 881        let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
 882            let element = element.pt_4();
 883            if extra_bottom_padding {
 884                element.pb_10()
 885            } else {
 886                element.pb_4()
 887            }
 888        };
 889
 890        let mut render_setting_item_inner =
 891            |setting_item: &SettingItem,
 892             padding: bool,
 893             sub_field: bool,
 894             cx: &mut Context<SettingsWindow>| {
 895                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 896                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 897
 898                let renderers = renderer.renderers.borrow();
 899
 900                let field_renderer =
 901                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 902                let field_renderer_or_warning =
 903                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 904                        if cfg!(debug_assertions) && !found {
 905                            Err("NO DEFAULT")
 906                        } else {
 907                            Ok(renderer)
 908                        }
 909                    });
 910
 911                let field = match field_renderer_or_warning {
 912                    Ok(field_renderer) => window.with_id(item_index, |window| {
 913                        field_renderer(
 914                            settings_window,
 915                            setting_item,
 916                            file.clone(),
 917                            setting_item.metadata.as_deref(),
 918                            sub_field,
 919                            window,
 920                            cx,
 921                        )
 922                    }),
 923                    Err(warning) => render_settings_item(
 924                        settings_window,
 925                        setting_item,
 926                        file.clone(),
 927                        Button::new("error-warning", warning)
 928                            .style(ButtonStyle::Outlined)
 929                            .size(ButtonSize::Medium)
 930                            .start_icon(Icon::new(IconName::Debug).color(Color::Error))
 931                            .tab_index(0_isize)
 932                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 933                            .into_any_element(),
 934                        sub_field,
 935                        cx,
 936                    ),
 937                };
 938
 939                let field = if padding {
 940                    field.map(apply_padding)
 941                } else {
 942                    field
 943                };
 944
 945                (field, field_renderer_or_warning.is_ok())
 946            };
 947
 948        match self {
 949            SettingsPageItem::SectionHeader(header) => {
 950                SettingsSectionHeader::new(SharedString::new_static(header)).into_any_element()
 951            }
 952            SettingsPageItem::SettingItem(setting_item) => {
 953                let (field_with_padding, _) =
 954                    render_setting_item_inner(setting_item, true, false, cx);
 955
 956                v_flex()
 957                    .group("setting-item")
 958                    .px_8()
 959                    .child(field_with_padding)
 960                    .when(bottom_border, |this| this.child(Divider::horizontal()))
 961                    .into_any_element()
 962            }
 963            SettingsPageItem::SubPageLink(sub_page_link) => v_flex()
 964                .group("setting-item")
 965                .px_8()
 966                .child(
 967                    h_flex()
 968                        .id(sub_page_link.title.clone())
 969                        .w_full()
 970                        .min_w_0()
 971                        .justify_between()
 972                        .map(apply_padding)
 973                        .child(
 974                            v_flex()
 975                                .relative()
 976                                .w_full()
 977                                .max_w_1_2()
 978                                .child(Label::new(sub_page_link.title.clone()))
 979                                .when_some(
 980                                    sub_page_link.description.as_ref(),
 981                                    |this, description| {
 982                                        this.child(
 983                                            Label::new(description.clone())
 984                                                .size(LabelSize::Small)
 985                                                .color(Color::Muted),
 986                                        )
 987                                    },
 988                                ),
 989                        )
 990                        .child(
 991                            Button::new(
 992                                ("sub-page".into(), sub_page_link.title.clone()),
 993                                "Configure",
 994                            )
 995                            .tab_index(0_isize)
 996                            .end_icon(
 997                                Icon::new(IconName::ChevronRight)
 998                                    .size(IconSize::Small)
 999                                    .color(Color::Muted),
1000                            )
1001                            .style(ButtonStyle::OutlinedGhost)
1002                            .size(ButtonSize::Medium)
1003                            .on_click({
1004                                let sub_page_link = sub_page_link.clone();
1005                                cx.listener(move |this, _, window, cx| {
1006                                    let header_text = this
1007                                        .sub_page_stack
1008                                        .last()
1009                                        .map(|sub_page| sub_page.link.title.clone())
1010                                        .or_else(|| {
1011                                            this.current_page()
1012                                                .items
1013                                                .iter()
1014                                                .take(item_index)
1015                                                .rev()
1016                                                .find_map(|item| {
1017                                                    item.header_text().map(SharedString::new_static)
1018                                                })
1019                                        });
1020
1021                                    let Some(header) = header_text else {
1022                                        unreachable!(
1023                                            "All items always have a section header above them"
1024                                        )
1025                                    };
1026
1027                                    this.push_sub_page(sub_page_link.clone(), header, window, cx)
1028                                })
1029                            }),
1030                        )
1031                        .child(render_settings_item_link(
1032                            sub_page_link.title.clone(),
1033                            sub_page_link.json_path,
1034                            false,
1035                            cx,
1036                        )),
1037                )
1038                .when(bottom_border, |this| this.child(Divider::horizontal()))
1039                .into_any_element(),
1040            SettingsPageItem::DynamicItem(DynamicItem {
1041                discriminant: discriminant_setting_item,
1042                pick_discriminant,
1043                fields,
1044            }) => {
1045                let file = file.to_settings();
1046                let discriminant = SettingsStore::global(cx)
1047                    .get_value_from_file(file, *pick_discriminant)
1048                    .1;
1049
1050                let (discriminant_element, rendered_ok) =
1051                    render_setting_item_inner(discriminant_setting_item, true, false, cx);
1052
1053                let has_sub_fields =
1054                    rendered_ok && discriminant.is_some_and(|d| !fields[d].is_empty());
1055
1056                let mut content = v_flex()
1057                    .id("dynamic-item")
1058                    .child(
1059                        div()
1060                            .group("setting-item")
1061                            .px_8()
1062                            .child(discriminant_element.when(has_sub_fields, |this| this.pb_4())),
1063                    )
1064                    .when(!has_sub_fields && bottom_border, |this| {
1065                        this.child(h_flex().px_8().child(Divider::horizontal()))
1066                    });
1067
1068                if rendered_ok {
1069                    let discriminant =
1070                        discriminant.expect("This should be Some if rendered_ok is true");
1071                    let sub_fields = &fields[discriminant];
1072                    let sub_field_count = sub_fields.len();
1073
1074                    for (index, field) in sub_fields.iter().enumerate() {
1075                        let is_last_sub_field = index == sub_field_count - 1;
1076                        let (raw_field, _) = render_setting_item_inner(field, false, true, cx);
1077
1078                        content = content.child(
1079                            raw_field
1080                                .group("setting-sub-item")
1081                                .mx_8()
1082                                .p_4()
1083                                .border_t_1()
1084                                .when(is_last_sub_field, |this| this.border_b_1())
1085                                .when(is_last_sub_field && extra_bottom_padding, |this| {
1086                                    this.mb_8()
1087                                })
1088                                .border_dashed()
1089                                .border_color(cx.theme().colors().border_variant)
1090                                .bg(cx.theme().colors().element_background.opacity(0.2)),
1091                        );
1092                    }
1093                }
1094
1095                return content.into_any_element();
1096            }
1097            SettingsPageItem::ActionLink(action_link) => v_flex()
1098                .group("setting-item")
1099                .px_8()
1100                .child(
1101                    h_flex()
1102                        .id(action_link.title.clone())
1103                        .w_full()
1104                        .min_w_0()
1105                        .justify_between()
1106                        .map(apply_padding)
1107                        .child(
1108                            v_flex()
1109                                .relative()
1110                                .w_full()
1111                                .max_w_1_2()
1112                                .child(Label::new(action_link.title.clone()))
1113                                .when_some(
1114                                    action_link.description.as_ref(),
1115                                    |this, description| {
1116                                        this.child(
1117                                            Label::new(description.clone())
1118                                                .size(LabelSize::Small)
1119                                                .color(Color::Muted),
1120                                        )
1121                                    },
1122                                ),
1123                        )
1124                        .child(
1125                            Button::new(
1126                                ("action-link".into(), action_link.title.clone()),
1127                                action_link.button_text.clone(),
1128                            )
1129                            .tab_index(0_isize)
1130                            .end_icon(
1131                                Icon::new(IconName::ArrowUpRight)
1132                                    .size(IconSize::Small)
1133                                    .color(Color::Muted),
1134                            )
1135                            .style(ButtonStyle::OutlinedGhost)
1136                            .size(ButtonSize::Medium)
1137                            .on_click({
1138                                let on_click = action_link.on_click.clone();
1139                                cx.listener(move |this, _, window, cx| {
1140                                    on_click(this, window, cx);
1141                                })
1142                            }),
1143                        ),
1144                )
1145                .when(bottom_border, |this| this.child(Divider::horizontal()))
1146                .into_any_element(),
1147        }
1148    }
1149}
1150
1151fn render_settings_item(
1152    settings_window: &SettingsWindow,
1153    setting_item: &SettingItem,
1154    file: SettingsUiFile,
1155    control: AnyElement,
1156    sub_field: bool,
1157    cx: &mut Context<'_, SettingsWindow>,
1158) -> Stateful<Div> {
1159    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
1160    let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
1161
1162    h_flex()
1163        .id(setting_item.title)
1164        .min_w_0()
1165        .justify_between()
1166        .child(
1167            v_flex()
1168                .relative()
1169                .w_full()
1170                .max_w_2_3()
1171                .min_w_0()
1172                .child(
1173                    h_flex()
1174                        .w_full()
1175                        .gap_1()
1176                        .child(Label::new(SharedString::new_static(setting_item.title)))
1177                        .when_some(
1178                            if sub_field {
1179                                None
1180                            } else {
1181                                setting_item
1182                                    .field
1183                                    .reset_to_default_fn(&file, &found_in_file, cx)
1184                            },
1185                            |this, reset_to_default| {
1186                                this.child(
1187                                    IconButton::new("reset-to-default-btn", IconName::Undo)
1188                                        .icon_color(Color::Muted)
1189                                        .icon_size(IconSize::Small)
1190                                        .tooltip(Tooltip::text("Reset to Default"))
1191                                        .on_click({
1192                                            move |_, window, cx| {
1193                                                reset_to_default(window, cx);
1194                                            }
1195                                        }),
1196                                )
1197                            },
1198                        )
1199                        .when_some(
1200                            file_set_in.filter(|file_set_in| file_set_in != &file),
1201                            |this, file_set_in| {
1202                                this.child(
1203                                    Label::new(format!(
1204                                        "—  Modified in {}",
1205                                        settings_window
1206                                            .display_name(&file_set_in)
1207                                            .expect("File name should exist")
1208                                    ))
1209                                    .color(Color::Muted)
1210                                    .size(LabelSize::Small),
1211                                )
1212                            },
1213                        ),
1214                )
1215                .child(
1216                    Label::new(SharedString::new_static(setting_item.description))
1217                        .size(LabelSize::Small)
1218                        .color(Color::Muted)
1219                        .render_code_spans(),
1220                ),
1221        )
1222        .child(control)
1223        .when(settings_window.sub_page_stack.is_empty(), |this| {
1224            this.child(render_settings_item_link(
1225                setting_item.description,
1226                setting_item.field.json_path(),
1227                sub_field,
1228                cx,
1229            ))
1230        })
1231}
1232
1233fn render_settings_item_link(
1234    id: impl Into<ElementId>,
1235    json_path: Option<&'static str>,
1236    sub_field: bool,
1237    cx: &mut Context<'_, SettingsWindow>,
1238) -> impl IntoElement {
1239    let clipboard_has_link = cx
1240        .read_from_clipboard()
1241        .and_then(|entry| entry.text())
1242        .map_or(false, |maybe_url| {
1243            json_path.is_some() && maybe_url.strip_prefix("zed://settings/") == json_path
1244        });
1245
1246    let (link_icon, link_icon_color) = if clipboard_has_link {
1247        (IconName::Check, Color::Success)
1248    } else {
1249        (IconName::Link, Color::Muted)
1250    };
1251
1252    div()
1253        .absolute()
1254        .top(rems_from_px(18.))
1255        .map(|this| {
1256            if sub_field {
1257                this.visible_on_hover("setting-sub-item")
1258                    .left(rems_from_px(-8.5))
1259            } else {
1260                this.visible_on_hover("setting-item")
1261                    .left(rems_from_px(-22.))
1262            }
1263        })
1264        .child(
1265            IconButton::new((id.into(), "copy-link-btn"), link_icon)
1266                .icon_color(link_icon_color)
1267                .icon_size(IconSize::Small)
1268                .shape(IconButtonShape::Square)
1269                .tooltip(Tooltip::text("Copy Link"))
1270                .when_some(json_path, |this, path| {
1271                    this.on_click(cx.listener(move |_, _, _, cx| {
1272                        let link = format!("zed://settings/{}", path);
1273                        cx.write_to_clipboard(ClipboardItem::new_string(link));
1274                        cx.notify();
1275                    }))
1276                }),
1277        )
1278}
1279
1280struct SettingItem {
1281    title: &'static str,
1282    description: &'static str,
1283    field: Box<dyn AnySettingField>,
1284    metadata: Option<Box<SettingsFieldMetadata>>,
1285    files: FileMask,
1286}
1287
1288struct DynamicItem {
1289    discriminant: SettingItem,
1290    pick_discriminant: fn(&SettingsContent) -> Option<usize>,
1291    fields: Vec<Vec<SettingItem>>,
1292}
1293
1294impl PartialEq for DynamicItem {
1295    fn eq(&self, other: &Self) -> bool {
1296        self.discriminant == other.discriminant && self.fields == other.fields
1297    }
1298}
1299
1300#[derive(PartialEq, Eq, Clone, Copy)]
1301struct FileMask(u8);
1302
1303impl std::fmt::Debug for FileMask {
1304    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1305        write!(f, "FileMask(")?;
1306        let mut items = vec![];
1307
1308        if self.contains(USER) {
1309            items.push("USER");
1310        }
1311        if self.contains(PROJECT) {
1312            items.push("LOCAL");
1313        }
1314        if self.contains(SERVER) {
1315            items.push("SERVER");
1316        }
1317
1318        write!(f, "{})", items.join(" | "))
1319    }
1320}
1321
1322const USER: FileMask = FileMask(1 << 0);
1323const PROJECT: FileMask = FileMask(1 << 2);
1324const SERVER: FileMask = FileMask(1 << 3);
1325
1326impl std::ops::BitAnd for FileMask {
1327    type Output = Self;
1328
1329    fn bitand(self, other: Self) -> Self {
1330        Self(self.0 & other.0)
1331    }
1332}
1333
1334impl std::ops::BitOr for FileMask {
1335    type Output = Self;
1336
1337    fn bitor(self, other: Self) -> Self {
1338        Self(self.0 | other.0)
1339    }
1340}
1341
1342impl FileMask {
1343    fn contains(&self, other: FileMask) -> bool {
1344        self.0 & other.0 != 0
1345    }
1346}
1347
1348impl PartialEq for SettingItem {
1349    fn eq(&self, other: &Self) -> bool {
1350        self.title == other.title
1351            && self.description == other.description
1352            && (match (&self.metadata, &other.metadata) {
1353                (None, None) => true,
1354                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1355                _ => false,
1356            })
1357    }
1358}
1359
1360#[derive(Clone, PartialEq, Default)]
1361enum SubPageType {
1362    Language,
1363    #[default]
1364    Other,
1365}
1366
1367#[derive(Clone)]
1368struct SubPageLink {
1369    title: SharedString,
1370    r#type: SubPageType,
1371    description: Option<SharedString>,
1372    /// See [`SettingField.json_path`]
1373    json_path: Option<&'static str>,
1374    /// Whether or not the settings in this sub page are configurable in settings.json
1375    /// Removes the "Edit in settings.json" button from the page.
1376    in_json: bool,
1377    files: FileMask,
1378    render:
1379        fn(&SettingsWindow, &ScrollHandle, &mut Window, &mut Context<SettingsWindow>) -> AnyElement,
1380}
1381
1382impl PartialEq for SubPageLink {
1383    fn eq(&self, other: &Self) -> bool {
1384        self.title == other.title
1385    }
1386}
1387
1388#[derive(Clone)]
1389struct ActionLink {
1390    title: SharedString,
1391    description: Option<SharedString>,
1392    button_text: SharedString,
1393    on_click: Arc<dyn Fn(&mut SettingsWindow, &mut Window, &mut App) + Send + Sync>,
1394    files: FileMask,
1395}
1396
1397impl PartialEq for ActionLink {
1398    fn eq(&self, other: &Self) -> bool {
1399        self.title == other.title
1400    }
1401}
1402
1403fn all_language_names(cx: &App) -> Vec<SharedString> {
1404    let state = workspace::AppState::global(cx);
1405    state
1406        .languages
1407        .language_names()
1408        .into_iter()
1409        .filter(|name| name.as_ref() != "Zed Keybind Context")
1410        .map(Into::into)
1411        .collect()
1412}
1413
1414#[allow(unused)]
1415#[derive(Clone, PartialEq, Debug)]
1416enum SettingsUiFile {
1417    User,                                // Uses all settings.
1418    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1419    Server(&'static str),                // Uses a special name, and the user settings
1420}
1421
1422impl SettingsUiFile {
1423    fn setting_type(&self) -> &'static str {
1424        match self {
1425            SettingsUiFile::User => "User",
1426            SettingsUiFile::Project(_) => "Project",
1427            SettingsUiFile::Server(_) => "Server",
1428        }
1429    }
1430
1431    fn is_server(&self) -> bool {
1432        matches!(self, SettingsUiFile::Server(_))
1433    }
1434
1435    fn worktree_id(&self) -> Option<WorktreeId> {
1436        match self {
1437            SettingsUiFile::User => None,
1438            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1439            SettingsUiFile::Server(_) => None,
1440        }
1441    }
1442
1443    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1444        Some(match file {
1445            settings::SettingsFile::User => SettingsUiFile::User,
1446            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1447            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1448            settings::SettingsFile::Default => return None,
1449            settings::SettingsFile::Global => return None,
1450        })
1451    }
1452
1453    fn to_settings(&self) -> settings::SettingsFile {
1454        match self {
1455            SettingsUiFile::User => settings::SettingsFile::User,
1456            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1457            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1458        }
1459    }
1460
1461    fn mask(&self) -> FileMask {
1462        match self {
1463            SettingsUiFile::User => USER,
1464            SettingsUiFile::Project(_) => PROJECT,
1465            SettingsUiFile::Server(_) => SERVER,
1466        }
1467    }
1468}
1469
1470impl SettingsWindow {
1471    fn new(
1472        original_window: Option<WindowHandle<MultiWorkspace>>,
1473        window: &mut Window,
1474        cx: &mut Context<Self>,
1475    ) -> Self {
1476        let font_family_cache = theme::FontFamilyCache::global(cx);
1477
1478        cx.spawn(async move |this, cx| {
1479            font_family_cache.prefetch(cx).await;
1480            this.update(cx, |_, cx| {
1481                cx.notify();
1482            })
1483        })
1484        .detach();
1485
1486        let current_file = SettingsUiFile::User;
1487        let search_bar = cx.new(|cx| {
1488            let mut editor = Editor::single_line(window, cx);
1489            editor.set_placeholder_text("Search settings…", window, cx);
1490            editor
1491        });
1492        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1493            let EditorEvent::Edited { transaction_id: _ } = event else {
1494                return;
1495            };
1496
1497            if this.opening_link {
1498                this.opening_link = false;
1499                return;
1500            }
1501            this.update_matches(cx);
1502        })
1503        .detach();
1504
1505        let mut ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1506        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1507            this.fetch_files(window, cx);
1508
1509            // Whenever settings are changed, it's possible that the changed
1510            // settings affects the rendering of the `SettingsWindow`, like is
1511            // the case with `ui_font_size`. When that happens, we need to
1512            // instruct the `ListState` to re-measure the list items, as the
1513            // list item heights may have changed depending on the new font
1514            // size.
1515            let new_ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1516            if new_ui_font_size != ui_font_size {
1517                this.list_state.remeasure();
1518                ui_font_size = new_ui_font_size;
1519            }
1520
1521            cx.notify();
1522        })
1523        .detach();
1524
1525        cx.on_window_closed(|cx, _window_id| {
1526            if let Some(existing_window) = cx
1527                .windows()
1528                .into_iter()
1529                .find_map(|window| window.downcast::<SettingsWindow>())
1530                && cx.windows().len() == 1
1531            {
1532                cx.update_window(*existing_window, |_, window, _| {
1533                    window.remove_window();
1534                })
1535                .ok();
1536
1537                telemetry::event!("Settings Closed")
1538            }
1539        })
1540        .detach();
1541
1542        let app_state = AppState::global(cx);
1543        let workspaces: Vec<Entity<Workspace>> = app_state
1544            .workspace_store
1545            .read(cx)
1546            .workspaces()
1547            .filter_map(|weak| weak.upgrade())
1548            .collect();
1549
1550        for workspace in workspaces {
1551            let project = workspace.read(cx).project().clone();
1552            cx.observe_release_in(&project, window, |this, _, window, cx| {
1553                this.fetch_files(window, cx)
1554            })
1555            .detach();
1556            cx.subscribe_in(&project, window, Self::handle_project_event)
1557                .detach();
1558            cx.observe_release_in(&workspace, window, |this, _, window, cx| {
1559                this.fetch_files(window, cx)
1560            })
1561            .detach();
1562        }
1563
1564        let this_weak = cx.weak_entity();
1565        cx.observe_new::<Project>({
1566            let this_weak = this_weak.clone();
1567
1568            move |_, window, cx| {
1569                let project = cx.entity();
1570                let Some(window) = window else {
1571                    return;
1572                };
1573
1574                this_weak
1575                    .update(cx, |_, cx| {
1576                        cx.defer_in(window, |settings_window, window, cx| {
1577                            settings_window.fetch_files(window, cx)
1578                        });
1579                        cx.observe_release_in(&project, window, |_, _, window, cx| {
1580                            cx.defer_in(window, |this, window, cx| this.fetch_files(window, cx));
1581                        })
1582                        .detach();
1583
1584                        cx.subscribe_in(&project, window, Self::handle_project_event)
1585                            .detach();
1586                    })
1587                    .ok();
1588            }
1589        })
1590        .detach();
1591
1592        let handle = window.window_handle();
1593        cx.observe_new::<Workspace>(move |workspace, _, cx| {
1594            let project = workspace.project().clone();
1595            let this_weak = this_weak.clone();
1596
1597            // We defer on the settings window (via `handle`) rather than using
1598            // the workspace's window from observe_new. When window.defer() runs
1599            // its callback, it calls handle.update() which temporarily removes
1600            // that window from cx.windows. If we deferred on the workspace's
1601            // window, then when fetch_files() tries to read ALL workspaces from
1602            // the store (including the newly created one), it would fail with
1603            // "window not found" because that workspace's window would be
1604            // temporarily removed from cx.windows for the duration of our callback.
1605            handle
1606                .update(cx, move |_, window, cx| {
1607                    window.defer(cx, move |window, cx| {
1608                        this_weak
1609                            .update(cx, |this, cx| {
1610                                this.fetch_files(window, cx);
1611                                cx.observe_release_in(&project, window, |this, _, window, cx| {
1612                                    this.fetch_files(window, cx)
1613                                })
1614                                .detach();
1615                            })
1616                            .ok();
1617                    });
1618                })
1619                .ok();
1620        })
1621        .detach();
1622
1623        let title_bar = if !cfg!(target_os = "macos") {
1624            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1625        } else {
1626            None
1627        };
1628
1629        let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1630        list_state.set_scroll_handler(|_, _, _| {});
1631
1632        let mut this = Self {
1633            title_bar,
1634            original_window,
1635
1636            worktree_root_dirs: HashMap::default(),
1637            files: vec![],
1638
1639            current_file: current_file,
1640            project_setting_file_buffers: HashMap::default(),
1641            pages: vec![],
1642            sub_page_stack: vec![],
1643            opening_link: false,
1644            navbar_entries: vec![],
1645            navbar_entry: 0,
1646            navbar_scroll_handle: UniformListScrollHandle::default(),
1647            search_bar,
1648            search_task: None,
1649            filter_table: vec![],
1650            has_query: false,
1651            content_handles: vec![],
1652            focus_handle: cx.focus_handle(),
1653            navbar_focus_handle: NonFocusableHandle::new(
1654                NAVBAR_CONTAINER_TAB_INDEX,
1655                false,
1656                window,
1657                cx,
1658            ),
1659            navbar_focus_subscriptions: vec![],
1660            content_focus_handle: NonFocusableHandle::new(
1661                CONTENT_CONTAINER_TAB_INDEX,
1662                false,
1663                window,
1664                cx,
1665            ),
1666            files_focus_handle: cx
1667                .focus_handle()
1668                .tab_index(HEADER_CONTAINER_TAB_INDEX)
1669                .tab_stop(false),
1670            search_index: None,
1671            shown_errors: HashSet::default(),
1672            regex_validation_error: None,
1673            list_state,
1674        };
1675
1676        this.fetch_files(window, cx);
1677        this.build_ui(window, cx);
1678        this.build_search_index();
1679
1680        this.search_bar.update(cx, |editor, cx| {
1681            editor.focus_handle(cx).focus(window, cx);
1682        });
1683
1684        this
1685    }
1686
1687    fn handle_project_event(
1688        &mut self,
1689        _: &Entity<Project>,
1690        event: &project::Event,
1691        window: &mut Window,
1692        cx: &mut Context<SettingsWindow>,
1693    ) {
1694        match event {
1695            project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1696                cx.defer_in(window, |this, window, cx| {
1697                    this.fetch_files(window, cx);
1698                });
1699            }
1700            _ => {}
1701        }
1702    }
1703
1704    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1705        // We can only toggle root entries
1706        if !self.navbar_entries[nav_entry_index].is_root {
1707            return;
1708        }
1709
1710        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1711        *expanded = !*expanded;
1712        self.navbar_entry = nav_entry_index;
1713        self.reset_list_state();
1714    }
1715
1716    fn build_navbar(&mut self, cx: &App) {
1717        let mut navbar_entries = Vec::new();
1718
1719        for (page_index, page) in self.pages.iter().enumerate() {
1720            navbar_entries.push(NavBarEntry {
1721                title: page.title,
1722                is_root: true,
1723                expanded: false,
1724                page_index,
1725                item_index: None,
1726                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1727            });
1728
1729            for (item_index, item) in page.items.iter().enumerate() {
1730                let SettingsPageItem::SectionHeader(title) = item else {
1731                    continue;
1732                };
1733                navbar_entries.push(NavBarEntry {
1734                    title,
1735                    is_root: false,
1736                    expanded: false,
1737                    page_index,
1738                    item_index: Some(item_index),
1739                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1740                });
1741            }
1742        }
1743
1744        self.navbar_entries = navbar_entries;
1745    }
1746
1747    fn setup_navbar_focus_subscriptions(
1748        &mut self,
1749        window: &mut Window,
1750        cx: &mut Context<SettingsWindow>,
1751    ) {
1752        let mut focus_subscriptions = Vec::new();
1753
1754        for entry_index in 0..self.navbar_entries.len() {
1755            let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1756
1757            let subscription = cx.on_focus(
1758                &focus_handle,
1759                window,
1760                move |this: &mut SettingsWindow,
1761                      window: &mut Window,
1762                      cx: &mut Context<SettingsWindow>| {
1763                    this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1764                },
1765            );
1766            focus_subscriptions.push(subscription);
1767        }
1768        self.navbar_focus_subscriptions = focus_subscriptions;
1769    }
1770
1771    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1772        let mut index = 0;
1773        let entries = &self.navbar_entries;
1774        let search_matches = &self.filter_table;
1775        let has_query = self.has_query;
1776        std::iter::from_fn(move || {
1777            while index < entries.len() {
1778                let entry = &entries[index];
1779                let included_in_search = if let Some(item_index) = entry.item_index {
1780                    search_matches[entry.page_index][item_index]
1781                } else {
1782                    search_matches[entry.page_index].iter().any(|b| *b)
1783                        || search_matches[entry.page_index].is_empty()
1784                };
1785                if included_in_search {
1786                    break;
1787                }
1788                index += 1;
1789            }
1790            if index >= self.navbar_entries.len() {
1791                return None;
1792            }
1793            let entry = &entries[index];
1794            let entry_index = index;
1795
1796            index += 1;
1797            if entry.is_root && !entry.expanded && !has_query {
1798                while index < entries.len() {
1799                    if entries[index].is_root {
1800                        break;
1801                    }
1802                    index += 1;
1803                }
1804            }
1805
1806            return Some((entry_index, entry));
1807        })
1808    }
1809
1810    fn filter_matches_to_file(&mut self) {
1811        let current_file = self.current_file.mask();
1812        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1813            let mut header_index = 0;
1814            let mut any_found_since_last_header = true;
1815
1816            for (index, item) in page.items.iter().enumerate() {
1817                match item {
1818                    SettingsPageItem::SectionHeader(_) => {
1819                        if !any_found_since_last_header {
1820                            page_filter[header_index] = false;
1821                        }
1822                        header_index = index;
1823                        any_found_since_last_header = false;
1824                    }
1825                    SettingsPageItem::SettingItem(SettingItem { files, .. })
1826                    | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1827                    | SettingsPageItem::DynamicItem(DynamicItem {
1828                        discriminant: SettingItem { files, .. },
1829                        ..
1830                    }) => {
1831                        if !files.contains(current_file) {
1832                            page_filter[index] = false;
1833                        } else {
1834                            any_found_since_last_header = true;
1835                        }
1836                    }
1837                    SettingsPageItem::ActionLink(ActionLink { files, .. }) => {
1838                        if !files.contains(current_file) {
1839                            page_filter[index] = false;
1840                        } else {
1841                            any_found_since_last_header = true;
1842                        }
1843                    }
1844                }
1845            }
1846            if let Some(last_header) = page_filter.get_mut(header_index)
1847                && !any_found_since_last_header
1848            {
1849                *last_header = false;
1850            }
1851        }
1852    }
1853
1854    fn filter_by_json_path(&self, query: &str) -> Vec<usize> {
1855        let Some(path) = query.strip_prefix('#') else {
1856            return vec![];
1857        };
1858        let Some(search_index) = self.search_index.as_ref() else {
1859            return vec![];
1860        };
1861        let mut indices = vec![];
1862        for (index, SearchKeyLUTEntry { json_path, .. }) in search_index.key_lut.iter().enumerate()
1863        {
1864            let Some(json_path) = json_path else {
1865                continue;
1866            };
1867
1868            if let Some(post) = json_path.strip_prefix(path)
1869                && (post.is_empty() || post.starts_with('.'))
1870            {
1871                indices.push(index);
1872            }
1873        }
1874        indices
1875    }
1876
1877    fn apply_match_indices(&mut self, match_indices: impl Iterator<Item = usize>) {
1878        let Some(search_index) = self.search_index.as_ref() else {
1879            return;
1880        };
1881
1882        for page in &mut self.filter_table {
1883            page.fill(false);
1884        }
1885
1886        for match_index in match_indices {
1887            let SearchKeyLUTEntry {
1888                page_index,
1889                header_index,
1890                item_index,
1891                ..
1892            } = search_index.key_lut[match_index];
1893            let page = &mut self.filter_table[page_index];
1894            page[header_index] = true;
1895            page[item_index] = true;
1896        }
1897        self.has_query = true;
1898        self.filter_matches_to_file();
1899        self.open_first_nav_page();
1900        self.reset_list_state();
1901    }
1902
1903    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1904        self.search_task.take();
1905        let query = self.search_bar.read(cx).text(cx);
1906        if query.is_empty() || self.search_index.is_none() {
1907            for page in &mut self.filter_table {
1908                page.fill(true);
1909            }
1910            self.has_query = false;
1911            self.filter_matches_to_file();
1912            self.reset_list_state();
1913            cx.notify();
1914            return;
1915        }
1916
1917        let is_json_link_query = query.starts_with("#");
1918        if is_json_link_query {
1919            let indices = self.filter_by_json_path(&query);
1920            if !indices.is_empty() {
1921                self.apply_match_indices(indices.into_iter());
1922                cx.notify();
1923                return;
1924            }
1925        }
1926
1927        let search_index = self.search_index.as_ref().unwrap().clone();
1928
1929        self.search_task = Some(cx.spawn(async move |this, cx| {
1930            let exact_match_task = cx.background_spawn({
1931                let search_index = search_index.clone();
1932                let query = query.clone();
1933                async move {
1934                    let query_lower = query.to_lowercase();
1935                    let query_words: Vec<&str> = query_lower.split_whitespace().collect();
1936                    search_index
1937                        .documents
1938                        .iter()
1939                        .filter(|doc| {
1940                            query_words.iter().any(|query_word| {
1941                                doc.words
1942                                    .iter()
1943                                    .any(|doc_word| doc_word.starts_with(query_word))
1944                            })
1945                        })
1946                        .map(|doc| doc.id)
1947                        .collect::<Vec<usize>>()
1948                }
1949            });
1950            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1951            let fuzzy_search_task = fuzzy::match_strings(
1952                search_index.fuzzy_match_candidates.as_slice(),
1953                &query,
1954                false,
1955                true,
1956                search_index.fuzzy_match_candidates.len(),
1957                &cancel_flag,
1958                cx.background_executor().clone(),
1959            );
1960
1961            let fuzzy_matches = fuzzy_search_task.await;
1962            let exact_matches = exact_match_task.await;
1963
1964            _ = this
1965                .update(cx, |this, cx| {
1966                    let exact_indices = exact_matches.into_iter();
1967                    let fuzzy_indices = fuzzy_matches
1968                        .into_iter()
1969                        .take_while(|fuzzy_match| fuzzy_match.score >= 0.5)
1970                        .map(|fuzzy_match| fuzzy_match.candidate_id);
1971                    let merged_indices = exact_indices.chain(fuzzy_indices);
1972
1973                    this.apply_match_indices(merged_indices);
1974                    cx.notify();
1975                })
1976                .ok();
1977
1978            cx.background_executor().timer(Duration::from_secs(1)).await;
1979            telemetry::event!("Settings Searched", query = query)
1980        }));
1981    }
1982
1983    fn build_filter_table(&mut self) {
1984        self.filter_table = self
1985            .pages
1986            .iter()
1987            .map(|page| vec![true; page.items.len()])
1988            .collect::<Vec<_>>();
1989    }
1990
1991    fn build_search_index(&mut self) {
1992        fn split_into_words(parts: &[&str]) -> Vec<String> {
1993            parts
1994                .iter()
1995                .flat_map(|s| {
1996                    s.split(|c: char| !c.is_alphanumeric())
1997                        .filter(|w| !w.is_empty())
1998                        .map(|w| w.to_lowercase())
1999                })
2000                .collect()
2001        }
2002
2003        let mut key_lut: Vec<SearchKeyLUTEntry> = vec![];
2004        let mut documents: Vec<SearchDocument> = Vec::default();
2005        let mut fuzzy_match_candidates = Vec::default();
2006
2007        fn push_candidates(
2008            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
2009            key_index: usize,
2010            input: &str,
2011        ) {
2012            for word in input.split_ascii_whitespace() {
2013                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
2014            }
2015        }
2016
2017        // PERF: We are currently searching all items even in project files
2018        // where many settings are filtered out, using the logic in filter_matches_to_file
2019        // we could only search relevant items based on the current file
2020        for (page_index, page) in self.pages.iter().enumerate() {
2021            let mut header_index = 0;
2022            let mut header_str = "";
2023            for (item_index, item) in page.items.iter().enumerate() {
2024                let key_index = key_lut.len();
2025                let mut json_path = None;
2026                match item {
2027                    SettingsPageItem::DynamicItem(DynamicItem {
2028                        discriminant: item, ..
2029                    })
2030                    | SettingsPageItem::SettingItem(item) => {
2031                        json_path = item
2032                            .field
2033                            .json_path()
2034                            .map(|path| path.trim_end_matches('$'));
2035                        documents.push(SearchDocument {
2036                            id: key_index,
2037                            words: split_into_words(&[
2038                                page.title,
2039                                header_str,
2040                                item.title,
2041                                item.description,
2042                            ]),
2043                        });
2044                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
2045                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
2046                    }
2047                    SettingsPageItem::SectionHeader(header) => {
2048                        documents.push(SearchDocument {
2049                            id: key_index,
2050                            words: split_into_words(&[header]),
2051                        });
2052                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
2053                        header_index = item_index;
2054                        header_str = *header;
2055                    }
2056                    SettingsPageItem::SubPageLink(sub_page_link) => {
2057                        json_path = sub_page_link.json_path;
2058                        documents.push(SearchDocument {
2059                            id: key_index,
2060                            words: split_into_words(&[
2061                                page.title,
2062                                header_str,
2063                                sub_page_link.title.as_ref(),
2064                            ]),
2065                        });
2066                        push_candidates(
2067                            &mut fuzzy_match_candidates,
2068                            key_index,
2069                            sub_page_link.title.as_ref(),
2070                        );
2071                    }
2072                    SettingsPageItem::ActionLink(action_link) => {
2073                        documents.push(SearchDocument {
2074                            id: key_index,
2075                            words: split_into_words(&[
2076                                page.title,
2077                                header_str,
2078                                action_link.title.as_ref(),
2079                            ]),
2080                        });
2081                        push_candidates(
2082                            &mut fuzzy_match_candidates,
2083                            key_index,
2084                            action_link.title.as_ref(),
2085                        );
2086                    }
2087                }
2088                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
2089                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
2090
2091                key_lut.push(SearchKeyLUTEntry {
2092                    page_index,
2093                    header_index,
2094                    item_index,
2095                    json_path,
2096                });
2097            }
2098        }
2099        self.search_index = Some(Arc::new(SearchIndex {
2100            documents,
2101            key_lut,
2102            fuzzy_match_candidates,
2103        }));
2104    }
2105
2106    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2107        self.content_handles = self
2108            .pages
2109            .iter()
2110            .map(|page| {
2111                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
2112                    .take(page.items.len())
2113                    .collect()
2114            })
2115            .collect::<Vec<_>>();
2116    }
2117
2118    fn reset_list_state(&mut self) {
2119        let mut visible_items_count = self.visible_page_items().count();
2120
2121        if visible_items_count > 0 {
2122            // show page title if page is non empty
2123            visible_items_count += 1;
2124        }
2125
2126        self.list_state.reset(visible_items_count);
2127    }
2128
2129    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2130        if self.pages.is_empty() {
2131            self.pages = page_data::settings_data(cx);
2132            self.build_navbar(cx);
2133            self.setup_navbar_focus_subscriptions(window, cx);
2134            self.build_content_handles(window, cx);
2135        }
2136        self.sub_page_stack.clear();
2137        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
2138        self.build_filter_table();
2139        self.reset_list_state();
2140        self.update_matches(cx);
2141
2142        cx.notify();
2143    }
2144
2145    #[track_caller]
2146    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2147        self.worktree_root_dirs.clear();
2148        let prev_files = self.files.clone();
2149        let settings_store = cx.global::<SettingsStore>();
2150        let mut ui_files = vec![];
2151        let mut all_files = settings_store.get_all_files();
2152        if !all_files.contains(&settings::SettingsFile::User) {
2153            all_files.push(settings::SettingsFile::User);
2154        }
2155        for file in all_files {
2156            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
2157                continue;
2158            };
2159            if settings_ui_file.is_server() {
2160                continue;
2161            }
2162
2163            if let Some(worktree_id) = settings_ui_file.worktree_id() {
2164                let directory_name = all_projects(self.original_window.as_ref(), cx)
2165                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
2166                    .map(|worktree| worktree.read(cx).root_name());
2167
2168                let Some(directory_name) = directory_name else {
2169                    log::error!(
2170                        "No directory name found for settings file at worktree ID: {}",
2171                        worktree_id
2172                    );
2173                    continue;
2174                };
2175
2176                self.worktree_root_dirs
2177                    .insert(worktree_id, directory_name.as_unix_str().to_string());
2178            }
2179
2180            let focus_handle = prev_files
2181                .iter()
2182                .find_map(|(prev_file, handle)| {
2183                    (prev_file == &settings_ui_file).then(|| handle.clone())
2184                })
2185                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
2186            ui_files.push((settings_ui_file, focus_handle));
2187        }
2188
2189        ui_files.reverse();
2190
2191        if self.original_window.is_some() {
2192            let mut missing_worktrees = Vec::new();
2193
2194            for worktree in all_projects(self.original_window.as_ref(), cx)
2195                .flat_map(|project| project.read(cx).visible_worktrees(cx))
2196                .filter(|tree| !self.worktree_root_dirs.contains_key(&tree.read(cx).id()))
2197            {
2198                let worktree = worktree.read(cx);
2199                let worktree_id = worktree.id();
2200                let Some(directory_name) = worktree.root_dir().and_then(|file| {
2201                    file.file_name()
2202                        .map(|os_string| os_string.to_string_lossy().to_string())
2203                }) else {
2204                    continue;
2205                };
2206
2207                missing_worktrees.push((worktree_id, directory_name.clone()));
2208                let path = RelPath::empty().to_owned().into_arc();
2209
2210                let settings_ui_file = SettingsUiFile::Project((worktree_id, path));
2211
2212                let focus_handle = prev_files
2213                    .iter()
2214                    .find_map(|(prev_file, handle)| {
2215                        (prev_file == &settings_ui_file).then(|| handle.clone())
2216                    })
2217                    .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
2218
2219                ui_files.push((settings_ui_file, focus_handle));
2220            }
2221
2222            self.worktree_root_dirs.extend(missing_worktrees);
2223        }
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().min_w_0().gap_1().overflow_x_hidden().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                .min_w_0()
3116                .justify_between()
3117                .child(
3118                    h_flex()
3119                        .min_w_0()
3120                        .ml_neg_1p5()
3121                        .gap_1()
3122                        .child(
3123                            IconButton::new("back-btn", IconName::ArrowLeft)
3124                                .icon_size(IconSize::Small)
3125                                .shape(IconButtonShape::Square)
3126                                .on_click(cx.listener(|this, _, window, cx| {
3127                                    this.pop_sub_page(window, cx);
3128                                })),
3129                        )
3130                        .child(self.render_sub_page_breadcrumbs()),
3131                )
3132                .when(current_sub_page.link.in_json, |this| {
3133                    this.child(
3134                        div().flex_shrink_0().child(
3135                            Button::new("open-in-settings-file", "Edit in settings.json")
3136                                .tab_index(0_isize)
3137                                .style(ButtonStyle::OutlinedGhost)
3138                                .tooltip(Tooltip::for_action_title_in(
3139                                    "Edit in settings.json",
3140                                    &OpenCurrentFile,
3141                                    &self.focus_handle,
3142                                ))
3143                                .on_click(cx.listener(|this, _, window, cx| {
3144                                    this.open_current_settings_file(window, cx);
3145                                })),
3146                        ),
3147                    )
3148                })
3149                .into_any_element();
3150
3151            let active_page_render_fn = &current_sub_page.link.render;
3152            page_content =
3153                (active_page_render_fn)(self, &current_sub_page.scroll_handle, window, cx);
3154        } else {
3155            page_header = self.render_files_header(window, cx).into_any_element();
3156
3157            page_content = self
3158                .render_current_page_items(window, cx)
3159                .into_any_element();
3160        }
3161
3162        let current_sub_page = self.sub_page_stack.last();
3163
3164        let mut warning_banner = gpui::Empty.into_any_element();
3165        if let Some(error) =
3166            SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
3167        {
3168            fn banner(
3169                label: &'static str,
3170                error: String,
3171                shown_errors: &mut HashSet<String>,
3172                cx: &mut Context<SettingsWindow>,
3173            ) -> impl IntoElement {
3174                if shown_errors.insert(error.clone()) {
3175                    telemetry::event!("Settings Error Shown", label = label, error = &error);
3176                }
3177                Banner::new()
3178                    .severity(Severity::Warning)
3179                    .child(
3180                        v_flex()
3181                            .my_0p5()
3182                            .gap_0p5()
3183                            .child(Label::new(label))
3184                            .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
3185                    )
3186                    .action_slot(
3187                        div().pr_1().pb_1().child(
3188                            Button::new("fix-in-json", "Fix in settings.json")
3189                                .tab_index(0_isize)
3190                                .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3191                                .on_click(cx.listener(|this, _, window, cx| {
3192                                    this.open_current_settings_file(window, cx);
3193                                })),
3194                        ),
3195                    )
3196            }
3197
3198            let parse_error = error.parse_error();
3199            let parse_failed = parse_error.is_some();
3200
3201            warning_banner = v_flex()
3202                .gap_2()
3203                .when_some(parse_error, |this, err| {
3204                    this.child(banner(
3205                        "Failed to load your settings. Some values may be incorrect and changes may be lost.",
3206                        err,
3207                        &mut self.shown_errors,
3208                        cx,
3209                    ))
3210                })
3211                .map(|this| match &error.migration_status {
3212                    settings::MigrationStatus::Succeeded => this.child(banner(
3213                        "Your settings are out of date, and need to be updated.",
3214                        match &self.current_file {
3215                            SettingsUiFile::User => "They can be automatically migrated to the latest version.",
3216                            SettingsUiFile::Server(_) | SettingsUiFile::Project(_)  => "They must be manually migrated to the latest version."
3217                        }.to_string(),
3218                        &mut self.shown_errors,
3219                        cx,
3220                    )),
3221                    settings::MigrationStatus::Failed { error: err } if !parse_failed => this
3222                        .child(banner(
3223                            "Your settings file is out of date, automatic migration failed",
3224                            err.clone(),
3225                            &mut self.shown_errors,
3226                            cx,
3227                        )),
3228                    _ => this,
3229                })
3230                .into_any_element()
3231        }
3232
3233        v_flex()
3234            .id("settings-ui-page")
3235            .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3236                if !this.sub_page_stack.is_empty() {
3237                    window.focus_next(cx);
3238                    return;
3239                }
3240                for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
3241                    let handle = this.content_handles[this.current_page_index()][actual_index]
3242                        .focus_handle(cx);
3243                    let mut offset = 1; // for page header
3244
3245                    if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
3246                        && matches!(next_item, SettingsPageItem::SectionHeader(_))
3247                    {
3248                        offset += 1;
3249                    }
3250                    if handle.contains_focused(window, cx) {
3251                        let next_logical_index = logical_index + offset + 1;
3252                        this.list_state.scroll_to_reveal_item(next_logical_index);
3253                        // We need to render the next item to ensure it's focus handle is in the element tree
3254                        cx.on_next_frame(window, |_, window, cx| {
3255                            cx.notify();
3256                            cx.on_next_frame(window, |_, window, cx| {
3257                                window.focus_next(cx);
3258                                cx.notify();
3259                            });
3260                        });
3261                        cx.notify();
3262                        return;
3263                    }
3264                }
3265                window.focus_next(cx);
3266            }))
3267            .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
3268                if !this.sub_page_stack.is_empty() {
3269                    window.focus_prev(cx);
3270                    return;
3271                }
3272                let mut prev_was_header = false;
3273                for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
3274                    let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
3275                    let handle = this.content_handles[this.current_page_index()][actual_index]
3276                        .focus_handle(cx);
3277                    let mut offset = 1; // for page header
3278
3279                    if prev_was_header {
3280                        offset -= 1;
3281                    }
3282                    if handle.contains_focused(window, cx) {
3283                        let next_logical_index = logical_index + offset - 1;
3284                        this.list_state.scroll_to_reveal_item(next_logical_index);
3285                        // We need to render the next item to ensure it's focus handle is in the element tree
3286                        cx.on_next_frame(window, |_, window, cx| {
3287                            cx.notify();
3288                            cx.on_next_frame(window, |_, window, cx| {
3289                                window.focus_prev(cx);
3290                                cx.notify();
3291                            });
3292                        });
3293                        cx.notify();
3294                        return;
3295                    }
3296                    prev_was_header = is_header;
3297                }
3298                window.focus_prev(cx);
3299            }))
3300            .when(current_sub_page.is_none(), |this| {
3301                this.vertical_scrollbar_for(&self.list_state, window, cx)
3302            })
3303            .when_some(current_sub_page, |this, current_sub_page| {
3304                this.custom_scrollbars(
3305                    Scrollbars::new(ui::ScrollAxes::Vertical)
3306                        .tracked_scroll_handle(&current_sub_page.scroll_handle)
3307                        .id((current_sub_page.link.title.clone(), 42)),
3308                    window,
3309                    cx,
3310                )
3311            })
3312            .track_focus(&self.content_focus_handle.focus_handle(cx))
3313            .pt_6()
3314            .gap_4()
3315            .flex_1()
3316            .min_w_0()
3317            .bg(cx.theme().colors().editor_background)
3318            .child(
3319                v_flex()
3320                    .px_8()
3321                    .gap_2()
3322                    .child(page_header)
3323                    .child(warning_banner),
3324            )
3325            .child(
3326                div()
3327                    .flex_1()
3328                    .min_h_0()
3329                    .size_full()
3330                    .tab_group()
3331                    .tab_index(CONTENT_GROUP_TAB_INDEX)
3332                    .child(page_content),
3333            )
3334    }
3335
3336    /// This function will create a new settings file if one doesn't exist
3337    /// if the current file is a project settings with a valid worktree id
3338    /// We do this because the settings ui allows initializing project settings
3339    fn open_current_settings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3340        match &self.current_file {
3341            SettingsUiFile::User => {
3342                let Some(original_window) = self.original_window else {
3343                    return;
3344                };
3345                original_window
3346                    .update(cx, |multi_workspace, window, cx| {
3347                        multi_workspace
3348                            .workspace()
3349                            .clone()
3350                            .update(cx, |workspace, cx| {
3351                                workspace
3352                                    .with_local_or_wsl_workspace(
3353                                        window,
3354                                        cx,
3355                                        open_user_settings_in_workspace,
3356                                    )
3357                                    .detach();
3358                            });
3359                    })
3360                    .ok();
3361
3362                window.remove_window();
3363            }
3364            SettingsUiFile::Project((worktree_id, path)) => {
3365                let settings_path = path.join(paths::local_settings_file_relative_path());
3366                let app_state = workspace::AppState::global(cx);
3367
3368                let Some((workspace_window, worktree, corresponding_workspace)) = app_state
3369                    .workspace_store
3370                    .read(cx)
3371                    .workspaces_with_windows()
3372                    .filter_map(|(window_handle, weak)| {
3373                        let workspace = weak.upgrade()?;
3374                        let window = window_handle.downcast::<MultiWorkspace>()?;
3375                        Some((window, workspace))
3376                    })
3377                    .find_map(|(window, workspace): (_, Entity<Workspace>)| {
3378                        workspace
3379                            .read(cx)
3380                            .project()
3381                            .read(cx)
3382                            .worktree_for_id(*worktree_id, cx)
3383                            .map(|worktree| (window, worktree, workspace))
3384                    })
3385                else {
3386                    log::error!(
3387                        "No corresponding workspace contains worktree id: {}",
3388                        worktree_id
3389                    );
3390
3391                    return;
3392                };
3393
3394                let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3395                    None
3396                } else {
3397                    Some(worktree.update(cx, |tree, cx| {
3398                        tree.create_entry(
3399                            settings_path.clone(),
3400                            false,
3401                            Some(initial_project_settings_content().as_bytes().to_vec()),
3402                            cx,
3403                        )
3404                    }))
3405                };
3406
3407                let worktree_id = *worktree_id;
3408
3409                // TODO: move zed::open_local_file() APIs to this crate, and
3410                // re-implement the "initial_contents" behavior
3411                let workspace_weak = corresponding_workspace.downgrade();
3412                workspace_window
3413                    .update(cx, |_, window, cx| {
3414                        cx.spawn_in(window, async move |_, cx| {
3415                            if let Some(create_task) = create_task {
3416                                create_task.await.ok()?;
3417                            };
3418
3419                            workspace_weak
3420                                .update_in(cx, |workspace, window, cx| {
3421                                    workspace.open_path(
3422                                        (worktree_id, settings_path.clone()),
3423                                        None,
3424                                        true,
3425                                        window,
3426                                        cx,
3427                                    )
3428                                })
3429                                .ok()?
3430                                .await
3431                                .log_err()?;
3432
3433                            workspace_weak
3434                                .update_in(cx, |_, window, cx| {
3435                                    window.activate_window();
3436                                    cx.notify();
3437                                })
3438                                .ok();
3439
3440                            Some(())
3441                        })
3442                        .detach();
3443                    })
3444                    .ok();
3445
3446                window.remove_window();
3447            }
3448            SettingsUiFile::Server(_) => {
3449                // Server files are not editable
3450                return;
3451            }
3452        };
3453    }
3454
3455    fn current_page_index(&self) -> usize {
3456        if self.navbar_entries.is_empty() {
3457            return 0;
3458        }
3459
3460        self.navbar_entries[self.navbar_entry].page_index
3461    }
3462
3463    fn current_page(&self) -> &SettingsPage {
3464        &self.pages[self.current_page_index()]
3465    }
3466
3467    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3468        ix == self.navbar_entry
3469    }
3470
3471    fn push_sub_page(
3472        &mut self,
3473        sub_page_link: SubPageLink,
3474        section_header: SharedString,
3475        window: &mut Window,
3476        cx: &mut Context<SettingsWindow>,
3477    ) {
3478        self.sub_page_stack
3479            .push(SubPage::new(sub_page_link, section_header));
3480        self.content_focus_handle.focus_handle(cx).focus(window, cx);
3481        cx.notify();
3482    }
3483
3484    /// Push a dynamically-created sub-page with a custom render function.
3485    /// This is useful for nested sub-pages that aren't defined in the main pages list.
3486    pub fn push_dynamic_sub_page(
3487        &mut self,
3488        title: impl Into<SharedString>,
3489        section_header: impl Into<SharedString>,
3490        json_path: Option<&'static str>,
3491        render: fn(
3492            &SettingsWindow,
3493            &ScrollHandle,
3494            &mut Window,
3495            &mut Context<SettingsWindow>,
3496        ) -> AnyElement,
3497        window: &mut Window,
3498        cx: &mut Context<SettingsWindow>,
3499    ) {
3500        self.regex_validation_error = None;
3501        let sub_page_link = SubPageLink {
3502            title: title.into(),
3503            r#type: SubPageType::default(),
3504            description: None,
3505            json_path,
3506            in_json: true,
3507            files: USER,
3508            render,
3509        };
3510        self.push_sub_page(sub_page_link, section_header.into(), window, cx);
3511    }
3512
3513    /// Navigate to a sub-page by its json_path.
3514    /// Returns true if the sub-page was found and pushed, false otherwise.
3515    pub fn navigate_to_sub_page(
3516        &mut self,
3517        json_path: &str,
3518        window: &mut Window,
3519        cx: &mut Context<SettingsWindow>,
3520    ) -> bool {
3521        for page in &self.pages {
3522            for (item_index, item) in page.items.iter().enumerate() {
3523                if let SettingsPageItem::SubPageLink(sub_page_link) = item {
3524                    if sub_page_link.json_path == Some(json_path) {
3525                        let section_header = page
3526                            .items
3527                            .iter()
3528                            .take(item_index)
3529                            .rev()
3530                            .find_map(|item| item.header_text().map(SharedString::new_static))
3531                            .unwrap_or_else(|| "Settings".into());
3532
3533                        self.push_sub_page(sub_page_link.clone(), section_header, window, cx);
3534                        return true;
3535                    }
3536                }
3537            }
3538        }
3539        false
3540    }
3541
3542    /// Navigate to a setting by its json_path.
3543    /// Clears the sub-page stack and scrolls to the setting item.
3544    /// Returns true if the setting was found, false otherwise.
3545    pub fn navigate_to_setting(
3546        &mut self,
3547        json_path: &str,
3548        window: &mut Window,
3549        cx: &mut Context<SettingsWindow>,
3550    ) -> bool {
3551        self.sub_page_stack.clear();
3552
3553        for (page_index, page) in self.pages.iter().enumerate() {
3554            for (item_index, item) in page.items.iter().enumerate() {
3555                let item_json_path = match item {
3556                    SettingsPageItem::SettingItem(setting_item) => setting_item.field.json_path(),
3557                    SettingsPageItem::DynamicItem(dynamic_item) => {
3558                        dynamic_item.discriminant.field.json_path()
3559                    }
3560                    _ => None,
3561                };
3562                if item_json_path == Some(json_path) {
3563                    if let Some(navbar_entry_index) = self
3564                        .navbar_entries
3565                        .iter()
3566                        .position(|e| e.page_index == page_index && e.is_root)
3567                    {
3568                        self.open_and_scroll_to_navbar_entry(
3569                            navbar_entry_index,
3570                            None,
3571                            false,
3572                            window,
3573                            cx,
3574                        );
3575                        self.scroll_to_content_item(item_index, window, cx);
3576                        return true;
3577                    }
3578                }
3579            }
3580        }
3581        false
3582    }
3583
3584    fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
3585        self.regex_validation_error = None;
3586        self.sub_page_stack.pop();
3587        self.content_focus_handle.focus_handle(cx).focus(window, cx);
3588        cx.notify();
3589    }
3590
3591    fn focus_file_at_index(&mut self, index: usize, window: &mut Window, cx: &mut App) {
3592        if let Some((_, handle)) = self.files.get(index) {
3593            handle.focus(window, cx);
3594        }
3595    }
3596
3597    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3598        if self.files_focus_handle.contains_focused(window, cx)
3599            && let Some(index) = self
3600                .files
3601                .iter()
3602                .position(|(_, handle)| handle.is_focused(window))
3603        {
3604            return index;
3605        }
3606        if let Some(current_file_index) = self
3607            .files
3608            .iter()
3609            .position(|(file, _)| file == &self.current_file)
3610        {
3611            return current_file_index;
3612        }
3613        0
3614    }
3615
3616    fn focus_handle_for_content_element(
3617        &self,
3618        actual_item_index: usize,
3619        cx: &Context<Self>,
3620    ) -> FocusHandle {
3621        let page_index = self.current_page_index();
3622        self.content_handles[page_index][actual_item_index].focus_handle(cx)
3623    }
3624
3625    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3626        if !self
3627            .navbar_focus_handle
3628            .focus_handle(cx)
3629            .contains_focused(window, cx)
3630        {
3631            return None;
3632        }
3633        for (index, entry) in self.navbar_entries.iter().enumerate() {
3634            if entry.focus_handle.is_focused(window) {
3635                return Some(index);
3636            }
3637        }
3638        None
3639    }
3640
3641    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3642        let mut index = Some(nav_entry_index);
3643        while let Some(prev_index) = index
3644            && !self.navbar_entries[prev_index].is_root
3645        {
3646            index = prev_index.checked_sub(1);
3647        }
3648        return index.expect("No root entry found");
3649    }
3650}
3651
3652impl Render for SettingsWindow {
3653    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3654        let ui_font = theme_settings::setup_ui_font(window, cx);
3655
3656        client_side_decorations(
3657            v_flex()
3658                .text_color(cx.theme().colors().text)
3659                .size_full()
3660                .children(self.title_bar.clone())
3661                .child(
3662                    div()
3663                        .id("settings-window")
3664                        .key_context("SettingsWindow")
3665                        .track_focus(&self.focus_handle)
3666                        .on_action(cx.listener(|this, _: &OpenCurrentFile, window, cx| {
3667                            this.open_current_settings_file(window, cx);
3668                        }))
3669                        .on_action(|_: &Minimize, window, _cx| {
3670                            window.minimize_window();
3671                        })
3672                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3673                            this.search_bar.focus_handle(cx).focus(window, cx);
3674                        }))
3675                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3676                            if this
3677                                .navbar_focus_handle
3678                                .focus_handle(cx)
3679                                .contains_focused(window, cx)
3680                            {
3681                                this.open_and_scroll_to_navbar_entry(
3682                                    this.navbar_entry,
3683                                    None,
3684                                    true,
3685                                    window,
3686                                    cx,
3687                                );
3688                            } else {
3689                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3690                            }
3691                        }))
3692                        .on_action(cx.listener(
3693                            |this, FocusFile(file_index): &FocusFile, window, cx| {
3694                                this.focus_file_at_index(*file_index as usize, window, cx);
3695                            },
3696                        ))
3697                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3698                            let next_index = usize::min(
3699                                this.focused_file_index(window, cx) + 1,
3700                                this.files.len().saturating_sub(1),
3701                            );
3702                            this.focus_file_at_index(next_index, window, cx);
3703                        }))
3704                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3705                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3706                            this.focus_file_at_index(prev_index, window, cx);
3707                        }))
3708                        .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3709                            if this
3710                                .search_bar
3711                                .focus_handle(cx)
3712                                .contains_focused(window, cx)
3713                            {
3714                                this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3715                            } else {
3716                                window.focus_next(cx);
3717                            }
3718                        }))
3719                        .on_action(|_: &menu::SelectPrevious, window, cx| {
3720                            window.focus_prev(cx);
3721                        })
3722                        .flex()
3723                        .flex_row()
3724                        .flex_1()
3725                        .min_h_0()
3726                        .font(ui_font)
3727                        .bg(cx.theme().colors().background)
3728                        .text_color(cx.theme().colors().text)
3729                        .when(!cfg!(target_os = "macos"), |this| {
3730                            this.border_t_1().border_color(cx.theme().colors().border)
3731                        })
3732                        .child(self.render_nav(window, cx))
3733                        .child(self.render_page(window, cx)),
3734                ),
3735            window,
3736            cx,
3737            Tiling::default(),
3738        )
3739    }
3740}
3741
3742fn all_projects(
3743    window: Option<&WindowHandle<MultiWorkspace>>,
3744    cx: &App,
3745) -> impl Iterator<Item = Entity<Project>> {
3746    let mut seen_project_ids = std::collections::HashSet::new();
3747    let app_state = workspace::AppState::global(cx);
3748    app_state
3749        .workspace_store
3750        .read(cx)
3751        .workspaces()
3752        .filter_map(|weak| weak.upgrade())
3753        .map(|workspace: Entity<Workspace>| workspace.read(cx).project().clone())
3754        .chain(
3755            window
3756                .and_then(|handle| handle.read(cx).ok())
3757                .into_iter()
3758                .flat_map(|multi_workspace| {
3759                    multi_workspace
3760                        .workspaces()
3761                        .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
3768fn open_user_settings_in_workspace(
3769    workspace: &mut Workspace,
3770    window: &mut Window,
3771    cx: &mut Context<Workspace>,
3772) {
3773    let project = workspace.project().clone();
3774
3775    cx.spawn_in(window, async move |workspace, cx| {
3776        let (config_dir, settings_file) = project.update(cx, |project, cx| {
3777            (
3778                project.try_windows_path_to_wsl(paths::config_dir().as_path(), cx),
3779                project.try_windows_path_to_wsl(paths::settings_file().as_path(), cx),
3780            )
3781        });
3782        let config_dir = config_dir.await?;
3783        let settings_file = settings_file.await?;
3784        project
3785            .update(cx, |project, cx| {
3786                project.find_or_create_worktree(&config_dir, false, cx)
3787            })
3788            .await
3789            .ok();
3790        workspace
3791            .update_in(cx, |workspace, window, cx| {
3792                workspace.open_paths(
3793                    vec![settings_file],
3794                    OpenOptions {
3795                        visible: Some(OpenVisible::None),
3796                        ..Default::default()
3797                    },
3798                    None,
3799                    window,
3800                    cx,
3801                )
3802            })?
3803            .await;
3804
3805        workspace.update_in(cx, |_, window, cx| {
3806            window.activate_window();
3807            cx.notify();
3808        })
3809    })
3810    .detach();
3811}
3812
3813fn update_settings_file(
3814    file: SettingsUiFile,
3815    file_name: Option<&'static str>,
3816    window: &mut Window,
3817    cx: &mut App,
3818    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3819) -> Result<()> {
3820    telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3821
3822    match file {
3823        SettingsUiFile::Project((worktree_id, rel_path)) => {
3824            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3825            let Some(settings_window) = window.root::<SettingsWindow>().flatten() else {
3826                anyhow::bail!("No settings window found");
3827            };
3828
3829            update_project_setting_file(worktree_id, rel_path, update, settings_window, cx)
3830        }
3831        SettingsUiFile::User => {
3832            // todo(settings_ui) error?
3833            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3834            Ok(())
3835        }
3836        SettingsUiFile::Server(_) => unimplemented!(),
3837    }
3838}
3839
3840struct ProjectSettingsUpdateEntry {
3841    worktree_id: WorktreeId,
3842    rel_path: Arc<RelPath>,
3843    settings_window: WeakEntity<SettingsWindow>,
3844    project: WeakEntity<Project>,
3845    worktree: WeakEntity<Worktree>,
3846    update: Box<dyn FnOnce(&mut SettingsContent, &App)>,
3847}
3848
3849struct ProjectSettingsUpdateQueue {
3850    tx: mpsc::UnboundedSender<ProjectSettingsUpdateEntry>,
3851    _task: Task<()>,
3852}
3853
3854impl Global for ProjectSettingsUpdateQueue {}
3855
3856impl ProjectSettingsUpdateQueue {
3857    fn new(cx: &mut App) -> Self {
3858        let (tx, mut rx) = mpsc::unbounded();
3859        let task = cx.spawn(async move |mut cx| {
3860            while let Some(entry) = rx.next().await {
3861                if let Err(err) = Self::process_entry(entry, &mut cx).await {
3862                    log::error!("Failed to update project settings: {err:?}");
3863                }
3864            }
3865        });
3866        Self { tx, _task: task }
3867    }
3868
3869    fn enqueue(cx: &mut App, entry: ProjectSettingsUpdateEntry) {
3870        cx.update_global::<Self, _>(|queue, _cx| {
3871            if let Err(err) = queue.tx.unbounded_send(entry) {
3872                log::error!("Failed to enqueue project settings update: {err}");
3873            }
3874        });
3875    }
3876
3877    async fn process_entry(entry: ProjectSettingsUpdateEntry, cx: &mut AsyncApp) -> Result<()> {
3878        let ProjectSettingsUpdateEntry {
3879            worktree_id,
3880            rel_path,
3881            settings_window,
3882            project,
3883            worktree,
3884            update,
3885        } = entry;
3886
3887        let project_path = ProjectPath {
3888            worktree_id,
3889            path: rel_path.clone(),
3890        };
3891
3892        let needs_creation = worktree.read_with(cx, |worktree, _| {
3893            worktree.entry_for_path(&rel_path).is_none()
3894        })?;
3895
3896        if needs_creation {
3897            worktree
3898                .update(cx, |worktree, cx| {
3899                    worktree.create_entry(rel_path.clone(), false, None, cx)
3900                })?
3901                .await?;
3902        }
3903
3904        let buffer_store = project.read_with(cx, |project, _cx| project.buffer_store().clone())?;
3905
3906        let cached_buffer = settings_window
3907            .read_with(cx, |settings_window, _| {
3908                settings_window
3909                    .project_setting_file_buffers
3910                    .get(&project_path)
3911                    .cloned()
3912            })
3913            .unwrap_or_default();
3914
3915        let buffer = if let Some(cached_buffer) = cached_buffer {
3916            let needs_reload = cached_buffer.read_with(cx, |buffer, _| buffer.has_conflict());
3917            if needs_reload {
3918                cached_buffer
3919                    .update(cx, |buffer, cx| buffer.reload(cx))
3920                    .await
3921                    .context("Failed to reload settings file")?;
3922            }
3923            cached_buffer
3924        } else {
3925            let buffer = buffer_store
3926                .update(cx, |store, cx| store.open_buffer(project_path.clone(), cx))
3927                .await
3928                .context("Failed to open settings file")?;
3929
3930            let _ = settings_window.update(cx, |this, _cx| {
3931                this.project_setting_file_buffers
3932                    .insert(project_path, buffer.clone());
3933            });
3934
3935            buffer
3936        };
3937
3938        buffer.update(cx, |buffer, cx| {
3939            let current_text = buffer.text();
3940            if let Some(new_text) = cx
3941                .global::<SettingsStore>()
3942                .new_text_for_update(current_text, |settings| update(settings, cx))
3943                .log_err()
3944            {
3945                buffer.edit([(0..buffer.len(), new_text)], None, cx);
3946            }
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_editable_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        .mode(NumberFieldMode::Edit, cx)
4075        .tab_index(0_isize)
4076        .on_change({
4077            move |value, window, cx| {
4078                let value = *value;
4079                update_settings_file(
4080                    file.clone(),
4081                    field.json_path,
4082                    window,
4083                    cx,
4084                    move |settings, _cx| {
4085                        (field.write)(settings, Some(value));
4086                    },
4087                )
4088                .log_err(); // todo(settings_ui) don't log err
4089            }
4090        })
4091        .into_any_element()
4092}
4093
4094fn render_dropdown<T>(
4095    field: SettingField<T>,
4096    file: SettingsUiFile,
4097    metadata: Option<&SettingsFieldMetadata>,
4098    _window: &mut Window,
4099    cx: &mut App,
4100) -> AnyElement
4101where
4102    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
4103{
4104    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
4105    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
4106    let should_do_titlecase = metadata
4107        .and_then(|metadata| metadata.should_do_titlecase)
4108        .unwrap_or(true);
4109
4110    let (_, current_value) =
4111        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4112    let current_value = current_value.copied().unwrap_or(variants()[0]);
4113
4114    EnumVariantDropdown::new("dropdown", current_value, variants(), labels(), {
4115        move |value, window, cx| {
4116            if value == current_value {
4117                return;
4118            }
4119            update_settings_file(
4120                file.clone(),
4121                field.json_path,
4122                window,
4123                cx,
4124                move |settings, _cx| {
4125                    (field.write)(settings, Some(value));
4126                },
4127            )
4128            .log_err(); // todo(settings_ui) don't log err
4129        }
4130    })
4131    .tab_index(0)
4132    .title_case(should_do_titlecase)
4133    .into_any_element()
4134}
4135
4136fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
4137    Button::new(id, label)
4138        .tab_index(0_isize)
4139        .style(ButtonStyle::Outlined)
4140        .size(ButtonSize::Medium)
4141        .end_icon(
4142            Icon::new(IconName::ChevronUpDown)
4143                .size(IconSize::Small)
4144                .color(Color::Muted),
4145        )
4146}
4147
4148fn render_font_picker(
4149    field: SettingField<settings::FontFamilyName>,
4150    file: SettingsUiFile,
4151    _metadata: Option<&SettingsFieldMetadata>,
4152    _window: &mut Window,
4153    cx: &mut App,
4154) -> AnyElement {
4155    let current_value = SettingsStore::global(cx)
4156        .get_value_from_file(file.to_settings(), field.pick)
4157        .1
4158        .cloned()
4159        .map_or_else(|| SharedString::default(), |value| value.into_gpui());
4160
4161    PopoverMenu::new("font-picker")
4162        .trigger(render_picker_trigger_button(
4163            "font_family_picker_trigger".into(),
4164            current_value.clone(),
4165        ))
4166        .menu(move |window, cx| {
4167            let file = file.clone();
4168            let current_value = current_value.clone();
4169
4170            Some(cx.new(move |cx| {
4171                font_picker(
4172                    current_value,
4173                    move |font_name, window, cx| {
4174                        update_settings_file(
4175                            file.clone(),
4176                            field.json_path,
4177                            window,
4178                            cx,
4179                            move |settings, _cx| {
4180                                (field.write)(settings, Some(font_name.to_string().into()));
4181                            },
4182                        )
4183                        .log_err(); // todo(settings_ui) don't log err
4184                    },
4185                    window,
4186                    cx,
4187                )
4188            }))
4189        })
4190        .anchor(gpui::Corner::TopLeft)
4191        .offset(gpui::Point {
4192            x: px(0.0),
4193            y: px(2.0),
4194        })
4195        .with_handle(ui::PopoverMenuHandle::default())
4196        .into_any_element()
4197}
4198
4199fn render_theme_picker(
4200    field: SettingField<settings::ThemeName>,
4201    file: SettingsUiFile,
4202    _metadata: Option<&SettingsFieldMetadata>,
4203    _window: &mut Window,
4204    cx: &mut App,
4205) -> AnyElement {
4206    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4207    let current_value = value
4208        .cloned()
4209        .map(|theme_name| theme_name.0.into())
4210        .unwrap_or_else(|| cx.theme().name.clone());
4211
4212    PopoverMenu::new("theme-picker")
4213        .trigger(render_picker_trigger_button(
4214            "theme_picker_trigger".into(),
4215            current_value.clone(),
4216        ))
4217        .menu(move |window, cx| {
4218            Some(cx.new(|cx| {
4219                let file = file.clone();
4220                let current_value = current_value.clone();
4221                theme_picker(
4222                    current_value,
4223                    move |theme_name, window, cx| {
4224                        update_settings_file(
4225                            file.clone(),
4226                            field.json_path,
4227                            window,
4228                            cx,
4229                            move |settings, _cx| {
4230                                (field.write)(
4231                                    settings,
4232                                    Some(settings::ThemeName(theme_name.into())),
4233                                );
4234                            },
4235                        )
4236                        .log_err(); // todo(settings_ui) don't log err
4237                    },
4238                    window,
4239                    cx,
4240                )
4241            }))
4242        })
4243        .anchor(gpui::Corner::TopLeft)
4244        .offset(gpui::Point {
4245            x: px(0.0),
4246            y: px(2.0),
4247        })
4248        .with_handle(ui::PopoverMenuHandle::default())
4249        .into_any_element()
4250}
4251
4252fn render_icon_theme_picker(
4253    field: SettingField<settings::IconThemeName>,
4254    file: SettingsUiFile,
4255    _metadata: Option<&SettingsFieldMetadata>,
4256    _window: &mut Window,
4257    cx: &mut App,
4258) -> AnyElement {
4259    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4260    let current_value = value
4261        .cloned()
4262        .map(|theme_name| theme_name.0.into())
4263        .unwrap_or_else(|| cx.theme().name.clone());
4264
4265    PopoverMenu::new("icon-theme-picker")
4266        .trigger(render_picker_trigger_button(
4267            "icon_theme_picker_trigger".into(),
4268            current_value.clone(),
4269        ))
4270        .menu(move |window, cx| {
4271            Some(cx.new(|cx| {
4272                let file = file.clone();
4273                let current_value = current_value.clone();
4274                icon_theme_picker(
4275                    current_value,
4276                    move |theme_name, window, cx| {
4277                        update_settings_file(
4278                            file.clone(),
4279                            field.json_path,
4280                            window,
4281                            cx,
4282                            move |settings, _cx| {
4283                                (field.write)(
4284                                    settings,
4285                                    Some(settings::IconThemeName(theme_name.into())),
4286                                );
4287                            },
4288                        )
4289                        .log_err(); // todo(settings_ui) don't log err
4290                    },
4291                    window,
4292                    cx,
4293                )
4294            }))
4295        })
4296        .anchor(gpui::Corner::TopLeft)
4297        .offset(gpui::Point {
4298            x: px(0.0),
4299            y: px(2.0),
4300        })
4301        .with_handle(ui::PopoverMenuHandle::default())
4302        .into_any_element()
4303}
4304
4305#[cfg(test)]
4306pub mod test {
4307
4308    use super::*;
4309
4310    impl SettingsWindow {
4311        fn navbar_entry(&self) -> usize {
4312            self.navbar_entry
4313        }
4314
4315        #[cfg(any(test, feature = "test-support"))]
4316        pub fn test(window: &mut Window, cx: &mut Context<Self>) -> Self {
4317            let search_bar = cx.new(|cx| Editor::single_line(window, cx));
4318            let dummy_page = SettingsPage {
4319                title: "Test",
4320                items: Box::new([]),
4321            };
4322            Self {
4323                title_bar: None,
4324                original_window: None,
4325                worktree_root_dirs: HashMap::default(),
4326                files: Vec::default(),
4327                current_file: SettingsUiFile::User,
4328                project_setting_file_buffers: HashMap::default(),
4329                pages: vec![dummy_page],
4330                search_bar,
4331                navbar_entry: 0,
4332                navbar_entries: Vec::default(),
4333                navbar_scroll_handle: UniformListScrollHandle::default(),
4334                navbar_focus_subscriptions: Vec::default(),
4335                filter_table: Vec::default(),
4336                has_query: false,
4337                content_handles: Vec::default(),
4338                search_task: None,
4339                sub_page_stack: Vec::default(),
4340                opening_link: false,
4341                focus_handle: cx.focus_handle(),
4342                navbar_focus_handle: NonFocusableHandle::new(
4343                    NAVBAR_CONTAINER_TAB_INDEX,
4344                    false,
4345                    window,
4346                    cx,
4347                ),
4348                content_focus_handle: NonFocusableHandle::new(
4349                    CONTENT_CONTAINER_TAB_INDEX,
4350                    false,
4351                    window,
4352                    cx,
4353                ),
4354                files_focus_handle: cx.focus_handle(),
4355                search_index: None,
4356                list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4357                shown_errors: HashSet::default(),
4358                regex_validation_error: None,
4359            }
4360        }
4361    }
4362
4363    impl PartialEq for NavBarEntry {
4364        fn eq(&self, other: &Self) -> bool {
4365            self.title == other.title
4366                && self.is_root == other.is_root
4367                && self.expanded == other.expanded
4368                && self.page_index == other.page_index
4369                && self.item_index == other.item_index
4370            // ignoring focus_handle
4371        }
4372    }
4373
4374    pub fn register_settings(cx: &mut App) {
4375        settings::init(cx);
4376        theme_settings::init(theme::LoadThemes::JustBase, cx);
4377        editor::init(cx);
4378        menu::init();
4379    }
4380
4381    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
4382        struct PageBuilder {
4383            title: &'static str,
4384            items: Vec<SettingsPageItem>,
4385        }
4386        let mut page_builders: Vec<PageBuilder> = Vec::new();
4387        let mut expanded_pages = Vec::new();
4388        let mut selected_idx = None;
4389        let mut index = 0;
4390        let mut in_expanded_section = false;
4391
4392        for mut line in input
4393            .lines()
4394            .map(|line| line.trim())
4395            .filter(|line| !line.is_empty())
4396        {
4397            if let Some(pre) = line.strip_suffix('*') {
4398                assert!(selected_idx.is_none(), "Only one selected entry allowed");
4399                selected_idx = Some(index);
4400                line = pre;
4401            }
4402            let (kind, title) = line.split_once(" ").unwrap();
4403            assert_eq!(kind.len(), 1);
4404            let kind = kind.chars().next().unwrap();
4405            if kind == 'v' {
4406                let page_idx = page_builders.len();
4407                expanded_pages.push(page_idx);
4408                page_builders.push(PageBuilder {
4409                    title,
4410                    items: vec![],
4411                });
4412                index += 1;
4413                in_expanded_section = true;
4414            } else if kind == '>' {
4415                page_builders.push(PageBuilder {
4416                    title,
4417                    items: vec![],
4418                });
4419                index += 1;
4420                in_expanded_section = false;
4421            } else if kind == '-' {
4422                page_builders
4423                    .last_mut()
4424                    .unwrap()
4425                    .items
4426                    .push(SettingsPageItem::SectionHeader(title));
4427                if selected_idx == Some(index) && !in_expanded_section {
4428                    panic!("Items in unexpanded sections cannot be selected");
4429                }
4430                index += 1;
4431            } else {
4432                panic!(
4433                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
4434                    line
4435                );
4436            }
4437        }
4438
4439        let pages: Vec<SettingsPage> = page_builders
4440            .into_iter()
4441            .map(|builder| SettingsPage {
4442                title: builder.title,
4443                items: builder.items.into_boxed_slice(),
4444            })
4445            .collect();
4446
4447        let mut settings_window = SettingsWindow {
4448            title_bar: None,
4449            original_window: None,
4450            worktree_root_dirs: HashMap::default(),
4451            files: Vec::default(),
4452            current_file: crate::SettingsUiFile::User,
4453            project_setting_file_buffers: HashMap::default(),
4454            pages,
4455            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
4456            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
4457            navbar_entries: Vec::default(),
4458            navbar_scroll_handle: UniformListScrollHandle::default(),
4459            navbar_focus_subscriptions: vec![],
4460            filter_table: vec![],
4461            sub_page_stack: vec![],
4462            opening_link: false,
4463            has_query: false,
4464            content_handles: vec![],
4465            search_task: None,
4466            focus_handle: cx.focus_handle(),
4467            navbar_focus_handle: NonFocusableHandle::new(
4468                NAVBAR_CONTAINER_TAB_INDEX,
4469                false,
4470                window,
4471                cx,
4472            ),
4473            content_focus_handle: NonFocusableHandle::new(
4474                CONTENT_CONTAINER_TAB_INDEX,
4475                false,
4476                window,
4477                cx,
4478            ),
4479            files_focus_handle: cx.focus_handle(),
4480            search_index: None,
4481            list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4482            shown_errors: HashSet::default(),
4483            regex_validation_error: None,
4484        };
4485
4486        settings_window.build_filter_table();
4487        settings_window.build_navbar(cx);
4488        for expanded_page_index in expanded_pages {
4489            for entry in &mut settings_window.navbar_entries {
4490                if entry.page_index == expanded_page_index && entry.is_root {
4491                    entry.expanded = true;
4492                }
4493            }
4494        }
4495        settings_window
4496    }
4497
4498    #[track_caller]
4499    fn check_navbar_toggle(
4500        before: &'static str,
4501        toggle_page: &'static str,
4502        after: &'static str,
4503        window: &mut Window,
4504        cx: &mut App,
4505    ) {
4506        let mut settings_window = parse(before, window, cx);
4507        let toggle_page_idx = settings_window
4508            .pages
4509            .iter()
4510            .position(|page| page.title == toggle_page)
4511            .expect("page not found");
4512        let toggle_idx = settings_window
4513            .navbar_entries
4514            .iter()
4515            .position(|entry| entry.page_index == toggle_page_idx)
4516            .expect("page not found");
4517        settings_window.toggle_navbar_entry(toggle_idx);
4518
4519        let expected_settings_window = parse(after, window, cx);
4520
4521        pretty_assertions::assert_eq!(
4522            settings_window
4523                .visible_navbar_entries()
4524                .map(|(_, entry)| entry)
4525                .collect::<Vec<_>>(),
4526            expected_settings_window
4527                .visible_navbar_entries()
4528                .map(|(_, entry)| entry)
4529                .collect::<Vec<_>>(),
4530        );
4531        pretty_assertions::assert_eq!(
4532            settings_window.navbar_entries[settings_window.navbar_entry()],
4533            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
4534        );
4535    }
4536
4537    macro_rules! check_navbar_toggle {
4538        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
4539            #[gpui::test]
4540            fn $name(cx: &mut gpui::TestAppContext) {
4541                let window = cx.add_empty_window();
4542                window.update(|window, cx| {
4543                    register_settings(cx);
4544                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
4545                });
4546            }
4547        };
4548    }
4549
4550    check_navbar_toggle!(
4551        navbar_basic_open,
4552        before: r"
4553        v General
4554        - General
4555        - Privacy*
4556        v Project
4557        - Project Settings
4558        ",
4559        toggle_page: "General",
4560        after: r"
4561        > General*
4562        v Project
4563        - Project Settings
4564        "
4565    );
4566
4567    check_navbar_toggle!(
4568        navbar_basic_close,
4569        before: r"
4570        > General*
4571        - General
4572        - Privacy
4573        v Project
4574        - Project Settings
4575        ",
4576        toggle_page: "General",
4577        after: r"
4578        v General*
4579        - General
4580        - Privacy
4581        v Project
4582        - Project Settings
4583        "
4584    );
4585
4586    check_navbar_toggle!(
4587        navbar_basic_second_root_entry_close,
4588        before: r"
4589        > General
4590        - General
4591        - Privacy
4592        v Project
4593        - Project Settings*
4594        ",
4595        toggle_page: "Project",
4596        after: r"
4597        > General
4598        > Project*
4599        "
4600    );
4601
4602    check_navbar_toggle!(
4603        navbar_toggle_subroot,
4604        before: r"
4605        v General Page
4606        - General
4607        - Privacy
4608        v Project
4609        - Worktree Settings Content*
4610        v AI
4611        - General
4612        > Appearance & Behavior
4613        ",
4614        toggle_page: "Project",
4615        after: r"
4616        v General Page
4617        - General
4618        - Privacy
4619        > Project*
4620        v AI
4621        - General
4622        > Appearance & Behavior
4623        "
4624    );
4625
4626    check_navbar_toggle!(
4627        navbar_toggle_close_propagates_selected_index,
4628        before: r"
4629        v General Page
4630        - General
4631        - Privacy
4632        v Project
4633        - Worktree Settings Content
4634        v AI
4635        - General*
4636        > Appearance & Behavior
4637        ",
4638        toggle_page: "General Page",
4639        after: r"
4640        > General Page*
4641        v Project
4642        - Worktree Settings Content
4643        v AI
4644        - General
4645        > Appearance & Behavior
4646        "
4647    );
4648
4649    check_navbar_toggle!(
4650        navbar_toggle_expand_propagates_selected_index,
4651        before: r"
4652        > General Page
4653        - General
4654        - Privacy
4655        v Project
4656        - Worktree Settings Content
4657        v AI
4658        - General*
4659        > Appearance & Behavior
4660        ",
4661        toggle_page: "General Page",
4662        after: 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    );
4673
4674    #[gpui::test]
4675    async fn test_settings_window_shows_worktrees_from_multiple_workspaces(
4676        cx: &mut gpui::TestAppContext,
4677    ) {
4678        use project::Project;
4679        use serde_json::json;
4680
4681        cx.update(|cx| {
4682            register_settings(cx);
4683        });
4684
4685        let app_state = cx.update(|cx| {
4686            let app_state = AppState::test(cx);
4687            AppState::set_global(app_state.clone(), cx);
4688            app_state
4689        });
4690
4691        let fake_fs = app_state.fs.as_fake();
4692
4693        fake_fs
4694            .insert_tree(
4695                "/workspace1",
4696                json!({
4697                    "worktree_a": {
4698                        "file1.rs": "fn main() {}"
4699                    },
4700                    "worktree_b": {
4701                        "file2.rs": "fn test() {}"
4702                    }
4703                }),
4704            )
4705            .await;
4706
4707        fake_fs
4708            .insert_tree(
4709                "/workspace2",
4710                json!({
4711                    "worktree_c": {
4712                        "file3.rs": "fn foo() {}"
4713                    }
4714                }),
4715            )
4716            .await;
4717
4718        let project1 = cx.update(|cx| {
4719            Project::local(
4720                app_state.client.clone(),
4721                app_state.node_runtime.clone(),
4722                app_state.user_store.clone(),
4723                app_state.languages.clone(),
4724                app_state.fs.clone(),
4725                None,
4726                project::LocalProjectFlags::default(),
4727                cx,
4728            )
4729        });
4730
4731        project1
4732            .update(cx, |project, cx| {
4733                project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4734            })
4735            .await
4736            .expect("Failed to create worktree_a");
4737        project1
4738            .update(cx, |project, cx| {
4739                project.find_or_create_worktree("/workspace1/worktree_b", true, cx)
4740            })
4741            .await
4742            .expect("Failed to create worktree_b");
4743
4744        let project2 = cx.update(|cx| {
4745            Project::local(
4746                app_state.client.clone(),
4747                app_state.node_runtime.clone(),
4748                app_state.user_store.clone(),
4749                app_state.languages.clone(),
4750                app_state.fs.clone(),
4751                None,
4752                project::LocalProjectFlags::default(),
4753                cx,
4754            )
4755        });
4756
4757        project2
4758            .update(cx, |project, cx| {
4759                project.find_or_create_worktree("/workspace2/worktree_c", true, cx)
4760            })
4761            .await
4762            .expect("Failed to create worktree_c");
4763
4764        let (_multi_workspace1, cx) = cx.add_window_view(|window, cx| {
4765            let workspace = cx.new(|cx| {
4766                Workspace::new(
4767                    Default::default(),
4768                    project1.clone(),
4769                    app_state.clone(),
4770                    window,
4771                    cx,
4772                )
4773            });
4774            MultiWorkspace::new(workspace, window, cx)
4775        });
4776
4777        let (_multi_workspace2, cx) = cx.add_window_view(|window, cx| {
4778            let workspace = cx.new(|cx| {
4779                Workspace::new(
4780                    Default::default(),
4781                    project2.clone(),
4782                    app_state.clone(),
4783                    window,
4784                    cx,
4785                )
4786            });
4787            MultiWorkspace::new(workspace, window, cx)
4788        });
4789
4790        let workspace2_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
4791
4792        cx.run_until_parked();
4793
4794        let (settings_window, cx) = cx
4795            .add_window_view(|window, cx| SettingsWindow::new(Some(workspace2_handle), window, cx));
4796
4797        cx.run_until_parked();
4798
4799        settings_window.read_with(cx, |settings_window, _| {
4800            let worktree_names: Vec<_> = settings_window
4801                .worktree_root_dirs
4802                .values()
4803                .cloned()
4804                .collect();
4805
4806            assert!(
4807                worktree_names.iter().any(|name| name == "worktree_a"),
4808                "Should contain worktree_a from workspace1, but found: {:?}",
4809                worktree_names
4810            );
4811            assert!(
4812                worktree_names.iter().any(|name| name == "worktree_b"),
4813                "Should contain worktree_b from workspace1, but found: {:?}",
4814                worktree_names
4815            );
4816            assert!(
4817                worktree_names.iter().any(|name| name == "worktree_c"),
4818                "Should contain worktree_c from workspace2, but found: {:?}",
4819                worktree_names
4820            );
4821
4822            assert_eq!(
4823                worktree_names.len(),
4824                3,
4825                "Should have exactly 3 worktrees from both workspaces, but found: {:?}",
4826                worktree_names
4827            );
4828
4829            let project_files: Vec<_> = settings_window
4830                .files
4831                .iter()
4832                .filter_map(|(f, _)| match f {
4833                    SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
4834                    _ => None,
4835                })
4836                .collect();
4837
4838            let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
4839            assert_eq!(
4840                project_files.len(),
4841                unique_project_files.len(),
4842                "Should have no duplicate project files, but found duplicates. All files: {:?}",
4843                project_files
4844            );
4845        });
4846    }
4847
4848    #[gpui::test]
4849    async fn test_settings_window_updates_when_new_workspace_created(
4850        cx: &mut gpui::TestAppContext,
4851    ) {
4852        use project::Project;
4853        use serde_json::json;
4854
4855        cx.update(|cx| {
4856            register_settings(cx);
4857        });
4858
4859        let app_state = cx.update(|cx| {
4860            let app_state = AppState::test(cx);
4861            AppState::set_global(app_state.clone(), cx);
4862            app_state
4863        });
4864
4865        let fake_fs = app_state.fs.as_fake();
4866
4867        fake_fs
4868            .insert_tree(
4869                "/workspace1",
4870                json!({
4871                    "worktree_a": {
4872                        "file1.rs": "fn main() {}"
4873                    }
4874                }),
4875            )
4876            .await;
4877
4878        fake_fs
4879            .insert_tree(
4880                "/workspace2",
4881                json!({
4882                    "worktree_b": {
4883                        "file2.rs": "fn test() {}"
4884                    }
4885                }),
4886            )
4887            .await;
4888
4889        let project1 = cx.update(|cx| {
4890            Project::local(
4891                app_state.client.clone(),
4892                app_state.node_runtime.clone(),
4893                app_state.user_store.clone(),
4894                app_state.languages.clone(),
4895                app_state.fs.clone(),
4896                None,
4897                project::LocalProjectFlags::default(),
4898                cx,
4899            )
4900        });
4901
4902        project1
4903            .update(cx, |project, cx| {
4904                project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4905            })
4906            .await
4907            .expect("Failed to create worktree_a");
4908
4909        let (_multi_workspace1, cx) = cx.add_window_view(|window, cx| {
4910            let workspace = cx.new(|cx| {
4911                Workspace::new(
4912                    Default::default(),
4913                    project1.clone(),
4914                    app_state.clone(),
4915                    window,
4916                    cx,
4917                )
4918            });
4919            MultiWorkspace::new(workspace, window, cx)
4920        });
4921
4922        let workspace1_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
4923
4924        cx.run_until_parked();
4925
4926        let (settings_window, cx) = cx
4927            .add_window_view(|window, cx| SettingsWindow::new(Some(workspace1_handle), window, cx));
4928
4929        cx.run_until_parked();
4930
4931        settings_window.read_with(cx, |settings_window, _| {
4932            assert_eq!(
4933                settings_window.worktree_root_dirs.len(),
4934                1,
4935                "Should have 1 worktree initially"
4936            );
4937        });
4938
4939        let project2 = cx.update(|_, cx| {
4940            Project::local(
4941                app_state.client.clone(),
4942                app_state.node_runtime.clone(),
4943                app_state.user_store.clone(),
4944                app_state.languages.clone(),
4945                app_state.fs.clone(),
4946                None,
4947                project::LocalProjectFlags::default(),
4948                cx,
4949            )
4950        });
4951
4952        project2
4953            .update(&mut cx.cx, |project, cx| {
4954                project.find_or_create_worktree("/workspace2/worktree_b", true, cx)
4955            })
4956            .await
4957            .expect("Failed to create worktree_b");
4958
4959        let (_multi_workspace2, cx) = cx.add_window_view(|window, cx| {
4960            let workspace = cx.new(|cx| {
4961                Workspace::new(
4962                    Default::default(),
4963                    project2.clone(),
4964                    app_state.clone(),
4965                    window,
4966                    cx,
4967                )
4968            });
4969            MultiWorkspace::new(workspace, window, cx)
4970        });
4971
4972        cx.run_until_parked();
4973
4974        settings_window.read_with(cx, |settings_window, _| {
4975            let worktree_names: Vec<_> = settings_window
4976                .worktree_root_dirs
4977                .values()
4978                .cloned()
4979                .collect();
4980
4981            assert!(
4982                worktree_names.iter().any(|name| name == "worktree_a"),
4983                "Should contain worktree_a, but found: {:?}",
4984                worktree_names
4985            );
4986            assert!(
4987                worktree_names.iter().any(|name| name == "worktree_b"),
4988                "Should contain worktree_b from newly created workspace, but found: {:?}",
4989                worktree_names
4990            );
4991
4992            assert_eq!(
4993                worktree_names.len(),
4994                2,
4995                "Should have 2 worktrees after new workspace created, but found: {:?}",
4996                worktree_names
4997            );
4998
4999            let project_files: Vec<_> = settings_window
5000                .files
5001                .iter()
5002                .filter_map(|(f, _)| match f {
5003                    SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
5004                    _ => None,
5005                })
5006                .collect();
5007
5008            let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
5009            assert_eq!(
5010                project_files.len(),
5011                unique_project_files.len(),
5012                "Should have no duplicate project files, but found duplicates. All files: {:?}",
5013                project_files
5014            );
5015        });
5016    }
5017}
5018
5019#[cfg(test)]
5020mod project_settings_update_tests {
5021    use super::*;
5022    use fs::{FakeFs, Fs as _};
5023    use gpui::TestAppContext;
5024    use project::Project;
5025    use serde_json::json;
5026    use std::sync::atomic::{AtomicUsize, Ordering};
5027
5028    struct TestSetup {
5029        fs: Arc<FakeFs>,
5030        project: Entity<Project>,
5031        worktree_id: WorktreeId,
5032        worktree: WeakEntity<Worktree>,
5033        rel_path: Arc<RelPath>,
5034        project_path: ProjectPath,
5035    }
5036
5037    async fn init_test(cx: &mut TestAppContext, initial_settings: Option<&str>) -> TestSetup {
5038        cx.update(|cx| {
5039            let store = settings::SettingsStore::test(cx);
5040            cx.set_global(store);
5041            theme_settings::init(theme::LoadThemes::JustBase, cx);
5042            editor::init(cx);
5043            menu::init();
5044            let queue = ProjectSettingsUpdateQueue::new(cx);
5045            cx.set_global(queue);
5046        });
5047
5048        let fs = FakeFs::new(cx.executor());
5049        let tree = if let Some(settings_content) = initial_settings {
5050            json!({
5051                ".zed": {
5052                    "settings.json": settings_content
5053                },
5054                "src": { "main.rs": "" }
5055            })
5056        } else {
5057            json!({ "src": { "main.rs": "" } })
5058        };
5059        fs.insert_tree("/project", tree).await;
5060
5061        let project = Project::test(fs.clone(), ["/project".as_ref()], cx).await;
5062
5063        let (worktree_id, worktree) = project.read_with(cx, |project, cx| {
5064            let worktree = project.worktrees(cx).next().unwrap();
5065            (worktree.read(cx).id(), worktree.downgrade())
5066        });
5067
5068        let rel_path: Arc<RelPath> = RelPath::unix(".zed/settings.json")
5069            .expect("valid path")
5070            .into_arc();
5071        let project_path = ProjectPath {
5072            worktree_id,
5073            path: rel_path.clone(),
5074        };
5075
5076        TestSetup {
5077            fs,
5078            project,
5079            worktree_id,
5080            worktree,
5081            rel_path,
5082            project_path,
5083        }
5084    }
5085
5086    #[gpui::test]
5087    async fn test_creates_settings_file_if_missing(cx: &mut TestAppContext) {
5088        let setup = init_test(cx, None).await;
5089
5090        let entry = ProjectSettingsUpdateEntry {
5091            worktree_id: setup.worktree_id,
5092            rel_path: setup.rel_path.clone(),
5093            settings_window: WeakEntity::new_invalid(),
5094            project: setup.project.downgrade(),
5095            worktree: setup.worktree,
5096            update: Box::new(|content, _cx| {
5097                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5098            }),
5099        };
5100
5101        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5102        cx.executor().run_until_parked();
5103
5104        let buffer_store = setup
5105            .project
5106            .read_with(cx, |project, _| project.buffer_store().clone());
5107        let buffer = buffer_store
5108            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5109            .await
5110            .expect("buffer should exist");
5111
5112        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5113        assert!(
5114            text.contains("\"tab_size\": 4"),
5115            "Expected tab_size setting in: {}",
5116            text
5117        );
5118    }
5119
5120    #[gpui::test]
5121    async fn test_updates_existing_settings_file(cx: &mut TestAppContext) {
5122        let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).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(8).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\": 8"),
5149            "Expected updated tab_size in: {}",
5150            text
5151        );
5152    }
5153
5154    #[gpui::test]
5155    async fn test_updates_are_serialized(cx: &mut TestAppContext) {
5156        let setup = init_test(cx, Some("{}")).await;
5157
5158        let update_order = Arc::new(std::sync::Mutex::new(Vec::new()));
5159
5160        for i in 1..=3 {
5161            let update_order = update_order.clone();
5162            let entry = ProjectSettingsUpdateEntry {
5163                worktree_id: setup.worktree_id,
5164                rel_path: setup.rel_path.clone(),
5165                settings_window: WeakEntity::new_invalid(),
5166                project: setup.project.downgrade(),
5167                worktree: setup.worktree.clone(),
5168                update: Box::new(move |content, _cx| {
5169                    update_order.lock().unwrap().push(i);
5170                    content.project.all_languages.defaults.tab_size =
5171                        Some(NonZeroU32::new(i).unwrap());
5172                }),
5173            };
5174            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5175        }
5176
5177        cx.executor().run_until_parked();
5178
5179        let order = update_order.lock().unwrap().clone();
5180        assert_eq!(order, vec![1, 2, 3], "Updates should be processed in order");
5181
5182        let buffer_store = setup
5183            .project
5184            .read_with(cx, |project, _| project.buffer_store().clone());
5185        let buffer = buffer_store
5186            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5187            .await
5188            .expect("buffer should exist");
5189
5190        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5191        assert!(
5192            text.contains("\"tab_size\": 3"),
5193            "Final tab_size should be 3: {}",
5194            text
5195        );
5196    }
5197
5198    #[gpui::test]
5199    async fn test_queue_continues_after_failure(cx: &mut TestAppContext) {
5200        let setup = init_test(cx, Some("{}")).await;
5201
5202        let successful_updates = Arc::new(AtomicUsize::new(0));
5203
5204        {
5205            let successful_updates = successful_updates.clone();
5206            let entry = ProjectSettingsUpdateEntry {
5207                worktree_id: setup.worktree_id,
5208                rel_path: setup.rel_path.clone(),
5209                settings_window: WeakEntity::new_invalid(),
5210                project: setup.project.downgrade(),
5211                worktree: setup.worktree.clone(),
5212                update: Box::new(move |content, _cx| {
5213                    successful_updates.fetch_add(1, Ordering::SeqCst);
5214                    content.project.all_languages.defaults.tab_size =
5215                        Some(NonZeroU32::new(2).unwrap());
5216                }),
5217            };
5218            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5219        }
5220
5221        {
5222            let entry = ProjectSettingsUpdateEntry {
5223                worktree_id: setup.worktree_id,
5224                rel_path: setup.rel_path.clone(),
5225                settings_window: WeakEntity::new_invalid(),
5226                project: WeakEntity::new_invalid(),
5227                worktree: setup.worktree.clone(),
5228                update: Box::new(|content, _cx| {
5229                    content.project.all_languages.defaults.tab_size =
5230                        Some(NonZeroU32::new(99).unwrap());
5231                }),
5232            };
5233            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5234        }
5235
5236        {
5237            let successful_updates = successful_updates.clone();
5238            let entry = ProjectSettingsUpdateEntry {
5239                worktree_id: setup.worktree_id,
5240                rel_path: setup.rel_path.clone(),
5241                settings_window: WeakEntity::new_invalid(),
5242                project: setup.project.downgrade(),
5243                worktree: setup.worktree.clone(),
5244                update: Box::new(move |content, _cx| {
5245                    successful_updates.fetch_add(1, Ordering::SeqCst);
5246                    content.project.all_languages.defaults.tab_size =
5247                        Some(NonZeroU32::new(4).unwrap());
5248                }),
5249            };
5250            cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5251        }
5252
5253        cx.executor().run_until_parked();
5254
5255        assert_eq!(
5256            successful_updates.load(Ordering::SeqCst),
5257            2,
5258            "Two updates should have succeeded despite middle failure"
5259        );
5260
5261        let buffer_store = setup
5262            .project
5263            .read_with(cx, |project, _| project.buffer_store().clone());
5264        let buffer = buffer_store
5265            .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5266            .await
5267            .expect("buffer should exist");
5268
5269        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5270        assert!(
5271            text.contains("\"tab_size\": 4"),
5272            "Final tab_size should be 4 (third update): {}",
5273            text
5274        );
5275    }
5276
5277    #[gpui::test]
5278    async fn test_handles_dropped_worktree(cx: &mut TestAppContext) {
5279        let setup = init_test(cx, Some("{}")).await;
5280
5281        let entry = ProjectSettingsUpdateEntry {
5282            worktree_id: setup.worktree_id,
5283            rel_path: setup.rel_path.clone(),
5284            settings_window: WeakEntity::new_invalid(),
5285            project: setup.project.downgrade(),
5286            worktree: WeakEntity::new_invalid(),
5287            update: Box::new(|content, _cx| {
5288                content.project.all_languages.defaults.tab_size =
5289                    Some(NonZeroU32::new(99).unwrap());
5290            }),
5291        };
5292
5293        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5294        cx.executor().run_until_parked();
5295
5296        let file_content = setup
5297            .fs
5298            .load("/project/.zed/settings.json".as_ref())
5299            .await
5300            .unwrap();
5301        assert_eq!(
5302            file_content, "{}",
5303            "File should be unchanged when worktree is dropped"
5304        );
5305    }
5306
5307    #[gpui::test]
5308    async fn test_reloads_conflicted_buffer(cx: &mut TestAppContext) {
5309        let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5310
5311        let buffer_store = setup
5312            .project
5313            .read_with(cx, |project, _| project.buffer_store().clone());
5314        let buffer = buffer_store
5315            .update(cx, |store, cx| {
5316                store.open_buffer(setup.project_path.clone(), cx)
5317            })
5318            .await
5319            .expect("buffer should exist");
5320
5321        buffer.update(cx, |buffer, cx| {
5322            buffer.edit([(0..0, "// comment\n")], None, cx);
5323        });
5324
5325        let has_unsaved_edits = buffer.read_with(cx, |buffer, _| buffer.has_unsaved_edits());
5326        assert!(has_unsaved_edits, "Buffer should have unsaved edits");
5327
5328        setup
5329            .fs
5330            .save(
5331                "/project/.zed/settings.json".as_ref(),
5332                &r#"{ "tab_size": 99 }"#.into(),
5333                Default::default(),
5334            )
5335            .await
5336            .expect("save should succeed");
5337
5338        cx.executor().run_until_parked();
5339
5340        let has_conflict = buffer.read_with(cx, |buffer, _| buffer.has_conflict());
5341        assert!(
5342            has_conflict,
5343            "Buffer should have conflict after external modification"
5344        );
5345
5346        let (settings_window, _) = cx.add_window_view(|window, cx| {
5347            let mut sw = SettingsWindow::test(window, cx);
5348            sw.project_setting_file_buffers
5349                .insert(setup.project_path.clone(), buffer.clone());
5350            sw
5351        });
5352
5353        let entry = ProjectSettingsUpdateEntry {
5354            worktree_id: setup.worktree_id,
5355            rel_path: setup.rel_path.clone(),
5356            settings_window: settings_window.downgrade(),
5357            project: setup.project.downgrade(),
5358            worktree: setup.worktree.clone(),
5359            update: Box::new(|content, _cx| {
5360                content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5361            }),
5362        };
5363
5364        cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5365        cx.executor().run_until_parked();
5366
5367        let text = buffer.read_with(cx, |buffer, _| buffer.text());
5368        assert!(
5369            text.contains("\"tab_size\": 4"),
5370            "Buffer should have the new tab_size after reload and update: {}",
5371            text
5372        );
5373        assert!(
5374            !text.contains("// comment"),
5375            "Buffer should not contain the unsaved edit after reload: {}",
5376            text
5377        );
5378        assert!(
5379            !text.contains("99"),
5380            "Buffer should not contain the external modification value: {}",
5381            text
5382        );
5383    }
5384}