settings_ui.rs

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