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::DocumentColorsRenderMode>(render_dropdown)
 539        .add_basic_renderer::<settings::ThemeSelectionDiscriminants>(render_dropdown)
 540        .add_basic_renderer::<settings::ThemeAppearanceMode>(render_dropdown)
 541        .add_basic_renderer::<settings::ThemeName>(render_theme_picker)
 542        .add_basic_renderer::<settings::IconThemeSelectionDiscriminants>(render_dropdown)
 543        .add_basic_renderer::<settings::IconThemeName>(render_icon_theme_picker)
 544        .add_basic_renderer::<settings::BufferLineHeightDiscriminants>(render_dropdown)
 545        .add_basic_renderer::<settings::AutosaveSettingDiscriminants>(render_dropdown)
 546        .add_basic_renderer::<settings::WorkingDirectoryDiscriminants>(render_dropdown)
 547        .add_basic_renderer::<settings::IncludeIgnoredContent>(render_dropdown)
 548        .add_basic_renderer::<settings::ShowIndentGuides>(render_dropdown)
 549        .add_basic_renderer::<settings::ShellDiscriminants>(render_dropdown)
 550        .add_basic_renderer::<settings::EditPredictionsMode>(render_dropdown)
 551        .add_basic_renderer::<settings::RelativeLineNumbers>(render_dropdown)
 552        .add_basic_renderer::<settings::WindowDecorations>(render_dropdown)
 553        .add_basic_renderer::<settings::WindowButtonLayoutContentDiscriminants>(render_dropdown)
 554        .add_basic_renderer::<settings::FontSize>(render_editable_number_field)
 555        .add_basic_renderer::<settings::OllamaModelName>(render_ollama_model_picker)
 556        .add_basic_renderer::<settings::SemanticTokens>(render_dropdown)
 557        .add_basic_renderer::<settings::DocumentFoldingRanges>(render_dropdown)
 558        .add_basic_renderer::<settings::DocumentSymbols>(render_dropdown)
 559        .add_basic_renderer::<settings::AudioInputDeviceName>(render_input_audio_device_dropdown)
 560        .add_basic_renderer::<settings::AudioOutputDeviceName>(render_output_audio_device_dropdown)
 561        // please semicolon stay on next line
 562        ;
 563}
 564
 565pub fn open_settings_editor(
 566    path: Option<&str>,
 567    target_worktree_id: Option<WorktreeId>,
 568    workspace_handle: Option<WindowHandle<MultiWorkspace>>,
 569    cx: &mut App,
 570) {
 571    telemetry::event!("Settings Viewed");
 572
 573    /// Assumes a settings GUI window is already open
 574    fn open_path(
 575        path: &str,
 576        settings_window: &mut SettingsWindow,
 577        window: &mut Window,
 578        cx: &mut Context<SettingsWindow>,
 579    ) {
 580        if path.starts_with("languages.$(language)") {
 581            log::error!("language-specific settings links are not currently supported");
 582            return;
 583        }
 584
 585        let query = format!("#{path}");
 586        let indices = settings_window.filter_by_json_path(&query);
 587
 588        settings_window.opening_link = true;
 589        settings_window.search_bar.update(cx, |editor, cx| {
 590            editor.set_text(query, window, cx);
 591        });
 592        settings_window.apply_match_indices(indices.iter().copied());
 593
 594        if indices.len() == 1
 595            && let Some(search_index) = settings_window.search_index.as_ref()
 596        {
 597            let SearchKeyLUTEntry {
 598                page_index,
 599                item_index,
 600                header_index,
 601                ..
 602            } = search_index.key_lut[indices[0]];
 603            let page = &settings_window.pages[page_index];
 604            let item = &page.items[item_index];
 605
 606            if settings_window.filter_table[page_index][item_index]
 607                && let SettingsPageItem::SubPageLink(link) = item
 608                && let SettingsPageItem::SectionHeader(header) = page.items[header_index]
 609            {
 610                settings_window.push_sub_page(link.clone(), SharedString::from(header), window, cx);
 611            }
 612        }
 613
 614        cx.notify();
 615    }
 616
 617    let existing_window = cx
 618        .windows()
 619        .into_iter()
 620        .find_map(|window| window.downcast::<SettingsWindow>());
 621
 622    if let Some(existing_window) = existing_window {
 623        existing_window
 624            .update(cx, |settings_window, window, cx| {
 625                settings_window.original_window = workspace_handle;
 626
 627                window.activate_window();
 628                if let Some(path) = path {
 629                    open_path(path, settings_window, window, cx);
 630                } else if let Some(target_id) = target_worktree_id
 631                    && let Some(file_index) = settings_window
 632                        .files
 633                        .iter()
 634                        .position(|(file, _)| file.worktree_id() == Some(target_id))
 635                {
 636                    settings_window.change_file(file_index, window, cx);
 637                    cx.notify();
 638                }
 639            })
 640            .ok();
 641        return;
 642    }
 643
 644    // We have to defer this to get the workspace off the stack.
 645    let path = path.map(ToOwned::to_owned);
 646    cx.defer(move |cx| {
 647        let current_rem_size: f32 = theme_settings::ThemeSettings::get_global(cx)
 648            .ui_font_size(cx)
 649            .into();
 650
 651        let default_bounds = DEFAULT_ADDITIONAL_WINDOW_SIZE;
 652        let default_rem_size = 16.0;
 653        let scale_factor = current_rem_size / default_rem_size;
 654        let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
 655
 656        let app_id = ReleaseChannel::global(cx).app_id();
 657        let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
 658            Ok(val) if val == "server" => gpui::WindowDecorations::Server,
 659            Ok(val) if val == "client" => gpui::WindowDecorations::Client,
 660            _ => gpui::WindowDecorations::Client,
 661        };
 662
 663        cx.open_window(
 664            WindowOptions {
 665                titlebar: Some(TitlebarOptions {
 666                    title: Some("Zed — Settings".into()),
 667                    appears_transparent: true,
 668                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 669                }),
 670                focus: true,
 671                show: true,
 672                is_movable: true,
 673                kind: gpui::WindowKind::Normal,
 674                window_background: cx.theme().window_background_appearance(),
 675                app_id: Some(app_id.to_owned()),
 676                window_decorations: Some(window_decorations),
 677                window_min_size: Some(gpui::Size {
 678                    // Don't make the settings window thinner than this,
 679                    // otherwise, it gets unusable. Users with smaller res monitors
 680                    // can customize the height, but not the width.
 681                    width: px(900.0),
 682                    height: px(240.0),
 683                }),
 684                window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
 685                ..Default::default()
 686            },
 687            |window, cx| {
 688                let settings_window =
 689                    cx.new(|cx| SettingsWindow::new(workspace_handle, window, cx));
 690                settings_window.update(cx, |settings_window, cx| {
 691                    if let Some(path) = path {
 692                        open_path(&path, settings_window, window, cx);
 693                    } else if let Some(target_id) = target_worktree_id
 694                        && let Some(file_index) = settings_window
 695                            .files
 696                            .iter()
 697                            .position(|(file, _)| file.worktree_id() == Some(target_id))
 698                    {
 699                        settings_window.change_file(file_index, window, cx);
 700                    }
 701                });
 702
 703                settings_window
 704            },
 705        )
 706        .log_err();
 707    });
 708}
 709
 710/// The current sub page path that is selected.
 711/// If this is empty the selected page is rendered,
 712/// otherwise the last sub page gets rendered.
 713///
 714/// Global so that `pick` and `write` callbacks can access it
 715/// and use it to dynamically render sub pages (e.g. for language settings)
 716static ACTIVE_LANGUAGE: LazyLock<RwLock<Option<SharedString>>> =
 717    LazyLock::new(|| RwLock::new(Option::None));
 718
 719fn active_language() -> Option<SharedString> {
 720    ACTIVE_LANGUAGE
 721        .read()
 722        .ok()
 723        .and_then(|language| language.clone())
 724}
 725
 726fn active_language_mut() -> Option<std::sync::RwLockWriteGuard<'static, Option<SharedString>>> {
 727    ACTIVE_LANGUAGE.write().ok()
 728}
 729
 730pub struct SettingsWindow {
 731    title_bar: Option<Entity<PlatformTitleBar>>,
 732    original_window: Option<WindowHandle<MultiWorkspace>>,
 733    files: Vec<(SettingsUiFile, FocusHandle)>,
 734    worktree_root_dirs: HashMap<WorktreeId, String>,
 735    current_file: SettingsUiFile,
 736    pages: Vec<SettingsPage>,
 737    sub_page_stack: Vec<SubPage>,
 738    opening_link: bool,
 739    search_bar: Entity<Editor>,
 740    search_task: Option<Task<()>>,
 741    /// Cached settings file buffers to avoid repeated disk I/O on each settings change
 742    project_setting_file_buffers: HashMap<ProjectPath, Entity<Buffer>>,
 743    /// Index into navbar_entries
 744    navbar_entry: usize,
 745    navbar_entries: Vec<NavBarEntry>,
 746    navbar_scroll_handle: UniformListScrollHandle,
 747    /// [page_index][page_item_index] will be false
 748    /// when the item is filtered out either by searches
 749    /// or by the current file
 750    navbar_focus_subscriptions: Vec<gpui::Subscription>,
 751    filter_table: Vec<Vec<bool>>,
 752    has_query: bool,
 753    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 754    focus_handle: FocusHandle,
 755    navbar_focus_handle: Entity<NonFocusableHandle>,
 756    content_focus_handle: Entity<NonFocusableHandle>,
 757    files_focus_handle: FocusHandle,
 758    search_index: Option<Arc<SearchIndex>>,
 759    list_state: ListState,
 760    shown_errors: HashSet<String>,
 761    pub(crate) regex_validation_error: Option<String>,
 762}
 763
 764struct SearchDocument {
 765    id: usize,
 766    words: Vec<String>,
 767}
 768
 769struct SearchIndex {
 770    documents: Vec<SearchDocument>,
 771    fuzzy_match_candidates: Vec<StringMatchCandidate>,
 772    key_lut: Vec<SearchKeyLUTEntry>,
 773}
 774
 775struct SearchKeyLUTEntry {
 776    page_index: usize,
 777    header_index: usize,
 778    item_index: usize,
 779    json_path: Option<&'static str>,
 780}
 781
 782struct SubPage {
 783    link: SubPageLink,
 784    section_header: SharedString,
 785    scroll_handle: ScrollHandle,
 786}
 787
 788impl SubPage {
 789    fn new(link: SubPageLink, section_header: SharedString) -> Self {
 790        if link.r#type == SubPageType::Language
 791            && let Some(mut active_language_global) = active_language_mut()
 792        {
 793            active_language_global.replace(link.title.clone());
 794        }
 795
 796        SubPage {
 797            link,
 798            section_header,
 799            scroll_handle: ScrollHandle::new(),
 800        }
 801    }
 802}
 803
 804impl Drop for SubPage {
 805    fn drop(&mut self) {
 806        if self.link.r#type == SubPageType::Language
 807            && let Some(mut active_language_global) = active_language_mut()
 808            && active_language_global
 809                .as_ref()
 810                .is_some_and(|language_name| language_name == &self.link.title)
 811        {
 812            active_language_global.take();
 813        }
 814    }
 815}
 816
 817#[derive(Debug)]
 818struct NavBarEntry {
 819    title: &'static str,
 820    is_root: bool,
 821    expanded: bool,
 822    page_index: usize,
 823    item_index: Option<usize>,
 824    focus_handle: FocusHandle,
 825}
 826
 827struct SettingsPage {
 828    title: &'static str,
 829    items: Box<[SettingsPageItem]>,
 830}
 831
 832#[derive(PartialEq)]
 833enum SettingsPageItem {
 834    SectionHeader(&'static str),
 835    SettingItem(SettingItem),
 836    SubPageLink(SubPageLink),
 837    DynamicItem(DynamicItem),
 838    ActionLink(ActionLink),
 839}
 840
 841impl std::fmt::Debug for SettingsPageItem {
 842    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 843        match self {
 844            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 845            SettingsPageItem::SettingItem(setting_item) => {
 846                write!(f, "SettingItem({})", setting_item.title)
 847            }
 848            SettingsPageItem::SubPageLink(sub_page_link) => {
 849                write!(f, "SubPageLink({})", sub_page_link.title)
 850            }
 851            SettingsPageItem::DynamicItem(dynamic_item) => {
 852                write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
 853            }
 854            SettingsPageItem::ActionLink(action_link) => {
 855                write!(f, "ActionLink({})", action_link.title)
 856            }
 857        }
 858    }
 859}
 860
 861impl SettingsPageItem {
 862    fn header_text(&self) -> Option<&'static str> {
 863        match self {
 864            SettingsPageItem::SectionHeader(header) => Some(header),
 865            _ => None,
 866        }
 867    }
 868
 869    fn render(
 870        &self,
 871        settings_window: &SettingsWindow,
 872        item_index: usize,
 873        bottom_border: bool,
 874        extra_bottom_padding: bool,
 875        window: &mut Window,
 876        cx: &mut Context<SettingsWindow>,
 877    ) -> AnyElement {
 878        let file = settings_window.current_file.clone();
 879
 880        let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
 881            let element = element.pt_4();
 882            if extra_bottom_padding {
 883                element.pb_10()
 884            } else {
 885                element.pb_4()
 886            }
 887        };
 888
 889        let mut render_setting_item_inner =
 890            |setting_item: &SettingItem,
 891             padding: bool,
 892             sub_field: bool,
 893             cx: &mut Context<SettingsWindow>| {
 894                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 895                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 896
 897                let renderers = renderer.renderers.borrow();
 898
 899                let field_renderer =
 900                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 901                let field_renderer_or_warning =
 902                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 903                        if cfg!(debug_assertions) && !found {
 904                            Err("NO DEFAULT")
 905                        } else {
 906                            Ok(renderer)
 907                        }
 908                    });
 909
 910                let field = match field_renderer_or_warning {
 911                    Ok(field_renderer) => window.with_id(item_index, |window| {
 912                        field_renderer(
 913                            settings_window,
 914                            setting_item,
 915                            file.clone(),
 916                            setting_item.metadata.as_deref(),
 917                            sub_field,
 918                            window,
 919                            cx,
 920                        )
 921                    }),
 922                    Err(warning) => render_settings_item(
 923                        settings_window,
 924                        setting_item,
 925                        file.clone(),
 926                        Button::new("error-warning", warning)
 927                            .style(ButtonStyle::Outlined)
 928                            .size(ButtonSize::Medium)
 929                            .start_icon(Icon::new(IconName::Debug).color(Color::Error))
 930                            .tab_index(0_isize)
 931                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 932                            .into_any_element(),
 933                        sub_field,
 934                        cx,
 935                    ),
 936                };
 937
 938                let field = if padding {
 939                    field.map(apply_padding)
 940                } else {
 941                    field
 942                };
 943
 944                (field, field_renderer_or_warning.is_ok())
 945            };
 946
 947        match self {
 948            SettingsPageItem::SectionHeader(header) => {
 949                SettingsSectionHeader::new(SharedString::new_static(header)).into_any_element()
 950            }
 951            SettingsPageItem::SettingItem(setting_item) => {
 952                let (field_with_padding, _) =
 953                    render_setting_item_inner(setting_item, true, false, cx);
 954
 955                v_flex()
 956                    .group("setting-item")
 957                    .px_8()
 958                    .child(field_with_padding)
 959                    .when(bottom_border, |this| this.child(Divider::horizontal()))
 960                    .into_any_element()
 961            }
 962            SettingsPageItem::SubPageLink(sub_page_link) => v_flex()
 963                .group("setting-item")
 964                .px_8()
 965                .child(
 966                    h_flex()
 967                        .id(sub_page_link.title.clone())
 968                        .w_full()
 969                        .min_w_0()
 970                        .justify_between()
 971                        .map(apply_padding)
 972                        .child(
 973                            v_flex()
 974                                .relative()
 975                                .w_full()
 976                                .max_w_1_2()
 977                                .child(Label::new(sub_page_link.title.clone()))
 978                                .when_some(
 979                                    sub_page_link.description.as_ref(),
 980                                    |this, description| {
 981                                        this.child(
 982                                            Label::new(description.clone())
 983                                                .size(LabelSize::Small)
 984                                                .color(Color::Muted),
 985                                        )
 986                                    },
 987                                ),
 988                        )
 989                        .child(
 990                            Button::new(
 991                                ("sub-page".into(), sub_page_link.title.clone()),
 992                                "Configure",
 993                            )
 994                            .tab_index(0_isize)
 995                            .end_icon(
 996                                Icon::new(IconName::ChevronRight)
 997                                    .size(IconSize::Small)
 998                                    .color(Color::Muted),
 999                            )
1000                            .style(ButtonStyle::OutlinedGhost)
1001                            .size(ButtonSize::Medium)
1002                            .on_click({
1003                                let sub_page_link = sub_page_link.clone();
1004                                cx.listener(move |this, _, window, cx| {
1005                                    let header_text = this
1006                                        .sub_page_stack
1007                                        .last()
1008                                        .map(|sub_page| sub_page.link.title.clone())
1009                                        .or_else(|| {
1010                                            this.current_page()
1011                                                .items
1012                                                .iter()
1013                                                .take(item_index)
1014                                                .rev()
1015                                                .find_map(|item| {
1016                                                    item.header_text().map(SharedString::new_static)
1017                                                })
1018                                        });
1019
1020                                    let Some(header) = header_text else {
1021                                        unreachable!(
1022                                            "All items always have a section header above them"
1023                                        )
1024                                    };
1025
1026                                    this.push_sub_page(sub_page_link.clone(), header, window, cx)
1027                                })
1028                            }),
1029                        )
1030                        .child(render_settings_item_link(
1031                            sub_page_link.title.clone(),
1032                            sub_page_link.json_path,
1033                            false,
1034                            cx,
1035                        )),
1036                )
1037                .when(bottom_border, |this| this.child(Divider::horizontal()))
1038                .into_any_element(),
1039            SettingsPageItem::DynamicItem(DynamicItem {
1040                discriminant: discriminant_setting_item,
1041                pick_discriminant,
1042                fields,
1043            }) => {
1044                let file = file.to_settings();
1045                let discriminant = SettingsStore::global(cx)
1046                    .get_value_from_file(file, *pick_discriminant)
1047                    .1;
1048
1049                let (discriminant_element, rendered_ok) =
1050                    render_setting_item_inner(discriminant_setting_item, true, false, cx);
1051
1052                let has_sub_fields =
1053                    rendered_ok && discriminant.is_some_and(|d| !fields[d].is_empty());
1054
1055                let mut content = v_flex()
1056                    .id("dynamic-item")
1057                    .child(
1058                        div()
1059                            .group("setting-item")
1060                            .px_8()
1061                            .child(discriminant_element.when(has_sub_fields, |this| this.pb_4())),
1062                    )
1063                    .when(!has_sub_fields && bottom_border, |this| {
1064                        this.child(h_flex().px_8().child(Divider::horizontal()))
1065                    });
1066
1067                if rendered_ok {
1068                    let discriminant =
1069                        discriminant.expect("This should be Some if rendered_ok is true");
1070                    let sub_fields = &fields[discriminant];
1071                    let sub_field_count = sub_fields.len();
1072
1073                    for (index, field) in sub_fields.iter().enumerate() {
1074                        let is_last_sub_field = index == sub_field_count - 1;
1075                        let (raw_field, _) = render_setting_item_inner(field, false, true, cx);
1076
1077                        content = content.child(
1078                            raw_field
1079                                .group("setting-sub-item")
1080                                .mx_8()
1081                                .p_4()
1082                                .border_t_1()
1083                                .when(is_last_sub_field, |this| this.border_b_1())
1084                                .when(is_last_sub_field && extra_bottom_padding, |this| {
1085                                    this.mb_8()
1086                                })
1087                                .border_dashed()
1088                                .border_color(cx.theme().colors().border_variant)
1089                                .bg(cx.theme().colors().element_background.opacity(0.2)),
1090                        );
1091                    }
1092                }
1093
1094                return content.into_any_element();
1095            }
1096            SettingsPageItem::ActionLink(action_link) => v_flex()
1097                .group("setting-item")
1098                .px_8()
1099                .child(
1100                    h_flex()
1101                        .id(action_link.title.clone())
1102                        .w_full()
1103                        .min_w_0()
1104                        .justify_between()
1105                        .map(apply_padding)
1106                        .child(
1107                            v_flex()
1108                                .relative()
1109                                .w_full()
1110                                .max_w_1_2()
1111                                .child(Label::new(action_link.title.clone()))
1112                                .when_some(
1113                                    action_link.description.as_ref(),
1114                                    |this, description| {
1115                                        this.child(
1116                                            Label::new(description.clone())
1117                                                .size(LabelSize::Small)
1118                                                .color(Color::Muted),
1119                                        )
1120                                    },
1121                                ),
1122                        )
1123                        .child(
1124                            Button::new(
1125                                ("action-link".into(), action_link.title.clone()),
1126                                action_link.button_text.clone(),
1127                            )
1128                            .tab_index(0_isize)
1129                            .end_icon(
1130                                Icon::new(IconName::ArrowUpRight)
1131                                    .size(IconSize::Small)
1132                                    .color(Color::Muted),
1133                            )
1134                            .style(ButtonStyle::OutlinedGhost)
1135                            .size(ButtonSize::Medium)
1136                            .on_click({
1137                                let on_click = action_link.on_click.clone();
1138                                cx.listener(move |this, _, window, cx| {
1139                                    on_click(this, window, cx);
1140                                })
1141                            }),
1142                        ),
1143                )
1144                .when(bottom_border, |this| this.child(Divider::horizontal()))
1145                .into_any_element(),
1146        }
1147    }
1148}
1149
1150fn render_settings_item(
1151    settings_window: &SettingsWindow,
1152    setting_item: &SettingItem,
1153    file: SettingsUiFile,
1154    control: AnyElement,
1155    sub_field: bool,
1156    cx: &mut Context<'_, SettingsWindow>,
1157) -> Stateful<Div> {
1158    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
1159    let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
1160
1161    h_flex()
1162        .id(setting_item.title)
1163        .min_w_0()
1164        .justify_between()
1165        .child(
1166            v_flex()
1167                .relative()
1168                .w_full()
1169                .max_w_2_3()
1170                .min_w_0()
1171                .child(
1172                    h_flex()
1173                        .w_full()
1174                        .gap_1()
1175                        .child(Label::new(SharedString::new_static(setting_item.title)))
1176                        .when_some(
1177                            if sub_field {
1178                                None
1179                            } else {
1180                                setting_item
1181                                    .field
1182                                    .reset_to_default_fn(&file, &found_in_file, cx)
1183                            },
1184                            |this, reset_to_default| {
1185                                this.child(
1186                                    IconButton::new("reset-to-default-btn", IconName::Undo)
1187                                        .icon_color(Color::Muted)
1188                                        .icon_size(IconSize::Small)
1189                                        .tooltip(Tooltip::text("Reset to Default"))
1190                                        .on_click({
1191                                            move |_, window, cx| {
1192                                                reset_to_default(window, cx);
1193                                            }
1194                                        }),
1195                                )
1196                            },
1197                        )
1198                        .when_some(
1199                            file_set_in.filter(|file_set_in| file_set_in != &file),
1200                            |this, file_set_in| {
1201                                this.child(
1202                                    Label::new(format!(
1203                                        "—  Modified in {}",
1204                                        settings_window
1205                                            .display_name(&file_set_in)
1206                                            .expect("File name should exist")
1207                                    ))
1208                                    .color(Color::Muted)
1209                                    .size(LabelSize::Small),
1210                                )
1211                            },
1212                        ),
1213                )
1214                .child(
1215                    Label::new(SharedString::new_static(setting_item.description))
1216                        .size(LabelSize::Small)
1217                        .color(Color::Muted)
1218                        .render_code_spans(),
1219                ),
1220        )
1221        .child(control)
1222        .when(settings_window.sub_page_stack.is_empty(), |this| {
1223            this.child(render_settings_item_link(
1224                setting_item.description,
1225                setting_item.field.json_path(),
1226                sub_field,
1227                cx,
1228            ))
1229        })
1230}
1231
1232fn render_settings_item_link(
1233    id: impl Into<ElementId>,
1234    json_path: Option<&'static str>,
1235    sub_field: bool,
1236    cx: &mut Context<'_, SettingsWindow>,
1237) -> impl IntoElement {
1238    let clipboard_has_link = cx
1239        .read_from_clipboard()
1240        .and_then(|entry| entry.text())
1241        .map_or(false, |maybe_url| {
1242            json_path.is_some() && maybe_url.strip_prefix("zed://settings/") == json_path
1243        });
1244
1245    let (link_icon, link_icon_color) = if clipboard_has_link {
1246        (IconName::Check, Color::Success)
1247    } else {
1248        (IconName::Link, Color::Muted)
1249    };
1250
1251    div()
1252        .absolute()
1253        .top(rems_from_px(18.))
1254        .map(|this| {
1255            if sub_field {
1256                this.visible_on_hover("setting-sub-item")
1257                    .left(rems_from_px(-8.5))
1258            } else {
1259                this.visible_on_hover("setting-item")
1260                    .left(rems_from_px(-22.))
1261            }
1262        })
1263        .child(
1264            IconButton::new((id.into(), "copy-link-btn"), link_icon)
1265                .icon_color(link_icon_color)
1266                .icon_size(IconSize::Small)
1267                .shape(IconButtonShape::Square)
1268                .tooltip(Tooltip::text("Copy Link"))
1269                .when_some(json_path, |this, path| {
1270                    this.on_click(cx.listener(move |_, _, _, cx| {
1271                        let link = format!("zed://settings/{}", path);
1272                        cx.write_to_clipboard(ClipboardItem::new_string(link));
1273                        cx.notify();
1274                    }))
1275                }),
1276        )
1277}
1278
1279struct SettingItem {
1280    title: &'static str,
1281    description: &'static str,
1282    field: Box<dyn AnySettingField>,
1283    metadata: Option<Box<SettingsFieldMetadata>>,
1284    files: FileMask,
1285}
1286
1287struct DynamicItem {
1288    discriminant: SettingItem,
1289    pick_discriminant: fn(&SettingsContent) -> Option<usize>,
1290    fields: Vec<Vec<SettingItem>>,
1291}
1292
1293impl PartialEq for DynamicItem {
1294    fn eq(&self, other: &Self) -> bool {
1295        self.discriminant == other.discriminant && self.fields == other.fields
1296    }
1297}
1298
1299#[derive(PartialEq, Eq, Clone, Copy)]
1300struct FileMask(u8);
1301
1302impl std::fmt::Debug for FileMask {
1303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1304        write!(f, "FileMask(")?;
1305        let mut items = vec![];
1306
1307        if self.contains(USER) {
1308            items.push("USER");
1309        }
1310        if self.contains(PROJECT) {
1311            items.push("LOCAL");
1312        }
1313        if self.contains(SERVER) {
1314            items.push("SERVER");
1315        }
1316
1317        write!(f, "{})", items.join(" | "))
1318    }
1319}
1320
1321const USER: FileMask = FileMask(1 << 0);
1322const PROJECT: FileMask = FileMask(1 << 2);
1323const SERVER: FileMask = FileMask(1 << 3);
1324
1325impl std::ops::BitAnd for FileMask {
1326    type Output = Self;
1327
1328    fn bitand(self, other: Self) -> Self {
1329        Self(self.0 & other.0)
1330    }
1331}
1332
1333impl std::ops::BitOr for FileMask {
1334    type Output = Self;
1335
1336    fn bitor(self, other: Self) -> Self {
1337        Self(self.0 | other.0)
1338    }
1339}
1340
1341impl FileMask {
1342    fn contains(&self, other: FileMask) -> bool {
1343        self.0 & other.0 != 0
1344    }
1345}
1346
1347impl PartialEq for SettingItem {
1348    fn eq(&self, other: &Self) -> bool {
1349        self.title == other.title
1350            && self.description == other.description
1351            && (match (&self.metadata, &other.metadata) {
1352                (None, None) => true,
1353                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1354                _ => false,
1355            })
1356    }
1357}
1358
1359#[derive(Clone, PartialEq, Default)]
1360enum SubPageType {
1361    Language,
1362    #[default]
1363    Other,
1364}
1365
1366#[derive(Clone)]
1367struct SubPageLink {
1368    title: SharedString,
1369    r#type: SubPageType,
1370    description: Option<SharedString>,
1371    /// See [`SettingField.json_path`]
1372    json_path: Option<&'static str>,
1373    /// Whether or not the settings in this sub page are configurable in settings.json
1374    /// Removes the "Edit in settings.json" button from the page.
1375    in_json: bool,
1376    files: FileMask,
1377    render:
1378        fn(&SettingsWindow, &ScrollHandle, &mut Window, &mut Context<SettingsWindow>) -> AnyElement,
1379}
1380
1381impl PartialEq for SubPageLink {
1382    fn eq(&self, other: &Self) -> bool {
1383        self.title == other.title
1384    }
1385}
1386
1387#[derive(Clone)]
1388struct ActionLink {
1389    title: SharedString,
1390    description: Option<SharedString>,
1391    button_text: SharedString,
1392    on_click: Arc<dyn Fn(&mut SettingsWindow, &mut Window, &mut App) + Send + Sync>,
1393    files: FileMask,
1394}
1395
1396impl PartialEq for ActionLink {
1397    fn eq(&self, other: &Self) -> bool {
1398        self.title == other.title
1399    }
1400}
1401
1402fn all_language_names(cx: &App) -> Vec<SharedString> {
1403    let state = workspace::AppState::global(cx);
1404    state
1405        .languages
1406        .language_names()
1407        .into_iter()
1408        .filter(|name| name.as_ref() != "Zed Keybind Context")
1409        .map(Into::into)
1410        .collect()
1411}
1412
1413#[allow(unused)]
1414#[derive(Clone, PartialEq, Debug)]
1415enum SettingsUiFile {
1416    User,                                // Uses all settings.
1417    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1418    Server(&'static str),                // Uses a special name, and the user settings
1419}
1420
1421impl SettingsUiFile {
1422    fn setting_type(&self) -> &'static str {
1423        match self {
1424            SettingsUiFile::User => "User",
1425            SettingsUiFile::Project(_) => "Project",
1426            SettingsUiFile::Server(_) => "Server",
1427        }
1428    }
1429
1430    fn is_server(&self) -> bool {
1431        matches!(self, SettingsUiFile::Server(_))
1432    }
1433
1434    fn worktree_id(&self) -> Option<WorktreeId> {
1435        match self {
1436            SettingsUiFile::User => None,
1437            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1438            SettingsUiFile::Server(_) => None,
1439        }
1440    }
1441
1442    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1443        Some(match file {
1444            settings::SettingsFile::User => SettingsUiFile::User,
1445            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1446            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1447            settings::SettingsFile::Default => return None,
1448            settings::SettingsFile::Global => return None,
1449        })
1450    }
1451
1452    fn to_settings(&self) -> settings::SettingsFile {
1453        match self {
1454            SettingsUiFile::User => settings::SettingsFile::User,
1455            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1456            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1457        }
1458    }
1459
1460    fn mask(&self) -> FileMask {
1461        match self {
1462            SettingsUiFile::User => USER,
1463            SettingsUiFile::Project(_) => PROJECT,
1464            SettingsUiFile::Server(_) => SERVER,
1465        }
1466    }
1467}
1468
1469impl SettingsWindow {
1470    fn new(
1471        original_window: Option<WindowHandle<MultiWorkspace>>,
1472        window: &mut Window,
1473        cx: &mut Context<Self>,
1474    ) -> Self {
1475        let font_family_cache = theme::FontFamilyCache::global(cx);
1476
1477        cx.spawn(async move |this, cx| {
1478            font_family_cache.prefetch(cx).await;
1479            this.update(cx, |_, cx| {
1480                cx.notify();
1481            })
1482        })
1483        .detach();
1484
1485        let current_file = SettingsUiFile::User;
1486        let search_bar = cx.new(|cx| {
1487            let mut editor = Editor::single_line(window, cx);
1488            editor.set_placeholder_text("Search settings…", window, cx);
1489            editor
1490        });
1491        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1492            let EditorEvent::Edited { transaction_id: _ } = event else {
1493                return;
1494            };
1495
1496            if this.opening_link {
1497                this.opening_link = false;
1498                return;
1499            }
1500            this.update_matches(cx);
1501        })
1502        .detach();
1503
1504        let mut ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1505        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1506            this.fetch_files(window, cx);
1507
1508            // Whenever settings are changed, it's possible that the changed
1509            // settings affects the rendering of the `SettingsWindow`, like is
1510            // the case with `ui_font_size`. When that happens, we need to
1511            // instruct the `ListState` to re-measure the list items, as the
1512            // list item heights may have changed depending on the new font
1513            // size.
1514            let new_ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1515            if new_ui_font_size != ui_font_size {
1516                this.list_state.remeasure();
1517                ui_font_size = new_ui_font_size;
1518            }
1519
1520            cx.notify();
1521        })
1522        .detach();
1523
1524        cx.on_window_closed(|cx, _window_id| {
1525            if let Some(existing_window) = cx
1526                .windows()
1527                .into_iter()
1528                .find_map(|window| window.downcast::<SettingsWindow>())
1529                && cx.windows().len() == 1
1530            {
1531                cx.update_window(*existing_window, |_, window, _| {
1532                    window.remove_window();
1533                })
1534                .ok();
1535
1536                telemetry::event!("Settings Closed")
1537            }
1538        })
1539        .detach();
1540
1541        let app_state = AppState::global(cx);
1542        let workspaces: Vec<Entity<Workspace>> = app_state
1543            .workspace_store
1544            .read(cx)
1545            .workspaces()
1546            .filter_map(|weak| weak.upgrade())
1547            .collect();
1548
1549        for workspace in workspaces {
1550            let project = workspace.read(cx).project().clone();
1551            cx.observe_release_in(&project, window, |this, _, window, cx| {
1552                this.fetch_files(window, cx)
1553            })
1554            .detach();
1555            cx.subscribe_in(&project, window, Self::handle_project_event)
1556                .detach();
1557            cx.observe_release_in(&workspace, window, |this, _, window, cx| {
1558                this.fetch_files(window, cx)
1559            })
1560            .detach();
1561        }
1562
1563        let this_weak = cx.weak_entity();
1564        cx.observe_new::<Project>({
1565            let this_weak = this_weak.clone();
1566
1567            move |_, window, cx| {
1568                let project = cx.entity();
1569                let Some(window) = window else {
1570                    return;
1571                };
1572
1573                this_weak
1574                    .update(cx, |_, cx| {
1575                        cx.defer_in(window, |settings_window, window, cx| {
1576                            settings_window.fetch_files(window, cx)
1577                        });
1578                        cx.observe_release_in(&project, window, |_, _, window, cx| {
1579                            cx.defer_in(window, |this, window, cx| this.fetch_files(window, cx));
1580                        })
1581                        .detach();
1582
1583                        cx.subscribe_in(&project, window, Self::handle_project_event)
1584                            .detach();
1585                    })
1586                    .ok();
1587            }
1588        })
1589        .detach();
1590
1591        let handle = window.window_handle();
1592        cx.observe_new::<Workspace>(move |workspace, _, cx| {
1593            let project = workspace.project().clone();
1594            let this_weak = this_weak.clone();
1595
1596            // We defer on the settings window (via `handle`) rather than using
1597            // the workspace's window from observe_new. When window.defer() runs
1598            // its callback, it calls handle.update() which temporarily removes
1599            // that window from cx.windows. If we deferred on the workspace's
1600            // window, then when fetch_files() tries to read ALL workspaces from
1601            // the store (including the newly created one), it would fail with
1602            // "window not found" because that workspace's window would be
1603            // temporarily removed from cx.windows for the duration of our callback.
1604            handle
1605                .update(cx, move |_, window, cx| {
1606                    window.defer(cx, move |window, cx| {
1607                        this_weak
1608                            .update(cx, |this, cx| {
1609                                this.fetch_files(window, cx);
1610                                cx.observe_release_in(&project, window, |this, _, window, cx| {
1611                                    this.fetch_files(window, cx)
1612                                })
1613                                .detach();
1614                            })
1615                            .ok();
1616                    });
1617                })
1618                .ok();
1619        })
1620        .detach();
1621
1622        let title_bar = if !cfg!(target_os = "macos") {
1623            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1624        } else {
1625            None
1626        };
1627
1628        let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1629        list_state.set_scroll_handler(|_, _, _| {});
1630
1631        let mut this = Self {
1632            title_bar,
1633            original_window,
1634
1635            worktree_root_dirs: HashMap::default(),
1636            files: vec![],
1637
1638            current_file: current_file,
1639            project_setting_file_buffers: HashMap::default(),
1640            pages: vec![],
1641            sub_page_stack: vec![],
1642            opening_link: false,
1643            navbar_entries: vec![],
1644            navbar_entry: 0,
1645            navbar_scroll_handle: UniformListScrollHandle::default(),
1646            search_bar,
1647            search_task: None,
1648            filter_table: vec![],
1649            has_query: false,
1650            content_handles: vec![],
1651            focus_handle: cx.focus_handle(),
1652            navbar_focus_handle: NonFocusableHandle::new(
1653                NAVBAR_CONTAINER_TAB_INDEX,
1654                false,
1655                window,
1656                cx,
1657            ),
1658            navbar_focus_subscriptions: vec![],
1659            content_focus_handle: NonFocusableHandle::new(
1660                CONTENT_CONTAINER_TAB_INDEX,
1661                false,
1662                window,
1663                cx,
1664            ),
1665            files_focus_handle: cx
1666                .focus_handle()
1667                .tab_index(HEADER_CONTAINER_TAB_INDEX)
1668                .tab_stop(false),
1669            search_index: None,
1670            shown_errors: HashSet::default(),
1671            regex_validation_error: None,
1672            list_state,
1673        };
1674
1675        this.fetch_files(window, cx);
1676        this.build_ui(window, cx);
1677        this.build_search_index();
1678
1679        this.search_bar.update(cx, |editor, cx| {
1680            editor.focus_handle(cx).focus(window, cx);
1681        });
1682
1683        this
1684    }
1685
1686    fn handle_project_event(
1687        &mut self,
1688        _: &Entity<Project>,
1689        event: &project::Event,
1690        window: &mut Window,
1691        cx: &mut Context<SettingsWindow>,
1692    ) {
1693        match event {
1694            project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1695                cx.defer_in(window, |this, window, cx| {
1696                    this.fetch_files(window, cx);
1697                });
1698            }
1699            _ => {}
1700        }
1701    }
1702
1703    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1704        // We can only toggle root entries
1705        if !self.navbar_entries[nav_entry_index].is_root {
1706            return;
1707        }
1708
1709        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1710        *expanded = !*expanded;
1711        self.navbar_entry = nav_entry_index;
1712        self.reset_list_state();
1713    }
1714
1715    fn build_navbar(&mut self, cx: &App) {
1716        let mut navbar_entries = Vec::new();
1717
1718        for (page_index, page) in self.pages.iter().enumerate() {
1719            navbar_entries.push(NavBarEntry {
1720                title: page.title,
1721                is_root: true,
1722                expanded: false,
1723                page_index,
1724                item_index: None,
1725                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1726            });
1727
1728            for (item_index, item) in page.items.iter().enumerate() {
1729                let SettingsPageItem::SectionHeader(title) = item else {
1730                    continue;
1731                };
1732                navbar_entries.push(NavBarEntry {
1733                    title,
1734                    is_root: false,
1735                    expanded: false,
1736                    page_index,
1737                    item_index: Some(item_index),
1738                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1739                });
1740            }
1741        }
1742
1743        self.navbar_entries = navbar_entries;
1744    }
1745
1746    fn setup_navbar_focus_subscriptions(
1747        &mut self,
1748        window: &mut Window,
1749        cx: &mut Context<SettingsWindow>,
1750    ) {
1751        let mut focus_subscriptions = Vec::new();
1752
1753        for entry_index in 0..self.navbar_entries.len() {
1754            let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1755
1756            let subscription = cx.on_focus(
1757                &focus_handle,
1758                window,
1759                move |this: &mut SettingsWindow,
1760                      window: &mut Window,
1761                      cx: &mut Context<SettingsWindow>| {
1762                    this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1763                },
1764            );
1765            focus_subscriptions.push(subscription);
1766        }
1767        self.navbar_focus_subscriptions = focus_subscriptions;
1768    }
1769
1770    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1771        let mut index = 0;
1772        let entries = &self.navbar_entries;
1773        let search_matches = &self.filter_table;
1774        let has_query = self.has_query;
1775        std::iter::from_fn(move || {
1776            while index < entries.len() {
1777                let entry = &entries[index];
1778                let included_in_search = if let Some(item_index) = entry.item_index {
1779                    search_matches[entry.page_index][item_index]
1780                } else {
1781                    search_matches[entry.page_index].iter().any(|b| *b)
1782                        || search_matches[entry.page_index].is_empty()
1783                };
1784                if included_in_search {
1785                    break;
1786                }
1787                index += 1;
1788            }
1789            if index >= self.navbar_entries.len() {
1790                return None;
1791            }
1792            let entry = &entries[index];
1793            let entry_index = index;
1794
1795            index += 1;
1796            if entry.is_root && !entry.expanded && !has_query {
1797                while index < entries.len() {
1798                    if entries[index].is_root {
1799                        break;
1800                    }
1801                    index += 1;
1802                }
1803            }
1804
1805            return Some((entry_index, entry));
1806        })
1807    }
1808
1809    fn filter_matches_to_file(&mut self) {
1810        let current_file = self.current_file.mask();
1811        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1812            let mut header_index = 0;
1813            let mut any_found_since_last_header = true;
1814
1815            for (index, item) in page.items.iter().enumerate() {
1816                match item {
1817                    SettingsPageItem::SectionHeader(_) => {
1818                        if !any_found_since_last_header {
1819                            page_filter[header_index] = false;
1820                        }
1821                        header_index = index;
1822                        any_found_since_last_header = false;
1823                    }
1824                    SettingsPageItem::SettingItem(SettingItem { files, .. })
1825                    | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1826                    | SettingsPageItem::DynamicItem(DynamicItem {
1827                        discriminant: SettingItem { files, .. },
1828                        ..
1829                    }) => {
1830                        if !files.contains(current_file) {
1831                            page_filter[index] = false;
1832                        } else {
1833                            any_found_since_last_header = true;
1834                        }
1835                    }
1836                    SettingsPageItem::ActionLink(ActionLink { files, .. }) => {
1837                        if !files.contains(current_file) {
1838                            page_filter[index] = false;
1839                        } else {
1840                            any_found_since_last_header = true;
1841                        }
1842                    }
1843                }
1844            }
1845            if let Some(last_header) = page_filter.get_mut(header_index)
1846                && !any_found_since_last_header
1847            {
1848                *last_header = false;
1849            }
1850        }
1851    }
1852
1853    fn filter_by_json_path(&self, query: &str) -> Vec<usize> {
1854        let Some(path) = query.strip_prefix('#') else {
1855            return vec![];
1856        };
1857        let Some(search_index) = self.search_index.as_ref() else {
1858            return vec![];
1859        };
1860        let mut indices = vec![];
1861        for (index, SearchKeyLUTEntry { json_path, .. }) in search_index.key_lut.iter().enumerate()
1862        {
1863            let Some(json_path) = json_path else {
1864                continue;
1865            };
1866
1867            if let Some(post) = json_path.strip_prefix(path)
1868                && (post.is_empty() || post.starts_with('.'))
1869            {
1870                indices.push(index);
1871            }
1872        }
1873        indices
1874    }
1875
1876    fn apply_match_indices(&mut self, match_indices: impl Iterator<Item = usize>) {
1877        let Some(search_index) = self.search_index.as_ref() else {
1878            return;
1879        };
1880
1881        for page in &mut self.filter_table {
1882            page.fill(false);
1883        }
1884
1885        for match_index in match_indices {
1886            let SearchKeyLUTEntry {
1887                page_index,
1888                header_index,
1889                item_index,
1890                ..
1891            } = search_index.key_lut[match_index];
1892            let page = &mut self.filter_table[page_index];
1893            page[header_index] = true;
1894            page[item_index] = true;
1895        }
1896        self.has_query = true;
1897        self.filter_matches_to_file();
1898        self.open_first_nav_page();
1899        self.reset_list_state();
1900    }
1901
1902    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1903        self.search_task.take();
1904        let query = self.search_bar.read(cx).text(cx);
1905        if query.is_empty() || self.search_index.is_none() {
1906            for page in &mut self.filter_table {
1907                page.fill(true);
1908            }
1909            self.has_query = false;
1910            self.filter_matches_to_file();
1911            self.reset_list_state();
1912            cx.notify();
1913            return;
1914        }
1915
1916        let is_json_link_query = query.starts_with("#");
1917        if is_json_link_query {
1918            let indices = self.filter_by_json_path(&query);
1919            if !indices.is_empty() {
1920                self.apply_match_indices(indices.into_iter());
1921                cx.notify();
1922                return;
1923            }
1924        }
1925
1926        let search_index = self.search_index.as_ref().unwrap().clone();
1927
1928        self.search_task = Some(cx.spawn(async move |this, cx| {
1929            let exact_match_task = cx.background_spawn({
1930                let search_index = search_index.clone();
1931                let query = query.clone();
1932                async move {
1933                    let query_lower = query.to_lowercase();
1934                    let query_words: Vec<&str> = query_lower.split_whitespace().collect();
1935                    search_index
1936                        .documents
1937                        .iter()
1938                        .filter(|doc| {
1939                            query_words.iter().any(|query_word| {
1940                                doc.words
1941                                    .iter()
1942                                    .any(|doc_word| doc_word.starts_with(query_word))
1943                            })
1944                        })
1945                        .map(|doc| doc.id)
1946                        .collect::<Vec<usize>>()
1947                }
1948            });
1949            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1950            let fuzzy_search_task = fuzzy::match_strings(
1951                search_index.fuzzy_match_candidates.as_slice(),
1952                &query,
1953                false,
1954                true,
1955                search_index.fuzzy_match_candidates.len(),
1956                &cancel_flag,
1957                cx.background_executor().clone(),
1958            );
1959
1960            let fuzzy_matches = fuzzy_search_task.await;
1961            let exact_matches = exact_match_task.await;
1962
1963            _ = this
1964                .update(cx, |this, cx| {
1965                    let exact_indices = exact_matches.into_iter();
1966                    let fuzzy_indices = fuzzy_matches
1967                        .into_iter()
1968                        .take_while(|fuzzy_match| fuzzy_match.score >= 0.5)
1969                        .map(|fuzzy_match| fuzzy_match.candidate_id);
1970                    let merged_indices = exact_indices.chain(fuzzy_indices);
1971
1972                    this.apply_match_indices(merged_indices);
1973                    cx.notify();
1974                })
1975                .ok();
1976
1977            cx.background_executor().timer(Duration::from_secs(1)).await;
1978            telemetry::event!("Settings Searched", query = query)
1979        }));
1980    }
1981
1982    fn build_filter_table(&mut self) {
1983        self.filter_table = self
1984            .pages
1985            .iter()
1986            .map(|page| vec![true; page.items.len()])
1987            .collect::<Vec<_>>();
1988    }
1989
1990    fn build_search_index(&mut self) {
1991        fn split_into_words(parts: &[&str]) -> Vec<String> {
1992            parts
1993                .iter()
1994                .flat_map(|s| {
1995                    s.split(|c: char| !c.is_alphanumeric())
1996                        .filter(|w| !w.is_empty())
1997                        .map(|w| w.to_lowercase())
1998                })
1999                .collect()
2000        }
2001
2002        let mut key_lut: Vec<SearchKeyLUTEntry> = vec![];
2003        let mut documents: Vec<SearchDocument> = Vec::default();
2004        let mut fuzzy_match_candidates = Vec::default();
2005
2006        fn push_candidates(
2007            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
2008            key_index: usize,
2009            input: &str,
2010        ) {
2011            for word in input.split_ascii_whitespace() {
2012                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
2013            }
2014        }
2015
2016        // PERF: We are currently searching all items even in project files
2017        // where many settings are filtered out, using the logic in filter_matches_to_file
2018        // we could only search relevant items based on the current file
2019        for (page_index, page) in self.pages.iter().enumerate() {
2020            let mut header_index = 0;
2021            let mut header_str = "";
2022            for (item_index, item) in page.items.iter().enumerate() {
2023                let key_index = key_lut.len();
2024                let mut json_path = None;
2025                match item {
2026                    SettingsPageItem::DynamicItem(DynamicItem {
2027                        discriminant: item, ..
2028                    })
2029                    | SettingsPageItem::SettingItem(item) => {
2030                        json_path = item
2031                            .field
2032                            .json_path()
2033                            .map(|path| path.trim_end_matches('$'));
2034                        documents.push(SearchDocument {
2035                            id: key_index,
2036                            words: split_into_words(&[
2037                                page.title,
2038                                header_str,
2039                                item.title,
2040                                item.description,
2041                            ]),
2042                        });
2043                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
2044                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
2045                    }
2046                    SettingsPageItem::SectionHeader(header) => {
2047                        documents.push(SearchDocument {
2048                            id: key_index,
2049                            words: split_into_words(&[header]),
2050                        });
2051                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
2052                        header_index = item_index;
2053                        header_str = *header;
2054                    }
2055                    SettingsPageItem::SubPageLink(sub_page_link) => {
2056                        json_path = sub_page_link.json_path;
2057                        documents.push(SearchDocument {
2058                            id: key_index,
2059                            words: split_into_words(&[
2060                                page.title,
2061                                header_str,
2062                                sub_page_link.title.as_ref(),
2063                            ]),
2064                        });
2065                        push_candidates(
2066                            &mut fuzzy_match_candidates,
2067                            key_index,
2068                            sub_page_link.title.as_ref(),
2069                        );
2070                    }
2071                    SettingsPageItem::ActionLink(action_link) => {
2072                        documents.push(SearchDocument {
2073                            id: key_index,
2074                            words: split_into_words(&[
2075                                page.title,
2076                                header_str,
2077                                action_link.title.as_ref(),
2078                            ]),
2079                        });
2080                        push_candidates(
2081                            &mut fuzzy_match_candidates,
2082                            key_index,
2083                            action_link.title.as_ref(),
2084                        );
2085                    }
2086                }
2087                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
2088                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
2089
2090                key_lut.push(SearchKeyLUTEntry {
2091                    page_index,
2092                    header_index,
2093                    item_index,
2094                    json_path,
2095                });
2096            }
2097        }
2098        self.search_index = Some(Arc::new(SearchIndex {
2099            documents,
2100            key_lut,
2101            fuzzy_match_candidates,
2102        }));
2103    }
2104
2105    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2106        self.content_handles = self
2107            .pages
2108            .iter()
2109            .map(|page| {
2110                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
2111                    .take(page.items.len())
2112                    .collect()
2113            })
2114            .collect::<Vec<_>>();
2115    }
2116
2117    fn reset_list_state(&mut self) {
2118        let mut visible_items_count = self.visible_page_items().count();
2119
2120        if visible_items_count > 0 {
2121            // show page title if page is non empty
2122            visible_items_count += 1;
2123        }
2124
2125        self.list_state.reset(visible_items_count);
2126    }
2127
2128    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2129        if self.pages.is_empty() {
2130            self.pages = page_data::settings_data(cx);
2131            self.build_navbar(cx);
2132            self.setup_navbar_focus_subscriptions(window, cx);
2133            self.build_content_handles(window, cx);
2134        }
2135        self.sub_page_stack.clear();
2136        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
2137        self.build_filter_table();
2138        self.reset_list_state();
2139        self.update_matches(cx);
2140
2141        cx.notify();
2142    }
2143
2144    #[track_caller]
2145    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2146        self.worktree_root_dirs.clear();
2147        let prev_files = self.files.clone();
2148        let settings_store = cx.global::<SettingsStore>();
2149        let mut ui_files = vec![];
2150        let mut all_files = settings_store.get_all_files();
2151        if !all_files.contains(&settings::SettingsFile::User) {
2152            all_files.push(settings::SettingsFile::User);
2153        }
2154        for file in all_files {
2155            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
2156                continue;
2157            };
2158            if settings_ui_file.is_server() {
2159                continue;
2160            }
2161
2162            if let Some(worktree_id) = settings_ui_file.worktree_id() {
2163                let directory_name = all_projects(self.original_window.as_ref(), cx)
2164                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
2165                    .map(|worktree| worktree.read(cx).root_name());
2166
2167                let Some(directory_name) = directory_name else {
2168                    log::error!(
2169                        "No directory name found for settings file at worktree ID: {}",
2170                        worktree_id
2171                    );
2172                    continue;
2173                };
2174
2175                self.worktree_root_dirs
2176                    .insert(worktree_id, directory_name.as_unix_str().to_string());
2177            }
2178
2179            let focus_handle = prev_files
2180                .iter()
2181                .find_map(|(prev_file, handle)| {
2182                    (prev_file == &settings_ui_file).then(|| handle.clone())
2183                })
2184                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
2185            ui_files.push((settings_ui_file, focus_handle));
2186        }
2187
2188        ui_files.reverse();
2189
2190        if self.original_window.is_some() {
2191            let mut missing_worktrees = Vec::new();
2192
2193            for worktree in all_projects(self.original_window.as_ref(), cx)
2194                .flat_map(|project| project.read(cx).visible_worktrees(cx))
2195                .filter(|tree| !self.worktree_root_dirs.contains_key(&tree.read(cx).id()))
2196            {
2197                let worktree = worktree.read(cx);
2198                let worktree_id = worktree.id();
2199                let Some(directory_name) = worktree.root_dir().and_then(|file| {
2200                    file.file_name()
2201                        .map(|os_string| os_string.to_string_lossy().to_string())
2202                }) else {
2203                    continue;
2204                };
2205
2206                missing_worktrees.push((worktree_id, directory_name.clone()));
2207                let path = RelPath::empty().to_owned().into_arc();
2208
2209                let settings_ui_file = SettingsUiFile::Project((worktree_id, path));
2210
2211                let focus_handle = prev_files
2212                    .iter()
2213                    .find_map(|(prev_file, handle)| {
2214                        (prev_file == &settings_ui_file).then(|| handle.clone())
2215                    })
2216                    .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
2217
2218                ui_files.push((settings_ui_file, focus_handle));
2219            }
2220
2221            self.worktree_root_dirs.extend(missing_worktrees);
2222        }
2223
2224        self.files = ui_files;
2225        let current_file_still_exists = self
2226            .files
2227            .iter()
2228            .any(|(file, _)| file == &self.current_file);
2229        if !current_file_still_exists {
2230            self.change_file(0, window, cx);
2231        }
2232    }
2233
2234    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
2235        if !self.is_nav_entry_visible(navbar_entry) {
2236            self.open_first_nav_page();
2237        }
2238
2239        let is_new_page = self.navbar_entries[self.navbar_entry].page_index
2240            != self.navbar_entries[navbar_entry].page_index;
2241        self.navbar_entry = navbar_entry;
2242
2243        // We only need to reset visible items when updating matches
2244        // and selecting a new page
2245        if is_new_page {
2246            self.reset_list_state();
2247        }
2248
2249        self.sub_page_stack.clear();
2250    }
2251
2252    fn open_first_nav_page(&mut self) {
2253        let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
2254        else {
2255            return;
2256        };
2257        self.open_navbar_entry_page(first_navbar_entry_index);
2258    }
2259
2260    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2261        if ix >= self.files.len() {
2262            self.current_file = SettingsUiFile::User;
2263            self.build_ui(window, cx);
2264            return;
2265        }
2266
2267        if self.files[ix].0 == self.current_file {
2268            return;
2269        }
2270        self.current_file = self.files[ix].0.clone();
2271
2272        if let SettingsUiFile::Project((_, _)) = &self.current_file {
2273            telemetry::event!("Setting Project Clicked");
2274        }
2275
2276        self.build_ui(window, cx);
2277
2278        if self
2279            .visible_navbar_entries()
2280            .any(|(index, _)| index == self.navbar_entry)
2281        {
2282            self.open_and_scroll_to_navbar_entry(self.navbar_entry, None, true, window, cx);
2283        } else {
2284            self.open_first_nav_page();
2285        };
2286    }
2287
2288    fn render_files_header(
2289        &self,
2290        window: &mut Window,
2291        cx: &mut Context<SettingsWindow>,
2292    ) -> impl IntoElement {
2293        static OVERFLOW_LIMIT: usize = 1;
2294
2295        let file_button =
2296            |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
2297                Button::new(
2298                    ix,
2299                    self.display_name(&file)
2300                        .expect("Files should always have a name"),
2301                )
2302                .toggle_state(file == &self.current_file)
2303                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
2304                .track_focus(focus_handle)
2305                .on_click(cx.listener({
2306                    let focus_handle = focus_handle.clone();
2307                    move |this, _: &gpui::ClickEvent, window, cx| {
2308                        this.change_file(ix, window, cx);
2309                        focus_handle.focus(window, cx);
2310                    }
2311                }))
2312            };
2313
2314        let this = cx.entity();
2315
2316        let selected_file_ix = self
2317            .files
2318            .iter()
2319            .enumerate()
2320            .skip(OVERFLOW_LIMIT)
2321            .find_map(|(ix, (file, _))| {
2322                if file == &self.current_file {
2323                    Some(ix)
2324                } else {
2325                    None
2326                }
2327            })
2328            .unwrap_or(OVERFLOW_LIMIT);
2329        let edit_in_json_id = SharedString::new(format!("edit-in-json-{}", selected_file_ix));
2330
2331        h_flex()
2332            .w_full()
2333            .gap_1()
2334            .justify_between()
2335            .track_focus(&self.files_focus_handle)
2336            .tab_group()
2337            .tab_index(HEADER_GROUP_TAB_INDEX)
2338            .child(
2339                h_flex()
2340                    .gap_1()
2341                    .children(
2342                        self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
2343                            |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
2344                        ),
2345                    )
2346                    .when(self.files.len() > OVERFLOW_LIMIT, |div| {
2347                        let (file, focus_handle) = &self.files[selected_file_ix];
2348
2349                        div.child(file_button(selected_file_ix, file, focus_handle, cx))
2350                            .when(self.files.len() > OVERFLOW_LIMIT + 1, |div| {
2351                                div.child(
2352                                    DropdownMenu::new(
2353                                        "more-files",
2354                                        format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
2355                                        ContextMenu::build(window, cx, move |mut menu, _, _| {
2356                                            for (mut ix, (file, focus_handle)) in self
2357                                                .files
2358                                                .iter()
2359                                                .enumerate()
2360                                                .skip(OVERFLOW_LIMIT + 1)
2361                                            {
2362                                                let (display_name, focus_handle) =
2363                                                    if selected_file_ix == ix {
2364                                                        ix = OVERFLOW_LIMIT;
2365                                                        (
2366                                                            self.display_name(&self.files[ix].0),
2367                                                            self.files[ix].1.clone(),
2368                                                        )
2369                                                    } else {
2370                                                        (
2371                                                            self.display_name(&file),
2372                                                            focus_handle.clone(),
2373                                                        )
2374                                                    };
2375
2376                                                menu = menu.entry(
2377                                                    display_name
2378                                                        .expect("Files should always have a name"),
2379                                                    None,
2380                                                    {
2381                                                        let this = this.clone();
2382                                                        move |window, cx| {
2383                                                            this.update(cx, |this, cx| {
2384                                                                this.change_file(ix, window, cx);
2385                                                            });
2386                                                            focus_handle.focus(window, cx);
2387                                                        }
2388                                                    },
2389                                                );
2390                                            }
2391
2392                                            menu
2393                                        }),
2394                                    )
2395                                    .style(DropdownStyle::Subtle)
2396                                    .trigger_tooltip(Tooltip::text("View Other Projects"))
2397                                    .trigger_icon(IconName::ChevronDown)
2398                                    .attach(gpui::Corner::BottomLeft)
2399                                    .offset(gpui::Point {
2400                                        x: px(0.0),
2401                                        y: px(2.0),
2402                                    })
2403                                    .tab_index(0),
2404                                )
2405                            })
2406                    }),
2407            )
2408            .child(
2409                Button::new(edit_in_json_id, "Edit in settings.json")
2410                    .tab_index(0_isize)
2411                    .style(ButtonStyle::OutlinedGhost)
2412                    .tooltip(Tooltip::for_action_title_in(
2413                        "Edit in settings.json",
2414                        &OpenCurrentFile,
2415                        &self.focus_handle,
2416                    ))
2417                    .on_click(cx.listener(|this, _, window, cx| {
2418                        this.open_current_settings_file(window, cx);
2419                    })),
2420            )
2421    }
2422
2423    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
2424        match file {
2425            SettingsUiFile::User => Some("User".to_string()),
2426            SettingsUiFile::Project((worktree_id, path)) => self
2427                .worktree_root_dirs
2428                .get(&worktree_id)
2429                .map(|directory_name| {
2430                    let path_style = PathStyle::local();
2431                    if path.is_empty() {
2432                        directory_name.clone()
2433                    } else {
2434                        format!(
2435                            "{}{}{}",
2436                            directory_name,
2437                            path_style.primary_separator(),
2438                            path.display(path_style)
2439                        )
2440                    }
2441                }),
2442            SettingsUiFile::Server(file) => Some(file.to_string()),
2443        }
2444    }
2445
2446    // TODO:
2447    //  Reconsider this after preview launch
2448    // fn file_location_str(&self) -> String {
2449    //     match &self.current_file {
2450    //         SettingsUiFile::User => "settings.json".to_string(),
2451    //         SettingsUiFile::Project((worktree_id, path)) => self
2452    //             .worktree_root_dirs
2453    //             .get(&worktree_id)
2454    //             .map(|directory_name| {
2455    //                 let path_style = PathStyle::local();
2456    //                 let file_path = path.join(paths::local_settings_file_relative_path());
2457    //                 format!(
2458    //                     "{}{}{}",
2459    //                     directory_name,
2460    //                     path_style.separator(),
2461    //                     file_path.display(path_style)
2462    //                 )
2463    //             })
2464    //             .expect("Current file should always be present in root dir map"),
2465    //         SettingsUiFile::Server(file) => file.to_string(),
2466    //     }
2467    // }
2468
2469    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2470        h_flex()
2471            .py_1()
2472            .px_1p5()
2473            .mb_3()
2474            .gap_1p5()
2475            .rounded_sm()
2476            .bg(cx.theme().colors().editor_background)
2477            .border_1()
2478            .border_color(cx.theme().colors().border)
2479            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2480            .child(self.search_bar.clone())
2481    }
2482
2483    fn render_nav(
2484        &self,
2485        window: &mut Window,
2486        cx: &mut Context<SettingsWindow>,
2487    ) -> impl IntoElement {
2488        let visible_count = self.visible_navbar_entries().count();
2489
2490        let focus_keybind_label = if self
2491            .navbar_focus_handle
2492            .read(cx)
2493            .handle
2494            .contains_focused(window, cx)
2495            || self
2496                .visible_navbar_entries()
2497                .any(|(_, entry)| entry.focus_handle.is_focused(window))
2498        {
2499            "Focus Content"
2500        } else {
2501            "Focus Navbar"
2502        };
2503
2504        let mut key_context = KeyContext::new_with_defaults();
2505        key_context.add("NavigationMenu");
2506        key_context.add("menu");
2507        if self.search_bar.focus_handle(cx).is_focused(window) {
2508            key_context.add("search");
2509        }
2510
2511        v_flex()
2512            .key_context(key_context)
2513            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2514                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2515                    return;
2516                };
2517                let focused_entry_parent = this.root_entry_containing(focused_entry);
2518                if this.navbar_entries[focused_entry_parent].expanded {
2519                    this.toggle_navbar_entry(focused_entry_parent);
2520                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle, cx);
2521                }
2522                cx.notify();
2523            }))
2524            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2525                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2526                    return;
2527                };
2528                if !this.navbar_entries[focused_entry].is_root {
2529                    return;
2530                }
2531                if !this.navbar_entries[focused_entry].expanded {
2532                    this.toggle_navbar_entry(focused_entry);
2533                }
2534                cx.notify();
2535            }))
2536            .on_action(
2537                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2538                    let entry_index = this
2539                        .focused_nav_entry(window, cx)
2540                        .unwrap_or(this.navbar_entry);
2541                    let mut root_index = None;
2542                    for (index, entry) in this.visible_navbar_entries() {
2543                        if index >= entry_index {
2544                            break;
2545                        }
2546                        if entry.is_root {
2547                            root_index = Some(index);
2548                        }
2549                    }
2550                    let Some(previous_root_index) = root_index else {
2551                        return;
2552                    };
2553                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2554                }),
2555            )
2556            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2557                let entry_index = this
2558                    .focused_nav_entry(window, cx)
2559                    .unwrap_or(this.navbar_entry);
2560                let mut root_index = None;
2561                for (index, entry) in this.visible_navbar_entries() {
2562                    if index <= entry_index {
2563                        continue;
2564                    }
2565                    if entry.is_root {
2566                        root_index = Some(index);
2567                        break;
2568                    }
2569                }
2570                let Some(next_root_index) = root_index else {
2571                    return;
2572                };
2573                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2574            }))
2575            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2576                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2577                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2578                }
2579            }))
2580            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2581                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2582                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2583                }
2584            }))
2585            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2586                let entry_index = this
2587                    .focused_nav_entry(window, cx)
2588                    .unwrap_or(this.navbar_entry);
2589                let mut next_index = None;
2590                for (index, _) in this.visible_navbar_entries() {
2591                    if index > entry_index {
2592                        next_index = Some(index);
2593                        break;
2594                    }
2595                }
2596                let Some(next_entry_index) = next_index else {
2597                    return;
2598                };
2599                this.open_and_scroll_to_navbar_entry(
2600                    next_entry_index,
2601                    Some(gpui::ScrollStrategy::Bottom),
2602                    false,
2603                    window,
2604                    cx,
2605                );
2606            }))
2607            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2608                let entry_index = this
2609                    .focused_nav_entry(window, cx)
2610                    .unwrap_or(this.navbar_entry);
2611                let mut prev_index = None;
2612                for (index, _) in this.visible_navbar_entries() {
2613                    if index >= entry_index {
2614                        break;
2615                    }
2616                    prev_index = Some(index);
2617                }
2618                let Some(prev_entry_index) = prev_index else {
2619                    return;
2620                };
2621                this.open_and_scroll_to_navbar_entry(
2622                    prev_entry_index,
2623                    Some(gpui::ScrollStrategy::Top),
2624                    false,
2625                    window,
2626                    cx,
2627                );
2628            }))
2629            .w_56()
2630            .h_full()
2631            .p_2p5()
2632            .when(cfg!(target_os = "macos"), |this| this.pt_10())
2633            .flex_none()
2634            .border_r_1()
2635            .border_color(cx.theme().colors().border)
2636            .bg(cx.theme().colors().panel_background)
2637            .child(self.render_search(window, cx))
2638            .child(
2639                v_flex()
2640                    .flex_1()
2641                    .overflow_hidden()
2642                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2643                    .tab_group()
2644                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
2645                    .child(
2646                        uniform_list(
2647                            "settings-ui-nav-bar",
2648                            visible_count + 1,
2649                            cx.processor(move |this, range: Range<usize>, _, cx| {
2650                                this.visible_navbar_entries()
2651                                    .skip(range.start.saturating_sub(1))
2652                                    .take(range.len())
2653                                    .map(|(entry_index, entry)| {
2654                                        TreeViewItem::new(
2655                                            ("settings-ui-navbar-entry", entry_index),
2656                                            entry.title,
2657                                        )
2658                                        .track_focus(&entry.focus_handle)
2659                                        .root_item(entry.is_root)
2660                                        .toggle_state(this.is_navbar_entry_selected(entry_index))
2661                                        .when(entry.is_root, |item| {
2662                                            item.expanded(entry.expanded || this.has_query)
2663                                                .on_toggle(cx.listener(
2664                                                    move |this, _, window, cx| {
2665                                                        this.toggle_navbar_entry(entry_index);
2666                                                        window.focus(
2667                                                            &this.navbar_entries[entry_index]
2668                                                                .focus_handle,
2669                                                            cx,
2670                                                        );
2671                                                        cx.notify();
2672                                                    },
2673                                                ))
2674                                        })
2675                                        .on_click({
2676                                            let category = this.pages[entry.page_index].title;
2677                                            let subcategory =
2678                                                (!entry.is_root).then_some(entry.title);
2679
2680                                            cx.listener(move |this, _, window, cx| {
2681                                                telemetry::event!(
2682                                                    "Settings Navigation Clicked",
2683                                                    category = category,
2684                                                    subcategory = subcategory
2685                                                );
2686
2687                                                this.open_and_scroll_to_navbar_entry(
2688                                                    entry_index,
2689                                                    None,
2690                                                    true,
2691                                                    window,
2692                                                    cx,
2693                                                );
2694                                            })
2695                                        })
2696                                    })
2697                                    .collect()
2698                            }),
2699                        )
2700                        .size_full()
2701                        .track_scroll(&self.navbar_scroll_handle),
2702                    )
2703                    .vertical_scrollbar_for(&self.navbar_scroll_handle, window, cx),
2704            )
2705            .child(
2706                h_flex()
2707                    .w_full()
2708                    .h_8()
2709                    .p_2()
2710                    .pb_0p5()
2711                    .flex_shrink_0()
2712                    .border_t_1()
2713                    .border_color(cx.theme().colors().border_variant)
2714                    .child(
2715                        KeybindingHint::new(
2716                            KeyBinding::for_action_in(
2717                                &ToggleFocusNav,
2718                                &self.navbar_focus_handle.focus_handle(cx),
2719                                cx,
2720                            ),
2721                            cx.theme().colors().surface_background.opacity(0.5),
2722                        )
2723                        .suffix(focus_keybind_label),
2724                    ),
2725            )
2726    }
2727
2728    fn open_and_scroll_to_navbar_entry(
2729        &mut self,
2730        navbar_entry_index: usize,
2731        scroll_strategy: Option<gpui::ScrollStrategy>,
2732        focus_content: bool,
2733        window: &mut Window,
2734        cx: &mut Context<Self>,
2735    ) {
2736        self.open_navbar_entry_page(navbar_entry_index);
2737        cx.notify();
2738
2739        let mut handle_to_focus = None;
2740
2741        if self.navbar_entries[navbar_entry_index].is_root
2742            || !self.is_nav_entry_visible(navbar_entry_index)
2743        {
2744            if let Some(scroll_handle) = self.current_sub_page_scroll_handle() {
2745                scroll_handle.set_offset(point(px(0.), px(0.)));
2746            }
2747
2748            if focus_content {
2749                let Some(first_item_index) =
2750                    self.visible_page_items().next().map(|(index, _)| index)
2751                else {
2752                    return;
2753                };
2754                handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2755            } else if !self.is_nav_entry_visible(navbar_entry_index) {
2756                let Some(first_visible_nav_entry_index) =
2757                    self.visible_navbar_entries().next().map(|(index, _)| index)
2758                else {
2759                    return;
2760                };
2761                self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2762            } else {
2763                handle_to_focus =
2764                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2765            }
2766        } else {
2767            let entry_item_index = self.navbar_entries[navbar_entry_index]
2768                .item_index
2769                .expect("Non-root items should have an item index");
2770            self.scroll_to_content_item(entry_item_index, window, cx);
2771            if focus_content {
2772                handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2773            } else {
2774                handle_to_focus =
2775                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2776            }
2777        }
2778
2779        if let Some(scroll_strategy) = scroll_strategy
2780            && let Some(logical_entry_index) = self
2781                .visible_navbar_entries()
2782                .into_iter()
2783                .position(|(index, _)| index == navbar_entry_index)
2784        {
2785            self.navbar_scroll_handle
2786                .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2787        }
2788
2789        // Page scroll handle updates the active item index
2790        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2791        // The call after that updates the offset of the scroll handle. So to
2792        // ensure the scroll handle doesn't lag behind we need to render three frames
2793        // back to back.
2794        cx.on_next_frame(window, move |_, window, cx| {
2795            if let Some(handle) = handle_to_focus.as_ref() {
2796                window.focus(handle, cx);
2797            }
2798
2799            cx.on_next_frame(window, |_, _, cx| {
2800                cx.notify();
2801            });
2802            cx.notify();
2803        });
2804        cx.notify();
2805    }
2806
2807    fn scroll_to_content_item(
2808        &self,
2809        content_item_index: usize,
2810        _window: &mut Window,
2811        cx: &mut Context<Self>,
2812    ) {
2813        let index = self
2814            .visible_page_items()
2815            .position(|(index, _)| index == content_item_index)
2816            .unwrap_or(0);
2817        if index == 0 {
2818            if let Some(scroll_handle) = self.current_sub_page_scroll_handle() {
2819                scroll_handle.set_offset(point(px(0.), px(0.)));
2820            }
2821
2822            self.list_state.scroll_to(gpui::ListOffset {
2823                item_ix: 0,
2824                offset_in_item: px(0.),
2825            });
2826            return;
2827        }
2828        self.list_state.scroll_to(gpui::ListOffset {
2829            item_ix: index + 1,
2830            offset_in_item: px(0.),
2831        });
2832        cx.notify();
2833    }
2834
2835    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2836        self.visible_navbar_entries()
2837            .any(|(index, _)| index == nav_entry_index)
2838    }
2839
2840    fn focus_and_scroll_to_first_visible_nav_entry(
2841        &self,
2842        window: &mut Window,
2843        cx: &mut Context<Self>,
2844    ) {
2845        if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2846        {
2847            self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2848        }
2849    }
2850
2851    fn focus_and_scroll_to_nav_entry(
2852        &self,
2853        nav_entry_index: usize,
2854        window: &mut Window,
2855        cx: &mut Context<Self>,
2856    ) {
2857        let Some(position) = self
2858            .visible_navbar_entries()
2859            .position(|(index, _)| index == nav_entry_index)
2860        else {
2861            return;
2862        };
2863        self.navbar_scroll_handle
2864            .scroll_to_item(position, gpui::ScrollStrategy::Top);
2865        window.focus(&self.navbar_entries[nav_entry_index].focus_handle, cx);
2866        cx.notify();
2867    }
2868
2869    fn current_sub_page_scroll_handle(&self) -> Option<&ScrollHandle> {
2870        self.sub_page_stack.last().map(|page| &page.scroll_handle)
2871    }
2872
2873    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2874        let page_idx = self.current_page_index();
2875
2876        self.current_page()
2877            .items
2878            .iter()
2879            .enumerate()
2880            .filter(move |&(item_index, _)| self.filter_table[page_idx][item_index])
2881    }
2882
2883    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2884        h_flex().min_w_0().gap_1().overflow_x_hidden().children(
2885            itertools::intersperse(
2886                std::iter::once(self.current_page().title.into()).chain(
2887                    self.sub_page_stack
2888                        .iter()
2889                        .enumerate()
2890                        .flat_map(|(index, page)| {
2891                            (index == 0)
2892                                .then(|| page.section_header.clone())
2893                                .into_iter()
2894                                .chain(std::iter::once(page.link.title.clone()))
2895                        }),
2896                ),
2897                "/".into(),
2898            )
2899            .map(|item| Label::new(item).color(Color::Muted)),
2900        )
2901    }
2902
2903    fn render_no_results(&self, cx: &App) -> impl IntoElement {
2904        let search_query = self.search_bar.read(cx).text(cx);
2905
2906        v_flex()
2907            .size_full()
2908            .items_center()
2909            .justify_center()
2910            .gap_1()
2911            .child(Label::new("No Results"))
2912            .child(
2913                Label::new(format!("No settings match \"{}\"", search_query))
2914                    .size(LabelSize::Small)
2915                    .color(Color::Muted),
2916            )
2917    }
2918
2919    fn render_current_page_items(
2920        &mut self,
2921        _window: &mut Window,
2922        cx: &mut Context<SettingsWindow>,
2923    ) -> impl IntoElement {
2924        let current_page_index = self.current_page_index();
2925        let mut page_content = v_flex().id("settings-ui-page").size_full();
2926
2927        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2928        let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2929
2930        if has_no_results {
2931            page_content = page_content.child(self.render_no_results(cx))
2932        } else {
2933            let last_non_header_index = self
2934                .visible_page_items()
2935                .filter_map(|(index, item)| {
2936                    (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2937                })
2938                .last();
2939
2940            let root_nav_label = self
2941                .navbar_entries
2942                .iter()
2943                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2944                .map(|entry| entry.title);
2945
2946            let list_content = list(
2947                self.list_state.clone(),
2948                cx.processor(move |this, index, window, cx| {
2949                    if index == 0 {
2950                        return div()
2951                            .px_8()
2952                            .when(this.sub_page_stack.is_empty(), |this| {
2953                                this.when_some(root_nav_label, |this, title| {
2954                                    this.child(
2955                                        Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2956                                    )
2957                                })
2958                            })
2959                            .into_any_element();
2960                    }
2961
2962                    let mut visible_items = this.visible_page_items();
2963                    let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2964                        return gpui::Empty.into_any_element();
2965                    };
2966
2967                    let next_is_header = visible_items
2968                        .next()
2969                        .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2970                        .unwrap_or(false);
2971
2972                    let is_last = Some(actual_item_index) == last_non_header_index;
2973                    let is_last_in_section = next_is_header || is_last;
2974
2975                    let bottom_border = !is_last_in_section;
2976                    let extra_bottom_padding = is_last_in_section;
2977
2978                    let item_focus_handle = this.content_handles[current_page_index]
2979                        [actual_item_index]
2980                        .focus_handle(cx);
2981
2982                    v_flex()
2983                        .id(("settings-page-item", actual_item_index))
2984                        .track_focus(&item_focus_handle)
2985                        .w_full()
2986                        .min_w_0()
2987                        .child(item.render(
2988                            this,
2989                            actual_item_index,
2990                            bottom_border,
2991                            extra_bottom_padding,
2992                            window,
2993                            cx,
2994                        ))
2995                        .into_any_element()
2996                }),
2997            );
2998
2999            page_content = page_content.child(list_content.size_full())
3000        }
3001        page_content
3002    }
3003
3004    fn render_sub_page_items<'a, Items>(
3005        &self,
3006        items: Items,
3007        scroll_handle: &ScrollHandle,
3008        window: &mut Window,
3009        cx: &mut Context<SettingsWindow>,
3010    ) -> impl IntoElement
3011    where
3012        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
3013    {
3014        let page_content = v_flex()
3015            .id("settings-ui-page")
3016            .size_full()
3017            .overflow_y_scroll()
3018            .track_scroll(scroll_handle);
3019        self.render_sub_page_items_in(page_content, items, false, window, cx)
3020    }
3021
3022    fn render_sub_page_items_section<'a, Items>(
3023        &self,
3024        items: Items,
3025        is_inline_section: bool,
3026        window: &mut Window,
3027        cx: &mut Context<SettingsWindow>,
3028    ) -> impl IntoElement
3029    where
3030        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
3031    {
3032        let page_content = v_flex().id("settings-ui-sub-page-section").size_full();
3033        self.render_sub_page_items_in(page_content, items, is_inline_section, window, cx)
3034    }
3035
3036    fn render_sub_page_items_in<'a, Items>(
3037        &self,
3038        page_content: Stateful<Div>,
3039        items: Items,
3040        is_inline_section: bool,
3041        window: &mut Window,
3042        cx: &mut Context<SettingsWindow>,
3043    ) -> impl IntoElement
3044    where
3045        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
3046    {
3047        let items: Vec<_> = items.collect();
3048        let items_len = items.len();
3049
3050        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
3051        let has_no_results = items_len == 0 && has_active_search;
3052
3053        if has_no_results {
3054            page_content.child(self.render_no_results(cx))
3055        } else {
3056            let last_non_header_index = items
3057                .iter()
3058                .enumerate()
3059                .rev()
3060                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
3061                .map(|(index, _)| index);
3062
3063            let root_nav_label = self
3064                .navbar_entries
3065                .iter()
3066                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
3067                .map(|entry| entry.title);
3068
3069            page_content
3070                .when(self.sub_page_stack.is_empty(), |this| {
3071                    this.when_some(root_nav_label, |this, title| {
3072                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
3073                    })
3074                })
3075                .children(items.clone().into_iter().enumerate().map(
3076                    |(index, (actual_item_index, item))| {
3077                        let is_last_item = Some(index) == last_non_header_index;
3078                        let next_is_header = items.get(index + 1).is_some_and(|(_, next_item)| {
3079                            matches!(next_item, SettingsPageItem::SectionHeader(_))
3080                        });
3081                        let bottom_border = !is_inline_section && !next_is_header && !is_last_item;
3082
3083                        let extra_bottom_padding =
3084                            !is_inline_section && (next_is_header || is_last_item);
3085
3086                        v_flex()
3087                            .w_full()
3088                            .min_w_0()
3089                            .id(("settings-page-item", actual_item_index))
3090                            .child(item.render(
3091                                self,
3092                                actual_item_index,
3093                                bottom_border,
3094                                extra_bottom_padding,
3095                                window,
3096                                cx,
3097                            ))
3098                    },
3099                ))
3100        }
3101    }
3102
3103    fn render_page(
3104        &mut self,
3105        window: &mut Window,
3106        cx: &mut Context<SettingsWindow>,
3107    ) -> impl IntoElement {
3108        let page_header;
3109        let page_content;
3110
3111        if let Some(current_sub_page) = self.sub_page_stack.last() {
3112            page_header = h_flex()
3113                .w_full()
3114                .min_w_0()
3115                .justify_between()
3116                .child(
3117                    h_flex()
3118                        .min_w_0()
3119                        .ml_neg_1p5()
3120                        .gap_1()
3121                        .child(
3122                            IconButton::new("back-btn", IconName::ArrowLeft)
3123                                .icon_size(IconSize::Small)
3124                                .shape(IconButtonShape::Square)
3125                                .on_click(cx.listener(|this, _, window, cx| {
3126                                    this.pop_sub_page(window, cx);
3127                                })),
3128                        )
3129                        .child(self.render_sub_page_breadcrumbs()),
3130                )
3131                .when(current_sub_page.link.in_json, |this| {
3132                    this.child(
3133                        div().flex_shrink_0().child(
3134                            Button::new("open-in-settings-file", "Edit in settings.json")
3135                                .tab_index(0_isize)
3136                                .style(ButtonStyle::OutlinedGhost)
3137                                .tooltip(Tooltip::for_action_title_in(
3138                                    "Edit in settings.json",
3139                                    &OpenCurrentFile,
3140                                    &self.focus_handle,
3141                                ))
3142                                .on_click(cx.listener(|this, _, window, cx| {
3143                                    this.open_current_settings_file(window, cx);
3144                                })),
3145                        ),
3146                    )
3147                })
3148                .into_any_element();
3149
3150            let active_page_render_fn = &current_sub_page.link.render;
3151            page_content =
3152                (active_page_render_fn)(self, &current_sub_page.scroll_handle, window, cx);
3153        } else {
3154            page_header = self.render_files_header(window, cx).into_any_element();
3155
3156            page_content = self
3157                .render_current_page_items(window, cx)
3158                .into_any_element();
3159        }
3160
3161        let current_sub_page = self.sub_page_stack.last();
3162
3163        let mut warning_banner = gpui::Empty.into_any_element();
3164        if let Some(error) =
3165            SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
3166        {
3167            fn banner(
3168                label: &'static str,
3169                error: String,
3170                shown_errors: &mut HashSet<String>,
3171                cx: &mut Context<SettingsWindow>,
3172            ) -> impl IntoElement {
3173                if shown_errors.insert(error.clone()) {
3174                    telemetry::event!("Settings Error Shown", label = label, error = &error);
3175                }
3176                Banner::new()
3177                    .severity(Severity::Warning)
3178                    .child(
3179                        v_flex()
3180                            .my_0p5()
3181                            .gap_0p5()
3182                            .child(Label::new(label))
3183                            .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
3184                    )
3185                    .action_slot(
3186                        div().pr_1().pb_1().child(
3187                            Button::new("fix-in-json", "Fix in settings.json")
3188                                .tab_index(0_isize)
3189                                .style(ButtonStyle::Tinted(ui::TintColor::Warning))
3190                                .on_click(cx.listener(|this, _, window, cx| {
3191                                    this.open_current_settings_file(window, cx);
3192                                })),
3193                        ),
3194                    )
3195            }
3196
3197            let parse_error = error.parse_error();
3198            let parse_failed = parse_error.is_some();
3199
3200            warning_banner = v_flex()
3201                .gap_2()
3202                .when_some(parse_error, |this, err| {
3203                    this.child(banner(
3204                        "Failed to load your settings. Some values may be incorrect and changes may be lost.",
3205                        err,
3206                        &mut self.shown_errors,
3207                        cx,
3208                    ))
3209                })
3210                .map(|this| match &error.migration_status {
3211                    settings::MigrationStatus::Succeeded => this.child(banner(
3212                        "Your settings are out of date, and need to be updated.",
3213                        match &self.current_file {
3214                            SettingsUiFile::User => "They can be automatically migrated to the latest version.",
3215                            SettingsUiFile::Server(_) | SettingsUiFile::Project(_)  => "They must be manually migrated to the latest version."
3216                        }.to_string(),
3217                        &mut self.shown_errors,
3218                        cx,
3219                    )),
3220                    settings::MigrationStatus::Failed { error: err } if !parse_failed => this
3221                        .child(banner(
3222                            "Your settings file is out of date, automatic migration failed",
3223                            err.clone(),
3224                            &mut self.shown_errors,
3225                            cx,
3226                        )),
3227                    _ => this,
3228                })
3229                .into_any_element()
3230        }
3231
3232        v_flex()
3233            .id("settings-ui-page")
3234            .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3235                if !this.sub_page_stack.is_empty() {
3236                    window.focus_next(cx);
3237                    return;
3238                }
3239                for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
3240                    let handle = this.content_handles[this.current_page_index()][actual_index]
3241                        .focus_handle(cx);
3242                    let mut offset = 1; // for page header
3243
3244                    if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
3245                        && matches!(next_item, SettingsPageItem::SectionHeader(_))
3246                    {
3247                        offset += 1;
3248                    }
3249                    if handle.contains_focused(window, cx) {
3250                        let next_logical_index = logical_index + offset + 1;
3251                        this.list_state.scroll_to_reveal_item(next_logical_index);
3252                        // We need to render the next item to ensure it's focus handle is in the element tree
3253                        cx.on_next_frame(window, |_, window, cx| {
3254                            cx.notify();
3255                            cx.on_next_frame(window, |_, window, cx| {
3256                                window.focus_next(cx);
3257                                cx.notify();
3258                            });
3259                        });
3260                        cx.notify();
3261                        return;
3262                    }
3263                }
3264                window.focus_next(cx);
3265            }))
3266            .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
3267                if !this.sub_page_stack.is_empty() {
3268                    window.focus_prev(cx);
3269                    return;
3270                }
3271                let mut prev_was_header = false;
3272                for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
3273                    let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
3274                    let handle = this.content_handles[this.current_page_index()][actual_index]
3275                        .focus_handle(cx);
3276                    let mut offset = 1; // for page header
3277
3278                    if prev_was_header {
3279                        offset -= 1;
3280                    }
3281                    if handle.contains_focused(window, cx) {
3282                        let next_logical_index = logical_index + offset - 1;
3283                        this.list_state.scroll_to_reveal_item(next_logical_index);
3284                        // We need to render the next item to ensure it's focus handle is in the element tree
3285                        cx.on_next_frame(window, |_, window, cx| {
3286                            cx.notify();
3287                            cx.on_next_frame(window, |_, window, cx| {
3288                                window.focus_prev(cx);
3289                                cx.notify();
3290                            });
3291                        });
3292                        cx.notify();
3293                        return;
3294                    }
3295                    prev_was_header = is_header;
3296                }
3297                window.focus_prev(cx);
3298            }))
3299            .when(current_sub_page.is_none(), |this| {
3300                this.vertical_scrollbar_for(&self.list_state, window, cx)
3301            })
3302            .when_some(current_sub_page, |this, current_sub_page| {
3303                this.custom_scrollbars(
3304                    Scrollbars::new(ui::ScrollAxes::Vertical)
3305                        .tracked_scroll_handle(&current_sub_page.scroll_handle)
3306                        .id((current_sub_page.link.title.clone(), 42)),
3307                    window,
3308                    cx,
3309                )
3310            })
3311            .track_focus(&self.content_focus_handle.focus_handle(cx))
3312            .pt_6()
3313            .gap_4()
3314            .flex_1()
3315            .min_w_0()
3316            .bg(cx.theme().colors().editor_background)
3317            .child(
3318                v_flex()
3319                    .px_8()
3320                    .gap_2()
3321                    .child(page_header)
3322                    .child(warning_banner),
3323            )
3324            .child(
3325                div()
3326                    .flex_1()
3327                    .min_h_0()
3328                    .size_full()
3329                    .tab_group()
3330                    .tab_index(CONTENT_GROUP_TAB_INDEX)
3331                    .child(page_content),
3332            )
3333    }
3334
3335    /// This function will create a new settings file if one doesn't exist
3336    /// if the current file is a project settings with a valid worktree id
3337    /// We do this because the settings ui allows initializing project settings
3338    fn open_current_settings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3339        match &self.current_file {
3340            SettingsUiFile::User => {
3341                let Some(original_window) = self.original_window else {
3342                    return;
3343                };
3344                original_window
3345                    .update(cx, |multi_workspace, window, cx| {
3346                        multi_workspace
3347                            .workspace()
3348                            .clone()
3349                            .update(cx, |workspace, cx| {
3350                                workspace
3351                                    .with_local_or_wsl_workspace(
3352                                        window,
3353                                        cx,
3354                                        open_user_settings_in_workspace,
3355                                    )
3356                                    .detach();
3357                            });
3358                    })
3359                    .ok();
3360
3361                window.remove_window();
3362            }
3363            SettingsUiFile::Project((worktree_id, path)) => {
3364                let settings_path = path.join(paths::local_settings_file_relative_path());
3365                let app_state = workspace::AppState::global(cx);
3366
3367                let Some((workspace_window, worktree, corresponding_workspace)) = app_state
3368                    .workspace_store
3369                    .read(cx)
3370                    .workspaces_with_windows()
3371                    .filter_map(|(window_handle, weak)| {
3372                        let workspace = weak.upgrade()?;
3373                        let window = window_handle.downcast::<MultiWorkspace>()?;
3374                        Some((window, workspace))
3375                    })
3376                    .find_map(|(window, workspace): (_, Entity<Workspace>)| {
3377                        workspace
3378                            .read(cx)
3379                            .project()
3380                            .read(cx)
3381                            .worktree_for_id(*worktree_id, cx)
3382                            .map(|worktree| (window, worktree, workspace))
3383                    })
3384                else {
3385                    log::error!(
3386                        "No corresponding workspace contains worktree id: {}",
3387                        worktree_id
3388                    );
3389
3390                    return;
3391                };
3392
3393                let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3394                    None
3395                } else {
3396                    Some(worktree.update(cx, |tree, cx| {
3397                        tree.create_entry(
3398                            settings_path.clone(),
3399                            false,
3400                            Some(initial_project_settings_content().as_bytes().to_vec()),
3401                            cx,
3402                        )
3403                    }))
3404                };
3405
3406                let worktree_id = *worktree_id;
3407
3408                // TODO: move zed::open_local_file() APIs to this crate, and
3409                // re-implement the "initial_contents" behavior
3410                let workspace_weak = corresponding_workspace.downgrade();
3411                workspace_window
3412                    .update(cx, |_, window, cx| {
3413                        cx.spawn_in(window, async move |_, cx| {
3414                            if let Some(create_task) = create_task {
3415                                create_task.await.ok()?;
3416                            };
3417
3418                            workspace_weak
3419                                .update_in(cx, |workspace, window, cx| {
3420                                    workspace.open_path(
3421                                        (worktree_id, settings_path.clone()),
3422                                        None,
3423                                        true,
3424                                        window,
3425                                        cx,
3426                                    )
3427                                })
3428                                .ok()?
3429                                .await
3430                                .log_err()?;
3431
3432                            workspace_weak
3433                                .update_in(cx, |_, window, cx| {
3434                                    window.activate_window();
3435                                    cx.notify();
3436                                })
3437                                .ok();
3438
3439                            Some(())
3440                        })
3441                        .detach();
3442                    })
3443                    .ok();
3444
3445                window.remove_window();
3446            }
3447            SettingsUiFile::Server(_) => {
3448                // Server files are not editable
3449                return;
3450            }
3451        };
3452    }
3453
3454    fn current_page_index(&self) -> usize {
3455        if self.navbar_entries.is_empty() {
3456            return 0;
3457        }
3458
3459        self.navbar_entries[self.navbar_entry].page_index
3460    }
3461
3462    fn current_page(&self) -> &SettingsPage {
3463        &self.pages[self.current_page_index()]
3464    }
3465
3466    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3467        ix == self.navbar_entry
3468    }
3469
3470    fn push_sub_page(
3471        &mut self,
3472        sub_page_link: SubPageLink,
3473        section_header: SharedString,
3474        window: &mut Window,
3475        cx: &mut Context<SettingsWindow>,
3476    ) {
3477        self.sub_page_stack
3478            .push(SubPage::new(sub_page_link, section_header));
3479        self.content_focus_handle.focus_handle(cx).focus(window, cx);
3480        cx.notify();
3481    }
3482
3483    /// Push a dynamically-created sub-page with a custom render function.
3484    /// This is useful for nested sub-pages that aren't defined in the main pages list.
3485    pub fn push_dynamic_sub_page(
3486        &mut self,
3487        title: impl Into<SharedString>,
3488        section_header: impl Into<SharedString>,
3489        json_path: Option<&'static str>,
3490        render: fn(
3491            &SettingsWindow,
3492            &ScrollHandle,
3493            &mut Window,
3494            &mut Context<SettingsWindow>,
3495        ) -> AnyElement,
3496        window: &mut Window,
3497        cx: &mut Context<SettingsWindow>,
3498    ) {
3499        self.regex_validation_error = None;
3500        let sub_page_link = SubPageLink {
3501            title: title.into(),
3502            r#type: SubPageType::default(),
3503            description: None,
3504            json_path,
3505            in_json: true,
3506            files: USER,
3507            render,
3508        };
3509        self.push_sub_page(sub_page_link, section_header.into(), window, cx);
3510    }
3511
3512    /// Navigate to a sub-page by its json_path.
3513    /// Returns true if the sub-page was found and pushed, false otherwise.
3514    pub fn navigate_to_sub_page(
3515        &mut self,
3516        json_path: &str,
3517        window: &mut Window,
3518        cx: &mut Context<SettingsWindow>,
3519    ) -> bool {
3520        for page in &self.pages {
3521            for (item_index, item) in page.items.iter().enumerate() {
3522                if let SettingsPageItem::SubPageLink(sub_page_link) = item {
3523                    if sub_page_link.json_path == Some(json_path) {
3524                        let section_header = page
3525                            .items
3526                            .iter()
3527                            .take(item_index)
3528                            .rev()
3529                            .find_map(|item| item.header_text().map(SharedString::new_static))
3530                            .unwrap_or_else(|| "Settings".into());
3531
3532                        self.push_sub_page(sub_page_link.clone(), section_header, window, cx);
3533                        return true;
3534                    }
3535                }
3536            }
3537        }
3538        false
3539    }
3540
3541    /// Navigate to a setting by its json_path.
3542    /// Clears the sub-page stack and scrolls to the setting item.
3543    /// Returns true if the setting was found, false otherwise.
3544    pub fn navigate_to_setting(
3545        &mut self,
3546        json_path: &str,
3547        window: &mut Window,
3548        cx: &mut Context<SettingsWindow>,
3549    ) -> bool {
3550        self.sub_page_stack.clear();
3551
3552        for (page_index, page) in self.pages.iter().enumerate() {
3553            for (item_index, item) in page.items.iter().enumerate() {
3554                let item_json_path = match item {
3555                    SettingsPageItem::SettingItem(setting_item) => setting_item.field.json_path(),
3556                    SettingsPageItem::DynamicItem(dynamic_item) => {
3557                        dynamic_item.discriminant.field.json_path()
3558                    }
3559                    _ => None,
3560                };
3561                if item_json_path == Some(json_path) {
3562                    if let Some(navbar_entry_index) = self
3563                        .navbar_entries
3564                        .iter()
3565                        .position(|e| e.page_index == page_index && e.is_root)
3566                    {
3567                        self.open_and_scroll_to_navbar_entry(
3568                            navbar_entry_index,
3569                            None,
3570                            false,
3571                            window,
3572                            cx,
3573                        );
3574                        self.scroll_to_content_item(item_index, window, cx);
3575                        return true;
3576                    }
3577                }
3578            }
3579        }
3580        false
3581    }
3582
3583    fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
3584        self.regex_validation_error = None;
3585        self.sub_page_stack.pop();
3586        self.content_focus_handle.focus_handle(cx).focus(window, cx);
3587        cx.notify();
3588    }
3589
3590    fn focus_file_at_index(&mut self, index: usize, window: &mut Window, cx: &mut App) {
3591        if let Some((_, handle)) = self.files.get(index) {
3592            handle.focus(window, cx);
3593        }
3594    }
3595
3596    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3597        if self.files_focus_handle.contains_focused(window, cx)
3598            && let Some(index) = self
3599                .files
3600                .iter()
3601                .position(|(_, handle)| handle.is_focused(window))
3602        {
3603            return index;
3604        }
3605        if let Some(current_file_index) = self
3606            .files
3607            .iter()
3608            .position(|(file, _)| file == &self.current_file)
3609        {
3610            return current_file_index;
3611        }
3612        0
3613    }
3614
3615    fn focus_handle_for_content_element(
3616        &self,
3617        actual_item_index: usize,
3618        cx: &Context<Self>,
3619    ) -> FocusHandle {
3620        let page_index = self.current_page_index();
3621        self.content_handles[page_index][actual_item_index].focus_handle(cx)
3622    }
3623
3624    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3625        if !self
3626            .navbar_focus_handle
3627            .focus_handle(cx)
3628            .contains_focused(window, cx)
3629        {
3630            return None;
3631        }
3632        for (index, entry) in self.navbar_entries.iter().enumerate() {
3633            if entry.focus_handle.is_focused(window) {
3634                return Some(index);
3635            }
3636        }
3637        None
3638    }
3639
3640    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3641        let mut index = Some(nav_entry_index);
3642        while let Some(prev_index) = index
3643            && !self.navbar_entries[prev_index].is_root
3644        {
3645            index = prev_index.checked_sub(1);
3646        }
3647        return index.expect("No root entry found");
3648    }
3649}
3650
3651impl Render for SettingsWindow {
3652    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3653        let ui_font = theme_settings::setup_ui_font(window, cx);
3654
3655        client_side_decorations(
3656            v_flex()
3657                .text_color(cx.theme().colors().text)
3658                .size_full()
3659                .children(self.title_bar.clone())
3660                .child(
3661                    div()
3662                        .id("settings-window")
3663                        .key_context("SettingsWindow")
3664                        .track_focus(&self.focus_handle)
3665                        .on_action(cx.listener(|this, _: &OpenCurrentFile, window, cx| {
3666                            this.open_current_settings_file(window, cx);
3667                        }))
3668                        .on_action(|_: &Minimize, window, _cx| {
3669                            window.minimize_window();
3670                        })
3671                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3672                            this.search_bar.focus_handle(cx).focus(window, cx);
3673                        }))
3674                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3675                            if this
3676                                .navbar_focus_handle
3677                                .focus_handle(cx)
3678                                .contains_focused(window, cx)
3679                            {
3680                                this.open_and_scroll_to_navbar_entry(
3681                                    this.navbar_entry,
3682                                    None,
3683                                    true,
3684                                    window,
3685                                    cx,
3686                                );
3687                            } else {
3688                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3689                            }
3690                        }))
3691                        .on_action(cx.listener(
3692                            |this, FocusFile(file_index): &FocusFile, window, cx| {
3693                                this.focus_file_at_index(*file_index as usize, window, cx);
3694                            },
3695                        ))
3696                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3697                            let next_index = usize::min(
3698                                this.focused_file_index(window, cx) + 1,
3699                                this.files.len().saturating_sub(1),
3700                            );
3701                            this.focus_file_at_index(next_index, window, cx);
3702                        }))
3703                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3704                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3705                            this.focus_file_at_index(prev_index, window, cx);
3706                        }))
3707                        .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3708                            if this
3709                                .search_bar
3710                                .focus_handle(cx)
3711                                .contains_focused(window, cx)
3712                            {
3713                                this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3714                            } else {
3715                                window.focus_next(cx);
3716                            }
3717                        }))
3718                        .on_action(|_: &menu::SelectPrevious, window, cx| {
3719                            window.focus_prev(cx);
3720                        })
3721                        .flex()
3722                        .flex_row()
3723                        .flex_1()
3724                        .min_h_0()
3725                        .font(ui_font)
3726                        .bg(cx.theme().colors().background)
3727                        .text_color(cx.theme().colors().text)
3728                        .when(!cfg!(target_os = "macos"), |this| {
3729                            this.border_t_1().border_color(cx.theme().colors().border)
3730                        })
3731                        .child(self.render_nav(window, cx))
3732                        .child(self.render_page(window, cx)),
3733                ),
3734            window,
3735            cx,
3736            Tiling::default(),
3737        )
3738    }
3739}
3740
3741fn all_projects(
3742    window: Option<&WindowHandle<MultiWorkspace>>,
3743    cx: &App,
3744) -> impl Iterator<Item = Entity<Project>> {
3745    let mut seen_project_ids = std::collections::HashSet::new();
3746    let app_state = workspace::AppState::global(cx);
3747    app_state
3748        .workspace_store
3749        .read(cx)
3750        .workspaces()
3751        .filter_map(|weak| weak.upgrade())
3752        .map(|workspace: Entity<Workspace>| workspace.read(cx).project().clone())
3753        .chain(
3754            window
3755                .and_then(|handle| handle.read(cx).ok())
3756                .into_iter()
3757                .flat_map(|multi_workspace| {
3758                    multi_workspace
3759                        .workspaces(cx)
3760                        .into_iter()
3761                        .map(|workspace| workspace.read(cx).project().clone())
3762                        .collect::<Vec<_>>()
3763                }),
3764        )
3765        .filter(move |project| seen_project_ids.insert(project.entity_id()))
3766}
3767
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}