Skip to content

Visual Studio Code, rebuilt in Rust

Rust
15.3 KB
Raw Blame
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::time::Duration;

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

use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::theme::load_theme;
use crate::workbench::Workbench;

/// The test's folder holding `a.ts` with `text` and `.vscode/settings.json` with `settings`, opened with the
/// language feature providers of `registrations` (method, arguments).
fn open<'a>(text: &str, settings: Value, registrations: &[(&str, Value)], cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>, PathBuf) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-model-events-{}-{}", std::process::id(), crate::test_name()));
    std::fs::create_dir_all(dir.join(".vscode")).unwrap();
    std::fs::write(dir.join("a.ts"), text).unwrap();
    std::fs::write(dir.join(".vscode/settings.json"), settings.to_string()).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 registrations: Vec<(String, Vec<Value>)> = registrations.iter().map(|(method, args)| (method.to_string(), args.as_array().unwrap().clone())).collect();
    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);
        for (method, args) in registrations {
            workbench.language_features.register(&method, args);
        }
        workbench.open_file(dir.join("a.ts"), true, window, cx);
        window.focus(&workbench.editor_focus, cx);
        workbench.inlay_hints_registrations_changed(cx);
        workbench.color_providers_changed(cx);
        workbench.linked_editing_reinitialize(false, cx);
        workbench
    });
    cx.update(|window, _| window.activate_window());
    cx.run_until_parked();
    (workbench, cx, receiver, dir)
}

/// Waits out every debounce, then answers each provider request sent so far; returns how many came per method.
fn answer(receiver: &Receiver<HostMessage>, cx: &mut VisualTestContext) -> Vec<String> {
    cx.executor().advance_clock(Duration::from_secs(5));
    cx.run_until_parked();
    let mut asked = Vec::new();
    for message in receiver.try_iter() {
        let answer = match message.method {
            "$provideCodeLenses" => json!({ "cacheId": 1, "lenses": [{ "cacheId": [1, 0], "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 2 }, "command": { "id": "lens.run", "title": "run" } }] }),
            "$provideCodeActions" => json!({ "cacheId": 1, "actions": [] }),
            "$provideSignatureHelp" => json!({ "id": 1, "signatures": [{ "label": "foo(a)", "parameters": [{ "label": "a" }] }], "activeSignature": 0, "activeParameter": 0 }),
            "$provideInlayHints" | "$provideDocumentColors" | "$provideLinkedEditingRanges" => Value::Null,
            _ => continue,
        };
        asked.push(message.method.to_owned());
        let _ = message.reply.expect("a call").send(Ok(answer));
    }
    cx.run_until_parked();
    asked
}

fn run(workbench: &gpui::Entity<Workbench>, command: &str, args: Vec<Value>, cx: &mut VisualTestContext) {
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(command, args, window, cx)));
    cx.run_until_parked();
}

/// codelensController.ts, inlayHintsController.ts, colorDetector.ts and links.ts listen to the code editor's
/// `onDidChangeModelContent`, which fires for a workspace edit of its model as for typing.
#[gpui::test]
fn a_workspace_edit_of_the_shown_model_asks_its_providers_again(cx: &mut TestAppContext) {
    let registrations = [
        ("$registerCodeLensSupport", json!([1, "*", 9])),
        ("$registerInlayHintsProvider", json!([2, "*", null, 2])),
        ("$registerDocumentColorProvider", json!([3, "*"])),
    ];
    let (workbench, cx, receiver, dir) = open("a\nb\n", json!({}), &registrations, cx);
    let mut first = answer(&receiver, cx);
    first.sort();
    assert_eq!(first, ["$provideCodeLenses", "$provideDocumentColors", "$provideInlayHints"]);
    let edit = json!([{ "resource": file_uri(&dir.join("a.ts")), "textEdit": { "range": { "startLineNumber": 2, "startColumn": 1, "endLineNumber": 2, "endColumn": 1 }, "text": "https://example.com " } }]);
    workbench.update(cx, |workbench, cx| workbench.apply_workspace_text_edits(&edit, &json!([]), files::operations::new_undo_group(), None, cx)).unwrap();
    let mut again = answer(&receiver, cx);
    again.sort();
    again.dedup();
    assert_eq!(again, ["$provideCodeLenses", "$provideDocumentColors", "$provideInlayHints"]);
    // The editor worker's link provider found the new URL.
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.links.list.len(), 1));
    std::fs::remove_dir_all(dir).unwrap();
}

/// codeActionModel.ts `CodeActionOracle`, parameterHintsModel.ts `onCursorChange`, linkedEditing.ts and
/// snippetController2.ts `_updateState` listen to `onDidChangeCursorPosition`, which a jump to the next snippet
/// placeholder and an Alt+click adding a cursor fire.
#[gpui::test]
fn a_cursor_move_wakes_the_cursor_listeners(cx: &mut TestAppContext) {
    let registrations = [
        ("$registerCodeActionSupport", json!([1, "*", {}, "test", "test.ext", false])),
        ("$registerSignatureHelpProvider", json!([2, "*", { "triggerCharacters": [], "retriggerCharacters": [] }])),
        ("$registerLinkedEditingRangeProvider", json!([3, "*"])),
    ];
    let (workbench, cx, receiver, dir) = open("foo\nbar\n", json!({ "editor.linkedEditing": true }), &registrations, cx);
    run(&workbench, "editor.action.insertSnippet", vec![json!({ "snippet": "x${1:y}z${2:w}$0" })], cx);
    run(&workbench, "editor.action.triggerParameterHints", vec![], cx);
    answer(&receiver, cx);
    workbench.update_in(cx, |workbench, window, _| assert_eq!(workbench.key_context(window)["parameterHintsVisible"], json!(true)));
    run(&workbench, "jumpToNextSnippetPlaceholder", vec![], cx);
    let mut asked = answer(&receiver, cx);
    asked.sort();
    asked.dedup();
    assert_eq!(asked, ["$provideCodeActions", "$provideLinkedEditingRanges", "$provideSignatureHelp"]);

    workbench.read_with(cx, |workbench, _| assert!(workbench.editors.active().unwrap().snippet_session.is_some()));
    workbench.update(cx, |workbench, cx| workbench.click_text(1, 0., alt(), false, 1, cx));
    workbench.read_with(cx, |workbench, _| assert!(workbench.editors.active().unwrap().snippet_session.is_none(), "a cursor left the placeholders"));
    std::fs::remove_dir_all(dir).unwrap();
}

fn alt() -> gpui::Modifiers {
    gpui::Modifiers { alt: true, ..Default::default() }
}

/// outputView.ts `onDidChangeCursorPosition`: a click (`CursorChangeReason.Explicit`) off the last line turns
/// auto scrolling off.
#[gpui::test]
fn a_click_in_the_output_view_locks_its_scroll(cx: &mut TestAppContext) {
    let (workbench, cx, _, dir) = open("", json!({}), &[], cx);
    let file = dir.join("exthost.log");
    std::fs::write(&file, "one\ntwo\n").unwrap();
    let request = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadLogger", method: "$registerLogger".into(), args: vec![json!({ "id": "exthost", "name": "Extension Host", "resource": file_uri(&file) })] };
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_host_request(request, window, cx)));
    run(&workbench, "workbench.action.output.toggleOutput", vec![], cx);
    workbench.update_in(cx, |workbench, window, cx| workbench.focus_group(crate::editor::PANEL_GROUP, window, cx));
    run(&workbench, "cursorBottom", vec![], cx);
    workbench.read_with(cx, |workbench, _| assert!(!workbench.output_view.scroll_lock));
    workbench.update(cx, |workbench, cx| workbench.click_text(0, 0., gpui::Modifiers::default(), false, 1, cx));
    workbench.read_with(cx, |workbench, _| assert!(workbench.output_view.scroll_lock));
    std::fs::remove_dir_all(dir).unwrap();
}

/// The one-character edit of each path, as the table test makes it.
#[derive(Clone, Copy, Debug)]
enum EditPath {
    Type,
    Command,
    Undo,
    BulkEditOfTheActiveEditor,
    BulkEditOfAnotherGroup,
    BulkEditOfAModelWithoutEditor,
    ReplaceAll,
    ReplaceTheLastMatch,
    HostEdit,
    SaveParticipant,
    Revert,
}

fn find_a_to_replace_with_x(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) {
    run(workbench, "actions.find", vec![], cx);
    workbench.update(cx, |workbench, _| {
        let viewport = workbench.editors.viewport;
        let editor = workbench.editors.active_mut().unwrap();
        let new = crate::editor::find::state::NewFindState { search_string: Some("a".into()), replace_string: Some("x".into()), ..Default::default() };
        workbench.find.controller.change(editor, viewport, new, false);
    });
}

fn insert_at_start(file: &Path, text: &str) -> Value {
    json!([{ "resource": file_uri(file), "textEdit": { "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 }, "text": text } }])
}

/// Every path tells the host first, then wakes the content listeners of the active code editor when it shows the
/// model (codelensController.ts, inlayHintsController.ts, colorDetector.ts) and none when it does not. The shown
/// editor's selection follows with the source cursor.ts gives it: coreCommands.ts `deleteRight`'s id, cursor.ts
/// `onModelContentChanged`'s for undo, findModel.ts `replaceAll`, saveParticipants.ts `insertFinalNewLine`.
#[gpui::test]
fn every_path_of_an_edit_tells_the_host_first_and_wakes_the_shown_editor(cx: &mut TestAppContext) {
    let table = [
        (EditPath::Type, true, Some("keyboard")),
        (EditPath::Command, true, Some("deleteRight")),
        (EditPath::Undo, true, Some("modelChange")),
        (EditPath::BulkEditOfTheActiveEditor, true, Some("modelChange")),
        (EditPath::BulkEditOfAnotherGroup, false, None),
        (EditPath::BulkEditOfAModelWithoutEditor, false, None),
        (EditPath::ReplaceAll, true, Some("replaceAll")),
        (EditPath::ReplaceTheLastMatch, true, Some("replace")),
        (EditPath::HostEdit, true, Some("MainThreadTextEditor")),
        (EditPath::SaveParticipant, true, Some("insertFinalNewLine")),
        (EditPath::Revert, true, Some("modelChange")),
    ];
    let registrations = [
        ("$registerCodeLensSupport", json!([1, "*", 9])),
        ("$registerInlayHintsProvider", json!([2, "*", null, 2])),
        ("$registerDocumentColorProvider", json!([3, "*"])),
    ];
    let providers = ["$provideCodeLenses", "$provideDocumentColors", "$provideInlayHints"];
    for (path, shown, source) in table {
        let (workbench, cx, receiver, dir) = open("a", json!({ "files.insertFinalNewline": true }), &registrations, cx);
        std::fs::write(dir.join("b.ts"), "b").unwrap();
        let a = dir.join("a.ts");
        match path {
            EditPath::Undo => run(&workbench, "type", vec![json!({ "text": "x" })], cx),
            EditPath::Revert => std::fs::write(&a, "ab").unwrap(),
            // findModel.ts `replace`: the first run selects the only match, the second replaces it. The code lens
            // answer comes first: asked after a find selection, the edit asks no lenses again (port/notes.md).
            EditPath::ReplaceTheLastMatch => {
                answer(&receiver, cx);
                find_a_to_replace_with_x(&workbench, cx);
                run(&workbench, "editor.action.replaceOne", vec![], cx);
            }
            EditPath::BulkEditOfAnotherGroup => {
                run(&workbench, "workbench.action.splitEditor", vec![], cx);
                workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join("b.ts"), true, window, cx));
            }
            _ => {}
        }
        answer(&receiver, cx);
        let edit_a = |workbench: &mut Workbench, cx: &mut gpui::Context<Workbench>| workbench.apply_workspace_text_edits(&insert_at_start(&a, "x"), &json!([]), files::operations::new_undo_group(), None, cx).unwrap();
        match path {
            EditPath::Type => run(&workbench, "type", vec![json!({ "text": "x" })], cx),
            EditPath::Command => run(&workbench, "deleteRight", vec![], cx),
            EditPath::Undo => run(&workbench, "undo", vec![], cx),
            EditPath::BulkEditOfTheActiveEditor | EditPath::BulkEditOfAnotherGroup => drop(workbench.update(cx, edit_a)),
            EditPath::BulkEditOfAModelWithoutEditor => drop(workbench.update(cx, |workbench, cx| workbench.apply_workspace_text_edits(&insert_at_start(&dir.join("b.ts"), "x"), &json!([]), files::operations::new_undo_group(), None, cx).unwrap())),
            EditPath::ReplaceAll => {
                find_a_to_replace_with_x(&workbench, cx);
                run(&workbench, "editor.action.replaceAll", vec![], cx);
            }
            EditPath::ReplaceTheLastMatch => run(&workbench, "editor.action.replaceOne", vec![], cx),
            EditPath::HostEdit => {
                let edits = json!([{ "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 }, "text": "x" }]);
                let version = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().text_model().version_id);
                workbench.update(cx, |workbench, cx| workbench.apply_host_edits(&json!(version), &edits, &json!({}), cx)).unwrap();
            }
            EditPath::SaveParticipant => run(&workbench, "workbench.action.files.save", vec![], cx),
            EditPath::Revert => run(&workbench, "workbench.action.files.revert", vec![], cx),
        }
        cx.executor().advance_clock(Duration::from_secs(5));
        cx.run_until_parked();
        let messages: Vec<HostMessage> = receiver.try_iter().collect();
        let methods: Vec<&str> = messages.iter().map(|message| message.method).collect();
        if let Some(source) = source {
            let mut after_change = messages.iter().skip_while(|message| message.method != "$acceptModelChanged");
            let selection = after_change.find(|message| message.method == "$acceptEditorPropertiesChanged").expect("the shown editor's selection");
            assert_eq!(selection.args[1]["selections"]["source"], source, "{path:?}");
        }
        let changed = methods.iter().position(|method| *method == "$acceptModelChanged");
        let first_request = methods.iter().position(|method| providers.contains(method));
        assert!(changed.is_some(), "{path:?}: no $acceptModelChanged in {methods:?}");
        assert!(first_request.is_none_or(|request| changed < Some(request)), "{path:?}: a provider was asked before the host heard the edit: {methods:?}");
        let mut asked: Vec<&str> = methods.iter().copied().filter(|method| providers.contains(method)).collect();
        asked.sort();
        asked.dedup();
        let expected: &[&str] = if shown { &providers } else { &[] };
        assert_eq!(asked, expected, "{path:?}");
        std::fs::remove_dir_all(dir).unwrap();
    }
}