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