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