Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.7 KB
Raw Blame
use std::sync::{Arc, Mutex};

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

use super::*;
use crate::host_sync::{HostMessage, HostSync};

#[test]
fn labels_are_cut_at_the_maximum_length_per_line() {
    let mut total = 0;
    let first = rendered_parts(&json!({ "label": "abcdef" }), &mut total, 8, None);
    assert_eq!(first[0].text, "abcdef");
    let second = rendered_parts(&json!({ "label": [{ "label": "gh" }, { "label": "ij" }] }), &mut total, 8, None);
    // The running total passes 8 in the second part: it loses the excess and ends in an ellipsis, the rest goes.
    assert_eq!(second.iter().map(|part| (part.text.as_str(), part.index)).collect::<Vec<_>>(), [("gh", 0), ("\u{2026}", 1)]);
}

#[test]
fn spaces_become_no_break_spaces() {
    let parts = rendered_parts(&json!({ "label": "a b\tc" }), &mut 0, 0, None);
    assert_eq!(parts[0].text, "a\u{a0}b\u{a0}c");
}

#[test]
fn a_fixed_length_cuts_or_pads_the_label() {
    let cut = rendered_parts(&json!({ "label": "string" }), &mut 0, 0, Some(3));
    assert_eq!(cut[0].text, "st\u{2026}");
    let padded = rendered_parts(&json!({ "label": "x" }), &mut 0, 0, Some(3));
    assert_eq!(padded.iter().map(|part| part.text.as_str()).collect::<String>(), "x\u{200a}\u{200a}");
}

#[test]
fn a_hint_after_a_word_attaches_after_it() {
    let languages = Languages::new(&[]);
    let document = TextDocument::untitled(std::path::Path::new("Untitled-1"), "let value = f(arg);", Some("plaintext"), &languages, &crate::default_settings().lock().unwrap());
    let theme = dark_modern();
    let type_hint = hint_item(&document, &languages, &theme, 1, json!({ "label": ": number", "position": { "lineNumber": 1, "column": 10 } }));
    assert_eq!((type_hint.position, type_hint.after), (Position::new(0, 9), true));
    let parameter = hint_item(&document, &languages, &theme, 1, json!({ "label": "x:", "position": { "lineNumber": 1, "column": 15 } }));
    assert_eq!((parameter.position, parameter.after), (Position::new(0, 14), false));
}

/// `_getRangeAtPosition`: off a word the hint goes after the token it is in; plain text is one token.
#[test]
fn a_hint_off_a_word_attaches_after_the_start_of_its_token() {
    let languages = Languages::new(&[]);
    let document = TextDocument::untitled(std::path::Path::new("Untitled-1"), "let value = f(arg);", Some("plaintext"), &languages, &crate::default_settings().lock().unwrap());
    let at_equals = hint_item(&document, &languages, &dark_modern(), 1, json!({ "label": "x", "position": { "lineNumber": 1, "column": 11 } }));
    assert_eq!((at_equals.position, at_equals.after), (Position::new(0, 10), true));
}


fn dark_modern() -> Theme {
    let themes = exthost::scan::scan_extension(&std::path::Path::new(env!("VSCODE_SRC")).join("extensions/theme-defaults"), true).unwrap();
    crate::theme::load_theme(&[themes], "Dark Modern").unwrap()
}

/// `_debounceInfo`: after six answers of 400ms a scroll asks again after 400ms, not after `min`.
#[gpui::test]
fn the_delay_follows_the_providers_answer_time(cx: &mut TestAppContext) {
    let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
    let dir = std::env::temp_dir().join(format!("code-gpui-inlay-hints-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.txt"), "let x = 1;\n").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 (sender, receiver) = std::sync::mpsc::channel::<HostMessage>();
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(dark_modern(), app_root.clone(), Some(workspace), Languages::new(&[]), settings, HostSync::new(sender), cx);
        workbench.open_file(dir.join("a.txt"), true, window, cx);
        workbench.language_features.register(REGISTER, vec![json!(1), json!("*"), json!(null), json!(2)]);
        workbench.inlay_hints_registrations_changed(cx);
        workbench
    });
    let asked = |cx: &mut VisualTestContext| {
        cx.run_until_parked();
        let mut asked = false;
        for message in receiver.try_iter() {
            if message.method == "$provideInlayHints" {
                asked = true;
                let _ = message.reply.expect("a call").send(Ok(Value::Null));
            }
        }
        cx.run_until_parked();
        asked
    };
    let answer_after = |cx: &mut VisualTestContext| {
        cx.run_until_parked();
        let requests: Vec<HostMessage> = receiver.try_iter().filter(|message| message.method == "$provideInlayHints").collect();
        assert_eq!(requests.len(), 1);
        cx.executor().advance_clock(Duration::from_millis(400));
        for request in requests {
            let _ = request.reply.expect("a call").send(Ok(Value::Null));
        }
        cx.run_until_parked();
    };
    answer_after(cx);
    for _ in 0..5 {
        let delay = workbench.update(cx, |workbench, cx| {
            workbench.inlay_hints_scrolled(cx);
            workbench.inlay_hints_delay()
        });
        cx.executor().advance_clock(delay);
        answer_after(cx);
    }
    workbench.update(cx, |workbench, cx| workbench.inlay_hints_scrolled(cx));
    cx.executor().advance_clock(Duration::from_millis(399));
    assert!(!asked(cx), "the answers took 400ms, so the debounce is 400ms, not 25ms");
    cx.executor().advance_clock(Duration::from_millis(1));
    assert!(asked(cx));
}

/// Without a provider a scroll asks nothing; a provider's answer draws the editor part again, not the workbench
/// (whose notify would draw every part).
#[gpui::test]
fn a_scroll_redraws_the_editor_only(cx: &mut TestAppContext) {
    let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
    let dir = std::env::temp_dir().join(format!("code-gpui-inlay-hints-redraw-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.txt"), "let x = 1;\n").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 (sender, receiver) = std::sync::mpsc::channel::<HostMessage>();
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(dark_modern(), app_root.clone(), Some(workspace), Languages::new(&[]), settings, HostSync::new(sender), cx);
        workbench.open_file(dir.join("a.txt"), true, window, cx);
        workbench
    });
    cx.run_until_parked();
    cx.update(|window, cx| drop(window.draw(cx)));
    let scheduled = workbench.update(cx, |workbench, cx| {
        workbench.inlay_hints_scrolled(cx);
        workbench.inlay_hints.request.is_some()
    });
    assert!(!scheduled, "no provider, so the scroll asks nothing");

    workbench.update(cx, |workbench, cx| {
        workbench.language_features.register(REGISTER, vec![json!(1), json!("*"), json!(null), json!(2)]);
        workbench.inlay_hints_registrations_changed(cx);
    });
    cx.executor().advance_clock(Duration::from_secs(1));
    cx.run_until_parked();
    for message in receiver.try_iter() {
        let _ = message.reply.map(|reply| reply.send(Ok(Value::Null)));
    }
    cx.run_until_parked();
    cx.update(|window, cx| drop(window.draw(cx)));
    workbench.update(cx, |workbench, cx| workbench.inlay_hints_scrolled(cx));
    cx.executor().advance_clock(Duration::from_secs(1));
    cx.run_until_parked();
    let requests: Vec<HostMessage> = receiver.try_iter().filter(|message| message.method == "$provideInlayHints").collect();
    assert_eq!(requests.len(), 1);
    let notified = std::rc::Rc::new(std::cell::Cell::new(0));
    let _observer = {
        let notified = notified.clone();
        cx.update(|_, cx| cx.observe(&workbench, move |_, _| notified.set(notified.get() + 1)))
    };
    for request in requests {
        let _ = request.reply.expect("a call").send(Ok(Value::Null));
    }
    cx.run_until_parked();
    assert_eq!(notified.get(), 0, "the answer draws the editor part alone");
    std::fs::remove_dir_all(dir).unwrap();
}

/// `_update` returns while `editor.inlayHints.enabled` is `off` (inlayHintsController.ts:180), before its scroll listener.
#[gpui::test]
fn a_scroll_asks_nothing_while_hints_are_off(cx: &mut TestAppContext) {
    let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
    let dir = std::env::temp_dir().join(format!("code-gpui-inlay-hints-off-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.txt"), "let x = 1;\n").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 (sender, receiver) = std::sync::mpsc::channel::<HostMessage>();
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(dark_modern(), app_root.clone(), Some(workspace), Languages::new(&[]), settings, HostSync::new(sender), cx);
        workbench.open_file(dir.join("a.txt"), true, window, cx);
        workbench.update_user_setting("editor.inlayHints.enabled", json!("off"));
        workbench.language_features.register(REGISTER, vec![json!(1), json!("*"), json!(null), json!(2)]);
        workbench.inlay_hints_registrations_changed(cx);
        workbench
    });
    workbench.update(cx, |workbench, cx| workbench.inlay_hints_scrolled(cx));
    cx.executor().advance_clock(Duration::from_secs(1));
    cx.run_until_parked();
    assert_eq!(receiver.try_iter().filter(|message| message.method == "$provideInlayHints").count(), 0);
    std::fs::remove_dir_all(dir).unwrap();
}

/// inlayHintsController.ts `_removeAllDecorations` clears the hints of the editor they were drawn in: hints drawn in an
/// editor of another group go when the focus moves away, not stay stale there.
#[gpui::test]
fn the_hints_of_an_editor_in_another_group_go_when_the_focus_leaves_it(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = crate::workbench::editor_groups::tests::workbench_with("inlay-hints-other-group", &["a.txt"], cx);
    let (sender, receiver) = std::sync::mpsc::channel::<HostMessage>();
    workbench.update(cx, |workbench, cx| {
        workbench.host = HostSync::new(sender);
        workbench.language_features.register(REGISTER, vec![json!(1), json!({ "scheme": "file" }), json!(null), json!(2)]);
        workbench.inlay_hints_registrations_changed(cx);
    });
    crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.focusNextGroup", vec![], window, cx)));
    cx.executor().advance_clock(Duration::from_secs(1));
    cx.run_until_parked();
    let hints = json!({ "hints": [{ "label": ": number", "position": { "lineNumber": 1, "column": 1 } }] });
    for message in receiver.try_iter().filter(|message| message.method == "$provideInlayHints") {
        let _ = message.reply.expect("a call").send(Ok(hints.clone()));
    }
    cx.run_until_parked();
    let shown = |workbench: &Workbench| workbench.editors.model("file", &dir.join("a.txt")).unwrap().injected_text.iter().filter(|injection| injection.owner == InjectionOwner::InlayHint).count();
    assert_eq!(workbench.read_with(cx, |workbench, _| shown(workbench)), 1, "the hint shows");
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.focusPreviousGroup", vec![], window, cx)));
    cx.run_until_parked();
    assert_eq!(workbench.read_with(cx, |workbench, _| shown(workbench)), 0);
    std::fs::remove_dir_all(dir).unwrap();
}