Visual Studio Code, rebuilt in Rust
Rust
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use gpui::{Bounds, TestAppContext, point, size};
use super::*;
#[test]
fn distance_to_rectangle_is_zero_inside_and_euclidean_outside() {
let bounds = Bounds { origin: point(10., 10.), size: size(20., 10.) };
assert_eq!(distance_to_rectangle(point(15., 15.), bounds), 0.);
assert_eq!(distance_to_rectangle(point(5., 15.), bounds), 5.);
assert_eq!(distance_to_rectangle(point(33., 24.), bounds), 5.);
}
#[test]
fn code_points_format_as_the_reference_writes_them() {
assert_eq!(code_point_to_hex('\u{2013}'), "U+2013");
assert_eq!(code_point_to_hex('\u{a0}'), "U+00a0");
assert_eq!(format_code_point_markdown('\u{2013}'), "`U+2013` \"`\u{2013}`\"");
assert_eq!(format_code_point_markdown('\u{200b}'), "`U+200b`");
}
#[test]
fn encode_uri_component_keeps_the_unreserved_marks() {
assert_eq!(encode_uri_component("{\"a\":1}"), "%7B%22a%22%3A1%7D");
assert_eq!(encode_uri_component("é-_.!~*'()"), "%C3%A9-_.!~*'()");
}
/// contentHoverController.ts runs per code editor: a move over another group's editor hovers that editor, a move
/// off it hides the hover.
#[gpui::test]
fn the_mouse_over_another_groups_editor_shows_its_hover(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("vsrustium-hover-group-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("User")).unwrap();
// `nonBasicASCII` highlights the `é`: the unicode highlighter's hover part explains it.
std::fs::write(dir.join("User/settings.json"), r#"{ "editor.unicodeHighlight.nonBasicASCII": true }"#).unwrap();
let file = dir.join("a.txt");
std::fs::write(&file, "café\n").unwrap();
let settings = Arc::new(Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let (workbench, cx) = cx.add_window_view(|window, cx| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx);
workbench.open_file(file.clone(), true, window, cx);
workbench
});
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.splitEditor", vec![], window, cx)));
cx.run_until_parked();
let (left, left_id) = workbench.update(cx, |workbench, _| {
let left = workbench.groups_in_grid_order()[0];
(left, workbench.with_group(left, |workbench| workbench.editors.active().unwrap().model_id))
});
assert_ne!(left_id, workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().model_id));
cx.update(|window, _| window.refresh());
cx.run_until_parked();
let (content_left, char_width, line_height) = workbench.update_in(cx, |workbench, window, _| {
workbench.with_group(left, |workbench| {
let metrics = workbench.editor_metrics(workbench.editors.active().unwrap(), window);
(metrics.content_left(), metrics.char_width, metrics.line_height)
})
});
let bounds = cx.debug_bounds(format!("text-area-{left_id}").leak()).unwrap();
let on_char = bounds.origin + point(gpui::px(content_left + 3.25 * char_width), gpui::px(line_height / 2.));
cx.simulate_mouse_move(on_char, None, gpui::Modifiers::default());
cx.executor().advance_clock(Duration::from_millis(1000));
cx.update(|window, _| window.refresh());
cx.run_until_parked();
workbench.read_with(cx, |workbench, _| {
let shown = workbench.content_hover.shown.as_ref().expect("the hover shows");
assert_eq!((shown.anchor.model_id, shown.anchor.line, shown.anchor.start), (left_id, 0, 3));
assert!(workbench.content_hover.widget_bounds.get().is_some(), "the other group draws the hover widget");
});
cx.simulate_mouse_move(bounds.origin - point(gpui::px(0.), gpui::px(10.)), None, gpui::Modifiers::default());
cx.run_until_parked();
workbench.read_with(cx, |workbench, _| assert!(workbench.content_hover.shown.is_none(), "leaving the editor hides its hover"));
std::fs::remove_dir_all(dir).unwrap();
}
/// A window with `a.txt` open, the workspace folder to remove and the messages to the host.
fn open<'a>(cx: &'a mut TestAppContext, name: &str) -> (gpui::Entity<Workbench>, &'a mut gpui::VisualTestContext, std::path::PathBuf, std::sync::mpsc::Receiver<crate::host_sync::HostMessage>) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("vsrustium-hover-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("User")).unwrap();
let file = dir.join("a.txt");
std::fs::write(&file, "text\n").unwrap();
let settings = Arc::new(Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let (sender, messages) = std::sync::mpsc::channel();
let (workbench, cx) = cx.add_window_view(|window, cx| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(sender), cx);
workbench.open_file(file.clone(), true, window, cx);
workbench
});
cx.simulate_resize(size(gpui::px(1600.), gpui::px(900.)));
(workbench, cx, dir, messages)
}
/// A keyboard hover over the first word holding `markdown`, laid out.
fn show_markdown(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext, markdown: &str) {
workbench.update(cx, |workbench, cx| {
let model_id = workbench.editors.active().unwrap().model_id;
let (start, end) = (Position::new(0, 0), Position::new(0, 4));
let part = Part { participant: Participant::Markdown, ordinal: 0, start, end, content: PartContent::Markdown(vec![json!({ "value": markdown })]), source: None };
let anchor = Anchor { model_id, line: 0, start: 0, end: 4 };
workbench.set_content_hover_result(Some(Shown { anchor, parts: vec![part], complete: true, keyboard: true, initial_mouse: None, closest_distance: None, scroll: (0., 0.) }), cx);
});
for _ in 0..3 {
cx.update(|window, _| window.refresh());
cx.run_until_parked();
}
}
/// resizableContentWidget.ts: below the line the east and south sashes resize the hover, within its contents'
/// width (`minSize`); the size holds until a new result lays the hover out again, and stays `_lastDimensions`.
#[gpui::test]
fn the_sashes_resize_the_hover_until_its_next_result(cx: &mut TestAppContext) {
use gpui::{Modifiers, MouseButton};
let (workbench, cx, dir, _) = open(cx, "resize");
let paragraphs: Vec<String> = (1..=30).map(|n| format!("paragraph {n} {}", "lorem ipsum ".repeat(6))).collect();
let markdown = paragraphs.join("\n\n");
let drawn = |cx: &mut gpui::VisualTestContext| {
cx.update(|window, _| window.refresh());
cx.run_until_parked();
let bounds = workbench.read_with(cx, |workbench, _| workbench.content_hover.widget_bounds.get()).expect("the hover draws");
(bounds.size.width + 2., bounds.size.height + 2.)
};
let drag = |cx: &mut gpui::VisualTestContext, sash: &'static str, by: gpui::Point<gpui::Pixels>| {
let from = cx.debug_bounds(sash).unwrap_or_else(|| panic!("{sash} draws")).center();
cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none());
cx.simulate_mouse_move(from + by, Some(MouseButton::Left), Modifiers::none());
cx.simulate_mouse_up(from + by, MouseButton::Left, Modifiers::none());
};
show_markdown(&workbench, cx, &markdown);
let (width, height) = drawn(cx);
assert!(cx.debug_bounds("content-hover-sash-s").is_some() && cx.debug_bounds("content-hover-sash-n").is_none(), "below the line: no north sash");
let south = cx.debug_bounds("content-hover-sash-s").unwrap().center();
cx.simulate_mouse_move(south, None, Modifiers::none());
cx.executor().advance_clock(Duration::from_millis(300));
cx.run_until_parked();
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.content_hover.hovered_sash), Some(1), "sash.hoverBorder after workbench.sash.hoverDelay");
drag(cx, "content-hover-sash-s", point(gpui::px(0.), gpui::px(-54.)));
assert_eq!(drawn(cx), (width, height - 54.));
drag(cx, "content-hover-sash-e", point(gpui::px(-40.), gpui::px(0.)));
assert_eq!(drawn(cx), (width - 40., height - 54.));
drag(cx, "content-hover-sash-e", point(gpui::px(-2000.), gpui::px(0.)));
assert_eq!(drawn(cx).0, 150., "minSize: the contents are wider than contentHoverWidget.ts' 150");
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_some()), "dragging keeps the hover");
show_markdown(&workbench, cx, &markdown);
assert_eq!(drawn(cx), (width, height));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.content_hover.last_size), (150., height - 54.));
std::fs::remove_dir_all(dir).unwrap();
}
/// hoverCopyButton.ts `_copyContent`: the part's text goes to the clipboard and aria.ts `status` reads it out.
#[gpui::test]
fn the_copy_button_copies_the_part_and_announces_it(cx: &mut TestAppContext) {
let (workbench, cx, dir, _) = open(cx, "copy");
show_markdown(&workbench, cx, "some **docs**");
let button = cx.debug_bounds("content-hover-copy-0").expect("the copy button draws").center();
cx.simulate_click(button, gpui::Modifiers::none());
assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("some docs"));
let status = workbench.read_with(cx, |workbench, _| workbench.accessibility.status.clone().map(|(message, _)| message));
assert_eq!(status.as_deref(), Some("Copied to clipboard"));
std::fs::remove_dir_all(dir).unwrap();
}
/// Answers the `$provideHover` calls sent since the last answer with `hover`; returns their contexts.
fn answer_hovers(messages: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, hover: Value, cx: &mut gpui::VisualTestContext) -> Vec<Value> {
let mut contexts = Vec::new();
for message in messages.try_iter().filter(|message| message.method == "$provideHover") {
contexts.push(message.args[3].clone());
let _ = message.reply.expect("a call").send(Ok(hover.clone()));
}
for _ in 0..3 {
cx.update(|window, _| window.refresh());
cx.run_until_parked();
}
contexts
}
/// markdownHoverParticipant.ts: a provider's hover that can grow shows + (and a disabled -); + asks the provider
/// again with `verbosityRequest` for the hover's id, a second request while one is out cancels it and adds its delta,
/// and the answer replaces the part.
#[gpui::test]
fn the_verbosity_actions_ask_the_provider_for_a_more_verbose_hover(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open(cx, "verbosity");
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
workbench.update_in(cx, |workbench, window, cx| {
workbench.language_features.register("$registerHoverProvider", vec![json!(3), json!("*")]);
_ = workbench.execute_command("editor.action.showHover", vec![], window, cx);
});
cx.run_until_parked();
let first = answer_hovers(&messages, json!({ "id": 0, "contents": [{ "value": "short" }], "range": range, "canIncreaseVerbosity": true }), cx);
assert_eq!(first, [json!({})]);
assert!(cx.debug_bounds("content-hover-verbosity-0--1").is_some(), "the disabled - shows next to +");
let plus = cx.debug_bounds("content-hover-verbosity-0-1").expect("+ draws").center();
cx.simulate_click(plus, gpui::Modifiers::none());
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.increaseHoverVerbosityLevel", vec![], window, cx));
cx.run_until_parked();
let longer = json!({ "id": 1, "contents": [{ "value": "short and long" }], "range": range, "canDecreaseVerbosity": true });
let contexts = answer_hovers(&messages, longer, cx);
let request = |delta: i64| json!({ "verbosityRequest": { "verbosityDelta": delta, "previousHover": { "id": 0 } } });
assert_eq!(contexts, [request(1), request(2)]);
workbench.read_with(cx, |workbench, _| {
let part = &workbench.content_hover.shown.as_ref().expect("the hover stays").parts[0];
let PartContent::Markdown(contents) = &part.content else { panic!("a markdown part") };
assert_eq!(contents, &[json!({ "value": "short and long" })]);
assert_eq!(part.source.as_ref().map(|source| source.hover["id"].clone()), Some(json!(1)));
});
std::fs::remove_dir_all(dir).unwrap();
}
/// markdownHoverParticipant.ts `_renderHoverExpansionAction`: each action's hover delegate targets
/// `.verbosity-actions-inner`, the column of both actions with its 5px paddings, not the action itself.
#[gpui::test]
fn the_verbosity_action_hovers_target_their_column(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "verbosity-target");
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", vec![], window, cx));
cx.run_until_parked();
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
answer_hovers(&messages, json!({ "id": 0, "contents": [{ "value": "short" }], "range": range, "canIncreaseVerbosity": true }), cx);
let plus = cx.debug_bounds("content-hover-verbosity-0-1").expect("+ draws");
let minus = cx.debug_bounds("content-hover-verbosity-0--1").expect("- draws");
let column = Bounds::from_corners(point(plus.left() - gpui::px(5.), plus.top()), point(plus.right() + gpui::px(5.), minus.bottom()));
for command in ["editor.action.increaseHoverVerbosityLevel", "editor.action.decreaseHoverVerbosityLevel"] {
let target = workbench.read_with(cx, |workbench, _| workbench.painted_hover_bounds(&gpui::ElementId::from(command)));
assert_eq!(target, Some(column), "{command}");
}
std::fs::remove_dir_all(dir).unwrap();
}
/// `open` with a hover provider for every document.
fn open_with_provider<'a>(cx: &'a mut TestAppContext, name: &str) -> (gpui::Entity<Workbench>, &'a mut gpui::VisualTestContext, std::path::PathBuf, std::sync::mpsc::Receiver<crate::host_sync::HostMessage>) {
let (workbench, cx, dir, messages) = open(cx, name);
workbench.update(cx, |workbench, _| workbench.language_features.register("$registerHoverProvider", vec![json!(3), json!("*")]));
(workbench, cx, dir, messages)
}
/// Runs `editor.action.showHover` with `args`; the provider answers with `docs` over the first word.
fn run_show_hover(workbench: &gpui::Entity<Workbench>, messages: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, args: Vec<Value>, cx: &mut gpui::VisualTestContext) {
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", args, window, cx));
cx.run_until_parked();
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
answer_hovers(messages, json!({ "contents": [{ "value": "docs" }], "range": range }), cx);
}
/// `editorHoverFocused`, `editorFocus` and `editorTextFocus`.
fn focus_keys(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext) -> [bool; 3] {
workbench.update_in(cx, |workbench, window, _| {
let context = workbench.key_context(window);
["editorHoverFocused", "editorFocus", "editorTextFocus"].map(|key| context[key] == true)
})
}
/// A keyboard hover with the focus in it, and a point of the text area below the text, away from the hover.
fn focused_hover(workbench: &gpui::Entity<Workbench>, messages: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, cx: &mut gpui::VisualTestContext) -> gpui::Point<gpui::Pixels> {
run_show_hover(workbench, messages, vec![], cx);
workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.content_hover_focus, cx));
cx.run_until_parked();
let id = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().model_id);
let bounds = cx.debug_bounds(format!("text-area-{id}").leak()).expect("the text area draws");
bounds.origin + point(bounds.size.width / 2., bounds.size.height - gpui::px(20.))
}
/// hoverActions.ts ShowOrFocusHoverAction: the first run shows the hover, a second focuses it; the hover is part of
/// the editor's DOM, so `editorFocus` holds and `editorTextFocus` does not.
#[gpui::test]
fn showing_the_hover_again_focuses_it(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-again");
run_show_hover(&workbench, &messages, vec![], cx);
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_some()), "the hover shows");
assert_eq!(focus_keys(&workbench, cx), [false, true, true], "the first run leaves the focus in the text");
run_show_hover(&workbench, &messages, vec![], cx);
assert_eq!(focus_keys(&workbench, cx), [true, true, false]);
std::fs::remove_dir_all(dir).unwrap();
}
/// `focus`: autoFocusImmediately focuses the hover it shows; noAutoFocus never focuses it.
#[gpui::test]
fn the_focus_argument_picks_when_the_hover_takes_the_focus(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-argument");
run_show_hover(&workbench, &messages, vec![json!({ "focus": "autoFocusImmediately" })], cx);
assert_eq!(focus_keys(&workbench, cx), [true, true, false], "the shown hover has the focus");
workbench.update_in(cx, |workbench, window, cx| {
workbench.hide_content_hover(cx);
window.focus(&workbench.editor_focus, cx);
});
run_show_hover(&workbench, &messages, vec![json!({ "focus": "noAutoFocus" })], cx);
run_show_hover(&workbench, &messages, vec![json!({ "focus": "noAutoFocus" })], cx);
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_some()), "the hover shows");
assert_eq!(focus_keys(&workbench, cx), [false, true, true]);
std::fs::remove_dir_all(dir).unwrap();
}
/// contentHoverWidgetWrapper.ts: Escape in the hover hides it, and contentHoverWidget.ts `hide` focuses the editor.
#[gpui::test]
fn escape_in_the_hover_hides_it_and_focuses_the_editor(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-escape");
focused_hover(&workbench, &messages, cx);
assert_eq!(focus_keys(&workbench, cx), [true, true, false]);
cx.simulate_keystrokes("escape");
cx.update(|window, _| window.refresh());
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_none()), "Escape hides the hover");
assert_eq!(focus_keys(&workbench, cx), [false, true, true]);
std::fs::remove_dir_all(dir).unwrap();
}
/// contentHoverController.ts `_shouldKeepCurrentHover`: with `editor.hover.sticky` off, a mouse move over the
/// text away from a focused hover keeps it.
#[gpui::test]
fn a_focused_hover_stays_while_the_mouse_moves_over_the_text(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-move");
workbench.update(cx, |workbench, _| workbench.update_user_setting("editor.hover.sticky", json!(false)));
let below_text = focused_hover(&workbench, &messages, cx);
cx.simulate_mouse_move(below_text, None, gpui::Modifiers::none());
cx.executor().advance_clock(Duration::from_millis(1000));
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_some()), "the focused hover stays");
std::fs::remove_dir_all(dir).unwrap();
}
/// `_onEditorMouseLeave` keeps a focused hover when the mouse leaves the editor.
#[gpui::test]
fn a_focused_hover_stays_when_the_mouse_leaves_the_editor(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-leave");
let below_text = focused_hover(&workbench, &messages, cx);
cx.simulate_mouse_move(below_text, None, gpui::Modifiers::none());
cx.run_until_parked();
let id = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().model_id);
let bounds = cx.debug_bounds(format!("text-area-{id}").leak()).unwrap();
cx.simulate_mouse_move(bounds.origin - point(gpui::px(0.), gpui::px(10.)), None, gpui::Modifiers::none());
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_some()), "the focused hover stays");
std::fs::remove_dir_all(dir).unwrap();
}
/// `_onEditorMouseDown` keeps the hover only for a click on it (`_shouldKeepHoverWidgetVisible`), focused or not.
#[gpui::test]
fn a_click_in_the_text_hides_a_focused_hover(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-click");
let below_text = focused_hover(&workbench, &messages, cx);
cx.simulate_click(below_text, gpui::Modifiers::none());
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_none()), "the click hides the hover");
assert_eq!(focus_keys(&workbench, cx), [false, true, true], "the click focuses the text");
std::fs::remove_dir_all(dir).unwrap();
}
/// Answers every `$provideHover` request with `hover` and returns the provider handles asked.
fn answer_hover_handles(messages: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, hover: Value, cx: &mut gpui::VisualTestContext) -> Vec<Value> {
let mut handles = Vec::new();
for message in messages.try_iter().filter(|message| message.method == "$provideHover") {
handles.push(message.args[0].clone());
let _ = message.reply.expect("a call").send(Ok(hover.clone()));
}
for _ in 0..3 {
cx.update(|window, _| window.refresh());
cx.run_until_parked();
}
handles
}
/// The provider handle of the rendered part at `index`.
fn rendered_part_handle(workbench: &gpui::Entity<Workbench>, index: usize, cx: &mut gpui::VisualTestContext) -> Value {
workbench.read_with(cx, |workbench, _| {
let mut parts: Vec<&Part> = workbench.content_hover.shown.as_ref().unwrap().parts.iter().collect();
parts.sort_by_key(|part| (part.participant, part.ordinal));
json!(parts[index].source.as_ref().unwrap().handle)
})
}
fn focused_part(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext) -> Option<usize> {
workbench.update_in(cx, |workbench, window, _| workbench.focused_hover_part_index(window))
}
/// The focused part and the element inside it that has the focus.
fn focused_stop(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext) -> Option<(usize, Option<PartStop>)> {
workbench.update_in(cx, |workbench, window, _| {
let index = workbench.focused_hover_part_index(window)?;
Some((index, workbench.focused_hover_stop(window).map(|(_, stop)| stop)))
})
}
/// Enter and Space on the elements inside a part: a link runs its command (markdownRenderer.ts `activateLink`), the
/// copy button copies (`SimpleButton`), + asks for a more verbose hover and focuses its part (`KeyDownAction`), and
/// the disabled - does nothing.
#[gpui::test]
fn enter_and_space_activate_the_focused_element_of_a_part(cx: &mut TestAppContext) {
use PartStop::{Copy, Link, Verbosity};
let (workbench, cx, dir, messages) = open_with_provider(cx, "part-stops");
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", vec![], window, cx));
cx.run_until_parked();
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
let contents = json!([{ "value": "see [docs](command:editor.action.hideHover) and [more](command:editor.action.hideHover)", "isTrusted": true }]);
answer_hovers(&messages, json!({ "id": 0, "contents": contents, "range": range, "canIncreaseVerbosity": true }), cx);
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", vec![json!({ "focus": true })], window, cx));
cx.run_until_parked();
let mut stops = Vec::new();
for _ in 0..5 {
cx.simulate_keystrokes("tab");
stops.push(focused_stop(&workbench, cx).and_then(|(_, stop)| stop));
}
assert_eq!(stops, [Some(Verbosity(1)), Some(Verbosity(-1)), Some(Link(0)), Some(Link(1)), Some(Copy)]);
cx.simulate_keystrokes("space");
assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("see docs and more"));
cx.simulate_keystrokes("shift-tab shift-tab shift-tab enter");
assert_eq!(focused_stop(&workbench, cx), Some((0, Some(Verbosity(-1)))), "the disabled - does nothing");
cx.simulate_keystrokes("shift-tab enter");
cx.run_until_parked();
assert_eq!(focused_stop(&workbench, cx), Some((0, None)), "+ focuses its part");
let request = json!({ "verbosityRequest": { "verbosityDelta": 1, "previousHover": { "id": 0 } } });
assert_eq!(answer_hovers(&messages, json!({ "id": 1, "contents": contents, "range": range }), cx), [request]);
cx.simulate_keystrokes("tab tab enter");
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_none()), "the link runs editor.action.hideHover");
std::fs::remove_dir_all(dir).unwrap();
}
/// contentHoverWidgetWrapper.ts `focus`: Show or Focus Hover on a hover of one part focuses that part.
#[gpui::test]
fn focusing_a_hover_of_one_part_focuses_the_part(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-one-part");
run_show_hover(&workbench, &messages, vec![], cx);
run_show_hover(&workbench, &messages, vec![], cx);
assert_eq!(focused_part(&workbench, cx), Some(0));
assert_eq!(focus_keys(&workbench, cx), [true, true, false]);
std::fs::remove_dir_all(dir).unwrap();
}
/// contentHoverRendered.ts: every part is focusable after the container, Tab and Shift+Tab move through them and the
/// verbosity actions and copy button inside each (DOM order), and the verbosity actions act on the focused part
/// (`focusedHoverPartIndex`); a click on + focuses its part.
#[gpui::test]
fn the_verbosity_actions_use_the_focused_part(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-parts");
workbench.update(cx, |workbench, _| workbench.language_features.register("$registerHoverProvider", vec![json!(4), json!("*")]));
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
let hover = json!({ "id": 0, "contents": [{ "value": "short" }], "range": range, "canIncreaseVerbosity": true });
let show = |cx: &mut gpui::VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", vec![], window, cx));
cx.run_until_parked();
answer_hover_handles(&messages, hover.clone(), cx)
};
assert_eq!(show(cx).len(), 2, "both providers are asked");
show(cx);
assert_eq!(focused_part(&workbench, cx), None, "a hover of two parts focuses its container");
assert_eq!(focus_keys(&workbench, cx), [true, true, false]);
let mut moves = Vec::new();
for keys in ["tab"; 9].into_iter().chain(["shift-tab"; 9]) {
cx.simulate_keystrokes(keys);
moves.push(focused_stop(&workbench, cx));
}
use PartStop::{Copy, Verbosity};
let part = |index: usize| [Some((index, None)), Some((index, Some(Verbosity(1)))), Some((index, Some(Verbosity(-1)))), Some((index, Some(Copy)))];
let parts: Vec<_> = part(0).into_iter().chain(part(1)).collect();
// Tab past the last element leaves the hover for the stop after the editor; Shift+Tab comes back in at its end.
let forward: Vec<_> = parts.iter().copied().chain([None]).collect();
let backward: Vec<_> = parts.iter().rev().copied().chain([None]).collect();
assert_eq!(moves, [forward, backward].concat());
cx.simulate_keystrokes("tab tab tab tab tab");
assert_eq!(focused_part(&workbench, cx), Some(1));
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.increaseHoverVerbosityLevel", vec![], window, cx));
cx.run_until_parked();
assert_eq!(answer_hover_handles(&messages, hover.clone(), cx), [rendered_part_handle(&workbench, 1, cx)]);
let plus = cx.debug_bounds("content-hover-verbosity-0-1").expect("+ draws").center();
cx.simulate_click(plus, gpui::Modifiers::none());
cx.run_until_parked();
assert_eq!(focused_part(&workbench, cx), Some(0), "the click focuses the part of its +");
assert_eq!(answer_hover_handles(&messages, hover, cx), [rendered_part_handle(&workbench, 0, cx)]);
std::fs::remove_dir_all(dir).unwrap();
}
/// hoverActions.ts scroll actions on a focused hover (default-macos.json `when: editorHoverFocused`): a line,
/// a page, the ends, and nothing past them; Left and Right scroll a hover that does not overflow across not at all.
#[gpui::test]
fn the_keys_scroll_a_focused_hover(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "focus-scroll");
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", vec![json!({ "focus": true })], window, cx));
cx.run_until_parked();
let long = (0..80).map(|line| format!("line {line}")).collect::<Vec<_>>().join("\n\n");
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
answer_hovers(&messages, json!({ "contents": [{ "value": long }], "range": range }), cx);
let (height, max) = workbench.read_with(cx, |workbench, _| {
let scroll = &workbench.content_hover.scroll;
(f32::from(scroll.bounds().size.height), f32::from(scroll.max_offset().y))
});
assert!(max > 2. * height, "the hover overflows: {max} past {height}");
assert!(workbench.read_with(cx, |workbench, _| workbench.scrollable_drawn("content-hover-contents")), "content-hover-contents sits in a ScrollableElement");
let keybindings = dir.join("User/keybindings.json");
workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), keybindings));
let mut tops = Vec::new();
for keys in ["down", "pagedown", "right", "end", "up", "home", "up", "left"] {
cx.simulate_keystrokes(keys);
let offset = workbench.read_with(cx, |workbench, _| workbench.content_hover.scroll.offset());
tops.push((-f32::from(offset.x), -f32::from(offset.y)));
}
let line = crate::editor::LINE_HEIGHT;
assert_eq!(tops, [(0., line), (0., line + height), (0., line + height), (0., max), (0., max - line), (0., 0.), (0., 0.), (0., 0.)]);
std::fs::remove_dir_all(dir).unwrap();
}
/// Two providers' parts of one verbosity-capable hover, with the hover's container focused.
fn focused_two_part_hover(workbench: &gpui::Entity<Workbench>, messages: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, cx: &mut gpui::VisualTestContext) -> Value {
workbench.update(cx, |workbench, _| workbench.language_features.register("$registerHoverProvider", vec![json!(4), json!("*")]));
let range = json!({ "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 5 });
let hover = json!({ "id": 0, "contents": [{ "value": "short" }], "range": range, "canIncreaseVerbosity": true });
for _ in 0..2 {
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.showHover", vec![], window, cx));
cx.run_until_parked();
answer_hover_handles(messages, hover.clone(), cx);
}
assert_eq!(focused_part(workbench, cx), None);
hover
}
fn run_command(workbench: &gpui::Entity<Workbench>, command: &str, cx: &mut gpui::VisualTestContext) {
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command(command, vec![], window, cx));
cx.update(|window, _| window.refresh());
cx.run_until_parked();
}
fn accessible_view(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext) -> Option<(&'static str, bool, Vec<String>, Vec<(String, bool)>)> {
workbench.update_in(cx, |workbench, window, _| workbench.accessible_view_state(window))
}
/// The toolbar's verbosity actions: (enabled of Increase, enabled of Decrease) and Increase's index.
fn verbosity_actions(toolbar: &[(String, bool)]) -> ((bool, bool), usize) {
let find = |title: &str| toolbar.iter().position(|(label, _)| label.starts_with(title)).expect("the toolbar has the action");
let (increase, decrease) = (find("Increase Hover Verbosity"), find("Decrease Hover Verbosity"));
((toolbar[increase].1, toolbar[decrease].1), increase)
}
/// hoverAccessibleViews.ts `HoverAccessibleView`: Alt+F2 in a focused part reads that part, its toolbar runs the
/// part's verbosity actions the part supports, the view follows the hover's new contents, the mouse leaves the hover
/// alone while the view shows, and Escape focuses the part again.
#[gpui::test]
fn the_accessible_view_reads_the_focused_hover_part(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "accessible-part");
workbench.update(cx, |workbench, _| workbench.update_user_setting("editor.hover.sticky", json!(false)));
let hover = focused_two_part_hover(&workbench, &messages, cx);
// The first part, its +, - and copy button, then the second part.
cx.simulate_keystrokes("tab tab tab tab tab");
assert_eq!(focused_part(&workbench, cx), Some(1));
run_command(&workbench, "editor.action.accessibleView", cx);
let (provider, help, lines, toolbar) = accessible_view(&workbench, cx).expect("the view shows");
assert_eq!((provider, help, lines.as_slice()), ("hover", false, ["short".to_owned()].as_slice()));
let (enabled, increase) = verbosity_actions(&toolbar);
assert_eq!(enabled, (true, false), "the part can grow, not shrink");
let id = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().model_id);
let bounds = cx.debug_bounds(format!("text-area-{id}").leak()).unwrap();
cx.simulate_mouse_move(bounds.origin + point(bounds.size.width / 2., bounds.size.height - gpui::px(20.)), None, gpui::Modifiers::none());
cx.executor().advance_clock(Duration::from_millis(1000));
cx.simulate_mouse_move(bounds.origin - point(gpui::px(0.), gpui::px(10.)), None, gpui::Modifiers::none());
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.content_hover.shown.is_some()), "shouldKeepOpenOnEditorMouseMoveOrLeave");
let action = cx.debug_bounds(format!("accessible-view-action-{increase}").leak()).expect("the action draws").center();
cx.simulate_click(action, gpui::Modifiers::none());
cx.run_until_parked();
let longer = json!({ "id": 1, "contents": [{ "value": "short and long" }], "range": hover["range"], "canDecreaseVerbosity": true });
assert_eq!(answer_hover_handles(&messages, longer, cx), [rendered_part_handle(&workbench, 1, cx)]);
let (_, _, lines, toolbar) = accessible_view(&workbench, cx).expect("the view stays");
assert_eq!((lines, verbosity_actions(&toolbar).0), (vec!["short and long".to_owned()], (false, true)));
cx.simulate_keystrokes("escape");
assert!(accessible_view(&workbench, cx).is_none());
assert_eq!(focused_part(&workbench, cx), Some(1));
std::fs::remove_dir_all(dir).unwrap();
}
/// `HoverAccessibilityHelpProvider`: the focused part's verbosity actions before its text; with the container
/// focused the whole hover, a blank line between parts, whose view has no part to run verbosity on.
#[gpui::test]
fn the_hover_help_lists_the_focused_parts_verbosity_actions(cx: &mut TestAppContext) {
let (workbench, cx, dir, messages) = open_with_provider(cx, "accessible-help");
focused_two_part_hover(&workbench, &messages, cx);
run_command(&workbench, "editor.action.accessibleView", cx);
let (_, _, lines, toolbar) = accessible_view(&workbench, cx).expect("the view shows");
assert_eq!(lines, ["short", "", "short"]);
assert_eq!(verbosity_actions(&toolbar).0, (false, false));
cx.simulate_keystrokes("escape");
assert_eq!(focus_keys(&workbench, cx), [true, true, false], "Escape focuses the hover");
assert_eq!(focused_part(&workbench, cx), None);
cx.simulate_keystrokes("tab");
run_command(&workbench, "editor.action.accessibilityHelp", cx);
let (provider, help, lines, _) = accessible_view(&workbench, cx).expect("the help shows");
assert_eq!((provider, help), ("hover", true));
let increase = lines.iter().position(|line| line == "- The focused hover part verbosity level can be increased with the Increase Hover Verbosity command.").expect("the increase line");
assert_eq!(lines[increase + 1], "short", "after the screen reader hint, the actions, then the part");
assert!(!lines.iter().any(|line| line.contains("can be decreased")), "{lines:#?}");
std::fs::remove_dir_all(dir).unwrap();
}
/// `ExtHoverAccessibleView`: Alt+F2 with a workbench hover shown reads it in place of the hover, Escape shows
/// the hover again with the focus in it (`showAndFocusLastHover`), and Escape there hides it.
#[gpui::test]
fn the_accessible_view_reads_a_workbench_hover(cx: &mut TestAppContext) {
let (workbench, cx, dir, _) = open(cx, "accessible-workbench-hover");
workbench.update_in(cx, |workbench, window, cx| {
let bounds = Bounds { origin: point(gpui::px(100.), gpui::px(100.)), size: size(gpui::px(50.), gpui::px(20.)) };
workbench.show_managed_hover("target", crate::workbench::hover::HoverContent::Markdown(serde_json::json!({ "value": "Some [docs](https://example.com)" })), crate::workbench::hover::HoverOptions::instant(), bounds, window, cx);
});
run_command(&workbench, "editor.action.accessibleView", cx);
let (provider, help, lines, _) = accessible_view(&workbench, cx).expect("the view shows");
assert_eq!((provider, help, lines.as_slice()), ("hover", false, ["Some docs".to_owned()].as_slice()));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned)), None, "the view takes the hover's place");
cx.simulate_keystrokes("escape");
assert!(accessible_view(&workbench, cx).is_none());
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned)).as_deref(), Some("Some [docs](https://example.com)"));
assert!(workbench.update_in(cx, |workbench, window, _| workbench.workbench_hover_focus.is_focused(window)), "the hover takes the focus");
assert_eq!(focus_keys(&workbench, cx), [false, false, false]);
// With Escape bound, the hover's own keydown listener still hides it.
std::fs::write(dir.join("keybindings.json"), r#"[{ "key": "escape", "command": "notifications.hideToasts" }]"#).unwrap();
workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json")));
cx.simulate_keystrokes("escape");
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned)), None);
assert!(accessible_view(&workbench, cx).is_none());
assert!(workbench.update_in(cx, |_, window, cx| window.focused(cx).is_none()), "no element before the hover to go back to");
std::fs::remove_dir_all(dir).unwrap();
}
/// `workbench.action.showHover` in the accessible view's toolbar: the focused action's managed hover, focused with
/// trapFocus; Tab stays in it and Escape gives the focus back to the toolbar.
#[gpui::test]
fn show_hover_focuses_the_accessible_view_toolbar_actions_hover(cx: &mut TestAppContext) {
let (workbench, cx, dir, _) = open(cx, "accessible-view-show-hover");
workbench.update_in(cx, |workbench, window, cx| {
let bounds = Bounds { origin: point(gpui::px(100.), gpui::px(100.)), size: size(gpui::px(50.), gpui::px(20.)) };
workbench.show_managed_hover("target", crate::workbench::hover::HoverContent::Text("Some docs".into()), crate::workbench::hover::HoverOptions::instant(), bounds, window, cx);
});
run_command(&workbench, "editor.action.accessibleView", cx);
let (_, _, _, toolbar) = accessible_view(&workbench, cx).expect("the view shows");
cx.simulate_keystrokes("shift-tab");
let state = |cx: &mut gpui::VisualTestContext| {
workbench.update_in(cx, |workbench, window, _| (workbench.hovers.shown_text().map(str::to_owned), workbench.workbench_hover_focus.is_focused(window), workbench.accessibility.view.toolbar_focus.is_focused(window)))
};
assert_eq!(state(cx), (None, false, true));
run_command(&workbench, "workbench.action.showHover", cx);
assert_eq!(state(cx), (Some(toolbar[0].0.clone()), true, false));
cx.simulate_keystrokes("tab");
assert_eq!(state(cx), (Some(toolbar[0].0.clone()), true, false), "trapFocus keeps Tab in the hover");
cx.simulate_keystrokes("escape");
assert_eq!(state(cx), (None, false, true));
assert!(accessible_view(&workbench, cx).is_some());
std::fs::remove_dir_all(dir).unwrap();
}