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