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