settings_ui.rs

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