Skip to content

Visual Studio Code, rebuilt in Rust

Rust
34.7 KB
Raw Blame
use std::path::Path;
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};

use exthost::session::ForwardedRequest;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::{Value, json};

use super::*;
use crate::debug::session::StackFrame;
use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::workbench::debug_service::DebugFocus;

/// debugUtils.test.ts `getExactExpressionStartAndEnd`.
#[test]
fn the_exact_expression_is_the_dotted_path_up_to_the_hovered_word() {
    let cases: [(&str, usize, usize, (usize, usize)); 17] = [
        ("foo", 1, 2, (1, 3)),
        ("!foo", 2, 3, (2, 4)),
        ("foo", 1, 3, (1, 3)),
        ("foo", 1, 4, (1, 3)),
        ("this.name = \"John\"", 1, 10, (1, 9)),
        ("this.name = \"John\"", 6, 10, (1, 9)),
        ("this->address = \"Main street\"", 6, 10, (1, 13)),
        ("var t = a.b.c.d.name", 16, 20, (9, 20)),
        ("MyClass::StaticProp", 10, 20, (1, 19)),
        ("largeNumber = myVar?.prop", 21, 25, (15, 25)),
        ("var t = a.b.c.d.name", 11, 12, (9, 11)),
        ("var t = a.b;c.d.name", 16, 20, (13, 20)),
        ("var t = a.b.c-d.name", 16, 20, (15, 20)),
        ("var aøñéå文 = a.b.c-d.name", 5, 5, (5, 10)),
        ("aøñéå文.aøñéå文.aøñéå文", 9, 9, (1, 13)),
        ("[...bar]", 5, 7, (5, 7)),
        ("...variable", 5, 5, (4, 11)),
    ];
    for (line, start, end, expected) in cases {
        assert_eq!(exact_expression_start_and_end(line, start, end), expected, "{line} {start} {end}");
    }
}

#[test]
fn the_safe_triangle_spans_from_the_mouse_to_the_widget() {
    let widget = Bounds { origin: point(100., 0.), size: Size { width: 100., height: 50. } };
    let origin = point(50., 100.);
    assert!(in_safe_triangle(origin, widget, point(90., 50.)), "between the mouse and the widget");
    assert!(!in_safe_triangle(origin, widget, point(20., 40.)), "beside the way to the widget");
}

fn workbench<'a>(cx: &'a mut TestAppContext, file: &Path, capabilities: Value) -> (gpui::Entity<Workbench>, Receiver<HostMessage>, &'a mut VisualTestContext) {
    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 javascript = exthost::scan::scan_extension(&app_root.join("extensions/javascript"), true).unwrap();
    let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
    let (sender, host) = std::sync::mpsc::channel();
    let file = file.to_path_buf();
    let user = file.parent().unwrap().join("User");
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[javascript]), Arc::new(Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user, None))), HostSync::new(sender), cx);
        workbench.open_file(file.clone(), true, window, cx);
        let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
        session.capabilities = capabilities;
        session.set_threads(&[json!({ "id": 1, "name": "main" })]);
        let frame = StackFrame { id: 9, name: "f".into(), source: json!({ "path": file.to_string_lossy() }), line: 2, column: 3, end_line: 2, end_column: 3, ..Default::default() };
        session.thread_mut(1).unwrap().frames = vec![frame];
        workbench.debug.sessions.push(session);
        workbench.set_debug_focus(DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) }, crate::workbench::debug_service::Reveal::No, window, cx);
        workbench
    });
    cx.run_until_parked();
    host.try_iter().for_each(drop);
    (workbench, host, cx)
}

/// The adapter requests sent so far, each answered by its command's body; the rest stay unanswered.
fn respond(workbench: &gpui::Entity<Workbench>, host: &Receiver<HostMessage>, bodies: &[(&str, Value)], cx: &mut VisualTestContext) -> Vec<Value> {
    let requests: Vec<Value> = host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).collect();
    for request in &requests {
        let Some((_, body)) = bodies.iter().find(|(command, _)| request["command"] == *command) else { continue };
        let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": request["command"], "body": body });
        let accept = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), response] };
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept, window, cx)));
        cx.run_until_parked();
    }
    requests
}

fn shown(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Option<(Anchor, String, i64)> {
    workbench.read_with(cx, |workbench, _| workbench.debug_hover.shown.as_ref().map(|shown| (shown.range, shown.value.value.clone(), shown.value.variables_reference)))
}

fn temp_file(name: &str, text: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("vsrustium-debug-hover-{name}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("a.js");
    std::fs::write(&file, text).unwrap();
    file
}

/// ShowDebugHoverAction at the cursor on `b` of `obj.b.c`: the `hover` evaluation of `obj.b` in the focused frame,
/// its value with the children of the result, and the editor hover off until the debug hover hides.
#[gpui::test]
fn show_debug_hover_evaluates_the_expression_at_the_cursor(cx: &mut TestAppContext) {
    let file = temp_file("evaluate", "function f(obj) {\n  return obj.b.c;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 14))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    let requests = respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    let evaluate = requests.iter().find(|request| request["command"] == "evaluate").expect("an evaluate request");
    assert_eq!(evaluate["arguments"]["expression"], "obj.b");
    assert_eq!(evaluate["arguments"]["context"], "hover");
    assert_eq!(evaluate["arguments"]["frameId"], 9);
    assert_eq!((evaluate["arguments"]["line"].clone(), evaluate["arguments"]["column"].clone()), (json!(2), json!(10)));
    let (range, value, reference) = shown(&workbench, cx).expect("the debug hover shows");
    assert_eq!((range.line, range.start, range.end, value.as_str(), reference), (1, 9, 14, "Object", 7));
    let requests = respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "c", "value": "3" }] }))], cx);
    assert!(requests.iter().any(|request| request["command"] == "variables" && request["arguments"]["variablesReference"] == 7), "{requests:?}");
    let editor_hover = workbench.read_with(cx, |workbench, _| workbench.hover_settings(workbench.editors.active().unwrap()).enabled);
    assert_eq!(editor_hover, "off");

    workbench.update_in(cx, |workbench, window, cx| workbench.debug_hover_key_down(window, cx));
    assert!(shown(&workbench, cx).is_none());
    let editor_hover = workbench.read_with(cx, |workbench, _| workbench.hover_settings(workbench.editors.active().unwrap()).enabled);
    assert_eq!(editor_hover, "on");
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// Without `supportsEvaluateForHovers` the dotted names are looked up in the frame's cheap scopes; a name the
/// scopes do not have leaves the editor hover to show.
#[gpui::test]
fn without_hover_evaluation_the_value_comes_from_the_scopes(cx: &mut TestAppContext) {
    let file = temp_file("scopes", "function f(obj) {\n  return obj.b + missing;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({}));
    let show = |column: usize, workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, column))]);
            drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
        });
        cx.run_until_parked();
    };
    show(14, &workbench, cx);
    respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4 }, { "name": "Global", "variablesReference": 5, "expensive": true }] }))], cx);
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "obj", "value": "Object", "variablesReference": 6 }] }))], cx);
    let requests = respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "b", "value": "2" }] }))], cx);
    assert_eq!(requests.iter().map(|request| request["arguments"]["variablesReference"].clone()).collect::<Vec<_>>(), [json!(6)], "the expensive scope is skipped");
    assert_eq!(shown(&workbench, cx).map(|(range, value, _)| (range.start, range.end, value)), Some((9, 14, "2".to_owned())));

    show(20, &workbench, cx);
    respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4 }] }))], cx);
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "obj", "value": "Object", "variablesReference": 6 }] }))], cx);
    assert!(shown(&workbench, cx).is_none());
    assert!(!workbench.read_with(cx, |workbench, _| workbench.debug_hover.lockout), "the editor hover takes over");
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// An `EvaluatableExpressionProvider` decides the range; without an expression its text is the range's.
#[gpui::test]
fn a_provider_range_without_an_expression_evaluates_the_range_text(cx: &mut TestAppContext) {
    let file = temp_file("provider", "function f(obj) {\n  return obj.b.c;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.language_features.register(REGISTER, vec![json!(3), json!("*")]);
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 14))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    let range = json!({ "startLineNumber": 2, "startColumn": 10, "endLineNumber": 2, "endColumn": 17 });
    let mut provided = 0;
    for mut message in host.try_iter().collect::<Vec<_>>() {
        if message.method == "$provideEvaluatableExpression" {
            provided += 1;
            assert_eq!(message.args[2], json!({ "lineNumber": 2, "column": 15 }));
            drop(message.reply.take().unwrap().send(Ok(json!({ "range": range }))));
        }
    }
    assert_eq!(provided, 1);
    cx.run_until_parked();
    let requests = respond(&workbench, &host, &[("evaluate", json!({ "result": "3", "variablesReference": 0 }))], cx);
    assert_eq!(requests.iter().map(|request| request["arguments"]["expression"].clone()).collect::<Vec<_>>(), [json!("obj.b.c")]);
    assert_eq!(shown(&workbench, cx).map(|(range, value, _)| (range.start, range.end, value)), Some((9, 16, "3".to_owned())));
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// debugHover.ts `layoutTree` in a 600px editor: the rows plus the 10px scrollbar, at most 55% of the editor, and at
/// most the hovered line's top less the 22px page padding unless the line is under the tree's top. The editor's top in
/// its group (57px: tabs and breadcrumbs) moves both.
#[test]
fn the_tree_height_keeps_an_above_hover_off_the_hovered_line() {
    assert_eq!(tree_height(600., 0., 3, 0., 400.), 64.);
    assert_eq!(tree_height(600., 0., 3, 30., 400.), 94., "the open find widget's padding is content");
    assert_eq!(tree_height(600., 0., 100, 0., 400.), 330.);
    assert_eq!(tree_height(600., 0., 100, 0., 200.), 178.);
    assert_eq!(tree_height(600., 0., 100, 0., 19.), 330.);
    assert_eq!(tree_height(600., 57., 100, 0., 36.), 330., "line 3 is under the tree's top");
    assert_eq!(tree_height(600., 57., 100, 0., 100.), 135.);
}

/// mouseTarget.ts: the caret goes to the nearer edge of the character under the mouse, a tab's middle included.
#[gpui::test]
fn the_hover_position_is_the_nearer_edge_of_a_tab(cx: &mut TestAppContext) {
    let file = temp_file("tab-edge", "\tvalue\n");
    let (workbench, _host, cx) = workbench(cx, &file, json!({}));
    let columns = workbench.read_with(cx, |workbench, _| {
        let editor = workbench.editors.active().unwrap();
        [1., 3., 4.2].map(|visible| hover_position(editor, 0, visible).map(|anchor| anchor.start))
    });
    assert_eq!(columns, [Some(0), Some(1), Some(1)]);
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// debugEditorContribution.ts `onEditorMouseMove`: the glyph margin clears the editor hover lockout while stopped,
/// unless Alt is down.
#[gpui::test]
fn the_glyph_margin_lifts_the_editor_hover_lockout(cx: &mut TestAppContext) {
    let file = temp_file("glyph-margin", "let a = 1;\n");
    let (workbench, _host, cx) = workbench(cx, &file, json!({}));
    let lockout_after_move = |alt: bool, cx: &mut VisualTestContext| {
        workbench.update(cx, |workbench, _| {
            let session = workbench.debug.session_mut("s").unwrap();
            session.initialized = true;
            session.thread_mut(1).unwrap().stopped = true;
            workbench.debug_hover.lockout = true;
            workbench.debug_hover.alt_pressed = alt;
            workbench.debug_hover_glyph_margin_moved();
            workbench.debug_hover.lockout
        })
    };
    assert!(!lockout_after_move(false, cx));
    assert!(lockout_after_move(true, cx));
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}
/// The focused tree takes the list keys: Down focuses the first row, Right expands it and then enters it, Left goes
/// back and collapses, a typed name focuses its row, End and Home jump, Enter selects, and Escape clears the
/// selection before it hides the hover.
#[gpui::test]
fn the_focused_tree_moves_with_the_list_keys(cx: &mut TestAppContext) {
    let file = temp_file("keys", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    let children = json!({ "variables": [{ "name": "alpha", "value": "Object", "variablesReference": 8 }, { "name": "beta", "value": "2" }, { "name": "gamma", "value": "3" }] });
    respond(&workbench, &host, &[("variables", children)], cx);
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.debug_hover_focus, cx));
    let state = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| (workbench.debug_hover.focused.clone(), workbench.debug_hover.expanded.len(), workbench.debug_hover.selected.clone()));
    let some = |key: &str| Some(key.to_owned());
    workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), file.parent().unwrap().join("keybindings.json")));

    cx.simulate_keystrokes("down");
    assert_eq!(state(cx), (some("hover/alpha"), 0, None));
    cx.simulate_keystrokes("right");
    assert_eq!(state(cx), (some("hover/alpha"), 1, None));
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "x", "value": "1" }] }))], cx);
    cx.simulate_keystrokes("right");
    assert_eq!(state(cx), (some("hover/alpha/x"), 1, None));
    cx.simulate_keystrokes("left");
    assert_eq!(state(cx), (some("hover/alpha"), 1, None));
    cx.simulate_keystrokes("left");
    assert_eq!(state(cx), (some("hover/alpha"), 0, None));
    cx.simulate_keystrokes("g");
    assert_eq!(state(cx), (some("hover/gamma"), 0, None));
    cx.simulate_keystrokes("home");
    assert_eq!(state(cx), (some("hover/alpha"), 0, None));
    cx.simulate_keystrokes("end enter");
    assert_eq!(state(cx), (some("hover/gamma"), 0, some("hover/gamma")));
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx).2, None);
    assert!(shown(&workbench, cx).is_some(), "the first Escape only clears the selection");
    cx.simulate_keystrokes("escape");
    assert!(shown(&workbench, cx).is_none());
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// abstractTree.ts: Alt+click toggles a row with every descendant whose children are loaded, the others stay
/// collapsed (asyncDataTree.ts collapses a stale node a deep expand reaches).
#[gpui::test]
fn alt_click_toggles_the_loaded_subtree(cx: &mut TestAppContext) {
    let file = temp_file("recursive", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "alpha", "value": "Object", "variablesReference": 8 }] }))], cx);
    let toggle = |key: &str, reference: i64, expand: bool, alt: bool, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| workbench.toggle_debug_hover_row(key, "s", &HoverChildren::Variables(reference), expand, alt, window, cx));
        cx.run_until_parked();
    };
    toggle("hover/alpha", 8, true, false, cx);
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "x", "value": "Object", "variablesReference": 10 }, { "name": "y", "value": "Object", "variablesReference": 11 }] }))], cx);
    toggle("hover/alpha/x", 10, true, false, cx);
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "z", "value": "1" }] }))], cx);
    toggle("hover/alpha/x", 10, false, false, cx);
    toggle("hover/alpha", 8, false, false, cx);
    let expanded = |cx: &mut VisualTestContext| {
        let mut keys: Vec<String> = workbench.read_with(cx, |workbench, _| workbench.debug_hover.expanded.iter().cloned().collect());
        keys.sort();
        keys
    };
    assert!(expanded(cx).is_empty());

    toggle("hover/alpha", 8, true, true, cx);
    assert_eq!(expanded(cx), ["hover/alpha", "hover/alpha/x"], "y's children are not loaded");
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug_hover.focused.clone()).as_deref(), Some("hover/alpha"));
    toggle("hover/alpha", 8, false, true, cx);
    assert!(expanded(cx).is_empty());

    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.debug_hover_focus, cx));
    cx.simulate_keystrokes("alt-space");
    assert_eq!(expanded(cx), ["hover/alpha", "hover/alpha/x"], "Alt+Space expands the focused row's loaded subtree");
    cx.simulate_keystrokes("alt-space");
    assert!(expanded(cx).is_empty());
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// abstractTree.ts `TreeMouseController.onViewPointer`: a click focuses the tree, a twistie click only toggles, a
/// row click toggles and focuses and selects the row.
#[gpui::test]
fn a_click_on_a_hover_row_focuses_the_tree(cx: &mut TestAppContext) {
    let file = temp_file("click", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    let children = json!({ "variables": [{ "name": "alpha", "value": "Object", "variablesReference": 8 }, { "name": "beta", "value": "2" }, { "name": "gamma", "value": "3" }] });
    respond(&workbench, &host, &[("variables", children)], cx);
    let tree = cx.debug_bounds("debug-hover-tree").expect("the hover shows its tree");
    assert!(workbench.read_with(cx, |workbench, _| workbench.scrollable_drawn("debug-hover-tree")), "debug-hover-tree sits in a ScrollableElement");
    let state = |cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, _| (workbench.debug_hover_focus.is_focused(window), workbench.debug_hover.focused.clone(), workbench.debug_hover.selected.clone(), workbench.debug_hover.expanded.contains("hover/alpha")))
    };
    let some = |key: &str| Some(key.to_owned());

    cx.simulate_click(tree.origin + point(px(100.), px(ROW_HEIGHT * 1.5)), Modifiers::none());
    assert_eq!(state(cx), (true, some("hover/beta"), some("hover/beta"), false));
    cx.simulate_click(tree.origin + point(px(INDENT + 11.), px(ROW_HEIGHT / 2.)), Modifiers::none());
    assert_eq!(state(cx), (true, some("hover/alpha"), some("hover/beta"), true), "the twistie toggles without selecting");
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "x", "value": "1" }] }))], cx);
    cx.simulate_click(tree.origin + point(px(100.), px(ROW_HEIGHT / 2.)), Modifiers::none());
    assert_eq!(state(cx), (true, some("hover/alpha"), some("hover/alpha"), false));
    workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), file.parent().unwrap().join("keybindings.json")));
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-alt-f"));
    assert!(workbench.read_with(cx, |workbench, _| workbench.debug_hover.find.open), "Cmd+Alt+F after the click opens the tree's find widget");
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// abstractTree.ts `FindController` on the hover's tree: `list.find` opens the widget in highlight mode, a pattern
/// highlights the matching names and focuses the first, `list.find` again selects the pattern, the Filter toggle
/// hides the rest but keeps a collapsed parent of a loaded match, a pattern nothing matches says so, and Escape
/// hides the hover and closes the widget.
#[gpui::test]
fn the_find_widget_filters_the_hover_tree(cx: &mut TestAppContext) {
    let file = temp_file("find", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    let children = json!({ "variables": [{ "name": "alpha", "value": "Object", "variablesReference": 8 }, { "name": "beta", "value": "2" }, { "name": "gamma", "value": "3" }] });
    respond(&workbench, &host, &[("variables", children)], cx);
    workbench.update_in(cx, |workbench, window, cx| workbench.toggle_debug_hover_row("hover/alpha", "s", &HoverChildren::Variables(8), true, false, window, cx));
    cx.run_until_parked();
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "bet", "value": "1" }] }))], cx);
    workbench.update_in(cx, |workbench, window, cx| workbench.toggle_debug_hover_row("hover/alpha", "s", &HoverChildren::Variables(8), false, false, window, cx));
    workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), file.parent().unwrap().join("keybindings.json")));
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.debug_hover_focus, cx));
    let rows = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let shown = workbench.debug_hover.shown.as_ref().unwrap();
            workbench.debug_hover_tree_rows(shown).iter().map(|row| (row.key.clone(), row.highlights.clone())).collect::<Vec<_>>()
        })
    };
    let row = |key: &str, highlights: Vec<Range<usize>>| (key.to_owned(), highlights);

    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-alt-f"));
    assert!(workbench.update_in(cx, |workbench, window, _| workbench.debug_hover.find.open && workbench.debug_hover.find.focus.is_focused(window)));
    cx.simulate_input("bet");
    assert_eq!(rows(cx), [row("hover/alpha", vec![]), row("hover/beta", vec![0..3]), row("hover/gamma", vec![])], "highlight mode keeps every row");
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug_hover.focused.clone()).as_deref(), Some("hover/beta"));
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-alt-f"));
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug_hover.find.input.selected_text()), "bet", "list.find again selects the pattern");

    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("list.toggleFindMode", Vec::new(), window, cx)));
    assert_eq!(rows(cx), [row("hover/alpha", vec![]), row("hover/beta", vec![0..3])], "the filter keeps the parent of the loaded match");
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug_hover_find_message()), None);
    cx.simulate_input("z");
    assert_eq!(rows(cx), []);
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug_hover_find_message()).as_deref(), Some("No results found."));

    cx.simulate_keystrokes("escape");
    assert!(shown(&workbench, cx).is_none());
    assert!(workbench.read_with(cx, |workbench, _| !workbench.debug_hover.find.open && workbench.debug_hover.find.previous_pattern == "z"));
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// A `presentationHint.lazy` child is not expandable until its eye button evaluates it: the `variables` request of
/// its reference answers with the one variable it stands for, which takes the row and expands (baseDebugView.ts
/// `lazyButton`, debugModel.ts `evaluateLazy`).
#[gpui::test]
fn a_lazy_row_takes_its_value_from_the_eye_button(cx: &mut TestAppContext) {
    let file = temp_file("lazy", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    let lazy = json!({ "name": "size", "value": "(...)", "variablesReference": 8, "presentationHint": { "lazy": true } });
    respond(&workbench, &host, &[("variables", json!({ "variables": [lazy] }))], cx);
    let row = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.debug.children[&("s".to_owned(), 7)][0].clone());
    assert!(!row(cx).has_children(), "a lazy row has no twistie");

    workbench.update_in(cx, |workbench, window, cx| workbench.evaluate_lazy_row("s", 7, "size", "hover/size", window, cx));
    cx.run_until_parked();
    let requests = respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "size", "value": "Map(1)", "variablesReference": 9 }] }))], cx);
    assert_eq!(requests[0]["arguments"]["variablesReference"], 8);
    assert_eq!((row(cx).value, row(cx).variables_reference, row(cx).has_children()), ("Map(1)".to_owned(), 9, true));
    let requests = respond(&workbench, &host, &[], cx);
    assert_eq!(requests[0]["arguments"]["variablesReference"], 9, "the evaluated row expands");
    assert!(workbench.read_with(cx, |workbench, _| workbench.debug_hover.expanded.contains("hover/size")));
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// debugHover.ts registers `VisualizedVariableRenderer`: a hover child offers its visualizers, a used tree
/// visualizer replaces the row with its item, which expands into `$getVisualizerTreeItemChildren`.
#[gpui::test]
fn a_visualized_child_shows_its_tree_in_the_hover(cx: &mut TestAppContext) {
    let file = temp_file("viz", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    let tree = "port.viz\0tree";
    workbench.update_in(cx, |workbench, window, cx| {
        let description = json!({ "contributes": { "debugVisualizers": [{ "id": "v", "when": "variableName == 'x'" }] } });
        workbench.extensions.push(exthost::scan::ScannedExtension { id: "port.viz".into(), location: "/viz".into(), description });
        for (method, args) in [("$registerDebugVisualizer", vec![json!("port.viz"), json!("v")]), ("$registerDebugVisualizerTree", vec![json!(tree), json!(false)])] {
            drop(workbench.handle_debug_request(ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: method.into(), args }, window, cx));
        }
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    let visualizers = json!([{ "id": 1, "name": "Tree", "visualization": { "type": 1, "id": tree } }, { "id": 2, "name": "Other" }]);
    let answer = |method: &str| match method {
        "$provideDebugVisualizers" => visualizers.clone(),
        "$getVisualizerTreeItem" => json!({ "id": 7, "label": "x", "description": "tree", "collapsibleState": 1 }),
        "$getVisualizerTreeItemChildren" => json!([{ "id": 8, "label": "child", "description": "c", "collapsibleState": 0 }]),
        _ => Value::Null,
    };
    let drain = |bodies: &[(&str, Value)], cx: &mut VisualTestContext| loop {
        cx.run_until_parked();
        let messages: Vec<HostMessage> = host.try_iter().collect();
        if messages.is_empty() {
            return;
        }
        for message in messages {
            if message.method == "$sendDAMessage" {
                let request = &message.args[1];
                let Some((_, body)) = bodies.iter().find(|(command, _)| request["command"] == *command) else { continue };
                let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": request["command"], "body": body });
                let accept = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), response] };
                workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept, window, cx)));
            } else if let Some(reply) = message.reply {
                let _ = reply.send(Ok(answer(message.method)));
            }
        }
    };
    let children = json!({ "variables": [{ "name": "x", "value": "1" }, { "name": "y", "value": "2" }] });
    drain(&[("evaluate", json!({ "result": "Object", "variablesReference": 7 })), ("variables", children)], cx);
    workbench.update(cx, |workbench, cx| {
        workbench.debug_hover.focused = Some("hover/x".into());
        cx.notify();
    });
    cx.run_until_parked();
    assert!(cx.debug_bounds("visualize-variable").is_some(), "the focused x shows its two visualizers behind Visualize Variable...");

    let rows = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let shown = workbench.debug_hover.shown.as_ref().unwrap();
            workbench.debug_hover_tree_rows(shown).iter().map(|row| format!("{} {}: {}", row.key, row.variable.name, row.variable.value)).collect::<Vec<_>>()
        })
    };
    workbench.update_in(cx, |workbench, window, cx| workbench.use_visualizer(("s".into(), 7, "x".into()), visualizers[0].clone(), window, cx));
    drain(&[], cx);
    assert_eq!(rows(cx), ["hover/x x: tree", "hover/y y: 2"]);

    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.debug_hover_focus, cx));
    workbench.update(cx, |workbench, _| workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), file.parent().unwrap().join("keybindings.json")));
    cx.simulate_keystrokes("right");
    drain(&[], cx);
    assert_eq!(rows(cx), ["hover/x x: tree", "hover/x/8 child: c", "hover/y y: 2"]);
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}

/// The eye button's "Click to expand" hover shows over the debug hover it sits in, so the mouse reaches it.
#[gpui::test]
fn a_workbench_hover_draws_over_the_debug_hover(cx: &mut TestAppContext) {
    let file = temp_file("over", "function f(obj) {\n  return obj;\n}\n");
    let (workbench, host, cx) = workbench(cx, &file, json!({ "supportsEvaluateForHovers": true }));
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(Position::new(1, 10))]);
        drop(workbench.execute_command("editor.debug.action.showDebugHover", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    respond(&workbench, &host, &[("evaluate", json!({ "result": "Object", "variablesReference": 7 }))], cx);
    respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "size", "value": "3", "variablesReference": 0 }] }))], cx);
    cx.update(|window, cx| drop(window.draw(cx)));
    let tree = cx.debug_bounds("debug-hover-tree").expect("the debug hover's tree");
    let eye = gpui::Bounds { origin: tree.origin, size: gpui::size(gpui::px(16.), gpui::px(16.)) };
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.show_managed_hover("eye", crate::workbench::hover::HoverContent::Text("Click to expand".into()), crate::workbench::hover::HoverOptions::mouse(), eye, window, cx);
    });
    cx.update(|window, cx| drop(window.draw(cx)));
    let tooltip = cx.debug_bounds("workbench-hover").expect("the tooltip");
    assert!(tree.intersects(&tooltip), "{tree:?} {tooltip:?}");
    cx.simulate_mouse_move(tooltip.center(), None, gpui::Modifiers::none());
    assert!(workbench.read_with(cx, |workbench, _| workbench.hovers.mouse_in_hover));
    std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}