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