settings_ui.rs

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