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