settings_ui.rs

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