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