settings_ui.rs

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