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