settings_ui.rs

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