settings_ui.rs

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