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