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