settings_ui.rs

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