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