Skip to content

Visual Studio Code, rebuilt in Rust

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

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

use super::*;
use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::theme::load_theme;

/// A folder with `a.ts` holding three lines, open, with one code lens provider.
fn open(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext, Receiver<HostMessage>) {
    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();
    // A folder per test: one test's b.ts would show in the explorer of another running at once.
    let dir = std::env::temp_dir().join(format!("code-gpui-code-lens-{}-{:?}", std::process::id(), std::thread::current().id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.ts"), "function a() {}\n  function b() {}\nc\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();
    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(sender), cx);
        workbench.watch_editor_focus(window, cx);
        workbench.language_features.register(REGISTER, vec![json!(3), json!("*"), json!(9)]);
        workbench.open_file(dir.join("a.ts"), true, window, cx);
        window.focus(&workbench.editor_focus, cx);
        workbench
    });
    cx.executor().advance_clock(DELAY);
    cx.run_until_parked();
    (workbench, cx, receiver)
}

fn lens(line: u64, column: u64, command: Option<&str>) -> Value {
    let range = json!({ "startLineNumber": line, "startColumn": column, "endLineNumber": line, "endColumn": column + 1 });
    match command {
        Some(title) => json!({ "cacheId": [1, line], "range": range, "command": { "id": "lens.run", "title": title, "arguments": [line] } }),
        None => json!({ "cacheId": [1, line], "range": range }),
    }
}

/// Answers the requests of `method` sent since the last answer with `answer(args)`; returns their count.
fn reply(receiver: &Receiver<HostMessage>, method: &str, answer: impl Fn(&[Value]) -> Value, cx: &mut VisualTestContext) -> usize {
    let mut count = 0;
    for message in receiver.try_iter().filter(|message| message.method == method) {
        count += 1;
        let _ = message.reply.expect("a call").send(Ok(answer(&message.args)));
    }
    cx.run_until_parked();
    count
}

#[gpui::test]
fn lenses_get_zones_above_their_lines_and_resolve_in_view(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open(cx);
    let lenses = json!({ "cacheId": 4, "lenses": [lens(2, 3, None), lens(1, 1, Some("1 reference")), lens(1, 10, None)] });
    assert_eq!(reply(&receiver, "$provideCodeLenses", |_| lenses.clone(), cx), 1);
    workbench.read_with(cx, |workbench, _| {
        let editor = workbench.editors.active().unwrap();
        let lines: Vec<usize> = workbench.code_lenses.groups.iter().map(|group| editor.view_zone(group.zone_id).unwrap().anchor.unwrap().line).collect();
        assert_eq!(lines, [0, 1]);
        // The first group shows its lens with a command at once; the second waits for its resolve.
        assert_eq!(workbench.code_lenses.groups[0].shown.as_ref().map(Vec::len), Some(1));
        assert!(workbench.code_lenses.groups[1].shown.is_none());
        assert!(editor.line_top(0, workbench.editors.viewport) > 0.);
    });
    cx.executor().advance_clock(DELAY);
    cx.run_until_parked();
    let resolved = reply(&receiver, "$resolveCodeLens", |args| {
        let mut symbol = args[1].clone();
        symbol["command"] = json!({ "id": "", "title": "$(gear) resolved" });
        symbol
    }, cx);
    assert_eq!(resolved, 2);
    workbench.read_with(cx, |workbench, _| {
        let shown = workbench.code_lenses.groups[1].shown.as_ref().unwrap();
        assert_eq!(shown[0].as_ref().unwrap()["command"]["title"], "$(gear) resolved");
        assert_eq!(workbench.code_lenses.groups[0].shown.as_ref().unwrap().len(), 2);
    });
    // An edit asks again; lenses on the same lines keep their zones.
    let zones: Vec<u32> = workbench.read_with(cx, |workbench, _| workbench.code_lenses.groups.iter().map(|group| group.zone_id).collect());
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("type", vec![json!({ "text": "x" })], window, cx));
    cx.executor().advance_clock(DELAY);
    cx.run_until_parked();
    assert_eq!(reply(&receiver, "$provideCodeLenses", |_| lenses.clone(), cx), 1);
    let released: Vec<Value> = receiver.try_iter().filter(|message| message.method == "$releaseCodeLenses").map(|message| message.args[1].clone()).collect();
    assert_eq!(released, [json!(4)]);
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.code_lenses.groups.iter().map(|group| group.zone_id).collect::<Vec<_>>(), zones));
}

#[gpui::test]
fn the_current_line_command_picks_among_its_lenses(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open(cx);
    reply(&receiver, "$provideCodeLenses", |_| json!({ "lenses": [lens(1, 1, Some("run")), lens(1, 5, Some("debug")), lens(2, 1, Some("other"))] }), cx);
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("codelens.showLensesInCurrentLine", vec![], window, cx));
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| {
        let input = workbench.quick_inputs.current().expect("a pick shows");
        let labels: Vec<_> = input.items().iter().filter_map(|entry| match entry {
            Entry::Item(item) => Some(item.label.clone()),
            _ => None,
        }).collect();
        assert_eq!(labels, ["run", "debug"]);
    });
}

#[gpui::test]
fn the_execute_command_sends_cancellable_requests(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open(cx);
    receiver.try_iter().for_each(drop);
    let uri = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().uri());
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("_executeCodeLensProvider", vec![uri, json!(1)], window, cx)));
    cx.run_until_parked();
    let provide = receiver.try_iter().find(|message| message.method == "$provideCodeLenses").unwrap();
    assert!(provide.cancellable, "providers read the token");
    let _ = provide.reply.unwrap().send(Ok(json!({ "cacheId": 4, "lenses": [lens(1, 1, None)] })));
    cx.run_until_parked();
    let resolve = receiver.try_iter().find(|message| message.method == "$resolveCodeLens").unwrap();
    assert!(resolve.cancellable);
}

/// codelensController.ts `_updateLensStyle` and codelensWidget.ts `withCommands`: `editor.codeLensFontFamily` sets the
/// lens font, and only commands that arrive with a resolve fade in.
#[gpui::test]
fn lenses_take_their_font_setting_and_fade_in_when_resolved(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open(cx);
    let lenses = json!({ "cacheId": 5, "lenses": [lens(1, 1, Some("1 reference")), lens(2, 3, None)] });
    reply(&receiver, "$provideCodeLenses", |_| lenses.clone(), cx);
    assert!(cx.debug_bounds("code-lens .SystemUIFont").is_some());
    assert!(cx.debug_bounds("code-lens fadein").is_none());
    workbench.update(cx, |workbench, cx| {
        workbench.settings.lock().unwrap().update_value("editor.codeLensFontFamily", Some(&json!("Courier")), config::service::Target::User, None, &[]).unwrap();
        cx.notify();
    });
    cx.executor().advance_clock(DELAY);
    cx.run_until_parked();
    reply(&receiver, "$resolveCodeLens", |args| {
        let mut symbol = args[1].clone();
        symbol["command"] = json!({ "id": "", "title": "resolved" });
        symbol
    }, cx);
    assert!(cx.debug_bounds("code-lens Courier").is_some());
    assert!(cx.debug_bounds("code-lens fadein").is_some());
}

/// codelensController.ts: the editor text's focus asks the providers again, a blur within the delay cancels that.
#[gpui::test]
fn the_editor_focus_asks_for_lenses_again(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open(cx);
    cx.update(|window, _| window.activate_window());
    reply(&receiver, "$provideCodeLenses", |_| json!({ "lenses": [] }), cx);
    let refocus = |cx: &mut VisualTestContext| {
        workbench.update_in(cx, |_, window, cx| window.blur(cx));
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.editor_focus, cx));
        cx.run_until_parked();
    };
    refocus(cx);
    cx.executor().advance_clock(DELAY);
    cx.run_until_parked();
    assert_eq!(reply(&receiver, "$provideCodeLenses", |_| json!({ "lenses": [] }), cx), 1);
    refocus(cx);
    workbench.update_in(cx, |_, window, cx| window.blur(cx));
    cx.executor().advance_clock(DELAY);
    cx.run_until_parked();
    assert_eq!(reply(&receiver, "$provideCodeLenses", |_| json!({ "lenses": [] }), cx), 0);
}

/// codeLensCache.ts: a model shown again draws its last lenses before its providers answer, the titles without
/// command ids; on shutdown the lines go to the workspace storage and come back as empty lenses.
#[gpui::test]
fn a_model_shown_again_draws_its_cached_lenses_at_once(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open(cx);
    let lenses = json!({ "cacheId": 6, "lenses": [lens(1, 1, Some("1 reference")), lens(3, 1, Some("run"))] });
    reply(&receiver, "$provideCodeLenses", |_| lenses.clone(), cx);
    let (a, b) = workbench.read_with(cx, |workbench, _| {
        let a = workbench.editors.active().unwrap().document().path.clone();
        (a.clone(), a.with_file_name("b.ts"))
    });
    std::fs::write(&b, "b\n").unwrap();
    let show = |path: &std::path::Path, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(path.to_path_buf(), true, window, cx));
        cx.run_until_parked();
    };
    let titles = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let groups = workbench.code_lenses.groups.iter();
            groups.map(|group| group.shown.iter().flatten().flatten().map(|symbol| format!("{}:{}", symbol["command"]["id"], symbol["command"]["title"])).collect::<String>()).collect::<Vec<_>>()
        })
    };
    show(&b, cx);
    show(&a, cx);
    assert_eq!(titles(cx), ["\"\":\"1 reference\"", "\"\":\"run\""]);
    workbench.update_in(cx, |workbench, window, cx| workbench.shutdown(super::super::lifecycle::ShutdownReason::Quit, window, cx, |_, _, _| {}));
    cx.run_until_parked();
    let stored = workbench.read_with(cx, |workbench, _| workbench.workspace_storage.lock().unwrap().get("codelens/cache2").map(str::to_owned)).unwrap();
    let stored: Value = serde_json::from_str(&stored).unwrap();
    let a_uri = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().uri_string());
    assert_eq!(stored[&a_uri], json!({ "lineCount": 4, "lines": [1, 3] }));
    workbench.update(cx, |workbench, _| workbench.code_lenses.cache = None);
    show(&b, cx);
    show(&a, cx);
    let lines = workbench.read_with(cx, |workbench, _| {
        let editor = workbench.editors.active().unwrap();
        workbench.code_lenses.groups.iter().map(|group| (editor.view_zone(group.zone_id).unwrap().anchor.unwrap().line, group.shown.is_none())).collect::<Vec<_>>()
    });
    assert_eq!(lines, [(0, true), (2, true)]);
    // Without a provider the cached lenses show, then go after 30 seconds.
    workbench.update(cx, |workbench, _| drop(workbench.language_features.unregister(3)));
    show(&b, cx);
    show(&a, cx);
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.code_lenses.groups.len()), 2);
    cx.executor().advance_clock(Duration::from_secs(30));
    cx.run_until_parked();
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.code_lenses.groups.len()), 0);
}