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