Skip to content

Visual Studio Code, rebuilt in Rust

Rust
56.9 KB
Raw Blame
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use exthost::scan::scan_extension;
use gpui::{Bounds, Modifiers, MouseButton, Pixels, TestAppContext, point, px, size};

use super::{HoverLayout, HoverOptions, HoverPosition, layout_hover, pointer_shape};
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;
use crate::workbench::Workbench;
use storage::Storage;

/// The reference's window in port/results/raw/hover/ref.
const VIEWPORT: gpui::Size<f32> = gpui::Size { width: 1024., height: 768. };

fn layout(target: (f32, f32, f32, f32), hover: (f32, f32), options: HoverOptions) -> HoverLayout {
    let target = Bounds { origin: point(target.0, target.1), size: size(target.2, target.3) };
    layout_hover(VIEWPORT, target, size(hover.0, hover.1), &options, None)
}

fn assert_near(actual: gpui::Point<f32>, expected: (f32, f32), tolerance: f32) {
    assert!((actual.x - expected.0).abs() <= tolerance && (actual.y - expected.1).abs() <= tolerance, "{actual:?} is not near {expected:?}");
}

#[test]
fn hovers_sit_where_the_reference_puts_them() {
    let composite_bar = HoverOptions::composite_bar(HoverPosition::Right);
    // Activity bar "Search (⇧⌘F)" and "Manage": right of the item, the caret on the left.
    let search = layout((8., 83., 36., 36.), (99.5, 25.), composite_bar);
    assert_eq!((search.side, search.pointer), (HoverPosition::Right, Some(11.5)));
    assert_near(search.origin, (47., 87.5), 0.01);
    assert_near(layout((8., 696., 36., 36.), (62.9, 25.), composite_bar).origin, (47., 700.5), 0.01);
    // Title bar actions: no room above, so below with the caret on top, centered on the item.
    let back = layout((284.4375, 7.5, 22., 22.), (93.88, 25.), HoverOptions::instant());
    assert_eq!(back.side, HoverPosition::Below);
    assert_near(back.origin, (249.5, 32.5), 0.5);
    assert_near(layout((912., 7.5, 22., 22.), (129.73, 25.), HoverOptions::instant()).origin, (859., 32.5), 0.01);
    // The command center's hover target is inside its 1px border.
    assert_near(layout((343.4375, 7.5, 389.12, 22.), (266.58, 25.), HoverOptions::instant()).origin, (405.49, 32.5), 0.5);
    // Too wide to center on "Toggle Primary Side Bar": right-aligned 2px from the window edge, then 1px right.
    let toggle = layout((938., 7.5, 22., 22.), (184.9, 25.), HoverOptions::instant());
    assert_near(toggle.origin, (838., 32.5), 0.01);
    assert_near(layout((964., 7.5, 22., 22.), (120.34, 25.), HoverOptions::instant()).origin, (903., 32.5), 0.01);
    assert_near(layout((990., 7.5, 22., 22.), (213.68, 25.), HoverOptions::instant()).origin, (809., 32.5), 0.01);
    assert_eq!(toggle.pointer, Some(949. - toggle.origin.x));
    // Status bar "No Problems": above, the caret at the bottom.
    let problems = layout((40., 742., 73.25, 24.), (90.47, 25.), HoverOptions::status_bar());
    assert_eq!(problems.side, HoverPosition::Above);
    assert_near(problems.origin, (32.5, 714.), 0.5);
}

#[test]
fn mouse_hovers_open_below_the_target_10px_right_of_the_pointer() {
    let target = |x, y, w, h| Bounds { origin: point(x, y), size: size(w, h) };
    // Tab "notes.txt" and Explorer row "src".
    let tab = layout_hover(VIEWPORT, target(309., 36., 111.8, 31.), size(217.5, 25.), &HoverOptions::mouse(), Some(374.));
    assert_eq!((tab.origin, tab.pointer), (point(374., 67.), None));
    let row = layout_hover(VIEWPORT, target(53., 118., 246., 22.), size(185., 25.), &HoverOptions::mouse(), Some(126.));
    assert_eq!(row.origin, point(126., 140.));
}

/// hoverService.test.ts "should centre the hover pointer on its target for odd and even hover widths".
#[test]
fn the_pointer_is_centered_on_its_target_for_odd_and_even_widths() {
    let below = HoverOptions { position: HoverPosition::Below, ..HoverOptions::instant() };
    for width in [202., 203.] {
        let hover = layout((300., 100., 100., 20.), (width, 25.), below);
        assert_eq!(hover.origin.x + hover.pointer.unwrap(), 350.);
    }
}

/// hover.css `.workbench-hover-pointer.left` (left: -3px) and `:after` (6px border box, rotate(135deg)): the square's
/// center is on the hover's outer edge, and its borders' centerline runs half a pixel inside its outward sides.
#[test]
fn the_pointer_square_is_centered_on_the_edge_with_its_borders_inside() {
    let (square, arms) = pointer_shape(HoverPosition::Right, point(100., 50.), size(80., 30.), 15.);
    let half = 3. * std::f32::consts::SQRT_2;
    assert_eq!(square, [point(100., 65. - half), point(100. - half, 65.), point(100., 65. + half), point(100. + half, 65.)]);
    let tip = arms[1];
    assert!((tip.x - (100. - half + std::f32::consts::FRAC_1_SQRT_2)).abs() < 1e-4 && tip.y == 65., "{tip:?}");
    assert!((arms[0].x - 100.354).abs() < 1e-3 && (arms[0].y - (65. - half + 0.354)).abs() < 1e-3, "{:?}", arms[0]);
}

/// hoverService.test.ts "should re-evaluate the requested side on every layout as the content size changes", with
/// its RIGHT and LEFT variants.
#[test]
fn the_requested_side_is_re_evaluated_for_each_hover_width() {
    let width = VIEWPORT.width;
    let side = |target: (f32, f32, f32, f32), client_width: f32, position| {
        let options = HoverOptions { position, ..HoverOptions::instant() };
        let hover = layout(target, (client_width + 2., 25.), options);
        (hover.side, hover.origin.x)
    };
    let right = (width - 300., 100., 50., 20.);
    assert_eq!(side(right, 100., HoverPosition::Right), (HoverPosition::Right, width - 250. + 3.));
    assert_eq!(side(right, 300., HoverPosition::Right), (HoverPosition::Left, width - 300. - 3. - 302.));
    assert_eq!(side(right, width, HoverPosition::Right).0, HoverPosition::Below);
    let left = (250., 100., 50., 20.);
    assert_eq!(side(left, 100., HoverPosition::Left), (HoverPosition::Left, 250. - 3. - 102.));
    assert_eq!(side(left, 300., HoverPosition::Left), (HoverPosition::Right, 300. + 3.));
    assert_eq!(side(left, width, HoverPosition::Left).0, HoverPosition::Below);
}

/// hoverService.test.ts "should centre the hover pointer vertically for odd hover heights": the caret's centre is
/// half the client height down the side.
#[test]
fn the_pointer_is_centered_vertically_for_odd_heights() {
    let right = HoverOptions { position: HoverPosition::Right, ..HoverOptions::instant() };
    let pointer = |client_height: f32| layout((300., 100., 100., 200.), (102., client_height + 2.), right).pointer.unwrap();
    assert_eq!((pointer(40.), pointer(41.)), (20., 20.5));
}

/// hoverService.test.ts "should re-evaluate a requested ABOVE side on every layout as the content size changes".
#[test]
fn a_requested_above_side_is_re_evaluated_for_each_height() {
    let above = HoverOptions { position: HoverPosition::Above, ..HoverOptions::instant() };
    let side = |height: f32| layout((100., 20., 100., 22.), (102., height + 2.), above).side;
    assert_eq!([side(10.), side(VIEWPORT.height), side(10.)], [HoverPosition::Above, HoverPosition::Below, HoverPosition::Above]);
}

/// hoverService.test.ts "should not choose a side using the maximum height applied by a previous layout" and "should
/// use the maximum height of the hover when choosing a vertical fallback": the side is chosen with the content's
/// height capped to `maxHeightRatio` of the window.
#[test]
fn the_vertical_fallback_uses_the_capped_height() {
    let no_pointer = |position| HoverOptions { position, follows_mouse: true, max_height_ratio: 0.5, ..HoverOptions::instant() };
    let side = |viewport: gpui::Size<f32>, top: f32, height: f32, position| {
        let target = Bounds { origin: point(100., top), size: size(100., 22.) };
        layout_hover(viewport, target, size(102., height), &no_pointer(position), None).side
    };
    assert_eq!(side(size(1024., 600.), 200., 800., HoverPosition::Above), HoverPosition::Below);
    assert_eq!(side(size(1024., 1200.), 400., 800., HoverPosition::Above), HoverPosition::Below);
    assert_eq!(side(VIEWPORT, 44., VIEWPORT.height, HoverPosition::Below), HoverPosition::Below);
}

/// hoverService.test.ts "should keep a side hover taller than the room above its target within the window".
#[test]
fn a_tall_side_hover_stays_inside_the_window() {
    let right = HoverOptions { position: HoverPosition::Right, ..HoverOptions::instant() };
    let hover = layout((0., 20., 100., 20.), (102., 302.), right);
    assert_eq!((hover.origin.y, hover.pointer), (2., Some(26.)));
}

fn open_workbench<'a>(name: &str, cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut gpui::VisualTestContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
    let theme = load_theme(&[themes], "Dark Modern").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-{name}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let (workbench, cx) = cx.add_window_view(|_, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
        let storage = Arc::new(Mutex::new(Storage::in_memory()));
        workbench.restore_profile_state(storage.clone(), storage);
        workbench
    });
    cx.run_until_parked();
    (workbench, cx)
}

/// On Windows the title bar ends at the window controls, three 46px buttons.
fn title_bar_end(width: Pixels) -> Pixels {
    width - px(if cfg!(windows) { 138. } else { 0. })
}

const TOGGLE_PANEL: &str = if matches!(crate::keybindings::OS, crate::keybindings::Os::Macintosh) { "Toggle Panel (⌘J)" } else { "Toggle Panel (Ctrl+J)" };
const TOGGLE_SECONDARY_SIDE_BAR: &str = if matches!(crate::keybindings::OS, crate::keybindings::Os::Macintosh) { "Toggle Secondary Side Bar (⌥⌘B)" } else { "Toggle Secondary Side Bar (Ctrl+Alt+B)" };

/// toggleTabFocusMode.ts: Ctrl+Shift+M on macOS, Ctrl+M elsewhere.
const TOGGLE_TAB_FOCUS: &str = if matches!(crate::keybindings::OS, crate::keybindings::Os::Macintosh) { "ctrl-shift-m" } else { "ctrl-m" };

fn wait(cx: &mut gpui::VisualTestContext, ms: u64) {
    cx.executor().advance_clock(Duration::from_millis(ms));
    cx.run_until_parked();
}

fn shown(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext) -> Option<String> {
    workbench.read_with(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned))
}

/// hoverService.test.ts "should not show a pending hover after the target was clicked" and "should hide a hover when
/// the mouse left the target shortly before the delay ended", then hover locking: Alt keeps a hover the pointer
/// left (`_keyDown`), releasing Alt away from it hides it (`_keyUp`).
#[gpui::test]
fn clicks_cancel_pending_hovers_and_alt_locks_a_shown_one(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-lock", cx);
    let width = cx.update(|window, _| window.viewport_size().width);
    let panel = point(title_bar_end(width) - px(49.), px(18.5));
    let outside = point(width / 2., px(300.));

    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 1000);
    cx.simulate_mouse_down(panel, MouseButton::Left, Modifiers::none());
    cx.simulate_mouse_up(panel, MouseButton::Left, Modifiers::none());
    wait(cx, 1000);
    assert_eq!(shown(&workbench, cx), None, "the click cancelled the pending hover");

    cx.simulate_mouse_move(outside, None, Modifiers::none());
    wait(cx, 1000);
    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 1400);
    cx.simulate_mouse_move(outside, None, Modifiers::none());
    wait(cx, 300);
    assert_eq!(shown(&workbench, cx), None, "leaving before the delay ended");

    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 1500);
    assert!(shown(&workbench, cx).is_some());
    // Modifier changes reach the workbench through the focused element.
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.status_bar_focus, cx));
    cx.simulate_modifiers_change(Modifiers::alt());
    cx.simulate_mouse_move(outside, None, Modifiers::alt());
    wait(cx, 1000);
    assert!(shown(&workbench, cx).is_some(), "Alt locks the hover");
    cx.simulate_modifiers_change(Modifiers::none());
    cx.run_until_parked();
    assert_eq!(shown(&workbench, cx), None, "releasing Alt away from the hover hides it");
}

/// The remote indicator (remoteIndicator.ts, `status.host`) is not in the status bar: workbench/contrib/remote is
/// removed by decision (port/notes.md). Problems is the first visible item, its label at the 12px inset without margin.
#[gpui::test]
fn the_status_bar_has_no_remote_indicator(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-remote", cx);
    let height = cx.update(|window, _| window.viewport_size().height);
    cx.simulate_mouse_move(point(px(13.), height - px(11.)), None, Modifiers::none());
    wait(cx, 1500);
    assert_eq!(shown(&workbench, cx).as_deref(), Some("No Problems"));
}

/// statusbarpart.css `.statusbar-item a:hover`: in high contrast the hovered label gets a 1px dashed
/// `contrastActiveBorder` outline, and its codicons (`color: inherit`) take `statusBarItem.hoverForeground`.
#[gpui::test]
fn a_hovered_status_item_is_outlined_and_its_icons_take_the_hover_foreground(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-status-hc", cx);
    let (scale, border) = workbench.update_in(cx, |workbench, window, cx| {
        let themes = scan_extension(&workbench.app_root.join("extensions/theme-defaults"), true).unwrap();
        workbench.theme = load_theme(&[themes], "Default High Contrast").unwrap();
        workbench.theme.set_customizations(&serde_json::json!({ "statusBarItem.hoverForeground": "#FF0000" }), &serde_json::json!({}));
        cx.notify();
        (window.scale_factor(), workbench.theme.color("contrastActiveBorder").unwrap())
    });
    cx.run_until_parked();
    let problems = cx.debug_bounds("status-bar-entry-status.problems").expect("the problems entry is drawn");
    let inside = |bounds: Bounds<gpui::ScaledPixels>| problems.contains(&bounds.center().map(|v| px(v.0 / scale)));
    let painted = |cx: &mut gpui::VisualTestContext| {
        cx.read_rendered_frame(|scene, _| {
            let outlined = scene.quads.iter().any(|quad| inside(quad.bounds) && quad.border_style == gpui::BorderStyle::Dashed && quad.border_color == border.into() && quad.border_widths.top == gpui::ScaledPixels(scale));
            let icons: Vec<gpui::Hsla> = scene.monochrome_sprites.iter().filter(|sprite| inside(sprite.bounds) && sprite.bounds.size.width.0 >= 16. * scale).map(|sprite| sprite.color).collect();
            (outlined, icons)
        })
    };
    let (outlined, icons) = painted(cx);
    assert!(!outlined && !icons.is_empty() && !icons.contains(&gpui::rgb(0xFF0000).into()), "not hovered: {icons:?}");
    cx.simulate_mouse_move(problems.center(), None, Modifiers::none());
    cx.run_until_parked();
    let (outlined, icons) = painted(cx);
    assert!(outlined, "the hovered problems entry has the dashed outline");
    assert!(!icons.is_empty() && icons.iter().all(|color| *color == gpui::rgb(0xFF0000).into()), "{icons:?}");
    // CSS `:hover` follows only the pointer: typing with the pointer still keeps the whole hover.
    cx.simulate_keystrokes("a");
    cx.run_until_parked();
    let (outlined, icons) = painted(cx);
    assert!(outlined, "a key press keeps the outline");
    assert!(!icons.is_empty() && icons.iter().all(|color| *color == gpui::rgb(0xFF0000).into()), "a key press keeps the icons' hover color: {icons:?}");
}

#[gpui::test]
fn a_hovered_extension_entry_s_icons_follow_its_label_color(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-status-extension", cx);
    let scale = workbench.update_in(cx, |workbench, window, cx| {
        workbench.theme.set_customizations(&serde_json::json!({ "statusBarItem.hoverForeground": "#FF0000" }), &serde_json::json!({}));
        let entry = |id: &str, text: &str, color: Option<&str>| crate::main_thread_status_bar::StatusEntry {
            entry_id: id.into(),
            extension_id: None,
            id: id.into(),
            name: id.into(),
            text: text.into(),
            tooltip: None,
            command: Some(serde_json::json!("noop")),
            color: color.map(|color| serde_json::json!(color)),
            background_color: None,
            kind: None,
            align_left: true,
            priority: 0.,
            secondary: 0,
            show_progress: false,
        };
        workbench.status_entries.push(entry("plain", "$(check) Plain", None));
        workbench.status_entries.push(entry("own", "$(check) Own", Some("#00FF00")));
        cx.notify();
        window.scale_factor()
    });
    cx.run_until_parked();
    // The test platform paints no text glyphs: the icons are the label's sprites.
    let icon_colors_when_hovered = |selector: &'static str, cx: &mut gpui::VisualTestContext| {
        let bounds = cx.debug_bounds(selector).expect("the entry is drawn");
        cx.simulate_mouse_move(bounds.center(), None, Modifiers::none());
        cx.run_until_parked();
        cx.read_rendered_frame(|scene, _| {
            let inside = |sprite: &gpui::MonochromeSprite| bounds.contains(&sprite.bounds.center().map(|v| px(v.0 / scale)));
            scene.monochrome_sprites.iter().filter(|sprite| inside(sprite)).map(|sprite| sprite.color).collect::<Vec<gpui::Hsla>>()
        })
    };
    // statusbarpart.css `a:hover` color and `span.codicon { color: inherit }`.
    let icons = icon_colors_when_hovered("status-bar-entry-plain", cx);
    assert!(!icons.is_empty() && icons.iter().all(|color| *color == gpui::rgb(0xFF0000).into()), "plain: {icons:?}");
    // statusbarItem.ts `applyColor`: the label's inline color wins over the hover rule.
    let icons = icon_colors_when_hovered("status-bar-entry-own", cx);
    assert!(!icons.is_empty() && icons.iter().all(|color| *color == gpui::rgb(0x00FF00).into()), "own: {icons:?}");
}

#[gpui::test]
fn a_hover_shows_after_the_delay_and_hides_when_the_pointer_leaves(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover", cx);
    let width = cx.update(|window, _| window.viewport_size().width);
    // Title bar right: 12px inset, 22px items 4px apart; Toggle Secondary Side Bar is last, Toggle Panel before it.
    let secondary = point(title_bar_end(width) - px(23.), px(18.5));
    let panel = point(title_bar_end(width) - px(49.), px(18.5));
    let outside = point(width / 2., px(300.));
    let shown = |cx: &mut gpui::VisualTestContext| shown(&workbench, cx);

    cx.simulate_mouse_move(secondary, None, Modifiers::none());
    wait(cx, 1499);
    assert_eq!(shown(cx), None);
    wait(cx, 1);
    assert_eq!(shown(cx).as_deref(), Some(TOGGLE_SECONDARY_SIDE_BAR));

    // Instant hover: the neighbour within 200ms of the hide shows at once.
    cx.simulate_mouse_move(panel, None, Modifiers::none());
    cx.run_until_parked();
    assert_eq!(shown(cx).as_deref(), Some(TOGGLE_PANEL));

    // Leaving hides it once the mouse tracker's 200ms pass.
    cx.simulate_mouse_move(outside, None, Modifiers::none());
    wait(cx, 199);
    assert!(shown(cx).is_some());
    wait(cx, 1);
    assert_eq!(shown(cx), None);

    // Past the 200ms the delay applies again; a click hides the hover until the pointer leaves the target.
    wait(cx, 200);
    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 1500);
    assert!(shown(cx).is_some());
    cx.simulate_mouse_down(panel, MouseButton::Left, Modifiers::none());
    cx.simulate_mouse_up(panel, MouseButton::Left, Modifiers::none());
    assert_eq!(shown(cx), None);
    cx.simulate_mouse_move(panel + point(px(1.), px(0.)), None, Modifiers::none());
    wait(cx, 1500);
    assert_eq!(shown(cx), None);

    // A key no keybinding takes hides it too. The click toggled the panel, which moved the focus.
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.status_bar_focus, cx));
    cx.simulate_mouse_move(secondary, None, Modifiers::none());
    wait(cx, 1500);
    assert!(shown(cx).is_some());
    cx.simulate_keystrokes("x");
    assert_eq!(shown(cx), None);
}

/// hoverService.ts `_createHover` with `persistence.sticky` (updateTitleBarEntry.ts' tooltip): the hover is locked and
/// adds no key listeners, so neither a key nor Alt released away from it hides it, no other target's hover replaces
/// it, and only a press outside it does.
#[gpui::test]
fn a_sticky_hover_stays_until_a_press_outside_it(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-sticky", cx);
    let width = cx.update(|window, _| window.viewport_size().width);
    let panel = point(title_bar_end(width) - px(49.), px(18.5));
    let outside = point(width / 2., px(300.));
    workbench.update_in(cx, |workbench, window, cx| {
        window.focus(&workbench.status_bar_focus, cx);
        let bounds = Bounds { origin: point(px(100.), px(100.)), size: size(px(50.), px(20.)) };
        workbench.show_managed_hover("sticky", super::HoverContent::Text("Sticky".into()), HoverOptions::instant().sticky(), bounds, window, cx);
    });
    cx.simulate_mouse_move(outside, None, Modifiers::none());
    cx.simulate_keystrokes("x");
    assert_eq!(shown(&workbench, cx).as_deref(), Some("Sticky"), "a key leaves it");
    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 1500);
    assert_eq!(shown(&workbench, cx).as_deref(), Some("Sticky"), "another target's hover does not replace it");
    cx.simulate_mouse_move(outside, None, Modifiers::none());
    cx.simulate_modifiers_change(Modifiers::alt());
    cx.simulate_modifiers_change(Modifiers::none());
    wait(cx, 300);
    assert_eq!(shown(&workbench, cx).as_deref(), Some("Sticky"), "Alt released away from it leaves it");
    cx.simulate_mouse_down(outside, MouseButton::Left, Modifiers::none());
    cx.simulate_mouse_up(outside, MouseButton::Left, Modifiers::none());
    assert_eq!(shown(&workbench, cx), None, "a press outside hides it");
}

/// Chromium's fake mouse move: a target uncovered by a closing context menu gets its hover with the pointer still.
#[gpui::test]
fn a_target_under_a_closing_context_menu_gets_its_hover(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-menu", cx);
    let width = cx.update(|window, _| window.viewport_size().width);
    let panel = point(title_bar_end(width) - px(49.), px(18.5));
    workbench.update_in(cx, |workbench, window, cx| {
        let actions = vec![crate::menus::MenuAction::Command { id: "workbench.action.closeAllEditors".into(), title: "Close All".into(), enabled: true, checked: false, alt: None }];
        workbench.show_context_menu_actions(actions, &Default::default(), Bounds::new(point(px(400.), px(300.)), size(px(0.), px(0.))), Vec::new(), window, cx);
    });
    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 1500);
    assert_eq!(shown(&workbench, cx), None, "the open menu's backdrop takes the pointer");
    workbench.update_in(cx, |workbench, window, cx| workbench.hide_context_menu(window, cx));
    // Two frames as the platform loop delivers them: next-frame callbacks, then the draw.
    for _ in 0..2 {
        cx.update(|window, cx| {
            window.simulate_next_frame(cx);
            drop(window.draw(cx));
        });
    }
    wait(cx, 1500);
    assert_eq!(shown(&workbench, cx).as_deref(), Some(TOGGLE_PANEL));
}

/// The tab's Unpin Editor after its context menu closes by Escape: the right click hid the hover, the menu left
/// the target, and the still pointer gets the hover again.
#[gpui::test]
fn a_right_clicked_target_gets_its_hover_after_the_menu_closes(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-right-click", cx);
    let width = cx.update(|window, _| window.viewport_size().width);
    let panel = point(title_bar_end(width) - px(49.), px(18.5));
    cx.simulate_mouse_move(panel, None, Modifiers::none());
    wait(cx, 500);
    cx.simulate_mouse_down(panel, MouseButton::Right, Modifiers::none());
    workbench.update_in(cx, |workbench, window, cx| {
        let actions = vec![crate::menus::MenuAction::Command { id: "workbench.action.closeAllEditors".into(), title: "Close All".into(), enabled: true, checked: false, alt: None }];
        workbench.show_context_menu_actions(actions, &Default::default(), Bounds::new(panel, size(px(0.), px(0.))), Vec::new(), window, cx);
    });
    cx.simulate_mouse_up(panel, MouseButton::Right, Modifiers::none());
    wait(cx, 1500);
    workbench.update_in(cx, |workbench, window, cx| workbench.hide_context_menu(window, cx));
    for _ in 0..2 {
        cx.update(|window, cx| {
            window.simulate_next_frame(cx);
            drop(window.draw(cx));
        });
    }
    wait(cx, 1500);
    assert_eq!(shown(&workbench, cx).as_deref(), Some(TOGGLE_PANEL));
}

/// Shows `markdown` as a managed hover on `target` and draws the measuring frame and the one after it.
fn show_markdown_hover(workbench: &gpui::Entity<Workbench>, markdown: serde_json::Value, target: Bounds<gpui::Pixels>, cx: &mut gpui::VisualTestContext) -> Bounds<gpui::Pixels> {
    workbench.update_in(cx, |workbench, window, cx| workbench.show_managed_hover("target", super::HoverContent::Markdown(markdown), HoverOptions::element(), target, window, cx));
    for _ in 0..2 {
        cx.update(|window, cx| {
            window.simulate_next_frame(cx);
            drop(window.draw(cx));
        });
    }
    cx.debug_bounds("workbench-hover").expect("the hover draws")
}

/// breakpointsView.ts:444: the breakpoints hint (js-debug's `unverifiedBreakpoints`) renders through the markdown
/// renderer, wraps at the 500px max width, and the hover sits on that measured size, 3px above its target.
#[gpui::test]
fn a_markdown_hover_wraps_at_the_max_width_and_is_placed_by_its_measured_size(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-markdown-wrap", cx);
    let message = "Some of your breakpoints could not be set. If you're having an issue, you can [troubleshoot your launch configuration](command:extension.js-debug.createDiagnostics).";
    let target = Bounds { origin: point(px(300.), px(400.)), size: size(px(16.), px(22.)) };
    let hover = show_markdown_hover(&workbench, serde_json::json!({ "value": message, "isTrusted": true }), target, cx);
    assert_eq!(hover.size, size(px(500. + 2. * 8. + 2.), px(2. * 19. + 2. * 2. + 2.)), "two lines of 500px contents in the 8px by 2px padding and the border");
    let viewport = cx.update(|window, _| window.viewport_size().map(f32::from));
    let placed = layout_hover(viewport, target.map(f32::from), hover.size.map(f32::from), &HoverOptions::element(), None);
    assert_eq!(hover.origin.map(f32::from), placed.origin, "placed by the measured size");
    assert_eq!(placed.side, HoverPosition::Above);
    let links = workbench.read_with(cx, |workbench, _| super::hover_link_hrefs(workbench.hovers.shown.as_ref().unwrap()));
    assert_eq!(links, ["command:extension.js-debug.createDiagnostics"]);
}

/// hoverWidget.css `.monaco-hover`: a plain text hover is as wide as its text, which stays on one line (a resolving
/// tree item's "Loading..." drew its last dot on a second line below the box).
#[gpui::test]
fn a_plain_text_hover_that_fits_keeps_its_text_on_one_line(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-plain-text", cx);
    let target = Bounds { origin: point(px(300.), px(400.)), size: size(px(16.), px(22.)) };
    for extra_padding_x in [0., 0.37, 0.5, 1.11, 6.] {
        for text in ["Loading...", "Explorer", "Run and Debug (⇧⌘D)", "Extensions (⇧⌘X)"] {
            let options = HoverOptions { extra_padding_x, ..HoverOptions::element() };
            workbench.update_in(cx, |workbench, window, cx| workbench.show_managed_hover("target", super::HoverContent::Text(text.into()), options, target, window, cx));
            cx.update(|window, cx| {
                window.simulate_next_frame(cx);
                drop(window.draw(cx));
            });
            let height = cx.debug_bounds("workbench-hover-text").expect("the text draws").size.height;
            assert_eq!(height, px(super::LINE_HEIGHT), "{text:?} with {extra_padding_x}px more padding is one line");
        }
    }
}

/// Each `<a>` is its own tab stop, also two adjacent links to one href, and a styled link stays one.
#[test]
fn adjacent_links_to_one_href_are_two_links() {
    let markdown = serde_json::json!({ "value": "[a](command:x)[b](command:x) [**c**d](command:x)", "isTrusted": true });
    let mut blocks = super::parse(&super::MarkdownString::from_value(&markdown));
    let links: Vec<usize> = super::link_spans(&mut blocks).iter().map(Vec::len).collect();
    assert_eq!(links, [1, 1, 2]);
}

/// hoverWidget.css: a `---` rule is 1px, 8px below the paragraph before it (its 4px top margin collapses) and 4px
/// above the one after it (its -4px bottom margin), as the terminal decoration's hover draws it.
#[gpui::test]
fn a_markdown_rule_collapses_its_margins(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-markdown-rule", cx);
    let target = Bounds { origin: point(px(300.), px(400.)), size: size(px(16.), px(22.)) };
    let hover = show_markdown_hover(&workbench, serde_json::json!({ "value": "Show Command Actions\n\n---\n\nCommand executed now and took 1ms" }), target, cx);
    assert_eq!(hover.size.height, px(19. + 8. + 1. + 4. + 19. + 2. * 2. + 2.));
}

/// hoverWidget.ts `addFocusTrap`: in a trapFocus hover Tab moves from the container through its links and back to the
/// container, Shift+Tab the other way, and Enter opens the focused link.
#[gpui::test]
fn tab_loops_over_a_trap_focus_hovers_links(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-links", cx);
    let side_bar = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.side_bar_visible());
    let before = side_bar(cx);
    workbench.update_in(cx, |workbench, window, cx| {
        window.focus(&workbench.status_bar_focus, cx);
        let content = super::HoverContent::Markdown(serde_json::json!({ "value": "See [one](command:workbench.action.toggleSidebarVisibility) and [two](https://example.com)", "isTrusted": true }));
        let bounds = Bounds { origin: point(px(100.), px(100.)), size: size(px(50.), px(20.)) };
        workbench.show_focused_hover(super::HoverTarget { id: "target".into(), content, options: HoverOptions::managed(), bounds, mouse_x: None }, true, window, cx);
    });
    let focused_link = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.hovers.shown.as_ref().map(|shown| shown.focused_link));
    assert_eq!(focused_link(cx), Some(None), "the container has the focus");
    let mut stops = Vec::new();
    for keys in ["tab", "tab", "tab", "shift-tab", "shift-tab", "shift-tab"] {
        cx.simulate_keystrokes(keys);
        stops.push(focused_link(cx).expect("the hover stays"));
    }
    assert_eq!(stops, [Some(0), Some(1), None, Some(1), Some(0), None]);
    cx.simulate_keystrokes("tab enter");
    assert_eq!(focused_link(cx), None, "the link's hover hides");
    assert_ne!(side_bar(cx), before, "Enter opened the command link");
}

/// statusbarActions.ts: in the focused status bar Home, End and the arrows move an entry focus through the drawn
/// entries, past the ends around; Escape drops the entry, then leaves for the editor; showHover shows the entry's hover.
#[gpui::test]
fn the_status_bar_keys_move_an_entry_focus_with_its_hover(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-status-entries", cx);
    let state = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| (workbench.status_entry_focus.get(&window.window_handle().window_id()).cloned(), workbench.status_bar_focus.is_focused(window)))
    };
    let entries = workbench.read_with(cx, |workbench, _| workbench.status_entry_bounds.borrow().iter().map(|(_, id, _)| id.clone()).collect::<Vec<_>>());
    assert!(entries.len() > 1, "{entries:?}");
    let (first, last) = (Some(entries[0].clone()), Some(entries[entries.len() - 1].clone()));
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.status_bar_focus, cx));

    cx.simulate_keystrokes("home");
    assert_eq!(state(cx), (first.clone(), true));
    cx.simulate_keystrokes("right");
    assert_eq!(state(cx), (Some(entries[1].clone()), true));
    cx.simulate_keystrokes("end");
    assert_eq!(state(cx), (last.clone(), true));
    cx.simulate_keystrokes("right");
    assert_eq!(state(cx), (first.clone(), true), "past the last entry the first");
    cx.simulate_keystrokes("left");
    assert_eq!(state(cx), (last, true), "before the first the last");

    cx.simulate_keystrokes("home");
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showHover", Vec::new(), window, cx)));
    assert_eq!(shown(&workbench, cx).as_deref(), Some("No Problems"));
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), (first, true), "the hover hides and gives the entry its focus back");

    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), (None, true));
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), (None, false), "the editor has the focus");
}

/// activitybarPart.ts `focusActivityBar` and actionbar.ts: the first view container takes the focus, Up and Down
/// move it and loop around, Home and End jump, Enter opens the focused container; showHover shows its hover.
#[gpui::test]
fn the_activity_bar_items_take_the_keyboard_focus_with_their_hover(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-activity-bar", cx);
    let focused = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| {
            let handles = workbench.action_bars.handles.borrow();
            handles.iter().find(|(_, focus)| focus.is_focused(window)).map(|((bar, key), _)| format!("{bar}:{key}"))
        })
    };
    let run = |command: &str, cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(command, Vec::new(), window, cx)));

    run("workbench.action.focusActivityBar", cx);
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.explorer"));
    cx.simulate_keystrokes("down");
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.search"));
    cx.simulate_keystrokes("up up");
    let last = focused(cx);
    assert!(last.as_deref().is_some_and(|last| last.starts_with("activity:") && last != "activity:workbench.view.explorer"), "before the first the last: {last:?}");
    cx.simulate_keystrokes("down");
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.explorer"), "past the last the first");
    cx.simulate_keystrokes("end home");
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.explorer"));
    cx.simulate_keystrokes("down tab");
    assert_eq!(focused(cx).as_deref(), Some("global-activity:manage"), "Tab reaches the global bar");
    cx.simulate_keystrokes("shift-tab");
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.search"), "Shift+Tab gives the bar its last item back");
    cx.simulate_keystrokes("home");

    run("workbench.action.showHover", cx);
    assert!(shown(&workbench, cx).is_some_and(|text| text.starts_with("Explorer")), "{:?}", shown(&workbench, cx));
    cx.simulate_keystrokes("escape");
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.explorer"), "the hover gives the item its focus back");
    cx.simulate_keystrokes("down");
    assert_eq!(focused(cx).as_deref(), Some("activity:workbench.view.search"));
    cx.simulate_keystrokes("enter");
    cx.simulate_event(gpui::KeyUpEvent { keystroke: gpui::Keystroke::parse("enter").unwrap() });
    cx.run_until_parked();
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.side_bar_view), crate::workbench::search_view::SideBarView::Search);
}

/// paneCompositePart.ts title: the tabs, the merged view's actions and the global actions are three action bars,
/// one tab stop each, between the part before and the content.
#[gpui::test]
fn the_panel_title_bars_take_the_keyboard_focus_with_their_hover(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-panel-title", cx);
    let focused = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| {
            let handles = workbench.action_bars.handles.borrow();
            handles.iter().find(|(_, focus)| focus.is_focused(window)).map(|((bar, key), _)| format!("{bar}:{key}"))
        })
    };
    let run = |command: &str, cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(command, Vec::new(), window, cx)));

    run("workbench.panel.markers.view.focus", cx);
    cx.run_until_parked();
    cx.simulate_keystrokes("shift-tab");
    assert_eq!(focused(cx).as_deref(), Some("panel-global-actions:workbench.action.toggleMaximizedPanel"), "Shift+Tab from the content");
    run("workbench.action.showHover", cx);
    assert_eq!(shown(&workbench, cx).as_deref(), Some("Maximize Panel Size"));
    cx.simulate_keystrokes("escape");
    assert_eq!(focused(cx).as_deref(), Some("panel-global-actions:workbench.action.toggleMaximizedPanel"), "the hover gives the item its focus back");
    cx.simulate_keystrokes("shift-tab");
    let view_action = focused(cx);
    assert!(view_action.as_deref().is_some_and(|item| item.starts_with("workbench.panel.markers.view:")), "the view's actions: {view_action:?}");
    cx.simulate_keystrokes("shift-tab");
    assert_eq!(focused(cx).as_deref(), Some("panel-composite-bar:workbench.panel.markers"));
    cx.simulate_keystrokes("right");
    assert_eq!(focused(cx).as_deref(), Some("panel-composite-bar:workbench.panel.output"));
    run("workbench.action.showHover", cx);
    assert!(shown(&workbench, cx).is_some_and(|text| text.starts_with("Output")), "{:?}", shown(&workbench, cx));
    cx.simulate_keystrokes("escape tab");
    assert_eq!(focused(cx), view_action, "Tab from the tabs");
    cx.simulate_keystrokes("tab right");
    assert_eq!(focused(cx).as_deref(), Some("panel-global-actions:workbench.action.closePanel"));
    cx.simulate_keystrokes("tab");
    assert_eq!(focused(cx), None, "Tab past the global actions leaves the title");
    assert_eq!(workbench.update_in(cx, |workbench, window, _| workbench.focused_movable_view(window)), Some("workbench.panel.markers.view"));
}

/// compositeBarActions.ts `computeTitle`: a panel tab's hover appends its badge's description.
#[gpui::test]
fn a_panel_tab_hover_appends_the_badge_description(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-panel-badge", cx);
    workbench.update_in(cx, |workbench, window, cx| {
        let marker = |line: usize| serde_json::json!({ "severity": 8, "message": "bad", "startLineNumber": line, "startColumn": 1, "endLineNumber": line, "endColumn": 2 });
        workbench.diagnostics.service.change_one("test", "file:///w/a.ts", &[marker(1), marker(2)], false);
        drop(workbench.execute_command("workbench.panel.markers.view.focus", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, cx| assert!(workbench.focus_action_bar("panel-composite-bar", window, cx)));
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showHover", Vec::new(), window, cx)));
    let text = shown(&workbench, cx).expect("the Problems tab's hover");
    assert!(text.starts_with("Problems (") && text.ends_with(") - Total 2 Problems"), "{text}");
}

/// The side bar title's "Views and More Actions..." is the tab stop before the first pane header.
#[gpui::test]
fn the_side_bar_title_more_actions_is_the_tab_stop_before_the_first_pane_header(cx: &mut TestAppContext) {
    use crate::workbench::view_panes::PaneContainer;
    let (workbench, cx) = open_workbench("hover-container-title", cx);
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.view.explorer", Vec::new(), window, cx)));
    cx.run_until_parked();
    let first = workbench.update_in(cx, |workbench, window, cx| {
        let first = workbench.panes(PaneContainer::Explorer).view.as_ref().expect("the explorer is laid out").ids()[0];
        workbench.focus_pane_header(first, window, cx);
        first
    });
    cx.simulate_keystrokes("shift-tab");
    cx.run_until_parked();
    let item = workbench.update_in(cx, |workbench, window, _| {
        let handles = workbench.action_bars.handles.borrow();
        handles.iter().find(|(_, focus)| focus.is_focused(window)).map(|((bar, key), _)| format!("{bar}:{key}"))
    });
    assert_eq!(item.as_deref(), Some("explorer:more"), "Shift+Tab from the first header");
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showHover", Vec::new(), window, cx)));
    assert_eq!(shown(&workbench, cx).as_deref(), Some("Views and More Actions..."));
    cx.simulate_keystrokes("escape tab");
    cx.run_until_parked();
    assert!(workbench.update_in(cx, |workbench, window, _| workbench.pane_header_focused(first, window)), "Tab from the title");
}

/// A side bar view alone in its container merges its actions into the composite title, the tab stop before its body.
#[gpui::test]
fn a_merged_view_title_is_the_tab_stop_before_its_body(cx: &mut TestAppContext) {
    use crate::workbench::input_box_view::InputId;
    use crate::workbench::search_view::SearchField;
    let (workbench, cx) = open_workbench("hover-merged-title", cx);
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.view.search", Vec::new(), window, cx)));
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.search.toggle_replace_focus.clone(), cx));
    cx.simulate_keystrokes("shift-tab");
    cx.run_until_parked();
    let bar = workbench.update_in(cx, |workbench, window, _| workbench.focused_action_bar(window));
    assert_eq!(bar, Some("workbench.view.search"), "Shift+Tab from the body");
    cx.simulate_keystrokes("tab");
    cx.run_until_parked();
    assert!(workbench.update_in(cx, |workbench, window, _| workbench.search.toggle_replace_focus.is_focused(window)), "Tab from the title");
    cx.simulate_keystrokes("tab");
    cx.run_until_parked();
    assert_eq!(workbench.update_in(cx, |workbench, window, _| workbench.focused_input(window)), Some(InputId::Search(SearchField::Query)), "Tab from the Toggle Replace button");
}

/// multiEditorTabsControl.ts: the active tab is the group title's tab stop before the editor; the arrows, Home and
/// End open their editor and keep the focus on its tab, Enter opens it with the focus, showHover shows its hover.
#[gpui::test]
fn the_active_editor_tab_takes_the_keyboard_focus_with_its_hover(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-editor-tab", cx);
    let dir = std::env::temp_dir().join(format!("code-gpui-hover-editor-tab-files-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    for name in ["a.txt", "b.txt", "c.txt"] {
        std::fs::write(dir.join(name), name).unwrap();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join(name), true, window, cx));
    }
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.watch_editor_focus(window, cx);
        window.activate_window();
        window.focus(&workbench.editor_focus, cx);
    });
    let state = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| {
            let name = workbench.editors.active().unwrap().document().path.file_name().unwrap().to_string_lossy().into_owned();
            (name, workbench.editor_tab_focus.is_focused(window), workbench.editor_focus.is_focused(window))
        })
    };
    let state_of = |name: &str, tab: bool, editor: bool| (name.to_string(), tab, editor);

    // Past the editor actions toolbar and c.txt's close action.
    cx.simulate_keystrokes(&format!("{TOGGLE_TAB_FOCUS} shift-tab shift-tab shift-tab"));
    assert_eq!(state(cx), state_of("c.txt", true, false), "Shift+Tab from the editor");
    cx.simulate_keystrokes("left");
    assert_eq!(state(cx), state_of("b.txt", true, false));
    cx.simulate_keystrokes("home left");
    assert_eq!(state(cx), state_of("a.txt", true, false), "no tab before the first");
    cx.simulate_keystrokes("end right");
    assert_eq!(state(cx), state_of("c.txt", true, false), "no tab after the last");
    cx.simulate_keystrokes("up");

    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showHover", Vec::new(), window, cx)));
    assert!(shown(&workbench, cx).is_some_and(|text| text.contains("b.txt")), "{:?}", shown(&workbench, cx));
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), state_of("b.txt", true, false), "the hover gives the tab its focus back");
    // b.txt's and c.txt's close actions and the editor actions toolbar come first.
    cx.simulate_keystrokes("tab tab tab tab");
    assert_eq!(state(cx), state_of("b.txt", false, true), "Tab goes on to the editor");
    cx.simulate_keystrokes("shift-tab shift-tab shift-tab shift-tab enter");
    cx.simulate_event(gpui::KeyUpEvent { keystroke: gpui::Keystroke::parse("enter").unwrap() });
    assert_eq!(state(cx), state_of("b.txt", false, true), "Enter opens the editor with the focus");

    // Shift+F10 shows the tab's context menu below the tab; closing it gives the group the focus.
    cx.simulate_keystrokes("shift-tab shift-tab shift-tab shift-tab shift-f10");
    let (menu, tab) = workbench.read_with(cx, |workbench, _| {
        let tab = workbench.painted_hover_bounds(&workbench.tab_hover_id(1)).unwrap();
        (workbench.context_menu.as_ref().map(|menu| menu.levels[0].origin), tab)
    });
    assert_eq!(menu, Some(gpui::point(tab.left(), tab.bottom())));
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), state_of("b.txt", false, true));
    std::fs::remove_dir_all(dir).unwrap();
}

/// multiEditorTabsControl.ts `createTab` and actionbar.ts: every tab's close action is a tab stop after its tab, the
/// editor actions toolbar one tab stop before the editor with the arrows inside it, and Enter on a close action
/// closes its editor.
#[gpui::test]
fn the_tab_close_actions_and_the_editor_actions_toolbar_are_tab_stops(cx: &mut TestAppContext) {
    use super::super::editor_view::{EDITOR_ACTIONS, TAB_ACTIONS};
    let (workbench, cx) = open_workbench("hover-tab-stops", cx);
    let dir = std::env::temp_dir().join(format!("code-gpui-hover-tab-stops-files-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    for name in ["a.txt", "b.txt", "c.txt"] {
        std::fs::write(dir.join(name), name).unwrap();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join(name), true, window, cx));
    }
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.activate(1);
        workbench.editors_changed(cx);
        workbench.watch_editor_focus(window, cx);
        window.activate_window();
        window.focus(&workbench.editor_focus, cx);
    });
    let focused = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| {
            if workbench.editor_focus.is_focused(window) {
                return "editor".to_string();
            }
            if workbench.editor_tab_focus.is_focused(window) {
                return "tab".to_string();
            }
            for index in 0..workbench.editors.editors.len() {
                if workbench.action_bar_focus(TAB_ACTIONS, &index.to_string(), cx).is_focused(window) {
                    return format!("close {index}");
                }
            }
            let actions = workbench.drawn_action_bar_items(EDITOR_ACTIONS);
            match actions.iter().position(|action| action.is_focused(window)) {
                Some(index) if index + 1 == actions.len() => "actions last".to_string(),
                Some(index) => format!("actions {index}"),
                None => "elsewhere".to_string(),
            }
        })
    };

    cx.simulate_keystrokes(TOGGLE_TAB_FOCUS);
    let mut backwards = Vec::new();
    for _ in 0..6 {
        cx.simulate_keystrokes("shift-tab");
        backwards.push(focused(cx));
    }
    assert_eq!(backwards, ["actions 0", "close 2", "close 1", "tab", "close 0", "elsewhere"], "Shift+Tab from the editor, only the active tab a stop");
    let mut forwards = Vec::new();
    for _ in 0..6 {
        cx.simulate_keystrokes("tab");
        forwards.push(focused(cx));
    }
    assert_eq!(forwards, ["close 0", "tab", "close 1", "close 2", "actions 0", "editor"], "Tab from before the group");

    cx.simulate_keystrokes("shift-tab left");
    assert_eq!(focused(cx), "actions last", "Left from the first action loops to the last");
    cx.simulate_keystrokes("right");
    assert_eq!(focused(cx), "actions 0");
    cx.simulate_keystrokes("end shift-tab tab");
    assert_eq!(focused(cx), "actions last", "the toolbar gives the focus back to its last focused action");

    cx.simulate_keystrokes("shift-tab shift-tab shift-tab shift-tab enter");
    cx.simulate_event(gpui::KeyUpEvent { keystroke: gpui::Keystroke::parse("enter").unwrap() });
    cx.run_until_parked();
    let names = workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| editor.document().path.file_name().unwrap().to_string_lossy().into_owned()).collect::<Vec<_>>());
    assert_eq!(names, ["b.txt", "c.txt"], "Enter on a.txt's close action closes it");
    std::fs::remove_dir_all(dir).unwrap();
}

/// updateTitleBarEntry.ts: the entry is `MenuId.TitleBarUpdate`'s toolbar, a tab stop before the activity bar, and
/// `workbench.action.showHover` on it shows its sticky tooltip with the focus on its buttons (`focusTooltip`).
#[gpui::test]
fn show_hover_on_the_update_title_bar_entry_focuses_its_tooltip(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-update-entry", cx);
    cx.update(|window, _| window.activate_window());
    let update = crate::update::Update { version: "b".into(), product_version: "1.148.0".into(), timestamp: 2, url: String::new(), sha256hash: String::new() };
    workbench.update_in(cx, |workbench, window, cx| workbench.update_state_changed(&crate::update::State::Downloaded { update }, window, cx));
    cx.run_until_parked();
    let state = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| (workbench.focused_action_bar(window), workbench.hovers.sticky_shown(super::super::update_title_bar::TOOLTIP), workbench.update_title_bar.focused_button))
    };

    workbench.update_in(cx, |workbench, window, cx| assert!(workbench.focus_action_bar("activity", window, cx)));
    cx.simulate_keystrokes("shift-tab shift-tab");
    assert_eq!(state(cx), (Some("title-update"), false, None), "Shift+Tab from the activity bar past the title actions");
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showHover", Vec::new(), window, cx)));
    assert_eq!(state(cx), (Some("title-update"), true, Some(0)), "the tooltip with its first button focused");
    cx.simulate_keystrokes("tab");
    assert_eq!(state(cx), (Some("title-update"), true, Some(1)), "Tab stays in the tooltip");
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), (Some("title-update"), false, None));
    cx.simulate_keystrokes("tab tab");
    assert_eq!(state(cx).0, Some("activity"), "Tab goes on past the title actions to the activity bar");
}

/// titlebarPart.ts: the command center (commandCenterControl.ts), the update entry and the action toolbar (editor,
/// layout and global actions) are each one tab stop, in the DOM order before the activity bar.
#[gpui::test]
fn the_title_bar_toolbars_are_tab_stops_in_the_dom_order(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-title-toolbars", cx);
    cx.update(|window, _| window.activate_window());
    let bar = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| workbench.focused_action_bar(window))
    };
    let side_bar = |cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, _, _| workbench.is_part_visible(super::super::layout::Part::SideBar));

    workbench.update_in(cx, |workbench, window, cx| assert!(workbench.focus_action_bar("activity", window, cx)));
    cx.simulate_keystrokes("shift-tab");
    assert_eq!(bar(cx), Some("title-actions"), "Shift+Tab from the activity bar reaches the action toolbar");
    let layout = workbench.update_in(cx, |workbench, _, cx| workbench.action_bar_focus("title-actions", "workbench.action.toggleSidebarVisibility", cx));
    cx.simulate_keystrokes("right");
    assert!(workbench.update_in(cx, |_, window, _| layout.is_focused(window)), "Right moves to Toggle Primary Side Bar");
    let visible = side_bar(cx);
    cx.simulate_keystrokes("enter");
    cx.simulate_event(gpui::KeyUpEvent { keystroke: gpui::Keystroke::parse("enter").unwrap() });
    cx.run_until_parked();
    assert_eq!(side_bar(cx), !visible, "Enter runs the layout control");
    let item = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, _| {
            let handles = workbench.action_bars.handles.borrow();
            handles.iter().find(|(_, focus)| focus.is_focused(window)).map(|((bar, key), _)| format!("{bar}:{key}"))
        })
    };
    let mut stops = Vec::new();
    for keys in ["shift-tab", "shift-tab", "tab", "tab", "tab"] {
        cx.simulate_keystrokes(keys);
        stops.push(item(cx).unwrap_or_default());
    }
    let layout = "title-actions:workbench.action.toggleSidebarVisibility";
    // The command center's center is a nested toolbar: a tab stop after the navigation buttons', without the update entry.
    assert_eq!(stops, ["title-command-center:center", "title-command-center:back", "title-command-center:center", layout, "activity:workbench.view.explorer"]);
    // workbench.css outlines the focused item itself, not the slot after its icon.
    let outline = workbench.update_in(cx, |workbench, _, cx| workbench.drawn_action_bar_item_bounds("activity", "workbench.view.explorer", cx));
    assert_eq!(Some(outline), cx.debug_bounds("workbench.view.explorer"));
}

/// hoverService.ts `setupManagedHover` `onFocus`: an action the keyboard focuses shows its hover after the delay and a
/// focus moving on hides it; an activity bar item's `setupDelayedHover` shows none on focus.
#[gpui::test]
fn a_keyboard_focused_action_shows_its_hover(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("hover-focused-action", cx);
    cx.update(|window, _| window.activate_window());
    cx.run_until_parked();
    let after_delay = |cx: &mut gpui::VisualTestContext| {
        cx.run_until_parked();
        let before = workbench.update(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned));
        cx.executor().advance_clock(Duration::from_millis(1500));
        cx.run_until_parked();
        (before, workbench.update(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned)))
    };

    workbench.update_in(cx, |workbench, window, cx| assert!(workbench.focus_action_bar("activity", window, cx)));
    assert_eq!(after_delay(cx), (None, None));
    cx.simulate_keystrokes("shift-tab");
    assert_eq!(after_delay(cx), (None, Some("Customize Layout...".to_string())));
    cx.simulate_keystrokes("right");
    let (before, after) = after_delay(cx);
    assert_eq!(before, None);
    assert!(after.is_some_and(|text| text.starts_with("Toggle Primary Side Bar")));
}

#[gpui::test]
fn a_focused_activity_item_draws_the_reference_focus_indicator(cx: &mut TestAppContext) {
    let (workbench, cx) = open_workbench("activity-focus-indicator", cx);
    cx.update(|window, _| window.activate_window());
    workbench.update_in(cx, |workbench, window, cx| assert!(workbench.focus_action_bar("activity", window, cx)));
    cx.run_until_parked();
    let (scale, border, indicator) = workbench.update_in(cx, |workbench, window, _| (window.scale_factor(), workbench.theme.color("focusBorder").unwrap(), workbench.theme.color("activityBar.activeBorder").unwrap()));
    let outline_radii = |cx: &mut gpui::VisualTestContext| cx.read_rendered_frame(|scene, _| scene.quads.iter().filter(|quad| quad.border_color == border.into() && quad.border_widths.top.0 > 0. && quad.bounds.size.width.0 <= 38. * scale).map(|quad| quad.corner_radii.top_left.0 / scale).collect::<Vec<_>>());
    let left_bars = |cx: &mut gpui::VisualTestContext| cx.read_rendered_frame(|scene, _| scene.quads.iter().filter(|quad| quad.background == indicator.into() && quad.bounds.size.width.0 == 2. * scale).count());

    assert_eq!((outline_radii(cx), left_bars(cx)), (vec![], 1), "the unchecked Explorer item: the left indicator");
    workbench.update_in(cx, |workbench, window, cx| {
        drop(workbench.execute_command("workbench.view.explorer", Vec::new(), window, cx));
        assert!(workbench.focus_action_bar("activity", window, cx));
    });
    cx.run_until_parked();
    let radii = outline_radii(cx);
    assert_eq!((!radii.is_empty() && radii.iter().all(|radius| *radius == 4.), left_bars(cx)), (true, 0), "the checked Explorer item: a rounded outline {radii:?}");
}