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