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::Normal,
 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                        .tab_index(0_isize)
 729                        .icon_position(IconPosition::End)
 730                        .icon_color(Color::Muted)
 731                        .icon_size(IconSize::Small)
 732                        .style(ButtonStyle::Outlined)
 733                        .size(ButtonSize::Medium),
 734                )
 735                .on_click({
 736                    let sub_page_link = sub_page_link.clone();
 737                    cx.listener(move |this, _, _, cx| {
 738                        this.push_sub_page(sub_page_link.clone(), section_header, cx)
 739                    })
 740                })
 741                .into_any_element(),
 742        }
 743    }
 744}
 745
 746struct SettingItem {
 747    title: &'static str,
 748    description: &'static str,
 749    field: Box<dyn AnySettingField>,
 750    metadata: Option<Box<SettingsFieldMetadata>>,
 751    files: FileMask,
 752}
 753
 754#[derive(PartialEq, Eq, Clone, Copy)]
 755struct FileMask(u8);
 756
 757impl std::fmt::Debug for FileMask {
 758    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 759        write!(f, "FileMask(")?;
 760        let mut items = vec![];
 761
 762        if self.contains(USER) {
 763            items.push("USER");
 764        }
 765        if self.contains(LOCAL) {
 766            items.push("LOCAL");
 767        }
 768        if self.contains(SERVER) {
 769            items.push("SERVER");
 770        }
 771
 772        write!(f, "{})", items.join(" | "))
 773    }
 774}
 775
 776const USER: FileMask = FileMask(1 << 0);
 777const LOCAL: FileMask = FileMask(1 << 2);
 778const SERVER: FileMask = FileMask(1 << 3);
 779
 780impl std::ops::BitAnd for FileMask {
 781    type Output = Self;
 782
 783    fn bitand(self, other: Self) -> Self {
 784        Self(self.0 & other.0)
 785    }
 786}
 787
 788impl std::ops::BitOr for FileMask {
 789    type Output = Self;
 790
 791    fn bitor(self, other: Self) -> Self {
 792        Self(self.0 | other.0)
 793    }
 794}
 795
 796impl FileMask {
 797    fn contains(&self, other: FileMask) -> bool {
 798        self.0 & other.0 != 0
 799    }
 800}
 801
 802impl PartialEq for SettingItem {
 803    fn eq(&self, other: &Self) -> bool {
 804        self.title == other.title
 805            && self.description == other.description
 806            && (match (&self.metadata, &other.metadata) {
 807                (None, None) => true,
 808                (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
 809                _ => false,
 810            })
 811    }
 812}
 813
 814#[derive(Clone)]
 815struct SubPageLink {
 816    title: &'static str,
 817    files: FileMask,
 818    render: Arc<
 819        dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
 820            + 'static
 821            + Send
 822            + Sync,
 823    >,
 824}
 825
 826impl PartialEq for SubPageLink {
 827    fn eq(&self, other: &Self) -> bool {
 828        self.title == other.title
 829    }
 830}
 831
 832#[allow(unused)]
 833#[derive(Clone, PartialEq)]
 834enum SettingsUiFile {
 835    User,                                // Uses all settings.
 836    Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
 837    Server(&'static str),                // Uses a special name, and the user settings
 838}
 839
 840impl SettingsUiFile {
 841    fn is_server(&self) -> bool {
 842        matches!(self, SettingsUiFile::Server(_))
 843    }
 844
 845    fn worktree_id(&self) -> Option<WorktreeId> {
 846        match self {
 847            SettingsUiFile::User => None,
 848            SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
 849            SettingsUiFile::Server(_) => None,
 850        }
 851    }
 852
 853    fn from_settings(file: settings::SettingsFile) -> Option<Self> {
 854        Some(match file {
 855            settings::SettingsFile::User => SettingsUiFile::User,
 856            settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
 857            settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
 858            settings::SettingsFile::Default => return None,
 859        })
 860    }
 861
 862    fn to_settings(&self) -> settings::SettingsFile {
 863        match self {
 864            SettingsUiFile::User => settings::SettingsFile::User,
 865            SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
 866            SettingsUiFile::Server(_) => settings::SettingsFile::Server,
 867        }
 868    }
 869
 870    fn mask(&self) -> FileMask {
 871        match self {
 872            SettingsUiFile::User => USER,
 873            SettingsUiFile::Project(_) => LOCAL,
 874            SettingsUiFile::Server(_) => SERVER,
 875        }
 876    }
 877}
 878
 879impl SettingsWindow {
 880    pub fn new(
 881        original_window: Option<WindowHandle<Workspace>>,
 882        window: &mut Window,
 883        cx: &mut Context<Self>,
 884    ) -> Self {
 885        let font_family_cache = theme::FontFamilyCache::global(cx);
 886
 887        cx.spawn(async move |this, cx| {
 888            font_family_cache.prefetch(cx).await;
 889            this.update(cx, |_, cx| {
 890                cx.notify();
 891            })
 892        })
 893        .detach();
 894
 895        let current_file = SettingsUiFile::User;
 896        let search_bar = cx.new(|cx| {
 897            let mut editor = Editor::single_line(window, cx);
 898            editor.set_placeholder_text("Search settings…", window, cx);
 899            editor
 900        });
 901
 902        cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
 903            let EditorEvent::Edited { transaction_id: _ } = event else {
 904                return;
 905            };
 906
 907            this.update_matches(cx);
 908        })
 909        .detach();
 910
 911        cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
 912            this.fetch_files(window, cx);
 913            cx.notify();
 914        })
 915        .detach();
 916
 917        let mut this = Self {
 918            original_window,
 919            worktree_root_dirs: HashMap::default(),
 920            files: vec![],
 921            current_file: current_file,
 922            pages: vec![],
 923            navbar_entries: vec![],
 924            navbar_entry: 0,
 925            list_handle: UniformListScrollHandle::default(),
 926            search_bar,
 927            search_task: None,
 928            search_matches: vec![],
 929            content_handles: vec![],
 930            scroll_handle: ScrollHandle::new(),
 931            focus_handle: cx.focus_handle(),
 932            navbar_focus_handle: NonFocusableHandle::new(
 933                NAVBAR_CONTAINER_TAB_INDEX,
 934                false,
 935                window,
 936                cx,
 937            ),
 938            content_focus_handle: NonFocusableHandle::new(
 939                CONTENT_CONTAINER_TAB_INDEX,
 940                false,
 941                window,
 942                cx,
 943            ),
 944            files_focus_handle: cx
 945                .focus_handle()
 946                .tab_index(HEADER_CONTAINER_TAB_INDEX)
 947                .tab_stop(false),
 948        };
 949
 950        this.fetch_files(window, cx);
 951        this.build_ui(window, cx);
 952
 953        this.search_bar.update(cx, |editor, cx| {
 954            editor.focus_handle(cx).focus(window);
 955        });
 956
 957        this
 958    }
 959
 960    fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
 961        // We can only toggle root entries
 962        if !self.navbar_entries[nav_entry_index].is_root {
 963            return;
 964        }
 965
 966        let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
 967        *expanded = !*expanded;
 968        let expanded = *expanded;
 969
 970        let toggle_page_index = self.page_index_from_navbar_index(nav_entry_index);
 971        let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
 972        // if currently selected page is a child of the parent page we are folding,
 973        // set the current page to the parent page
 974        if !expanded && selected_page_index == toggle_page_index {
 975            self.navbar_entry = nav_entry_index;
 976            // note: not opening page. Toggling does not change content just selected page
 977        }
 978    }
 979
 980    fn build_navbar(&mut self, cx: &App) {
 981        let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
 982        for (page_index, page) in self.pages.iter().enumerate() {
 983            navbar_entries.push(NavBarEntry {
 984                title: page.title,
 985                is_root: true,
 986                expanded: false,
 987                page_index,
 988                item_index: None,
 989                focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
 990            });
 991
 992            for (item_index, item) in page.items.iter().enumerate() {
 993                let SettingsPageItem::SectionHeader(title) = item else {
 994                    continue;
 995                };
 996                navbar_entries.push(NavBarEntry {
 997                    title,
 998                    is_root: false,
 999                    expanded: false,
1000                    page_index,
1001                    item_index: Some(item_index),
1002                    focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1003                });
1004            }
1005        }
1006
1007        self.navbar_entries = navbar_entries;
1008    }
1009
1010    fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1011        let mut index = 0;
1012        let entries = &self.navbar_entries;
1013        let search_matches = &self.search_matches;
1014        std::iter::from_fn(move || {
1015            while index < entries.len() {
1016                let entry = &entries[index];
1017                let included_in_search = if let Some(item_index) = entry.item_index {
1018                    search_matches[entry.page_index][item_index]
1019                } else {
1020                    search_matches[entry.page_index].iter().any(|b| *b)
1021                        || search_matches[entry.page_index].is_empty()
1022                };
1023                if included_in_search {
1024                    break;
1025                }
1026                index += 1;
1027            }
1028            if index >= self.navbar_entries.len() {
1029                return None;
1030            }
1031            let entry = &entries[index];
1032            let entry_index = index;
1033
1034            index += 1;
1035            if entry.is_root && !entry.expanded {
1036                while index < entries.len() {
1037                    if entries[index].is_root {
1038                        break;
1039                    }
1040                    index += 1;
1041                }
1042            }
1043
1044            return Some((entry_index, entry));
1045        })
1046    }
1047
1048    fn filter_matches_to_file(&mut self) {
1049        let current_file = self.current_file.mask();
1050        for (page, page_filter) in std::iter::zip(&self.pages, &mut self.search_matches) {
1051            let mut header_index = 0;
1052            let mut any_found_since_last_header = true;
1053
1054            for (index, item) in page.items.iter().enumerate() {
1055                match item {
1056                    SettingsPageItem::SectionHeader(_) => {
1057                        if !any_found_since_last_header {
1058                            page_filter[header_index] = false;
1059                        }
1060                        header_index = index;
1061                        any_found_since_last_header = false;
1062                    }
1063                    SettingsPageItem::SettingItem(setting_item) => {
1064                        if !setting_item.files.contains(current_file) {
1065                            page_filter[index] = false;
1066                        } else {
1067                            any_found_since_last_header = true;
1068                        }
1069                    }
1070                    SettingsPageItem::SubPageLink(sub_page_link) => {
1071                        if !sub_page_link.files.contains(current_file) {
1072                            page_filter[index] = false;
1073                        } else {
1074                            any_found_since_last_header = true;
1075                        }
1076                    }
1077                }
1078            }
1079            if let Some(last_header) = page_filter.get_mut(header_index)
1080                && !any_found_since_last_header
1081            {
1082                *last_header = false;
1083            }
1084        }
1085    }
1086
1087    fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1088        self.search_task.take();
1089        let query = self.search_bar.read(cx).text(cx);
1090        if query.is_empty() {
1091            for page in &mut self.search_matches {
1092                page.fill(true);
1093            }
1094            self.filter_matches_to_file();
1095            cx.notify();
1096            return;
1097        }
1098
1099        struct ItemKey {
1100            page_index: usize,
1101            header_index: usize,
1102            item_index: usize,
1103        }
1104        let mut key_lut: Vec<ItemKey> = vec![];
1105        let mut candidates = Vec::default();
1106
1107        for (page_index, page) in self.pages.iter().enumerate() {
1108            let mut header_index = 0;
1109            for (item_index, item) in page.items.iter().enumerate() {
1110                let key_index = key_lut.len();
1111                match item {
1112                    SettingsPageItem::SettingItem(item) => {
1113                        candidates.push(StringMatchCandidate::new(key_index, item.title));
1114                        candidates.push(StringMatchCandidate::new(key_index, item.description));
1115                    }
1116                    SettingsPageItem::SectionHeader(header) => {
1117                        candidates.push(StringMatchCandidate::new(key_index, header));
1118                        header_index = item_index;
1119                    }
1120                    SettingsPageItem::SubPageLink(sub_page_link) => {
1121                        candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
1122                    }
1123                }
1124                key_lut.push(ItemKey {
1125                    page_index,
1126                    header_index,
1127                    item_index,
1128                });
1129            }
1130        }
1131        let atomic_bool = AtomicBool::new(false);
1132
1133        self.search_task = Some(cx.spawn(async move |this, cx| {
1134            let string_matches = fuzzy::match_strings(
1135                candidates.as_slice(),
1136                &query,
1137                false,
1138                true,
1139                candidates.len(),
1140                &atomic_bool,
1141                cx.background_executor().clone(),
1142            );
1143            let string_matches = string_matches.await;
1144
1145            this.update(cx, |this, cx| {
1146                for page in &mut this.search_matches {
1147                    page.fill(false);
1148                }
1149
1150                for string_match in string_matches {
1151                    let ItemKey {
1152                        page_index,
1153                        header_index,
1154                        item_index,
1155                    } = key_lut[string_match.candidate_id];
1156                    let page = &mut this.search_matches[page_index];
1157                    page[header_index] = true;
1158                    page[item_index] = true;
1159                }
1160                this.filter_matches_to_file();
1161                this.open_first_nav_page();
1162                cx.notify();
1163            })
1164            .ok();
1165        }));
1166    }
1167
1168    fn build_search_matches(&mut self) {
1169        self.search_matches = self
1170            .pages
1171            .iter()
1172            .map(|page| vec![true; page.items.len()])
1173            .collect::<Vec<_>>();
1174    }
1175
1176    fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1177        self.content_handles = self
1178            .pages
1179            .iter()
1180            .map(|page| {
1181                std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1182                    .take(page.items.len())
1183                    .collect()
1184            })
1185            .collect::<Vec<_>>();
1186    }
1187
1188    fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1189        if self.pages.is_empty() {
1190            self.pages = page_data::settings_data();
1191            self.build_navbar(cx);
1192            self.build_content_handles(window, cx);
1193        }
1194        sub_page_stack_mut().clear();
1195        // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1196        self.build_search_matches();
1197        self.update_matches(cx);
1198
1199        cx.notify();
1200    }
1201
1202    fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1203        self.worktree_root_dirs.clear();
1204        let prev_files = self.files.clone();
1205        let settings_store = cx.global::<SettingsStore>();
1206        let mut ui_files = vec![];
1207        let all_files = settings_store.get_all_files();
1208        for file in all_files {
1209            let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1210                continue;
1211            };
1212            if settings_ui_file.is_server() {
1213                continue;
1214            }
1215
1216            if let Some(worktree_id) = settings_ui_file.worktree_id() {
1217                let directory_name = all_projects(cx)
1218                    .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1219                    .and_then(|worktree| worktree.read(cx).root_dir())
1220                    .and_then(|root_dir| {
1221                        root_dir
1222                            .file_name()
1223                            .map(|os_string| os_string.to_string_lossy().to_string())
1224                    });
1225
1226                let Some(directory_name) = directory_name else {
1227                    log::error!(
1228                        "No directory name found for settings file at worktree ID: {}",
1229                        worktree_id
1230                    );
1231                    continue;
1232                };
1233
1234                self.worktree_root_dirs.insert(worktree_id, directory_name);
1235            }
1236
1237            let focus_handle = prev_files
1238                .iter()
1239                .find_map(|(prev_file, handle)| {
1240                    (prev_file == &settings_ui_file).then(|| handle.clone())
1241                })
1242                .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1243            ui_files.push((settings_ui_file, focus_handle));
1244        }
1245        ui_files.reverse();
1246        self.files = ui_files;
1247        let current_file_still_exists = self
1248            .files
1249            .iter()
1250            .any(|(file, _)| file == &self.current_file);
1251        if !current_file_still_exists {
1252            self.change_file(0, window, cx);
1253        }
1254    }
1255
1256    fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1257        if !self.is_nav_entry_visible(navbar_entry) {
1258            self.open_first_nav_page();
1259        }
1260        self.navbar_entry = navbar_entry;
1261        sub_page_stack_mut().clear();
1262    }
1263
1264    fn open_first_nav_page(&mut self) {
1265        let first_navbar_entry_index = self
1266            .visible_navbar_entries()
1267            .next()
1268            .map(|e| e.0)
1269            .unwrap_or(0);
1270        self.open_navbar_entry_page(first_navbar_entry_index);
1271    }
1272
1273    fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1274        if ix >= self.files.len() {
1275            self.current_file = SettingsUiFile::User;
1276            self.build_ui(window, cx);
1277            return;
1278        }
1279        if self.files[ix].0 == self.current_file {
1280            return;
1281        }
1282        self.current_file = self.files[ix].0.clone();
1283
1284        self.build_ui(window, cx);
1285
1286        if self
1287            .visible_navbar_entries()
1288            .any(|(index, _)| index == self.navbar_entry)
1289        {
1290            self.open_and_scroll_to_navbar_entry(self.navbar_entry, window, cx);
1291        } else {
1292            self.open_first_nav_page();
1293        };
1294    }
1295
1296    fn render_files_header(
1297        &self,
1298        _window: &mut Window,
1299        cx: &mut Context<SettingsWindow>,
1300    ) -> impl IntoElement {
1301        h_flex()
1302            .w_full()
1303            .pb_4()
1304            .gap_1()
1305            .justify_between()
1306            .tab_group()
1307            .track_focus(&self.files_focus_handle)
1308            .tab_index(HEADER_GROUP_TAB_INDEX)
1309            .child(
1310                h_flex()
1311                    .id("file_buttons_container")
1312                    .w_64() // Temporary fix until long-term solution is a fixed set of buttons representing a file location (User, Project, and Remote)
1313                    .gap_1()
1314                    .overflow_x_scroll()
1315                    .children(
1316                        self.files
1317                            .iter()
1318                            .enumerate()
1319                            .map(|(ix, (file, focus_handle))| {
1320                                Button::new(
1321                                    ix,
1322                                    self.display_name(&file)
1323                                        .expect("Files should always have a name"),
1324                                )
1325                                .toggle_state(file == &self.current_file)
1326                                .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1327                                .track_focus(focus_handle)
1328                                .on_click(cx.listener({
1329                                    let focus_handle = focus_handle.clone();
1330                                    move |this, _: &gpui::ClickEvent, window, cx| {
1331                                        this.change_file(ix, window, cx);
1332                                        focus_handle.focus(window);
1333                                    }
1334                                }))
1335                            }),
1336                    ),
1337            )
1338            .child(
1339                Button::new("edit-in-json", "Edit in settings.json")
1340                    .tab_index(0_isize)
1341                    .style(ButtonStyle::OutlinedGhost)
1342                    .on_click(cx.listener(|this, _, _, cx| {
1343                        this.open_current_settings_file(cx);
1344                    })),
1345            )
1346    }
1347
1348    pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1349        match file {
1350            SettingsUiFile::User => Some("User".to_string()),
1351            SettingsUiFile::Project((worktree_id, path)) => self
1352                .worktree_root_dirs
1353                .get(&worktree_id)
1354                .map(|directory_name| {
1355                    let path_style = PathStyle::local();
1356                    if path.is_empty() {
1357                        directory_name.clone()
1358                    } else {
1359                        format!(
1360                            "{}{}{}",
1361                            directory_name,
1362                            path_style.separator(),
1363                            path.display(path_style)
1364                        )
1365                    }
1366                }),
1367            SettingsUiFile::Server(file) => Some(file.to_string()),
1368        }
1369    }
1370
1371    // TODO:
1372    //  Reconsider this after preview launch
1373    // fn file_location_str(&self) -> String {
1374    //     match &self.current_file {
1375    //         SettingsUiFile::User => "settings.json".to_string(),
1376    //         SettingsUiFile::Project((worktree_id, path)) => self
1377    //             .worktree_root_dirs
1378    //             .get(&worktree_id)
1379    //             .map(|directory_name| {
1380    //                 let path_style = PathStyle::local();
1381    //                 let file_path = path.join(paths::local_settings_file_relative_path());
1382    //                 format!(
1383    //                     "{}{}{}",
1384    //                     directory_name,
1385    //                     path_style.separator(),
1386    //                     file_path.display(path_style)
1387    //                 )
1388    //             })
1389    //             .expect("Current file should always be present in root dir map"),
1390    //         SettingsUiFile::Server(file) => file.to_string(),
1391    //     }
1392    // }
1393
1394    fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1395        h_flex()
1396            .py_1()
1397            .px_1p5()
1398            .mb_3()
1399            .gap_1p5()
1400            .rounded_sm()
1401            .bg(cx.theme().colors().editor_background)
1402            .border_1()
1403            .border_color(cx.theme().colors().border)
1404            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1405            .child(self.search_bar.clone())
1406    }
1407
1408    fn render_nav(
1409        &self,
1410        window: &mut Window,
1411        cx: &mut Context<SettingsWindow>,
1412    ) -> impl IntoElement {
1413        let visible_count = self.visible_navbar_entries().count();
1414
1415        // let focus_keybind_label = if self.navbar_focus_handle.contains_focused(window, cx) {
1416        //     "Focus Content"
1417        // } else {
1418        //     "Focus Navbar"
1419        // };
1420
1421        v_flex()
1422            .w_64()
1423            .p_2p5()
1424            .pt_10()
1425            .flex_none()
1426            .border_r_1()
1427            .key_context("NavigationMenu")
1428            .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1429                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1430                    return;
1431                };
1432                let focused_entry_parent = this.root_entry_containing(focused_entry);
1433                if this.navbar_entries[focused_entry_parent].expanded {
1434                    this.toggle_navbar_entry(focused_entry_parent);
1435                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1436                }
1437                cx.notify();
1438            }))
1439            .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1440                let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1441                    return;
1442                };
1443                if !this.navbar_entries[focused_entry].is_root {
1444                    return;
1445                }
1446                if !this.navbar_entries[focused_entry].expanded {
1447                    this.toggle_navbar_entry(focused_entry);
1448                }
1449                cx.notify();
1450            }))
1451            .on_action(
1452                cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1453                    let entry_index = this
1454                        .focused_nav_entry(window, cx)
1455                        .unwrap_or(this.navbar_entry);
1456                    let mut root_index = None;
1457                    for (index, entry) in this.visible_navbar_entries() {
1458                        if index >= entry_index {
1459                            break;
1460                        }
1461                        if entry.is_root {
1462                            root_index = Some(index);
1463                        }
1464                    }
1465                    let Some(previous_root_index) = root_index else {
1466                        return;
1467                    };
1468                    this.focus_and_scroll_to_nav_entry(previous_root_index, window);
1469                }),
1470            )
1471            .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
1472                let entry_index = this
1473                    .focused_nav_entry(window, cx)
1474                    .unwrap_or(this.navbar_entry);
1475                let mut root_index = None;
1476                for (index, entry) in this.visible_navbar_entries() {
1477                    if index <= entry_index {
1478                        continue;
1479                    }
1480                    if entry.is_root {
1481                        root_index = Some(index);
1482                        break;
1483                    }
1484                }
1485                let Some(next_root_index) = root_index else {
1486                    return;
1487                };
1488                this.focus_and_scroll_to_nav_entry(next_root_index, window);
1489            }))
1490            .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, _| {
1491                if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1492                    this.focus_and_scroll_to_nav_entry(first_entry_index, window);
1493                }
1494            }))
1495            .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, _| {
1496                if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1497                    this.focus_and_scroll_to_nav_entry(last_entry_index, window);
1498                }
1499            }))
1500            .border_color(cx.theme().colors().border)
1501            .bg(cx.theme().colors().panel_background)
1502            .child(self.render_search(window, cx))
1503            .child(
1504                v_flex()
1505                    .flex_grow()
1506                    .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1507                    .tab_group()
1508                    .tab_index(NAVBAR_GROUP_TAB_INDEX)
1509                    .child(
1510                        uniform_list(
1511                            "settings-ui-nav-bar",
1512                            visible_count + 1,
1513                            cx.processor(move |this, range: Range<usize>, _, cx| {
1514                                this.visible_navbar_entries()
1515                                    .skip(range.start.saturating_sub(1))
1516                                    .take(range.len())
1517                                    .map(|(ix, entry)| {
1518                                        TreeViewItem::new(
1519                                            ("settings-ui-navbar-entry", ix),
1520                                            entry.title,
1521                                        )
1522                                        .track_focus(&entry.focus_handle)
1523                                        .root_item(entry.is_root)
1524                                        .toggle_state(this.is_navbar_entry_selected(ix))
1525                                        .when(entry.is_root, |item| {
1526                                            item.expanded(entry.expanded).on_toggle(cx.listener(
1527                                                move |this, _, window, cx| {
1528                                                    this.toggle_navbar_entry(ix);
1529                                                    window.focus(
1530                                                        &this.navbar_entries[ix].focus_handle,
1531                                                    );
1532                                                    cx.notify();
1533                                                },
1534                                            ))
1535                                        })
1536                                        .on_click(
1537                                            cx.listener(move |this, _, window, cx| {
1538                                                this.open_and_scroll_to_navbar_entry(
1539                                                    ix, window, cx,
1540                                                );
1541                                            }),
1542                                        )
1543                                    })
1544                                    .collect()
1545                            }),
1546                        )
1547                        .size_full()
1548                        .track_scroll(self.list_handle.clone()),
1549                    )
1550                    .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1551            )
1552        // TODO: Restore this once we've fixed the ToggleFocusNav action
1553        // .child(
1554        //     h_flex()
1555        //         .w_full()
1556        //         .p_2()
1557        //         .pb_0p5()
1558        //         .flex_none()
1559        //         .border_t_1()
1560        //         .border_color(cx.theme().colors().border_variant)
1561        //         .children(
1562        //             KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1563        //                 KeybindingHint::new(
1564        //                     this,
1565        //                     cx.theme().colors().surface_background.opacity(0.5),
1566        //                 )
1567        //                 .suffix(focus_keybind_label)
1568        //             }),
1569        //         ),
1570        // )
1571    }
1572
1573    fn open_and_scroll_to_navbar_entry(
1574        &mut self,
1575        navbar_entry_index: usize,
1576        window: &mut Window,
1577        cx: &mut Context<Self>,
1578    ) {
1579        self.open_navbar_entry_page(navbar_entry_index);
1580        cx.notify();
1581
1582        if self.navbar_entries[navbar_entry_index].is_root
1583            || !self.is_nav_entry_visible(navbar_entry_index)
1584        {
1585            let Some(first_item_index) = self.visible_page_items().next().map(|(index, _)| index)
1586            else {
1587                return;
1588            };
1589            self.focus_content_element(first_item_index, window, cx);
1590            self.scroll_handle.set_offset(point(px(0.), px(0.)));
1591        } else {
1592            let entry_item_index = self.navbar_entries[navbar_entry_index]
1593                .item_index
1594                .expect("Non-root items should have an item index");
1595            let Some(selected_item_index) = self
1596                .visible_page_items()
1597                .position(|(index, _)| index == entry_item_index)
1598            else {
1599                return;
1600            };
1601            self.scroll_handle
1602                .scroll_to_top_of_item(selected_item_index);
1603            self.focus_content_element(entry_item_index, window, cx);
1604        }
1605    }
1606
1607    fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
1608        self.visible_navbar_entries()
1609            .any(|(index, _)| index == nav_entry_index)
1610    }
1611
1612    fn focus_and_scroll_to_nav_entry(&self, nav_entry_index: usize, window: &mut Window) {
1613        let Some(position) = self
1614            .visible_navbar_entries()
1615            .position(|(index, _)| index == nav_entry_index)
1616        else {
1617            return;
1618        };
1619        self.list_handle
1620            .scroll_to_item(position, gpui::ScrollStrategy::Top);
1621        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
1622    }
1623
1624    fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1625        let page_idx = self.current_page_index();
1626
1627        self.current_page()
1628            .items
1629            .iter()
1630            .enumerate()
1631            .filter_map(move |(item_index, item)| {
1632                self.search_matches[page_idx][item_index].then_some((item_index, item))
1633            })
1634    }
1635
1636    fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1637        let mut items = vec![];
1638        items.push(self.current_page().title);
1639        items.extend(
1640            sub_page_stack()
1641                .iter()
1642                .flat_map(|page| [page.section_header, page.link.title]),
1643        );
1644
1645        let last = items.pop().unwrap();
1646        h_flex()
1647            .gap_1()
1648            .children(
1649                items
1650                    .into_iter()
1651                    .flat_map(|item| [item, "/"])
1652                    .map(|item| Label::new(item).color(Color::Muted)),
1653            )
1654            .child(Label::new(last))
1655    }
1656
1657    fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
1658        &self,
1659        items: Items,
1660        page_index: Option<usize>,
1661        window: &mut Window,
1662        cx: &mut Context<SettingsWindow>,
1663    ) -> impl IntoElement {
1664        let mut page_content = v_flex()
1665            .id("settings-ui-page")
1666            .size_full()
1667            .overflow_y_scroll()
1668            .track_scroll(&self.scroll_handle);
1669
1670        let items: Vec<_> = items.collect();
1671        let items_len = items.len();
1672        let mut section_header = None;
1673
1674        let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1675        let has_no_results = items_len == 0 && has_active_search;
1676
1677        if has_no_results {
1678            let search_query = self.search_bar.read(cx).text(cx);
1679            page_content = page_content.child(
1680                v_flex()
1681                    .size_full()
1682                    .items_center()
1683                    .justify_center()
1684                    .gap_1()
1685                    .child(div().child("No Results"))
1686                    .child(
1687                        div()
1688                            .text_sm()
1689                            .text_color(cx.theme().colors().text_muted)
1690                            .child(format!("No settings match \"{}\"", search_query)),
1691                    ),
1692            )
1693        } else {
1694            let last_non_header_index = items
1695                .iter()
1696                .enumerate()
1697                .rev()
1698                .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
1699                .map(|(index, _)| index);
1700
1701            page_content = page_content.children(items.clone().into_iter().enumerate().map(
1702                |(index, (actual_item_index, item))| {
1703                    let no_bottom_border = items
1704                        .get(index + 1)
1705                        .map(|(_, next_item)| {
1706                            matches!(next_item, SettingsPageItem::SectionHeader(_))
1707                        })
1708                        .unwrap_or(false);
1709                    let is_last = Some(index) == last_non_header_index;
1710
1711                    if let SettingsPageItem::SectionHeader(header) = item {
1712                        section_header = Some(*header);
1713                    }
1714                    v_flex()
1715                        .w_full()
1716                        .min_w_0()
1717                        .id(("settings-page-item", actual_item_index))
1718                        .when_some(page_index, |element, page_index| {
1719                            element.track_focus(
1720                                &self.content_handles[page_index][actual_item_index]
1721                                    .focus_handle(cx),
1722                            )
1723                        })
1724                        .child(item.render(
1725                            self,
1726                            section_header.expect("All items rendered after a section header"),
1727                            no_bottom_border || is_last,
1728                            window,
1729                            cx,
1730                        ))
1731                },
1732            ))
1733        }
1734        page_content
1735    }
1736
1737    fn render_page(
1738        &mut self,
1739        window: &mut Window,
1740        cx: &mut Context<SettingsWindow>,
1741    ) -> impl IntoElement {
1742        let page_header;
1743        let page_content;
1744
1745        if sub_page_stack().is_empty() {
1746            page_header = self.render_files_header(window, cx).into_any_element();
1747
1748            page_content = self
1749                .render_page_items(
1750                    self.visible_page_items(),
1751                    Some(self.current_page_index()),
1752                    window,
1753                    cx,
1754                )
1755                .into_any_element();
1756        } else {
1757            page_header = h_flex()
1758                .ml_neg_1p5()
1759                .pb_4()
1760                .gap_1()
1761                .child(
1762                    IconButton::new("back-btn", IconName::ArrowLeft)
1763                        .icon_size(IconSize::Small)
1764                        .shape(IconButtonShape::Square)
1765                        .on_click(cx.listener(|this, _, _, cx| {
1766                            this.pop_sub_page(cx);
1767                        })),
1768                )
1769                .child(self.render_sub_page_breadcrumbs())
1770                .into_any_element();
1771
1772            let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1773            page_content = (active_page_render_fn)(self, window, cx);
1774        }
1775
1776        return v_flex()
1777            .size_full()
1778            .pt_6()
1779            .pb_8()
1780            .px_8()
1781            .bg(cx.theme().colors().editor_background)
1782            .child(page_header)
1783            .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1784            .track_focus(&self.content_focus_handle.focus_handle(cx))
1785            .child(
1786                div()
1787                    .size_full()
1788                    .tab_group()
1789                    .tab_index(CONTENT_GROUP_TAB_INDEX)
1790                    .child(page_content),
1791            );
1792    }
1793
1794    fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
1795        match &self.current_file {
1796            SettingsUiFile::User => {
1797                let Some(original_window) = self.original_window else {
1798                    return;
1799                };
1800                original_window
1801                    .update(cx, |workspace, window, cx| {
1802                        workspace
1803                            .with_local_workspace(window, cx, |workspace, window, cx| {
1804                                let create_task = workspace.project().update(cx, |project, cx| {
1805                                    project.find_or_create_worktree(
1806                                        paths::config_dir().as_path(),
1807                                        false,
1808                                        cx,
1809                                    )
1810                                });
1811                                let open_task = workspace.open_paths(
1812                                    vec![paths::settings_file().to_path_buf()],
1813                                    OpenOptions {
1814                                        visible: Some(OpenVisible::None),
1815                                        ..Default::default()
1816                                    },
1817                                    None,
1818                                    window,
1819                                    cx,
1820                                );
1821
1822                                cx.spawn_in(window, async move |workspace, cx| {
1823                                    create_task.await.ok();
1824                                    open_task.await;
1825
1826                                    workspace.update_in(cx, |_, window, cx| {
1827                                        window.activate_window();
1828                                        cx.notify();
1829                                    })
1830                                })
1831                                .detach();
1832                            })
1833                            .detach();
1834                    })
1835                    .ok();
1836            }
1837            SettingsUiFile::Project((worktree_id, path)) => {
1838                let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
1839                let settings_path = path.join(paths::local_settings_file_relative_path());
1840                let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
1841                    return;
1842                };
1843                for workspace in app_state.workspace_store.read(cx).workspaces() {
1844                    let contains_settings_file = workspace
1845                        .read_with(cx, |workspace, cx| {
1846                            workspace.project().read(cx).contains_local_settings_file(
1847                                *worktree_id,
1848                                settings_path.as_ref(),
1849                                cx,
1850                            )
1851                        })
1852                        .ok();
1853                    if Some(true) == contains_settings_file {
1854                        corresponding_workspace = Some(*workspace);
1855
1856                        break;
1857                    }
1858                }
1859
1860                let Some(corresponding_workspace) = corresponding_workspace else {
1861                    log::error!(
1862                        "No corresponding workspace found for settings file {}",
1863                        settings_path.as_std_path().display()
1864                    );
1865
1866                    return;
1867                };
1868
1869                // TODO: move zed::open_local_file() APIs to this crate, and
1870                // re-implement the "initial_contents" behavior
1871                corresponding_workspace
1872                    .update(cx, |workspace, window, cx| {
1873                        let open_task = workspace.open_path(
1874                            (*worktree_id, settings_path.clone()),
1875                            None,
1876                            true,
1877                            window,
1878                            cx,
1879                        );
1880
1881                        cx.spawn_in(window, async move |workspace, cx| {
1882                            if open_task.await.log_err().is_some() {
1883                                workspace
1884                                    .update_in(cx, |_, window, cx| {
1885                                        window.activate_window();
1886                                        cx.notify();
1887                                    })
1888                                    .ok();
1889                            }
1890                        })
1891                        .detach();
1892                    })
1893                    .ok();
1894            }
1895            SettingsUiFile::Server(_) => {
1896                return;
1897            }
1898        };
1899    }
1900
1901    fn current_page_index(&self) -> usize {
1902        self.page_index_from_navbar_index(self.navbar_entry)
1903    }
1904
1905    fn current_page(&self) -> &SettingsPage {
1906        &self.pages[self.current_page_index()]
1907    }
1908
1909    fn page_index_from_navbar_index(&self, index: usize) -> usize {
1910        if self.navbar_entries.is_empty() {
1911            return 0;
1912        }
1913
1914        self.navbar_entries[index].page_index
1915    }
1916
1917    fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1918        ix == self.navbar_entry
1919    }
1920
1921    fn push_sub_page(
1922        &mut self,
1923        sub_page_link: SubPageLink,
1924        section_header: &'static str,
1925        cx: &mut Context<SettingsWindow>,
1926    ) {
1927        sub_page_stack_mut().push(SubPage {
1928            link: sub_page_link,
1929            section_header,
1930        });
1931        cx.notify();
1932    }
1933
1934    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1935        sub_page_stack_mut().pop();
1936        cx.notify();
1937    }
1938
1939    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1940        if let Some((_, handle)) = self.files.get(index) {
1941            handle.focus(window);
1942        }
1943    }
1944
1945    fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1946        if self.files_focus_handle.contains_focused(window, cx)
1947            && let Some(index) = self
1948                .files
1949                .iter()
1950                .position(|(_, handle)| handle.is_focused(window))
1951        {
1952            return index;
1953        }
1954        if let Some(current_file_index) = self
1955            .files
1956            .iter()
1957            .position(|(file, _)| file == &self.current_file)
1958        {
1959            return current_file_index;
1960        }
1961        0
1962    }
1963
1964    fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
1965        if !sub_page_stack().is_empty() {
1966            return;
1967        }
1968        let page_index = self.current_page_index();
1969        window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
1970    }
1971
1972    fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
1973        if !self
1974            .navbar_focus_handle
1975            .focus_handle(cx)
1976            .contains_focused(window, cx)
1977        {
1978            return None;
1979        }
1980        for (index, entry) in self.navbar_entries.iter().enumerate() {
1981            if entry.focus_handle.is_focused(window) {
1982                return Some(index);
1983            }
1984        }
1985        None
1986    }
1987
1988    fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
1989        let mut index = Some(nav_entry_index);
1990        while let Some(prev_index) = index
1991            && !self.navbar_entries[prev_index].is_root
1992        {
1993            index = prev_index.checked_sub(1);
1994        }
1995        return index.expect("No root entry found");
1996    }
1997}
1998
1999impl Render for SettingsWindow {
2000    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2001        let ui_font = theme::setup_ui_font(window, cx);
2002
2003        div()
2004            .id("settings-window")
2005            .key_context("SettingsWindow")
2006            .track_focus(&self.focus_handle)
2007            .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2008                this.open_current_settings_file(cx);
2009            }))
2010            .on_action(|_: &Minimize, window, _cx| {
2011                window.minimize_window();
2012            })
2013            .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2014                this.search_bar.focus_handle(cx).focus(window);
2015            }))
2016            .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2017                if this
2018                    .navbar_focus_handle
2019                    .focus_handle(cx)
2020                    .contains_focused(window, cx)
2021                {
2022                    this.open_and_scroll_to_navbar_entry(this.navbar_entry, window, cx);
2023                } else {
2024                    this.focus_and_scroll_to_nav_entry(this.navbar_entry, window);
2025                }
2026            }))
2027            .on_action(
2028                cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
2029                    this.focus_file_at_index(*file_index as usize, window);
2030                }),
2031            )
2032            .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2033                let next_index = usize::min(
2034                    this.focused_file_index(window, cx) + 1,
2035                    this.files.len().saturating_sub(1),
2036                );
2037                this.focus_file_at_index(next_index, window);
2038            }))
2039            .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2040                let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2041                this.focus_file_at_index(prev_index, window);
2042            }))
2043            .on_action(|_: &menu::SelectNext, window, _| {
2044                window.focus_next();
2045            })
2046            .on_action(|_: &menu::SelectPrevious, window, _| {
2047                window.focus_prev();
2048            })
2049            .flex()
2050            .flex_row()
2051            .size_full()
2052            .font(ui_font)
2053            .bg(cx.theme().colors().background)
2054            .text_color(cx.theme().colors().text)
2055            .child(self.render_nav(window, cx))
2056            .child(self.render_page(window, cx))
2057    }
2058}
2059
2060fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2061    workspace::AppState::global(cx)
2062        .upgrade()
2063        .map(|app_state| {
2064            app_state
2065                .workspace_store
2066                .read(cx)
2067                .workspaces()
2068                .iter()
2069                .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2070        })
2071        .into_iter()
2072        .flatten()
2073}
2074
2075fn update_settings_file(
2076    file: SettingsUiFile,
2077    cx: &mut App,
2078    update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2079) -> Result<()> {
2080    match file {
2081        SettingsUiFile::Project((worktree_id, rel_path)) => {
2082            let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2083            let project = all_projects(cx).find(|project| {
2084                project.read_with(cx, |project, cx| {
2085                    project.contains_local_settings_file(worktree_id, &rel_path, cx)
2086                })
2087            });
2088            let Some(project) = project else {
2089                anyhow::bail!(
2090                    "Could not find worktree containing settings file: {}",
2091                    &rel_path.display(PathStyle::local())
2092                );
2093            };
2094            project.update(cx, |project, cx| {
2095                project.update_local_settings_file(worktree_id, rel_path, cx, update);
2096            });
2097            return Ok(());
2098        }
2099        SettingsUiFile::User => {
2100            // todo(settings_ui) error?
2101            SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2102            Ok(())
2103        }
2104        SettingsUiFile::Server(_) => unimplemented!(),
2105    }
2106}
2107
2108fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2109    field: SettingField<T>,
2110    file: SettingsUiFile,
2111    metadata: Option<&SettingsFieldMetadata>,
2112    cx: &mut App,
2113) -> AnyElement {
2114    let (_, initial_text) =
2115        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2116    let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2117
2118    SettingsEditor::new()
2119        .tab_index(0)
2120        .when_some(initial_text, |editor, text| {
2121            editor.with_initial_text(text.as_ref().to_string())
2122        })
2123        .when_some(
2124            metadata.and_then(|metadata| metadata.placeholder),
2125            |editor, placeholder| editor.with_placeholder(placeholder),
2126        )
2127        .on_confirm({
2128            move |new_text, cx| {
2129                update_settings_file(file.clone(), cx, move |settings, _cx| {
2130                    *(field.pick_mut)(settings) = new_text.map(Into::into);
2131                })
2132                .log_err(); // todo(settings_ui) don't log err
2133            }
2134        })
2135        .into_any_element()
2136}
2137
2138fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2139    field: SettingField<B>,
2140    file: SettingsUiFile,
2141    cx: &mut App,
2142) -> AnyElement {
2143    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2144
2145    let toggle_state = if value.copied().map_or(false, Into::into) {
2146        ToggleState::Selected
2147    } else {
2148        ToggleState::Unselected
2149    };
2150
2151    Switch::new("toggle_button", toggle_state)
2152        .color(ui::SwitchColor::Accent)
2153        .on_click({
2154            move |state, _window, cx| {
2155                let state = *state == ui::ToggleState::Selected;
2156                update_settings_file(file.clone(), cx, move |settings, _cx| {
2157                    *(field.pick_mut)(settings) = Some(state.into());
2158                })
2159                .log_err(); // todo(settings_ui) don't log err
2160            }
2161        })
2162        .tab_index(0_isize)
2163        .color(SwitchColor::Accent)
2164        .into_any_element()
2165}
2166
2167fn render_font_picker(
2168    field: SettingField<settings::FontFamilyName>,
2169    file: SettingsUiFile,
2170    window: &mut Window,
2171    cx: &mut App,
2172) -> AnyElement {
2173    let current_value = SettingsStore::global(cx)
2174        .get_value_from_file(file.to_settings(), field.pick)
2175        .1
2176        .cloned()
2177        .unwrap_or_else(|| SharedString::default().into());
2178
2179    let font_picker = cx.new(|cx| {
2180        ui_input::font_picker(
2181            current_value.clone().into(),
2182            move |font_name, cx| {
2183                update_settings_file(file.clone(), cx, move |settings, _cx| {
2184                    *(field.pick_mut)(settings) = Some(font_name.into());
2185                })
2186                .log_err(); // todo(settings_ui) don't log err
2187            },
2188            window,
2189            cx,
2190        )
2191    });
2192
2193    PopoverMenu::new("font-picker")
2194        .menu(move |_window, _cx| Some(font_picker.clone()))
2195        .trigger(
2196            Button::new("font-family-button", current_value)
2197                .tab_index(0_isize)
2198                .style(ButtonStyle::Outlined)
2199                .size(ButtonSize::Medium)
2200                .icon(IconName::ChevronUpDown)
2201                .icon_color(Color::Muted)
2202                .icon_size(IconSize::Small)
2203                .icon_position(IconPosition::End),
2204        )
2205        .anchor(gpui::Corner::TopLeft)
2206        .offset(gpui::Point {
2207            x: px(0.0),
2208            y: px(2.0),
2209        })
2210        .with_handle(ui::PopoverMenuHandle::default())
2211        .into_any_element()
2212}
2213
2214fn render_number_field<T: NumberFieldType + Send + Sync>(
2215    field: SettingField<T>,
2216    file: SettingsUiFile,
2217    window: &mut Window,
2218    cx: &mut App,
2219) -> AnyElement {
2220    let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2221    let value = value.copied().unwrap_or_else(T::min_value);
2222    NumberField::new("numeric_stepper", value, window, cx)
2223        .on_change({
2224            move |value, _window, cx| {
2225                let value = *value;
2226                update_settings_file(file.clone(), cx, move |settings, _cx| {
2227                    *(field.pick_mut)(settings) = Some(value);
2228                })
2229                .log_err(); // todo(settings_ui) don't log err
2230            }
2231        })
2232        .into_any_element()
2233}
2234
2235fn render_dropdown<T>(
2236    field: SettingField<T>,
2237    file: SettingsUiFile,
2238    window: &mut Window,
2239    cx: &mut App,
2240) -> AnyElement
2241where
2242    T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2243{
2244    let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2245    let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2246
2247    let (_, current_value) =
2248        SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2249    let current_value = current_value.copied().unwrap_or(variants()[0]);
2250
2251    let current_value_label =
2252        labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2253
2254    DropdownMenu::new(
2255        "dropdown",
2256        current_value_label.to_title_case(),
2257        ContextMenu::build(window, cx, move |mut menu, _, _| {
2258            for (&value, &label) in std::iter::zip(variants(), labels()) {
2259                let file = file.clone();
2260                menu = menu.toggleable_entry(
2261                    label.to_title_case(),
2262                    value == current_value,
2263                    IconPosition::End,
2264                    None,
2265                    move |_, cx| {
2266                        if value == current_value {
2267                            return;
2268                        }
2269                        update_settings_file(file.clone(), cx, move |settings, _cx| {
2270                            *(field.pick_mut)(settings) = Some(value);
2271                        })
2272                        .log_err(); // todo(settings_ui) don't log err
2273                    },
2274                );
2275            }
2276            menu
2277        }),
2278    )
2279    .trigger_size(ButtonSize::Medium)
2280    .style(DropdownStyle::Outlined)
2281    .offset(gpui::Point {
2282        x: px(0.0),
2283        y: px(2.0),
2284    })
2285    .tab_index(0)
2286    .into_any_element()
2287}
2288
2289#[cfg(test)]
2290mod test {
2291
2292    use super::*;
2293
2294    impl SettingsWindow {
2295        fn navbar_entry(&self) -> usize {
2296            self.navbar_entry
2297        }
2298
2299        fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
2300            let mut this = Self::new(None, window, cx);
2301            this.navbar_entries.clear();
2302            this.pages.clear();
2303            this
2304        }
2305
2306        fn build(mut self, cx: &App) -> Self {
2307            self.build_search_matches();
2308            self.build_navbar(cx);
2309            self
2310        }
2311
2312        fn add_page(
2313            mut self,
2314            title: &'static str,
2315            build_page: impl Fn(SettingsPage) -> SettingsPage,
2316        ) -> Self {
2317            let page = SettingsPage {
2318                title,
2319                items: Vec::default(),
2320            };
2321
2322            self.pages.push(build_page(page));
2323            self
2324        }
2325
2326        fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
2327            self.search_task.take();
2328            self.search_bar.update(cx, |editor, cx| {
2329                editor.set_text(search_query, window, cx);
2330            });
2331            self.update_matches(cx);
2332        }
2333
2334        fn assert_search_results(&self, other: &Self) {
2335            // page index could be different because of filtered out pages
2336            #[derive(Debug, PartialEq)]
2337            struct EntryMinimal {
2338                is_root: bool,
2339                title: &'static str,
2340            }
2341            pretty_assertions::assert_eq!(
2342                other
2343                    .visible_navbar_entries()
2344                    .map(|(_, entry)| EntryMinimal {
2345                        is_root: entry.is_root,
2346                        title: entry.title,
2347                    })
2348                    .collect::<Vec<_>>(),
2349                self.visible_navbar_entries()
2350                    .map(|(_, entry)| EntryMinimal {
2351                        is_root: entry.is_root,
2352                        title: entry.title,
2353                    })
2354                    .collect::<Vec<_>>(),
2355            );
2356            assert_eq!(
2357                self.current_page().items.iter().collect::<Vec<_>>(),
2358                other
2359                    .visible_page_items()
2360                    .map(|(_, item)| item)
2361                    .collect::<Vec<_>>()
2362            );
2363        }
2364    }
2365
2366    impl SettingsPage {
2367        fn item(mut self, item: SettingsPageItem) -> Self {
2368            self.items.push(item);
2369            self
2370        }
2371    }
2372
2373    impl PartialEq for NavBarEntry {
2374        fn eq(&self, other: &Self) -> bool {
2375            self.title == other.title
2376                && self.is_root == other.is_root
2377                && self.expanded == other.expanded
2378                && self.page_index == other.page_index
2379                && self.item_index == other.item_index
2380            // ignoring focus_handle
2381        }
2382    }
2383
2384    impl SettingsPageItem {
2385        fn basic_item(title: &'static str, description: &'static str) -> Self {
2386            SettingsPageItem::SettingItem(SettingItem {
2387                files: USER,
2388                title,
2389                description,
2390                field: Box::new(SettingField {
2391                    pick: |settings_content| &settings_content.auto_update,
2392                    pick_mut: |settings_content| &mut settings_content.auto_update,
2393                }),
2394                metadata: None,
2395            })
2396        }
2397    }
2398
2399    fn register_settings(cx: &mut App) {
2400        settings::init(cx);
2401        theme::init(theme::LoadThemes::JustBase, cx);
2402        workspace::init_settings(cx);
2403        project::Project::init_settings(cx);
2404        language::init(cx);
2405        editor::init(cx);
2406        menu::init();
2407    }
2408
2409    fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2410        let mut pages: Vec<SettingsPage> = Vec::new();
2411        let mut expanded_pages = Vec::new();
2412        let mut selected_idx = None;
2413        let mut index = 0;
2414        let mut in_expanded_section = false;
2415
2416        for mut line in input
2417            .lines()
2418            .map(|line| line.trim())
2419            .filter(|line| !line.is_empty())
2420        {
2421            if let Some(pre) = line.strip_suffix('*') {
2422                assert!(selected_idx.is_none(), "Only one selected entry allowed");
2423                selected_idx = Some(index);
2424                line = pre;
2425            }
2426            let (kind, title) = line.split_once(" ").unwrap();
2427            assert_eq!(kind.len(), 1);
2428            let kind = kind.chars().next().unwrap();
2429            if kind == 'v' {
2430                let page_idx = pages.len();
2431                expanded_pages.push(page_idx);
2432                pages.push(SettingsPage {
2433                    title,
2434                    items: vec![],
2435                });
2436                index += 1;
2437                in_expanded_section = true;
2438            } else if kind == '>' {
2439                pages.push(SettingsPage {
2440                    title,
2441                    items: vec![],
2442                });
2443                index += 1;
2444                in_expanded_section = false;
2445            } else if kind == '-' {
2446                pages
2447                    .last_mut()
2448                    .unwrap()
2449                    .items
2450                    .push(SettingsPageItem::SectionHeader(title));
2451                if selected_idx == Some(index) && !in_expanded_section {
2452                    panic!("Items in unexpanded sections cannot be selected");
2453                }
2454                index += 1;
2455            } else {
2456                panic!(
2457                    "Entries must start with one of 'v', '>', or '-'\n line: {}",
2458                    line
2459                );
2460            }
2461        }
2462
2463        let mut settings_window = SettingsWindow {
2464            original_window: None,
2465            worktree_root_dirs: HashMap::default(),
2466            files: Vec::default(),
2467            current_file: crate::SettingsUiFile::User,
2468            pages,
2469            search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2470            navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2471            navbar_entries: Vec::default(),
2472            list_handle: UniformListScrollHandle::default(),
2473            search_matches: vec![],
2474            content_handles: vec![],
2475            search_task: None,
2476            scroll_handle: ScrollHandle::new(),
2477            focus_handle: cx.focus_handle(),
2478            navbar_focus_handle: NonFocusableHandle::new(
2479                NAVBAR_CONTAINER_TAB_INDEX,
2480                false,
2481                window,
2482                cx,
2483            ),
2484            content_focus_handle: NonFocusableHandle::new(
2485                CONTENT_CONTAINER_TAB_INDEX,
2486                false,
2487                window,
2488                cx,
2489            ),
2490            files_focus_handle: cx.focus_handle(),
2491        };
2492
2493        settings_window.build_search_matches();
2494        settings_window.build_navbar(cx);
2495        for expanded_page_index in expanded_pages {
2496            for entry in &mut settings_window.navbar_entries {
2497                if entry.page_index == expanded_page_index && entry.is_root {
2498                    entry.expanded = true;
2499                }
2500            }
2501        }
2502        settings_window
2503    }
2504
2505    #[track_caller]
2506    fn check_navbar_toggle(
2507        before: &'static str,
2508        toggle_page: &'static str,
2509        after: &'static str,
2510        window: &mut Window,
2511        cx: &mut App,
2512    ) {
2513        let mut settings_window = parse(before, window, cx);
2514        let toggle_page_idx = settings_window
2515            .pages
2516            .iter()
2517            .position(|page| page.title == toggle_page)
2518            .expect("page not found");
2519        let toggle_idx = settings_window
2520            .navbar_entries
2521            .iter()
2522            .position(|entry| entry.page_index == toggle_page_idx)
2523            .expect("page not found");
2524        settings_window.toggle_navbar_entry(toggle_idx);
2525
2526        let expected_settings_window = parse(after, window, cx);
2527
2528        pretty_assertions::assert_eq!(
2529            settings_window
2530                .visible_navbar_entries()
2531                .map(|(_, entry)| entry)
2532                .collect::<Vec<_>>(),
2533            expected_settings_window
2534                .visible_navbar_entries()
2535                .map(|(_, entry)| entry)
2536                .collect::<Vec<_>>(),
2537        );
2538        pretty_assertions::assert_eq!(
2539            settings_window.navbar_entries[settings_window.navbar_entry()],
2540            expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2541        );
2542    }
2543
2544    macro_rules! check_navbar_toggle {
2545        ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2546            #[gpui::test]
2547            fn $name(cx: &mut gpui::TestAppContext) {
2548                let window = cx.add_empty_window();
2549                window.update(|window, cx| {
2550                    register_settings(cx);
2551                    check_navbar_toggle($before, $toggle_page, $after, window, cx);
2552                });
2553            }
2554        };
2555    }
2556
2557    check_navbar_toggle!(
2558        navbar_basic_open,
2559        before: r"
2560        v General
2561        - General
2562        - Privacy*
2563        v Project
2564        - Project Settings
2565        ",
2566        toggle_page: "General",
2567        after: r"
2568        > General*
2569        v Project
2570        - Project Settings
2571        "
2572    );
2573
2574    check_navbar_toggle!(
2575        navbar_basic_close,
2576        before: r"
2577        > General*
2578        - General
2579        - Privacy
2580        v Project
2581        - Project Settings
2582        ",
2583        toggle_page: "General",
2584        after: r"
2585        v General*
2586        - General
2587        - Privacy
2588        v Project
2589        - Project Settings
2590        "
2591    );
2592
2593    check_navbar_toggle!(
2594        navbar_basic_second_root_entry_close,
2595        before: r"
2596        > General
2597        - General
2598        - Privacy
2599        v Project
2600        - Project Settings*
2601        ",
2602        toggle_page: "Project",
2603        after: r"
2604        > General
2605        > Project*
2606        "
2607    );
2608
2609    check_navbar_toggle!(
2610        navbar_toggle_subroot,
2611        before: r"
2612        v General Page
2613        - General
2614        - Privacy
2615        v Project
2616        - Worktree Settings Content*
2617        v AI
2618        - General
2619        > Appearance & Behavior
2620        ",
2621        toggle_page: "Project",
2622        after: r"
2623        v General Page
2624        - General
2625        - Privacy
2626        > Project*
2627        v AI
2628        - General
2629        > Appearance & Behavior
2630        "
2631    );
2632
2633    check_navbar_toggle!(
2634        navbar_toggle_close_propagates_selected_index,
2635        before: r"
2636        v General Page
2637        - General
2638        - Privacy
2639        v Project
2640        - Worktree Settings Content
2641        v AI
2642        - General*
2643        > Appearance & Behavior
2644        ",
2645        toggle_page: "General Page",
2646        after: r"
2647        > General Page
2648        v Project
2649        - Worktree Settings Content
2650        v AI
2651        - General*
2652        > Appearance & Behavior
2653        "
2654    );
2655
2656    check_navbar_toggle!(
2657        navbar_toggle_expand_propagates_selected_index,
2658        before: r"
2659        > General Page
2660        - General
2661        - Privacy
2662        v Project
2663        - Worktree Settings Content
2664        v AI
2665        - General*
2666        > Appearance & Behavior
2667        ",
2668        toggle_page: "General Page",
2669        after: r"
2670        v General Page
2671        - General
2672        - Privacy
2673        v Project
2674        - Worktree Settings Content
2675        v AI
2676        - General*
2677        > Appearance & Behavior
2678        "
2679    );
2680
2681    #[gpui::test]
2682    fn test_basic_search(cx: &mut gpui::TestAppContext) {
2683        let cx = cx.add_empty_window();
2684        let (actual, expected) = cx.update(|window, cx| {
2685            register_settings(cx);
2686
2687            let expected = cx.new(|cx| {
2688                SettingsWindow::new_builder(window, cx)
2689                    .add_page("General", |page| {
2690                        page.item(SettingsPageItem::SectionHeader("General settings"))
2691                            .item(SettingsPageItem::basic_item("test title", "General test"))
2692                    })
2693                    .build(cx)
2694            });
2695
2696            let actual = cx.new(|cx| {
2697                SettingsWindow::new_builder(window, cx)
2698                    .add_page("General", |page| {
2699                        page.item(SettingsPageItem::SectionHeader("General settings"))
2700                            .item(SettingsPageItem::basic_item("test title", "General test"))
2701                    })
2702                    .add_page("Theme", |page| {
2703                        page.item(SettingsPageItem::SectionHeader("Theme settings"))
2704                    })
2705                    .build(cx)
2706            });
2707
2708            actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2709
2710            (actual, expected)
2711        });
2712
2713        cx.cx.run_until_parked();
2714
2715        cx.update(|_window, cx| {
2716            let expected = expected.read(cx);
2717            let actual = actual.read(cx);
2718            expected.assert_search_results(&actual);
2719        })
2720    }
2721
2722    #[gpui::test]
2723    fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2724        let cx = cx.add_empty_window();
2725        let (actual, expected) = cx.update(|window, cx| {
2726            register_settings(cx);
2727
2728            let actual = cx.new(|cx| {
2729                SettingsWindow::new_builder(window, cx)
2730                    .add_page("General", |page| {
2731                        page.item(SettingsPageItem::SectionHeader("General settings"))
2732                            .item(SettingsPageItem::basic_item(
2733                                "Confirm Quit",
2734                                "Whether to confirm before quitting Zed",
2735                            ))
2736                            .item(SettingsPageItem::basic_item(
2737                                "Auto Update",
2738                                "Automatically update Zed",
2739                            ))
2740                    })
2741                    .add_page("AI", |page| {
2742                        page.item(SettingsPageItem::basic_item(
2743                            "Disable AI",
2744                            "Whether to disable all AI features in Zed",
2745                        ))
2746                    })
2747                    .add_page("Appearance & Behavior", |page| {
2748                        page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2749                            SettingsPageItem::basic_item(
2750                                "Cursor Shape",
2751                                "Cursor shape for the editor",
2752                            ),
2753                        )
2754                    })
2755                    .build(cx)
2756            });
2757
2758            let expected = cx.new(|cx| {
2759                SettingsWindow::new_builder(window, cx)
2760                    .add_page("Appearance & Behavior", |page| {
2761                        page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2762                            SettingsPageItem::basic_item(
2763                                "Cursor Shape",
2764                                "Cursor shape for the editor",
2765                            ),
2766                        )
2767                    })
2768                    .build(cx)
2769            });
2770
2771            actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2772
2773            (actual, expected)
2774        });
2775
2776        cx.cx.run_until_parked();
2777
2778        cx.update(|_window, cx| {
2779            let expected = expected.read(cx);
2780            let actual = actual.read(cx);
2781            expected.assert_search_results(&actual);
2782        })
2783    }
2784}