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