Visual Studio Code, rebuilt in Rust
Rust
//! debugVisualizers.ts `DebugVisualizerService` with mainThreadDebugService.ts's visualizer handlers, debugViewModel.ts's
//! visualized expressions and variablesView.ts's visualizer actions and `VisualizedVariableRenderer` rows.
use std::collections::{HashMap, HashSet};
use gpui::{ClickEvent, Context, MouseButton, Rgba, Window, div, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::debug_service::{answer, on_workbench};
use super::debug_view::{EXPRESSION_FONT, EXPRESSION_FONT_SIZE, Editing};
use super::hover::{HoverContent, HoverOptions};
use super::variable_menu::{VariableMenuRow, protocol_variable};
use crate::commands::Outcome;
use crate::contextkey::Expr;
use crate::debug::session::Variable;
use crate::menus::{MenuAction, MenuId};
/// A variable row: its session, the parent's `variablesReference` and its name.
pub(super) type RowKey = (String, i64, String);
/// The `debugViz.{index}` commands of the Visualize Variable... menu.
const PICK_VISUALIZER_ID: &str = "debugViz";
#[derive(Default)]
pub struct DebugVisualizers {
/// `handles`: the `extensionId\0id` keys `$registerDebugVisualizer` registered.
handles: HashSet<String>,
/// `trees`: the tree ids `$registerDebugVisualizerTree` registered, each with whether its items can be edited.
trees: HashMap<String, bool>,
/// `getApplicableFor`'s visualizers (`IDebugVisualization`) of each variable row with any.
pub applicable: HashMap<RowKey, Vec<Value>>,
/// debugViewModel.ts `visualized`: a variable row and the tree it shows as instead.
pub visualized: HashMap<RowKey, Visualized>,
/// debugViewModel.ts `preferredVisualizers`: `getPreferredVisualizedKey` and the tree id its variables show as.
preferred: HashMap<String, String>,
/// `getVisualizedChildren` answers by tree id and item id.
pub tree_children: HashMap<(String, i64), Vec<Value>>,
/// The row and visualizers of the open Visualize Variable... menu.
pick: Option<(RowKey, Vec<Value>)>,
pick_commands: usize,
/// Each row's Visualize Variable... button, the menu's anchor (variablesView.ts `pickVisualizer`).
pick_buttons: std::rc::Rc<std::cell::RefCell<HashMap<RowKey, gpui::Bounds<gpui::Pixels>>>>,
}
/// debugModel.ts `VisualizedExpression` of a variable: the tree and its `IDebugVisualizationTreeItem`.
#[derive(Clone)]
pub struct Visualized {
pub tree_id: String,
pub item: Value,
}
/// debugViewModel.ts `getPreferredVisualizedKey`.
fn preferred_key(variable: &Variable) -> String {
format!("{}\0{}\0{}", variable.name, variable.type_name.as_deref().unwrap_or_default(), variable.memory_reference.is_some())
}
/// debugVisualizers.ts `toKey`.
fn handle_key(extension_id: &str, id: &str) -> String {
format!("{}\0{id}", extension_id.to_lowercase())
}
impl Workbench {
/// mainThreadDebugService.ts's visualizer methods.
pub(super) fn handle_visualizer_request(&mut self, method: &str, args: &[Value]) {
let text = |index: usize| args.get(index).and_then(Value::as_str).unwrap_or_default();
let visualizers = &mut self.debug.visualizers;
match method {
"$registerDebugVisualizer" => _ = visualizers.handles.insert(handle_key(text(0), text(1))),
"$unregisterDebugVisualizer" => _ = visualizers.handles.remove(&handle_key(text(0), text(1))),
"$registerDebugVisualizerTree" => _ = visualizers.trees.insert(text(0).to_owned(), args.get(1) == Some(&Value::Bool(true))),
"$unregisterDebugVisualizerTree" => _ = visualizers.trees.remove(text(0)),
_ => {}
}
}
/// baseDebugView.ts `AbstractExpressionDataSource.getChildren` and variablesView.ts `renderActionBar` on new
/// children: each variable shows as its preferred tree, and asks the visualizers whose `when` holds.
pub(super) fn visualize_children(&mut self, session_id: &str, reference: i64, window: &mut Window, cx: &mut Context<Self>) {
let parent = (session_id.to_owned(), reference);
let visualizers = &mut self.debug.visualizers;
let mut disposed = Vec::new();
visualizers.applicable.retain(|(session, parent_reference, _), applicable| {
let stale = (session.as_str(), *parent_reference) == (session_id, reference);
if stale {
disposed.extend(applicable.iter().map(|visualizer| visualizer["id"].clone()));
}
!stale
});
visualizers.visualized.retain(|(session, parent_reference, _), _| (session.as_str(), *parent_reference) != (session_id, reference));
if !disposed.is_empty() {
self.host.send("ExtHostDebugService", "$disposeDebugVisualizers", vec![Value::Array(disposed)]);
}
let Some(thread) = self.debug.focus.thread else { return };
let registrations = self.visualizer_registrations();
let children = self.debug.children.get(&parent).cloned().unwrap_or_default();
for variable in children {
let row: RowKey = (session_id.to_owned(), reference, variable.name.clone());
let context = self.visualization_context(session_id, reference, thread, &variable);
if let Some(tree_id) = self.debug.visualizers.preferred.get(&preferred_key(&variable)).cloned() {
self.show_visualized(row.clone(), tree_id, context.clone(), window, cx);
}
if registrations.is_empty() {
continue;
}
let when_context = self.visualizer_when_context(&row, &variable, window);
let matching: Vec<(String, String)> = registrations.iter().filter(|(_, _, when)| when.evaluate(&when_context)).map(|(extension, id, _)| (extension.clone(), id.clone())).collect();
if !matching.is_empty() {
self.provide_visualizers(row, matching, context, window, cx);
}
}
}
/// `processExtensionRegistration`: every extension's `debugVisualizers` whose `when` parses.
fn visualizer_registrations(&self) -> Vec<(String, String, Expr)> {
let mut registrations = Vec::new();
for extension in &self.extensions {
for visualizer in extension.description["contributes"]["debugVisualizers"].as_array().into_iter().flatten() {
let (Some(id), Some(when)) = (visualizer["id"].as_str(), visualizer["when"].as_str().and_then(Expr::deserialize)) else { continue };
registrations.push((extension.id.to_lowercase(), id.to_owned(), when));
}
}
registrations
}
/// debugContext.ts `getContextForVariable` with the variable's name, value and type.
fn visualizer_when_context(&self, row: &RowKey, variable: &Variable, window: &Window) -> HashMap<String, Value> {
let mut context = self.key_context(window);
let menu_row = VariableMenuRow::Variable { menu: MenuId::DebugVariablesContext, session: row.0.clone(), parent_reference: row.1, variable: variable.clone() };
self.variable_menu_context(&menu_row, &mut context);
context.insert("variableName".into(), json!(variable.name));
context.insert("variableValue".into(), json!(variable.value));
context.insert("variableType".into(), json!(variable.type_name));
context
}
/// `getVariableContext`: `containerId` under a variable, `frameId` of the scope the variable descends from.
fn visualization_context(&self, session_id: &str, reference: i64, thread: i64, variable: &Variable) -> Value {
let parent_of = |reference: i64| self.debug.children.iter().find(|((session, _), children)| session == session_id && children.iter().any(|child| child.variables_reference == reference)).map(|((_, parent), _)| *parent);
let mut context = json!({ "sessionId": session_id, "threadId": thread, "variable": protocol_variable(variable) });
if parent_of(reference).is_some() {
context["containerId"] = json!(variable.variables_reference);
}
let mut ancestor = reference;
let mut visited = HashSet::new();
while visited.insert(ancestor) {
if self.debug.scopes.iter().any(|scope| scope.variables_reference == ancestor) {
context["frameId"] = json!(self.debug.focus.frame);
break;
}
let Some(parent) = parent_of(ancestor) else { break };
ancestor = parent;
}
context
}
/// `getApplicableFor`: each matching visualizer's extension activated by `onDebugVisualizer:{id}`, then asked.
fn provide_visualizers(&mut self, row: RowKey, matching: Vec<(String, String)>, context: Value, window: &mut Window, cx: &mut Context<Self>) {
let activations: Vec<_> = matching.iter().map(|(_, id)| self.host.activate_by_event(&format!("onDebugVisualizer:{id}"))).collect();
cx.spawn_in(window, async move |this, cx| {
let mut found = Vec::new();
for ((extension, id), activation) in matching.into_iter().zip(activations) {
let _ = activation.await;
let Ok(Some(reply)) = on_workbench(&this, cx, |workbench, _, _| {
workbench.debug.visualizers.handles.contains(&handle_key(&extension, &id)).then(|| workbench.host.call("ExtHostDebugService", "$provideDebugVisualizers", vec![json!(extension), json!(id), context.clone()]))
}) else { continue };
found.extend(answer(reply).await.ok().and_then(|visualizers| visualizers.as_array().cloned()).unwrap_or_default());
}
if found.is_empty() {
return;
}
let _ = on_workbench(&this, cx, |workbench, _, cx| {
let shown = workbench.debug.children.get(&(row.0.clone(), row.1)).is_some_and(|children| children.iter().any(|child| child.name == row.2));
if !shown {
let ids = found.iter().map(|visualizer| visualizer["id"].clone()).collect();
return workbench.host.send("ExtHostDebugService", "$disposeDebugVisualizers", vec![Value::Array(ids)]);
}
workbench.debug.visualizers.applicable.insert(row, found);
cx.notify();
});
})
.detach();
}
/// `getVisualizedNodeFor` then `setVisualizedExpression`: the row shows as the tree's item for the variable.
fn show_visualized(&mut self, row: RowKey, tree_id: String, context: Value, window: &mut Window, cx: &mut Context<Self>) {
if !self.debug.visualizers.trees.contains_key(&tree_id) {
return;
}
let reply = self.host.call("ExtHostDebugService", "$getVisualizerTreeItem", vec![json!(tree_id), context]);
cx.spawn_in(window, async move |this, cx| {
let item = match answer(reply).await {
Ok(item) if item.is_object() => item,
Ok(_) => return,
Err(error) => return eprintln!("Failed to get visualized node {error}"),
};
let _ = on_workbench(&this, cx, |workbench, _, cx| {
let Some(variable) = workbench.debug.children.get(&(row.0.clone(), row.1)).and_then(|children| children.iter().find(|child| child.name == row.2)) else { return };
workbench.debug.visualizers.preferred.insert(preferred_key(variable), tree_id.clone());
workbench.debug.visualizers.visualized.insert(row, Visualized { tree_id, item });
cx.notify();
});
})
.detach();
}
/// variablesView.ts `useVisualizer`: a command visualizer runs, a tree visualizer replaces the row.
pub(super) fn use_visualizer(&mut self, row: RowKey, visualizer: Value, window: &mut Window, cx: &mut Context<Self>) {
let id = visualizer["id"].clone();
let resolve = visualizer["visualization"].is_null().then(|| self.host.call("ExtHostDebugService", "$resolveDebugVisualizer", vec![id.clone()]));
cx.spawn_in(window, async move |this, cx| {
let visualization = match resolve {
Some(reply) => answer(reply).await.unwrap_or_default(),
None => visualizer["visualization"].clone(),
};
let _ = on_workbench(&this, cx, |workbench, window, cx| {
// DebugVisualizationType.Command
if visualization["type"] == 0 {
return workbench.host.send("ExtHostDebugService", "$executeDebugVisualizerCommand", vec![id]);
}
let Some(tree_id) = visualization["id"].as_str() else { return };
let (Some(thread), Some(variable)) = (workbench.debug.focus.thread, workbench.debug.children.get(&(row.0.clone(), row.1)).and_then(|children| children.iter().find(|child| child.name == row.2)).cloned()) else { return };
let context = workbench.visualization_context(&row.0, row.1, thread, &variable);
workbench.show_visualized(row, tree_id.to_owned(), context, window, cx);
});
})
.detach();
}
/// The Remove Visualizer action: `setVisualizedExpression(original, undefined)`.
fn remove_visualizer(&mut self, row: &RowKey, cx: &mut Context<Self>) {
self.debug.visualizers.visualized.remove(row);
if let Some(variable) = self.debug.children.get(&(row.0.clone(), row.1)).and_then(|children| children.iter().find(|child| child.name == row.2)) {
self.debug.visualizers.preferred.remove(&preferred_key(variable));
}
cx.notify();
}
/// `pickVisualizer`: the menu of the row's visualizers under its action bar.
fn pick_visualizer(&mut self, row: RowKey, visualizers: Vec<Value>, anchor: gpui::Bounds<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
while self.debug.visualizers.pick_commands < visualizers.len() {
let index = self.debug.visualizers.pick_commands;
self.commands.register(format!("{PICK_VISUALIZER_ID}.{index}"), move |workbench, _, window, cx| {
let Some((row, visualizers)) = workbench.debug.visualizers.pick.take() else { return Outcome::done() };
if let Some(visualizer) = visualizers.get(index).cloned() {
workbench.use_visualizer(row, visualizer, window, cx);
}
Outcome::done()
});
self.debug.visualizers.pick_commands += 1;
}
let actions = visualizers.iter().enumerate().map(|(index, visualizer)| MenuAction::Command { id: format!("{PICK_VISUALIZER_ID}.{index}"), title: visualizer["name"].as_str().unwrap_or_default().to_owned(), enabled: true, checked: false, alt: None }).collect();
self.debug.visualizers.pick = Some((row, visualizers));
let context = self.key_context(window);
self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
}
/// The visualizer actions at the end of a variable row: one visualizer's own icon, several behind
/// Visualize Variable..., for the row's action bar.
pub(super) fn visualizer_actions(&self, row: &RowKey, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
let visualizers = self.debug.visualizers.applicable.get(row)?.clone();
let foreground = self.foreground_or("icon.foreground");
let id = format!("{}/{}/{}/viz", row.0, row.1, row.2);
let button = match visualizers.as_slice() {
[visualizer] => {
let (row, visualizer) = (row.clone(), visualizer.clone());
let title = visualizer["name"].as_str().unwrap_or_default().to_owned();
self.visualizer_button(&id, visualizer_icon(&visualizer), title, foreground).on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
cx.stop_propagation();
workbench.use_visualizer(row.clone(), visualizer.clone(), window, cx);
}))
}
_ => {
let (row, tracked_row, tracked) = (row.clone(), row.clone(), self.debug.visualizers.pick_buttons.clone());
self.visualizer_button(&id, Some("eye".into()), "Visualize Variable...".into(), foreground)
.debug_selector(|| "visualize-variable".into())
.child(gpui::canvas(move |bounds, _, _| _ = tracked.borrow_mut().insert(tracked_row, bounds), |_, _, _, _| {}).absolute().size_full())
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
cx.stop_propagation();
let anchor = workbench.debug.visualizers.pick_buttons.borrow()[&row];
workbench.pick_visualizer(row.clone(), visualizers.clone(), anchor, window, cx);
}))
}
};
Some(button.into_any_element())
}
/// `VisualizedVariableRenderer.renderActionBar` on a visualized variable.
pub(super) fn remove_visualizer_action(&self, key: &str, original: RowKey, shows: bool, cx: &mut Context<Self>) -> gpui::AnyElement {
let foreground = self.foreground_or("icon.foreground");
let button = self.visualizer_button(&format!("{key}/remove-viz"), Some("eye".into()), "Remove Visualizer".into(), foreground).on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
cx.stop_propagation();
workbench.remove_visualizer(&original, cx);
}));
self.row_action_bar(shows).child(button).into_any_element()
}
fn visualizer_button(&self, id: &str, icon: Option<String>, title: String, foreground: Rgba) -> gpui::Stateful<gpui::Div> {
let label = match icon {
Some(icon) => self.icon(&icon, 20., 16., foreground),
None => div().size(px(20.)),
};
label
.id(gpui::SharedString::from(id.to_owned()))
.rounded(px(5.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.on_mouse_down(MouseButton::Left, super::scm_view::stop_action_mouse_down)
.child(self.hover_target(gpui::SharedString::from(format!("{id}/hover")), HoverContent::Text(title), HoverOptions::action_item()))
}
/// debugViewlet.css: a row's `.monaco-action-bar` is `display: none` but on the hovered or focused row. A
/// `group_hover` display change would skip the bar's prepaint and panic in its paint.
pub(super) fn row_action_bar(&self, shown: bool) -> gpui::Div {
div().flex_none().ml_auto().items_center().hidden().when(shown, |bar| bar.flex())
}
/// `VisualizedVariableRenderer`: a visualized row, then its expanded children. `original` is the variable row it
/// replaces, which shows Remove Visualizer.
#[allow(clippy::too_many_arguments)]
pub(super) fn visualized_rows(&self, tree_id: &str, item: &Value, original: Option<&RowKey>, key: String, depth: usize, list_focused: bool, rows: &mut Vec<super::debug_view::DebugTreeRow>, window: &Window, cx: &mut Context<Self>) {
let item_id = item["id"].as_i64().unwrap_or_default();
let edit = Editing::Visualized { tree_id: tree_id.to_owned(), item_id };
if self.debug_view.editing.as_ref() == Some(&edit) {
rows.push((self.debug_input_row(key, depth, list_focused, window, cx), depth, false));
return;
}
// DebugTreeItemCollapsibleState.None
let expandable = item["collapsibleState"].as_u64().unwrap_or_default() != 0;
let expanded = expandable && self.row_expanded(&key, false);
let label = item["label"].as_str().unwrap_or_default();
let description = item["description"].as_str().unwrap_or_default();
let text = match description.is_empty() {
true => label.to_owned(),
false => format!("{label}:"),
};
let value_color = self.value_color(&Variable { value: description.to_owned(), ..Variable::default() });
let group = gpui::SharedString::from(key.clone());
let mut row = self
.debug_row(key.clone(), depth, expandable.then_some(expanded), self.debug_view.selected.as_deref() == Some(key.as_str()), list_focused, cx)
.group(group.clone())
.child(
div()
.flex()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.font_family(EXPRESSION_FONT)
.text_size(px(EXPRESSION_FONT_SIZE))
.child(div().text_color(self.color("debugTokenExpression.name")).child(text))
.child(div().ml(px(6.)).text_color(value_color).overflow_hidden().text_ellipsis().child(description.to_owned())),
);
if let Some(original) = original.cloned() {
row = row.child(self.remove_visualizer_action(&key, original, self.row_shows_actions(&key), cx));
}
let can_edit = item["canEdit"] == true;
let (row_key, tree) = (key.clone(), tree_id.to_owned());
row = row.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
// variablesView.ts `canSetExpressionValue`: a visualized item that `canEdit`.
if can_edit && event.click_count() == 2 {
return workbench.start_debug_view_edit(edit.clone(), window, cx);
}
if expandable {
workbench.toggle_visualized_row(&row_key, expanded, &tree, item_id, window, cx);
}
}));
let selected = self.debug_view.selected.as_deref() == Some(key.as_str());
rows.push((row.into_any_element(), depth, selected));
if !expanded {
return;
}
let children = self.debug.visualizers.tree_children.get(&(tree_id.to_owned(), item_id)).cloned().unwrap_or_default();
for child in &children {
let child_key = format!("{key}/{}", child["id"].as_i64().unwrap_or_default());
self.visualized_rows(tree_id, child, None, child_key, depth + 1, list_focused, rows, window, cx);
}
}
/// `VisualizedExpression.getChildren`: `$getVisualizerTreeItemChildren` the first time the row expands.
fn toggle_visualized_row(&mut self, key: &str, expanded: bool, tree_id: &str, item_id: i64, window: &mut Window, cx: &mut Context<Self>) {
if expanded {
self.debug_view.expanded.remove(key);
self.debug_view.collapsed_rows.insert(key.to_owned());
} else {
self.debug_view.collapsed_rows.remove(key);
self.debug_view.expanded.insert(key.to_owned());
self.fetch_visualized_children(tree_id, item_id, window, cx);
}
self.debug_view.selected = Some(key.to_owned());
cx.notify();
}
pub(super) fn fetch_visualized_children(&mut self, tree_id: &str, item_id: i64, window: &mut Window, cx: &mut Context<Self>) {
if !self.debug.visualizers.trees.contains_key(tree_id) {
return;
}
let key = (tree_id.to_owned(), item_id);
let reply = self.host.call("ExtHostDebugService", "$getVisualizerTreeItemChildren", vec![json!(tree_id), json!(item_id)]);
cx.spawn_in(window, async move |this, cx| {
let children = answer(reply).await.ok().and_then(|children| children.as_array().cloned()).unwrap_or_default();
let _ = on_workbench(&this, cx, |workbench, _, cx| {
workbench.debug.visualizers.tree_children.insert(key, children);
cx.notify();
});
})
.detach();
}
/// The visualized item's value in its input: `VisualizedExpression.value`.
pub(super) fn visualized_item(&self, tree_id: &str, item_id: i64) -> Option<&Value> {
let visualizers = &self.debug.visualizers;
let roots = visualizers.visualized.values().filter(|visualized| visualized.tree_id == tree_id).map(|visualized| &visualized.item);
let children = visualizers.tree_children.iter().filter(|((tree, _), _)| tree == tree_id).flat_map(|(_, children)| children);
roots.chain(children).find(|item| item["id"] == item_id)
}
/// `VisualizedVariableRenderer.getInputBoxOptions` `onFinish`: `editTreeItem`, whose answer replaces the item in
/// place, then `updateViews`. A failed edit sets `errorMessage` after the input closed, so nothing shows it.
pub(super) fn edit_visualized_item(&mut self, tree_id: String, item_id: i64, value: String, window: &mut Window, cx: &mut Context<Self>) {
if self.debug.visualizers.trees.get(&tree_id) != Some(&true) {
return;
}
let reply = self.host.call("ExtHostDebugService", "$editVisualizerTreeItem", vec![json!(item_id), json!(value)]);
cx.spawn_in(window, async move |this, cx| {
let Ok(new_item) = answer(reply).await else { return };
let _ = on_workbench(&this, cx, |workbench, window, cx| {
if let Some(fields) = new_item.as_object() {
let visualizers = &mut workbench.debug.visualizers;
let roots = visualizers.visualized.values_mut().filter(|visualized| visualized.tree_id == tree_id).map(|visualized| &mut visualized.item);
let children = visualizers.tree_children.iter_mut().filter(|((tree, _), _)| *tree == tree_id).flat_map(|(_, children)| children.iter_mut());
for item in roots.chain(children).filter(|item| item["id"] == item_id) {
for (field, value) in fields {
item[field] = value.clone();
}
}
}
workbench.update_debug_views(window, cx);
});
})
.detach();
}
}
/// `v.iconClass`, `ThemeIcon.asClassName`'s `codicon codicon-{id}`; without one the action has no icon, as
/// variablesView.ts's `class: v.iconClass || 'debug-viz-icon'` ignores a Uri `iconPath` and no CSS styles `debug-viz-icon`.
fn visualizer_icon(visualizer: &Value) -> Option<String> {
let class = visualizer["iconClass"].as_str()?;
class.split(' ').find_map(|part| part.strip_prefix("codicon-")).map(str::to_owned)
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::Receiver;
use exthost::session::ForwardedRequest;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::{Value, json};
use super::super::debug_view::Editing;
use super::super::variable_menu::tests::{respond, sent_request, stopped_session};
use super::*;
use crate::host_sync::HostMessage;
const TREE: &str = "port.viz\0tree";
/// A stopped session whose Local scope (reference 4) shows `x` and `y`, with an extension contributing visualizer
/// `v` for `variableName == 'x'` and registering it and its editable tree.
fn visualizer_session(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext, Receiver<HostMessage>) {
let (workbench, cx, host) = stopped_session(cx, json!({}));
workbench.update_in(cx, |workbench, window, cx| {
let description = json!({ "contributes": { "debugVisualizers": [{ "id": "v", "when": "variableName == 'x'" }] } });
workbench.extensions.push(exthost::scan::ScannedExtension { id: "port.viz".into(), location: "/viz".into(), description });
workbench.debug.scopes = vec![Variable { name: "Local".into(), variables_reference: 4, ..Variable::default() }];
for (method, args) in [("$registerDebugVisualizer", vec![json!("port.viz"), json!("v")]), ("$registerDebugVisualizerTree", vec![json!(TREE), json!(true)])] {
let request = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: method.into(), args };
drop(workbench.handle_debug_request(request, window, cx));
}
});
cx.run_until_parked();
host.try_iter().for_each(drop);
workbench.update_in(cx, |workbench, window, cx| workbench.fetch_children("s", 4, window, cx));
cx.run_until_parked();
let request = sent_request(&host, "variables");
respond(&workbench, cx, &request, true, json!({ "variables": [{ "name": "x", "value": "1", "variablesReference": 0 }, { "name": "y", "value": "2", "variablesReference": 0 }] }));
(workbench, cx, host)
}
/// The host calls since the last one, each answered by `answer`.
fn answer_calls(host: &Receiver<HostMessage>, cx: &mut VisualTestContext, answer: impl Fn(&str, &[Value]) -> Value) -> Vec<(&'static str, Vec<Value>)> {
let mut calls = Vec::new();
loop {
cx.run_until_parked();
let messages: Vec<HostMessage> = host.try_iter().collect();
if messages.is_empty() {
return calls;
}
for message in messages {
if let Some(reply) = message.reply {
let _ = reply.send(Ok(answer(message.method, &message.args)));
}
calls.push((message.method, message.args));
}
}
}
fn methods(calls: &[(&'static str, Vec<Value>)]) -> Vec<&'static str> {
calls.iter().map(|(method, _)| *method).collect()
}
fn tree_visualizer() -> Value {
json!({ "id": 1, "name": "Tree", "iconClass": "codicon codicon-graph", "visualization": { "type": 1, "id": TREE } })
}
fn tree_answer(method: &str, _: &[Value]) -> Value {
match method {
"$provideDebugVisualizers" => json!([tree_visualizer()]),
"$getVisualizerTreeItem" => json!({ "id": 7, "label": "x", "description": "tree", "collapsibleState": 1, "canEdit": true }),
"$getVisualizerTreeItemChildren" => json!([{ "id": 8, "label": "child", "collapsibleState": 0 }]),
"$editVisualizerTreeItem" => json!({ "id": 7, "label": "x", "description": "edited", "collapsibleState": 1, "canEdit": true }),
_ => Value::Null,
}
}
/// debugVisualizers.ts `getApplicableFor`: only a variable whose `when` holds activates `onDebugVisualizer:v`
/// and asks `$provideDebugVisualizers` with `getVariableContext`.
#[gpui::test]
fn a_visualizer_whose_when_holds_is_asked_for_its_variable(cx: &mut TestAppContext) {
let (workbench, cx, host) = visualizer_session(cx);
let calls = answer_calls(&host, cx, tree_answer);
assert_eq!(methods(&calls), ["$activateByEvent", "$provideDebugVisualizers"]);
assert_eq!(calls[0].1[0], "onDebugVisualizer:v");
let context = &calls[1].1[2];
assert_eq!((&calls[1].1[0], &calls[1].1[1]), (&json!("port.viz"), &json!("v")));
assert_eq!((&context["sessionId"], &context["threadId"], &context["frameId"], &context["variable"]["name"]), (&json!("s"), &json!(1), &json!(9), &json!("x")));
assert!(context.get("containerId").is_none(), "a variable under a scope has no container");
let applicable = workbench.read_with(cx, |workbench, _| workbench.debug.visualizers.applicable.clone());
assert_eq!(applicable, HashMap::from([(("s".to_owned(), 4, "x".to_owned()), vec![tree_visualizer()])]));
assert_eq!(visualizer_icon(&tree_visualizer()).as_deref(), Some("graph"));
assert_eq!(visualizer_icon(&json!({ "iconPath": { "dark": { "path": "/x/icon.svg" } } })), None, "variablesView.ts draws no `iconPath`");
}
/// variablesView.ts `useVisualizer` on a tree: the row shows the tree's item, its children come from
/// `$getVisualizerTreeItemChildren`, the next children of the scope show it again (`preferredVisualizers`), and
/// Remove Visualizer brings the variable back.
#[gpui::test]
fn a_tree_visualizer_replaces_the_row_until_removed(cx: &mut TestAppContext) {
let (workbench, cx, host) = visualizer_session(cx);
answer_calls(&host, cx, tree_answer);
let row: RowKey = ("s".into(), 4, "x".into());
workbench.update_in(cx, |workbench, window, cx| workbench.use_visualizer(row.clone(), tree_visualizer(), window, cx));
let calls = answer_calls(&host, cx, tree_answer);
assert_eq!(methods(&calls), ["$getVisualizerTreeItem"]);
assert_eq!((&calls[0].1[0], &calls[0].1[1]["variable"]["name"]), (&json!(TREE), &json!("x")));
let shown = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.debug.visualizers.visualized.get(&row).map(|visualized| visualized.item["description"].clone()));
assert_eq!(shown(cx), Some(json!("tree")));
workbench.update_in(cx, |workbench, window, cx| workbench.toggle_visualized_row("viz", false, TREE, 7, window, cx));
let calls = answer_calls(&host, cx, tree_answer);
assert_eq!(calls.iter().find(|(method, _)| *method == "$getVisualizerTreeItemChildren").map(|(_, args)| args.clone()), Some(vec![json!(TREE), json!(7)]));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug.visualizers.tree_children[&(TREE.to_owned(), 7)][0]["label"].clone()), "child");
workbench.update_in(cx, |workbench, window, cx| workbench.update_debug_views(window, cx));
cx.run_until_parked();
let request = sent_request(&host, "variables");
respond(&workbench, cx, &request, true, json!({ "variables": [{ "name": "x", "value": "3", "variablesReference": 0 }] }));
assert_eq!(shown(cx), None, "new children drop the old visualized rows");
let calls = answer_calls(&host, cx, tree_answer);
assert!(methods(&calls).contains(&"$getVisualizerTreeItem"), "the preferred tree visualizes the new x: {:?}", methods(&calls));
assert_eq!(shown(cx), Some(json!("tree")));
workbench.update_in(cx, |workbench, _, cx| workbench.remove_visualizer(&row, cx));
assert_eq!(shown(cx), None);
workbench.update_in(cx, |workbench, window, cx| workbench.update_debug_views(window, cx));
cx.run_until_parked();
let request = sent_request(&host, "variables");
respond(&workbench, cx, &request, true, json!({ "variables": [{ "name": "x", "value": "4", "variablesReference": 0 }] }));
let calls = answer_calls(&host, cx, tree_answer);
assert!(!methods(&calls).contains(&"$getVisualizerTreeItem"), "a removed visualizer is no longer preferred");
}
/// watchExpressionsView.ts registers `VisualizedVariableRenderer`: a watch expression's visualized child draws
/// its tree's item and children.
#[gpui::test]
fn a_watch_expressions_visualized_child_draws_its_tree(cx: &mut TestAppContext) {
let (workbench, cx, host) = visualizer_session(cx);
answer_calls(&host, cx, tree_answer);
workbench.update_in(cx, |workbench, window, cx| workbench.use_visualizer(("s".into(), 4, "x".into()), tree_visualizer(), window, cx));
answer_calls(&host, cx, tree_answer);
workbench.update_in(cx, |workbench, window, cx| {
workbench.show_debug_view(cx);
workbench.debug.model.watch_expressions.push(crate::debug::WatchExpression { id: "w".into(), name: "obj".into() });
workbench.debug.watch_values.insert("w".into(), Variable { name: "obj".into(), value: "Object".into(), variables_reference: 4, ..Variable::default() });
workbench.debug_view.expanded.insert("watch/w".into());
workbench.toggle_visualized_row("watch/w/x", false, TREE, 7, window, cx);
});
answer_calls(&host, cx, tree_answer);
assert!(cx.debug_bounds("watch/w/x/8").is_some(), "the tree's child row draws under the watch expression");
}
/// `VisualizedVariableRenderer.getInputBoxOptions`: an item that `canEdit` opens with its description, and the
/// accepted value goes to `$editVisualizerTreeItem`, whose answer replaces the item.
#[gpui::test]
fn an_editable_visualized_item_takes_a_new_value(cx: &mut TestAppContext) {
let (workbench, cx, host) = visualizer_session(cx);
answer_calls(&host, cx, tree_answer);
workbench.update_in(cx, |workbench, window, cx| workbench.use_visualizer(("s".into(), 4, "x".into()), tree_visualizer(), window, cx));
answer_calls(&host, cx, tree_answer);
let edit = Editing::Visualized { tree_id: TREE.into(), item_id: 7 };
workbench.update_in(cx, |workbench, window, cx| workbench.start_debug_view_edit(edit.clone(), window, cx));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug_view.input.value.clone()), "tree");
workbench.update_in(cx, |workbench, window, cx| workbench.edit_visualized_item(TREE.into(), 7, "edited".into(), window, cx));
let calls = answer_calls(&host, cx, tree_answer);
assert_eq!(calls.iter().find(|(method, _)| *method == "$editVisualizerTreeItem").map(|(_, args)| args.clone()), Some(vec![json!(7), json!("edited")]));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.visualized_item(TREE, 7).map(|item| item["description"].clone())), Some(json!("edited")));
}
/// variablesView.ts `pickVisualizer`: the Visualize Variable... menu hangs below its button, `getAnchor` the
/// action bar, not at the click.
#[gpui::test]
fn the_visualize_variable_menu_opens_below_its_button(cx: &mut TestAppContext) {
let (workbench, cx, host) = visualizer_session(cx);
answer_calls(&host, cx, |method, args| if method == "$provideDebugVisualizers" { json!([tree_visualizer(), { "id": 2, "name": "Other" }]) } else { tree_answer(method, args) });
workbench.update_in(cx, |workbench, _, cx| {
workbench.show_debug_view(cx);
workbench.debug_view.expanded.insert("scope/Local".into());
workbench.debug_view.focused_row = Some("scope/Local/x".into());
cx.notify();
});
cx.run_until_parked();
let button = cx.debug_bounds("visualize-variable").expect("x has two visualizers behind Visualize Variable...");
cx.simulate_click(button.origin + gpui::point(gpui::px(2.), gpui::px(2.)), gpui::Modifiers::none());
let origin = workbench.read_with(cx, |workbench, _| workbench.context_menu.as_ref().expect("the menu opens").levels[0].origin);
assert_eq!((origin.x, origin.y), (button.left(), button.bottom()));
}
/// `useVisualizer` on a visualizer without a visualization: `$resolveDebugVisualizer`, and a command one runs
/// through `$executeDebugVisualizerCommand`.
#[gpui::test]
fn a_command_visualizer_resolves_and_runs(cx: &mut TestAppContext) {
let (workbench, cx, host) = visualizer_session(cx);
answer_calls(&host, cx, tree_answer);
workbench.update_in(cx, |workbench, window, cx| workbench.use_visualizer(("s".into(), 4, "x".into()), json!({ "id": 3, "name": "Run" }), window, cx));
let calls = answer_calls(&host, cx, |method, _| if method == "$resolveDebugVisualizer" { json!({ "type": 0 }) } else { Value::Null });
assert_eq!(calls, [("$resolveDebugVisualizer", vec![json!(3)]), ("$executeDebugVisualizerCommand", vec![json!(3)])]);
assert!(workbench.read_with(cx, |workbench, _| workbench.debug.visualizers.visualized.is_empty()));
}
}