settings_ui.rs

   1mod components;
   2mod page_data;
   3
   4use anyhow::Result;
   5use editor::{Editor, EditorEvent};
   6use feature_flags::FeatureFlag;
   7use fuzzy::StringMatchCandidate;
   8use gpui::{
   9    Action, App, ClipboardItem, DEFAULT_ADDITIONAL_WINDOW_SIZE, Div, Entity, FocusHandle,
  10    Focusable, Global, KeyContext, ListState, ReadGlobal as _, ScrollHandle, Stateful,
  11    Subscription, Task, TitlebarOptions, UniformListScrollHandle, Window, WindowBounds,
  12    WindowHandle, WindowOptions, actions, div, list, point, prelude::*, px, uniform_list,
  13};
  14use project::{Project, WorktreeId};
  15use release_channel::ReleaseChannel;
  16use schemars::JsonSchema;
  17use serde::Deserialize;
  18use settings::{Settings, SettingsContent, SettingsStore, initial_project_settings_content};
  19use std::{
  20    any::{Any, TypeId, type_name},
  21    cell::RefCell,
  22    collections::{HashMap, HashSet},
  23    num::{NonZero, NonZeroU32},
  24    ops::Range,
  25    rc::Rc,
  26    sync::{Arc, LazyLock, RwLock},
  27    time::Duration,
  28};
  29use title_bar::platform_title_bar::PlatformTitleBar;
  30use ui::{
  31    Banner, ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape,
  32    KeyBinding, KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem,
  33    WithScrollbar, prelude::*,
  34};
  35use ui_input::{NumberField, NumberFieldType};
  36use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
  37use workspace::{AppState, OpenOptions, OpenVisible, Workspace, client_side_decorations};
  38use zed_actions::{OpenProjectSettings, OpenSettings, OpenSettingsAt};
  39
  40use crate::components::{
  41    EnumVariantDropdown, SettingsInputField, font_picker, icon_theme_picker, theme_picker,
  42};
  43
  44const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
  45const NAVBAR_GROUP_TAB_INDEX: isize = 1;
  46
  47const HEADER_CONTAINER_TAB_INDEX: isize = 2;
  48const HEADER_GROUP_TAB_INDEX: isize = 3;
  49
  50const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
  51const CONTENT_GROUP_TAB_INDEX: isize = 5;
  52
  53actions!(
  54    settings_editor,
  55    [
  56        /// Minimizes the settings UI window.
  57        Minimize,
  58        /// Toggles focus between the navbar and the main content.
  59        ToggleFocusNav,
  60        /// Expands the navigation entry.
  61        ExpandNavEntry,
  62        /// Collapses the navigation entry.
  63        CollapseNavEntry,
  64        /// Focuses the next file in the file list.
  65        FocusNextFile,
  66        /// Focuses the previous file in the file list.
  67        FocusPreviousFile,
  68        /// Opens an editor for the current file
  69        OpenCurrentFile,
  70        /// Focuses the previous root navigation entry.
  71        FocusPreviousRootNavEntry,
  72        /// Focuses the next root navigation entry.
  73        FocusNextRootNavEntry,
  74        /// Focuses the first navigation entry.
  75        FocusFirstNavEntry,
  76        /// Focuses the last navigation entry.
  77        FocusLastNavEntry,
  78        /// Focuses and opens the next navigation entry without moving focus to content.
  79        FocusNextNavEntry,
  80        /// Focuses and opens the previous navigation entry without moving focus to content.
  81        FocusPreviousNavEntry
  82    ]
  83);
  84
  85#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
  86#[action(namespace = settings_editor)]
  87struct FocusFile(pub u32);
  88
  89struct SettingField<T: 'static> {
  90    pick: fn(&SettingsContent) -> Option<&T>,
  91    write: fn(&mut SettingsContent, Option<T>),
  92
  93    /// A json-path-like string that gives a unique-ish string that identifies
  94    /// where in the JSON the setting is defined.
  95    ///
  96    /// The syntax is `jq`-like, but modified slightly to be URL-safe (and
  97    /// without the leading dot), e.g. `foo.bar`.
  98    ///
  99    /// They are URL-safe (this is important since links are the main use-case
 100    /// for these paths).
 101    ///
 102    /// There are a couple of special cases:
 103    /// - discrimminants are represented with a trailing `$`, for example
 104    /// `terminal.working_directory$`. This is to distinguish the discrimminant
 105    /// setting (i.e. the setting that changes whether the value is a string or
 106    /// an object) from the setting in the case that it is a string.
 107    /// - language-specific settings begin `languages.$(language)`. Links
 108    /// targeting these settings should take the form `languages/Rust/...`, for
 109    /// example, but are not currently supported.
 110    json_path: Option<&'static str>,
 111}
 112
 113impl<T: 'static> Clone for SettingField<T> {
 114    fn clone(&self) -> Self {
 115        *self
 116    }
 117}
 118
 119// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
 120impl<T: 'static> Copy for SettingField<T> {}
 121
 122/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
 123/// to keep the setting around in the UI with valid pick and write implementations, but don't actually try to render it.
 124/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
 125#[derive(Clone, Copy)]
 126struct UnimplementedSettingField;
 127
 128impl PartialEq for UnimplementedSettingField {
 129    fn eq(&self, _other: &Self) -> bool {
 130        true
 131    }
 132}
 133
 134impl<T: 'static> SettingField<T> {
 135    /// Helper for settings with types that are not yet implemented.
 136    #[allow(unused)]
 137    fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
 138        SettingField {
 139            pick: |_| Some(&UnimplementedSettingField),
 140            write: |_, _| unreachable!(),
 141            json_path: self.json_path,
 142        }
 143    }
 144}
 145
 146trait AnySettingField {
 147    fn as_any(&self) -> &dyn Any;
 148    fn type_name(&self) -> &'static str;
 149    fn type_id(&self) -> TypeId;
 150    // 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)
 151    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
 152    fn reset_to_default_fn(
 153        &self,
 154        current_file: &SettingsUiFile,
 155        file_set_in: &settings::SettingsFile,
 156        cx: &App,
 157    ) -> Option<Box<dyn Fn(&mut App)>>;
 158
 159    fn json_path(&self) -> Option<&'static str>;
 160}
 161
 162impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
 163    fn as_any(&self) -> &dyn Any {
 164        self
 165    }
 166
 167    fn type_name(&self) -> &'static str {
 168        type_name::<T>()
 169    }
 170
 171    fn type_id(&self) -> TypeId {
 172        TypeId::of::<T>()
 173    }
 174
 175    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
 176        let (file, value) = cx
 177            .global::<SettingsStore>()
 178            .get_value_from_file(file.to_settings(), self.pick);
 179        return (file, value.is_some());
 180    }
 181
 182    fn reset_to_default_fn(
 183        &self,
 184        current_file: &SettingsUiFile,
 185        file_set_in: &settings::SettingsFile,
 186        cx: &App,
 187    ) -> Option<Box<dyn Fn(&mut App)>> {
 188        if file_set_in == &settings::SettingsFile::Default {
 189            return None;
 190        }
 191        if file_set_in != &current_file.to_settings() {
 192            return None;
 193        }
 194        let this = *self;
 195        let store = SettingsStore::global(cx);
 196        let default_value = (this.pick)(store.raw_default_settings());
 197        let is_default = store
 198            .get_content_for_file(file_set_in.clone())
 199            .map_or(None, this.pick)
 200            == default_value;
 201        if is_default {
 202            return None;
 203        }
 204        let current_file = current_file.clone();
 205
 206        return Some(Box::new(move |cx| {
 207            let store = SettingsStore::global(cx);
 208            let default_value = (this.pick)(store.raw_default_settings());
 209            let is_set_somewhere_other_than_default = store
 210                .get_value_up_to_file(current_file.to_settings(), this.pick)
 211                .0
 212                != settings::SettingsFile::Default;
 213            let value_to_set = if is_set_somewhere_other_than_default {
 214                default_value.cloned()
 215            } else {
 216                None
 217            };
 218            update_settings_file(current_file.clone(), None, cx, move |settings, _| {
 219                (this.write)(settings, value_to_set);
 220            })
 221            // todo(settings_ui): Don't log err
 222            .log_err();
 223        }));
 224    }
 225
 226    fn json_path(&self) -> Option<&'static str> {
 227        self.json_path
 228    }
 229}
 230
 231#[derive(Default, Clone)]
 232struct SettingFieldRenderer {
 233    renderers: Rc<
 234        RefCell<
 235            HashMap<
 236                TypeId,
 237                Box<
 238                    dyn Fn(
 239                        &SettingsWindow,
 240                        &SettingItem,
 241                        SettingsUiFile,
 242                        Option<&SettingsFieldMetadata>,
 243                        bool,
 244                        &mut Window,
 245                        &mut Context<SettingsWindow>,
 246                    ) -> Stateful<Div>,
 247                >,
 248            >,
 249        >,
 250    >,
 251}
 252
 253impl Global for SettingFieldRenderer {}
 254
 255impl SettingFieldRenderer {
 256    fn add_basic_renderer<T: 'static>(
 257        &mut self,
 258        render_control: impl Fn(
 259            SettingField<T>,
 260            SettingsUiFile,
 261            Option<&SettingsFieldMetadata>,
 262            &mut Window,
 263            &mut App,
 264        ) -> AnyElement
 265        + 'static,
 266    ) -> &mut Self {
 267        self.add_renderer(
 268            move |settings_window: &SettingsWindow,
 269                  item: &SettingItem,
 270                  field: SettingField<T>,
 271                  settings_file: SettingsUiFile,
 272                  metadata: Option<&SettingsFieldMetadata>,
 273                  sub_field: bool,
 274                  window: &mut Window,
 275                  cx: &mut Context<SettingsWindow>| {
 276                render_settings_item(
 277                    settings_window,
 278                    item,
 279                    settings_file.clone(),
 280                    render_control(field, settings_file, metadata, window, cx),
 281                    sub_field,
 282                    cx,
 283                )
 284            },
 285        )
 286    }
 287
 288    fn add_renderer<T: 'static>(
 289        &mut self,
 290        renderer: impl Fn(
 291            &SettingsWindow,
 292            &SettingItem,
 293            SettingField<T>,
 294            SettingsUiFile,
 295            Option<&SettingsFieldMetadata>,
 296            bool,
 297            &mut Window,
 298            &mut Context<SettingsWindow>,
 299        ) -> Stateful<Div>
 300        + 'static,
 301    ) -> &mut Self {
 302        let key = TypeId::of::<T>();
 303        let renderer = Box::new(
 304            move |settings_window: &SettingsWindow,
 305                  item: &SettingItem,
 306                  settings_file: SettingsUiFile,
 307                  metadata: Option<&SettingsFieldMetadata>,
 308                  sub_field: bool,
 309                  window: &mut Window,
 310                  cx: &mut Context<SettingsWindow>| {
 311                let field = *item
 312                    .field
 313                    .as_ref()
 314                    .as_any()
 315                    .downcast_ref::<SettingField<T>>()
 316                    .unwrap();
 317                renderer(
 318                    settings_window,
 319                    item,
 320                    field,
 321                    settings_file,
 322                    metadata,
 323                    sub_field,
 324                    window,
 325                    cx,
 326                )
 327            },
 328        );
 329        self.renderers.borrow_mut().insert(key, renderer);
 330        self
 331    }
 332}
 333
 334struct NonFocusableHandle {
 335    handle: FocusHandle,
 336    _subscription: Subscription,
 337}
 338
 339impl NonFocusableHandle {
 340    fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
 341        let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
 342        Self::from_handle(handle, window, cx)
 343    }
 344
 345    fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
 346        cx.new(|cx| {
 347            let _subscription = cx.on_focus(&handle, window, {
 348                move |_, window, _| {
 349                    window.focus_next();
 350                }
 351            });
 352            Self {
 353                handle,
 354                _subscription,
 355            }
 356        })
 357    }
 358}
 359
 360impl Focusable for NonFocusableHandle {
 361    fn focus_handle(&self, _: &App) -> FocusHandle {
 362        self.handle.clone()
 363    }
 364}
 365
 366#[derive(Default)]
 367struct SettingsFieldMetadata {
 368    placeholder: Option<&'static str>,
 369    should_do_titlecase: Option<bool>,
 370}
 371
 372pub struct SettingsUiFeatureFlag;
 373
 374impl FeatureFlag for SettingsUiFeatureFlag {
 375    const NAME: &'static str = "settings-ui";
 376}
 377
 378pub fn init(cx: &mut App) {
 379    init_renderers(cx);
 380
 381    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 382        workspace
 383            .register_action(
 384                |workspace, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
 385                    let window_handle = window
 386                        .window_handle()
 387                        .downcast::<Workspace>()
 388                        .expect("Workspaces are root Windows");
 389                    open_settings_editor(workspace, Some(&path), false, window_handle, cx);
 390                },
 391            )
 392            .register_action(|workspace, _: &OpenSettings, window, cx| {
 393                let window_handle = window
 394                    .window_handle()
 395                    .downcast::<Workspace>()
 396                    .expect("Workspaces are root Windows");
 397                open_settings_editor(workspace, None, false, window_handle, cx);
 398            })
 399            .register_action(|workspace, _: &OpenProjectSettings, window, cx| {
 400                let window_handle = window
 401                    .window_handle()
 402                    .downcast::<Workspace>()
 403                    .expect("Workspaces are root Windows");
 404                open_settings_editor(workspace, None, true, window_handle, cx);
 405            });
 406    })
 407    .detach();
 408}
 409
 410fn init_renderers(cx: &mut App) {
 411    cx.default_global::<SettingFieldRenderer>()
 412        .add_renderer::<UnimplementedSettingField>(
 413            |settings_window, item, _, settings_file, _, sub_field, _, cx| {
 414                render_settings_item(
 415                    settings_window,
 416                    item,
 417                    settings_file,
 418                    Button::new("open-in-settings-file", "Edit in settings.json")
 419                        .style(ButtonStyle::Outlined)
 420                        .size(ButtonSize::Medium)
 421                        .tab_index(0_isize)
 422                        .tooltip(Tooltip::for_action_title_in(
 423                            "Edit in settings.json",
 424                            &OpenCurrentFile,
 425                            &settings_window.focus_handle,
 426                        ))
 427                        .on_click(cx.listener(|this, _, window, cx| {
 428                            this.open_current_settings_file(window, cx);
 429                        }))
 430                        .into_any_element(),
 431                    sub_field,
 432                    cx,
 433                )
 434            },
 435        )
 436        .add_basic_renderer::<bool>(render_toggle_button)
 437        .add_basic_renderer::<String>(render_text_field)
 438        .add_basic_renderer::<SharedString>(render_text_field)
 439        .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
 440        .add_basic_renderer::<settings::CursorShape>(render_dropdown)
 441        .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
 442        .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
 443        .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
 444        .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
 445        .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
 446        .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
 447        .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
 448        .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
 449        .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
 450        .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
 451        .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
 452        .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
 453        .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
 454        .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
 455        .add_basic_renderer::<settings::DockSide>(render_dropdown)
 456        .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
 457        .add_basic_renderer::<settings::DockPosition>(render_dropdown)
 458        .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
 459        .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
 460        .add_basic_renderer::<settings::GitPathStyle>(render_dropdown)
 461        .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
 462        .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
 463        .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
 464        .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
 465        .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
 466        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 467        .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
 468        .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
 469        .add_basic_renderer::<settings::ProjectPanelSortMode>(render_dropdown)
 470        .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
 471        .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
 472        .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
 473        .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
 474        .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
 475        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 476        .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
 477        .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
 478        .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
 479        .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
 480        .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
 481        .add_basic_renderer::<f32>(render_number_field)
 482        .add_basic_renderer::<u32>(render_number_field)
 483        .add_basic_renderer::<u64>(render_number_field)
 484        .add_basic_renderer::<usize>(render_number_field)
 485        .add_basic_renderer::<NonZero<usize>>(render_number_field)
 486        .add_basic_renderer::<NonZeroU32>(render_number_field)
 487        .add_basic_renderer::<settings::CodeFade>(render_number_field)
 488        .add_basic_renderer::<settings::DelayMs>(render_number_field)
 489        .add_basic_renderer::<gpui::FontWeight>(render_number_field)
 490        .add_basic_renderer::<settings::CenteredPaddingSettings>(render_number_field)
 491        .add_basic_renderer::<settings::InactiveOpacity>(render_number_field)
 492        .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
 493        .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
 494        .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
 495        .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
 496        .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
 497        .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
 498        .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
 499        .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
 500        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 501        .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
 502        .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
 503        .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
 504        .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
 505        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 506        .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
 507        .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
 508        .add_basic_renderer::<settings::ThemeSelectionDiscriminants>(render_dropdown)
 509        .add_basic_renderer::<settings::ThemeAppearanceMode>(render_dropdown)
 510        .add_basic_renderer::<settings::ThemeName>(render_theme_picker)
 511        .add_basic_renderer::<settings::IconThemeSelectionDiscriminants>(render_dropdown)
 512        .add_basic_renderer::<settings::IconThemeName>(render_icon_theme_picker)
 513        .add_basic_renderer::<settings::BufferLineHeightDiscriminants>(render_dropdown)
 514        .add_basic_renderer::<settings::AutosaveSettingDiscriminants>(render_dropdown)
 515        .add_basic_renderer::<settings::WorkingDirectoryDiscriminants>(render_dropdown)
 516        .add_basic_renderer::<settings::IncludeIgnoredContent>(render_dropdown)
 517        .add_basic_renderer::<settings::ShowIndentGuides>(render_dropdown)
 518        .add_basic_renderer::<settings::ShellDiscriminants>(render_dropdown)
 519        .add_basic_renderer::<settings::EditPredictionsMode>(render_dropdown)
 520        .add_basic_renderer::<settings::RelativeLineNumbers>(render_dropdown)
 521        .add_basic_renderer::<settings::WindowDecorations>(render_dropdown)
 522        // please semicolon stay on next line
 523        ;
 524}
 525
 526pub fn open_settings_editor(
 527    _workspace: &mut Workspace,
 528    path: Option<&str>,
 529    open_project_settings: bool,
 530    workspace_handle: WindowHandle<Workspace>,
 531    cx: &mut App,
 532) {
 533    telemetry::event!("Settings Viewed");
 534
 535    /// Assumes a settings GUI window is already open
 536    fn open_path(
 537        path: &str,
 538        // Note: This option is unsupported right now
 539        _open_project_settings: bool,
 540        settings_window: &mut SettingsWindow,
 541        window: &mut Window,
 542        cx: &mut Context<SettingsWindow>,
 543    ) {
 544        if path.starts_with("languages.$(language)") {
 545            log::error!("language-specific settings links are not currently supported");
 546            return;
 547        }
 548
 549        settings_window.search_bar.update(cx, |editor, cx| {
 550            editor.set_text(format!("#{path}"), window, cx);
 551        });
 552        settings_window.update_matches(cx);
 553    }
 554
 555    let existing_window = cx
 556        .windows()
 557        .into_iter()
 558        .find_map(|window| window.downcast::<SettingsWindow>());
 559
 560    if let Some(existing_window) = existing_window {
 561        existing_window
 562            .update(cx, |settings_window, window, cx| {
 563                settings_window.original_window = Some(workspace_handle);
 564                window.activate_window();
 565                if let Some(path) = path {
 566                    open_path(path, open_project_settings, settings_window, window, cx);
 567                } else if open_project_settings {
 568                    if let Some(file_index) = settings_window
 569                        .files
 570                        .iter()
 571                        .position(|(file, _)| file.worktree_id().is_some())
 572                    {
 573                        settings_window.change_file(file_index, window, cx);
 574                    }
 575
 576                    cx.notify();
 577                }
 578            })
 579            .ok();
 580        return;
 581    }
 582
 583    // We have to defer this to get the workspace off the stack.
 584
 585    let path = path.map(ToOwned::to_owned);
 586    cx.defer(move |cx| {
 587        let current_rem_size: f32 = theme::ThemeSettings::get_global(cx).ui_font_size(cx).into();
 588
 589        let default_bounds = DEFAULT_ADDITIONAL_WINDOW_SIZE;
 590        let default_rem_size = 16.0;
 591        let scale_factor = current_rem_size / default_rem_size;
 592        let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
 593
 594        let app_id = ReleaseChannel::global(cx).app_id();
 595        let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
 596            Ok(val) if val == "server" => gpui::WindowDecorations::Server,
 597            Ok(val) if val == "client" => gpui::WindowDecorations::Client,
 598            _ => gpui::WindowDecorations::Client,
 599        };
 600
 601        cx.open_window(
 602            WindowOptions {
 603                titlebar: Some(TitlebarOptions {
 604                    title: Some("Zed — Settings".into()),
 605                    appears_transparent: true,
 606                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 607                }),
 608                focus: true,
 609                show: true,
 610                is_movable: true,
 611                kind: gpui::WindowKind::Floating,
 612                window_background: cx.theme().window_background_appearance(),
 613                app_id: Some(app_id.to_owned()),
 614                window_decorations: Some(window_decorations),
 615                window_min_size: Some(gpui::Size {
 616                    width: px(360.0),
 617                    height: px(240.0),
 618                }),
 619                window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
 620                ..Default::default()
 621            },
 622            |window, cx| {
 623                let settings_window =
 624                    cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx));
 625                settings_window.update(cx, |settings_window, cx| {
 626                    if let Some(path) = path {
 627                        open_path(&path, open_project_settings, settings_window, window, cx);
 628                    } else if open_project_settings {
 629                        if let Some(file_index) = settings_window
 630                            .files
 631                            .iter()
 632                            .position(|(file, _)| file.worktree_id().is_some())
 633                        {
 634                            settings_window.change_file(file_index, window, cx);
 635                        }
 636
 637                        settings_window.fetch_files(window, cx);
 638                    }
 639                });
 640
 641                settings_window
 642            },
 643        )
 644        .log_err();
 645    });
 646}
 647
 648/// The current sub page path that is selected.
 649/// If this is empty the selected page is rendered,
 650/// otherwise the last sub page gets rendered.
 651///
 652/// Global so that `pick` and `write` callbacks can access it
 653/// and use it to dynamically render sub pages (e.g. for language settings)
 654static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
 655
 656fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
 657    SUB_PAGE_STACK
 658        .read()
 659        .expect("SUB_PAGE_STACK is never poisoned")
 660}
 661
 662fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
 663    SUB_PAGE_STACK
 664        .write()
 665        .expect("SUB_PAGE_STACK is never poisoned")
 666}
 667
 668pub struct SettingsWindow {
 669    title_bar: Option<Entity<PlatformTitleBar>>,
 670    original_window: Option<WindowHandle<Workspace>>,
 671    files: Vec<(SettingsUiFile, FocusHandle)>,
 672    worktree_root_dirs: HashMap<WorktreeId, String>,
 673    current_file: SettingsUiFile,
 674    pages: Vec<SettingsPage>,
 675    search_bar: Entity<Editor>,
 676    search_task: Option<Task<()>>,
 677    /// Index into navbar_entries
 678    navbar_entry: usize,
 679    navbar_entries: Vec<NavBarEntry>,
 680    navbar_scroll_handle: UniformListScrollHandle,
 681    /// [page_index][page_item_index] will be false
 682    /// when the item is filtered out either by searches
 683    /// or by the current file
 684    navbar_focus_subscriptions: Vec<gpui::Subscription>,
 685    filter_table: Vec<Vec<bool>>,
 686    has_query: bool,
 687    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 688    sub_page_scroll_handle: ScrollHandle,
 689    focus_handle: FocusHandle,
 690    navbar_focus_handle: Entity<NonFocusableHandle>,
 691    content_focus_handle: Entity<NonFocusableHandle>,
 692    files_focus_handle: FocusHandle,
 693    search_index: Option<Arc<SearchIndex>>,
 694    list_state: ListState,
 695    shown_errors: HashSet<String>,
 696}
 697
 698struct SearchIndex {
 699    bm25_engine: bm25::SearchEngine<usize>,
 700    fuzzy_match_candidates: Vec<StringMatchCandidate>,
 701    key_lut: Vec<SearchKeyLUTEntry>,
 702}
 703
 704struct SearchKeyLUTEntry {
 705    page_index: usize,
 706    header_index: usize,
 707    item_index: usize,
 708    json_path: Option<&'static str>,
 709}
 710
 711struct SubPage {
 712    link: SubPageLink,
 713    section_header: &'static str,
 714}
 715
 716#[derive(Debug)]
 717struct NavBarEntry {
 718    title: &'static str,
 719    is_root: bool,
 720    expanded: bool,
 721    page_index: usize,
 722    item_index: Option<usize>,
 723    focus_handle: FocusHandle,
 724}
 725
 726struct SettingsPage {
 727    title: &'static str,
 728    items: Vec<SettingsPageItem>,
 729}
 730
 731#[derive(PartialEq)]
 732enum SettingsPageItem {
 733    SectionHeader(&'static str),
 734    SettingItem(SettingItem),
 735    SubPageLink(SubPageLink),
 736    DynamicItem(DynamicItem),
 737}
 738
 739impl std::fmt::Debug for SettingsPageItem {
 740    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 741        match self {
 742            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 743            SettingsPageItem::SettingItem(setting_item) => {
 744                write!(f, "SettingItem({})", setting_item.title)
 745            }
 746            SettingsPageItem::SubPageLink(sub_page_link) => {
 747                write!(f, "SubPageLink({})", sub_page_link.title)
 748            }
 749            SettingsPageItem::DynamicItem(dynamic_item) => {
 750                write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
 751            }
 752        }
 753    }
 754}
 755
 756impl SettingsPageItem {
 757    fn render(
 758        &self,
 759        settings_window: &SettingsWindow,
 760        item_index: usize,
 761        is_last: bool,
 762        window: &mut Window,
 763        cx: &mut Context<SettingsWindow>,
 764    ) -> AnyElement {
 765        let file = settings_window.current_file.clone();
 766
 767        let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
 768            let element = element.pt_4();
 769            if is_last {
 770                element.pb_10()
 771            } else {
 772                element.pb_4()
 773            }
 774        };
 775
 776        let mut render_setting_item_inner =
 777            |setting_item: &SettingItem,
 778             padding: bool,
 779             sub_field: bool,
 780             cx: &mut Context<SettingsWindow>| {
 781                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 782                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 783
 784                let renderers = renderer.renderers.borrow();
 785
 786                let field_renderer =
 787                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 788                let field_renderer_or_warning =
 789                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 790                        if cfg!(debug_assertions) && !found {
 791                            Err("NO DEFAULT")
 792                        } else {
 793                            Ok(renderer)
 794                        }
 795                    });
 796
 797                let field = match field_renderer_or_warning {
 798                    Ok(field_renderer) => window.with_id(item_index, |window| {
 799                        field_renderer(
 800                            settings_window,
 801                            setting_item,
 802                            file.clone(),
 803                            setting_item.metadata.as_deref(),
 804                            sub_field,
 805                            window,
 806                            cx,
 807                        )
 808                    }),
 809                    Err(warning) => render_settings_item(
 810                        settings_window,
 811                        setting_item,
 812                        file.clone(),
 813                        Button::new("error-warning", warning)
 814                            .style(ButtonStyle::Outlined)
 815                            .size(ButtonSize::Medium)
 816                            .icon(Some(IconName::Debug))
 817                            .icon_position(IconPosition::Start)
 818                            .icon_color(Color::Error)
 819                            .tab_index(0_isize)
 820                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 821                            .into_any_element(),
 822                        sub_field,
 823                        cx,
 824                    ),
 825                };
 826
 827                let field = if padding {
 828                    field.map(apply_padding)
 829                } else {
 830                    field
 831                };
 832
 833                (field, field_renderer_or_warning.is_ok())
 834            };
 835
 836        match self {
 837            SettingsPageItem::SectionHeader(header) => v_flex()
 838                .w_full()
 839                .px_8()
 840                .gap_1p5()
 841                .child(
 842                    Label::new(SharedString::new_static(header))
 843                        .size(LabelSize::Small)
 844                        .color(Color::Muted)
 845                        .buffer_font(cx),
 846                )
 847                .child(Divider::horizontal().color(DividerColor::BorderFaded))
 848                .into_any_element(),
 849            SettingsPageItem::SettingItem(setting_item) => {
 850                let (field_with_padding, _) =
 851                    render_setting_item_inner(setting_item, true, false, cx);
 852
 853                v_flex()
 854                    .group("setting-item")
 855                    .px_8()
 856                    .child(field_with_padding)
 857                    .when(!is_last, |this| this.child(Divider::horizontal()))
 858                    .into_any_element()
 859            }
 860            SettingsPageItem::SubPageLink(sub_page_link) => v_flex()
 861                .group("setting-item")
 862                .px_8()
 863                .child(
 864                    h_flex()
 865                        .id(sub_page_link.title.clone())
 866                        .w_full()
 867                        .min_w_0()
 868                        .justify_between()
 869                        .map(apply_padding)
 870                        .child(
 871                            v_flex()
 872                                .w_full()
 873                                .max_w_1_2()
 874                                .child(Label::new(sub_page_link.title.clone())),
 875                        )
 876                        .child(
 877                            Button::new(
 878                                ("sub-page".into(), sub_page_link.title.clone()),
 879                                "Configure",
 880                            )
 881                            .icon(IconName::ChevronRight)
 882                            .tab_index(0_isize)
 883                            .icon_position(IconPosition::End)
 884                            .icon_color(Color::Muted)
 885                            .icon_size(IconSize::Small)
 886                            .style(ButtonStyle::OutlinedGhost)
 887                            .size(ButtonSize::Medium)
 888                            .on_click({
 889                                let sub_page_link = sub_page_link.clone();
 890                                cx.listener(move |this, _, _, cx| {
 891                                    let mut section_index = item_index;
 892                                    let current_page = this.current_page();
 893
 894                                    while !matches!(
 895                                        current_page.items[section_index],
 896                                        SettingsPageItem::SectionHeader(_)
 897                                    ) {
 898                                        section_index -= 1;
 899                                    }
 900
 901                                    let SettingsPageItem::SectionHeader(header) =
 902                                        current_page.items[section_index]
 903                                    else {
 904                                        unreachable!(
 905                                            "All items always have a section header above them"
 906                                        )
 907                                    };
 908
 909                                    this.push_sub_page(sub_page_link.clone(), header, cx)
 910                                })
 911                            }),
 912                        ),
 913                )
 914                .when(!is_last, |this| this.child(Divider::horizontal()))
 915                .into_any_element(),
 916            SettingsPageItem::DynamicItem(DynamicItem {
 917                discriminant: discriminant_setting_item,
 918                pick_discriminant,
 919                fields,
 920            }) => {
 921                let file = file.to_settings();
 922                let discriminant = SettingsStore::global(cx)
 923                    .get_value_from_file(file, *pick_discriminant)
 924                    .1;
 925
 926                let (discriminant_element, rendered_ok) =
 927                    render_setting_item_inner(discriminant_setting_item, true, false, cx);
 928
 929                let has_sub_fields =
 930                    rendered_ok && discriminant.map(|d| !fields[d].is_empty()).unwrap_or(false);
 931
 932                let mut content = v_flex()
 933                    .id("dynamic-item")
 934                    .child(
 935                        div()
 936                            .group("setting-item")
 937                            .px_8()
 938                            .child(discriminant_element.when(has_sub_fields, |this| this.pb_4())),
 939                    )
 940                    .when(!has_sub_fields && !is_last, |this| {
 941                        this.child(h_flex().px_8().child(Divider::horizontal()))
 942                    });
 943
 944                if rendered_ok {
 945                    let discriminant =
 946                        discriminant.expect("This should be Some if rendered_ok is true");
 947                    let sub_fields = &fields[discriminant];
 948                    let sub_field_count = sub_fields.len();
 949
 950                    for (index, field) in sub_fields.iter().enumerate() {
 951                        let is_last_sub_field = index == sub_field_count - 1;
 952                        let (raw_field, _) = render_setting_item_inner(field, false, true, cx);
 953
 954                        content = content.child(
 955                            raw_field
 956                                .group("setting-sub-item")
 957                                .mx_8()
 958                                .p_4()
 959                                .border_t_1()
 960                                .when(is_last_sub_field, |this| this.border_b_1())
 961                                .when(is_last_sub_field && is_last, |this| this.mb_8())
 962                                .border_dashed()
 963                                .border_color(cx.theme().colors().border_variant)
 964                                .bg(cx.theme().colors().element_background.opacity(0.2)),
 965                        );
 966                    }
 967                }
 968
 969                return content.into_any_element();
 970            }
 971        }
 972    }
 973}
 974
 975fn render_settings_item(
 976    settings_window: &SettingsWindow,
 977    setting_item: &SettingItem,
 978    file: SettingsUiFile,
 979    control: AnyElement,
 980    sub_field: bool,
 981    cx: &mut Context<'_, SettingsWindow>,
 982) -> Stateful<Div> {
 983    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
 984    let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
 985
 986    let clipboard_has_link = cx
 987        .read_from_clipboard()
 988        .and_then(|entry| entry.text())
 989        .map_or(false, |maybe_url| {
 990            setting_item.field.json_path().is_some()
 991                && maybe_url.strip_prefix("zed://settings/") == setting_item.field.json_path()
 992        });
 993
 994    let (link_icon, link_icon_color) = if clipboard_has_link {
 995        (IconName::Check, Color::Success)
 996    } else {
 997        (IconName::Link, Color::Muted)
 998    };
 999
1000    h_flex()
1001        .id(setting_item.title)
1002        .min_w_0()
1003        .justify_between()
1004        .child(
1005            v_flex()
1006                .relative()
1007                .w_1_2()
1008                .child(
1009                    h_flex()
1010                        .w_full()
1011                        .gap_1()
1012                        .child(Label::new(SharedString::new_static(setting_item.title)))
1013                        .when_some(
1014                            if sub_field {
1015                                None
1016                            } else {
1017                                setting_item
1018                                    .field
1019                                    .reset_to_default_fn(&file, &found_in_file, cx)
1020                            },
1021                            |this, reset_to_default| {
1022                                this.child(
1023                                    IconButton::new("reset-to-default-btn", IconName::Undo)
1024                                        .icon_color(Color::Muted)
1025                                        .icon_size(IconSize::Small)
1026                                        .tooltip(Tooltip::text("Reset to Default"))
1027                                        .on_click({
1028                                            move |_, _, cx| {
1029                                                reset_to_default(cx);
1030                                            }
1031                                        }),
1032                                )
1033                            },
1034                        )
1035                        .when_some(
1036                            file_set_in.filter(|file_set_in| file_set_in != &file),
1037                            |this, file_set_in| {
1038                                this.child(
1039                                    Label::new(format!(
1040                                        "—  Modified in {}",
1041                                        settings_window
1042                                            .display_name(&file_set_in)
1043                                            .expect("File name should exist")
1044                                    ))
1045                                    .color(Color::Muted)
1046                                    .size(LabelSize::Small),
1047                                )
1048                            },
1049                        ),
1050                )
1051                .child(
1052                    Label::new(SharedString::new_static(setting_item.description))
1053                        .size(LabelSize::Small)
1054                        .color(Color::Muted),
1055                ),
1056        )
1057        .child(control)
1058        .when(sub_page_stack().is_empty(), |this| {
1059            // Intentionally using the description to make the icon button
1060            // unique because some items share the same title (e.g., "Font Size")
1061            let icon_button_id =
1062                SharedString::new(format!("copy-link-btn-{}", setting_item.description));
1063
1064            this.child(
1065                div()
1066                    .absolute()
1067                    .top(rems_from_px(18.))
1068                    .map(|this| {
1069                        if sub_field {
1070                            this.visible_on_hover("setting-sub-item")
1071                                .left(rems_from_px(-8.5))
1072                        } else {
1073                            this.visible_on_hover("setting-item")
1074                                .left(rems_from_px(-22.))
1075                        }
1076                    })
1077                    .child({
1078                        IconButton::new(icon_button_id, link_icon)
1079                            .icon_color(link_icon_color)
1080                            .icon_size(IconSize::Small)
1081                            .shape(IconButtonShape::Square)
1082                            .tooltip(Tooltip::text("Copy Link"))
1083                            .when_some(setting_item.field.json_path(), |this, path| {
1084                                this.on_click(cx.listener(move |_, _, _, cx| {
1085                                    let link = format!("zed://settings/{}", path);
1086                                    cx.write_to_clipboard(ClipboardItem::new_string(link));
1087                                    cx.notify();
1088                                }))
1089                            })
1090                    }),
1091            )
1092        })
1093}
1094
1095struct SettingItem {
1096    title: &'static str,
1097    description: &'static str,
1098    field: Box<dyn AnySettingField>,
1099    metadata: Option<Box<SettingsFieldMetadata>>,
1100    files: FileMask,
1101}
1102
1103struct DynamicItem {
1104    discriminant: SettingItem,
1105    pick_discriminant: fn(&SettingsContent) -> Option<usize>,
1106    fields: Vec<Vec<SettingItem>>,
1107}
1108
1109impl PartialEq for DynamicItem {
1110    fn eq(&self, other: &Self) -> bool {
1111        self.discriminant == other.discriminant && self.fields == other.fields
1112    }
1113}
1114
1115#[derive(PartialEq, Eq, Clone, Copy)]
1116struct FileMask(u8);
1117
1118impl std::fmt::Debug for FileMask {
1119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1120        write!(f, "FileMask(")?;
1121        let mut items = vec![];
1122
1123        if self.contains(USER) {
1124            items.push("USER");
1125        }
1126        if self.contains(PROJECT) {
1127            items.push("LOCAL");
1128        }
1129        if self.contains(SERVER) {
1130            items.push("SERVER");
1131        }
1132
1133        write!(f, "{})", items.join(" | "))
1134    }
1135}
1136
1137const USER: FileMask = FileMask(1 << 0);
1138const PROJECT: FileMask = FileMask(1 << 2);
1139const SERVER: FileMask = FileMask(1 << 3);
1140
1141impl std::ops::BitAnd for FileMask {
1142    type Output = Self;
1143
1144    fn bitand(self, other: Self) -> Self {
1145        Self(self.0 & other.0)
1146    }
1147}
1148
1149impl std::ops::BitOr for FileMask {
1150    type Output = Self;
1151
1152    fn bitor(self, other: Self) -> Self {
1153        Self(self.0 | other.0)
1154    }
1155}
1156
1157impl FileMask {
1158    fn contains(&self, other: FileMask) -> bool {
1159        self.0 & other.0 != 0
1160    }
1161}
1162
1163impl PartialEq for SettingItem {
1164    fn eq(&self, other: &Self) -> bool {
1165        self.title == other.title
1166            && self.description == other.description
1167            && (match (&self.metadata, &other.metadata) {
1168                (None, None) => true,
1169                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1170                _ => false,
1171            })
1172    }
1173}
1174
1175#[derive(Clone)]
1176struct SubPageLink {
1177    title: SharedString,
1178    files: FileMask,
1179    render: Arc<
1180        dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
1181            + 'static
1182            + Send
1183            + Sync,
1184    >,
1185}
1186
1187impl PartialEq for SubPageLink {
1188    fn eq(&self, other: &Self) -> bool {
1189        self.title == other.title
1190    }
1191}
1192
1193fn all_language_names(cx: &App) -> Vec<SharedString> {
1194    workspace::AppState::global(cx)
1195        .upgrade()
1196        .map_or(vec![], |state| {
1197            state
1198                .languages
1199                .language_names()
1200                .into_iter()
1201                .filter(|name| name.as_ref() != "Zed Keybind Context")
1202                .map(Into::into)
1203                .collect()
1204        })
1205}
1206
1207#[allow(unused)]
1208#[derive(Clone, PartialEq, Debug)]
1209enum SettingsUiFile {
1210    User,                                // Uses all settings.
1211    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1212    Server(&'static str),                // Uses a special name, and the user settings
1213}
1214
1215impl SettingsUiFile {
1216    fn setting_type(&self) -> &'static str {
1217        match self {
1218            SettingsUiFile::User => "User",
1219            SettingsUiFile::Project(_) => "Project",
1220            SettingsUiFile::Server(_) => "Server",
1221        }
1222    }
1223
1224    fn is_server(&self) -> bool {
1225        matches!(self, SettingsUiFile::Server(_))
1226    }
1227
1228    fn worktree_id(&self) -> Option<WorktreeId> {
1229        match self {
1230            SettingsUiFile::User => None,
1231            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1232            SettingsUiFile::Server(_) => None,
1233        }
1234    }
1235
1236    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1237        Some(match file {
1238            settings::SettingsFile::User => SettingsUiFile::User,
1239            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1240            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1241            settings::SettingsFile::Default => return None,
1242            settings::SettingsFile::Global => return None,
1243        })
1244    }
1245
1246    fn to_settings(&self) -> settings::SettingsFile {
1247        match self {
1248            SettingsUiFile::User => settings::SettingsFile::User,
1249            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1250            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1251        }
1252    }
1253
1254    fn mask(&self) -> FileMask {
1255        match self {
1256            SettingsUiFile::User => USER,
1257            SettingsUiFile::Project(_) => PROJECT,
1258            SettingsUiFile::Server(_) => SERVER,
1259        }
1260    }
1261}
1262
1263impl SettingsWindow {
1264    fn new(
1265        original_window: Option<WindowHandle<Workspace>>,
1266        window: &mut Window,
1267        cx: &mut Context<Self>,
1268    ) -> Self {
1269        let font_family_cache = theme::FontFamilyCache::global(cx);
1270
1271        cx.spawn(async move |this, cx| {
1272            font_family_cache.prefetch(cx).await;
1273            this.update(cx, |_, cx| {
1274                cx.notify();
1275            })
1276        })
1277        .detach();
1278
1279        let current_file = SettingsUiFile::User;
1280        let search_bar = cx.new(|cx| {
1281            let mut editor = Editor::single_line(window, cx);
1282            editor.set_placeholder_text("Search settings…", window, cx);
1283            editor
1284        });
1285
1286        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1287            let EditorEvent::Edited { transaction_id: _ } = event else {
1288                return;
1289            };
1290
1291            this.update_matches(cx);
1292        })
1293        .detach();
1294
1295        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1296            this.fetch_files(window, cx);
1297            cx.notify();
1298        })
1299        .detach();
1300
1301        cx.on_window_closed(|cx| {
1302            if let Some(existing_window) = cx
1303                .windows()
1304                .into_iter()
1305                .find_map(|window| window.downcast::<SettingsWindow>())
1306                && cx.windows().len() == 1
1307            {
1308                cx.update_window(*existing_window, |_, window, _| {
1309                    window.remove_window();
1310                })
1311                .ok();
1312
1313                telemetry::event!("Settings Closed")
1314            }
1315        })
1316        .detach();
1317
1318        if let Some(app_state) = AppState::global(cx).upgrade() {
1319            for project in app_state
1320                .workspace_store
1321                .read(cx)
1322                .workspaces()
1323                .iter()
1324                .filter_map(|space| {
1325                    space
1326                        .read(cx)
1327                        .ok()
1328                        .map(|workspace| workspace.project().clone())
1329                })
1330                .collect::<Vec<_>>()
1331            {
1332                cx.observe_release_in(&project, window, |this, _, window, cx| {
1333                    this.fetch_files(window, cx)
1334                })
1335                .detach();
1336                cx.subscribe_in(&project, window, Self::handle_project_event)
1337                    .detach();
1338            }
1339
1340            for workspace in app_state
1341                .workspace_store
1342                .read(cx)
1343                .workspaces()
1344                .iter()
1345                .filter_map(|space| space.entity(cx).ok())
1346            {
1347                cx.observe_release_in(&workspace, window, |this, _, window, cx| {
1348                    this.fetch_files(window, cx)
1349                })
1350                .detach();
1351            }
1352        } else {
1353            log::error!("App state doesn't exist when creating a new settings window");
1354        }
1355
1356        let this_weak = cx.weak_entity();
1357        cx.observe_new::<Project>({
1358            let this_weak = this_weak.clone();
1359
1360            move |_, window, cx| {
1361                let project = cx.entity();
1362                let Some(window) = window else {
1363                    return;
1364                };
1365
1366                this_weak
1367                    .update(cx, |this, cx| {
1368                        this.fetch_files(window, cx);
1369                        cx.observe_release_in(&project, window, |_, _, window, cx| {
1370                            cx.defer_in(window, |this, window, cx| this.fetch_files(window, cx));
1371                        })
1372                        .detach();
1373
1374                        cx.subscribe_in(&project, window, Self::handle_project_event)
1375                            .detach();
1376                    })
1377                    .ok();
1378            }
1379        })
1380        .detach();
1381
1382        cx.observe_new::<Workspace>(move |_, window, cx| {
1383            let workspace = cx.entity();
1384            let Some(window) = window else {
1385                return;
1386            };
1387
1388            this_weak
1389                .update(cx, |this, cx| {
1390                    this.fetch_files(window, cx);
1391                    cx.observe_release_in(&workspace, window, |this, _, window, cx| {
1392                        this.fetch_files(window, cx)
1393                    })
1394                    .detach();
1395                })
1396                .ok();
1397        })
1398        .detach();
1399
1400        let title_bar = if !cfg!(target_os = "macos") {
1401            Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1402        } else {
1403            None
1404        };
1405
1406        // high overdraw value so the list scrollbar len doesn't change too much
1407        let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1408        list_state.set_scroll_handler(|_, _, _| {});
1409
1410        let mut this = Self {
1411            title_bar,
1412            original_window,
1413
1414            worktree_root_dirs: HashMap::default(),
1415            files: vec![],
1416
1417            current_file: current_file,
1418            pages: vec![],
1419            navbar_entries: vec![],
1420            navbar_entry: 0,
1421            navbar_scroll_handle: UniformListScrollHandle::default(),
1422            search_bar,
1423            search_task: None,
1424            filter_table: vec![],
1425            has_query: false,
1426            content_handles: vec![],
1427            sub_page_scroll_handle: ScrollHandle::new(),
1428            focus_handle: cx.focus_handle(),
1429            navbar_focus_handle: NonFocusableHandle::new(
1430                NAVBAR_CONTAINER_TAB_INDEX,
1431                false,
1432                window,
1433                cx,
1434            ),
1435            navbar_focus_subscriptions: vec![],
1436            content_focus_handle: NonFocusableHandle::new(
1437                CONTENT_CONTAINER_TAB_INDEX,
1438                false,
1439                window,
1440                cx,
1441            ),
1442            files_focus_handle: cx
1443                .focus_handle()
1444                .tab_index(HEADER_CONTAINER_TAB_INDEX)
1445                .tab_stop(false),
1446            search_index: None,
1447            shown_errors: HashSet::default(),
1448            list_state,
1449        };
1450
1451        this.fetch_files(window, cx);
1452        this.build_ui(window, cx);
1453        this.build_search_index();
1454
1455        this.search_bar.update(cx, |editor, cx| {
1456            editor.focus_handle(cx).focus(window);
1457        });
1458
1459        this
1460    }
1461
1462    fn handle_project_event(
1463        &mut self,
1464        _: &Entity<Project>,
1465        event: &project::Event,
1466        window: &mut Window,
1467        cx: &mut Context<SettingsWindow>,
1468    ) {
1469        match event {
1470            project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1471                cx.defer_in(window, |this, window, cx| {
1472                    this.fetch_files(window, cx);
1473                });
1474            }
1475            _ => {}
1476        }
1477    }
1478
1479    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1480        // We can only toggle root entries
1481        if !self.navbar_entries[nav_entry_index].is_root {
1482            return;
1483        }
1484
1485        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1486        *expanded = !*expanded;
1487        self.navbar_entry = nav_entry_index;
1488        self.reset_list_state();
1489    }
1490
1491    fn build_navbar(&mut self, cx: &App) {
1492        let mut navbar_entries = Vec::new();
1493
1494        for (page_index, page) in self.pages.iter().enumerate() {
1495            navbar_entries.push(NavBarEntry {
1496                title: page.title,
1497                is_root: true,
1498                expanded: false,
1499                page_index,
1500                item_index: None,
1501                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1502            });
1503
1504            for (item_index, item) in page.items.iter().enumerate() {
1505                let SettingsPageItem::SectionHeader(title) = item else {
1506                    continue;
1507                };
1508                navbar_entries.push(NavBarEntry {
1509                    title,
1510                    is_root: false,
1511                    expanded: false,
1512                    page_index,
1513                    item_index: Some(item_index),
1514                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1515                });
1516            }
1517        }
1518
1519        self.navbar_entries = navbar_entries;
1520    }
1521
1522    fn setup_navbar_focus_subscriptions(
1523        &mut self,
1524        window: &mut Window,
1525        cx: &mut Context<SettingsWindow>,
1526    ) {
1527        let mut focus_subscriptions = Vec::new();
1528
1529        for entry_index in 0..self.navbar_entries.len() {
1530            let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1531
1532            let subscription = cx.on_focus(
1533                &focus_handle,
1534                window,
1535                move |this: &mut SettingsWindow,
1536                      window: &mut Window,
1537                      cx: &mut Context<SettingsWindow>| {
1538                    this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1539                },
1540            );
1541            focus_subscriptions.push(subscription);
1542        }
1543        self.navbar_focus_subscriptions = focus_subscriptions;
1544    }
1545
1546    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1547        let mut index = 0;
1548        let entries = &self.navbar_entries;
1549        let search_matches = &self.filter_table;
1550        let has_query = self.has_query;
1551        std::iter::from_fn(move || {
1552            while index < entries.len() {
1553                let entry = &entries[index];
1554                let included_in_search = if let Some(item_index) = entry.item_index {
1555                    search_matches[entry.page_index][item_index]
1556                } else {
1557                    search_matches[entry.page_index].iter().any(|b| *b)
1558                        || search_matches[entry.page_index].is_empty()
1559                };
1560                if included_in_search {
1561                    break;
1562                }
1563                index += 1;
1564            }
1565            if index >= self.navbar_entries.len() {
1566                return None;
1567            }
1568            let entry = &entries[index];
1569            let entry_index = index;
1570
1571            index += 1;
1572            if entry.is_root && !entry.expanded && !has_query {
1573                while index < entries.len() {
1574                    if entries[index].is_root {
1575                        break;
1576                    }
1577                    index += 1;
1578                }
1579            }
1580
1581            return Some((entry_index, entry));
1582        })
1583    }
1584
1585    fn filter_matches_to_file(&mut self) {
1586        let current_file = self.current_file.mask();
1587        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1588            let mut header_index = 0;
1589            let mut any_found_since_last_header = true;
1590
1591            for (index, item) in page.items.iter().enumerate() {
1592                match item {
1593                    SettingsPageItem::SectionHeader(_) => {
1594                        if !any_found_since_last_header {
1595                            page_filter[header_index] = false;
1596                        }
1597                        header_index = index;
1598                        any_found_since_last_header = false;
1599                    }
1600                    SettingsPageItem::SettingItem(SettingItem { files, .. })
1601                    | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1602                    | SettingsPageItem::DynamicItem(DynamicItem {
1603                        discriminant: SettingItem { files, .. },
1604                        ..
1605                    }) => {
1606                        if !files.contains(current_file) {
1607                            page_filter[index] = false;
1608                        } else {
1609                            any_found_since_last_header = true;
1610                        }
1611                    }
1612                }
1613            }
1614            if let Some(last_header) = page_filter.get_mut(header_index)
1615                && !any_found_since_last_header
1616            {
1617                *last_header = false;
1618            }
1619        }
1620    }
1621
1622    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1623        self.search_task.take();
1624        let mut query = self.search_bar.read(cx).text(cx);
1625        if query.is_empty() || self.search_index.is_none() {
1626            for page in &mut self.filter_table {
1627                page.fill(true);
1628            }
1629            self.has_query = false;
1630            self.filter_matches_to_file();
1631            self.reset_list_state();
1632            cx.notify();
1633            return;
1634        }
1635
1636        let is_json_link_query;
1637        if query.starts_with("#") {
1638            query.remove(0);
1639            is_json_link_query = true;
1640        } else {
1641            is_json_link_query = false;
1642        }
1643
1644        let search_index = self.search_index.as_ref().unwrap().clone();
1645
1646        fn update_matches_inner(
1647            this: &mut SettingsWindow,
1648            search_index: &SearchIndex,
1649            match_indices: impl Iterator<Item = usize>,
1650            cx: &mut Context<SettingsWindow>,
1651        ) {
1652            for page in &mut this.filter_table {
1653                page.fill(false);
1654            }
1655
1656            for match_index in match_indices {
1657                let SearchKeyLUTEntry {
1658                    page_index,
1659                    header_index,
1660                    item_index,
1661                    ..
1662                } = search_index.key_lut[match_index];
1663                let page = &mut this.filter_table[page_index];
1664                page[header_index] = true;
1665                page[item_index] = true;
1666            }
1667            this.has_query = true;
1668            this.filter_matches_to_file();
1669            this.open_first_nav_page();
1670            this.reset_list_state();
1671            cx.notify();
1672        }
1673
1674        self.search_task = Some(cx.spawn(async move |this, cx| {
1675            if is_json_link_query {
1676                let mut indices = vec![];
1677                for (index, SearchKeyLUTEntry { json_path, .. }) in
1678                    search_index.key_lut.iter().enumerate()
1679                {
1680                    let Some(json_path) = json_path else {
1681                        continue;
1682                    };
1683
1684                    if let Some(post) = query.strip_prefix(json_path)
1685                        && (post.is_empty() || post.starts_with('.'))
1686                    {
1687                        indices.push(index);
1688                    }
1689                }
1690                if !indices.is_empty() {
1691                    this.update(cx, |this, cx| {
1692                        update_matches_inner(this, search_index.as_ref(), indices.into_iter(), cx);
1693                    })
1694                    .ok();
1695                    return;
1696                }
1697            }
1698            let bm25_task = cx.background_spawn({
1699                let search_index = search_index.clone();
1700                let max_results = search_index.key_lut.len();
1701                let query = query.clone();
1702                async move { search_index.bm25_engine.search(&query, max_results) }
1703            });
1704            let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1705            let fuzzy_search_task = fuzzy::match_strings(
1706                search_index.fuzzy_match_candidates.as_slice(),
1707                &query,
1708                false,
1709                true,
1710                search_index.fuzzy_match_candidates.len(),
1711                &cancel_flag,
1712                cx.background_executor().clone(),
1713            );
1714
1715            let fuzzy_matches = fuzzy_search_task.await;
1716
1717            _ = this
1718                .update(cx, |this, cx| {
1719                    // For tuning the score threshold
1720                    // for fuzzy_match in &fuzzy_matches {
1721                    //     let SearchItemKey {
1722                    //         page_index,
1723                    //         header_index,
1724                    //         item_index,
1725                    //     } = search_index.key_lut[fuzzy_match.candidate_id];
1726                    //     let SettingsPageItem::SectionHeader(header) =
1727                    //         this.pages[page_index].items[header_index]
1728                    //     else {
1729                    //         continue;
1730                    //     };
1731                    //     let SettingsPageItem::SettingItem(SettingItem {
1732                    //         title, description, ..
1733                    //     }) = this.pages[page_index].items[item_index]
1734                    //     else {
1735                    //         continue;
1736                    //     };
1737                    //     let score = fuzzy_match.score;
1738                    //     eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1739                    // }
1740                    update_matches_inner(
1741                        this,
1742                        search_index.as_ref(),
1743                        fuzzy_matches
1744                            .into_iter()
1745                            // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1746                            // flexible enough to catch misspellings and <4 letter queries
1747                            // More flexible is good for us here because fuzzy matches will only be used for things that don't
1748                            // match using bm25
1749                            .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1750                            .map(|fuzzy_match| fuzzy_match.candidate_id),
1751                        cx,
1752                    );
1753                })
1754                .ok();
1755
1756            let bm25_matches = bm25_task.await;
1757
1758            _ = this
1759                .update(cx, |this, cx| {
1760                    if bm25_matches.is_empty() {
1761                        return;
1762                    }
1763                    update_matches_inner(
1764                        this,
1765                        search_index.as_ref(),
1766                        bm25_matches
1767                            .into_iter()
1768                            .map(|bm25_match| bm25_match.document.id),
1769                        cx,
1770                    );
1771                })
1772                .ok();
1773
1774            cx.background_executor().timer(Duration::from_secs(1)).await;
1775            telemetry::event!("Settings Searched", query = query)
1776        }));
1777    }
1778
1779    fn build_filter_table(&mut self) {
1780        self.filter_table = self
1781            .pages
1782            .iter()
1783            .map(|page| vec![true; page.items.len()])
1784            .collect::<Vec<_>>();
1785    }
1786
1787    fn build_search_index(&mut self) {
1788        let mut key_lut: Vec<SearchKeyLUTEntry> = vec![];
1789        let mut documents = Vec::default();
1790        let mut fuzzy_match_candidates = Vec::default();
1791
1792        fn push_candidates(
1793            fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1794            key_index: usize,
1795            input: &str,
1796        ) {
1797            for word in input.split_ascii_whitespace() {
1798                fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1799            }
1800        }
1801
1802        // PERF: We are currently searching all items even in project files
1803        // where many settings are filtered out, using the logic in filter_matches_to_file
1804        // we could only search relevant items based on the current file
1805        for (page_index, page) in self.pages.iter().enumerate() {
1806            let mut header_index = 0;
1807            let mut header_str = "";
1808            for (item_index, item) in page.items.iter().enumerate() {
1809                let key_index = key_lut.len();
1810                let mut json_path = None;
1811                match item {
1812                    SettingsPageItem::DynamicItem(DynamicItem {
1813                        discriminant: item, ..
1814                    })
1815                    | SettingsPageItem::SettingItem(item) => {
1816                        json_path = item
1817                            .field
1818                            .json_path()
1819                            .map(|path| path.trim_end_matches('$'));
1820                        documents.push(bm25::Document {
1821                            id: key_index,
1822                            contents: [page.title, header_str, item.title, item.description]
1823                                .join("\n"),
1824                        });
1825                        push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1826                        push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1827                    }
1828                    SettingsPageItem::SectionHeader(header) => {
1829                        documents.push(bm25::Document {
1830                            id: key_index,
1831                            contents: header.to_string(),
1832                        });
1833                        push_candidates(&mut fuzzy_match_candidates, key_index, header);
1834                        header_index = item_index;
1835                        header_str = *header;
1836                    }
1837                    SettingsPageItem::SubPageLink(sub_page_link) => {
1838                        documents.push(bm25::Document {
1839                            id: key_index,
1840                            contents: [page.title, header_str, sub_page_link.title.as_ref()]
1841                                .join("\n"),
1842                        });
1843                        push_candidates(
1844                            &mut fuzzy_match_candidates,
1845                            key_index,
1846                            sub_page_link.title.as_ref(),
1847                        );
1848                    }
1849                }
1850                push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1851                push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1852
1853                key_lut.push(SearchKeyLUTEntry {
1854                    page_index,
1855                    header_index,
1856                    item_index,
1857                    json_path,
1858                });
1859            }
1860        }
1861        let engine =
1862            bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1863        self.search_index = Some(Arc::new(SearchIndex {
1864            bm25_engine: engine,
1865            key_lut,
1866            fuzzy_match_candidates,
1867        }));
1868    }
1869
1870    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1871        self.content_handles = self
1872            .pages
1873            .iter()
1874            .map(|page| {
1875                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1876                    .take(page.items.len())
1877                    .collect()
1878            })
1879            .collect::<Vec<_>>();
1880    }
1881
1882    fn reset_list_state(&mut self) {
1883        // plus one for the title
1884        let mut visible_items_count = self.visible_page_items().count();
1885
1886        if visible_items_count > 0 {
1887            // show page title if page is non empty
1888            visible_items_count += 1;
1889        }
1890
1891        self.list_state.reset(visible_items_count);
1892    }
1893
1894    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1895        if self.pages.is_empty() {
1896            self.pages = page_data::settings_data(cx);
1897            self.build_navbar(cx);
1898            self.setup_navbar_focus_subscriptions(window, cx);
1899            self.build_content_handles(window, cx);
1900        }
1901        sub_page_stack_mut().clear();
1902        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1903        self.build_filter_table();
1904        self.reset_list_state();
1905        self.update_matches(cx);
1906
1907        cx.notify();
1908    }
1909
1910    #[track_caller]
1911    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1912        self.worktree_root_dirs.clear();
1913        let prev_files = self.files.clone();
1914        let settings_store = cx.global::<SettingsStore>();
1915        let mut ui_files = vec![];
1916        let mut all_files = settings_store.get_all_files();
1917        if !all_files.contains(&settings::SettingsFile::User) {
1918            all_files.push(settings::SettingsFile::User);
1919        }
1920        for file in all_files {
1921            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1922                continue;
1923            };
1924            if settings_ui_file.is_server() {
1925                continue;
1926            }
1927
1928            if let Some(worktree_id) = settings_ui_file.worktree_id() {
1929                let directory_name = all_projects(cx)
1930                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1931                    .and_then(|worktree| worktree.read(cx).root_dir())
1932                    .and_then(|root_dir| {
1933                        root_dir
1934                            .file_name()
1935                            .map(|os_string| os_string.to_string_lossy().to_string())
1936                    });
1937
1938                let Some(directory_name) = directory_name else {
1939                    log::error!(
1940                        "No directory name found for settings file at worktree ID: {}",
1941                        worktree_id
1942                    );
1943                    continue;
1944                };
1945
1946                self.worktree_root_dirs.insert(worktree_id, directory_name);
1947            }
1948
1949            let focus_handle = prev_files
1950                .iter()
1951                .find_map(|(prev_file, handle)| {
1952                    (prev_file == &settings_ui_file).then(|| handle.clone())
1953                })
1954                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1955            ui_files.push((settings_ui_file, focus_handle));
1956        }
1957
1958        ui_files.reverse();
1959
1960        let mut missing_worktrees = Vec::new();
1961
1962        for worktree in all_projects(cx)
1963            .flat_map(|project| project.read(cx).visible_worktrees(cx))
1964            .filter(|tree| !self.worktree_root_dirs.contains_key(&tree.read(cx).id()))
1965        {
1966            let worktree = worktree.read(cx);
1967            let worktree_id = worktree.id();
1968            let Some(directory_name) = worktree.root_dir().and_then(|file| {
1969                file.file_name()
1970                    .map(|os_string| os_string.to_string_lossy().to_string())
1971            }) else {
1972                continue;
1973            };
1974
1975            missing_worktrees.push((worktree_id, directory_name.clone()));
1976            let path = RelPath::empty().to_owned().into_arc();
1977
1978            let settings_ui_file = SettingsUiFile::Project((worktree_id, path));
1979
1980            let focus_handle = prev_files
1981                .iter()
1982                .find_map(|(prev_file, handle)| {
1983                    (prev_file == &settings_ui_file).then(|| handle.clone())
1984                })
1985                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1986
1987            ui_files.push((settings_ui_file, focus_handle));
1988        }
1989
1990        self.worktree_root_dirs.extend(missing_worktrees);
1991
1992        self.files = ui_files;
1993        let current_file_still_exists = self
1994            .files
1995            .iter()
1996            .any(|(file, _)| file == &self.current_file);
1997        if !current_file_still_exists {
1998            self.change_file(0, window, cx);
1999        }
2000    }
2001
2002    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
2003        if !self.is_nav_entry_visible(navbar_entry) {
2004            self.open_first_nav_page();
2005        }
2006
2007        let is_new_page = self.navbar_entries[self.navbar_entry].page_index
2008            != self.navbar_entries[navbar_entry].page_index;
2009        self.navbar_entry = navbar_entry;
2010
2011        // We only need to reset visible items when updating matches
2012        // and selecting a new page
2013        if is_new_page {
2014            self.reset_list_state();
2015        }
2016
2017        sub_page_stack_mut().clear();
2018    }
2019
2020    fn open_first_nav_page(&mut self) {
2021        let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
2022        else {
2023            return;
2024        };
2025        self.open_navbar_entry_page(first_navbar_entry_index);
2026    }
2027
2028    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
2029        if ix >= self.files.len() {
2030            self.current_file = SettingsUiFile::User;
2031            self.build_ui(window, cx);
2032            return;
2033        }
2034
2035        if self.files[ix].0 == self.current_file {
2036            return;
2037        }
2038        self.current_file = self.files[ix].0.clone();
2039
2040        if let SettingsUiFile::Project((_, _)) = &self.current_file {
2041            telemetry::event!("Setting Project Clicked");
2042        }
2043
2044        self.build_ui(window, cx);
2045
2046        if self
2047            .visible_navbar_entries()
2048            .any(|(index, _)| index == self.navbar_entry)
2049        {
2050            self.open_and_scroll_to_navbar_entry(self.navbar_entry, None, true, window, cx);
2051        } else {
2052            self.open_first_nav_page();
2053        };
2054    }
2055
2056    fn render_files_header(
2057        &self,
2058        window: &mut Window,
2059        cx: &mut Context<SettingsWindow>,
2060    ) -> impl IntoElement {
2061        static OVERFLOW_LIMIT: usize = 1;
2062
2063        let file_button =
2064            |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
2065                Button::new(
2066                    ix,
2067                    self.display_name(&file)
2068                        .expect("Files should always have a name"),
2069                )
2070                .toggle_state(file == &self.current_file)
2071                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
2072                .track_focus(focus_handle)
2073                .on_click(cx.listener({
2074                    let focus_handle = focus_handle.clone();
2075                    move |this, _: &gpui::ClickEvent, window, cx| {
2076                        this.change_file(ix, window, cx);
2077                        focus_handle.focus(window);
2078                    }
2079                }))
2080            };
2081
2082        let this = cx.entity();
2083
2084        let selected_file_ix = self
2085            .files
2086            .iter()
2087            .enumerate()
2088            .skip(OVERFLOW_LIMIT)
2089            .find_map(|(ix, (file, _))| {
2090                if file == &self.current_file {
2091                    Some(ix)
2092                } else {
2093                    None
2094                }
2095            })
2096            .unwrap_or(OVERFLOW_LIMIT);
2097        let edit_in_json_id = SharedString::new(format!("edit-in-json-{}", selected_file_ix));
2098
2099        h_flex()
2100            .w_full()
2101            .gap_1()
2102            .justify_between()
2103            .track_focus(&self.files_focus_handle)
2104            .tab_group()
2105            .tab_index(HEADER_GROUP_TAB_INDEX)
2106            .child(
2107                h_flex()
2108                    .gap_1()
2109                    .children(
2110                        self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
2111                            |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
2112                        ),
2113                    )
2114                    .when(self.files.len() > OVERFLOW_LIMIT, |div| {
2115                        let (file, focus_handle) = &self.files[selected_file_ix];
2116
2117                        div.child(file_button(selected_file_ix, file, focus_handle, cx))
2118                            .when(self.files.len() > OVERFLOW_LIMIT + 1, |div| {
2119                                div.child(
2120                                    DropdownMenu::new(
2121                                        "more-files",
2122                                        format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
2123                                        ContextMenu::build(window, cx, move |mut menu, _, _| {
2124                                            for (mut ix, (file, focus_handle)) in self
2125                                                .files
2126                                                .iter()
2127                                                .enumerate()
2128                                                .skip(OVERFLOW_LIMIT + 1)
2129                                            {
2130                                                let (display_name, focus_handle) =
2131                                                    if selected_file_ix == ix {
2132                                                        ix = OVERFLOW_LIMIT;
2133                                                        (
2134                                                            self.display_name(&self.files[ix].0),
2135                                                            self.files[ix].1.clone(),
2136                                                        )
2137                                                    } else {
2138                                                        (
2139                                                            self.display_name(&file),
2140                                                            focus_handle.clone(),
2141                                                        )
2142                                                    };
2143
2144                                                menu = menu.entry(
2145                                                    display_name
2146                                                        .expect("Files should always have a name"),
2147                                                    None,
2148                                                    {
2149                                                        let this = this.clone();
2150                                                        move |window, cx| {
2151                                                            this.update(cx, |this, cx| {
2152                                                                this.change_file(ix, window, cx);
2153                                                            });
2154                                                            focus_handle.focus(window);
2155                                                        }
2156                                                    },
2157                                                );
2158                                            }
2159
2160                                            menu
2161                                        }),
2162                                    )
2163                                    .style(DropdownStyle::Subtle)
2164                                    .trigger_tooltip(Tooltip::text("View Other Projects"))
2165                                    .trigger_icon(IconName::ChevronDown)
2166                                    .attach(gpui::Corner::BottomLeft)
2167                                    .offset(gpui::Point {
2168                                        x: px(0.0),
2169                                        y: px(2.0),
2170                                    })
2171                                    .tab_index(0),
2172                                )
2173                            })
2174                    }),
2175            )
2176            .child(
2177                Button::new(edit_in_json_id, "Edit in settings.json")
2178                    .tab_index(0_isize)
2179                    .style(ButtonStyle::OutlinedGhost)
2180                    .tooltip(Tooltip::for_action_title_in(
2181                        "Edit in settings.json",
2182                        &OpenCurrentFile,
2183                        &self.focus_handle,
2184                    ))
2185                    .on_click(cx.listener(|this, _, window, cx| {
2186                        this.open_current_settings_file(window, cx);
2187                    })),
2188            )
2189    }
2190
2191    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
2192        match file {
2193            SettingsUiFile::User => Some("User".to_string()),
2194            SettingsUiFile::Project((worktree_id, path)) => self
2195                .worktree_root_dirs
2196                .get(&worktree_id)
2197                .map(|directory_name| {
2198                    let path_style = PathStyle::local();
2199                    if path.is_empty() {
2200                        directory_name.clone()
2201                    } else {
2202                        format!(
2203                            "{}{}{}",
2204                            directory_name,
2205                            path_style.primary_separator(),
2206                            path.display(path_style)
2207                        )
2208                    }
2209                }),
2210            SettingsUiFile::Server(file) => Some(file.to_string()),
2211        }
2212    }
2213
2214    // TODO:
2215    //  Reconsider this after preview launch
2216    // fn file_location_str(&self) -> String {
2217    //     match &self.current_file {
2218    //         SettingsUiFile::User => "settings.json".to_string(),
2219    //         SettingsUiFile::Project((worktree_id, path)) => self
2220    //             .worktree_root_dirs
2221    //             .get(&worktree_id)
2222    //             .map(|directory_name| {
2223    //                 let path_style = PathStyle::local();
2224    //                 let file_path = path.join(paths::local_settings_file_relative_path());
2225    //                 format!(
2226    //                     "{}{}{}",
2227    //                     directory_name,
2228    //                     path_style.separator(),
2229    //                     file_path.display(path_style)
2230    //                 )
2231    //             })
2232    //             .expect("Current file should always be present in root dir map"),
2233    //         SettingsUiFile::Server(file) => file.to_string(),
2234    //     }
2235    // }
2236
2237    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2238        h_flex()
2239            .py_1()
2240            .px_1p5()
2241            .mb_3()
2242            .gap_1p5()
2243            .rounded_sm()
2244            .bg(cx.theme().colors().editor_background)
2245            .border_1()
2246            .border_color(cx.theme().colors().border)
2247            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2248            .child(self.search_bar.clone())
2249    }
2250
2251    fn render_nav(
2252        &self,
2253        window: &mut Window,
2254        cx: &mut Context<SettingsWindow>,
2255    ) -> impl IntoElement {
2256        let visible_count = self.visible_navbar_entries().count();
2257
2258        let focus_keybind_label = if self
2259            .navbar_focus_handle
2260            .read(cx)
2261            .handle
2262            .contains_focused(window, cx)
2263            || self
2264                .visible_navbar_entries()
2265                .any(|(_, entry)| entry.focus_handle.is_focused(window))
2266        {
2267            "Focus Content"
2268        } else {
2269            "Focus Navbar"
2270        };
2271
2272        let mut key_context = KeyContext::new_with_defaults();
2273        key_context.add("NavigationMenu");
2274        key_context.add("menu");
2275        if self.search_bar.focus_handle(cx).is_focused(window) {
2276            key_context.add("search");
2277        }
2278
2279        v_flex()
2280            .key_context(key_context)
2281            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2282                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2283                    return;
2284                };
2285                let focused_entry_parent = this.root_entry_containing(focused_entry);
2286                if this.navbar_entries[focused_entry_parent].expanded {
2287                    this.toggle_navbar_entry(focused_entry_parent);
2288                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
2289                }
2290                cx.notify();
2291            }))
2292            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2293                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2294                    return;
2295                };
2296                if !this.navbar_entries[focused_entry].is_root {
2297                    return;
2298                }
2299                if !this.navbar_entries[focused_entry].expanded {
2300                    this.toggle_navbar_entry(focused_entry);
2301                }
2302                cx.notify();
2303            }))
2304            .on_action(
2305                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2306                    let entry_index = this
2307                        .focused_nav_entry(window, cx)
2308                        .unwrap_or(this.navbar_entry);
2309                    let mut root_index = None;
2310                    for (index, entry) in this.visible_navbar_entries() {
2311                        if index >= entry_index {
2312                            break;
2313                        }
2314                        if entry.is_root {
2315                            root_index = Some(index);
2316                        }
2317                    }
2318                    let Some(previous_root_index) = root_index else {
2319                        return;
2320                    };
2321                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2322                }),
2323            )
2324            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2325                let entry_index = this
2326                    .focused_nav_entry(window, cx)
2327                    .unwrap_or(this.navbar_entry);
2328                let mut root_index = None;
2329                for (index, entry) in this.visible_navbar_entries() {
2330                    if index <= entry_index {
2331                        continue;
2332                    }
2333                    if entry.is_root {
2334                        root_index = Some(index);
2335                        break;
2336                    }
2337                }
2338                let Some(next_root_index) = root_index else {
2339                    return;
2340                };
2341                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2342            }))
2343            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2344                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2345                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2346                }
2347            }))
2348            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2349                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2350                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2351                }
2352            }))
2353            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2354                let entry_index = this
2355                    .focused_nav_entry(window, cx)
2356                    .unwrap_or(this.navbar_entry);
2357                let mut next_index = None;
2358                for (index, _) in this.visible_navbar_entries() {
2359                    if index > entry_index {
2360                        next_index = Some(index);
2361                        break;
2362                    }
2363                }
2364                let Some(next_entry_index) = next_index else {
2365                    return;
2366                };
2367                this.open_and_scroll_to_navbar_entry(
2368                    next_entry_index,
2369                    Some(gpui::ScrollStrategy::Bottom),
2370                    false,
2371                    window,
2372                    cx,
2373                );
2374            }))
2375            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2376                let entry_index = this
2377                    .focused_nav_entry(window, cx)
2378                    .unwrap_or(this.navbar_entry);
2379                let mut prev_index = None;
2380                for (index, _) in this.visible_navbar_entries() {
2381                    if index >= entry_index {
2382                        break;
2383                    }
2384                    prev_index = Some(index);
2385                }
2386                let Some(prev_entry_index) = prev_index else {
2387                    return;
2388                };
2389                this.open_and_scroll_to_navbar_entry(
2390                    prev_entry_index,
2391                    Some(gpui::ScrollStrategy::Top),
2392                    false,
2393                    window,
2394                    cx,
2395                );
2396            }))
2397            .w_56()
2398            .h_full()
2399            .p_2p5()
2400            .when(cfg!(target_os = "macos"), |this| this.pt_10())
2401            .flex_none()
2402            .border_r_1()
2403            .border_color(cx.theme().colors().border)
2404            .bg(cx.theme().colors().panel_background)
2405            .child(self.render_search(window, cx))
2406            .child(
2407                v_flex()
2408                    .flex_1()
2409                    .overflow_hidden()
2410                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2411                    .tab_group()
2412                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
2413                    .child(
2414                        uniform_list(
2415                            "settings-ui-nav-bar",
2416                            visible_count + 1,
2417                            cx.processor(move |this, range: Range<usize>, _, cx| {
2418                                this.visible_navbar_entries()
2419                                    .skip(range.start.saturating_sub(1))
2420                                    .take(range.len())
2421                                    .map(|(entry_index, entry)| {
2422                                        TreeViewItem::new(
2423                                            ("settings-ui-navbar-entry", entry_index),
2424                                            entry.title,
2425                                        )
2426                                        .track_focus(&entry.focus_handle)
2427                                        .root_item(entry.is_root)
2428                                        .toggle_state(this.is_navbar_entry_selected(entry_index))
2429                                        .when(entry.is_root, |item| {
2430                                            item.expanded(entry.expanded || this.has_query)
2431                                                .on_toggle(cx.listener(
2432                                                    move |this, _, window, cx| {
2433                                                        this.toggle_navbar_entry(entry_index);
2434                                                        window.focus(
2435                                                            &this.navbar_entries[entry_index]
2436                                                                .focus_handle,
2437                                                        );
2438                                                        cx.notify();
2439                                                    },
2440                                                ))
2441                                        })
2442                                        .on_click({
2443                                            let category = this.pages[entry.page_index].title;
2444                                            let subcategory =
2445                                                (!entry.is_root).then_some(entry.title);
2446
2447                                            cx.listener(move |this, _, window, cx| {
2448                                                telemetry::event!(
2449                                                    "Settings Navigation Clicked",
2450                                                    category = category,
2451                                                    subcategory = subcategory
2452                                                );
2453
2454                                                this.open_and_scroll_to_navbar_entry(
2455                                                    entry_index,
2456                                                    None,
2457                                                    true,
2458                                                    window,
2459                                                    cx,
2460                                                );
2461                                            })
2462                                        })
2463                                    })
2464                                    .collect()
2465                            }),
2466                        )
2467                        .size_full()
2468                        .track_scroll(&self.navbar_scroll_handle),
2469                    )
2470                    .vertical_scrollbar_for(&self.navbar_scroll_handle, window, cx),
2471            )
2472            .child(
2473                h_flex()
2474                    .w_full()
2475                    .h_8()
2476                    .p_2()
2477                    .pb_0p5()
2478                    .flex_shrink_0()
2479                    .border_t_1()
2480                    .border_color(cx.theme().colors().border_variant)
2481                    .child(
2482                        KeybindingHint::new(
2483                            KeyBinding::for_action_in(
2484                                &ToggleFocusNav,
2485                                &self.navbar_focus_handle.focus_handle(cx),
2486                                cx,
2487                            ),
2488                            cx.theme().colors().surface_background.opacity(0.5),
2489                        )
2490                        .suffix(focus_keybind_label),
2491                    ),
2492            )
2493    }
2494
2495    fn open_and_scroll_to_navbar_entry(
2496        &mut self,
2497        navbar_entry_index: usize,
2498        scroll_strategy: Option<gpui::ScrollStrategy>,
2499        focus_content: bool,
2500        window: &mut Window,
2501        cx: &mut Context<Self>,
2502    ) {
2503        self.open_navbar_entry_page(navbar_entry_index);
2504        cx.notify();
2505
2506        let mut handle_to_focus = None;
2507
2508        if self.navbar_entries[navbar_entry_index].is_root
2509            || !self.is_nav_entry_visible(navbar_entry_index)
2510        {
2511            self.sub_page_scroll_handle
2512                .set_offset(point(px(0.), px(0.)));
2513            if focus_content {
2514                let Some(first_item_index) =
2515                    self.visible_page_items().next().map(|(index, _)| index)
2516                else {
2517                    return;
2518                };
2519                handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2520            } else if !self.is_nav_entry_visible(navbar_entry_index) {
2521                let Some(first_visible_nav_entry_index) =
2522                    self.visible_navbar_entries().next().map(|(index, _)| index)
2523                else {
2524                    return;
2525                };
2526                self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2527            } else {
2528                handle_to_focus =
2529                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2530            }
2531        } else {
2532            let entry_item_index = self.navbar_entries[navbar_entry_index]
2533                .item_index
2534                .expect("Non-root items should have an item index");
2535            self.scroll_to_content_item(entry_item_index, window, cx);
2536            if focus_content {
2537                handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2538            } else {
2539                handle_to_focus =
2540                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2541            }
2542        }
2543
2544        if let Some(scroll_strategy) = scroll_strategy
2545            && let Some(logical_entry_index) = self
2546                .visible_navbar_entries()
2547                .into_iter()
2548                .position(|(index, _)| index == navbar_entry_index)
2549        {
2550            self.navbar_scroll_handle
2551                .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2552        }
2553
2554        // Page scroll handle updates the active item index
2555        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2556        // The call after that updates the offset of the scroll handle. So to
2557        // ensure the scroll handle doesn't lag behind we need to render three frames
2558        // back to back.
2559        cx.on_next_frame(window, move |_, window, cx| {
2560            if let Some(handle) = handle_to_focus.as_ref() {
2561                window.focus(handle);
2562            }
2563
2564            cx.on_next_frame(window, |_, _, cx| {
2565                cx.notify();
2566            });
2567            cx.notify();
2568        });
2569        cx.notify();
2570    }
2571
2572    fn scroll_to_content_item(
2573        &self,
2574        content_item_index: usize,
2575        _window: &mut Window,
2576        cx: &mut Context<Self>,
2577    ) {
2578        let index = self
2579            .visible_page_items()
2580            .position(|(index, _)| index == content_item_index)
2581            .unwrap_or(0);
2582        if index == 0 {
2583            self.sub_page_scroll_handle
2584                .set_offset(point(px(0.), px(0.)));
2585            self.list_state.scroll_to(gpui::ListOffset {
2586                item_ix: 0,
2587                offset_in_item: px(0.),
2588            });
2589            return;
2590        }
2591        self.list_state.scroll_to(gpui::ListOffset {
2592            item_ix: index + 1,
2593            offset_in_item: px(0.),
2594        });
2595        cx.notify();
2596    }
2597
2598    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2599        self.visible_navbar_entries()
2600            .any(|(index, _)| index == nav_entry_index)
2601    }
2602
2603    fn focus_and_scroll_to_first_visible_nav_entry(
2604        &self,
2605        window: &mut Window,
2606        cx: &mut Context<Self>,
2607    ) {
2608        if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2609        {
2610            self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2611        }
2612    }
2613
2614    fn focus_and_scroll_to_nav_entry(
2615        &self,
2616        nav_entry_index: usize,
2617        window: &mut Window,
2618        cx: &mut Context<Self>,
2619    ) {
2620        let Some(position) = self
2621            .visible_navbar_entries()
2622            .position(|(index, _)| index == nav_entry_index)
2623        else {
2624            return;
2625        };
2626        self.navbar_scroll_handle
2627            .scroll_to_item(position, gpui::ScrollStrategy::Top);
2628        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2629        cx.notify();
2630    }
2631
2632    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2633        let page_idx = self.current_page_index();
2634
2635        self.current_page()
2636            .items
2637            .iter()
2638            .enumerate()
2639            .filter_map(move |(item_index, item)| {
2640                self.filter_table[page_idx][item_index].then_some((item_index, item))
2641            })
2642    }
2643
2644    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2645        let mut items = vec![];
2646        items.push(self.current_page().title.into());
2647        items.extend(
2648            sub_page_stack()
2649                .iter()
2650                .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2651        );
2652
2653        let last = items.pop().unwrap();
2654        h_flex()
2655            .gap_1()
2656            .children(
2657                items
2658                    .into_iter()
2659                    .flat_map(|item| [item, "/".into()])
2660                    .map(|item| Label::new(item).color(Color::Muted)),
2661            )
2662            .child(Label::new(last))
2663    }
2664
2665    fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2666        v_flex()
2667            .size_full()
2668            .items_center()
2669            .justify_center()
2670            .gap_1()
2671            .child(Label::new("No Results"))
2672            .child(
2673                Label::new(search_query)
2674                    .size(LabelSize::Small)
2675                    .color(Color::Muted),
2676            )
2677    }
2678
2679    fn render_page_items(
2680        &mut self,
2681        page_index: usize,
2682        _window: &mut Window,
2683        cx: &mut Context<SettingsWindow>,
2684    ) -> impl IntoElement {
2685        let mut page_content = v_flex().id("settings-ui-page").size_full();
2686
2687        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2688        let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2689
2690        if has_no_results {
2691            let search_query = self.search_bar.read(cx).text(cx);
2692            page_content = page_content.child(
2693                self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2694            )
2695        } else {
2696            let last_non_header_index = self
2697                .visible_page_items()
2698                .filter_map(|(index, item)| {
2699                    (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2700                })
2701                .last();
2702
2703            let root_nav_label = self
2704                .navbar_entries
2705                .iter()
2706                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2707                .map(|entry| entry.title);
2708
2709            let list_content = list(
2710                self.list_state.clone(),
2711                cx.processor(move |this, index, window, cx| {
2712                    if index == 0 {
2713                        return div()
2714                            .px_8()
2715                            .when(sub_page_stack().is_empty(), |this| {
2716                                this.when_some(root_nav_label, |this, title| {
2717                                    this.child(
2718                                        Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2719                                    )
2720                                })
2721                            })
2722                            .into_any_element();
2723                    }
2724
2725                    let mut visible_items = this.visible_page_items();
2726                    let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2727                        return gpui::Empty.into_any_element();
2728                    };
2729
2730                    let no_bottom_border = visible_items
2731                        .next()
2732                        .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2733                        .unwrap_or(false);
2734
2735                    let is_last = Some(actual_item_index) == last_non_header_index;
2736
2737                    let item_focus_handle =
2738                        this.content_handles[page_index][actual_item_index].focus_handle(cx);
2739
2740                    v_flex()
2741                        .id(("settings-page-item", actual_item_index))
2742                        .track_focus(&item_focus_handle)
2743                        .w_full()
2744                        .min_w_0()
2745                        .child(item.render(
2746                            this,
2747                            actual_item_index,
2748                            no_bottom_border || is_last,
2749                            window,
2750                            cx,
2751                        ))
2752                        .into_any_element()
2753                }),
2754            );
2755
2756            page_content = page_content.child(list_content.size_full())
2757        }
2758        page_content
2759    }
2760
2761    fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2762        &self,
2763        items: Items,
2764        page_index: Option<usize>,
2765        window: &mut Window,
2766        cx: &mut Context<SettingsWindow>,
2767    ) -> impl IntoElement {
2768        let mut page_content = v_flex()
2769            .id("settings-ui-page")
2770            .size_full()
2771            .overflow_y_scroll()
2772            .track_scroll(&self.sub_page_scroll_handle);
2773
2774        let items: Vec<_> = items.collect();
2775        let items_len = items.len();
2776        let mut section_header = None;
2777
2778        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2779        let has_no_results = items_len == 0 && has_active_search;
2780
2781        if has_no_results {
2782            let search_query = self.search_bar.read(cx).text(cx);
2783            page_content = page_content.child(
2784                self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2785            )
2786        } else {
2787            let last_non_header_index = items
2788                .iter()
2789                .enumerate()
2790                .rev()
2791                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2792                .map(|(index, _)| index);
2793
2794            let root_nav_label = self
2795                .navbar_entries
2796                .iter()
2797                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2798                .map(|entry| entry.title);
2799
2800            page_content = page_content
2801                .when(sub_page_stack().is_empty(), |this| {
2802                    this.when_some(root_nav_label, |this, title| {
2803                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2804                    })
2805                })
2806                .children(items.clone().into_iter().enumerate().map(
2807                    |(index, (actual_item_index, item))| {
2808                        let no_bottom_border = items
2809                            .get(index + 1)
2810                            .map(|(_, next_item)| {
2811                                matches!(next_item, SettingsPageItem::SectionHeader(_))
2812                            })
2813                            .unwrap_or(false);
2814                        let is_last = Some(index) == last_non_header_index;
2815
2816                        if let SettingsPageItem::SectionHeader(header) = item {
2817                            section_header = Some(*header);
2818                        }
2819                        v_flex()
2820                            .w_full()
2821                            .min_w_0()
2822                            .id(("settings-page-item", actual_item_index))
2823                            .when_some(page_index, |element, page_index| {
2824                                element.track_focus(
2825                                    &self.content_handles[page_index][actual_item_index]
2826                                        .focus_handle(cx),
2827                                )
2828                            })
2829                            .child(item.render(
2830                                self,
2831                                actual_item_index,
2832                                no_bottom_border || is_last,
2833                                window,
2834                                cx,
2835                            ))
2836                    },
2837                ))
2838        }
2839        page_content
2840    }
2841
2842    fn render_page(
2843        &mut self,
2844        window: &mut Window,
2845        cx: &mut Context<SettingsWindow>,
2846    ) -> impl IntoElement {
2847        let page_header;
2848        let page_content;
2849
2850        if sub_page_stack().is_empty() {
2851            page_header = self.render_files_header(window, cx).into_any_element();
2852
2853            page_content = self
2854                .render_page_items(self.current_page_index(), window, cx)
2855                .into_any_element();
2856        } else {
2857            page_header = h_flex()
2858                .w_full()
2859                .justify_between()
2860                .child(
2861                    h_flex()
2862                        .ml_neg_1p5()
2863                        .gap_1()
2864                        .child(
2865                            IconButton::new("back-btn", IconName::ArrowLeft)
2866                                .icon_size(IconSize::Small)
2867                                .shape(IconButtonShape::Square)
2868                                .on_click(cx.listener(|this, _, _, cx| {
2869                                    this.pop_sub_page(cx);
2870                                })),
2871                        )
2872                        .child(self.render_sub_page_breadcrumbs()),
2873                )
2874                .child(
2875                    Button::new("open-in-settings-file", "Edit in settings.json")
2876                        .tab_index(0_isize)
2877                        .style(ButtonStyle::OutlinedGhost)
2878                        .tooltip(Tooltip::for_action_title_in(
2879                            "Edit in settings.json",
2880                            &OpenCurrentFile,
2881                            &self.focus_handle,
2882                        ))
2883                        .on_click(cx.listener(|this, _, window, cx| {
2884                            this.open_current_settings_file(window, cx);
2885                        })),
2886                )
2887                .into_any_element();
2888
2889            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2890            page_content = (active_page_render_fn)(self, window, cx);
2891        }
2892
2893        let mut warning_banner = gpui::Empty.into_any_element();
2894        if let Some(error) =
2895            SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2896        {
2897            fn banner(
2898                label: &'static str,
2899                error: String,
2900                shown_errors: &mut HashSet<String>,
2901                cx: &mut Context<SettingsWindow>,
2902            ) -> impl IntoElement {
2903                if shown_errors.insert(error.clone()) {
2904                    telemetry::event!("Settings Error Shown", label = label, error = &error);
2905                }
2906                Banner::new()
2907                    .severity(Severity::Warning)
2908                    .child(
2909                        v_flex()
2910                            .my_0p5()
2911                            .gap_0p5()
2912                            .child(Label::new(label))
2913                            .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
2914                    )
2915                    .action_slot(
2916                        div().pr_1().pb_1().child(
2917                            Button::new("fix-in-json", "Fix in settings.json")
2918                                .tab_index(0_isize)
2919                                .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2920                                .on_click(cx.listener(|this, _, window, cx| {
2921                                    this.open_current_settings_file(window, cx);
2922                                })),
2923                        ),
2924                    )
2925            }
2926
2927            let parse_error = error.parse_error();
2928            let parse_failed = parse_error.is_some();
2929
2930            warning_banner = v_flex()
2931                .gap_2()
2932                .when_some(parse_error, |this, err| {
2933                    this.child(banner(
2934                        "Failed to load your settings. Some values may be incorrect and changes may be lost.",
2935                        err,
2936                        &mut self.shown_errors,
2937                        cx,
2938                    ))
2939                })
2940                .map(|this| match &error.migration_status {
2941                    settings::MigrationStatus::Succeeded => this.child(banner(
2942                        "Your settings are out of date, and need to be updated.",
2943                        match &self.current_file {
2944                            SettingsUiFile::User => "They can be automatically migrated to the latest version.",
2945                            SettingsUiFile::Server(_) | SettingsUiFile::Project(_)  => "They must be manually migrated to the latest version."
2946                        }.to_string(),
2947                        &mut self.shown_errors,
2948                        cx,
2949                    )),
2950                    settings::MigrationStatus::Failed { error: err } if !parse_failed => this
2951                        .child(banner(
2952                            "Your settings file is out of date, automatic migration failed",
2953                            err.clone(),
2954                            &mut self.shown_errors,
2955                            cx,
2956                        )),
2957                    _ => this,
2958                })
2959                .into_any_element()
2960        }
2961
2962        return v_flex()
2963            .id("settings-ui-page")
2964            .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2965                if !sub_page_stack().is_empty() {
2966                    window.focus_next();
2967                    return;
2968                }
2969                for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2970                    let handle = this.content_handles[this.current_page_index()][actual_index]
2971                        .focus_handle(cx);
2972                    let mut offset = 1; // for page header
2973
2974                    if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2975                        && matches!(next_item, SettingsPageItem::SectionHeader(_))
2976                    {
2977                        offset += 1;
2978                    }
2979                    if handle.contains_focused(window, cx) {
2980                        let next_logical_index = logical_index + offset + 1;
2981                        this.list_state.scroll_to_reveal_item(next_logical_index);
2982                        // We need to render the next item to ensure it's focus handle is in the element tree
2983                        cx.on_next_frame(window, |_, window, cx| {
2984                            cx.notify();
2985                            cx.on_next_frame(window, |_, window, cx| {
2986                                window.focus_next();
2987                                cx.notify();
2988                            });
2989                        });
2990                        cx.notify();
2991                        return;
2992                    }
2993                }
2994                window.focus_next();
2995            }))
2996            .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2997                if !sub_page_stack().is_empty() {
2998                    window.focus_prev();
2999                    return;
3000                }
3001                let mut prev_was_header = false;
3002                for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
3003                    let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
3004                    let handle = this.content_handles[this.current_page_index()][actual_index]
3005                        .focus_handle(cx);
3006                    let mut offset = 1; // for page header
3007
3008                    if prev_was_header {
3009                        offset -= 1;
3010                    }
3011                    if handle.contains_focused(window, cx) {
3012                        let next_logical_index = logical_index + offset - 1;
3013                        this.list_state.scroll_to_reveal_item(next_logical_index);
3014                        // We need to render the next item to ensure it's focus handle is in the element tree
3015                        cx.on_next_frame(window, |_, window, cx| {
3016                            cx.notify();
3017                            cx.on_next_frame(window, |_, window, cx| {
3018                                window.focus_prev();
3019                                cx.notify();
3020                            });
3021                        });
3022                        cx.notify();
3023                        return;
3024                    }
3025                    prev_was_header = is_header;
3026                }
3027                window.focus_prev();
3028            }))
3029            .when(sub_page_stack().is_empty(), |this| {
3030                this.vertical_scrollbar_for(&self.list_state, window, cx)
3031            })
3032            .when(!sub_page_stack().is_empty(), |this| {
3033                this.vertical_scrollbar_for(&self.sub_page_scroll_handle, window, cx)
3034            })
3035            .track_focus(&self.content_focus_handle.focus_handle(cx))
3036            .pt_6()
3037            .gap_4()
3038            .flex_1()
3039            .bg(cx.theme().colors().editor_background)
3040            .child(
3041                v_flex()
3042                    .px_8()
3043                    .gap_2()
3044                    .child(page_header)
3045                    .child(warning_banner),
3046            )
3047            .child(
3048                div()
3049                    .flex_1()
3050                    .size_full()
3051                    .tab_group()
3052                    .tab_index(CONTENT_GROUP_TAB_INDEX)
3053                    .child(page_content),
3054            );
3055    }
3056
3057    /// This function will create a new settings file if one doesn't exist
3058    /// if the current file is a project settings with a valid worktree id
3059    /// We do this because the settings ui allows initializing project settings
3060    fn open_current_settings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3061        match &self.current_file {
3062            SettingsUiFile::User => {
3063                let Some(original_window) = self.original_window else {
3064                    return;
3065                };
3066                original_window
3067                    .update(cx, |workspace, window, cx| {
3068                        workspace
3069                            .with_local_workspace(window, cx, |workspace, window, cx| {
3070                                let create_task = workspace.project().update(cx, |project, cx| {
3071                                    project.find_or_create_worktree(
3072                                        paths::config_dir().as_path(),
3073                                        false,
3074                                        cx,
3075                                    )
3076                                });
3077                                let open_task = workspace.open_paths(
3078                                    vec![paths::settings_file().to_path_buf()],
3079                                    OpenOptions {
3080                                        visible: Some(OpenVisible::None),
3081                                        ..Default::default()
3082                                    },
3083                                    None,
3084                                    window,
3085                                    cx,
3086                                );
3087
3088                                cx.spawn_in(window, async move |workspace, cx| {
3089                                    create_task.await.ok();
3090                                    open_task.await;
3091
3092                                    workspace.update_in(cx, |_, window, cx| {
3093                                        window.activate_window();
3094                                        cx.notify();
3095                                    })
3096                                })
3097                                .detach();
3098                            })
3099                            .detach();
3100                    })
3101                    .ok();
3102
3103                window.remove_window();
3104            }
3105            SettingsUiFile::Project((worktree_id, path)) => {
3106                let settings_path = path.join(paths::local_settings_file_relative_path());
3107                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
3108                    return;
3109                };
3110
3111                let Some((worktree, corresponding_workspace)) = app_state
3112                    .workspace_store
3113                    .read(cx)
3114                    .workspaces()
3115                    .iter()
3116                    .find_map(|workspace| {
3117                        workspace
3118                            .read_with(cx, |workspace, cx| {
3119                                workspace
3120                                    .project()
3121                                    .read(cx)
3122                                    .worktree_for_id(*worktree_id, cx)
3123                            })
3124                            .ok()
3125                            .flatten()
3126                            .zip(Some(*workspace))
3127                    })
3128                else {
3129                    log::error!(
3130                        "No corresponding workspace contains worktree id: {}",
3131                        worktree_id
3132                    );
3133
3134                    return;
3135                };
3136
3137                let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3138                    None
3139                } else {
3140                    Some(worktree.update(cx, |tree, cx| {
3141                        tree.create_entry(
3142                            settings_path.clone(),
3143                            false,
3144                            Some(initial_project_settings_content().as_bytes().to_vec()),
3145                            cx,
3146                        )
3147                    }))
3148                };
3149
3150                let worktree_id = *worktree_id;
3151
3152                // TODO: move zed::open_local_file() APIs to this crate, and
3153                // re-implement the "initial_contents" behavior
3154                corresponding_workspace
3155                    .update(cx, |_, window, cx| {
3156                        cx.spawn_in(window, async move |workspace, cx| {
3157                            if let Some(create_task) = create_task {
3158                                create_task.await.ok()?;
3159                            };
3160
3161                            workspace
3162                                .update_in(cx, |workspace, window, cx| {
3163                                    workspace.open_path(
3164                                        (worktree_id, settings_path.clone()),
3165                                        None,
3166                                        true,
3167                                        window,
3168                                        cx,
3169                                    )
3170                                })
3171                                .ok()?
3172                                .await
3173                                .log_err()?;
3174
3175                            workspace
3176                                .update_in(cx, |_, window, cx| {
3177                                    window.activate_window();
3178                                    cx.notify();
3179                                })
3180                                .ok();
3181
3182                            Some(())
3183                        })
3184                        .detach();
3185                    })
3186                    .ok();
3187
3188                window.remove_window();
3189            }
3190            SettingsUiFile::Server(_) => {
3191                // Server files are not editable
3192                return;
3193            }
3194        };
3195    }
3196
3197    fn current_page_index(&self) -> usize {
3198        self.page_index_from_navbar_index(self.navbar_entry)
3199    }
3200
3201    fn current_page(&self) -> &SettingsPage {
3202        &self.pages[self.current_page_index()]
3203    }
3204
3205    fn page_index_from_navbar_index(&self, index: usize) -> usize {
3206        if self.navbar_entries.is_empty() {
3207            return 0;
3208        }
3209
3210        self.navbar_entries[index].page_index
3211    }
3212
3213    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3214        ix == self.navbar_entry
3215    }
3216
3217    fn push_sub_page(
3218        &mut self,
3219        sub_page_link: SubPageLink,
3220        section_header: &'static str,
3221        cx: &mut Context<SettingsWindow>,
3222    ) {
3223        sub_page_stack_mut().push(SubPage {
3224            link: sub_page_link,
3225            section_header,
3226        });
3227        cx.notify();
3228    }
3229
3230    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
3231        sub_page_stack_mut().pop();
3232        cx.notify();
3233    }
3234
3235    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
3236        if let Some((_, handle)) = self.files.get(index) {
3237            handle.focus(window);
3238        }
3239    }
3240
3241    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3242        if self.files_focus_handle.contains_focused(window, cx)
3243            && let Some(index) = self
3244                .files
3245                .iter()
3246                .position(|(_, handle)| handle.is_focused(window))
3247        {
3248            return index;
3249        }
3250        if let Some(current_file_index) = self
3251            .files
3252            .iter()
3253            .position(|(file, _)| file == &self.current_file)
3254        {
3255            return current_file_index;
3256        }
3257        0
3258    }
3259
3260    fn focus_handle_for_content_element(
3261        &self,
3262        actual_item_index: usize,
3263        cx: &Context<Self>,
3264    ) -> FocusHandle {
3265        let page_index = self.current_page_index();
3266        self.content_handles[page_index][actual_item_index].focus_handle(cx)
3267    }
3268
3269    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3270        if !self
3271            .navbar_focus_handle
3272            .focus_handle(cx)
3273            .contains_focused(window, cx)
3274        {
3275            return None;
3276        }
3277        for (index, entry) in self.navbar_entries.iter().enumerate() {
3278            if entry.focus_handle.is_focused(window) {
3279                return Some(index);
3280            }
3281        }
3282        None
3283    }
3284
3285    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3286        let mut index = Some(nav_entry_index);
3287        while let Some(prev_index) = index
3288            && !self.navbar_entries[prev_index].is_root
3289        {
3290            index = prev_index.checked_sub(1);
3291        }
3292        return index.expect("No root entry found");
3293    }
3294}
3295
3296impl Render for SettingsWindow {
3297    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3298        let ui_font = theme::setup_ui_font(window, cx);
3299
3300        client_side_decorations(
3301            v_flex()
3302                .text_color(cx.theme().colors().text)
3303                .size_full()
3304                .children(self.title_bar.clone())
3305                .child(
3306                    div()
3307                        .id("settings-window")
3308                        .key_context("SettingsWindow")
3309                        .track_focus(&self.focus_handle)
3310                        .on_action(cx.listener(|this, _: &OpenCurrentFile, window, cx| {
3311                            this.open_current_settings_file(window, cx);
3312                        }))
3313                        .on_action(|_: &Minimize, window, _cx| {
3314                            window.minimize_window();
3315                        })
3316                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3317                            this.search_bar.focus_handle(cx).focus(window);
3318                        }))
3319                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3320                            if this
3321                                .navbar_focus_handle
3322                                .focus_handle(cx)
3323                                .contains_focused(window, cx)
3324                            {
3325                                this.open_and_scroll_to_navbar_entry(
3326                                    this.navbar_entry,
3327                                    None,
3328                                    true,
3329                                    window,
3330                                    cx,
3331                                );
3332                            } else {
3333                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3334                            }
3335                        }))
3336                        .on_action(cx.listener(
3337                            |this, FocusFile(file_index): &FocusFile, window, _| {
3338                                this.focus_file_at_index(*file_index as usize, window);
3339                            },
3340                        ))
3341                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3342                            let next_index = usize::min(
3343                                this.focused_file_index(window, cx) + 1,
3344                                this.files.len().saturating_sub(1),
3345                            );
3346                            this.focus_file_at_index(next_index, window);
3347                        }))
3348                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3349                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3350                            this.focus_file_at_index(prev_index, window);
3351                        }))
3352                        .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3353                            if this
3354                                .search_bar
3355                                .focus_handle(cx)
3356                                .contains_focused(window, cx)
3357                            {
3358                                this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3359                            } else {
3360                                window.focus_next();
3361                            }
3362                        }))
3363                        .on_action(|_: &menu::SelectPrevious, window, _| {
3364                            window.focus_prev();
3365                        })
3366                        .flex()
3367                        .flex_row()
3368                        .flex_1()
3369                        .min_h_0()
3370                        .font(ui_font)
3371                        .bg(cx.theme().colors().background)
3372                        .text_color(cx.theme().colors().text)
3373                        .when(!cfg!(target_os = "macos"), |this| {
3374                            this.border_t_1().border_color(cx.theme().colors().border)
3375                        })
3376                        .child(self.render_nav(window, cx))
3377                        .child(self.render_page(window, cx)),
3378                ),
3379            window,
3380            cx,
3381        )
3382    }
3383}
3384
3385fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
3386    workspace::AppState::global(cx)
3387        .upgrade()
3388        .map(|app_state| {
3389            app_state
3390                .workspace_store
3391                .read(cx)
3392                .workspaces()
3393                .iter()
3394                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
3395        })
3396        .into_iter()
3397        .flatten()
3398}
3399
3400fn update_settings_file(
3401    file: SettingsUiFile,
3402    file_name: Option<&'static str>,
3403    cx: &mut App,
3404    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3405) -> Result<()> {
3406    telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3407
3408    match file {
3409        SettingsUiFile::Project((worktree_id, rel_path)) => {
3410            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3411            let Some((worktree, project)) = all_projects(cx).find_map(|project| {
3412                project
3413                    .read(cx)
3414                    .worktree_for_id(worktree_id, cx)
3415                    .zip(Some(project))
3416            }) else {
3417                anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3418            };
3419
3420            project.update(cx, |project, cx| {
3421                let task = if project.contains_local_settings_file(worktree_id, &rel_path, cx) {
3422                    None
3423                } else {
3424                    Some(worktree.update(cx, |worktree, cx| {
3425                        worktree.create_entry(rel_path.clone(), false, None, cx)
3426                    }))
3427                };
3428
3429                cx.spawn(async move |project, cx| {
3430                    if let Some(task) = task
3431                        && task.await.is_err()
3432                    {
3433                        return;
3434                    };
3435
3436                    project
3437                        .update(cx, |project, cx| {
3438                            project.update_local_settings_file(worktree_id, rel_path, cx, update);
3439                        })
3440                        .ok();
3441                })
3442                .detach();
3443            });
3444
3445            return Ok(());
3446        }
3447        SettingsUiFile::User => {
3448            // todo(settings_ui) error?
3449            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3450            Ok(())
3451        }
3452        SettingsUiFile::Server(_) => unimplemented!(),
3453    }
3454}
3455
3456fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3457    field: SettingField<T>,
3458    file: SettingsUiFile,
3459    metadata: Option<&SettingsFieldMetadata>,
3460    _window: &mut Window,
3461    cx: &mut App,
3462) -> AnyElement {
3463    let (_, initial_text) =
3464        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3465    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3466
3467    SettingsInputField::new()
3468        .tab_index(0)
3469        .when_some(initial_text, |editor, text| {
3470            editor.with_initial_text(text.as_ref().to_string())
3471        })
3472        .when_some(
3473            metadata.and_then(|metadata| metadata.placeholder),
3474            |editor, placeholder| editor.with_placeholder(placeholder),
3475        )
3476        .on_confirm({
3477            move |new_text, cx| {
3478                update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3479                    (field.write)(settings, new_text.map(Into::into));
3480                })
3481                .log_err(); // todo(settings_ui) don't log err
3482            }
3483        })
3484        .into_any_element()
3485}
3486
3487fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3488    field: SettingField<B>,
3489    file: SettingsUiFile,
3490    _metadata: Option<&SettingsFieldMetadata>,
3491    _window: &mut Window,
3492    cx: &mut App,
3493) -> AnyElement {
3494    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3495
3496    let toggle_state = if value.copied().map_or(false, Into::into) {
3497        ToggleState::Selected
3498    } else {
3499        ToggleState::Unselected
3500    };
3501
3502    Switch::new("toggle_button", toggle_state)
3503        .tab_index(0_isize)
3504        .color(SwitchColor::Accent)
3505        .on_click({
3506            move |state, _window, cx| {
3507                telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());
3508
3509                let state = *state == ui::ToggleState::Selected;
3510                update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3511                    (field.write)(settings, Some(state.into()));
3512                })
3513                .log_err(); // todo(settings_ui) don't log err
3514            }
3515        })
3516        .into_any_element()
3517}
3518
3519fn render_number_field<T: NumberFieldType + Send + Sync>(
3520    field: SettingField<T>,
3521    file: SettingsUiFile,
3522    _metadata: Option<&SettingsFieldMetadata>,
3523    window: &mut Window,
3524    cx: &mut App,
3525) -> AnyElement {
3526    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3527    let value = value.copied().unwrap_or_else(T::min_value);
3528    NumberField::new("numeric_stepper", value, window, cx)
3529        .on_change({
3530            move |value, _window, cx| {
3531                let value = *value;
3532                update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3533                    (field.write)(settings, Some(value));
3534                })
3535                .log_err(); // todo(settings_ui) don't log err
3536            }
3537        })
3538        .into_any_element()
3539}
3540
3541fn render_dropdown<T>(
3542    field: SettingField<T>,
3543    file: SettingsUiFile,
3544    metadata: Option<&SettingsFieldMetadata>,
3545    _window: &mut Window,
3546    cx: &mut App,
3547) -> AnyElement
3548where
3549    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3550{
3551    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3552    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3553    let should_do_titlecase = metadata
3554        .and_then(|metadata| metadata.should_do_titlecase)
3555        .unwrap_or(true);
3556
3557    let (_, current_value) =
3558        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3559    let current_value = current_value.copied().unwrap_or(variants()[0]);
3560
3561    EnumVariantDropdown::new("dropdown", current_value, variants(), labels(), {
3562        move |value, cx| {
3563            if value == current_value {
3564                return;
3565            }
3566            update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3567                (field.write)(settings, Some(value));
3568            })
3569            .log_err(); // todo(settings_ui) don't log err
3570        }
3571    })
3572    .tab_index(0)
3573    .title_case(should_do_titlecase)
3574    .into_any_element()
3575}
3576
3577fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3578    Button::new(id, label)
3579        .tab_index(0_isize)
3580        .style(ButtonStyle::Outlined)
3581        .size(ButtonSize::Medium)
3582        .icon(IconName::ChevronUpDown)
3583        .icon_color(Color::Muted)
3584        .icon_size(IconSize::Small)
3585        .icon_position(IconPosition::End)
3586}
3587
3588fn render_font_picker(
3589    field: SettingField<settings::FontFamilyName>,
3590    file: SettingsUiFile,
3591    _metadata: Option<&SettingsFieldMetadata>,
3592    _window: &mut Window,
3593    cx: &mut App,
3594) -> AnyElement {
3595    let current_value = SettingsStore::global(cx)
3596        .get_value_from_file(file.to_settings(), field.pick)
3597        .1
3598        .cloned()
3599        .unwrap_or_else(|| SharedString::default().into());
3600
3601    PopoverMenu::new("font-picker")
3602        .trigger(render_picker_trigger_button(
3603            "font_family_picker_trigger".into(),
3604            current_value.clone().into(),
3605        ))
3606        .menu(move |window, cx| {
3607            let file = file.clone();
3608            let current_value = current_value.clone();
3609
3610            Some(cx.new(move |cx| {
3611                font_picker(
3612                    current_value.clone().into(),
3613                    move |font_name, cx| {
3614                        update_settings_file(
3615                            file.clone(),
3616                            field.json_path,
3617                            cx,
3618                            move |settings, _cx| {
3619                                (field.write)(settings, Some(font_name.into()));
3620                            },
3621                        )
3622                        .log_err(); // todo(settings_ui) don't log err
3623                    },
3624                    window,
3625                    cx,
3626                )
3627            }))
3628        })
3629        .anchor(gpui::Corner::TopLeft)
3630        .offset(gpui::Point {
3631            x: px(0.0),
3632            y: px(2.0),
3633        })
3634        .with_handle(ui::PopoverMenuHandle::default())
3635        .into_any_element()
3636}
3637
3638fn render_theme_picker(
3639    field: SettingField<settings::ThemeName>,
3640    file: SettingsUiFile,
3641    _metadata: Option<&SettingsFieldMetadata>,
3642    _window: &mut Window,
3643    cx: &mut App,
3644) -> AnyElement {
3645    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3646    let current_value = value
3647        .cloned()
3648        .map(|theme_name| theme_name.0.into())
3649        .unwrap_or_else(|| cx.theme().name.clone());
3650
3651    PopoverMenu::new("theme-picker")
3652        .trigger(render_picker_trigger_button(
3653            "theme_picker_trigger".into(),
3654            current_value.clone(),
3655        ))
3656        .menu(move |window, cx| {
3657            Some(cx.new(|cx| {
3658                let file = file.clone();
3659                let current_value = current_value.clone();
3660                theme_picker(
3661                    current_value,
3662                    move |theme_name, cx| {
3663                        update_settings_file(
3664                            file.clone(),
3665                            field.json_path,
3666                            cx,
3667                            move |settings, _cx| {
3668                                (field.write)(
3669                                    settings,
3670                                    Some(settings::ThemeName(theme_name.into())),
3671                                );
3672                            },
3673                        )
3674                        .log_err(); // todo(settings_ui) don't log err
3675                    },
3676                    window,
3677                    cx,
3678                )
3679            }))
3680        })
3681        .anchor(gpui::Corner::TopLeft)
3682        .offset(gpui::Point {
3683            x: px(0.0),
3684            y: px(2.0),
3685        })
3686        .with_handle(ui::PopoverMenuHandle::default())
3687        .into_any_element()
3688}
3689
3690fn render_icon_theme_picker(
3691    field: SettingField<settings::IconThemeName>,
3692    file: SettingsUiFile,
3693    _metadata: Option<&SettingsFieldMetadata>,
3694    _window: &mut Window,
3695    cx: &mut App,
3696) -> AnyElement {
3697    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3698    let current_value = value
3699        .cloned()
3700        .map(|theme_name| theme_name.0.into())
3701        .unwrap_or_else(|| cx.theme().name.clone());
3702
3703    PopoverMenu::new("icon-theme-picker")
3704        .trigger(render_picker_trigger_button(
3705            "icon_theme_picker_trigger".into(),
3706            current_value.clone(),
3707        ))
3708        .menu(move |window, cx| {
3709            Some(cx.new(|cx| {
3710                let file = file.clone();
3711                let current_value = current_value.clone();
3712                icon_theme_picker(
3713                    current_value,
3714                    move |theme_name, cx| {
3715                        update_settings_file(
3716                            file.clone(),
3717                            field.json_path,
3718                            cx,
3719                            move |settings, _cx| {
3720                                (field.write)(
3721                                    settings,
3722                                    Some(settings::IconThemeName(theme_name.into())),
3723                                );
3724                            },
3725                        )
3726                        .log_err(); // todo(settings_ui) don't log err
3727                    },
3728                    window,
3729                    cx,
3730                )
3731            }))
3732        })
3733        .anchor(gpui::Corner::TopLeft)
3734        .offset(gpui::Point {
3735            x: px(0.0),
3736            y: px(2.0),
3737        })
3738        .with_handle(ui::PopoverMenuHandle::default())
3739        .into_any_element()
3740}
3741
3742#[cfg(test)]
3743pub mod test {
3744
3745    use super::*;
3746
3747    impl SettingsWindow {
3748        fn navbar_entry(&self) -> usize {
3749            self.navbar_entry
3750        }
3751    }
3752
3753    impl PartialEq for NavBarEntry {
3754        fn eq(&self, other: &Self) -> bool {
3755            self.title == other.title
3756                && self.is_root == other.is_root
3757                && self.expanded == other.expanded
3758                && self.page_index == other.page_index
3759                && self.item_index == other.item_index
3760            // ignoring focus_handle
3761        }
3762    }
3763
3764    pub fn register_settings(cx: &mut App) {
3765        settings::init(cx);
3766        theme::init(theme::LoadThemes::JustBase, cx);
3767        editor::init(cx);
3768        menu::init();
3769    }
3770
3771    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3772        let mut pages: Vec<SettingsPage> = Vec::new();
3773        let mut expanded_pages = Vec::new();
3774        let mut selected_idx = None;
3775        let mut index = 0;
3776        let mut in_expanded_section = false;
3777
3778        for mut line in input
3779            .lines()
3780            .map(|line| line.trim())
3781            .filter(|line| !line.is_empty())
3782        {
3783            if let Some(pre) = line.strip_suffix('*') {
3784                assert!(selected_idx.is_none(), "Only one selected entry allowed");
3785                selected_idx = Some(index);
3786                line = pre;
3787            }
3788            let (kind, title) = line.split_once(" ").unwrap();
3789            assert_eq!(kind.len(), 1);
3790            let kind = kind.chars().next().unwrap();
3791            if kind == 'v' {
3792                let page_idx = pages.len();
3793                expanded_pages.push(page_idx);
3794                pages.push(SettingsPage {
3795                    title,
3796                    items: vec![],
3797                });
3798                index += 1;
3799                in_expanded_section = true;
3800            } else if kind == '>' {
3801                pages.push(SettingsPage {
3802                    title,
3803                    items: vec![],
3804                });
3805                index += 1;
3806                in_expanded_section = false;
3807            } else if kind == '-' {
3808                pages
3809                    .last_mut()
3810                    .unwrap()
3811                    .items
3812                    .push(SettingsPageItem::SectionHeader(title));
3813                if selected_idx == Some(index) && !in_expanded_section {
3814                    panic!("Items in unexpanded sections cannot be selected");
3815                }
3816                index += 1;
3817            } else {
3818                panic!(
3819                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
3820                    line
3821                );
3822            }
3823        }
3824
3825        let mut settings_window = SettingsWindow {
3826            title_bar: None,
3827            original_window: None,
3828            worktree_root_dirs: HashMap::default(),
3829            files: Vec::default(),
3830            current_file: crate::SettingsUiFile::User,
3831            pages,
3832            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3833            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3834            navbar_entries: Vec::default(),
3835            navbar_scroll_handle: UniformListScrollHandle::default(),
3836            navbar_focus_subscriptions: vec![],
3837            filter_table: vec![],
3838            has_query: false,
3839            content_handles: vec![],
3840            search_task: None,
3841            sub_page_scroll_handle: ScrollHandle::new(),
3842            focus_handle: cx.focus_handle(),
3843            navbar_focus_handle: NonFocusableHandle::new(
3844                NAVBAR_CONTAINER_TAB_INDEX,
3845                false,
3846                window,
3847                cx,
3848            ),
3849            content_focus_handle: NonFocusableHandle::new(
3850                CONTENT_CONTAINER_TAB_INDEX,
3851                false,
3852                window,
3853                cx,
3854            ),
3855            files_focus_handle: cx.focus_handle(),
3856            search_index: None,
3857            list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3858            shown_errors: HashSet::default(),
3859        };
3860
3861        settings_window.build_filter_table();
3862        settings_window.build_navbar(cx);
3863        for expanded_page_index in expanded_pages {
3864            for entry in &mut settings_window.navbar_entries {
3865                if entry.page_index == expanded_page_index && entry.is_root {
3866                    entry.expanded = true;
3867                }
3868            }
3869        }
3870        settings_window
3871    }
3872
3873    #[track_caller]
3874    fn check_navbar_toggle(
3875        before: &'static str,
3876        toggle_page: &'static str,
3877        after: &'static str,
3878        window: &mut Window,
3879        cx: &mut App,
3880    ) {
3881        let mut settings_window = parse(before, window, cx);
3882        let toggle_page_idx = settings_window
3883            .pages
3884            .iter()
3885            .position(|page| page.title == toggle_page)
3886            .expect("page not found");
3887        let toggle_idx = settings_window
3888            .navbar_entries
3889            .iter()
3890            .position(|entry| entry.page_index == toggle_page_idx)
3891            .expect("page not found");
3892        settings_window.toggle_navbar_entry(toggle_idx);
3893
3894        let expected_settings_window = parse(after, window, cx);
3895
3896        pretty_assertions::assert_eq!(
3897            settings_window
3898                .visible_navbar_entries()
3899                .map(|(_, entry)| entry)
3900                .collect::<Vec<_>>(),
3901            expected_settings_window
3902                .visible_navbar_entries()
3903                .map(|(_, entry)| entry)
3904                .collect::<Vec<_>>(),
3905        );
3906        pretty_assertions::assert_eq!(
3907            settings_window.navbar_entries[settings_window.navbar_entry()],
3908            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3909        );
3910    }
3911
3912    macro_rules! check_navbar_toggle {
3913        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3914            #[gpui::test]
3915            fn $name(cx: &mut gpui::TestAppContext) {
3916                let window = cx.add_empty_window();
3917                window.update(|window, cx| {
3918                    register_settings(cx);
3919                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
3920                });
3921            }
3922        };
3923    }
3924
3925    check_navbar_toggle!(
3926        navbar_basic_open,
3927        before: r"
3928        v General
3929        - General
3930        - Privacy*
3931        v Project
3932        - Project Settings
3933        ",
3934        toggle_page: "General",
3935        after: r"
3936        > General*
3937        v Project
3938        - Project Settings
3939        "
3940    );
3941
3942    check_navbar_toggle!(
3943        navbar_basic_close,
3944        before: r"
3945        > General*
3946        - General
3947        - Privacy
3948        v Project
3949        - Project Settings
3950        ",
3951        toggle_page: "General",
3952        after: r"
3953        v General*
3954        - General
3955        - Privacy
3956        v Project
3957        - Project Settings
3958        "
3959    );
3960
3961    check_navbar_toggle!(
3962        navbar_basic_second_root_entry_close,
3963        before: r"
3964        > General
3965        - General
3966        - Privacy
3967        v Project
3968        - Project Settings*
3969        ",
3970        toggle_page: "Project",
3971        after: r"
3972        > General
3973        > Project*
3974        "
3975    );
3976
3977    check_navbar_toggle!(
3978        navbar_toggle_subroot,
3979        before: r"
3980        v General Page
3981        - General
3982        - Privacy
3983        v Project
3984        - Worktree Settings Content*
3985        v AI
3986        - General
3987        > Appearance & Behavior
3988        ",
3989        toggle_page: "Project",
3990        after: r"
3991        v General Page
3992        - General
3993        - Privacy
3994        > Project*
3995        v AI
3996        - General
3997        > Appearance & Behavior
3998        "
3999    );
4000
4001    check_navbar_toggle!(
4002        navbar_toggle_close_propagates_selected_index,
4003        before: r"
4004        v General Page
4005        - General
4006        - Privacy
4007        v Project
4008        - Worktree Settings Content
4009        v AI
4010        - General*
4011        > Appearance & Behavior
4012        ",
4013        toggle_page: "General Page",
4014        after: r"
4015        > General Page*
4016        v Project
4017        - Worktree Settings Content
4018        v AI
4019        - General
4020        > Appearance & Behavior
4021        "
4022    );
4023
4024    check_navbar_toggle!(
4025        navbar_toggle_expand_propagates_selected_index,
4026        before: r"
4027        > General Page
4028        - General
4029        - Privacy
4030        v Project
4031        - Worktree Settings Content
4032        v AI
4033        - General*
4034        > Appearance & Behavior
4035        ",
4036        toggle_page: "General Page",
4037        after: r"
4038        v General Page*
4039        - General
4040        - Privacy
4041        v Project
4042        - Worktree Settings Content
4043        v AI
4044        - General
4045        > Appearance & Behavior
4046        "
4047    );
4048}