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::ThemeAppearanceMode>(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 && !is_last, |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    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2120        h_flex()
2121            .py_1()
2122            .px_1p5()
2123            .mb_3()
2124            .gap_1p5()
2125            .rounded_sm()
2126            .bg(cx.theme().colors().editor_background)
2127            .border_1()
2128            .border_color(cx.theme().colors().border)
2129            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2130            .child(self.search_bar.clone())
2131    }
2132
2133    fn render_nav(
2134        &self,
2135        window: &mut Window,
2136        cx: &mut Context<SettingsWindow>,
2137    ) -> impl IntoElement {
2138        let visible_count = self.visible_navbar_entries().count();
2139
2140        let focus_keybind_label = if self
2141            .navbar_focus_handle
2142            .read(cx)
2143            .handle
2144            .contains_focused(window, cx)
2145            || self
2146                .visible_navbar_entries()
2147                .any(|(_, entry)| entry.focus_handle.is_focused(window))
2148        {
2149            "Focus Content"
2150        } else {
2151            "Focus Navbar"
2152        };
2153
2154        let mut key_context = KeyContext::new_with_defaults();
2155        key_context.add("NavigationMenu");
2156        key_context.add("menu");
2157        if self.search_bar.focus_handle(cx).is_focused(window) {
2158            key_context.add("search");
2159        }
2160
2161        v_flex()
2162            .key_context(key_context)
2163            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2164                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2165                    return;
2166                };
2167                let focused_entry_parent = this.root_entry_containing(focused_entry);
2168                if this.navbar_entries[focused_entry_parent].expanded {
2169                    this.toggle_navbar_entry(focused_entry_parent);
2170                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
2171                }
2172                cx.notify();
2173            }))
2174            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2175                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2176                    return;
2177                };
2178                if !this.navbar_entries[focused_entry].is_root {
2179                    return;
2180                }
2181                if !this.navbar_entries[focused_entry].expanded {
2182                    this.toggle_navbar_entry(focused_entry);
2183                }
2184                cx.notify();
2185            }))
2186            .on_action(
2187                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2188                    let entry_index = this
2189                        .focused_nav_entry(window, cx)
2190                        .unwrap_or(this.navbar_entry);
2191                    let mut root_index = None;
2192                    for (index, entry) in this.visible_navbar_entries() {
2193                        if index >= entry_index {
2194                            break;
2195                        }
2196                        if entry.is_root {
2197                            root_index = Some(index);
2198                        }
2199                    }
2200                    let Some(previous_root_index) = root_index else {
2201                        return;
2202                    };
2203                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2204                }),
2205            )
2206            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2207                let entry_index = this
2208                    .focused_nav_entry(window, cx)
2209                    .unwrap_or(this.navbar_entry);
2210                let mut root_index = None;
2211                for (index, entry) in this.visible_navbar_entries() {
2212                    if index <= entry_index {
2213                        continue;
2214                    }
2215                    if entry.is_root {
2216                        root_index = Some(index);
2217                        break;
2218                    }
2219                }
2220                let Some(next_root_index) = root_index else {
2221                    return;
2222                };
2223                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2224            }))
2225            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2226                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2227                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2228                }
2229            }))
2230            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2231                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2232                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2233                }
2234            }))
2235            .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2236                let entry_index = this
2237                    .focused_nav_entry(window, cx)
2238                    .unwrap_or(this.navbar_entry);
2239                let mut next_index = None;
2240                for (index, _) in this.visible_navbar_entries() {
2241                    if index > entry_index {
2242                        next_index = Some(index);
2243                        break;
2244                    }
2245                }
2246                let Some(next_entry_index) = next_index else {
2247                    return;
2248                };
2249                this.open_and_scroll_to_navbar_entry(
2250                    next_entry_index,
2251                    Some(gpui::ScrollStrategy::Bottom),
2252                    false,
2253                    window,
2254                    cx,
2255                );
2256            }))
2257            .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2258                let entry_index = this
2259                    .focused_nav_entry(window, cx)
2260                    .unwrap_or(this.navbar_entry);
2261                let mut prev_index = None;
2262                for (index, _) in this.visible_navbar_entries() {
2263                    if index >= entry_index {
2264                        break;
2265                    }
2266                    prev_index = Some(index);
2267                }
2268                let Some(prev_entry_index) = prev_index else {
2269                    return;
2270                };
2271                this.open_and_scroll_to_navbar_entry(
2272                    prev_entry_index,
2273                    Some(gpui::ScrollStrategy::Top),
2274                    false,
2275                    window,
2276                    cx,
2277                );
2278            }))
2279            .w_56()
2280            .h_full()
2281            .p_2p5()
2282            .when(cfg!(target_os = "macos"), |this| this.pt_10())
2283            .flex_none()
2284            .border_r_1()
2285            .border_color(cx.theme().colors().border)
2286            .bg(cx.theme().colors().panel_background)
2287            .child(self.render_search(window, cx))
2288            .child(
2289                v_flex()
2290                    .flex_1()
2291                    .overflow_hidden()
2292                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2293                    .tab_group()
2294                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
2295                    .child(
2296                        uniform_list(
2297                            "settings-ui-nav-bar",
2298                            visible_count + 1,
2299                            cx.processor(move |this, range: Range<usize>, _, cx| {
2300                                this.visible_navbar_entries()
2301                                    .skip(range.start.saturating_sub(1))
2302                                    .take(range.len())
2303                                    .map(|(entry_index, entry)| {
2304                                        TreeViewItem::new(
2305                                            ("settings-ui-navbar-entry", entry_index),
2306                                            entry.title,
2307                                        )
2308                                        .track_focus(&entry.focus_handle)
2309                                        .root_item(entry.is_root)
2310                                        .toggle_state(this.is_navbar_entry_selected(entry_index))
2311                                        .when(entry.is_root, |item| {
2312                                            item.expanded(entry.expanded || this.has_query)
2313                                                .on_toggle(cx.listener(
2314                                                    move |this, _, window, cx| {
2315                                                        this.toggle_navbar_entry(entry_index);
2316                                                        window.focus(
2317                                                            &this.navbar_entries[entry_index]
2318                                                                .focus_handle,
2319                                                        );
2320                                                        cx.notify();
2321                                                    },
2322                                                ))
2323                                        })
2324                                        .on_click({
2325                                            let category = this.pages[entry.page_index].title;
2326                                            let subcategory =
2327                                                (!entry.is_root).then_some(entry.title);
2328
2329                                            cx.listener(move |this, _, window, cx| {
2330                                                telemetry::event!(
2331                                                    "Settings Navigation Clicked",
2332                                                    category = category,
2333                                                    subcategory = subcategory
2334                                                );
2335
2336                                                this.open_and_scroll_to_navbar_entry(
2337                                                    entry_index,
2338                                                    None,
2339                                                    true,
2340                                                    window,
2341                                                    cx,
2342                                                );
2343                                            })
2344                                        })
2345                                    })
2346                                    .collect()
2347                            }),
2348                        )
2349                        .size_full()
2350                        .track_scroll(self.navbar_scroll_handle.clone()),
2351                    )
2352                    .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
2353            )
2354            .child(
2355                h_flex()
2356                    .w_full()
2357                    .h_8()
2358                    .p_2()
2359                    .pb_0p5()
2360                    .flex_shrink_0()
2361                    .border_t_1()
2362                    .border_color(cx.theme().colors().border_variant)
2363                    .child(
2364                        KeybindingHint::new(
2365                            KeyBinding::for_action_in(
2366                                &ToggleFocusNav,
2367                                &self.navbar_focus_handle.focus_handle(cx),
2368                                cx,
2369                            ),
2370                            cx.theme().colors().surface_background.opacity(0.5),
2371                        )
2372                        .suffix(focus_keybind_label),
2373                    ),
2374            )
2375    }
2376
2377    fn open_and_scroll_to_navbar_entry(
2378        &mut self,
2379        navbar_entry_index: usize,
2380        scroll_strategy: Option<gpui::ScrollStrategy>,
2381        focus_content: bool,
2382        window: &mut Window,
2383        cx: &mut Context<Self>,
2384    ) {
2385        self.open_navbar_entry_page(navbar_entry_index);
2386        cx.notify();
2387
2388        let mut handle_to_focus = None;
2389
2390        if self.navbar_entries[navbar_entry_index].is_root
2391            || !self.is_nav_entry_visible(navbar_entry_index)
2392        {
2393            self.sub_page_scroll_handle
2394                .set_offset(point(px(0.), px(0.)));
2395            if focus_content {
2396                let Some(first_item_index) =
2397                    self.visible_page_items().next().map(|(index, _)| index)
2398                else {
2399                    return;
2400                };
2401                handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2402            } else if !self.is_nav_entry_visible(navbar_entry_index) {
2403                let Some(first_visible_nav_entry_index) =
2404                    self.visible_navbar_entries().next().map(|(index, _)| index)
2405                else {
2406                    return;
2407                };
2408                self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2409            } else {
2410                handle_to_focus =
2411                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2412            }
2413        } else {
2414            let entry_item_index = self.navbar_entries[navbar_entry_index]
2415                .item_index
2416                .expect("Non-root items should have an item index");
2417            self.scroll_to_content_item(entry_item_index, window, cx);
2418            if focus_content {
2419                handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2420            } else {
2421                handle_to_focus =
2422                    Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2423            }
2424        }
2425
2426        if let Some(scroll_strategy) = scroll_strategy
2427            && let Some(logical_entry_index) = self
2428                .visible_navbar_entries()
2429                .into_iter()
2430                .position(|(index, _)| index == navbar_entry_index)
2431        {
2432            self.navbar_scroll_handle
2433                .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2434        }
2435
2436        // Page scroll handle updates the active item index
2437        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2438        // The call after that updates the offset of the scroll handle. So to
2439        // ensure the scroll handle doesn't lag behind we need to render three frames
2440        // back to back.
2441        cx.on_next_frame(window, move |_, window, cx| {
2442            if let Some(handle) = handle_to_focus.as_ref() {
2443                window.focus(handle);
2444            }
2445
2446            cx.on_next_frame(window, |_, _, cx| {
2447                cx.notify();
2448            });
2449            cx.notify();
2450        });
2451        cx.notify();
2452    }
2453
2454    fn scroll_to_content_item(
2455        &self,
2456        content_item_index: usize,
2457        _window: &mut Window,
2458        cx: &mut Context<Self>,
2459    ) {
2460        let index = self
2461            .visible_page_items()
2462            .position(|(index, _)| index == content_item_index)
2463            .unwrap_or(0);
2464        if index == 0 {
2465            self.sub_page_scroll_handle
2466                .set_offset(point(px(0.), px(0.)));
2467            self.list_state.scroll_to(gpui::ListOffset {
2468                item_ix: 0,
2469                offset_in_item: px(0.),
2470            });
2471            return;
2472        }
2473        self.list_state.scroll_to(gpui::ListOffset {
2474            item_ix: index + 1,
2475            offset_in_item: px(0.),
2476        });
2477        cx.notify();
2478    }
2479
2480    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2481        self.visible_navbar_entries()
2482            .any(|(index, _)| index == nav_entry_index)
2483    }
2484
2485    fn focus_and_scroll_to_first_visible_nav_entry(
2486        &self,
2487        window: &mut Window,
2488        cx: &mut Context<Self>,
2489    ) {
2490        if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2491        {
2492            self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2493        }
2494    }
2495
2496    fn focus_and_scroll_to_nav_entry(
2497        &self,
2498        nav_entry_index: usize,
2499        window: &mut Window,
2500        cx: &mut Context<Self>,
2501    ) {
2502        let Some(position) = self
2503            .visible_navbar_entries()
2504            .position(|(index, _)| index == nav_entry_index)
2505        else {
2506            return;
2507        };
2508        self.navbar_scroll_handle
2509            .scroll_to_item(position, gpui::ScrollStrategy::Top);
2510        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2511        cx.notify();
2512    }
2513
2514    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2515        let page_idx = self.current_page_index();
2516
2517        self.current_page()
2518            .items
2519            .iter()
2520            .enumerate()
2521            .filter_map(move |(item_index, item)| {
2522                self.filter_table[page_idx][item_index].then_some((item_index, item))
2523            })
2524    }
2525
2526    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2527        let mut items = vec![];
2528        items.push(self.current_page().title.into());
2529        items.extend(
2530            sub_page_stack()
2531                .iter()
2532                .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2533        );
2534
2535        let last = items.pop().unwrap();
2536        h_flex()
2537            .gap_1()
2538            .children(
2539                items
2540                    .into_iter()
2541                    .flat_map(|item| [item, "/".into()])
2542                    .map(|item| Label::new(item).color(Color::Muted)),
2543            )
2544            .child(Label::new(last))
2545    }
2546
2547    fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2548        v_flex()
2549            .size_full()
2550            .items_center()
2551            .justify_center()
2552            .gap_1()
2553            .child(Label::new("No Results"))
2554            .child(
2555                Label::new(search_query)
2556                    .size(LabelSize::Small)
2557                    .color(Color::Muted),
2558            )
2559    }
2560
2561    fn render_page_items(
2562        &mut self,
2563        page_index: usize,
2564        _window: &mut Window,
2565        cx: &mut Context<SettingsWindow>,
2566    ) -> impl IntoElement {
2567        let mut page_content = v_flex().id("settings-ui-page").size_full();
2568
2569        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2570        let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2571
2572        if has_no_results {
2573            let search_query = self.search_bar.read(cx).text(cx);
2574            page_content = page_content.child(
2575                self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2576            )
2577        } else {
2578            let last_non_header_index = self
2579                .visible_page_items()
2580                .filter_map(|(index, item)| {
2581                    (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2582                })
2583                .last();
2584
2585            let root_nav_label = self
2586                .navbar_entries
2587                .iter()
2588                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2589                .map(|entry| entry.title);
2590
2591            let list_content = list(
2592                self.list_state.clone(),
2593                cx.processor(move |this, index, window, cx| {
2594                    if index == 0 {
2595                        return div()
2596                            .px_8()
2597                            .when(sub_page_stack().is_empty(), |this| {
2598                                this.when_some(root_nav_label, |this, title| {
2599                                    this.child(
2600                                        Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2601                                    )
2602                                })
2603                            })
2604                            .into_any_element();
2605                    }
2606
2607                    let mut visible_items = this.visible_page_items();
2608                    let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2609                        return gpui::Empty.into_any_element();
2610                    };
2611
2612                    let no_bottom_border = visible_items
2613                        .next()
2614                        .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2615                        .unwrap_or(false);
2616
2617                    let is_last = Some(actual_item_index) == last_non_header_index;
2618
2619                    let item_focus_handle =
2620                        this.content_handles[page_index][actual_item_index].focus_handle(cx);
2621
2622                    v_flex()
2623                        .id(("settings-page-item", actual_item_index))
2624                        .track_focus(&item_focus_handle)
2625                        .w_full()
2626                        .min_w_0()
2627                        .child(item.render(
2628                            this,
2629                            actual_item_index,
2630                            no_bottom_border || is_last,
2631                            window,
2632                            cx,
2633                        ))
2634                        .into_any_element()
2635                }),
2636            );
2637
2638            page_content = page_content.child(list_content.size_full())
2639        }
2640        page_content
2641    }
2642
2643    fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2644        &self,
2645        items: Items,
2646        page_index: Option<usize>,
2647        window: &mut Window,
2648        cx: &mut Context<SettingsWindow>,
2649    ) -> impl IntoElement {
2650        let mut page_content = v_flex()
2651            .id("settings-ui-page")
2652            .size_full()
2653            .overflow_y_scroll()
2654            .track_scroll(&self.sub_page_scroll_handle);
2655
2656        let items: Vec<_> = items.collect();
2657        let items_len = items.len();
2658        let mut section_header = None;
2659
2660        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2661        let has_no_results = items_len == 0 && has_active_search;
2662
2663        if has_no_results {
2664            let search_query = self.search_bar.read(cx).text(cx);
2665            page_content = page_content.child(
2666                self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2667            )
2668        } else {
2669            let last_non_header_index = items
2670                .iter()
2671                .enumerate()
2672                .rev()
2673                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2674                .map(|(index, _)| index);
2675
2676            let root_nav_label = self
2677                .navbar_entries
2678                .iter()
2679                .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2680                .map(|entry| entry.title);
2681
2682            page_content = page_content
2683                .when(sub_page_stack().is_empty(), |this| {
2684                    this.when_some(root_nav_label, |this, title| {
2685                        this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2686                    })
2687                })
2688                .children(items.clone().into_iter().enumerate().map(
2689                    |(index, (actual_item_index, item))| {
2690                        let no_bottom_border = items
2691                            .get(index + 1)
2692                            .map(|(_, next_item)| {
2693                                matches!(next_item, SettingsPageItem::SectionHeader(_))
2694                            })
2695                            .unwrap_or(false);
2696                        let is_last = Some(index) == last_non_header_index;
2697
2698                        if let SettingsPageItem::SectionHeader(header) = item {
2699                            section_header = Some(*header);
2700                        }
2701                        v_flex()
2702                            .w_full()
2703                            .min_w_0()
2704                            .id(("settings-page-item", actual_item_index))
2705                            .when_some(page_index, |element, page_index| {
2706                                element.track_focus(
2707                                    &self.content_handles[page_index][actual_item_index]
2708                                        .focus_handle(cx),
2709                                )
2710                            })
2711                            .child(item.render(
2712                                self,
2713                                actual_item_index,
2714                                no_bottom_border || is_last,
2715                                window,
2716                                cx,
2717                            ))
2718                    },
2719                ))
2720        }
2721        page_content
2722    }
2723
2724    fn render_page(
2725        &mut self,
2726        window: &mut Window,
2727        cx: &mut Context<SettingsWindow>,
2728    ) -> impl IntoElement {
2729        let page_header;
2730        let page_content;
2731
2732        if sub_page_stack().is_empty() {
2733            page_header = self.render_files_header(window, cx).into_any_element();
2734
2735            page_content = self
2736                .render_page_items(self.current_page_index(), window, cx)
2737                .into_any_element();
2738        } else {
2739            page_header = h_flex()
2740                .ml_neg_1p5()
2741                .gap_1()
2742                .child(
2743                    IconButton::new("back-btn", IconName::ArrowLeft)
2744                        .icon_size(IconSize::Small)
2745                        .shape(IconButtonShape::Square)
2746                        .on_click(cx.listener(|this, _, _, cx| {
2747                            this.pop_sub_page(cx);
2748                        })),
2749                )
2750                .child(self.render_sub_page_breadcrumbs())
2751                .into_any_element();
2752
2753            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2754            page_content = (active_page_render_fn)(self, window, cx);
2755        }
2756
2757        let mut warning_banner = gpui::Empty.into_any_element();
2758        if let Some(error) =
2759            SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2760        {
2761            fn banner(
2762                label: &'static str,
2763                error: String,
2764                shown_errors: &mut HashSet<String>,
2765                cx: &mut Context<SettingsWindow>,
2766            ) -> impl IntoElement {
2767                if shown_errors.insert(error.clone()) {
2768                    telemetry::event!("Settings Error Shown", label = label, error = &error);
2769                }
2770                Banner::new()
2771                    .severity(Severity::Warning)
2772                    .child(
2773                        v_flex()
2774                            .my_0p5()
2775                            .gap_0p5()
2776                            .child(Label::new(label))
2777                            .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
2778                    )
2779                    .action_slot(
2780                        div().pr_1().pb_1().child(
2781                            Button::new("fix-in-json", "Fix in settings.json")
2782                                .tab_index(0_isize)
2783                                .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2784                                .on_click(cx.listener(|this, _, window, cx| {
2785                                    this.open_current_settings_file(window, cx);
2786                                })),
2787                        ),
2788                    )
2789            }
2790
2791            let parse_error = error.parse_error();
2792            let parse_failed = parse_error.is_some();
2793
2794            warning_banner = v_flex()
2795                .gap_2()
2796                .when_some(parse_error, |this, err| {
2797                    this.child(banner(
2798                        "Failed to load your settings. Some values may be incorrect and changes may be lost.",
2799                        err,
2800                        &mut self.shown_errors,
2801                        cx,
2802                    ))
2803                })
2804                .map(|this| match &error.migration_status {
2805                    settings::MigrationStatus::Succeeded => this.child(banner(
2806                        "Your settings are out of date, and need to be updated.",
2807                        match &self.current_file {
2808                            SettingsUiFile::User => "They can be automatically migrated to the latest version.",
2809                            SettingsUiFile::Server(_) | SettingsUiFile::Project(_)  => "They must be manually migrated to the latest version."
2810                        }.to_string(),
2811                        &mut self.shown_errors,
2812                        cx,
2813                    )),
2814                    settings::MigrationStatus::Failed { error: err } if !parse_failed => this
2815                        .child(banner(
2816                            "Your settings file is out of date, automatic migration failed",
2817                            err.clone(),
2818                            &mut self.shown_errors,
2819                            cx,
2820                        )),
2821                    _ => this,
2822                })
2823                .into_any_element()
2824        }
2825
2826        return v_flex()
2827            .id("settings-ui-page")
2828            .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2829                if !sub_page_stack().is_empty() {
2830                    window.focus_next();
2831                    return;
2832                }
2833                for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2834                    let handle = this.content_handles[this.current_page_index()][actual_index]
2835                        .focus_handle(cx);
2836                    let mut offset = 1; // for page header
2837
2838                    if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2839                        && matches!(next_item, SettingsPageItem::SectionHeader(_))
2840                    {
2841                        offset += 1;
2842                    }
2843                    if handle.contains_focused(window, cx) {
2844                        let next_logical_index = logical_index + offset + 1;
2845                        this.list_state.scroll_to_reveal_item(next_logical_index);
2846                        // We need to render the next item to ensure it's focus handle is in the element tree
2847                        cx.on_next_frame(window, |_, window, cx| {
2848                            cx.notify();
2849                            cx.on_next_frame(window, |_, window, cx| {
2850                                window.focus_next();
2851                                cx.notify();
2852                            });
2853                        });
2854                        cx.notify();
2855                        return;
2856                    }
2857                }
2858                window.focus_next();
2859            }))
2860            .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2861                if !sub_page_stack().is_empty() {
2862                    window.focus_prev();
2863                    return;
2864                }
2865                let mut prev_was_header = false;
2866                for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
2867                    let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
2868                    let handle = this.content_handles[this.current_page_index()][actual_index]
2869                        .focus_handle(cx);
2870                    let mut offset = 1; // for page header
2871
2872                    if prev_was_header {
2873                        offset -= 1;
2874                    }
2875                    if handle.contains_focused(window, cx) {
2876                        let next_logical_index = logical_index + offset - 1;
2877                        this.list_state.scroll_to_reveal_item(next_logical_index);
2878                        // We need to render the next item to ensure it's focus handle is in the element tree
2879                        cx.on_next_frame(window, |_, window, cx| {
2880                            cx.notify();
2881                            cx.on_next_frame(window, |_, window, cx| {
2882                                window.focus_prev();
2883                                cx.notify();
2884                            });
2885                        });
2886                        cx.notify();
2887                        return;
2888                    }
2889                    prev_was_header = is_header;
2890                }
2891                window.focus_prev();
2892            }))
2893            .when(sub_page_stack().is_empty(), |this| {
2894                this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2895            })
2896            .when(!sub_page_stack().is_empty(), |this| {
2897                this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2898            })
2899            .track_focus(&self.content_focus_handle.focus_handle(cx))
2900            .pt_6()
2901            .gap_4()
2902            .flex_1()
2903            .bg(cx.theme().colors().editor_background)
2904            .child(
2905                v_flex()
2906                    .px_8()
2907                    .gap_2()
2908                    .child(page_header)
2909                    .child(warning_banner),
2910            )
2911            .child(
2912                div()
2913                    .flex_1()
2914                    .size_full()
2915                    .tab_group()
2916                    .tab_index(CONTENT_GROUP_TAB_INDEX)
2917                    .child(page_content),
2918            );
2919    }
2920
2921    /// This function will create a new settings file if one doesn't exist
2922    /// if the current file is a project settings with a valid worktree id
2923    /// We do this because the settings ui allows initializing project settings
2924    fn open_current_settings_file(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2925        match &self.current_file {
2926            SettingsUiFile::User => {
2927                let Some(original_window) = self.original_window else {
2928                    return;
2929                };
2930                original_window
2931                    .update(cx, |workspace, window, cx| {
2932                        workspace
2933                            .with_local_workspace(window, cx, |workspace, window, cx| {
2934                                let create_task = workspace.project().update(cx, |project, cx| {
2935                                    project.find_or_create_worktree(
2936                                        paths::config_dir().as_path(),
2937                                        false,
2938                                        cx,
2939                                    )
2940                                });
2941                                let open_task = workspace.open_paths(
2942                                    vec![paths::settings_file().to_path_buf()],
2943                                    OpenOptions {
2944                                        visible: Some(OpenVisible::None),
2945                                        ..Default::default()
2946                                    },
2947                                    None,
2948                                    window,
2949                                    cx,
2950                                );
2951
2952                                cx.spawn_in(window, async move |workspace, cx| {
2953                                    create_task.await.ok();
2954                                    open_task.await;
2955
2956                                    workspace.update_in(cx, |_, window, cx| {
2957                                        window.activate_window();
2958                                        cx.notify();
2959                                    })
2960                                })
2961                                .detach();
2962                            })
2963                            .detach();
2964                    })
2965                    .ok();
2966
2967                window.remove_window();
2968            }
2969            SettingsUiFile::Project((worktree_id, path)) => {
2970                let settings_path = path.join(paths::local_settings_file_relative_path());
2971                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2972                    return;
2973                };
2974
2975                let Some((worktree, corresponding_workspace)) = app_state
2976                    .workspace_store
2977                    .read(cx)
2978                    .workspaces()
2979                    .iter()
2980                    .find_map(|workspace| {
2981                        workspace
2982                            .read_with(cx, |workspace, cx| {
2983                                workspace
2984                                    .project()
2985                                    .read(cx)
2986                                    .worktree_for_id(*worktree_id, cx)
2987                            })
2988                            .ok()
2989                            .flatten()
2990                            .zip(Some(*workspace))
2991                    })
2992                else {
2993                    log::error!(
2994                        "No corresponding workspace contains worktree id: {}",
2995                        worktree_id
2996                    );
2997
2998                    return;
2999                };
3000
3001                let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3002                    None
3003                } else {
3004                    Some(worktree.update(cx, |tree, cx| {
3005                        tree.create_entry(
3006                            settings_path.clone(),
3007                            false,
3008                            Some("{\n\n}".as_bytes().to_vec()),
3009                            cx,
3010                        )
3011                    }))
3012                };
3013
3014                let worktree_id = *worktree_id;
3015
3016                // TODO: move zed::open_local_file() APIs to this crate, and
3017                // re-implement the "initial_contents" behavior
3018                corresponding_workspace
3019                    .update(cx, |_, window, cx| {
3020                        cx.spawn_in(window, async move |workspace, cx| {
3021                            if let Some(create_task) = create_task {
3022                                create_task.await.ok()?;
3023                            };
3024
3025                            workspace
3026                                .update_in(cx, |workspace, window, cx| {
3027                                    workspace.open_path(
3028                                        (worktree_id, settings_path.clone()),
3029                                        None,
3030                                        true,
3031                                        window,
3032                                        cx,
3033                                    )
3034                                })
3035                                .ok()?
3036                                .await
3037                                .log_err()?;
3038
3039                            workspace
3040                                .update_in(cx, |_, window, cx| {
3041                                    window.activate_window();
3042                                    cx.notify();
3043                                })
3044                                .ok();
3045
3046                            Some(())
3047                        })
3048                        .detach();
3049                    })
3050                    .ok();
3051
3052                window.remove_window();
3053            }
3054            SettingsUiFile::Server(_) => {
3055                // Server files are not editable
3056                return;
3057            }
3058        };
3059    }
3060
3061    fn current_page_index(&self) -> usize {
3062        self.page_index_from_navbar_index(self.navbar_entry)
3063    }
3064
3065    fn current_page(&self) -> &SettingsPage {
3066        &self.pages[self.current_page_index()]
3067    }
3068
3069    fn page_index_from_navbar_index(&self, index: usize) -> usize {
3070        if self.navbar_entries.is_empty() {
3071            return 0;
3072        }
3073
3074        self.navbar_entries[index].page_index
3075    }
3076
3077    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3078        ix == self.navbar_entry
3079    }
3080
3081    fn push_sub_page(
3082        &mut self,
3083        sub_page_link: SubPageLink,
3084        section_header: &'static str,
3085        cx: &mut Context<SettingsWindow>,
3086    ) {
3087        sub_page_stack_mut().push(SubPage {
3088            link: sub_page_link,
3089            section_header,
3090        });
3091        cx.notify();
3092    }
3093
3094    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
3095        sub_page_stack_mut().pop();
3096        cx.notify();
3097    }
3098
3099    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
3100        if let Some((_, handle)) = self.files.get(index) {
3101            handle.focus(window);
3102        }
3103    }
3104
3105    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3106        if self.files_focus_handle.contains_focused(window, cx)
3107            && let Some(index) = self
3108                .files
3109                .iter()
3110                .position(|(_, handle)| handle.is_focused(window))
3111        {
3112            return index;
3113        }
3114        if let Some(current_file_index) = self
3115            .files
3116            .iter()
3117            .position(|(file, _)| file == &self.current_file)
3118        {
3119            return current_file_index;
3120        }
3121        0
3122    }
3123
3124    fn focus_handle_for_content_element(
3125        &self,
3126        actual_item_index: usize,
3127        cx: &Context<Self>,
3128    ) -> FocusHandle {
3129        let page_index = self.current_page_index();
3130        self.content_handles[page_index][actual_item_index].focus_handle(cx)
3131    }
3132
3133    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3134        if !self
3135            .navbar_focus_handle
3136            .focus_handle(cx)
3137            .contains_focused(window, cx)
3138        {
3139            return None;
3140        }
3141        for (index, entry) in self.navbar_entries.iter().enumerate() {
3142            if entry.focus_handle.is_focused(window) {
3143                return Some(index);
3144            }
3145        }
3146        None
3147    }
3148
3149    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3150        let mut index = Some(nav_entry_index);
3151        while let Some(prev_index) = index
3152            && !self.navbar_entries[prev_index].is_root
3153        {
3154            index = prev_index.checked_sub(1);
3155        }
3156        return index.expect("No root entry found");
3157    }
3158}
3159
3160impl Render for SettingsWindow {
3161    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3162        let ui_font = theme::setup_ui_font(window, cx);
3163
3164        client_side_decorations(
3165            v_flex()
3166                .text_color(cx.theme().colors().text)
3167                .size_full()
3168                .children(self.title_bar.clone())
3169                .child(
3170                    div()
3171                        .id("settings-window")
3172                        .key_context("SettingsWindow")
3173                        .track_focus(&self.focus_handle)
3174                        .on_action(cx.listener(|this, _: &OpenCurrentFile, window, cx| {
3175                            this.open_current_settings_file(window, cx);
3176                        }))
3177                        .on_action(|_: &Minimize, window, _cx| {
3178                            window.minimize_window();
3179                        })
3180                        .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3181                            this.search_bar.focus_handle(cx).focus(window);
3182                        }))
3183                        .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3184                            if this
3185                                .navbar_focus_handle
3186                                .focus_handle(cx)
3187                                .contains_focused(window, cx)
3188                            {
3189                                this.open_and_scroll_to_navbar_entry(
3190                                    this.navbar_entry,
3191                                    None,
3192                                    true,
3193                                    window,
3194                                    cx,
3195                                );
3196                            } else {
3197                                this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3198                            }
3199                        }))
3200                        .on_action(cx.listener(
3201                            |this, FocusFile(file_index): &FocusFile, window, _| {
3202                                this.focus_file_at_index(*file_index as usize, window);
3203                            },
3204                        ))
3205                        .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3206                            let next_index = usize::min(
3207                                this.focused_file_index(window, cx) + 1,
3208                                this.files.len().saturating_sub(1),
3209                            );
3210                            this.focus_file_at_index(next_index, window);
3211                        }))
3212                        .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3213                            let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3214                            this.focus_file_at_index(prev_index, window);
3215                        }))
3216                        .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3217                            if this
3218                                .search_bar
3219                                .focus_handle(cx)
3220                                .contains_focused(window, cx)
3221                            {
3222                                this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3223                            } else {
3224                                window.focus_next();
3225                            }
3226                        }))
3227                        .on_action(|_: &menu::SelectPrevious, window, _| {
3228                            window.focus_prev();
3229                        })
3230                        .flex()
3231                        .flex_row()
3232                        .flex_1()
3233                        .min_h_0()
3234                        .font(ui_font)
3235                        .bg(cx.theme().colors().background)
3236                        .text_color(cx.theme().colors().text)
3237                        .when(!cfg!(target_os = "macos"), |this| {
3238                            this.border_t_1().border_color(cx.theme().colors().border)
3239                        })
3240                        .child(self.render_nav(window, cx))
3241                        .child(self.render_page(window, cx)),
3242                ),
3243            window,
3244            cx,
3245        )
3246    }
3247}
3248
3249fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
3250    workspace::AppState::global(cx)
3251        .upgrade()
3252        .map(|app_state| {
3253            app_state
3254                .workspace_store
3255                .read(cx)
3256                .workspaces()
3257                .iter()
3258                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
3259        })
3260        .into_iter()
3261        .flatten()
3262}
3263
3264fn update_settings_file(
3265    file: SettingsUiFile,
3266    file_name: Option<&'static str>,
3267    cx: &mut App,
3268    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3269) -> Result<()> {
3270    telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3271
3272    match file {
3273        SettingsUiFile::Project((worktree_id, rel_path)) => {
3274            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3275            let Some((worktree, project)) = all_projects(cx).find_map(|project| {
3276                project
3277                    .read(cx)
3278                    .worktree_for_id(worktree_id, cx)
3279                    .zip(Some(project))
3280            }) else {
3281                anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3282            };
3283
3284            project.update(cx, |project, cx| {
3285                let task = if project.contains_local_settings_file(worktree_id, &rel_path, cx) {
3286                    None
3287                } else {
3288                    Some(worktree.update(cx, |worktree, cx| {
3289                        worktree.create_entry(rel_path.clone(), false, None, cx)
3290                    }))
3291                };
3292
3293                cx.spawn(async move |project, cx| {
3294                    if let Some(task) = task
3295                        && task.await.is_err()
3296                    {
3297                        return;
3298                    };
3299
3300                    project
3301                        .update(cx, |project, cx| {
3302                            project.update_local_settings_file(worktree_id, rel_path, cx, update);
3303                        })
3304                        .ok();
3305                })
3306                .detach();
3307            });
3308
3309            return Ok(());
3310        }
3311        SettingsUiFile::User => {
3312            // todo(settings_ui) error?
3313            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3314            Ok(())
3315        }
3316        SettingsUiFile::Server(_) => unimplemented!(),
3317    }
3318}
3319
3320fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3321    field: SettingField<T>,
3322    file: SettingsUiFile,
3323    metadata: Option<&SettingsFieldMetadata>,
3324    _window: &mut Window,
3325    cx: &mut App,
3326) -> AnyElement {
3327    let (_, initial_text) =
3328        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3329    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3330
3331    SettingsInputField::new()
3332        .tab_index(0)
3333        .when_some(initial_text, |editor, text| {
3334            editor.with_initial_text(text.as_ref().to_string())
3335        })
3336        .when_some(
3337            metadata.and_then(|metadata| metadata.placeholder),
3338            |editor, placeholder| editor.with_placeholder(placeholder),
3339        )
3340        .on_confirm({
3341            move |new_text, cx| {
3342                update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3343                    (field.write)(settings, new_text.map(Into::into));
3344                })
3345                .log_err(); // todo(settings_ui) don't log err
3346            }
3347        })
3348        .into_any_element()
3349}
3350
3351fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3352    field: SettingField<B>,
3353    file: SettingsUiFile,
3354    _metadata: Option<&SettingsFieldMetadata>,
3355    _window: &mut Window,
3356    cx: &mut App,
3357) -> AnyElement {
3358    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3359
3360    let toggle_state = if value.copied().map_or(false, Into::into) {
3361        ToggleState::Selected
3362    } else {
3363        ToggleState::Unselected
3364    };
3365
3366    Switch::new("toggle_button", toggle_state)
3367        .tab_index(0_isize)
3368        .color(SwitchColor::Accent)
3369        .on_click({
3370            move |state, _window, cx| {
3371                telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());
3372
3373                let state = *state == ui::ToggleState::Selected;
3374                update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3375                    (field.write)(settings, Some(state.into()));
3376                })
3377                .log_err(); // todo(settings_ui) don't log err
3378            }
3379        })
3380        .into_any_element()
3381}
3382
3383fn render_number_field<T: NumberFieldType + Send + Sync>(
3384    field: SettingField<T>,
3385    file: SettingsUiFile,
3386    _metadata: Option<&SettingsFieldMetadata>,
3387    window: &mut Window,
3388    cx: &mut App,
3389) -> AnyElement {
3390    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3391    let value = value.copied().unwrap_or_else(T::min_value);
3392    NumberField::new("numeric_stepper", value, window, cx)
3393        .on_change({
3394            move |value, _window, cx| {
3395                let value = *value;
3396                update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3397                    (field.write)(settings, Some(value));
3398                })
3399                .log_err(); // todo(settings_ui) don't log err
3400            }
3401        })
3402        .into_any_element()
3403}
3404
3405fn render_dropdown<T>(
3406    field: SettingField<T>,
3407    file: SettingsUiFile,
3408    metadata: Option<&SettingsFieldMetadata>,
3409    _window: &mut Window,
3410    cx: &mut App,
3411) -> AnyElement
3412where
3413    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3414{
3415    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3416    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3417    let should_do_titlecase = metadata
3418        .and_then(|metadata| metadata.should_do_titlecase)
3419        .unwrap_or(true);
3420
3421    let (_, current_value) =
3422        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3423    let current_value = current_value.copied().unwrap_or(variants()[0]);
3424
3425    EnumVariantDropdown::new("dropdown", current_value, variants(), labels(), {
3426        move |value, cx| {
3427            if value == current_value {
3428                return;
3429            }
3430            update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3431                (field.write)(settings, Some(value));
3432            })
3433            .log_err(); // todo(settings_ui) don't log err
3434        }
3435    })
3436    .tab_index(0)
3437    .title_case(should_do_titlecase)
3438    .into_any_element()
3439}
3440
3441fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3442    Button::new(id, label)
3443        .tab_index(0_isize)
3444        .style(ButtonStyle::Outlined)
3445        .size(ButtonSize::Medium)
3446        .icon(IconName::ChevronUpDown)
3447        .icon_color(Color::Muted)
3448        .icon_size(IconSize::Small)
3449        .icon_position(IconPosition::End)
3450}
3451
3452fn render_font_picker(
3453    field: SettingField<settings::FontFamilyName>,
3454    file: SettingsUiFile,
3455    _metadata: Option<&SettingsFieldMetadata>,
3456    _window: &mut Window,
3457    cx: &mut App,
3458) -> AnyElement {
3459    let current_value = SettingsStore::global(cx)
3460        .get_value_from_file(file.to_settings(), field.pick)
3461        .1
3462        .cloned()
3463        .unwrap_or_else(|| SharedString::default().into());
3464
3465    PopoverMenu::new("font-picker")
3466        .trigger(render_picker_trigger_button(
3467            "font_family_picker_trigger".into(),
3468            current_value.clone().into(),
3469        ))
3470        .menu(move |window, cx| {
3471            let file = file.clone();
3472            let current_value = current_value.clone();
3473
3474            Some(cx.new(move |cx| {
3475                font_picker(
3476                    current_value.clone().into(),
3477                    move |font_name, cx| {
3478                        update_settings_file(
3479                            file.clone(),
3480                            field.json_path,
3481                            cx,
3482                            move |settings, _cx| {
3483                                (field.write)(settings, Some(font_name.into()));
3484                            },
3485                        )
3486                        .log_err(); // todo(settings_ui) don't log err
3487                    },
3488                    window,
3489                    cx,
3490                )
3491            }))
3492        })
3493        .anchor(gpui::Corner::TopLeft)
3494        .offset(gpui::Point {
3495            x: px(0.0),
3496            y: px(2.0),
3497        })
3498        .with_handle(ui::PopoverMenuHandle::default())
3499        .into_any_element()
3500}
3501
3502fn render_theme_picker(
3503    field: SettingField<settings::ThemeName>,
3504    file: SettingsUiFile,
3505    _metadata: Option<&SettingsFieldMetadata>,
3506    _window: &mut Window,
3507    cx: &mut App,
3508) -> AnyElement {
3509    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3510    let current_value = value
3511        .cloned()
3512        .map(|theme_name| theme_name.0.into())
3513        .unwrap_or_else(|| cx.theme().name.clone());
3514
3515    PopoverMenu::new("theme-picker")
3516        .trigger(render_picker_trigger_button(
3517            "theme_picker_trigger".into(),
3518            current_value.clone(),
3519        ))
3520        .menu(move |window, cx| {
3521            Some(cx.new(|cx| {
3522                let file = file.clone();
3523                let current_value = current_value.clone();
3524                theme_picker(
3525                    current_value,
3526                    move |theme_name, cx| {
3527                        update_settings_file(
3528                            file.clone(),
3529                            field.json_path,
3530                            cx,
3531                            move |settings, _cx| {
3532                                (field.write)(
3533                                    settings,
3534                                    Some(settings::ThemeName(theme_name.into())),
3535                                );
3536                            },
3537                        )
3538                        .log_err(); // todo(settings_ui) don't log err
3539                    },
3540                    window,
3541                    cx,
3542                )
3543            }))
3544        })
3545        .anchor(gpui::Corner::TopLeft)
3546        .offset(gpui::Point {
3547            x: px(0.0),
3548            y: px(2.0),
3549        })
3550        .with_handle(ui::PopoverMenuHandle::default())
3551        .into_any_element()
3552}
3553
3554fn render_icon_theme_picker(
3555    field: SettingField<settings::IconThemeName>,
3556    file: SettingsUiFile,
3557    _metadata: Option<&SettingsFieldMetadata>,
3558    _window: &mut Window,
3559    cx: &mut App,
3560) -> AnyElement {
3561    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3562    let current_value = value
3563        .cloned()
3564        .map(|theme_name| theme_name.0.into())
3565        .unwrap_or_else(|| cx.theme().name.clone());
3566
3567    PopoverMenu::new("icon-theme-picker")
3568        .trigger(render_picker_trigger_button(
3569            "icon_theme_picker_trigger".into(),
3570            current_value.clone(),
3571        ))
3572        .menu(move |window, cx| {
3573            Some(cx.new(|cx| {
3574                let file = file.clone();
3575                let current_value = current_value.clone();
3576                icon_theme_picker(
3577                    current_value,
3578                    move |theme_name, cx| {
3579                        update_settings_file(
3580                            file.clone(),
3581                            field.json_path,
3582                            cx,
3583                            move |settings, _cx| {
3584                                (field.write)(
3585                                    settings,
3586                                    Some(settings::IconThemeName(theme_name.into())),
3587                                );
3588                            },
3589                        )
3590                        .log_err(); // todo(settings_ui) don't log err
3591                    },
3592                    window,
3593                    cx,
3594                )
3595            }))
3596        })
3597        .anchor(gpui::Corner::TopLeft)
3598        .offset(gpui::Point {
3599            x: px(0.0),
3600            y: px(2.0),
3601        })
3602        .with_handle(ui::PopoverMenuHandle::default())
3603        .into_any_element()
3604}
3605
3606#[cfg(test)]
3607pub mod test {
3608
3609    use super::*;
3610
3611    impl SettingsWindow {
3612        fn navbar_entry(&self) -> usize {
3613            self.navbar_entry
3614        }
3615    }
3616
3617    impl PartialEq for NavBarEntry {
3618        fn eq(&self, other: &Self) -> bool {
3619            self.title == other.title
3620                && self.is_root == other.is_root
3621                && self.expanded == other.expanded
3622                && self.page_index == other.page_index
3623                && self.item_index == other.item_index
3624            // ignoring focus_handle
3625        }
3626    }
3627
3628    pub fn register_settings(cx: &mut App) {
3629        settings::init(cx);
3630        theme::init(theme::LoadThemes::JustBase, cx);
3631        editor::init(cx);
3632        menu::init();
3633    }
3634
3635    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3636        let mut pages: Vec<SettingsPage> = Vec::new();
3637        let mut expanded_pages = Vec::new();
3638        let mut selected_idx = None;
3639        let mut index = 0;
3640        let mut in_expanded_section = false;
3641
3642        for mut line in input
3643            .lines()
3644            .map(|line| line.trim())
3645            .filter(|line| !line.is_empty())
3646        {
3647            if let Some(pre) = line.strip_suffix('*') {
3648                assert!(selected_idx.is_none(), "Only one selected entry allowed");
3649                selected_idx = Some(index);
3650                line = pre;
3651            }
3652            let (kind, title) = line.split_once(" ").unwrap();
3653            assert_eq!(kind.len(), 1);
3654            let kind = kind.chars().next().unwrap();
3655            if kind == 'v' {
3656                let page_idx = pages.len();
3657                expanded_pages.push(page_idx);
3658                pages.push(SettingsPage {
3659                    title,
3660                    items: vec![],
3661                });
3662                index += 1;
3663                in_expanded_section = true;
3664            } else if kind == '>' {
3665                pages.push(SettingsPage {
3666                    title,
3667                    items: vec![],
3668                });
3669                index += 1;
3670                in_expanded_section = false;
3671            } else if kind == '-' {
3672                pages
3673                    .last_mut()
3674                    .unwrap()
3675                    .items
3676                    .push(SettingsPageItem::SectionHeader(title));
3677                if selected_idx == Some(index) && !in_expanded_section {
3678                    panic!("Items in unexpanded sections cannot be selected");
3679                }
3680                index += 1;
3681            } else {
3682                panic!(
3683                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
3684                    line
3685                );
3686            }
3687        }
3688
3689        let mut settings_window = SettingsWindow {
3690            title_bar: None,
3691            original_window: None,
3692            worktree_root_dirs: HashMap::default(),
3693            files: Vec::default(),
3694            current_file: crate::SettingsUiFile::User,
3695            pages,
3696            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3697            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3698            navbar_entries: Vec::default(),
3699            navbar_scroll_handle: UniformListScrollHandle::default(),
3700            navbar_focus_subscriptions: vec![],
3701            filter_table: vec![],
3702            has_query: false,
3703            content_handles: vec![],
3704            search_task: None,
3705            sub_page_scroll_handle: ScrollHandle::new(),
3706            focus_handle: cx.focus_handle(),
3707            navbar_focus_handle: NonFocusableHandle::new(
3708                NAVBAR_CONTAINER_TAB_INDEX,
3709                false,
3710                window,
3711                cx,
3712            ),
3713            content_focus_handle: NonFocusableHandle::new(
3714                CONTENT_CONTAINER_TAB_INDEX,
3715                false,
3716                window,
3717                cx,
3718            ),
3719            files_focus_handle: cx.focus_handle(),
3720            search_index: None,
3721            list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3722            shown_errors: HashSet::default(),
3723        };
3724
3725        settings_window.build_filter_table();
3726        settings_window.build_navbar(cx);
3727        for expanded_page_index in expanded_pages {
3728            for entry in &mut settings_window.navbar_entries {
3729                if entry.page_index == expanded_page_index && entry.is_root {
3730                    entry.expanded = true;
3731                }
3732            }
3733        }
3734        settings_window
3735    }
3736
3737    #[track_caller]
3738    fn check_navbar_toggle(
3739        before: &'static str,
3740        toggle_page: &'static str,
3741        after: &'static str,
3742        window: &mut Window,
3743        cx: &mut App,
3744    ) {
3745        let mut settings_window = parse(before, window, cx);
3746        let toggle_page_idx = settings_window
3747            .pages
3748            .iter()
3749            .position(|page| page.title == toggle_page)
3750            .expect("page not found");
3751        let toggle_idx = settings_window
3752            .navbar_entries
3753            .iter()
3754            .position(|entry| entry.page_index == toggle_page_idx)
3755            .expect("page not found");
3756        settings_window.toggle_navbar_entry(toggle_idx);
3757
3758        let expected_settings_window = parse(after, window, cx);
3759
3760        pretty_assertions::assert_eq!(
3761            settings_window
3762                .visible_navbar_entries()
3763                .map(|(_, entry)| entry)
3764                .collect::<Vec<_>>(),
3765            expected_settings_window
3766                .visible_navbar_entries()
3767                .map(|(_, entry)| entry)
3768                .collect::<Vec<_>>(),
3769        );
3770        pretty_assertions::assert_eq!(
3771            settings_window.navbar_entries[settings_window.navbar_entry()],
3772            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3773        );
3774    }
3775
3776    macro_rules! check_navbar_toggle {
3777        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3778            #[gpui::test]
3779            fn $name(cx: &mut gpui::TestAppContext) {
3780                let window = cx.add_empty_window();
3781                window.update(|window, cx| {
3782                    register_settings(cx);
3783                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
3784                });
3785            }
3786        };
3787    }
3788
3789    check_navbar_toggle!(
3790        navbar_basic_open,
3791        before: r"
3792        v General
3793        - General
3794        - Privacy*
3795        v Project
3796        - Project Settings
3797        ",
3798        toggle_page: "General",
3799        after: r"
3800        > General*
3801        v Project
3802        - Project Settings
3803        "
3804    );
3805
3806    check_navbar_toggle!(
3807        navbar_basic_close,
3808        before: r"
3809        > General*
3810        - General
3811        - Privacy
3812        v Project
3813        - Project Settings
3814        ",
3815        toggle_page: "General",
3816        after: r"
3817        v General*
3818        - General
3819        - Privacy
3820        v Project
3821        - Project Settings
3822        "
3823    );
3824
3825    check_navbar_toggle!(
3826        navbar_basic_second_root_entry_close,
3827        before: r"
3828        > General
3829        - General
3830        - Privacy
3831        v Project
3832        - Project Settings*
3833        ",
3834        toggle_page: "Project",
3835        after: r"
3836        > General
3837        > Project*
3838        "
3839    );
3840
3841    check_navbar_toggle!(
3842        navbar_toggle_subroot,
3843        before: r"
3844        v General Page
3845        - General
3846        - Privacy
3847        v Project
3848        - Worktree Settings Content*
3849        v AI
3850        - General
3851        > Appearance & Behavior
3852        ",
3853        toggle_page: "Project",
3854        after: r"
3855        v General Page
3856        - General
3857        - Privacy
3858        > Project*
3859        v AI
3860        - General
3861        > Appearance & Behavior
3862        "
3863    );
3864
3865    check_navbar_toggle!(
3866        navbar_toggle_close_propagates_selected_index,
3867        before: r"
3868        v General Page
3869        - General
3870        - Privacy
3871        v Project
3872        - Worktree Settings Content
3873        v AI
3874        - General*
3875        > Appearance & Behavior
3876        ",
3877        toggle_page: "General Page",
3878        after: r"
3879        > General Page*
3880        v Project
3881        - Worktree Settings Content
3882        v AI
3883        - General
3884        > Appearance & Behavior
3885        "
3886    );
3887
3888    check_navbar_toggle!(
3889        navbar_toggle_expand_propagates_selected_index,
3890        before: r"
3891        > General Page
3892        - General
3893        - Privacy
3894        v Project
3895        - Worktree Settings Content
3896        v AI
3897        - General*
3898        > Appearance & Behavior
3899        ",
3900        toggle_page: "General Page",
3901        after: r"
3902        v General Page*
3903        - General
3904        - Privacy
3905        v Project
3906        - Worktree Settings Content
3907        v AI
3908        - General
3909        > Appearance & Behavior
3910        "
3911    );
3912}