settings_ui.rs

   1//! # settings_ui
   2mod components;
   3mod page_data;
   4
   5use anyhow::Result;
   6use editor::{Editor, EditorEvent};
   7use feature_flags::FeatureFlag;
   8use fuzzy::StringMatchCandidate;
   9use gpui::{
  10    Action, App, Div, Entity, FocusHandle, Focusable, FontWeight, Global, ReadGlobal as _,
  11    ScrollHandle, Stateful, Subscription, Task, TitlebarOptions, UniformListScrollHandle, Window,
  12    WindowBounds, WindowHandle, WindowOptions, actions, div, point, prelude::*, px, size,
  13    uniform_list,
  14};
  15use heck::ToTitleCase as _;
  16use project::WorktreeId;
  17use schemars::JsonSchema;
  18use serde::Deserialize;
  19use settings::{
  20    BottomDockLayout, CloseWindowWhenNoItems, CodeFade, CursorShape, OnLastWindowClosed,
  21    RestoreOnStartupBehavior, SaturatingBool, SettingsContent, SettingsStore,
  22};
  23use std::{
  24    any::{Any, TypeId, type_name},
  25    cell::RefCell,
  26    collections::HashMap,
  27    num::{NonZero, NonZeroU32},
  28    ops::Range,
  29    rc::Rc,
  30    sync::{Arc, LazyLock, RwLock, atomic::AtomicBool},
  31};
  32use ui::{
  33    ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape, KeyBinding,
  34    KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem, WithScrollbar,
  35    prelude::*,
  36};
  37use ui_input::{NumberField, NumberFieldType};
  38use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
  39use workspace::{OpenOptions, OpenVisible, Workspace};
  40use zed_actions::OpenSettingsEditor;
  41
  42use crate::components::SettingsEditor;
  43
  44const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
  45const NAVBAR_GROUP_TAB_INDEX: isize = 1;
  46
  47const HEADER_CONTAINER_TAB_INDEX: isize = 2;
  48const HEADER_GROUP_TAB_INDEX: isize = 3;
  49
  50const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
  51const CONTENT_GROUP_TAB_INDEX: isize = 5;
  52
  53actions!(
  54    settings_editor,
  55    [
  56        /// Minimizes the settings UI window.
  57        Minimize,
  58        /// Toggles focus between the navbar and the main content.
  59        ToggleFocusNav,
  60        /// Expands the navigation entry.
  61        ExpandNavEntry,
  62        /// Collapses the navigation entry.
  63        CollapseNavEntry,
  64        /// Focuses the next file in the file list.
  65        FocusNextFile,
  66        /// Focuses the previous file in the file list.
  67        FocusPreviousFile,
  68        /// Opens an editor for the current file
  69        OpenCurrentFile,
  70        /// Focuses the previous root navigation entry.
  71        FocusPreviousRootNavEntry,
  72        /// Focuses the next root navigation entry.
  73        FocusNextRootNavEntry,
  74        /// Focuses the first navigation entry.
  75        FocusFirstNavEntry,
  76        /// Focuses the last navigation entry.
  77        FocusLastNavEntry
  78    ]
  79);
  80
  81#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
  82#[action(namespace = settings_editor)]
  83struct FocusFile(pub u32);
  84
  85struct SettingField<T: 'static> {
  86    pick: fn(&SettingsContent) -> &Option<T>,
  87    pick_mut: fn(&mut SettingsContent) -> &mut Option<T>,
  88}
  89
  90impl<T: 'static> Clone for SettingField<T> {
  91    fn clone(&self) -> Self {
  92        *self
  93    }
  94}
  95
  96// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
  97impl<T: 'static> Copy for SettingField<T> {}
  98
  99/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
 100/// to keep the setting around in the UI with valid pick and pick_mut implementations, but don't actually try to render it.
 101/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
 102struct UnimplementedSettingField;
 103
 104impl<T: 'static> SettingField<T> {
 105    /// Helper for settings with types that are not yet implemented.
 106    #[allow(unused)]
 107    fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
 108        SettingField {
 109            pick: |_| &Some(UnimplementedSettingField),
 110            pick_mut: |_| unreachable!(),
 111        }
 112    }
 113}
 114
 115trait AnySettingField {
 116    fn as_any(&self) -> &dyn Any;
 117    fn type_name(&self) -> &'static str;
 118    fn type_id(&self) -> TypeId;
 119    // 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)
 120    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
 121}
 122
 123impl<T> AnySettingField for SettingField<T> {
 124    fn as_any(&self) -> &dyn Any {
 125        self
 126    }
 127
 128    fn type_name(&self) -> &'static str {
 129        type_name::<T>()
 130    }
 131
 132    fn type_id(&self) -> TypeId {
 133        TypeId::of::<T>()
 134    }
 135
 136    fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
 137        let (file, value) = cx
 138            .global::<SettingsStore>()
 139            .get_value_from_file(file.to_settings(), self.pick);
 140        return (file, value.is_some());
 141    }
 142}
 143
 144#[derive(Default, Clone)]
 145struct SettingFieldRenderer {
 146    renderers: Rc<
 147        RefCell<
 148            HashMap<
 149                TypeId,
 150                Box<
 151                    dyn Fn(
 152                        &SettingsWindow,
 153                        &SettingItem,
 154                        SettingsUiFile,
 155                        Option<&SettingsFieldMetadata>,
 156                        &mut Window,
 157                        &mut Context<SettingsWindow>,
 158                    ) -> Stateful<Div>,
 159                >,
 160            >,
 161        >,
 162    >,
 163}
 164
 165impl Global for SettingFieldRenderer {}
 166
 167impl SettingFieldRenderer {
 168    fn add_basic_renderer<T: 'static>(
 169        &mut self,
 170        render_control: impl Fn(
 171            SettingField<T>,
 172            SettingsUiFile,
 173            Option<&SettingsFieldMetadata>,
 174            &mut Window,
 175            &mut App,
 176        ) -> AnyElement
 177        + 'static,
 178    ) -> &mut Self {
 179        self.add_renderer(
 180            move |settings_window: &SettingsWindow,
 181                  item: &SettingItem,
 182                  field: SettingField<T>,
 183                  settings_file: SettingsUiFile,
 184                  metadata: Option<&SettingsFieldMetadata>,
 185                  window: &mut Window,
 186                  cx: &mut Context<SettingsWindow>| {
 187                render_settings_item(
 188                    settings_window,
 189                    item,
 190                    settings_file.clone(),
 191                    render_control(field, settings_file, metadata, window, cx),
 192                    window,
 193                    cx,
 194                )
 195            },
 196        )
 197    }
 198
 199    fn add_renderer<T: 'static>(
 200        &mut self,
 201        renderer: impl Fn(
 202            &SettingsWindow,
 203            &SettingItem,
 204            SettingField<T>,
 205            SettingsUiFile,
 206            Option<&SettingsFieldMetadata>,
 207            &mut Window,
 208            &mut Context<SettingsWindow>,
 209        ) -> Stateful<Div>
 210        + 'static,
 211    ) -> &mut Self {
 212        let key = TypeId::of::<T>();
 213        let renderer = Box::new(
 214            move |settings_window: &SettingsWindow,
 215                  item: &SettingItem,
 216                  settings_file: SettingsUiFile,
 217                  metadata: Option<&SettingsFieldMetadata>,
 218                  window: &mut Window,
 219                  cx: &mut Context<SettingsWindow>| {
 220                let field = *item
 221                    .field
 222                    .as_ref()
 223                    .as_any()
 224                    .downcast_ref::<SettingField<T>>()
 225                    .unwrap();
 226                renderer(
 227                    settings_window,
 228                    item,
 229                    field,
 230                    settings_file,
 231                    metadata,
 232                    window,
 233                    cx,
 234                )
 235            },
 236        );
 237        self.renderers.borrow_mut().insert(key, renderer);
 238        self
 239    }
 240}
 241
 242struct NonFocusableHandle {
 243    handle: FocusHandle,
 244    _subscription: Subscription,
 245}
 246
 247impl NonFocusableHandle {
 248    fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
 249        let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
 250        Self::from_handle(handle, window, cx)
 251    }
 252
 253    fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
 254        cx.new(|cx| {
 255            let _subscription = cx.on_focus(&handle, window, {
 256                move |_, window, _| {
 257                    window.focus_next();
 258                }
 259            });
 260            Self {
 261                handle,
 262                _subscription,
 263            }
 264        })
 265    }
 266}
 267
 268impl Focusable for NonFocusableHandle {
 269    fn focus_handle(&self, _: &App) -> FocusHandle {
 270        self.handle.clone()
 271    }
 272}
 273
 274struct SettingsFieldMetadata {
 275    placeholder: Option<&'static str>,
 276}
 277
 278pub struct SettingsUiFeatureFlag;
 279
 280impl FeatureFlag for SettingsUiFeatureFlag {
 281    const NAME: &'static str = "settings-ui";
 282}
 283
 284pub fn init(cx: &mut App) {
 285    init_renderers(cx);
 286
 287    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 288        workspace.register_action(|workspace, _: &OpenSettingsEditor, window, cx| {
 289            let window_handle = window
 290                .window_handle()
 291                .downcast::<Workspace>()
 292                .expect("Workspaces are root Windows");
 293            open_settings_editor(workspace, window_handle, cx);
 294        });
 295    })
 296    .detach();
 297}
 298
 299fn init_renderers(cx: &mut App) {
 300    cx.default_global::<SettingFieldRenderer>()
 301        .add_basic_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
 302            Button::new("open-in-settings-file", "Edit in settings.json")
 303                .style(ButtonStyle::Outlined)
 304                .size(ButtonSize::Medium)
 305                .tab_index(0_isize)
 306                .on_click(|_, window, cx| {
 307                    window.dispatch_action(Box::new(OpenCurrentFile), cx);
 308                })
 309                .into_any_element()
 310        })
 311        .add_basic_renderer::<bool>(render_toggle_button)
 312        .add_basic_renderer::<String>(render_text_field)
 313        .add_basic_renderer::<SaturatingBool>(render_toggle_button)
 314        .add_basic_renderer::<CursorShape>(render_dropdown)
 315        .add_basic_renderer::<RestoreOnStartupBehavior>(render_dropdown)
 316        .add_basic_renderer::<BottomDockLayout>(render_dropdown)
 317        .add_basic_renderer::<OnLastWindowClosed>(render_dropdown)
 318        .add_basic_renderer::<CloseWindowWhenNoItems>(render_dropdown)
 319        .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
 320        // todo(settings_ui): This needs custom ui
 321        // .add_renderer::<settings::BufferLineHeight>(|settings_field, file, _, window, cx| {
 322        //     // todo(settings_ui): Do we want to expose the custom variant of buffer line height?
 323        //     // right now there's a manual impl of strum::VariantArray
 324        //     render_dropdown(*settings_field, file, window, cx)
 325        // })
 326        .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
 327        .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
 328        .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
 329        .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
 330        .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
 331        .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
 332        .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
 333        .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
 334        .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
 335        .add_basic_renderer::<settings::DockSide>(render_dropdown)
 336        .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
 337        .add_basic_renderer::<settings::DockPosition>(render_dropdown)
 338        .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
 339        .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
 340        .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
 341        .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
 342        .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
 343        .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
 344        .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
 345        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 346        .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
 347        .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
 348        .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
 349        .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
 350        .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
 351        .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
 352        .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
 353        .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
 354        .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
 355        .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
 356        .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
 357        .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
 358        .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
 359        .add_basic_renderer::<f32>(render_number_field)
 360        .add_basic_renderer::<u32>(render_number_field)
 361        .add_basic_renderer::<u64>(render_number_field)
 362        .add_basic_renderer::<usize>(render_number_field)
 363        .add_basic_renderer::<NonZero<usize>>(render_number_field)
 364        .add_basic_renderer::<NonZeroU32>(render_number_field)
 365        .add_basic_renderer::<CodeFade>(render_number_field)
 366        .add_basic_renderer::<FontWeight>(render_number_field)
 367        .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
 368        .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
 369        .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
 370        .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
 371        .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
 372        .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
 373        .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
 374        .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown);
 375    // .add_renderer::<ThemeSelection>(|settings_field, file, _, window, cx| {
 376    //     render_dropdown(*settings_field, file, window, cx)
 377    // });
 378}
 379
 380pub fn open_settings_editor(
 381    _workspace: &mut Workspace,
 382    workspace_handle: WindowHandle<Workspace>,
 383    cx: &mut App,
 384) {
 385    let existing_window = cx
 386        .windows()
 387        .into_iter()
 388        .find_map(|window| window.downcast::<SettingsWindow>());
 389
 390    if let Some(existing_window) = existing_window {
 391        existing_window
 392            .update(cx, |settings_window, window, _| {
 393                settings_window.original_window = Some(workspace_handle);
 394                window.activate_window();
 395            })
 396            .ok();
 397        return;
 398    }
 399
 400    // We have to defer this to get the workspace off the stack.
 401
 402    cx.defer(move |cx| {
 403        cx.open_window(
 404            WindowOptions {
 405                titlebar: Some(TitlebarOptions {
 406                    title: Some("Settings Window".into()),
 407                    appears_transparent: true,
 408                    traffic_light_position: Some(point(px(12.0), px(12.0))),
 409                }),
 410                focus: true,
 411                show: true,
 412                kind: gpui::WindowKind::Normal,
 413                window_background: cx.theme().window_background_appearance(),
 414                window_min_size: Some(size(px(900.), px(750.))), // 4:3 Aspect Ratio
 415                window_bounds: Some(WindowBounds::centered(size(px(900.), px(750.)), cx)),
 416                ..Default::default()
 417            },
 418            |window, cx| cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx)),
 419        )
 420        .log_err();
 421    });
 422}
 423
 424/// The current sub page path that is selected.
 425/// If this is empty the selected page is rendered,
 426/// otherwise the last sub page gets rendered.
 427///
 428/// Global so that `pick` and `pick_mut` callbacks can access it
 429/// and use it to dynamically render sub pages (e.g. for language settings)
 430static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
 431
 432fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
 433    SUB_PAGE_STACK
 434        .read()
 435        .expect("SUB_PAGE_STACK is never poisoned")
 436}
 437
 438fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
 439    SUB_PAGE_STACK
 440        .write()
 441        .expect("SUB_PAGE_STACK is never poisoned")
 442}
 443
 444pub struct SettingsWindow {
 445    original_window: Option<WindowHandle<Workspace>>,
 446    files: Vec<(SettingsUiFile, FocusHandle)>,
 447    worktree_root_dirs: HashMap<WorktreeId, String>,
 448    current_file: SettingsUiFile,
 449    pages: Vec<SettingsPage>,
 450    search_bar: Entity<Editor>,
 451    search_task: Option<Task<()>>,
 452    /// Index into navbar_entries
 453    navbar_entry: usize,
 454    navbar_entries: Vec<NavBarEntry>,
 455    navbar_scroll_handle: UniformListScrollHandle,
 456    search_matches: Vec<Vec<bool>>,
 457    content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
 458    page_scroll_handle: ScrollHandle,
 459    focus_handle: FocusHandle,
 460    navbar_focus_handle: Entity<NonFocusableHandle>,
 461    content_focus_handle: Entity<NonFocusableHandle>,
 462    files_focus_handle: FocusHandle,
 463}
 464
 465struct SubPage {
 466    link: SubPageLink,
 467    section_header: &'static str,
 468}
 469
 470#[derive(Debug)]
 471struct NavBarEntry {
 472    title: &'static str,
 473    is_root: bool,
 474    expanded: bool,
 475    page_index: usize,
 476    item_index: Option<usize>,
 477    focus_handle: FocusHandle,
 478}
 479
 480struct SettingsPage {
 481    title: &'static str,
 482    items: Vec<SettingsPageItem>,
 483}
 484
 485#[derive(PartialEq)]
 486enum SettingsPageItem {
 487    SectionHeader(&'static str),
 488    SettingItem(SettingItem),
 489    SubPageLink(SubPageLink),
 490}
 491
 492impl std::fmt::Debug for SettingsPageItem {
 493    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 494        match self {
 495            SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
 496            SettingsPageItem::SettingItem(setting_item) => {
 497                write!(f, "SettingItem({})", setting_item.title)
 498            }
 499            SettingsPageItem::SubPageLink(sub_page_link) => {
 500                write!(f, "SubPageLink({})", sub_page_link.title)
 501            }
 502        }
 503    }
 504}
 505
 506impl SettingsPageItem {
 507    fn render(
 508        &self,
 509        settings_window: &SettingsWindow,
 510        section_header: &'static str,
 511        is_last: bool,
 512        window: &mut Window,
 513        cx: &mut Context<SettingsWindow>,
 514    ) -> AnyElement {
 515        let file = settings_window.current_file.clone();
 516        match self {
 517            SettingsPageItem::SectionHeader(header) => v_flex()
 518                .w_full()
 519                .gap_1p5()
 520                .child(
 521                    Label::new(SharedString::new_static(header))
 522                        .size(LabelSize::Small)
 523                        .color(Color::Muted)
 524                        .buffer_font(cx),
 525                )
 526                .child(Divider::horizontal().color(DividerColor::BorderFaded))
 527                .into_any_element(),
 528            SettingsPageItem::SettingItem(setting_item) => {
 529                let renderer = cx.default_global::<SettingFieldRenderer>().clone();
 530                let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
 531
 532                let renderers = renderer.renderers.borrow();
 533                let field_renderer =
 534                    renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
 535                let field_renderer_or_warning =
 536                    field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
 537                        if cfg!(debug_assertions) && !found {
 538                            Err("NO DEFAULT")
 539                        } else {
 540                            Ok(renderer)
 541                        }
 542                    });
 543
 544                let field = match field_renderer_or_warning {
 545                    Ok(field_renderer) => field_renderer(
 546                        settings_window,
 547                        setting_item,
 548                        file,
 549                        setting_item.metadata.as_deref(),
 550                        window,
 551                        cx,
 552                    ),
 553                    Err(warning) => render_settings_item(
 554                        settings_window,
 555                        setting_item,
 556                        file,
 557                        Button::new("error-warning", warning)
 558                            .style(ButtonStyle::Outlined)
 559                            .size(ButtonSize::Medium)
 560                            .icon(Some(IconName::Debug))
 561                            .icon_position(IconPosition::Start)
 562                            .icon_color(Color::Error)
 563                            .tab_index(0_isize)
 564                            .tooltip(Tooltip::text(setting_item.field.type_name()))
 565                            .into_any_element(),
 566                        window,
 567                        cx,
 568                    ),
 569                };
 570
 571                field
 572                    .pt_4()
 573                    .map(|this| {
 574                        if is_last {
 575                            this.pb_10()
 576                        } else {
 577                            this.pb_4()
 578                                .border_b_1()
 579                                .border_color(cx.theme().colors().border_variant)
 580                        }
 581                    })
 582                    .into_any_element()
 583            }
 584            SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
 585                .id(sub_page_link.title)
 586                .w_full()
 587                .min_w_0()
 588                .gap_2()
 589                .justify_between()
 590                .pt_4()
 591                .when(!is_last, |this| {
 592                    this.pb_4()
 593                        .border_b_1()
 594                        .border_color(cx.theme().colors().border_variant)
 595                })
 596                .child(
 597                    v_flex()
 598                        .w_full()
 599                        .max_w_1_2()
 600                        .child(Label::new(SharedString::new_static(sub_page_link.title))),
 601                )
 602                .child(
 603                    Button::new(("sub-page".into(), sub_page_link.title), "Configure")
 604                        .icon(IconName::ChevronRight)
 605                        .tab_index(0_isize)
 606                        .icon_position(IconPosition::End)
 607                        .icon_color(Color::Muted)
 608                        .icon_size(IconSize::Small)
 609                        .style(ButtonStyle::Outlined)
 610                        .size(ButtonSize::Medium),
 611                )
 612                .on_click({
 613                    let sub_page_link = sub_page_link.clone();
 614                    cx.listener(move |this, _, _, cx| {
 615                        this.push_sub_page(sub_page_link.clone(), section_header, cx)
 616                    })
 617                })
 618                .into_any_element(),
 619        }
 620    }
 621}
 622
 623fn render_settings_item(
 624    settings_window: &SettingsWindow,
 625    setting_item: &SettingItem,
 626    file: SettingsUiFile,
 627    control: AnyElement,
 628    _window: &mut Window,
 629    cx: &mut Context<'_, SettingsWindow>,
 630) -> Stateful<Div> {
 631    let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
 632    let file_set_in = SettingsUiFile::from_settings(found_in_file);
 633
 634    h_flex()
 635        .id(setting_item.title)
 636        .min_w_0()
 637        .gap_2()
 638        .justify_between()
 639        .child(
 640            v_flex()
 641                .w_1_2()
 642                .child(
 643                    h_flex()
 644                        .w_full()
 645                        .gap_1()
 646                        .child(Label::new(SharedString::new_static(setting_item.title)))
 647                        .when_some(
 648                            file_set_in.filter(|file_set_in| file_set_in != &file),
 649                            |this, file_set_in| {
 650                                this.child(
 651                                    Label::new(format!(
 652                                        "— set in {}",
 653                                        settings_window
 654                                            .display_name(&file_set_in)
 655                                            .expect("File name should exist")
 656                                    ))
 657                                    .color(Color::Muted)
 658                                    .size(LabelSize::Small),
 659                                )
 660                            },
 661                        ),
 662                )
 663                .child(
 664                    Label::new(SharedString::new_static(setting_item.description))
 665                        .size(LabelSize::Small)
 666                        .color(Color::Muted),
 667                ),
 668        )
 669        .child(control)
 670}
 671
 672struct SettingItem {
 673    title: &'static str,
 674    description: &'static str,
 675    field: Box<dyn AnySettingField>,
 676    metadata: Option<Box<SettingsFieldMetadata>>,
 677    files: FileMask,
 678}
 679
 680#[derive(PartialEq, Eq, Clone, Copy)]
 681struct FileMask(u8);
 682
 683impl std::fmt::Debug for FileMask {
 684    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 685        write!(f, "FileMask(")?;
 686        let mut items = vec![];
 687
 688        if self.contains(USER) {
 689            items.push("USER");
 690        }
 691        if self.contains(LOCAL) {
 692            items.push("LOCAL");
 693        }
 694        if self.contains(SERVER) {
 695            items.push("SERVER");
 696        }
 697
 698        write!(f, "{})", items.join(" | "))
 699    }
 700}
 701
 702const USER: FileMask = FileMask(1 << 0);
 703const LOCAL: FileMask = FileMask(1 << 2);
 704const SERVER: FileMask = FileMask(1 << 3);
 705
 706impl std::ops::BitAnd for FileMask {
 707    type Output = Self;
 708
 709    fn bitand(self, other: Self) -> Self {
 710        Self(self.0 & other.0)
 711    }
 712}
 713
 714impl std::ops::BitOr for FileMask {
 715    type Output = Self;
 716
 717    fn bitor(self, other: Self) -> Self {
 718        Self(self.0 | other.0)
 719    }
 720}
 721
 722impl FileMask {
 723    fn contains(&self, other: FileMask) -> bool {
 724        self.0 & other.0 != 0
 725    }
 726}
 727
 728impl PartialEq for SettingItem {
 729    fn eq(&self, other: &Self) -> bool {
 730        self.title == other.title
 731            && self.description == other.description
 732            && (match (&self.metadata, &other.metadata) {
 733                (None, None) => true,
 734                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
 735                _ => false,
 736            })
 737    }
 738}
 739
 740#[derive(Clone)]
 741struct SubPageLink {
 742    title: &'static str,
 743    files: FileMask,
 744    render: Arc<
 745        dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
 746            + 'static
 747            + Send
 748            + Sync,
 749    >,
 750}
 751
 752impl PartialEq for SubPageLink {
 753    fn eq(&self, other: &Self) -> bool {
 754        self.title == other.title
 755    }
 756}
 757
 758#[allow(unused)]
 759#[derive(Clone, PartialEq)]
 760enum SettingsUiFile {
 761    User,                                // Uses all settings.
 762    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
 763    Server(&'static str),                // Uses a special name, and the user settings
 764}
 765
 766impl SettingsUiFile {
 767    fn is_server(&self) -> bool {
 768        matches!(self, SettingsUiFile::Server(_))
 769    }
 770
 771    fn worktree_id(&self) -> Option<WorktreeId> {
 772        match self {
 773            SettingsUiFile::User => None,
 774            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
 775            SettingsUiFile::Server(_) => None,
 776        }
 777    }
 778
 779    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
 780        Some(match file {
 781            settings::SettingsFile::User => SettingsUiFile::User,
 782            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
 783            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
 784            settings::SettingsFile::Default => return None,
 785        })
 786    }
 787
 788    fn to_settings(&self) -> settings::SettingsFile {
 789        match self {
 790            SettingsUiFile::User => settings::SettingsFile::User,
 791            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
 792            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
 793        }
 794    }
 795
 796    fn mask(&self) -> FileMask {
 797        match self {
 798            SettingsUiFile::User => USER,
 799            SettingsUiFile::Project(_) => LOCAL,
 800            SettingsUiFile::Server(_) => SERVER,
 801        }
 802    }
 803}
 804
 805impl SettingsWindow {
 806    pub fn new(
 807        original_window: Option<WindowHandle<Workspace>>,
 808        window: &mut Window,
 809        cx: &mut Context<Self>,
 810    ) -> Self {
 811        let font_family_cache = theme::FontFamilyCache::global(cx);
 812
 813        cx.spawn(async move |this, cx| {
 814            font_family_cache.prefetch(cx).await;
 815            this.update(cx, |_, cx| {
 816                cx.notify();
 817            })
 818        })
 819        .detach();
 820
 821        let current_file = SettingsUiFile::User;
 822        let search_bar = cx.new(|cx| {
 823            let mut editor = Editor::single_line(window, cx);
 824            editor.set_placeholder_text("Search settings…", window, cx);
 825            editor
 826        });
 827
 828        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
 829            let EditorEvent::Edited { transaction_id: _ } = event else {
 830                return;
 831            };
 832
 833            this.update_matches(cx);
 834        })
 835        .detach();
 836
 837        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
 838            this.fetch_files(window, cx);
 839            cx.notify();
 840        })
 841        .detach();
 842
 843        let mut this = Self {
 844            original_window,
 845            worktree_root_dirs: HashMap::default(),
 846            files: vec![],
 847            current_file: current_file,
 848            pages: vec![],
 849            navbar_entries: vec![],
 850            navbar_entry: 0,
 851            navbar_scroll_handle: UniformListScrollHandle::default(),
 852            search_bar,
 853            search_task: None,
 854            search_matches: vec![],
 855            content_handles: vec![],
 856            page_scroll_handle: ScrollHandle::new(),
 857            focus_handle: cx.focus_handle(),
 858            navbar_focus_handle: NonFocusableHandle::new(
 859                NAVBAR_CONTAINER_TAB_INDEX,
 860                false,
 861                window,
 862                cx,
 863            ),
 864            content_focus_handle: NonFocusableHandle::new(
 865                CONTENT_CONTAINER_TAB_INDEX,
 866                false,
 867                window,
 868                cx,
 869            ),
 870            files_focus_handle: cx
 871                .focus_handle()
 872                .tab_index(HEADER_CONTAINER_TAB_INDEX)
 873                .tab_stop(false),
 874        };
 875
 876        this.fetch_files(window, cx);
 877        this.build_ui(window, cx);
 878
 879        this.search_bar.update(cx, |editor, cx| {
 880            editor.focus_handle(cx).focus(window);
 881        });
 882
 883        this
 884    }
 885
 886    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
 887        // We can only toggle root entries
 888        if !self.navbar_entries[nav_entry_index].is_root {
 889            return;
 890        }
 891
 892        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
 893        *expanded = !*expanded;
 894        let expanded = *expanded;
 895
 896        let toggle_page_index = self.page_index_from_navbar_index(nav_entry_index);
 897        let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
 898        // if currently selected page is a child of the parent page we are folding,
 899        // set the current page to the parent page
 900        if !expanded && selected_page_index == toggle_page_index {
 901            self.navbar_entry = nav_entry_index;
 902            // note: not opening page. Toggling does not change content just selected page
 903        }
 904    }
 905
 906    fn build_navbar(&mut self, cx: &App) {
 907        let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
 908        for (page_index, page) in self.pages.iter().enumerate() {
 909            navbar_entries.push(NavBarEntry {
 910                title: page.title,
 911                is_root: true,
 912                expanded: false,
 913                page_index,
 914                item_index: None,
 915                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
 916            });
 917
 918            for (item_index, item) in page.items.iter().enumerate() {
 919                let SettingsPageItem::SectionHeader(title) = item else {
 920                    continue;
 921                };
 922                navbar_entries.push(NavBarEntry {
 923                    title,
 924                    is_root: false,
 925                    expanded: false,
 926                    page_index,
 927                    item_index: Some(item_index),
 928                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
 929                });
 930            }
 931        }
 932
 933        self.navbar_entries = navbar_entries;
 934    }
 935
 936    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
 937        let mut index = 0;
 938        let entries = &self.navbar_entries;
 939        let search_matches = &self.search_matches;
 940        std::iter::from_fn(move || {
 941            while index < entries.len() {
 942                let entry = &entries[index];
 943                let included_in_search = if let Some(item_index) = entry.item_index {
 944                    search_matches[entry.page_index][item_index]
 945                } else {
 946                    search_matches[entry.page_index].iter().any(|b| *b)
 947                        || search_matches[entry.page_index].is_empty()
 948                };
 949                if included_in_search {
 950                    break;
 951                }
 952                index += 1;
 953            }
 954            if index >= self.navbar_entries.len() {
 955                return None;
 956            }
 957            let entry = &entries[index];
 958            let entry_index = index;
 959
 960            index += 1;
 961            if entry.is_root && !entry.expanded {
 962                while index < entries.len() {
 963                    if entries[index].is_root {
 964                        break;
 965                    }
 966                    index += 1;
 967                }
 968            }
 969
 970            return Some((entry_index, entry));
 971        })
 972    }
 973
 974    fn filter_matches_to_file(&mut self) {
 975        let current_file = self.current_file.mask();
 976        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.search_matches) {
 977            let mut header_index = 0;
 978            let mut any_found_since_last_header = true;
 979
 980            for (index, item) in page.items.iter().enumerate() {
 981                match item {
 982                    SettingsPageItem::SectionHeader(_) => {
 983                        if !any_found_since_last_header {
 984                            page_filter[header_index] = false;
 985                        }
 986                        header_index = index;
 987                        any_found_since_last_header = false;
 988                    }
 989                    SettingsPageItem::SettingItem(setting_item) => {
 990                        if !setting_item.files.contains(current_file) {
 991                            page_filter[index] = false;
 992                        } else {
 993                            any_found_since_last_header = true;
 994                        }
 995                    }
 996                    SettingsPageItem::SubPageLink(sub_page_link) => {
 997                        if !sub_page_link.files.contains(current_file) {
 998                            page_filter[index] = false;
 999                        } else {
1000                            any_found_since_last_header = true;
1001                        }
1002                    }
1003                }
1004            }
1005            if let Some(last_header) = page_filter.get_mut(header_index)
1006                && !any_found_since_last_header
1007            {
1008                *last_header = false;
1009            }
1010        }
1011    }
1012
1013    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1014        self.search_task.take();
1015        let query = self.search_bar.read(cx).text(cx);
1016        if query.is_empty() {
1017            for page in &mut self.search_matches {
1018                page.fill(true);
1019            }
1020            self.filter_matches_to_file();
1021            cx.notify();
1022            return;
1023        }
1024
1025        struct ItemKey {
1026            page_index: usize,
1027            header_index: usize,
1028            item_index: usize,
1029        }
1030        let mut key_lut: Vec<ItemKey> = vec![];
1031        let mut candidates = Vec::default();
1032
1033        for (page_index, page) in self.pages.iter().enumerate() {
1034            let mut header_index = 0;
1035            for (item_index, item) in page.items.iter().enumerate() {
1036                let key_index = key_lut.len();
1037                match item {
1038                    SettingsPageItem::SettingItem(item) => {
1039                        candidates.push(StringMatchCandidate::new(key_index, item.title));
1040                        candidates.push(StringMatchCandidate::new(key_index, item.description));
1041                    }
1042                    SettingsPageItem::SectionHeader(header) => {
1043                        candidates.push(StringMatchCandidate::new(key_index, header));
1044                        header_index = item_index;
1045                    }
1046                    SettingsPageItem::SubPageLink(sub_page_link) => {
1047                        candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
1048                    }
1049                }
1050                key_lut.push(ItemKey {
1051                    page_index,
1052                    header_index,
1053                    item_index,
1054                });
1055            }
1056        }
1057        let atomic_bool = AtomicBool::new(false);
1058
1059        self.search_task = Some(cx.spawn(async move |this, cx| {
1060            let string_matches = fuzzy::match_strings(
1061                candidates.as_slice(),
1062                &query,
1063                false,
1064                true,
1065                candidates.len(),
1066                &atomic_bool,
1067                cx.background_executor().clone(),
1068            );
1069            let string_matches = string_matches.await;
1070
1071            this.update(cx, |this, cx| {
1072                for page in &mut this.search_matches {
1073                    page.fill(false);
1074                }
1075
1076                for string_match in string_matches {
1077                    let ItemKey {
1078                        page_index,
1079                        header_index,
1080                        item_index,
1081                    } = key_lut[string_match.candidate_id];
1082                    let page = &mut this.search_matches[page_index];
1083                    page[header_index] = true;
1084                    page[item_index] = true;
1085                }
1086                this.filter_matches_to_file();
1087                this.open_first_nav_page();
1088                cx.notify();
1089            })
1090            .ok();
1091        }));
1092    }
1093
1094    fn build_search_matches(&mut self) {
1095        self.search_matches = self
1096            .pages
1097            .iter()
1098            .map(|page| vec![true; page.items.len()])
1099            .collect::<Vec<_>>();
1100    }
1101
1102    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1103        self.content_handles = self
1104            .pages
1105            .iter()
1106            .map(|page| {
1107                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1108                    .take(page.items.len())
1109                    .collect()
1110            })
1111            .collect::<Vec<_>>();
1112    }
1113
1114    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1115        if self.pages.is_empty() {
1116            self.pages = page_data::settings_data();
1117            self.build_navbar(cx);
1118            self.build_content_handles(window, cx);
1119        }
1120        sub_page_stack_mut().clear();
1121        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1122        self.build_search_matches();
1123        self.update_matches(cx);
1124
1125        cx.notify();
1126    }
1127
1128    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1129        self.worktree_root_dirs.clear();
1130        let prev_files = self.files.clone();
1131        let settings_store = cx.global::<SettingsStore>();
1132        let mut ui_files = vec![];
1133        let all_files = settings_store.get_all_files();
1134        for file in all_files {
1135            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1136                continue;
1137            };
1138            if settings_ui_file.is_server() {
1139                continue;
1140            }
1141
1142            if let Some(worktree_id) = settings_ui_file.worktree_id() {
1143                let directory_name = all_projects(cx)
1144                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1145                    .and_then(|worktree| worktree.read(cx).root_dir())
1146                    .and_then(|root_dir| {
1147                        root_dir
1148                            .file_name()
1149                            .map(|os_string| os_string.to_string_lossy().to_string())
1150                    });
1151
1152                let Some(directory_name) = directory_name else {
1153                    log::error!(
1154                        "No directory name found for settings file at worktree ID: {}",
1155                        worktree_id
1156                    );
1157                    continue;
1158                };
1159
1160                self.worktree_root_dirs.insert(worktree_id, directory_name);
1161            }
1162
1163            let focus_handle = prev_files
1164                .iter()
1165                .find_map(|(prev_file, handle)| {
1166                    (prev_file == &settings_ui_file).then(|| handle.clone())
1167                })
1168                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1169            ui_files.push((settings_ui_file, focus_handle));
1170        }
1171        ui_files.reverse();
1172        self.files = ui_files;
1173        let current_file_still_exists = self
1174            .files
1175            .iter()
1176            .any(|(file, _)| file == &self.current_file);
1177        if !current_file_still_exists {
1178            self.change_file(0, window, cx);
1179        }
1180    }
1181
1182    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1183        if !self.is_nav_entry_visible(navbar_entry) {
1184            self.open_first_nav_page();
1185        }
1186        self.navbar_entry = navbar_entry;
1187        sub_page_stack_mut().clear();
1188    }
1189
1190    fn open_first_nav_page(&mut self) {
1191        let first_navbar_entry_index = self
1192            .visible_navbar_entries()
1193            .next()
1194            .map(|e| e.0)
1195            .unwrap_or(0);
1196        self.open_navbar_entry_page(first_navbar_entry_index);
1197    }
1198
1199    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1200        if ix >= self.files.len() {
1201            self.current_file = SettingsUiFile::User;
1202            self.build_ui(window, cx);
1203            return;
1204        }
1205        if self.files[ix].0 == self.current_file {
1206            return;
1207        }
1208        self.current_file = self.files[ix].0.clone();
1209
1210        self.build_ui(window, cx);
1211
1212        if self
1213            .visible_navbar_entries()
1214            .any(|(index, _)| index == self.navbar_entry)
1215        {
1216            self.open_and_scroll_to_navbar_entry(self.navbar_entry, window, cx);
1217        } else {
1218            self.open_first_nav_page();
1219        };
1220    }
1221
1222    fn render_files_header(
1223        &self,
1224        _window: &mut Window,
1225        cx: &mut Context<SettingsWindow>,
1226    ) -> impl IntoElement {
1227        h_flex()
1228            .w_full()
1229            .pb_4()
1230            .gap_1()
1231            .justify_between()
1232            .tab_group()
1233            .track_focus(&self.files_focus_handle)
1234            .tab_index(HEADER_GROUP_TAB_INDEX)
1235            .child(
1236                h_flex()
1237                    .id("file_buttons_container")
1238                    .w_64() // Temporary fix until long-term solution is a fixed set of buttons representing a file location (User, Project, and Remote)
1239                    .gap_1()
1240                    .overflow_x_scroll()
1241                    .children(
1242                        self.files
1243                            .iter()
1244                            .enumerate()
1245                            .map(|(ix, (file, focus_handle))| {
1246                                Button::new(
1247                                    ix,
1248                                    self.display_name(&file)
1249                                        .expect("Files should always have a name"),
1250                                )
1251                                .toggle_state(file == &self.current_file)
1252                                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1253                                .track_focus(focus_handle)
1254                                .on_click(cx.listener({
1255                                    let focus_handle = focus_handle.clone();
1256                                    move |this, _: &gpui::ClickEvent, window, cx| {
1257                                        this.change_file(ix, window, cx);
1258                                        focus_handle.focus(window);
1259                                    }
1260                                }))
1261                            }),
1262                    ),
1263            )
1264            .child(
1265                Button::new("edit-in-json", "Edit in settings.json")
1266                    .tab_index(0_isize)
1267                    .style(ButtonStyle::OutlinedGhost)
1268                    .on_click(cx.listener(|this, _, _, cx| {
1269                        this.open_current_settings_file(cx);
1270                    })),
1271            )
1272    }
1273
1274    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1275        match file {
1276            SettingsUiFile::User => Some("User".to_string()),
1277            SettingsUiFile::Project((worktree_id, path)) => self
1278                .worktree_root_dirs
1279                .get(&worktree_id)
1280                .map(|directory_name| {
1281                    let path_style = PathStyle::local();
1282                    if path.is_empty() {
1283                        directory_name.clone()
1284                    } else {
1285                        format!(
1286                            "{}{}{}",
1287                            directory_name,
1288                            path_style.separator(),
1289                            path.display(path_style)
1290                        )
1291                    }
1292                }),
1293            SettingsUiFile::Server(file) => Some(file.to_string()),
1294        }
1295    }
1296
1297    // TODO:
1298    //  Reconsider this after preview launch
1299    // fn file_location_str(&self) -> String {
1300    //     match &self.current_file {
1301    //         SettingsUiFile::User => "settings.json".to_string(),
1302    //         SettingsUiFile::Project((worktree_id, path)) => self
1303    //             .worktree_root_dirs
1304    //             .get(&worktree_id)
1305    //             .map(|directory_name| {
1306    //                 let path_style = PathStyle::local();
1307    //                 let file_path = path.join(paths::local_settings_file_relative_path());
1308    //                 format!(
1309    //                     "{}{}{}",
1310    //                     directory_name,
1311    //                     path_style.separator(),
1312    //                     file_path.display(path_style)
1313    //                 )
1314    //             })
1315    //             .expect("Current file should always be present in root dir map"),
1316    //         SettingsUiFile::Server(file) => file.to_string(),
1317    //     }
1318    // }
1319
1320    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1321        h_flex()
1322            .py_1()
1323            .px_1p5()
1324            .mb_3()
1325            .gap_1p5()
1326            .rounded_sm()
1327            .bg(cx.theme().colors().editor_background)
1328            .border_1()
1329            .border_color(cx.theme().colors().border)
1330            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1331            .child(self.search_bar.clone())
1332    }
1333
1334    fn render_nav(
1335        &self,
1336        window: &mut Window,
1337        cx: &mut Context<SettingsWindow>,
1338    ) -> impl IntoElement {
1339        let visible_count = self.visible_navbar_entries().count();
1340
1341        let focus_keybind_label = if self
1342            .navbar_focus_handle
1343            .read(cx)
1344            .handle
1345            .contains_focused(window, cx)
1346        {
1347            "Focus Content"
1348        } else {
1349            "Focus Navbar"
1350        };
1351
1352        v_flex()
1353            .w_64()
1354            .p_2p5()
1355            .pt_10()
1356            .flex_none()
1357            .border_r_1()
1358            .key_context("NavigationMenu")
1359            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1360                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1361                    return;
1362                };
1363                let focused_entry_parent = this.root_entry_containing(focused_entry);
1364                if this.navbar_entries[focused_entry_parent].expanded {
1365                    this.toggle_navbar_entry(focused_entry_parent);
1366                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1367                }
1368                cx.notify();
1369            }))
1370            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1371                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1372                    return;
1373                };
1374                if !this.navbar_entries[focused_entry].is_root {
1375                    return;
1376                }
1377                if !this.navbar_entries[focused_entry].expanded {
1378                    this.toggle_navbar_entry(focused_entry);
1379                }
1380                cx.notify();
1381            }))
1382            .on_action(
1383                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1384                    let entry_index = this
1385                        .focused_nav_entry(window, cx)
1386                        .unwrap_or(this.navbar_entry);
1387                    let mut root_index = None;
1388                    for (index, entry) in this.visible_navbar_entries() {
1389                        if index >= entry_index {
1390                            break;
1391                        }
1392                        if entry.is_root {
1393                            root_index = Some(index);
1394                        }
1395                    }
1396                    let Some(previous_root_index) = root_index else {
1397                        return;
1398                    };
1399                    this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
1400                }),
1401            )
1402            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
1403                let entry_index = this
1404                    .focused_nav_entry(window, cx)
1405                    .unwrap_or(this.navbar_entry);
1406                let mut root_index = None;
1407                for (index, entry) in this.visible_navbar_entries() {
1408                    if index <= entry_index {
1409                        continue;
1410                    }
1411                    if entry.is_root {
1412                        root_index = Some(index);
1413                        break;
1414                    }
1415                }
1416                let Some(next_root_index) = root_index else {
1417                    return;
1418                };
1419                this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
1420            }))
1421            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
1422                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1423                    this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
1424                }
1425            }))
1426            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
1427                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1428                    this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
1429                }
1430            }))
1431            .border_color(cx.theme().colors().border)
1432            .bg(cx.theme().colors().panel_background)
1433            .child(self.render_search(window, cx))
1434            .child(
1435                v_flex()
1436                    .flex_grow()
1437                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1438                    .tab_group()
1439                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
1440                    .child(
1441                        uniform_list(
1442                            "settings-ui-nav-bar",
1443                            visible_count + 1,
1444                            cx.processor(move |this, range: Range<usize>, _, cx| {
1445                                this.visible_navbar_entries()
1446                                    .skip(range.start.saturating_sub(1))
1447                                    .take(range.len())
1448                                    .map(|(ix, entry)| {
1449                                        TreeViewItem::new(
1450                                            ("settings-ui-navbar-entry", ix),
1451                                            entry.title,
1452                                        )
1453                                        .track_focus(&entry.focus_handle)
1454                                        .root_item(entry.is_root)
1455                                        .toggle_state(this.is_navbar_entry_selected(ix))
1456                                        .when(entry.is_root, |item| {
1457                                            item.expanded(entry.expanded).on_toggle(cx.listener(
1458                                                move |this, _, window, cx| {
1459                                                    this.toggle_navbar_entry(ix);
1460                                                    window.focus(
1461                                                        &this.navbar_entries[ix].focus_handle,
1462                                                    );
1463                                                    cx.notify();
1464                                                },
1465                                            ))
1466                                        })
1467                                        .on_click(
1468                                            cx.listener(move |this, _, window, cx| {
1469                                                this.open_and_scroll_to_navbar_entry(
1470                                                    ix, window, cx,
1471                                                );
1472                                            }),
1473                                        )
1474                                    })
1475                                    .collect()
1476                            }),
1477                        )
1478                        .size_full()
1479                        .track_scroll(self.navbar_scroll_handle.clone()),
1480                    )
1481                    .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
1482            )
1483            .child(
1484                h_flex()
1485                    .w_full()
1486                    .p_2()
1487                    .pb_0p5()
1488                    .flex_none()
1489                    .border_t_1()
1490                    .border_color(cx.theme().colors().border_variant)
1491                    .children(
1492                        KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1493                            KeybindingHint::new(
1494                                this,
1495                                cx.theme().colors().surface_background.opacity(0.5),
1496                            )
1497                            .suffix(focus_keybind_label)
1498                        }),
1499                    ),
1500            )
1501    }
1502
1503    fn open_and_scroll_to_navbar_entry(
1504        &mut self,
1505        navbar_entry_index: usize,
1506        window: &mut Window,
1507        cx: &mut Context<Self>,
1508    ) {
1509        self.open_navbar_entry_page(navbar_entry_index);
1510        cx.notify();
1511
1512        if self.navbar_entries[navbar_entry_index].is_root
1513            || !self.is_nav_entry_visible(navbar_entry_index)
1514        {
1515            let Some(first_item_index) = self.visible_page_items().next().map(|(index, _)| index)
1516            else {
1517                return;
1518            };
1519            self.focus_content_element(first_item_index, window, cx);
1520            self.page_scroll_handle.set_offset(point(px(0.), px(0.)));
1521        } else {
1522            let entry_item_index = self.navbar_entries[navbar_entry_index]
1523                .item_index
1524                .expect("Non-root items should have an item index");
1525            let Some(selected_item_index) = self
1526                .visible_page_items()
1527                .position(|(index, _)| index == entry_item_index)
1528            else {
1529                return;
1530            };
1531            self.page_scroll_handle
1532                .scroll_to_top_of_item(selected_item_index);
1533            self.focus_content_element(entry_item_index, window, cx);
1534        }
1535
1536        // Page scroll handle updates the active item index
1537        // in it's next paint call after using scroll_handle.scroll_to_top_of_item
1538        // The call after that updates the offset of the scroll handle. So to
1539        // ensure the scroll handle doesn't lag behind we need to render three frames
1540        // back to back.
1541        cx.on_next_frame(window, |_, window, cx| {
1542            cx.on_next_frame(window, |_, _, cx| {
1543                cx.notify();
1544            });
1545            cx.notify();
1546        });
1547        cx.notify();
1548    }
1549
1550    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
1551        self.visible_navbar_entries()
1552            .any(|(index, _)| index == nav_entry_index)
1553    }
1554
1555    fn focus_and_scroll_to_nav_entry(
1556        &self,
1557        nav_entry_index: usize,
1558        window: &mut Window,
1559        cx: &mut Context<Self>,
1560    ) {
1561        let Some(position) = self
1562            .visible_navbar_entries()
1563            .position(|(index, _)| index == nav_entry_index)
1564        else {
1565            return;
1566        };
1567        self.navbar_scroll_handle
1568            .scroll_to_item(position, gpui::ScrollStrategy::Top);
1569        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
1570        cx.notify();
1571    }
1572
1573    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1574        let page_idx = self.current_page_index();
1575
1576        self.current_page()
1577            .items
1578            .iter()
1579            .enumerate()
1580            .filter_map(move |(item_index, item)| {
1581                self.search_matches[page_idx][item_index].then_some((item_index, item))
1582            })
1583    }
1584
1585    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1586        let mut items = vec![];
1587        items.push(self.current_page().title);
1588        items.extend(
1589            sub_page_stack()
1590                .iter()
1591                .flat_map(|page| [page.section_header, page.link.title]),
1592        );
1593
1594        let last = items.pop().unwrap();
1595        h_flex()
1596            .gap_1()
1597            .children(
1598                items
1599                    .into_iter()
1600                    .flat_map(|item| [item, "/"])
1601                    .map(|item| Label::new(item).color(Color::Muted)),
1602            )
1603            .child(Label::new(last))
1604    }
1605
1606    fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
1607        &self,
1608        items: Items,
1609        page_index: Option<usize>,
1610        window: &mut Window,
1611        cx: &mut Context<SettingsWindow>,
1612    ) -> impl IntoElement {
1613        let mut page_content = v_flex()
1614            .id("settings-ui-page")
1615            .size_full()
1616            .overflow_y_scroll()
1617            .track_scroll(&self.page_scroll_handle);
1618
1619        let items: Vec<_> = items.collect();
1620        let items_len = items.len();
1621        let mut section_header = None;
1622
1623        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1624        let has_no_results = items_len == 0 && has_active_search;
1625
1626        if has_no_results {
1627            let search_query = self.search_bar.read(cx).text(cx);
1628            page_content = page_content.child(
1629                v_flex()
1630                    .size_full()
1631                    .items_center()
1632                    .justify_center()
1633                    .gap_1()
1634                    .child(div().child("No Results"))
1635                    .child(
1636                        div()
1637                            .text_sm()
1638                            .text_color(cx.theme().colors().text_muted)
1639                            .child(format!("No settings match \"{}\"", search_query)),
1640                    ),
1641            )
1642        } else {
1643            let last_non_header_index = items
1644                .iter()
1645                .enumerate()
1646                .rev()
1647                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
1648                .map(|(index, _)| index);
1649
1650            page_content = page_content.children(items.clone().into_iter().enumerate().map(
1651                |(index, (actual_item_index, item))| {
1652                    let no_bottom_border = items
1653                        .get(index + 1)
1654                        .map(|(_, next_item)| {
1655                            matches!(next_item, SettingsPageItem::SectionHeader(_))
1656                        })
1657                        .unwrap_or(false);
1658                    let is_last = Some(index) == last_non_header_index;
1659
1660                    if let SettingsPageItem::SectionHeader(header) = item {
1661                        section_header = Some(*header);
1662                    }
1663                    v_flex()
1664                        .w_full()
1665                        .min_w_0()
1666                        .id(("settings-page-item", actual_item_index))
1667                        .when_some(page_index, |element, page_index| {
1668                            element.track_focus(
1669                                &self.content_handles[page_index][actual_item_index]
1670                                    .focus_handle(cx),
1671                            )
1672                        })
1673                        .child(item.render(
1674                            self,
1675                            section_header.expect("All items rendered after a section header"),
1676                            no_bottom_border || is_last,
1677                            window,
1678                            cx,
1679                        ))
1680                },
1681            ))
1682        }
1683        page_content
1684    }
1685
1686    fn render_page(
1687        &mut self,
1688        window: &mut Window,
1689        cx: &mut Context<SettingsWindow>,
1690    ) -> impl IntoElement {
1691        let page_header;
1692        let page_content;
1693
1694        if sub_page_stack().is_empty() {
1695            page_header = self.render_files_header(window, cx).into_any_element();
1696
1697            page_content = self
1698                .render_page_items(
1699                    self.visible_page_items(),
1700                    Some(self.current_page_index()),
1701                    window,
1702                    cx,
1703                )
1704                .into_any_element();
1705        } else {
1706            page_header = h_flex()
1707                .ml_neg_1p5()
1708                .pb_4()
1709                .gap_1()
1710                .child(
1711                    IconButton::new("back-btn", IconName::ArrowLeft)
1712                        .icon_size(IconSize::Small)
1713                        .shape(IconButtonShape::Square)
1714                        .on_click(cx.listener(|this, _, _, cx| {
1715                            this.pop_sub_page(cx);
1716                        })),
1717                )
1718                .child(self.render_sub_page_breadcrumbs())
1719                .into_any_element();
1720
1721            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1722            page_content = (active_page_render_fn)(self, window, cx);
1723        }
1724
1725        return v_flex()
1726            .size_full()
1727            .pt_6()
1728            .pb_8()
1729            .px_8()
1730            .bg(cx.theme().colors().editor_background)
1731            .child(page_header)
1732            .vertical_scrollbar_for(self.page_scroll_handle.clone(), window, cx)
1733            .track_focus(&self.content_focus_handle.focus_handle(cx))
1734            .child(
1735                div()
1736                    .size_full()
1737                    .tab_group()
1738                    .tab_index(CONTENT_GROUP_TAB_INDEX)
1739                    .child(page_content),
1740            );
1741    }
1742
1743    fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
1744        match &self.current_file {
1745            SettingsUiFile::User => {
1746                let Some(original_window) = self.original_window else {
1747                    return;
1748                };
1749                original_window
1750                    .update(cx, |workspace, window, cx| {
1751                        workspace
1752                            .with_local_workspace(window, cx, |workspace, window, cx| {
1753                                let create_task = workspace.project().update(cx, |project, cx| {
1754                                    project.find_or_create_worktree(
1755                                        paths::config_dir().as_path(),
1756                                        false,
1757                                        cx,
1758                                    )
1759                                });
1760                                let open_task = workspace.open_paths(
1761                                    vec![paths::settings_file().to_path_buf()],
1762                                    OpenOptions {
1763                                        visible: Some(OpenVisible::None),
1764                                        ..Default::default()
1765                                    },
1766                                    None,
1767                                    window,
1768                                    cx,
1769                                );
1770
1771                                cx.spawn_in(window, async move |workspace, cx| {
1772                                    create_task.await.ok();
1773                                    open_task.await;
1774
1775                                    workspace.update_in(cx, |_, window, cx| {
1776                                        window.activate_window();
1777                                        cx.notify();
1778                                    })
1779                                })
1780                                .detach();
1781                            })
1782                            .detach();
1783                    })
1784                    .ok();
1785            }
1786            SettingsUiFile::Project((worktree_id, path)) => {
1787                let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
1788                let settings_path = path.join(paths::local_settings_file_relative_path());
1789                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
1790                    return;
1791                };
1792                for workspace in app_state.workspace_store.read(cx).workspaces() {
1793                    let contains_settings_file = workspace
1794                        .read_with(cx, |workspace, cx| {
1795                            workspace.project().read(cx).contains_local_settings_file(
1796                                *worktree_id,
1797                                settings_path.as_ref(),
1798                                cx,
1799                            )
1800                        })
1801                        .ok();
1802                    if Some(true) == contains_settings_file {
1803                        corresponding_workspace = Some(*workspace);
1804
1805                        break;
1806                    }
1807                }
1808
1809                let Some(corresponding_workspace) = corresponding_workspace else {
1810                    log::error!(
1811                        "No corresponding workspace found for settings file {}",
1812                        settings_path.as_std_path().display()
1813                    );
1814
1815                    return;
1816                };
1817
1818                // TODO: move zed::open_local_file() APIs to this crate, and
1819                // re-implement the "initial_contents" behavior
1820                corresponding_workspace
1821                    .update(cx, |workspace, window, cx| {
1822                        let open_task = workspace.open_path(
1823                            (*worktree_id, settings_path.clone()),
1824                            None,
1825                            true,
1826                            window,
1827                            cx,
1828                        );
1829
1830                        cx.spawn_in(window, async move |workspace, cx| {
1831                            if open_task.await.log_err().is_some() {
1832                                workspace
1833                                    .update_in(cx, |_, window, cx| {
1834                                        window.activate_window();
1835                                        cx.notify();
1836                                    })
1837                                    .ok();
1838                            }
1839                        })
1840                        .detach();
1841                    })
1842                    .ok();
1843            }
1844            SettingsUiFile::Server(_) => {
1845                return;
1846            }
1847        };
1848    }
1849
1850    fn current_page_index(&self) -> usize {
1851        self.page_index_from_navbar_index(self.navbar_entry)
1852    }
1853
1854    fn current_page(&self) -> &SettingsPage {
1855        &self.pages[self.current_page_index()]
1856    }
1857
1858    fn page_index_from_navbar_index(&self, index: usize) -> usize {
1859        if self.navbar_entries.is_empty() {
1860            return 0;
1861        }
1862
1863        self.navbar_entries[index].page_index
1864    }
1865
1866    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1867        ix == self.navbar_entry
1868    }
1869
1870    fn push_sub_page(
1871        &mut self,
1872        sub_page_link: SubPageLink,
1873        section_header: &'static str,
1874        cx: &mut Context<SettingsWindow>,
1875    ) {
1876        sub_page_stack_mut().push(SubPage {
1877            link: sub_page_link,
1878            section_header,
1879        });
1880        cx.notify();
1881    }
1882
1883    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1884        sub_page_stack_mut().pop();
1885        cx.notify();
1886    }
1887
1888    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1889        if let Some((_, handle)) = self.files.get(index) {
1890            handle.focus(window);
1891        }
1892    }
1893
1894    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1895        if self.files_focus_handle.contains_focused(window, cx)
1896            && let Some(index) = self
1897                .files
1898                .iter()
1899                .position(|(_, handle)| handle.is_focused(window))
1900        {
1901            return index;
1902        }
1903        if let Some(current_file_index) = self
1904            .files
1905            .iter()
1906            .position(|(file, _)| file == &self.current_file)
1907        {
1908            return current_file_index;
1909        }
1910        0
1911    }
1912
1913    fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
1914        if !sub_page_stack().is_empty() {
1915            return;
1916        }
1917        let page_index = self.current_page_index();
1918        window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
1919    }
1920
1921    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
1922        if !self
1923            .navbar_focus_handle
1924            .focus_handle(cx)
1925            .contains_focused(window, cx)
1926        {
1927            return None;
1928        }
1929        for (index, entry) in self.navbar_entries.iter().enumerate() {
1930            if entry.focus_handle.is_focused(window) {
1931                return Some(index);
1932            }
1933        }
1934        None
1935    }
1936
1937    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
1938        let mut index = Some(nav_entry_index);
1939        while let Some(prev_index) = index
1940            && !self.navbar_entries[prev_index].is_root
1941        {
1942            index = prev_index.checked_sub(1);
1943        }
1944        return index.expect("No root entry found");
1945    }
1946}
1947
1948impl Render for SettingsWindow {
1949    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1950        let ui_font = theme::setup_ui_font(window, cx);
1951
1952        div()
1953            .id("settings-window")
1954            .key_context("SettingsWindow")
1955            .track_focus(&self.focus_handle)
1956            .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
1957                this.open_current_settings_file(cx);
1958            }))
1959            .on_action(|_: &Minimize, window, _cx| {
1960                window.minimize_window();
1961            })
1962            .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
1963                this.search_bar.focus_handle(cx).focus(window);
1964            }))
1965            .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
1966                if this
1967                    .navbar_focus_handle
1968                    .focus_handle(cx)
1969                    .contains_focused(window, cx)
1970                {
1971                    this.open_and_scroll_to_navbar_entry(this.navbar_entry, window, cx);
1972                } else {
1973                    this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
1974                }
1975            }))
1976            .on_action(
1977                cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
1978                    this.focus_file_at_index(*file_index as usize, window);
1979                }),
1980            )
1981            .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
1982                let next_index = usize::min(
1983                    this.focused_file_index(window, cx) + 1,
1984                    this.files.len().saturating_sub(1),
1985                );
1986                this.focus_file_at_index(next_index, window);
1987            }))
1988            .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
1989                let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
1990                this.focus_file_at_index(prev_index, window);
1991            }))
1992            .on_action(|_: &menu::SelectNext, window, _| {
1993                window.focus_next();
1994            })
1995            .on_action(|_: &menu::SelectPrevious, window, _| {
1996                window.focus_prev();
1997            })
1998            .flex()
1999            .flex_row()
2000            .size_full()
2001            .font(ui_font)
2002            .bg(cx.theme().colors().background)
2003            .text_color(cx.theme().colors().text)
2004            .child(self.render_nav(window, cx))
2005            .child(self.render_page(window, cx))
2006    }
2007}
2008
2009fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2010    workspace::AppState::global(cx)
2011        .upgrade()
2012        .map(|app_state| {
2013            app_state
2014                .workspace_store
2015                .read(cx)
2016                .workspaces()
2017                .iter()
2018                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2019        })
2020        .into_iter()
2021        .flatten()
2022}
2023
2024fn update_settings_file(
2025    file: SettingsUiFile,
2026    cx: &mut App,
2027    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2028) -> Result<()> {
2029    match file {
2030        SettingsUiFile::Project((worktree_id, rel_path)) => {
2031            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2032            let project = all_projects(cx).find(|project| {
2033                project.read_with(cx, |project, cx| {
2034                    project.contains_local_settings_file(worktree_id, &rel_path, cx)
2035                })
2036            });
2037            let Some(project) = project else {
2038                anyhow::bail!(
2039                    "Could not find worktree containing settings file: {}",
2040                    &rel_path.display(PathStyle::local())
2041                );
2042            };
2043            project.update(cx, |project, cx| {
2044                project.update_local_settings_file(worktree_id, rel_path, cx, update);
2045            });
2046            return Ok(());
2047        }
2048        SettingsUiFile::User => {
2049            // todo(settings_ui) error?
2050            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2051            Ok(())
2052        }
2053        SettingsUiFile::Server(_) => unimplemented!(),
2054    }
2055}
2056
2057fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2058    field: SettingField<T>,
2059    file: SettingsUiFile,
2060    metadata: Option<&SettingsFieldMetadata>,
2061    _window: &mut Window,
2062    cx: &mut App,
2063) -> AnyElement {
2064    let (_, initial_text) =
2065        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2066    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2067
2068    SettingsEditor::new()
2069        .tab_index(0)
2070        .when_some(initial_text, |editor, text| {
2071            editor.with_initial_text(text.as_ref().to_string())
2072        })
2073        .when_some(
2074            metadata.and_then(|metadata| metadata.placeholder),
2075            |editor, placeholder| editor.with_placeholder(placeholder),
2076        )
2077        .on_confirm({
2078            move |new_text, cx| {
2079                update_settings_file(file.clone(), cx, move |settings, _cx| {
2080                    *(field.pick_mut)(settings) = new_text.map(Into::into);
2081                })
2082                .log_err(); // todo(settings_ui) don't log err
2083            }
2084        })
2085        .into_any_element()
2086}
2087
2088fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2089    field: SettingField<B>,
2090    file: SettingsUiFile,
2091    _metadata: Option<&SettingsFieldMetadata>,
2092    _window: &mut Window,
2093    cx: &mut App,
2094) -> AnyElement {
2095    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2096
2097    let toggle_state = if value.copied().map_or(false, Into::into) {
2098        ToggleState::Selected
2099    } else {
2100        ToggleState::Unselected
2101    };
2102
2103    Switch::new("toggle_button", toggle_state)
2104        .color(ui::SwitchColor::Accent)
2105        .on_click({
2106            move |state, _window, cx| {
2107                let state = *state == ui::ToggleState::Selected;
2108                update_settings_file(file.clone(), cx, move |settings, _cx| {
2109                    *(field.pick_mut)(settings) = Some(state.into());
2110                })
2111                .log_err(); // todo(settings_ui) don't log err
2112            }
2113        })
2114        .tab_index(0_isize)
2115        .color(SwitchColor::Accent)
2116        .into_any_element()
2117}
2118
2119fn render_font_picker(
2120    field: SettingField<settings::FontFamilyName>,
2121    file: SettingsUiFile,
2122    _metadata: Option<&SettingsFieldMetadata>,
2123    window: &mut Window,
2124    cx: &mut App,
2125) -> AnyElement {
2126    let current_value = SettingsStore::global(cx)
2127        .get_value_from_file(file.to_settings(), field.pick)
2128        .1
2129        .cloned()
2130        .unwrap_or_else(|| SharedString::default().into());
2131
2132    let font_picker = cx.new(|cx| {
2133        ui_input::font_picker(
2134            current_value.clone().into(),
2135            move |font_name, cx| {
2136                update_settings_file(file.clone(), cx, move |settings, _cx| {
2137                    *(field.pick_mut)(settings) = Some(font_name.into());
2138                })
2139                .log_err(); // todo(settings_ui) don't log err
2140            },
2141            window,
2142            cx,
2143        )
2144    });
2145
2146    PopoverMenu::new("font-picker")
2147        .menu(move |_window, _cx| Some(font_picker.clone()))
2148        .trigger(
2149            Button::new("font-family-button", current_value)
2150                .tab_index(0_isize)
2151                .style(ButtonStyle::Outlined)
2152                .size(ButtonSize::Medium)
2153                .icon(IconName::ChevronUpDown)
2154                .icon_color(Color::Muted)
2155                .icon_size(IconSize::Small)
2156                .icon_position(IconPosition::End),
2157        )
2158        .anchor(gpui::Corner::TopLeft)
2159        .offset(gpui::Point {
2160            x: px(0.0),
2161            y: px(2.0),
2162        })
2163        .with_handle(ui::PopoverMenuHandle::default())
2164        .into_any_element()
2165}
2166
2167fn render_number_field<T: NumberFieldType + Send + Sync>(
2168    field: SettingField<T>,
2169    file: SettingsUiFile,
2170    _metadata: Option<&SettingsFieldMetadata>,
2171    window: &mut Window,
2172    cx: &mut App,
2173) -> AnyElement {
2174    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2175    let value = value.copied().unwrap_or_else(T::min_value);
2176    NumberField::new("numeric_stepper", value, window, cx)
2177        .on_change({
2178            move |value, _window, cx| {
2179                let value = *value;
2180                update_settings_file(file.clone(), cx, move |settings, _cx| {
2181                    *(field.pick_mut)(settings) = Some(value);
2182                })
2183                .log_err(); // todo(settings_ui) don't log err
2184            }
2185        })
2186        .into_any_element()
2187}
2188
2189fn render_dropdown<T>(
2190    field: SettingField<T>,
2191    file: SettingsUiFile,
2192    _metadata: Option<&SettingsFieldMetadata>,
2193    window: &mut Window,
2194    cx: &mut App,
2195) -> AnyElement
2196where
2197    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2198{
2199    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2200    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2201
2202    let (_, current_value) =
2203        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2204    let current_value = current_value.copied().unwrap_or(variants()[0]);
2205
2206    let current_value_label =
2207        labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2208
2209    DropdownMenu::new(
2210        "dropdown",
2211        current_value_label.to_title_case(),
2212        ContextMenu::build(window, cx, move |mut menu, _, _| {
2213            for (&value, &label) in std::iter::zip(variants(), labels()) {
2214                let file = file.clone();
2215                menu = menu.toggleable_entry(
2216                    label.to_title_case(),
2217                    value == current_value,
2218                    IconPosition::End,
2219                    None,
2220                    move |_, cx| {
2221                        if value == current_value {
2222                            return;
2223                        }
2224                        update_settings_file(file.clone(), cx, move |settings, _cx| {
2225                            *(field.pick_mut)(settings) = Some(value);
2226                        })
2227                        .log_err(); // todo(settings_ui) don't log err
2228                    },
2229                );
2230            }
2231            menu
2232        }),
2233    )
2234    .trigger_size(ButtonSize::Medium)
2235    .style(DropdownStyle::Outlined)
2236    .offset(gpui::Point {
2237        x: px(0.0),
2238        y: px(2.0),
2239    })
2240    .tab_index(0)
2241    .into_any_element()
2242}
2243
2244#[cfg(test)]
2245mod test {
2246
2247    use super::*;
2248
2249    impl SettingsWindow {
2250        fn navbar_entry(&self) -> usize {
2251            self.navbar_entry
2252        }
2253
2254        fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
2255            let mut this = Self::new(None, window, cx);
2256            this.navbar_entries.clear();
2257            this.pages.clear();
2258            this
2259        }
2260
2261        fn build(mut self, cx: &App) -> Self {
2262            self.build_search_matches();
2263            self.build_navbar(cx);
2264            self
2265        }
2266
2267        fn add_page(
2268            mut self,
2269            title: &'static str,
2270            build_page: impl Fn(SettingsPage) -> SettingsPage,
2271        ) -> Self {
2272            let page = SettingsPage {
2273                title,
2274                items: Vec::default(),
2275            };
2276
2277            self.pages.push(build_page(page));
2278            self
2279        }
2280
2281        fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
2282            self.search_task.take();
2283            self.search_bar.update(cx, |editor, cx| {
2284                editor.set_text(search_query, window, cx);
2285            });
2286            self.update_matches(cx);
2287        }
2288
2289        fn assert_search_results(&self, other: &Self) {
2290            // page index could be different because of filtered out pages
2291            #[derive(Debug, PartialEq)]
2292            struct EntryMinimal {
2293                is_root: bool,
2294                title: &'static str,
2295            }
2296            pretty_assertions::assert_eq!(
2297                other
2298                    .visible_navbar_entries()
2299                    .map(|(_, entry)| EntryMinimal {
2300                        is_root: entry.is_root,
2301                        title: entry.title,
2302                    })
2303                    .collect::<Vec<_>>(),
2304                self.visible_navbar_entries()
2305                    .map(|(_, entry)| EntryMinimal {
2306                        is_root: entry.is_root,
2307                        title: entry.title,
2308                    })
2309                    .collect::<Vec<_>>(),
2310            );
2311            assert_eq!(
2312                self.current_page().items.iter().collect::<Vec<_>>(),
2313                other
2314                    .visible_page_items()
2315                    .map(|(_, item)| item)
2316                    .collect::<Vec<_>>()
2317            );
2318        }
2319    }
2320
2321    impl SettingsPage {
2322        fn item(mut self, item: SettingsPageItem) -> Self {
2323            self.items.push(item);
2324            self
2325        }
2326    }
2327
2328    impl PartialEq for NavBarEntry {
2329        fn eq(&self, other: &Self) -> bool {
2330            self.title == other.title
2331                && self.is_root == other.is_root
2332                && self.expanded == other.expanded
2333                && self.page_index == other.page_index
2334                && self.item_index == other.item_index
2335            // ignoring focus_handle
2336        }
2337    }
2338
2339    impl SettingsPageItem {
2340        fn basic_item(title: &'static str, description: &'static str) -> Self {
2341            SettingsPageItem::SettingItem(SettingItem {
2342                files: USER,
2343                title,
2344                description,
2345                field: Box::new(SettingField {
2346                    pick: |settings_content| &settings_content.auto_update,
2347                    pick_mut: |settings_content| &mut settings_content.auto_update,
2348                }),
2349                metadata: None,
2350            })
2351        }
2352    }
2353
2354    fn register_settings(cx: &mut App) {
2355        settings::init(cx);
2356        theme::init(theme::LoadThemes::JustBase, cx);
2357        workspace::init_settings(cx);
2358        project::Project::init_settings(cx);
2359        language::init(cx);
2360        editor::init(cx);
2361        menu::init();
2362    }
2363
2364    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2365        let mut pages: Vec<SettingsPage> = Vec::new();
2366        let mut expanded_pages = Vec::new();
2367        let mut selected_idx = None;
2368        let mut index = 0;
2369        let mut in_expanded_section = false;
2370
2371        for mut line in input
2372            .lines()
2373            .map(|line| line.trim())
2374            .filter(|line| !line.is_empty())
2375        {
2376            if let Some(pre) = line.strip_suffix('*') {
2377                assert!(selected_idx.is_none(), "Only one selected entry allowed");
2378                selected_idx = Some(index);
2379                line = pre;
2380            }
2381            let (kind, title) = line.split_once(" ").unwrap();
2382            assert_eq!(kind.len(), 1);
2383            let kind = kind.chars().next().unwrap();
2384            if kind == 'v' {
2385                let page_idx = pages.len();
2386                expanded_pages.push(page_idx);
2387                pages.push(SettingsPage {
2388                    title,
2389                    items: vec![],
2390                });
2391                index += 1;
2392                in_expanded_section = true;
2393            } else if kind == '>' {
2394                pages.push(SettingsPage {
2395                    title,
2396                    items: vec![],
2397                });
2398                index += 1;
2399                in_expanded_section = false;
2400            } else if kind == '-' {
2401                pages
2402                    .last_mut()
2403                    .unwrap()
2404                    .items
2405                    .push(SettingsPageItem::SectionHeader(title));
2406                if selected_idx == Some(index) && !in_expanded_section {
2407                    panic!("Items in unexpanded sections cannot be selected");
2408                }
2409                index += 1;
2410            } else {
2411                panic!(
2412                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
2413                    line
2414                );
2415            }
2416        }
2417
2418        let mut settings_window = SettingsWindow {
2419            original_window: None,
2420            worktree_root_dirs: HashMap::default(),
2421            files: Vec::default(),
2422            current_file: crate::SettingsUiFile::User,
2423            pages,
2424            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2425            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2426            navbar_entries: Vec::default(),
2427            navbar_scroll_handle: UniformListScrollHandle::default(),
2428            search_matches: vec![],
2429            content_handles: vec![],
2430            search_task: None,
2431            page_scroll_handle: ScrollHandle::new(),
2432            focus_handle: cx.focus_handle(),
2433            navbar_focus_handle: NonFocusableHandle::new(
2434                NAVBAR_CONTAINER_TAB_INDEX,
2435                false,
2436                window,
2437                cx,
2438            ),
2439            content_focus_handle: NonFocusableHandle::new(
2440                CONTENT_CONTAINER_TAB_INDEX,
2441                false,
2442                window,
2443                cx,
2444            ),
2445            files_focus_handle: cx.focus_handle(),
2446        };
2447
2448        settings_window.build_search_matches();
2449        settings_window.build_navbar(cx);
2450        for expanded_page_index in expanded_pages {
2451            for entry in &mut settings_window.navbar_entries {
2452                if entry.page_index == expanded_page_index && entry.is_root {
2453                    entry.expanded = true;
2454                }
2455            }
2456        }
2457        settings_window
2458    }
2459
2460    #[track_caller]
2461    fn check_navbar_toggle(
2462        before: &'static str,
2463        toggle_page: &'static str,
2464        after: &'static str,
2465        window: &mut Window,
2466        cx: &mut App,
2467    ) {
2468        let mut settings_window = parse(before, window, cx);
2469        let toggle_page_idx = settings_window
2470            .pages
2471            .iter()
2472            .position(|page| page.title == toggle_page)
2473            .expect("page not found");
2474        let toggle_idx = settings_window
2475            .navbar_entries
2476            .iter()
2477            .position(|entry| entry.page_index == toggle_page_idx)
2478            .expect("page not found");
2479        settings_window.toggle_navbar_entry(toggle_idx);
2480
2481        let expected_settings_window = parse(after, window, cx);
2482
2483        pretty_assertions::assert_eq!(
2484            settings_window
2485                .visible_navbar_entries()
2486                .map(|(_, entry)| entry)
2487                .collect::<Vec<_>>(),
2488            expected_settings_window
2489                .visible_navbar_entries()
2490                .map(|(_, entry)| entry)
2491                .collect::<Vec<_>>(),
2492        );
2493        pretty_assertions::assert_eq!(
2494            settings_window.navbar_entries[settings_window.navbar_entry()],
2495            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2496        );
2497    }
2498
2499    macro_rules! check_navbar_toggle {
2500        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2501            #[gpui::test]
2502            fn $name(cx: &mut gpui::TestAppContext) {
2503                let window = cx.add_empty_window();
2504                window.update(|window, cx| {
2505                    register_settings(cx);
2506                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
2507                });
2508            }
2509        };
2510    }
2511
2512    check_navbar_toggle!(
2513        navbar_basic_open,
2514        before: r"
2515        v General
2516        - General
2517        - Privacy*
2518        v Project
2519        - Project Settings
2520        ",
2521        toggle_page: "General",
2522        after: r"
2523        > General*
2524        v Project
2525        - Project Settings
2526        "
2527    );
2528
2529    check_navbar_toggle!(
2530        navbar_basic_close,
2531        before: r"
2532        > General*
2533        - General
2534        - Privacy
2535        v Project
2536        - Project Settings
2537        ",
2538        toggle_page: "General",
2539        after: r"
2540        v General*
2541        - General
2542        - Privacy
2543        v Project
2544        - Project Settings
2545        "
2546    );
2547
2548    check_navbar_toggle!(
2549        navbar_basic_second_root_entry_close,
2550        before: r"
2551        > General
2552        - General
2553        - Privacy
2554        v Project
2555        - Project Settings*
2556        ",
2557        toggle_page: "Project",
2558        after: r"
2559        > General
2560        > Project*
2561        "
2562    );
2563
2564    check_navbar_toggle!(
2565        navbar_toggle_subroot,
2566        before: r"
2567        v General Page
2568        - General
2569        - Privacy
2570        v Project
2571        - Worktree Settings Content*
2572        v AI
2573        - General
2574        > Appearance & Behavior
2575        ",
2576        toggle_page: "Project",
2577        after: r"
2578        v General Page
2579        - General
2580        - Privacy
2581        > Project*
2582        v AI
2583        - General
2584        > Appearance & Behavior
2585        "
2586    );
2587
2588    check_navbar_toggle!(
2589        navbar_toggle_close_propagates_selected_index,
2590        before: r"
2591        v General Page
2592        - General
2593        - Privacy
2594        v Project
2595        - Worktree Settings Content
2596        v AI
2597        - General*
2598        > Appearance & Behavior
2599        ",
2600        toggle_page: "General Page",
2601        after: r"
2602        > General Page
2603        v Project
2604        - Worktree Settings Content
2605        v AI
2606        - General*
2607        > Appearance & Behavior
2608        "
2609    );
2610
2611    check_navbar_toggle!(
2612        navbar_toggle_expand_propagates_selected_index,
2613        before: r"
2614        > General Page
2615        - General
2616        - Privacy
2617        v Project
2618        - Worktree Settings Content
2619        v AI
2620        - General*
2621        > Appearance & Behavior
2622        ",
2623        toggle_page: "General Page",
2624        after: r"
2625        v General Page
2626        - General
2627        - Privacy
2628        v Project
2629        - Worktree Settings Content
2630        v AI
2631        - General*
2632        > Appearance & Behavior
2633        "
2634    );
2635
2636    #[gpui::test]
2637    fn test_basic_search(cx: &mut gpui::TestAppContext) {
2638        let cx = cx.add_empty_window();
2639        let (actual, expected) = cx.update(|window, cx| {
2640            register_settings(cx);
2641
2642            let expected = cx.new(|cx| {
2643                SettingsWindow::new_builder(window, cx)
2644                    .add_page("General", |page| {
2645                        page.item(SettingsPageItem::SectionHeader("General settings"))
2646                            .item(SettingsPageItem::basic_item("test title", "General test"))
2647                    })
2648                    .build(cx)
2649            });
2650
2651            let actual = cx.new(|cx| {
2652                SettingsWindow::new_builder(window, cx)
2653                    .add_page("General", |page| {
2654                        page.item(SettingsPageItem::SectionHeader("General settings"))
2655                            .item(SettingsPageItem::basic_item("test title", "General test"))
2656                    })
2657                    .add_page("Theme", |page| {
2658                        page.item(SettingsPageItem::SectionHeader("Theme settings"))
2659                    })
2660                    .build(cx)
2661            });
2662
2663            actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2664
2665            (actual, expected)
2666        });
2667
2668        cx.cx.run_until_parked();
2669
2670        cx.update(|_window, cx| {
2671            let expected = expected.read(cx);
2672            let actual = actual.read(cx);
2673            expected.assert_search_results(&actual);
2674        })
2675    }
2676
2677    #[gpui::test]
2678    fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2679        let cx = cx.add_empty_window();
2680        let (actual, expected) = cx.update(|window, cx| {
2681            register_settings(cx);
2682
2683            let actual = cx.new(|cx| {
2684                SettingsWindow::new_builder(window, cx)
2685                    .add_page("General", |page| {
2686                        page.item(SettingsPageItem::SectionHeader("General settings"))
2687                            .item(SettingsPageItem::basic_item(
2688                                "Confirm Quit",
2689                                "Whether to confirm before quitting Zed",
2690                            ))
2691                            .item(SettingsPageItem::basic_item(
2692                                "Auto Update",
2693                                "Automatically update Zed",
2694                            ))
2695                    })
2696                    .add_page("AI", |page| {
2697                        page.item(SettingsPageItem::basic_item(
2698                            "Disable AI",
2699                            "Whether to disable all AI features in Zed",
2700                        ))
2701                    })
2702                    .add_page("Appearance & Behavior", |page| {
2703                        page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2704                            SettingsPageItem::basic_item(
2705                                "Cursor Shape",
2706                                "Cursor shape for the editor",
2707                            ),
2708                        )
2709                    })
2710                    .build(cx)
2711            });
2712
2713            let expected = cx.new(|cx| {
2714                SettingsWindow::new_builder(window, cx)
2715                    .add_page("Appearance & Behavior", |page| {
2716                        page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2717                            SettingsPageItem::basic_item(
2718                                "Cursor Shape",
2719                                "Cursor shape for the editor",
2720                            ),
2721                        )
2722                    })
2723                    .build(cx)
2724            });
2725
2726            actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2727
2728            (actual, expected)
2729        });
2730
2731        cx.cx.run_until_parked();
2732
2733        cx.update(|_window, cx| {
2734            let expected = expected.read(cx);
2735            let actual = actual.read(cx);
2736            expected.assert_search_results(&actual);
2737        })
2738    }
2739}