Visual Studio Code, rebuilt in Rust
Rust
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
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 serde_json::json;
use super::*;
use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::theme::load_theme;
const VIEW_TYPE: &str = "test.edit";
fn scratch() -> PathBuf {
static MADE: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!("vsrustium-custom-documents-{}-{}", std::process::id(), MADE.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(dir.join("folder")).unwrap();
std::fs::create_dir_all(dir.join("user/User")).unwrap();
std::fs::write(dir.join("folder/a.bin"), "a").unwrap();
dir
}
/// A window on `<dir>/folder` with its backups in `<dir>/user` and the `test.edit` provider registered.
fn open<'a>(cx: &'a mut TestAppContext, dir: &Path) -> (gpui::Entity<Workbench>, Receiver<HostMessage>, &'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();
let workspace = config::workspace::Workspace::folder(dir.join("folder"));
let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("user/User"), Some(workspace.clone()))));
let (sender, receiver) = std::sync::mpsc::channel();
let user_data = dir.join("user");
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.start_backups(&user_data, None, window, cx);
workbench
});
cx.run_until_parked();
(workbench, receiver, cx)
}
fn register_provider(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) {
let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });
let args = [extension, json!(VIEW_TYPE), json!({}), json!({}), json!(false), json!(false)];
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_custom_editors_request("$registerCustomEditorProvider", &args, window, cx)));
cx.run_until_parked();
}
fn resource(dir: &Path) -> Value {
Uri::file(&dir.join("folder/a.bin").to_string_lossy()).to_json()
}
/// The next message to `method`, the ones before it dropped (their calls cancelled).
fn next(receiver: &Receiver<HostMessage>, method: &str) -> HostMessage {
loop {
let message = receiver.try_recv().unwrap_or_else(|_| panic!("no {method}"));
if message.method == method {
return message;
}
}
}
fn answer(message: HostMessage, value: Value, cx: &mut VisualTestContext) {
let _ = message.reply.expect("a call").send(Ok(value));
cx.run_until_parked();
}
fn run(workbench: &gpui::Entity<Workbench>, command: &str, cx: &mut VisualTestContext) {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(command, Vec::new(), window, cx)));
cx.run_until_parked();
}
fn host_event(workbench: &gpui::Entity<Workbench>, method: &str, args: Vec<Value>, cx: &mut VisualTestContext) {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_custom_editors_request(method, &args, window, cx)));
cx.run_until_parked();
}
fn active_dirty(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> bool {
workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().is_dirty())
}
/// Opens a.bin in the editable `test.edit` editor: the host creates the document and resolves the webview.
fn open_document(workbench: &gpui::Entity<Workbench>, receiver: &Receiver<HostMessage>, dir: &Path, cx: &mut VisualTestContext) {
let resource = resource(dir);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.open_with_resolver(&resource, Some(VIEW_TYPE), json!({ "pinned": true }), window, cx)));
cx.run_until_parked();
answer(next(receiver, "$createCustomDocument"), json!({ "editable": true }), cx);
answer(next(receiver, "$resolveCustomEditor"), Value::Null, cx);
}
#[gpui::test]
fn edits_undo_redo_save_and_revert_through_the_host(cx: &mut TestAppContext) {
let dir = scratch();
let (workbench, receiver, cx) = open(cx, &dir);
register_provider(&workbench, cx);
open_document(&workbench, &receiver, &dir, cx);
let resource = resource(&dir);
assert!(!active_dirty(&workbench, cx));
// As the host revives and sends it: `$mid` and `external` besides the parts the workbench sent.
let mut host_resource = resource.clone();
host_resource["$mid"] = json!(1);
host_resource["external"] = json!(format!("file://{}", dir.join("folder/a.bin").display()));
host_event(&workbench, "$onDidEdit", vec![host_resource, json!(VIEW_TYPE), json!(1), json!("Edit")], cx);
assert!(active_dirty(&workbench, cx));
run(&workbench, "undo", cx);
let undo = next(&receiver, "$undo");
assert_eq!(undo.args[2..], [json!(1), json!(false)]);
assert!(!active_dirty(&workbench, cx));
// The element runs until the extension answers; a redo before that cannot take its lock.
answer(undo, Value::Null, cx);
run(&workbench, "redo", cx);
let redo = next(&receiver, "$redo");
assert_eq!(redo.args[2..], [json!(1), json!(true)]);
answer(redo, Value::Null, cx);
assert!(active_dirty(&workbench, cx));
run(&workbench, "workbench.action.files.save", cx);
answer(next(&receiver, "$onSave"), Value::Null, cx);
assert!(!active_dirty(&workbench, cx));
host_event(&workbench, "$onDidEdit", vec![resource.clone(), json!(VIEW_TYPE), json!(2), json!("Edit")], cx);
run(&workbench, "undo", cx);
answer(next(&receiver, "$undo"), Value::Null, cx);
// A new edit drops the undone one.
host_event(&workbench, "$onDidEdit", vec![resource.clone(), json!(VIEW_TYPE), json!(3), json!("Edit")], cx);
assert_eq!(next(&receiver, "$disposeEdits").args[2], json!([2]));
assert!(active_dirty(&workbench, cx));
run(&workbench, "workbench.action.files.revert", cx);
next(&receiver, "$revert");
assert_eq!(next(&receiver, "$disposeEdits").args[2], json!([3]));
assert!(!active_dirty(&workbench, cx));
host_event(&workbench, "$onContentChange", vec![resource, json!(VIEW_TYPE)], cx);
assert!(active_dirty(&workbench, cx));
let _ = std::fs::remove_dir_all(dir);
}
/// mainThreadCustomEditors.ts `MainThreadCustomEditorModel.dispose`: `removeElements(this.resource)`.
#[gpui::test]
fn a_disposed_document_drops_its_undo_stack(cx: &mut TestAppContext) {
let dir = scratch();
let (workbench, receiver, cx) = open(cx, &dir);
register_provider(&workbench, cx);
open_document(&workbench, &receiver, &dir, cx);
let resource = resource(&dir);
host_event(&workbench, "$onDidEdit", vec![resource.clone(), json!(VIEW_TYPE), json!(1), json!("Edit")], cx);
run(&workbench, "workbench.action.files.save", cx);
answer(next(&receiver, "$onSave"), Value::Null, cx);
let key = crate::notebook::uri_string(&resource);
let has_elements = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.undo_redo.borrow().has_elements(&key));
assert!(has_elements(cx));
run(&workbench, "workbench.action.closeActiveEditor", cx);
next(&receiver, "$disposeCustomDocument");
assert!(!has_elements(cx));
let _ = std::fs::remove_dir_all(dir);
}
#[gpui::test]
fn a_dirty_document_backs_up_and_opens_from_its_backup(cx: &mut TestAppContext) {
let dir = scratch();
let resource = resource(&dir);
{
let (workbench, receiver, cx) = open(cx, &dir);
register_provider(&workbench, cx);
open_document(&workbench, &receiver, &dir, cx);
host_event(&workbench, "$onDidEdit", vec![resource.clone(), json!(VIEW_TYPE), json!(1), json!("Edit")], cx);
cx.executor().advance_clock(std::time::Duration::from_millis(1000));
cx.run_until_parked();
let backup = next(&receiver, "$backup");
assert_eq!(backup.args[..2], [resource.clone(), json!(VIEW_TYPE)]);
answer(backup, json!("backup-7"), cx);
cx.run_until_parked();
}
let home = std::fs::read_dir(dir.join("user/Backups")).unwrap().filter_map(Result::ok).find(|entry| entry.path().is_dir()).unwrap().path();
let backups = backups::list(&home);
assert_eq!(backups.len(), 1);
let backup = backups::resolve(&backups[0]).unwrap();
assert_eq!(backup.resource, working_copy_uri(&resource, VIEW_TYPE).unwrap());
assert_eq!((backup.meta.as_ref().unwrap()["backupId"].clone(), backup.content), (json!("backup-7"), Vec::new()));
let (workbench, receiver, cx) = open(cx, &dir);
register_provider(&workbench, cx);
let create = next(&receiver, "$createCustomDocument");
assert_eq!(create.args[..3], [resource.clone(), json!(VIEW_TYPE), json!("backup-7")]);
answer(create, json!({ "editable": true }), cx);
assert!(workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().any(|editor| editor.is_dirty())));
// Reverting the restored document drops its backup.
workbench.update_in(cx, |workbench, _, cx| {
let index = workbench.editors.editors.iter().position(|editor| editor.is_dirty()).unwrap();
workbench.editors.activate(index);
workbench.editors_changed(cx);
});
run(&workbench, "workbench.action.files.revert", cx);
assert!(backups::list(&home).is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn working_copy_uri_is_the_view_type_and_the_utf16_base64_of_the_resource() {
let resource = json!({ "scheme": "file", "path": "/a b.bin" });
let uri = working_copy_uri(&resource, "my.view type").unwrap();
assert_eq!((uri.scheme.as_str(), uri.authority.as_str()), (CUSTOM_EDITOR_SCHEME, "my-view-type"));
// btoa(toBinary('file:///a b.bin')): UTF-16LE bytes of each code unit.
assert_eq!(uri.path, "/ZgBpAGwAZQA6AC8ALwAvAGEAIABiAC4AYgBpAG4A");
assert_eq!(uri.query, r#"{"$mid":1,"path":"/a b.bin","scheme":"file"}"#);
}
/// editorResolverService.ts `mergeEditorAssociationSettings`: of two globs of one length that match, the
/// workspace's comes before the user's.
#[gpui::test]
fn a_workspace_association_wins_over_a_user_one_of_the_same_length(cx: &mut TestAppContext) {
let dir = scratch();
std::fs::write(dir.join("user/User/settings.json"), r#"{ "workbench.editorAssociations": { "a.bi?": "test.other" } }"#).unwrap();
std::fs::create_dir_all(dir.join("folder/.vscode")).unwrap();
std::fs::write(dir.join("folder/.vscode/settings.json"), r#"{ "workbench.editorAssociations": { "*.bin": "test.edit" } }"#).unwrap();
let (workbench, _receiver, cx) = open(cx, &dir);
let editor = workbench.read_with(cx, |workbench, _| workbench.custom_editor_for("file", &dir.join("folder/a.bin")));
assert_eq!(editor.as_deref(), Some(VIEW_TYPE));
let _ = std::fs::remove_dir_all(dir);
}
/// editorResolverService.ts `moveExistingEditorForResource` and customEditors.ts `singlePerResource`: opening a
/// custom document open in another group moves its editor here, or with `supportsMultipleEditorsPerDocument` opens
/// a second one; as tab schemes of the first group, then of the active second.
fn tabs_after_opening_in_a_second_group(multiple: bool, cx: &mut TestAppContext) -> (Vec<String>, Vec<String>) {
let dir = scratch();
std::fs::write(dir.join("folder/b.txt"), "b").unwrap();
let (workbench, _receiver, cx) = open(cx, &dir);
let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });
let args = [extension, json!(VIEW_TYPE), json!({}), json!({}), json!(multiple), json!(false)];
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_custom_editors_request("$registerCustomEditorProvider", &args, window, cx)));
let open_a = |cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.open_with_resolver(&resource(&dir), Some(VIEW_TYPE), json!({ "pinned": true }), window, cx)));
cx.run_until_parked();
};
open_a(cx);
workbench.update_in(cx, |workbench, window, cx| {
workbench.open_file(dir.join("folder/b.txt"), true, window, cx);
workbench.execute_command("workbench.action.splitEditorRight", Vec::new(), window, cx);
});
cx.run_until_parked();
open_a(cx);
let tabs = workbench.read_with(cx, |workbench, _| {
let groups = workbench.groups_in_grid_order();
assert_eq!(workbench.editors.id, groups[1], "the second group stays active");
let schemes = |group| workbench.editors.group_tabs(group).0.iter().map(|editor| editor.document().scheme.clone()).collect::<Vec<_>>();
(schemes(groups[0]), schemes(groups[1]))
});
let _ = std::fs::remove_dir_all(dir);
tabs
}
#[gpui::test]
fn a_custom_document_open_in_another_group_moves_to_the_active_one(cx: &mut TestAppContext) {
let (first, second) = tabs_after_opening_in_a_second_group(false, cx);
assert_eq!((first, second), (vec!["file".to_owned()], vec!["file".to_owned(), WEBVIEW_PANEL_SCHEME.to_owned()]));
}
#[gpui::test]
fn a_custom_document_with_multiple_editors_opens_one_more_in_the_active_group(cx: &mut TestAppContext) {
let (first, second) = tabs_after_opening_in_a_second_group(true, cx);
assert_eq!((first, second), (vec![WEBVIEW_PANEL_SCHEME.to_owned(), "file".to_owned()], vec!["file".to_owned(), WEBVIEW_PANEL_SCHEME.to_owned()]));
}
/// customEditorInput.ts: each editor of a custom text editor's resource has a webview of its own, the one opened in
/// another group and the copy a split makes.
#[gpui::test]
fn each_group_s_custom_text_editor_has_its_own_webview(cx: &mut TestAppContext) {
let dir = scratch();
std::fs::write(dir.join("folder/b.txt"), "b").unwrap();
let (workbench, receiver, cx) = open(cx, &dir);
let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });
let args = [extension, json!("test.text"), json!({}), json!({ "supportsMove": false }), json!(false)];
let first = workbench.update_in(cx, |workbench, window, cx| {
drop(workbench.handle_custom_editors_request("$registerTextEditorProvider", &args, window, cx));
workbench.open_file(dir.join("folder/b.txt"), true, window, cx);
let first = workbench.editors.id;
workbench.execute_command("workbench.action.splitEditorRight", Vec::new(), window, cx);
first
});
cx.run_until_parked();
let open_a = |cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.open_with_resolver(&resource(&dir), Some("test.text"), json!({ "pinned": true }), window, cx)));
cx.run_until_parked();
};
let mut resolved = Vec::new();
let mut resolve = |cx: &mut VisualTestContext| {
let message = next(&receiver, "$resolveCustomEditor");
resolved.push(message.args[1].clone());
answer(message, Value::Null, cx);
};
open_a(cx);
resolve(cx);
run(&workbench, "workbench.action.splitEditorRight", cx);
resolve(cx);
workbench.update_in(cx, |workbench, window, cx| workbench.focus_group(first, window, cx));
open_a(cx);
resolve(cx);
let shown = workbench.read_with(cx, |workbench, _| {
let groups = workbench.groups_in_grid_order();
let active = |group| {
let (editors, active) = workbench.editors.group_tabs(group);
workbench.custom_editor_over(&editors[active.unwrap()]).map(|panel| json!(panel.handle))
};
groups.into_iter().map(active).collect::<Vec<_>>()
});
assert_eq!(resolved, [json!("custom-editor-1"), json!("custom-editor-2"), json!("custom-editor-3")]);
assert_eq!(shown, [Some(json!("custom-editor-3")), Some(json!("custom-editor-1")), Some(json!("custom-editor-2"))]);
let _ = std::fs::remove_dir_all(dir);
}
/// mainThreadCustomEditors.ts `resolveWebview` passes `editorGroupToColumn` of the editor's group; a copy into a new
/// window (`copyEditorToNewWindow`) gets a webview of its own, like a split.
#[gpui::test]
fn custom_text_editors_resolve_in_their_group_s_column(cx: &mut TestAppContext) {
let dir = scratch();
let (workbench, receiver, cx) = open(cx, &dir);
let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });
let args = [extension, json!("test.text"), json!({}), json!({ "supportsMove": false }), json!(false)];
workbench.update_in(cx, |workbench, window, cx| {
drop(workbench.handle_custom_editors_request("$registerTextEditorProvider", &args, window, cx));
drop(workbench.open_with_resolver(&resource(&dir), Some("test.text"), json!({ "pinned": true }), window, cx));
});
cx.run_until_parked();
let mut resolved = Vec::new();
let mut resolve = |cx: &mut VisualTestContext| {
let message = next(&receiver, "$resolveCustomEditor");
resolved.push((message.args[1].clone(), message.args[4].clone()));
answer(message, Value::Null, cx);
};
resolve(cx);
run(&workbench, "workbench.action.splitEditorRight", cx);
resolve(cx);
run(&workbench, "workbench.action.copyEditorToNewWindow", cx);
resolve(cx);
let expected = [(json!("custom-editor-1"), json!(0)), (json!("custom-editor-2"), json!(1)), (json!("custom-editor-3"), json!(2))];
assert_eq!(resolved, expected);
let _ = std::fs::remove_dir_all(dir);
}
/// editorResolverService.ts `doHandleConflictingDefaults`: two default editors for a.bin and no association warn once;
/// closing the warning keeps the first and stores the editors for `*.bin`, so the next open does not ask.
#[gpui::test]
fn two_default_editors_for_a_resource_ask_once_which_to_keep(cx: &mut TestAppContext) {
let dir = scratch();
let (workbench, _receiver, cx) = open(cx, &dir);
register_provider(&workbench, cx);
let editors = json!({ "displayName": "Test", "contributes": { "customEditors": [
{ "viewType": VIEW_TYPE, "displayName": "Test Edit", "selector": [{ "filenamePattern": "*.bin" }] },
{ "viewType": "test.other", "displayName": "Test Other", "selector": [{ "filenamePattern": "*.bin" }] },
] } });
workbench.update(cx, |workbench, _| workbench.extensions.push(exthost::scan::ScannedExtension { id: "port.test".into(), location: PathBuf::new(), description: editors }));
let warnings = |cx: &mut VisualTestContext| {
workbench.read_with(cx, |workbench, _| {
let items = workbench.notifications.model.items.iter().filter(|item| item.message.raw == "There are multiple default editors available for the resource.");
items.map(|item| (item.key, item.primary.iter().map(|action| action.label.clone()).collect::<Vec<_>>())).collect::<Vec<_>>()
})
};
let open_a = |cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.open_with_resolver(&resource(&dir), None, json!({}), window, cx)));
cx.run_until_parked();
};
open_a(cx);
let shown = warnings(cx);
assert_eq!(shown.iter().map(|(_, labels)| labels.clone()).collect::<Vec<_>>(), [["Configure Default", "Keep Test Edit"]]);
workbench.update_in(cx, |workbench, window, cx| workbench.close_notification(shown[0].0, window, cx));
cx.run_until_parked();
let stored = workbench.read_with(cx, |workbench, _| workbench.profile_storage.lock().unwrap().get("editorOverrideService.conflictingDefaults").map(str::to_owned));
assert_eq!(stored.as_deref(), Some(r#"{"*.bin":["test.edit","test.other","default"]}"#));
open_a(cx);
assert!(warnings(cx).is_empty());
let _ = std::fs::remove_dir_all(dir);
}
/// customEditors.ts `createDiffEditorInput`: a text custom editor that supports inline diffs resolves the diff in one
/// webview (`$resolveCustomEditorInlineDiff`); Reopen as Text (`ReOpenInTextEditorAction`) turns it into the text diff.
#[gpui::test]
fn reopen_as_text_turns_an_inline_custom_diff_into_the_text_diff(cx: &mut TestAppContext) {
let dir = scratch();
std::fs::write(dir.join("folder/a.txt"), "a").unwrap();
std::fs::write(dir.join("folder/b.txt"), "b").unwrap();
let (workbench, receiver, cx) = open(cx, &dir);
let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });
let args = [extension, json!("test.text"), json!({}), json!({ "supportsInlineDiff": true }), json!(false)];
let side = |name: &str| crate::diff_editor::Side { scheme: "file".into(), path: dir.join("folder").join(name) };
let modified = Uri::file(&dir.join("folder/b.txt").to_string_lossy()).to_json();
workbench.update_in(cx, |workbench, window, cx| {
drop(workbench.handle_custom_editors_request("$registerTextEditorProvider", &args, window, cx));
drop(workbench.open_custom_editor("test.text".into(), modified, Some((side("a.txt"), None)), json!({}), window, cx));
});
cx.run_until_parked();
let message = next(&receiver, "$resolveCustomEditorInlineDiff");
answer(message, Value::Null, cx);
let shown = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| {
let diff = workbench.editors.active_diff().expect("an active diff");
(diff.custom.as_ref().map(|custom| (custom.view_type.clone(), custom.inline)), diff.name(), workbench.active_custom_editor_text_diff())
});
assert_eq!(shown(cx), (Some(("test.text".to_owned(), true)), "a.txt - b.txt".to_owned(), true));
run(&workbench, "workbench.action.reopenTextEditor", cx);
assert_eq!(shown(cx), (None, "a.txt \u{2194} b.txt".to_owned(), false));
let _ = std::fs::remove_dir_all(dir);
}
/// editor.contribution.ts Reopen as Text has `enableInModalMode`: a custom diff in the modal part shows it in the header.
#[gpui::test]
fn the_modal_header_of_a_custom_diff_offers_reopen_as_text(cx: &mut TestAppContext) {
let dir = scratch();
std::fs::write(dir.join("folder/a.txt"), "a").unwrap();
std::fs::write(dir.join("folder/b.txt"), "b").unwrap();
let (workbench, receiver, cx) = open(cx, &dir);
let extension = json!({ "id": "port.test", "location": { "scheme": "file", "path": "/ext" } });
let args = [extension, json!("test.text"), json!({}), json!({ "supportsInlineDiff": true }), json!(false)];
let side = |name: &str| crate::diff_editor::Side { scheme: "file".into(), path: dir.join("folder").join(name) };
let modified = Uri::file(&dir.join("folder/b.txt").to_string_lossy()).to_json();
workbench.update_in(cx, |workbench, window, cx| {
workbench.update_setting("workbench.editor.useModal", json!("all"));
drop(workbench.handle_custom_editors_request("$registerTextEditorProvider", &args, window, cx));
drop(workbench.open_custom_editor("test.text".into(), modified, Some((side("a.txt"), None)), json!({}), window, cx));
});
cx.run_until_parked();
answer(next(&receiver, "$resolveCustomEditorInlineDiff"), Value::Null, cx);
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editors.id), crate::editor::MODAL_GROUP);
assert!(cx.debug_bounds("modal-editor-action-workbench.action.reopenTextEditor").is_some());
let _ = std::fs::remove_dir_all(dir);
}