settings_ui.rs

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