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