Skip to content

Visual Studio Code, rebuilt in Rust

Rust
29.1 KB
Raw Blame
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use config::registry::Registry;
use config::service::Settings;
use exthost::scan::scan_extension;
use gpui::{TestAppContext, VisualTestContext};

use super::*;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;

#[test]
fn quick_suggestions_read_bools_and_kinds() {
    assert!(quick_suggestions_all_off(&json!(false)));
    assert!(quick_suggestions_all_on(&json!(true)));
    let default = json!({ "other": "on", "comments": "off", "strings": "off" });
    assert!(!quick_suggestions_all_off(&default) && !quick_suggestions_all_on(&default));
    assert_eq!(quick_suggestions_value(&default, "strings"), "off");
    // `validate`: a string applies to every kind, a missing kind takes its default.
    assert_eq!(quick_suggestions_value(&json!("offWhenInlineCompletions"), "comments"), "offWhenInlineCompletions");
    assert_eq!(quick_suggestions_value(&json!({ "comments": "on" }), "other"), "offWhenInlineCompletions");
    assert_eq!(quick_suggestions_value(&json!({ "comments": "on" }), "strings"), "off");
}

#[test]
fn line_words_split_at_the_word_definition() {
    let words = |pattern: &onig::Regex, line: &str| pattern_words(pattern, line).into_iter().map(|word| line.chars().skip(word.start).take(word.len()).collect::<String>()).collect::<Vec<_>>();
    let languages = Languages::new(&[]);
    assert_eq!(words(word_definition(&languages, "plaintext"), "foo.bar(baz, 12)"), ["foo", "bar", "baz", "12"]);
    // `_wordenize` stops at the first empty match.
    assert_eq!(words(&onig::Regex::new("[a-z]*").unwrap(), "ab cd"), ["ab"]);
}

/// A folder with `a.txt` holding `text`, open and focused at its end.
fn open<'a>(cx: &'a mut TestAppContext, text: &str) -> (gpui::Entity<Workbench>, &'a mut 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();
    static OPENED: AtomicUsize = AtomicUsize::new(0);
    let dir = std::env::temp_dir().join(format!("code-gpui-suggest-{}-{}", std::process::id(), OPENED.fetch_add(1, Ordering::Relaxed)));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.txt"), text).unwrap();
    let workspace = config::workspace::Workspace::folder(dir.clone());
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), Some(workspace.clone()))));
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), Some(workspace), Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.watch_editor_focus(window, cx);
        workbench.open_file(dir.join("a.txt"), true, window, cx);
        window.focus(&workbench.editor_focus, cx);
        workbench
    });
    cx.update(|window, _| window.activate_window());
    cx.run_until_parked();
    run(&workbench, cx, "cursorBottom");
    (workbench, cx)
}

fn run(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, command: &str) {
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command(command, vec![], window, cx));
    cx.run_until_parked();
}

fn type_text(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, text: &str) {
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("type", vec![json!({ "text": text })], window, cx));
    cx.executor().advance_clock(Duration::from_millis(20));
    cx.run_until_parked();
}

fn shown(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<String> {
    workbench.read_with(cx, |workbench, _| match workbench.suggest_widget_visible() {
        true => workbench.suggest.session.as_ref().and_then(|session| session.model.as_ref()).map(|model| model.filtered().iter().map(|item| item.label.clone()).collect()).unwrap_or_default(),
        false => Vec::new(),
    })
}

fn text(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> String {
    workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().lines.join("\n"))
}

/// contentWidgets.ts `_layoutHorizontalSegmentInPage` clamps the width `beforeRender` gives: the list's, its borders
/// and the 14px horizontal padding, so near the window's right edge the widget ends 15px plus 14px before it.
#[gpui::test]
fn near_the_right_edge_the_widget_keeps_its_padding_from_the_window(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, &format!("foo fob {}\n", "a".repeat(400)));
    run(&workbench, cx, "cursorUp");
    run(&workbench, cx, "cursorEnd");
    type_text(&workbench, cx, " f");
    assert_eq!(shown(&workbench, cx), ["fob", "foo"]);
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let widget = cx.debug_bounds("suggest-widget").expect("the widget draws");
    let window_width = cx.update(|window, _| f32::from(window.viewport_size().width));
    assert_eq!(f32::from(widget.right()), window_width - 15. - 14.);
}

/// suggestModel.ts `_onCursorChange` sees every cursor change: typing over a line the gutter selected suggests.
#[gpui::test]
fn typing_over_a_line_the_gutter_selected_suggests(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "foo fob bar\nbaz\nqux\n");
    workbench.update(cx, |workbench, cx| workbench.gutter_line_select(1, gpui::Modifiers::none(), false, true, cx));
    type_text(&workbench, cx, "f");
    assert_eq!(shown(&workbench, cx), ["fob", "foo"]);
}

/// Typing a word start shows the other words of the document (the word based provider) and filters as it goes.
#[gpui::test]
fn typing_shows_the_document_words_and_filters_them(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "foo fob bar\n");
    type_text(&workbench, cx, "f");
    assert_eq!(shown(&workbench, cx), ["fob", "foo"]);
    type_text(&workbench, cx, "oo");
    assert_eq!(shown(&workbench, cx), ["foo"]);
    run(&workbench, cx, "hideSuggestWidget");
    assert!(shown(&workbench, cx).is_empty());
}

/// editorWorkerService.ts `WordBasedCompletionItemProvider` reads the words of `modelService.getModels()`: a file of
/// the same language shown only in another group gives its words.
#[gpui::test]
fn word_suggestions_take_the_words_of_a_file_in_another_group(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "fable\n");
    crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.editor_focus, cx));
    type_text(&workbench, cx, "f");
    run(&workbench, cx, "editor.action.triggerSuggest");
    cx.executor().advance_clock(Duration::from_millis(20));
    cx.run_until_parked();
    assert_eq!(shown(&workbench, cx), ["fable"]);
}

/// selectNextSuggestion moves the focus; acceptSelectedSuggestion replaces the typed word with the item.
#[gpui::test]
fn accepting_replaces_the_typed_prefix(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "foo fob bar\n");
    type_text(&workbench, cx, "f");
    run(&workbench, cx, "selectNextSuggestion");
    run(&workbench, cx, "acceptSelectedSuggestion");
    assert_eq!(text(&workbench, cx), "foo fob bar\nfoo");
    assert!(shown(&workbench, cx).is_empty());
}

fn insert_snippet(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, template: &str) {
    workbench.update(cx, |workbench, cx| {
        let head = workbench.editors.active().unwrap().selection().head;
        let snippets = [(head, head, template, false)];
        workbench.insert_snippets(SnippetInsert { snippets: &snippets, clipboard: None, undo_stop_before: true, undo_stop_after: true, reason: "snippet" }, cx);
    });
    cx.run_until_parked();
}

fn in_snippet(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> bool {
    workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().snippet_session.is_some())
}

/// snippetController2.test.ts: typing replaces the placeholder, Tab goes to the next one, the final tab stop ends
/// the session.
#[gpui::test]
fn tab_moves_through_the_placeholders_and_the_final_one_ends_the_session(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "");
    insert_snippet(&workbench, cx, "f(${1:x}, ${2:y})$0;");
    assert!(in_snippet(&workbench, cx));
    type_text(&workbench, cx, "ab");
    run(&workbench, cx, "jumpToNextSnippetPlaceholder");
    type_text(&workbench, cx, "c");
    assert_eq!(text(&workbench, cx), "f(ab, c);");
    run(&workbench, cx, "jumpToPrevSnippetPlaceholder");
    let selection = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selection());
    assert_eq!((selection.start().column, selection.end().column), (2, 4));
    run(&workbench, cx, "jumpToNextSnippetPlaceholder");
    run(&workbench, cx, "jumpToNextSnippetPlaceholder");
    assert!(!in_snippet(&workbench, cx));
    let head = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selection().head);
    assert_eq!(head.column, 8);
}

/// Escape (`leaveSnippet`) ends the session; a choice placeholder shows its options in the suggest widget.
#[gpui::test]
fn a_choice_shows_its_options_and_escape_leaves(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "");
    insert_snippet(&workbench, cx, "${1|one,two|} $2");
    assert_eq!(shown(&workbench, cx), ["one", "two"]);
    run(&workbench, cx, "selectNextSuggestion");
    run(&workbench, cx, "acceptSelectedSuggestion");
    assert_eq!(text(&workbench, cx), "two ");
    assert!(in_snippet(&workbench, cx));
    run(&workbench, cx, "leaveSnippet");
    assert!(!in_snippet(&workbench, cx));
}

/// A manual trigger with no word shows every word; a cursor move off the line ends the session.
#[gpui::test]
fn a_manual_trigger_lists_every_word_and_a_move_off_the_line_cancels(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "foo bar\n");
    run(&workbench, cx, "editor.action.triggerSuggest");
    assert_eq!(shown(&workbench, cx), ["bar", "foo"]);
    run(&workbench, cx, "cursorUp");
    assert!(shown(&workbench, cx).is_empty());
}

/// snippetsService.ts: a user `plaintext.json` snippet shows beside the words and inserts as a snippet.
#[gpui::test]
fn user_snippets_show_and_insert_as_snippets(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "");
    let folder = workbench.read_with(cx, |workbench, _| workbench.settings.lock().unwrap().user_home().join("snippets"));
    std::fs::create_dir_all(&folder).unwrap();
    std::fs::write(folder.join("plaintext.json"), r#"{ "Greet": { "prefix": "hello", "body": "hello ${1:name}", "description": "Say hello" } }"#).unwrap();
    type_text(&workbench, cx, "he");
    assert_eq!(shown(&workbench, cx), ["hello"]);
    run(&workbench, cx, "acceptSelectedSuggestion");
    assert_eq!(text(&workbench, cx), "hello name");
    assert!(in_snippet(&workbench, cx));
}

/// suggest.ts `_executeCompletionItemProvider` asks the snippet support beside the providers and sorts the items as
/// `SnippetSortOrder.Bottom`: sort text, then label, snippets last.
#[gpui::test]
fn execute_completion_item_provider_adds_the_snippets_last(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "zebra apple he");
    let folder = workbench.read_with(cx, |workbench, _| workbench.settings.lock().unwrap().user_home().join("snippets"));
    std::fs::create_dir_all(&folder).unwrap();
    std::fs::write(folder.join("plaintext.json"), r#"{ "Greet": { "prefix": "hello", "body": "hello ${1:name}" } }"#).unwrap();
    let uri = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().uri());
    let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("_executeCompletionItemProvider", vec![uri, json!({ "lineNumber": 1, "column": 15 })], window, cx));
    cx.run_until_parked();
    let crate::commands::Outcome::Pending(mut result) = outcome else { panic!("the providers answer later") };
    let list = result.try_recv().unwrap().unwrap().unwrap();
    let labels: Vec<&str> = list["suggestions"].as_array().unwrap().iter().map(|item| item["label"].as_str().or(item["label"]["label"].as_str()).unwrap()).collect();
    assert_eq!(labels, ["apple", "zebra", "hello"]);
}

/// suggestMemory.ts `LRUMemory`: with `editor.suggestSelection: recentlyUsed` the item accepted last is focused the
/// next time it is among the top-scored ones, and the memory is stored in the workspace's storage.
#[gpui::test]
fn recently_used_focuses_the_last_accepted_item(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "foo fob bar\n");
    workbench.update(cx, |workbench, _| _ = workbench.settings.lock().unwrap().update_value("editor.suggestSelection", Some(&json!("recentlyUsed")), config::service::Target::User, None, &[]).unwrap());
    let focused = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.suggest.widget.focused);
    type_text(&workbench, cx, "f");
    assert_eq!((shown(&workbench, cx), focused(cx)), (vec!["fob".to_owned(), "foo".to_owned()], Some(0)));
    run(&workbench, cx, "selectNextSuggestion");
    run(&workbench, cx, "acceptSelectedSuggestion");
    type_text(&workbench, cx, " f");
    assert_eq!((shown(&workbench, cx), focused(cx)), (vec!["fob".to_owned(), "foo".to_owned()], Some(1)));
    cx.executor().advance_clock(Duration::from_millis(500));
    cx.run_until_parked();
    let stored = workbench.read_with(cx, |workbench, _| workbench.workspace_storage.lock().unwrap().get("suggest/memories/recentlyUsed").map(str::to_owned));
    assert_eq!(serde_json::from_str::<Value>(&stored.unwrap()).unwrap()[0][0], "plaintext/foo");
}

/// suggestWidgetStatus.ts: `editor.suggest.showStatusBar` adds a row under the list with the
/// `suggestWidgetStatusbarMenu` actions that hold for the focused item.
#[gpui::test]
fn the_status_bar_shows_the_actions_of_the_focused_item(cx: &mut TestAppContext) {
    let (workbench, cx) = open(cx, "foo fob bar\n");
    workbench.update(cx, |workbench, _| _ = workbench.settings.lock().unwrap().update_value("editor.suggest.showStatusBar", Some(&json!(true)), config::service::Target::User, None, &[]).unwrap());
    type_text(&workbench, cx, "f");
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let widget = cx.debug_bounds("suggest-widget").expect("the widget draws");
    let status_bar = cx.debug_bounds("suggest-status-bar").expect("the status bar draws");
    assert_eq!(f32::from(widget.size.height), 3. * crate::editor::LINE_HEIGHT + 2.);
    assert_eq!(f32::from(status_bar.bottom()), f32::from(widget.bottom()) - 1.);
    let titles = workbench.update_in(cx, |workbench, window, _| {
        let actions = crate::menus::menu_actions(&workbench.menus, crate::menus::MenuId::SuggestWidgetStatusBar, &workbench.key_context(window));
        actions.into_iter().filter_map(|action| if let crate::menus::MenuAction::Command { title, .. } = action { Some(title) } else { None }).collect::<Vec<_>>()
    });
    assert_eq!(titles, ["Insert", "Show More"]);
}

/// A document whose last line is `words`, with the cursor on the line after it at the bottom of a `width` by 500
/// window, so the suggest list draws above the line.
fn open_at_the_bottom<'a>(cx: &'a mut TestAppContext, words: &str, width: f32) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext) {
    let (workbench, cx) = open(cx, &format!("{}{words}\n", "\n".repeat(60)));
    cx.simulate_resize(gpui::size(gpui::px(width), gpui::px(500.)));
    run(&workbench, cx, "cursorTop");
    run(&workbench, cx, "cursorBottom");
    (workbench, cx)
}

/// Shows the details of the first item with `detail` and `documentation`, and returns the list and the details.
fn show_details(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, detail: &str, documentation: &str) -> (gpui::Bounds<gpui::Pixels>, gpui::Bounds<gpui::Pixels>) {
    workbench.update(cx, |workbench, _| {
        let model = workbench.suggest.session.as_mut().and_then(|session| session.model.as_mut()).unwrap();
        let item = model.item_mut(0).unwrap();
        item.detail = Some(detail.to_owned());
        item.documentation = if documentation.is_empty() { Value::Null } else { json!(documentation) };
        workbench.suggest.widget.details = true;
        workbench.suggest.widget.focused = Some(0);
    });
    drawn_details(cx)
}

/// Two frames: the first measures the details, the second places them (the test platform runs no `on_next_frame`).
fn drawn_details(cx: &mut VisualTestContext) -> (gpui::Bounds<gpui::Pixels>, gpui::Bounds<gpui::Pixels>) {
    for _ in 0..2 {
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
    }
    (cx.debug_bounds("suggest-widget").expect("the widget draws"), cx.debug_bounds("suggest-details").expect("the details draw"))
}

/// suggestWidgetDetails.ts `_placeAtAnchor`: with no room east or west of a list drawn above the line, the details
/// go north of it, their bottom a border below the list's top, as wide as the list inside its borders.
#[gpui::test]
fn details_go_north_of_a_list_above_the_line(cx: &mut TestAppContext) {
    let words: Vec<String> = ('a'..='t').map(|c| format!("f{c}")).collect();
    let (workbench, cx) = open_at_the_bottom(cx, &words.join(" "), 600.);
    type_text(&workbench, cx, "f");
    let (widget, details) = show_details(&workbench, cx, "a detail", &"documentation ".repeat(10));
    assert!(cx.debug_bounds("suggest-sash-n").is_some(), "the list is above the line");
    assert_eq!(f32::from(details.bottom()), f32::from(widget.top()) + 1.);
    assert_eq!((details.left(), details.size.width), (widget.left(), widget.size.width - gpui::px(2.)));
    assert!(cx.debug_bounds("suggest-details-sash-n").is_some() && cx.debug_bounds("suggest-details-sash-w").is_some());
}

/// `_placeAtAnchor`: east of a list above the line, details taller than the list rise from its bottom (less the
/// two borders) and get the north sash.
#[gpui::test]
fn details_beside_a_list_above_the_line_align_at_its_bottom(cx: &mut TestAppContext) {
    let words: Vec<String> = ('a'..='t').map(|c| format!("f{c}")).collect();
    let (workbench, cx) = open_at_the_bottom(cx, &words.join(" "), 1600.);
    type_text(&workbench, cx, "f");
    let (widget, details) = show_details(&workbench, cx, "a detail", &"documentation ".repeat(60));
    assert!(cx.debug_bounds("suggest-sash-n").is_some(), "the list is above the line");
    assert!(details.size.height > widget.size.height, "{details:?} {widget:?}");
    assert_eq!(f32::from(details.left()), f32::from(widget.right()) - 1.);
    assert_eq!(f32::from(details.bottom()), f32::from(widget.bottom()) - 2.);
    assert!(cx.debug_bounds("suggest-details-sash-n").is_some() && cx.debug_bounds("suggest-details-sash-s").is_none());
}

/// SuggestDetailsOverlay: the east sash widens the details east of a list below the line; the size holds while the
/// session lasts (`_userSize`) and is forgotten when the widget hides (`hide(sessionEnded)`).
#[gpui::test]
fn the_details_east_sash_resizes_them_for_the_session(cx: &mut TestAppContext) {
    use gpui::{Modifiers, MouseButton};
    let (workbench, cx) = open(cx, "foo fob\n");
    cx.simulate_resize(gpui::size(gpui::px(1600.), gpui::px(700.)));
    type_text(&workbench, cx, "f");
    let (_, details) = show_details(&workbench, cx, "a detail", "");
    assert_eq!(f32::from(details.size.width), 330.);
    let sash = cx.debug_bounds("suggest-details-sash-e").expect("the east sash draws").center();
    let target = gpui::point(sash.x + gpui::px(50.), sash.y);
    cx.simulate_mouse_move(sash, None, Modifiers::none());
    let hovered = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.suggest.widget.hovered_sash);
    assert_eq!(hovered(cx), None);
    cx.executor().advance_clock(Duration::from_millis(300));
    cx.run_until_parked();
    assert_eq!(hovered(cx), Some(("details", 1)), "sash.hoverBorder after workbench.sash.hoverDelay");
    cx.simulate_mouse_down(sash, MouseButton::Left, Modifiers::none());
    cx.simulate_mouse_move(target, Some(MouseButton::Left), Modifiers::none());
    cx.simulate_mouse_up(target, MouseButton::Left, Modifiers::none());
    assert_eq!(f32::from(drawn_details(cx).1.size.width), 380.);
    run(&workbench, cx, "selectNextSuggestion");
    run(&workbench, cx, "selectPrevSuggestion");
    assert_eq!(f32::from(drawn_details(cx).1.size.width), 380.);
    run(&workbench, cx, "hideSuggestWidget");
    type_text(&workbench, cx, " f");
    let (_, details) = show_details(&workbench, cx, "a detail", "");
    assert_eq!(f32::from(details.size.width), 330.);
}

/// suggestWidget.ts: the south sash resizes the list below the line, the height is persisted for the profile and
/// used on the next show, the untouched width keeps its default; Reset Suggest Widget Size forgets it.
#[gpui::test]
fn the_south_sash_resizes_and_persists_the_height(cx: &mut TestAppContext) {
    use gpui::{Modifiers, MouseButton};
    let words: Vec<String> = ('a'..='t').map(|c| format!("f{c}")).collect();
    let (workbench, cx) = open(cx, &format!("{}\n", words.join(" ")));
    let line_height = crate::editor::LINE_HEIGHT;
    let height = |cx: &mut VisualTestContext| {
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
        f32::from(cx.debug_bounds("suggest-widget").expect("the widget draws").size.height)
    };
    type_text(&workbench, cx, "f");
    assert_eq!(height(cx), 12. * line_height + 2.);
    let sash = cx.debug_bounds("suggest-sash-s").expect("the south sash draws").center();
    let target = gpui::point(sash.x, sash.y - gpui::px(3. * line_height));
    cx.simulate_mouse_down(sash, MouseButton::Left, Modifiers::none());
    cx.simulate_mouse_move(target, Some(MouseButton::Left), Modifiers::none());
    cx.simulate_mouse_up(target, MouseButton::Left, Modifiers::none());
    assert_eq!(height(cx), 9. * line_height + 2.);
    let stored = workbench.read_with(cx, |workbench, _| workbench.profile_storage.lock().unwrap().get("suggestWidget.size/vs.editor.ICodeEditor/false").map(str::to_owned));
    assert_eq!(serde_json::from_str::<Value>(&stored.unwrap()).unwrap(), json!({ "width": 430., "height": 9. * line_height }));
    run(&workbench, cx, "hideSuggestWidget");
    type_text(&workbench, cx, " f");
    assert_eq!(height(cx), 9. * line_height + 2.);
    run(&workbench, cx, "hideSuggestWidget");
    run(&workbench, cx, "editor.action.resetSuggestSize");
    type_text(&workbench, cx, " f");
    assert_eq!(height(cx), 12. * line_height + 2.);
}

/// suggestController.test.ts "resolve additionalTextEdits async when needed": `a.txt` holding `text` with the cursor
/// at `cursor`, one completion provider that resolves, and its `let` item inserting `hello` accepted.
fn accept_unresolved<'a>(cx: &'a mut TestAppContext, name: &str, text: &str, cursor: Position) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, std::sync::mpsc::Receiver<crate::host_sync::HostMessage>) {
    let (workbench, cx, receiver, _) = crate::workbench::goto_symbol::tests::open(cx, name, text);
    workbench.update(cx, |workbench, _| {
        workbench.language_features.register("$registerCompletionsProvider", vec![json!(5), json!("*"), json!([]), json!(true)]);
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(cursor)]);
    });
    run(&workbench, cx, "editor.action.triggerSuggest");
    cx.executor().advance_clock(Duration::from_millis(100));
    cx.run_until_parked();
    let (line, column) = (cursor.line + 1, cursor.column + 1);
    let at = json!({ "startLineNumber": line, "startColumn": column, "endLineNumber": line, "endColumn": column });
    for message in receiver.try_iter().filter(|message| message.method == "$provideCompletionItems") {
        let list = json!({ "a": at, "b": [{ "a": "let", "b": crate::suggest::KIND_TEXT, "h": "hello", "j": at, "x": [1, 0] }], "x": 1 });
        _ = message.reply.expect("a call").send(Ok(list));
    }
    cx.run_until_parked();
    assert_eq!(shown(&workbench, cx), ["let"]);
    run(&workbench, cx, "acceptSelectedSuggestion");
    (workbench, cx, receiver)
}

/// Answers every `$resolveCompletionItem` call with `I came late` inserted at `at`.
fn resolve_late(receiver: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, at: Position, cx: &mut VisualTestContext) {
    let (line, column) = (at.line + 1, at.column + 1);
    let edit = json!({ "text": "I came late", "range": { "startLineNumber": line, "startColumn": column, "endLineNumber": line, "endColumn": column } });
    for message in receiver.try_iter().filter(|message| message.method == "$resolveCompletionItem") {
        _ = message.reply.expect("a call").send(Ok(json!({ "a": "let", "h": "hello", "l": [edit] })));
    }
    cx.run_until_parked();
}

fn head(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Position {
    workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selection().head)
}

#[gpui::test]
fn resolve_additional_text_edits_async_when_needed(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = accept_unresolved(cx, "suggest-async", "hello\nhallo", Position::new(1, 5));
    assert_eq!(text(&workbench, cx), "hello\nhallohello");
    resolve_late(&receiver, Position::new(0, 0), cx);
    assert_eq!(text(&workbench, cx), "I came latehello\nhallohello");
    run(&workbench, cx, "undo");
    assert_eq!(text(&workbench, cx), "hello\nhallo");
}

#[gpui::test]
fn resolve_additional_text_edits_async_when_needed_typing(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = accept_unresolved(cx, "suggest-async-typing", "hello\nhallo", Position::new(1, 5));
    assert_eq!(head(&workbench, cx), Position::new(1, 10));
    type_text(&workbench, cx, "TYPING");
    assert_eq!(text(&workbench, cx), "hello\nhallohelloTYPING");
    resolve_late(&receiver, Position::new(0, 0), cx);
    assert_eq!(text(&workbench, cx), "I came latehello\nhallohelloTYPING");
    assert_eq!(head(&workbench, cx), Position::new(1, 16));
}

/// The late edit starts after the insert: dropped.
#[gpui::test]
fn resolve_additional_text_edits_async_when_needed_simple_conflict(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = accept_unresolved(cx, "suggest-async-simple-conflict", "", Position::new(0, 0));
    assert_eq!(text(&workbench, cx), "hello");
    resolve_late(&receiver, Position::new(0, 5), cx);
    assert_eq!(text(&workbench, cx), "hello");
}

/// The late edit starts after where the user typed: dropped.
#[gpui::test]
fn resolve_additional_text_edits_async_when_needed_conflict(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = accept_unresolved(cx, "suggest-async-conflict", "hello\nhallo", Position::new(1, 5));
    assert_eq!(text(&workbench, cx), "hello\nhallohello");
    workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(0, 0))]));
    type_text(&workbench, cx, "TYPING");
    assert_eq!(text(&workbench, cx), "TYPINGhello\nhallohello");
    resolve_late(&receiver, Position::new(0, 1), cx);
    assert_eq!(text(&workbench, cx), "TYPINGhello\nhallohello");
    assert_eq!(head(&workbench, cx), Position::new(0, 6));
}

/// suggestWidget.ts `this._list` and suggestWidgetDetails.ts `_body` sit in ScrollableElements: the pointer over
/// them shows their scrollbars and the wheel scrolls them.
#[gpui::test]
fn the_list_and_the_details_scroll_with_scrollbars(cx: &mut TestAppContext) {
    use crate::workbench::list_scroll::ListId;
    use gpui::{Modifiers, ScrollDelta, ScrollWheelEvent, point, px};
    let words: Vec<String> = (0..40).map(|index| format!("word{index:02}")).collect();
    let (workbench, cx) = open(cx, &format!("{}\n", words.join(" ")));
    run(&workbench, cx, "editor.action.triggerSuggest");
    assert_eq!(shown(&workbench, cx).len(), 40);
    // A list that opens under the pointer: the first move over it is a mouseover.
    let center = workbench.read_with(cx, |workbench, _| workbench.list_scroller(ListId::Suggest).bounds().center());
    run(&workbench, cx, "hideSuggestWidget");
    cx.simulate_mouse_move(center, None, Modifiers::none());
    run(&workbench, cx, "editor.action.triggerSuggest");
    cx.simulate_mouse_move(center + point(px(1.), px(0.)), None, Modifiers::none());
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.list_hover(ListId::Suggest).map(|(over, _)| over)), Some(true));
    let long = (0..60).map(|line| format!("line {line}")).collect::<Vec<_>>().join("\n\n");
    show_details(&workbench, cx, "detail", &long);
    let wheel = |list: ListId, cx: &mut VisualTestContext| {
        let bounds = workbench.read_with(cx, |workbench, _| workbench.list_scroller(list).bounds());
        cx.simulate_mouse_move(bounds.center(), None, Modifiers::none());
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.list_hover(list).map(|(over, _)| over)), Some(true), "{list:?}");
        cx.simulate_event(ScrollWheelEvent { position: bounds.center(), delta: ScrollDelta::Lines(point(0., -1.)), ..Default::default() });
        cx.run_until_parked();
        workbench.read_with(cx, |workbench, _| workbench.list_scroller(list).position().y)
    };
    assert_eq!(wheel(ListId::Scrollable("suggest-details-body"), cx), 50.);
    assert_eq!(wheel(ListId::Suggest, cx), (50. / crate::editor::LINE_HEIGHT).round() * crate::editor::LINE_HEIGHT);
}