Visual Studio Code, rebuilt in Rust
Rust
use std::path::Path;
use std::sync::mpsc::Receiver;
use exthost::scan::scan_extension;
use exthost::session::ForwardedRequest;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::{Value, json};
use crate::commands::Outcome;
use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::theme::load_theme;
use crate::workbench::Workbench;
const VIEW: &str = "test.tree";
fn workbench_with<'a>(name: &str, cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a 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();
let dir = std::env::temp_dir().join(format!("vsrustium-tree-view-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let manifest = json!({ "name": "trees", "publisher": "test", "version": "1.0.0", "engines": { "vscode": "*" },
"contributes": { "views": { "explorer": [{ "id": VIEW, "name": "Test Tree" }, { "id": "test.hidden", "name": "Hidden", "when": "never" }] } } });
std::fs::write(dir.join("package.json"), manifest.to_string()).unwrap();
let extension = scan_extension(&dir, false).unwrap();
let (sender, receiver) = std::sync::mpsc::channel();
let (workbench, cx) = cx.add_window_view(|_, cx| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx);
workbench.set_tree_views(&[extension]);
workbench
});
drop(workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("workbench.view.explorer", Vec::new(), window, cx)));
draw(cx);
receiver.try_iter().for_each(drop);
(workbench, cx, receiver)
}
fn request(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, method: &str, args: Value) -> Outcome {
let request = ForwardedRequest { req: 1, proxy: "MainThreadTreeViews", method: method.into(), args: args.as_array().unwrap().clone() };
let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx));
cx.run_until_parked();
outcome
}
/// The host messages sent since the last call, as `method(args)`; `$getChildren` is answered from `children`.
fn sent(receiver: &Receiver<HostMessage>, cx: &mut VisualTestContext, children: &[(Value, Value)]) -> Vec<String> {
let answer = |method: &str, args: &[Value]| match method {
"$getChildren" => children.iter().find(|(parents, _)| args.get(1) == Some(parents)).map_or(Value::Null, |(_, answer)| answer.clone()),
_ => Value::Null,
};
sent_with(receiver, cx, answer).into_iter().map(|(method, args)| format!("{method}({})", Value::Array(args))).collect()
}
/// The host messages sent since the last call, each request answered by `answer`.
fn sent_with(receiver: &Receiver<HostMessage>, cx: &mut VisualTestContext, answer: impl Fn(&str, &[Value]) -> Value) -> Vec<(&'static str, Vec<Value>)> {
draw(cx);
let mut sent = Vec::new();
for message in receiver.try_iter() {
if let Some(reply) = message.reply {
let _ = reply.send(Ok(answer(message.method, &message.args)));
}
sent.push((message.method, message.args));
}
draw(cx);
sent
}
/// The Explorer lays out its panes and the tree views sync their visibility while the window draws.
fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| drop(window.draw(cx)));
cx.run_until_parked();
}
fn item(handle: &str, parent: Option<&str>, state: u64) -> Value {
json!({ "handle": handle, "parentHandle": parent, "label": { "label": handle }, "collapsibleState": state })
}
fn rows(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<(String, usize)> {
workbench.read_with(cx, |workbench, _| workbench.tree_views.trees[VIEW].rows().into_iter().map(|(item, depth)| (item.handle.clone(), depth)).collect())
}
#[gpui::test]
fn a_collapsed_view_fetches_nothing_until_its_pane_expands(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = workbench_with("collapsed", cx);
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.shown_tree_views()), vec![VIEW]);
request(&workbench, cx, "$registerTreeViewDataProvider", json!([VIEW, { "showCollapseAll": false }]));
assert_eq!(sent(&receiver, cx, &[]), vec![format!("$hasResolve([\"{VIEW}\"])"), format!("$setVisible([\"{VIEW}\",false])")]);
request(&workbench, cx, "$refresh", json!([VIEW]));
assert_eq!(sent(&receiver, cx, &[]), Vec::<String>::new(), "treeView.ts: no tree, no fetch");
workbench.update(cx, |workbench, cx| workbench.expand_pane(crate::workbench::view_panes::PaneContainer::Explorer, VIEW, cx));
let roots = json!([[0, item("a", None, 1), item("b", None, 0)]]);
let messages = sent(&receiver, cx, &[(Value::Null, roots)]);
assert!(messages.contains(&format!("$activateByEvent([\"onView:{VIEW}\",0])")), "{messages:?}");
assert!(messages.contains(&format!("$setVisible([\"{VIEW}\",true])")), "{messages:?}");
assert!(messages.contains(&format!("$getChildren([\"{VIEW}\",null])")), "{messages:?}");
assert_eq!(rows(&workbench, cx), vec![("a".into(), 0), ("b".into(), 0)]);
workbench.update(cx, |workbench, cx| workbench.toggle_tree_item(VIEW, "a", cx));
let messages = sent(&receiver, cx, &[(json!(["a"]), json!([[0, item("a/1", Some("a"), 0)]]))]);
assert_eq!(messages, vec![format!("$setExpanded([\"{VIEW}\",\"a\",true])"), format!("$getChildren([\"{VIEW}\",[\"a\"]])")]);
assert_eq!(rows(&workbench, cx), vec![("a".into(), 0), ("a/1".into(), 1), ("b".into(), 0)]);
let renamed = json!([VIEW, { "b": { "handle": "b", "label": { "label": "~~B~~" }, "collapsibleState": 0 } }]);
request(&workbench, cx, "$refresh", renamed);
assert_eq!(sent(&receiver, cx, &[]), Vec::<String>::new(), "a changed item with its handle kept is not fetched again");
assert!(workbench.read_with(cx, |workbench, _| workbench.tree_views.trees[VIEW].items["b"].strikethrough()));
}
/// treeView.ts puts the tree in a ScrollableElement: the pointer over it shows its scrollbar.
#[gpui::test]
fn the_tree_shows_its_scrollbar_under_the_pointer(cx: &mut TestAppContext) {
let mut roots = vec![json!(0)];
roots.extend((0..50).map(|index| item(&format!("i{index}"), None, 0)));
let children = [(Value::Null, json!([roots]))];
let (workbench, cx, _) = shown_tree("scrollbar", json!({}), &children, false, cx);
let list = crate::workbench::list_scroll::ListId::Scrollable(VIEW);
let bounds = workbench.read_with(cx, |workbench, _| workbench.list_scroller(list).bounds());
cx.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::none());
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.list_hover(list).map(|(over, _)| over)), Some(true));
}
#[gpui::test]
fn reveal_opens_the_view_expands_the_parents_and_selects_the_item(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = workbench_with("reveal", cx);
request(&workbench, cx, "$registerTreeViewDataProvider", json!([VIEW, {}]));
sent(&receiver, cx, &[]);
let info = json!({ "item": item("a/1", Some("a"), 0), "parentChain": [item("a", None, 1)] });
let outcome = request(&workbench, cx, "$reveal", json!([VIEW, info, { "select": true, "focus": false, "expand": false }]));
let answers = [(Value::Null, json!([[0, item("a", None, 1)]])), (json!(["a"]), json!([[0, item("a/1", Some("a"), 0)]]))];
// The roots, then the parent's children, then the selection.
let mut messages = sent(&receiver, cx, &answers);
messages.extend(sent(&receiver, cx, &answers));
messages.extend(sent(&receiver, cx, &answers));
assert_eq!(messages.iter().filter(|message| message.starts_with("$getChildren")).count(), 2, "{messages:?}");
assert!(messages.contains(&format!("$setSelectionAndFocus([\"{VIEW}\",[\"a/1\"],\"a/1\"])")), "{messages:?}");
assert_eq!(rows(&workbench, cx), vec![("a".into(), 0), ("a/1".into(), 1)]);
let Outcome::Pending(mut reply) = outcome else { panic!("$reveal waits for the fetches") };
assert_eq!(reply.try_recv().unwrap(), Some(Ok(Value::Null)));
let hidden = request(&workbench, cx, "$reveal", json!(["test.hidden", info, {}]));
let Outcome::Pending(mut reply) = hidden else { panic!() };
cx.run_until_parked();
assert_eq!(reply.try_recv().unwrap(), Some(Ok(Value::Null)), "a view whose when is false has no tree to reveal in");
}
/// The tree view expanded, registered with `options`, its items fetched from `children` (by parents, as `sent`).
fn shown_tree<'a>(name: &str, options: Value, children: &[(Value, Value)], has_resolve: bool, cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>) {
let (workbench, cx, receiver) = workbench_with(name, cx);
workbench.update(cx, |workbench, cx| workbench.expand_pane(crate::workbench::view_panes::PaneContainer::Explorer, VIEW, cx));
request(&workbench, cx, "$registerTreeViewDataProvider", json!([VIEW, options]));
let answer = |method: &str, args: &[Value]| match method {
"$hasResolve" => json!(has_resolve),
"$getChildren" => children.iter().find(|(parents, _)| args[1] == *parents).map_or(Value::Null, |(_, answer)| answer.clone()),
_ => Value::Null,
};
for _ in 0..3 {
sent_with(&receiver, cx, answer);
}
(workbench, cx, receiver)
}
fn checkbox_item(handle: &str, parent: Option<&str>, state: u64, checked: bool) -> Value {
let mut item = item(handle, parent, state);
item["checkbox"] = json!({ "isChecked": checked });
item
}
/// checkbox.ts `TreeItemCheckbox`: a click toggles the box, cascades to the parent (`setCascadingCheckboxUpdates`)
/// and tells the host (`$changeCheckboxState`); the row is selected, but neither toggles nor runs its command.
#[gpui::test]
fn a_checkbox_click_sends_the_changed_states_and_selects_the_row(cx: &mut TestAppContext) {
let children = [(Value::Null, json!([[0, checkbox_item("a", None, 2, false)]])), (json!(["a"]), json!([[0, checkbox_item("a/1", Some("a"), 0, false), checkbox_item("a/2", Some("a"), 0, true)]]))];
let (workbench, cx, receiver) = shown_tree("checkbox", json!({}), &children, false, cx);
assert_eq!(rows(&workbench, cx), vec![("a".into(), 0), ("a/1".into(), 1), ("a/2".into(), 1)]);
let checkbox = cx.debug_bounds("tree-checkbox-a/1").expect("a/1 draws its checkbox").center();
cx.simulate_click(checkbox, gpui::Modifiers::none());
assert_eq!(sent(&receiver, cx, &[]), vec![
format!("$changeCheckboxState([\"{VIEW}\",[{{\"treeItemHandle\":\"a/1\",\"newState\":true}},{{\"treeItemHandle\":\"a\",\"newState\":true}}]])"),
format!("$setSelectionAndFocus([\"{VIEW}\",[\"a/1\"],\"a/1\"])"),
]);
let checked = workbench.read_with(cx, |workbench, _| ["a", "a/1", "a/2"].map(|handle| workbench.tree_views.trees[VIEW].items[handle].checked()));
assert_eq!(checked, [Some(true); 3]);
let parent = cx.debug_bounds("tree-row-a").unwrap().center();
cx.simulate_click(parent, gpui::Modifiers::none());
assert_eq!(sent(&receiver, cx, &[]), vec![format!("$setSelectionAndFocus([\"{VIEW}\",[\"a\"],\"a\"])")], "an item with a checkbox expands by its twistie only");
}
/// views.ts `ResolvableTreeItem`: the hover of an item without a tooltip shows "Loading..." while `$resolve` runs,
/// then the resolved tooltip; a click on an item without a command resolves it and runs the resolved one.
#[gpui::test]
fn an_item_resolves_its_tooltip_on_hover_and_its_command_on_click(cx: &mut TestAppContext) {
let roots = [(Value::Null, json!([[0, item("a", None, 0), item("b", None, 0)]]))];
let (workbench, cx, receiver) = shown_tree("resolve", json!({}), &roots, true, cx);
let ran = std::rc::Rc::new(std::cell::Cell::new(false));
let flag = ran.clone();
workbench.update(cx, |workbench, _| {
workbench.commands.register("test.resolved", move |_, _, _, _| {
flag.set(true);
Outcome::done()
})
});
let shown = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned));
let (a, b) = (cx.debug_bounds("tree-row-a").unwrap().center(), cx.debug_bounds("tree-row-b").unwrap().center());
cx.simulate_mouse_move(a, None, gpui::Modifiers::none());
cx.executor().advance_clock(std::time::Duration::from_millis(1500));
cx.run_until_parked();
assert_eq!(shown(cx).as_deref(), Some("Loading..."));
let resolved = sent_with(&receiver, cx, |method, _| if method == "$resolve" { json!({ "handle": "a", "tooltip": "Resolved A" }) } else { Value::Null });
assert_eq!(resolved, vec![("$resolve", vec![json!(VIEW), json!("a")])]);
assert_eq!(shown(cx).as_deref(), Some("Resolved A"));
cx.simulate_click(b, gpui::Modifiers::none());
let messages = sent_with(&receiver, cx, |method, _| if method == "$resolve" { json!({ "handle": "b", "command": { "id": "test.resolved" } }) } else { Value::Null });
assert!(messages.contains(&("$resolve", vec![json!(VIEW), json!("b")])), "{messages:?}");
assert!(ran.get(), "resolveCommand runs the command $resolve gave");
}
/// treeView.ts `CustomTreeViewDragAndDrop`: a row dragged onto another asks the host for the drag's data
/// (`$handleDrag`), then drops the tree's own type with the source items and that data on the target (`$handleDrop`).
#[gpui::test]
fn a_row_dragged_onto_another_sends_handle_drag_then_handle_drop(cx: &mut TestAppContext) {
let roots = [(Value::Null, json!([[0, item("a", None, 0), item("b", None, 0)]]))];
let tree_mime = format!("application/vnd.code.tree.{VIEW}");
let options = json!({ "hasHandleDrag": true, "hasHandleDrop": true, "dropMimeTypes": [tree_mime], "dragMimeTypes": ["text/x-test"] });
let (_workbench, cx, receiver) = shown_tree("drag", options, &roots, false, cx);
let (a, b) = (cx.debug_bounds("tree-row-a").unwrap().center(), cx.debug_bounds("tree-row-b").unwrap().center());
cx.simulate_mouse_down(a, gpui::MouseButton::Left, gpui::Modifiers::none());
cx.simulate_mouse_move(a + gpui::point(gpui::px(0.), gpui::px(5.)), gpui::MouseButton::Left, gpui::Modifiers::none());
let transfer = json!({ "items": [["text/x-test", { "id": "1", "asString": "payload" }]] });
let dragged = sent_with(&receiver, cx, |method, _| if method == "$handleDrag" { transfer.clone() } else { Value::Null });
let [("$handleDrag", args)] = dragged.as_slice() else { panic!("{dragged:?}") };
assert_eq!(args[..2], [json!(VIEW), json!(["a"])]);
let uuid = args[2].clone();
cx.simulate_mouse_move(b, gpui::MouseButton::Left, gpui::Modifiers::none());
cx.simulate_mouse_up(b, gpui::MouseButton::Left, gpui::Modifiers::none());
let dropped = sent_with(&receiver, cx, |_, _| Value::Null);
let [("$handleDrop", args)] = dropped.as_slice() else { panic!("{dropped:?}") };
let items: Vec<(&str, &str)> = args[2]["items"].as_array().unwrap().iter().map(|item| (item[0].as_str().unwrap(), item[1]["asString"].as_str().unwrap())).collect();
assert_eq!(items, [(tree_mime.as_str(), format!("{{\"id\":\"{VIEW}\",\"itemHandles\":[\"a\"]}}").as_str()), ("text/x-test", "payload")]);
assert_eq!([&args[0], &args[3], &args[5], &args[6], &args[7]], [&json!(VIEW), &json!("b"), &uuid, &json!(VIEW), &json!(["a"])]);
}
#[test]
fn a_markdown_message_turns_lone_links_into_buttons() {
use super::MessageLine::*;
let lines = super::message_lines("Intro [docs](https://e.com)\n[$(github) Publish](command:a.b \"Tip\")\n[Other](command:c)\n\n[Last](command:d)");
let button = |label: &str, href: &str, title: Option<&str>, secondary| Button { label: label.into(), href: href.into(), title: title.map(str::to_owned), secondary };
assert_eq!(lines, vec"), button("$(github) Publish", "command:a.b", Some("Tip"), false), button("Other", "command:c", None, true), Markdown(""), button("Last", "command:d", None, false)]);
}
#[gpui::test]
fn a_markdown_message_draws_its_button_icons_and_a_string_one_stays_text(cx: &mut TestAppContext) {
let (workbench, cx, _receiver) = workbench_with("message", cx);
workbench.update(cx, |workbench, cx| workbench.expand_pane(crate::workbench::view_panes::PaneContainer::Explorer, VIEW, cx));
request(&workbench, cx, "$setMessage", json!([VIEW, "$(github) plain"]));
draw(cx);
assert!(cx.debug_bounds("codicon-github").is_none(), "treeView.ts sets a string message as textContent");
request(&workbench, cx, "$setMessage", json!([VIEW, { "value": "Publish it.\n[$(github) Publish](command:github.publish)", "supportThemeIcons": false }]));
draw(cx);
assert!(cx.debug_bounds("codicon-github").is_some());
request(&workbench, cx, "$setMessage", json!([VIEW, { "value": "$(info) Read the docs.", "supportThemeIcons": true }]));
draw(cx);
assert!(cx.debug_bounds("codicon-info").is_some(), "markdownRenderer.ts renders a paragraph's theme icons");
}
/// treeView.ts `updateMessage`: a view without a data provider shows `noDataProviderMessage`, an empty message none.
#[gpui::test]
fn a_view_without_a_provider_shows_the_no_data_provider_message(cx: &mut TestAppContext) {
let (workbench, cx, _receiver) = workbench_with("no-provider", cx);
workbench.update(cx, |workbench, cx| workbench.expand_pane(crate::workbench::view_panes::PaneContainer::Explorer, VIEW, cx));
draw(cx);
assert!(cx.debug_bounds("tree-message-test.tree").is_some());
request(&workbench, cx, "$registerTreeViewDataProvider", json!([VIEW, {}]));
request(&workbench, cx, "$setMessage", json!([VIEW, ""]));
draw(cx);
assert!(cx.debug_bounds("tree-message-test.tree").is_none());
}
/// viewsExtensionPoint.ts `isValidViewsContainer`, `addViews` and `isValidViewDescriptors` collector messages.
#[test]
fn invalid_views_and_view_containers_are_extension_messages() {
use crate::notifications::Severity::{Error, Warning};
let extension = |id: &str, contributes: Value| exthost::scan::ScannedExtension { id: id.into(), location: "/x".into(), description: json!({ "contributes": contributes }) };
let first = extension("test.view-messages", json!({
"viewsContainers": {
"activitybar": [{ "id": "good", "title": "Good", "icon": "$(beaker)" }],
"panel": [{ "id": "bad id", "title": "Bad", "icon": "x.svg" }],
"secondarySidebar": [{ "id": "untitled", "title": " ", "icon": "x.svg" }],
"other": {},
},
"views": {
"good": [{ "id": "test.one", "name": "One" }, { "id": "test.one", "name": "Again" }, { "id": "test.web", "name": "Web", "type": "webview" }, { "id": "test.odd", "name": "Odd", "type": "grid" }],
"untitled": [{ "id": "test.two", "name": "Two" }],
"missing": [{ "id": "test.moved", "name": "Moved" }],
"explorer": [{ "id": "outline", "name": "Outline" }],
"test": [{ "id": "test.three", "name": 3 }],
"scm": [{ "id": "test.four", "name": "Four", "visibility": "open" }],
"debug": { "id": "test.five" },
"remote": [{ "id": "test.remote", "name": "Remote" }],
},
}));
let second = extension("test.view-messages-2", json!({ "views": { "explorer": [{ "id": "test.one", "name": "Elsewhere" }, { "id": "test.seven", "name": "Seven" }], "scm": [{ "id": "test.six", "name": "Six", "when": true }] } }));
let views = super::contributed_views(&[first, second]);
let shown: Vec<(&str, &str)> = views.iter().map(|view| (view.id, view.container.as_str())).collect();
assert_eq!(shown, [("test.one", "good"), ("test.web", "good"), ("test.two", "untitled"), ("test.moved", "explorer"), ("test.seven", "explorer")]);
let messages = crate::perf::messages;
let expected = |messages: &[(crate::notifications::Severity, &str)]| messages.iter().map(|(severity, message)| (*severity, message.to_string())).collect::<Vec<_>>();
assert_eq!(messages("test.view-messages"), expected(&[
(Error, "property `id` is mandatory and must be of type `string` with non-empty value. Only alphanumeric characters, '_', and '-' are allowed."),
(Warning, "property `title` is mandatory and must be of type `string` with non-empty value"),
(Error, "views containers must be an array"),
(Error, "Cannot register multiple views with same id `test.one`"),
(Error, "Unknown view type `grid`."),
(Warning, "View container 'missing' does not exist and all views registered to it will be added to 'Explorer'."),
(Error, "A view with id `outline` is already registered."),
(Error, "property `name` is mandatory and must be of type `string`"),
(Error, "property `visibility` can be omitted or must be one of visible, hidden, collapsed"),
(Error, "views must be an array"),
(Warning, "View container 'remote' requires 'enabledApiProposals: [\"contribViewsRemote\"]' to be added to 'Remote'."),
]));
assert_eq!(messages("test.view-messages-2"), expected(&[
(Error, "Cannot register multiple views with same id `test.one`"),
(Error, "property `when` can be omitted or must be of type `string`"),
]));
}