Visual Studio Code, rebuilt in Rust
Rust
//! variablesView.ts `openContextMenuForVariableTreeElement` (`MenuId.DebugVariablesContext`, debugHover.ts's
//! `MenuId.DebugHoverContext`) and watchExpressionsView.ts `onContextMenu` (`MenuId.DebugWatchContext`), and the
//! commands those menus run on their row's context.
use std::collections::HashMap;
use gpui::{Bounds, ClipboardItem, Context, Pixels, Window};
use serde_json::{Value, json};
use super::Workbench;
use super::debug_service::answer;
use super::debug_view::{Editing, VARIABLES_VIEW, WATCH_VIEW};
use crate::commands::Outcome;
use crate::debug::DataBreakpoint;
use crate::debug::session::Variable;
use crate::menus::{MenuId, menu_group_actions};
/// A row a variable menu opens on.
#[derive(Clone)]
pub(super) enum VariableMenuRow {
/// A Variables view or hover row: its session, the parent's `variablesReference` and the variable.
Variable { menu: MenuId, session: String, parent_reference: i64, variable: Variable },
/// A Watch view root: the watch expression's id and name.
WatchExpression { id: String, name: String },
/// A Watch view row under an expression: its session, the parent's `variablesReference` and the variable.
WatchVariable { session: String, parent_reference: i64, variable: Variable },
}
impl Workbench {
/// variablesView.ts `openContextMenuForVariableTreeElement` and watchExpressionsView.ts `onContextMenu`: a session
/// that `supportsDataBreakpoints` answers `dataBreakpointInfo` first, which sets the Break on Value items' keys.
pub(super) fn show_variable_menu(&mut self, row: VariableMenuRow, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
if let VariableMenuRow::Variable { variable, .. } = &row
&& variable.value.is_empty()
{
return;
}
self.debug_view.menu_variable = match &row {
VariableMenuRow::Variable { session, parent_reference, variable, .. } => Some(Editing::Variable { session: session.clone(), parent_reference: *parent_reference, name: variable.name.clone(), watch: false }),
VariableMenuRow::WatchVariable { session, parent_reference, variable } => Some(Editing::Variable { session: session.clone(), parent_reference: *parent_reference, name: variable.name.clone(), watch: true }),
VariableMenuRow::WatchExpression { .. } => None,
};
let Some((session_id, arguments)) = self.data_breakpoint_info_arguments(&row) else {
return self.open_variable_menu(&row, None, anchor, window, cx);
};
let reply = self.dap_request(&session_id, "dataBreakpointInfo", arguments);
cx.spawn_in(window, async move |workbench, cx| {
let info = match answer(reply).await {
Ok(info) => info,
// The Variables view's menu does not open on a failed request; the Watch view's opens without the items.
Err(_) if matches!(row, VariableMenuRow::Variable { .. }) => return,
Err(_) => Value::Null,
};
let _ = workbench.update_in(cx, |workbench, window, cx| {
workbench.debug_view.data_breakpoint_info = Some(info.clone());
workbench.open_variable_menu(&row, Some(&info), anchor, window, cx);
});
})
.detach();
}
fn open_variable_menu(&mut self, row: &VariableMenuRow, data_breakpoint_info: Option<&Value>, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let mut context = self.key_context(window);
if let Some(info) = data_breakpoint_info {
insert_data_breakpoint_keys(info, &mut context);
}
let (menu, args) = self.variable_menu_context(row, &mut context);
let actions = menu_group_actions(&self.menus, menu, &context, |group| group != "inline");
self.show_context_menu_actions(actions, &context, anchor, args, window, cx);
}
/// variablesView.ts `getContextForVariableMenuWithDataAccess` and watchExpressionsView.ts
/// `getContextForWatchExpressionMenuWithDataAccess`: the `dataBreakpointInfo` request of the row's session.
fn data_breakpoint_info_arguments(&self, row: &VariableMenuRow) -> Option<(String, Value)> {
let session = match row {
VariableMenuRow::Variable { session, .. } | VariableMenuRow::WatchVariable { session, .. } => self.debug.session(session),
VariableMenuRow::WatchExpression { .. } => self.debug.focused_session(),
}?;
if session.capabilities["supportsDataBreakpoints"] != true {
return None;
}
let mut arguments = match row {
VariableMenuRow::Variable { parent_reference, variable, .. } => return Some((session.id.clone(), json!({ "name": variable.name, "variablesReference": parent_reference }))),
VariableMenuRow::WatchExpression { name, .. } => json!({ "name": name }),
VariableMenuRow::WatchVariable { variable, .. } if variable.evaluate_name.as_deref().is_some_and(|name| !name.is_empty()) => json!({ "name": variable.evaluate_name }),
VariableMenuRow::WatchVariable { parent_reference, variable, .. } => json!({ "name": variable.name, "variablesReference": parent_reference }),
};
if let Some(frame) = self.debug.focus.frame {
arguments["frameId"] = json!(frame);
}
Some((session.id.clone(), arguments))
}
/// debugContext.ts `getContextForVariable` or watchExpressionsView.ts `getContextForWatchExpressionMenu` into
/// `context`, and the menu with its command argument.
pub(super) fn variable_menu_context(&self, row: &VariableMenuRow, context: &mut HashMap<String, Value>) -> (MenuId, Vec<Value>) {
let session = match row {
VariableMenuRow::Variable { session, .. } => self.debug.session(session),
_ => self.debug.focused_session(),
};
context.insert("debugType".into(), session.map_or(Value::Null, |session| session.configuration["type"].clone()));
let (variable, evaluate_name_present) = match row {
VariableMenuRow::Variable { variable, .. } => (Some(variable), variable.evaluate_name.is_some()),
// `'evaluateName' in expression`: a Variable always declares the field, an Expression never.
VariableMenuRow::WatchVariable { variable, .. } => (Some(variable), true),
VariableMenuRow::WatchExpression { id, .. } => (self.debug.watch_values.get(id), false),
};
let supports_read_memory = session.is_some_and(|session| session.capabilities["supportsReadMemoryRequest"] == true);
context.insert("canViewMemory".into(), json!(supports_read_memory && variable.is_some_and(|variable| variable.memory_reference.is_some())));
context.insert("variableEvaluateNamePresent".into(), json!(evaluate_name_present));
if let Some(variable) = variable {
let hint = &variable.presentation_hint;
let read_only = hint["attributes"].as_array().is_some_and(|attributes| attributes.iter().any(|attribute| attribute == "readOnly")) || hint["lazy"] == true;
context.insert("variableIsReadonly".into(), json!(read_only));
context.insert("variableType".into(), json!(variable.type_name));
}
match row {
VariableMenuRow::Variable { menu, session, parent_reference, variable } => {
context.insert("debugProtocolVariableMenuContext".into(), json!(""));
let args = json!({ "sessionId": session, "container": self.variable_container(*menu, session, *parent_reference), "variable": protocol_variable(variable) });
(*menu, vec![args])
}
VariableMenuRow::WatchExpression { id, name } => {
context.insert("watchItemType".into(), json!("expression"));
(MenuId::DebugWatchContext, vec![json!({ "watchExpressionId": id, "name": name })])
}
VariableMenuRow::WatchVariable { variable, .. } => {
context.insert("watchItemType".into(), json!("variable"));
(MenuId::DebugWatchContext, vec![protocol_variable(variable)])
}
}
}
/// variablesView.ts and watchExpressionsView.ts `renderActionBar`: the menu's `inline` items for the row. The hover's
/// `VariablesRenderer` takes them from DebugVariablesContext too.
pub(super) fn variable_inline_actions(&self, row: &VariableMenuRow, window: &Window, cx: &mut Context<Self>) -> gpui::Div {
let mut context = self.key_context(window);
let (menu, args) = self.variable_menu_context(row, &mut context);
let menu = if menu == MenuId::DebugHoverContext { MenuId::DebugVariablesContext } else { menu };
self.inline_actions(menu, None, &context, args, self.foreground_or("icon.foreground"), cx)
}
/// variablesView.ts `getVariablesContext` `container`: the parent scope's or variable's `toDebugProtocolObject`, or
/// `{ expression }` for the hover's evaluated expression (debugHover.ts finds it in the scopes without `supportsEvaluateForHovers`).
fn variable_container(&self, menu: MenuId, session: &str, parent_reference: i64) -> Value {
if menu == MenuId::DebugHoverContext
&& let Some(shown) = self.debug_hover.shown.as_ref().filter(|shown| shown.value.variables_reference == parent_reference)
{
let evaluated = self.debug.session(session).is_some_and(|session| session.capabilities["supportsEvaluateForHovers"] == true);
return if evaluated { json!({ "expression": shown.value.name }) } else { protocol_variable(&shown.value) };
}
if let Some(scope) = self.debug.scopes.iter().find(|scope| scope.variables_reference == parent_reference) {
return json!({ "name": scope.name, "variablesReference": scope.variables_reference, "expensive": scope.expensive });
}
let mut siblings = self.debug.children.iter().filter(|((owner, _), _)| owner == session).flat_map(|(_, children)| children);
siblings.find(|child| child.variables_reference == parent_reference).map_or(Value::Null, protocol_variable)
}
/// The Variables or Watch view's element its keybindings act on: the focused view's list focus, or its selection.
fn focused_tree_element(&self, selection: bool, window: &Window) -> Option<VariableMenuRow> {
let prefix = match self.focused_movable_view(window)? {
VARIABLES_VIEW => "scope/",
WATCH_VIEW => "watch/",
_ => return None,
};
let key = if selection { self.debug_view.selected.as_deref() } else { self.debug_view.focused_row.as_deref() }?;
key.starts_with(prefix).then(|| self.tree_element(key)).flatten()
}
/// The Variables or Watch row of a key as `variables_rows` and `watch_rows` build them; a scope row is none.
fn tree_element(&self, key: &str) -> Option<VariableMenuRow> {
let session = self.debug.focus.session.clone().unwrap_or_default();
for scope in &self.debug.scopes {
if let Some(path) = key.strip_prefix(&format!("scope/{}/", scope.name))
&& let Some(row) = self.variable_at(&session, scope.variables_reference, path, false)
{
return Some(row);
}
}
for expression in &self.debug.model.watch_expressions {
let watch_key = format!("watch/{}", expression.id);
if key == watch_key {
return Some(VariableMenuRow::WatchExpression { id: expression.id.clone(), name: expression.name.clone() });
}
if let Some(path) = key.strip_prefix(&format!("{watch_key}/"))
&& let Some(value) = self.debug.watch_values.get(&expression.id)
&& let Some(row) = self.variable_at(&session, value.variables_reference, path, true)
{
return Some(row);
}
}
None
}
fn variable_at(&self, session: &str, reference: i64, path: &str, watch: bool) -> Option<VariableMenuRow> {
for variable in self.debug.children.get(&(session.to_owned(), reference))? {
if path == variable.name {
let (session, parent_reference, variable) = (session.to_owned(), reference, variable.clone());
return Some(if watch { VariableMenuRow::WatchVariable { session, parent_reference, variable } } else { VariableMenuRow::Variable { menu: MenuId::DebugVariablesContext, session, parent_reference, variable } });
}
if let Some(rest) = path.strip_prefix(variable.name.as_str()).and_then(|rest| rest.strip_prefix('/'))
&& let Some(row) = self.variable_at(session, variable.variables_reference, rest, watch)
{
return Some(row);
}
}
None
}
/// The command argument the row's menu passes.
fn tree_element_argument(&self, row: &VariableMenuRow) -> Value {
self.variable_menu_context(row, &mut HashMap::new()).1.remove(0)
}
/// A watch expression's id from the command's argument, else the Watch view's focused expression.
fn watch_expression_argument(&self, args: &[Value], window: &Window) -> Option<String> {
if let Some(arg) = args.first() {
return arg["watchExpressionId"].as_str().map(str::to_owned);
}
match self.focused_tree_element(false, window)? {
VariableMenuRow::WatchExpression { id, .. } => Some(id),
_ => None,
}
}
/// variablesView.ts `canSetExpressionValue`.
pub(super) fn can_set_variable_value(&self, variable: &Variable) -> bool {
let Some(session) = self.debug.focused_session() else { return false };
if session.capabilities["supportsSetVariable"] != true && session.capabilities["supportsSetExpression"] != true {
return false;
}
let hint = &variable.presentation_hint;
!hint["attributes"].as_array().is_some_and(|attributes| attributes.iter().any(|attribute| attribute == "readOnly")) && hint["lazy"] != true
}
/// The input's `onFinish`: variablesView.ts `VariablesRenderer` runs debugModel.ts `Variable.setVariable` on a
/// changed value, watchExpressionsView.ts `setExpression` on a non-empty one; then `updateViews`.
pub(super) fn set_variable_value(&mut self, target: Editing, value: String, window: &mut Window, cx: &mut Context<Self>) {
let (Some(focused), Some(frame)) = (self.debug.focused_session(), self.debug.focus.frame) else { return };
let (supports_set_variable, supports_set_expression, focused_id) = (focused.capabilities["supportsSetVariable"] == true, focused.capabilities["supportsSetExpression"] == true, focused.id.clone());
let (session_id, command, arguments, edited) = match &target {
Editing::WatchValue(id) => {
let Some(expression) = self.debug.model.watch_expressions.iter().find(|expression| expression.id == *id) else { return };
if value.is_empty() {
return;
}
(focused_id, "setExpression", json!({ "expression": expression.name, "value": value, "frameId": frame }), None)
}
Editing::Variable { session, parent_reference, name, watch } => {
let key = (session.clone(), *parent_reference);
let Some(variable) = self.debug.children.get(&key).and_then(|children| children.iter().find(|child| child.name == *name)) else { return };
let evaluate_name = variable.evaluate_name.clone().filter(|name| !name.is_empty());
let set_expression = *watch || (supports_set_expression && !supports_set_variable && evaluate_name.is_some());
if (*watch && value.is_empty()) || (!*watch && variable.value == value) {
return;
}
match (set_expression, evaluate_name) {
(true, None) => return,
(true, Some(expression)) => (session.clone(), "setExpression", json!({ "expression": expression, "value": value, "frameId": frame }), Some((key, name.clone()))),
(false, _) => (session.clone(), "setVariable", json!({ "variablesReference": parent_reference, "name": name, "value": value }), Some((key, name.clone()))),
}
}
_ => return,
};
let reply = self.dap_request(&session_id, command, arguments);
cx.spawn_in(window, async move |workbench, cx| {
let result = answer(reply).await;
// `setVariable` keeps the adapter's error as `errorMessage`; a failed `setExpression` rejects and nothing updates.
if result.is_err() && command == "setExpression" {
return;
}
let _ = workbench.update_in(cx, |workbench, window, cx| {
match (result, edited) {
(Ok(body), Some((key, name))) => {
if let Some(variable) = workbench.debug.children.get_mut(&key).and_then(|children| children.iter_mut().find(|child| child.name == name)) {
apply_set_response(variable, &body);
}
}
(Ok(_), None) => {}
(Err(message), _) => {
workbench.start_debug_view_edit(target, window, cx);
workbench.debug_view.edit_error = Some(message);
}
}
workbench.update_debug_views(window, cx);
});
})
.detach();
}
pub(super) fn register_variable_menu_commands(&mut self) {
// variablesView.ts SET_VARIABLE_ID on `variableInternalContext`, the row the menu opened on; debugCommands.ts
// `debug.setVariable` (Enter) on the Variables view's focused variable.
self.commands.register("debug.setVariable", |workbench, args, window, cx| {
let target = if args.is_empty() {
match workbench.focused_tree_element(false, window) {
Some(VariableMenuRow::Variable { session, parent_reference, variable, .. }) => Some(Editing::Variable { session, parent_reference, name: variable.name, watch: false }),
_ => None,
}
} else {
workbench.debug_view.menu_variable.clone()
};
if let Some(target) = target {
workbench.start_debug_view_edit(target, window, cx);
}
Outcome::done()
});
// debugCommands.ts SET_EXPRESSION_COMMAND_ID: the value of the watch expression or of the Watch row under it.
self.commands.register("debug.setWatchExpression", |workbench, args, window, cx| {
let target = match args.first().and_then(|arg| arg["watchExpressionId"].as_str()) {
Some(id) => Some(Editing::WatchValue(id.to_owned())),
None => workbench.debug_view.menu_variable.clone(),
};
if let Some(target) = target {
workbench.start_debug_view_edit(target, window, cx);
}
Outcome::done()
});
// debugCommands.ts BREAK_WHEN_VALUE_IS_READ_ID, BREAK_WHEN_VALUE_CHANGES_ID and BREAK_WHEN_VALUE_IS_ACCESSED_ID.
for (id, access_type) in [("debug.breakWhenValueIsRead", "read"), ("debug.breakWhenValueChanges", "write"), ("debug.breakWhenValueIsAccessed", "readWrite")] {
self.commands.register(id, move |workbench, _, _, cx| {
let Some(info) = workbench.debug_view.data_breakpoint_info.clone().filter(|info| !info.is_null()) else { return Outcome::done() };
let breakpoint = DataBreakpoint {
base: crate::debug::base_breakpoint(crate::debug::generate_uuid(), &json!({})),
description: info["description"].as_str().unwrap_or_default().to_owned(),
data_id: info["dataId"].as_str().unwrap_or_default().to_owned(),
can_persist: info["canPersist"] == true,
access_type: access_type.to_owned(),
access_types: Some(info["accessTypes"].clone()).filter(|types| !types.is_null()),
};
let change = workbench.debug.model.add_data_breakpoint(breakpoint);
workbench.breakpoints_changed(change, true, cx);
Outcome::done()
});
}
// variablesView.ts COPY_VALUE_ID: the expression's or variable's value evaluated again, else the shown value;
// without an argument (Cmd+C) the focused view's selected row.
self.commands.register("workbench.debug.viewlet.action.copyValue", |workbench, args, window, cx| {
let selected = workbench.focused_tree_element(true, window).map(|row| workbench.tree_element_argument(&row));
let Some(arg) = args.first().or(selected.as_ref()) else { return Outcome::done() };
let (element_context, expression, value) = match arg.get("variable") {
Some(variable) => ("variables", evaluate_name_or_value(variable), variable["value"].clone()),
None if arg.get("watchExpressionId").is_some() => {
let id = arg["watchExpressionId"].as_str().unwrap_or_default();
let value = workbench.debug.watch_values.get(id).map_or(Value::Null, |variable| json!(variable.value));
("watch", arg["name"].clone(), value)
}
None => ("watch", evaluate_name_or_value(arg), arg["value"].clone()),
};
let (Some(session), Some(frame)) = (workbench.debug.focused_session(), workbench.debug.focus.frame) else { return Outcome::done() };
let eval_context = if session.capabilities["supportsClipboardContext"] == true { "clipboard" } else { element_context };
let session_id = session.id.clone();
let reply = workbench.dap_request(&session_id, "evaluate", json!({ "expression": expression, "frameId": frame, "context": eval_context }));
cx.spawn_in(window, async move |_, cx| {
let text = match reply.await {
Ok(Ok(body)) => body["result"].clone(),
_ => value,
};
let _ = cx.update(|_, cx| cx.write_to_clipboard(ClipboardItem::new_string(text.as_str().unwrap_or_default().to_owned())));
})
.detach();
Outcome::done()
});
self.commands.register("debug.copyEvaluatePath", |_, args, _, cx| {
let Some(arg) = args.first() else { return Outcome::done() };
let variable = arg.get("variable").unwrap_or(arg);
cx.write_to_clipboard(ClipboardItem::new_string(variable["evaluateName"].as_str().unwrap_or_default().to_owned()));
Outcome::done()
});
self.commands.register("debug.addToWatchExpressions", |workbench, args, window, cx| {
let Some(name) = args.first().and_then(|arg| arg["variable"]["evaluateName"].as_str()) else { return Outcome::done() };
workbench.debug.model.add_watch_expression(name);
workbench.store_debug_model();
workbench.refresh_focus(window, cx);
Outcome::done()
});
// watchExpressionsView.ts CopyExpression and CopyAllWatchExpressions.
self.commands.register("debug.copyWatchExpression", |workbench, args, window, cx| {
let selected = workbench.focused_tree_element(true, window).map(|row| workbench.tree_element_argument(&row));
let Some(name) = args.first().or(selected.as_ref()).and_then(|arg| arg["name"].as_str()) else { return Outcome::done() };
cx.write_to_clipboard(ClipboardItem::new_string(name.to_owned()));
Outcome::done()
});
self.commands.register("workbench.debug.viewlet.action.copyAllWatchExpressions", |workbench, _, _, cx| {
let lines: Vec<String> = workbench.debug.model.watch_expressions.iter().map(|expression| {
let value = workbench.debug.watch_values.get(&expression.id).map_or("", |variable| variable.value.as_str());
format!("{}: {value}", expression.name)
}).collect();
cx.write_to_clipboard(ClipboardItem::new_string(lines.join("\n")));
Outcome::done()
});
// debugCommands.ts EDIT_EXPRESSION_COMMAND_ID and REMOVE_EXPRESSION_COMMAND_ID on the row's expression, or
// without an argument (Enter, Cmd+Backspace) on the Watch view's focused expression.
self.commands.register("debug.renameWatchExpression", |workbench, args, window, cx| {
let Some(id) = workbench.watch_expression_argument(&args, window) else { return Outcome::done() };
workbench.start_debug_view_edit(super::debug_view::Editing::Watch(id), window, cx);
Outcome::done()
});
self.commands.register("debug.removeWatchExpression", |workbench, args, window, cx| {
let Some(id) = workbench.watch_expression_argument(&args, window) else { return Outcome::done() };
workbench.debug.model.remove_watch_expressions(Some(&id));
workbench.store_debug_model();
workbench.refresh_focus(window, cx);
Outcome::done()
});
}
}
/// debugModel.ts `Variable.toDebugProtocolObject`.
pub(super) fn protocol_variable(variable: &Variable) -> Value {
json!({
"name": variable.name,
"value": variable.value,
"type": variable.type_name,
"variablesReference": variable.variables_reference,
"evaluateName": variable.evaluate_name,
"presentationHint": variable.presentation_hint,
"namedVariables": variable.named_variables,
"indexedVariables": variable.indexed_variables,
"memoryReference": variable.memory_reference,
})
}
/// debugModel.ts `handleSetResponse`.
fn apply_set_response(variable: &mut Variable, body: &Value) {
variable.value = body["value"].as_str().unwrap_or_default().to_owned();
if let Some(type_name) = body["type"].as_str() {
variable.type_name = Some(type_name.to_owned());
}
variable.variables_reference = body["variablesReference"].as_i64().unwrap_or(0);
variable.named_variables = body["namedVariables"].as_u64();
variable.indexed_variables = body["indexedVariables"].as_u64();
variable.memory_reference = body["memoryReference"].as_str().map(str::to_owned);
}
/// The Break on Value keys of a `dataBreakpointInfo` answer: Change alone without `accessTypes`.
fn insert_data_breakpoint_keys(info: &Value, context: &mut HashMap<String, Value>) {
let supported = json!(info["dataId"].is_string());
let Some(access_types) = info["accessTypes"].as_array() else {
context.insert("breakWhenValueChangesSupported".into(), supported);
return;
};
for access_type in access_types {
let key = match access_type.as_str() {
Some("read") => "breakWhenValueIsReadSupported",
Some("write") => "breakWhenValueChangesSupported",
Some("readWrite") => "breakWhenValueIsAccessedSupported",
_ => continue,
};
context.insert(key.into(), supported.clone());
}
}
/// COPY_VALUE_ID's `element.evaluateName || element.value`.
fn evaluate_name_or_value(variable: &Value) -> Value {
match variable["evaluateName"].as_str() {
Some(name) if !name.is_empty() => json!(name),
_ => variable["value"].clone(),
}
}
#[cfg(test)]
pub(super) mod tests {
use std::path::Path;
use exthost::session::ForwardedRequest;
use gpui::TestAppContext;
use super::*;
use crate::host_sync::HostMessage;
use crate::menus::MenuAction;
fn variable(name: &str, value: &str, evaluate_name: Option<&str>) -> Variable {
Variable { name: name.into(), value: value.into(), evaluate_name: evaluate_name.map(str::to_owned), ..Variable::default() }
}
/// debug.contribution.ts's `DebugVariablesContext`, `DebugHoverContext` and `DebugWatchContext` items over
/// `getContextForVariable` and `getContextForWatchExpressionMenu`, and variablesView.ts's commands on the row.
#[gpui::test]
fn a_variable_row_menu_shows_its_items_and_runs_them_on_the_row(cx: &mut TestAppContext) {
let (workbench, cx, host) = stopped_session(cx, json!({ "supportsClipboardContext": true }));
let titles = |row: VariableMenuRow, cx: &mut gpui::VisualTestContext| menu_titles(&workbench, row, cx);
let row = |menu: MenuId, variable: Variable| VariableMenuRow::Variable { menu, session: "s".into(), parent_reference: 4, variable };
assert_eq!(titles(row(MenuId::DebugVariablesContext, variable("x", "1", Some("obj.x"))), cx), ["Copy Value", "Copy as Expression", "-", "Add to Watch"]);
assert_eq!(titles(row(MenuId::DebugVariablesContext, variable("x", "1", None)), cx), ["Copy Value"]);
assert_eq!(titles(row(MenuId::DebugHoverContext, variable("x", "1", Some("obj.x"))), cx), ["Copy Value", "Copy as Expression", "-", "Add to Watch"]);
assert!(titles(row(MenuId::DebugVariablesContext, variable("x", "", Some("obj.x"))), cx).is_empty(), "a variable without a value has no menu");
assert_eq!(titles(VariableMenuRow::WatchExpression { id: "w".into(), name: "a + b".into() }, cx), ["Add Expression", "Copy Expression", "Edit Expression", "Copy Value", "Copy All", "-", "Remove All Expressions"]);
assert_eq!(titles(VariableMenuRow::WatchVariable { session: "s".into(), parent_reference: 5, variable: variable("x", "1", None) }, cx), ["Add Expression", "Copy Value", "Copy All", "Copy as Expression", "-", "Remove All Expressions"]);
let args = |row: VariableMenuRow, cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.variable_menu_context(&row, &mut HashMap::new()).1);
let variable_args = args(row(MenuId::DebugVariablesContext, variable("x", "1", Some("obj.x"))), cx);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.copyEvaluatePath", variable_args.clone(), window, cx)));
assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("obj.x"));
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.addToWatchExpressions", variable_args.clone(), window, cx)));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug.model.watch_expressions.iter().map(|expression| expression.name.clone()).collect::<Vec<_>>()), ["obj.x"]);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.debug.viewlet.action.copyAllWatchExpressions", Vec::new(), window, cx)));
assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("obj.x: "));
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.copyWatchExpression", vec![json!({ "watchExpressionId": "w", "name": "a + b" })], window, cx)));
assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("a + b"));
cx.run_until_parked();
host.try_iter().for_each(drop);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.debug.viewlet.action.copyValue", variable_args, window, cx)));
cx.run_until_parked();
let request = sent_request(&host, "evaluate");
assert_eq!(request["arguments"], json!({ "expression": "obj.x", "frameId": 9, "context": "clipboard" }));
respond(&workbench, cx, &request, true, json!({ "result": "{ x: 1 }", "variablesReference": 0 }));
assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("{ x: 1 }"));
assert_eq!(args(VariableMenuRow::WatchExpression { id: "w".into(), name: "a + b".into() }, cx), [json!({ "watchExpressionId": "w", "name": "a + b" })]);
let id = workbench.read_with(cx, |workbench, _| workbench.debug.model.watch_expressions[0].id.clone());
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.removeWatchExpression", vec![json!({ "watchExpressionId": id, "name": "obj.x" })], window, cx)));
assert!(workbench.read_with(cx, |workbench, _| workbench.debug.model.watch_expressions.is_empty()));
}
/// variablesView.ts `getVariablesContext`: `container` is the parent scope's or variable's protocol object.
#[gpui::test]
fn a_variable_row_menu_passes_its_parent_as_the_container(cx: &mut TestAppContext) {
let (workbench, cx, _host) = stopped_session(cx, json!({}));
workbench.update_in(cx, |workbench, _, _| {
workbench.debug.scopes = vec![Variable { name: "Local".into(), variables_reference: 4, ..Variable::default() }];
let parent = Variable { variables_reference: 7, ..variable("obj", "{...}", Some("obj")) };
workbench.debug.children.insert(("s".into(), 4), vec![parent]);
});
let container = |parent_reference: i64, cx: &mut gpui::VisualTestContext| {
let row = VariableMenuRow::Variable { menu: MenuId::DebugVariablesContext, session: "s".into(), parent_reference, variable: variable("x", "1", None) };
workbench.read_with(cx, |workbench, _| workbench.variable_menu_context(&row, &mut HashMap::new()).1[0]["container"].clone())
};
assert_eq!(container(4, cx), json!({ "name": "Local", "variablesReference": 4, "expensive": false }));
let parent = container(7, cx);
assert_eq!((&parent["name"], &parent["variablesReference"], &parent["evaluateName"]), (&json!("obj"), &json!(7), &json!("obj")));
}
/// variablesView.ts SET_VARIABLE_ID and `VariablesRenderer.getInputBoxOptions`: Set Value opens the row's input, which
/// sends `setVariable` and takes the answer, or keeps the adapter's error as the input's message.
#[gpui::test]
fn set_value_edits_a_variable_through_set_variable(cx: &mut TestAppContext) {
let (workbench, cx, host) = stopped_session(cx, json!({ "supportsSetVariable": true }));
workbench.update_in(cx, |workbench, _, _| drop(workbench.debug.children.insert(("s".into(), 4), vec![variable("x", "1", Some("obj.x"))])));
let row = || VariableMenuRow::Variable { menu: MenuId::DebugVariablesContext, session: "s".into(), parent_reference: 4, variable: variable("x", "1", Some("obj.x")) };
assert_eq!(menu_titles(&workbench, row(), cx), ["Set Value", "-", "Copy Value", "Copy as Expression", "-", "Add to Watch"]);
let args = workbench.read_with(cx, |workbench, _| workbench.variable_menu_context(&row(), &mut HashMap::new()).1);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.setVariable", args, window, cx)));
let edit = Editing::Variable { session: "s".into(), parent_reference: 4, name: "x".into(), watch: false };
assert_eq!(workbench.read_with(cx, |workbench, _| (workbench.debug_view.editing.clone(), workbench.debug_view.input.value.clone())), (Some(edit.clone()), "1".to_owned()));
cx.run_until_parked();
host.try_iter().for_each(drop);
workbench.update_in(cx, |workbench, window, cx| workbench.set_variable_value(edit.clone(), "2".into(), window, cx));
cx.run_until_parked();
let request = sent_request(&host, "setVariable");
assert_eq!(request["arguments"], json!({ "variablesReference": 4, "name": "x", "value": "2" }));
respond(&workbench, cx, &request, true, json!({ "value": "2", "type": "number" }));
let x = workbench.read_with(cx, |workbench, _| workbench.debug.children[&("s".to_owned(), 4)][0].clone());
assert_eq!((x.value.as_str(), x.type_name.as_deref()), ("2", Some("number")));
workbench.update_in(cx, |workbench, window, cx| workbench.set_variable_value(edit.clone(), "nope".into(), window, cx));
cx.run_until_parked();
let request = sent_request(&host, "setVariable");
respond(&workbench, cx, &request, false, json!({ "error": { "id": 1, "format": "Invalid value" } }));
assert_eq!(workbench.read_with(cx, |workbench, _| (workbench.debug_view.editing.clone(), workbench.debug_view.edit_error.is_some())), (Some(edit), true));
}
/// debugCommands.ts SET_EXPRESSION_COMMAND_ID and watchExpressionsView.ts's `settingValue` input: `setExpression` on
/// the watch expression in the focused frame.
#[gpui::test]
fn set_value_of_a_watch_expression_sends_set_expression(cx: &mut TestAppContext) {
let (workbench, cx, host) = stopped_session(cx, json!({ "supportsSetExpression": true }));
let id = workbench.update_in(cx, |workbench, _, _| {
workbench.debug.model.add_watch_expression("a");
workbench.debug.model.watch_expressions[0].id.clone()
});
let row = VariableMenuRow::WatchExpression { id: id.clone(), name: "a".into() };
assert!(menu_titles(&workbench, row, cx).contains(&"Set Value".to_owned()));
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.setWatchExpression", vec![json!({ "watchExpressionId": id, "name": "a" })], window, cx)));
let editing = workbench.read_with(cx, |workbench, _| workbench.debug_view.editing.clone());
assert_eq!(editing, Some(Editing::WatchValue(id)));
cx.run_until_parked();
host.try_iter().for_each(drop);
workbench.update_in(cx, |workbench, window, cx| workbench.set_variable_value(editing.unwrap(), "3".into(), window, cx));
cx.run_until_parked();
assert_eq!(sent_request(&host, "setExpression")["arguments"], json!({ "expression": "a", "value": "3", "frameId": 9 }));
}
/// variablesView.ts `getContextForVariableMenuWithDataAccess`: the `dataBreakpointInfo` answer's access types show
/// their Break on Value items, which add a data breakpoint of that access type.
#[gpui::test]
fn break_on_value_items_follow_data_breakpoint_info(cx: &mut TestAppContext) {
let (workbench, cx, host) = stopped_session(cx, json!({ "supportsDataBreakpoints": true }));
cx.run_until_parked();
host.try_iter().for_each(drop);
let row = VariableMenuRow::Variable { menu: MenuId::DebugVariablesContext, session: "s".into(), parent_reference: 4, variable: variable("x", "1", None) };
workbench.update_in(cx, |workbench, window, cx| workbench.show_variable_menu(row, Bounds::default(), window, cx));
cx.run_until_parked();
let request = sent_request(&host, "dataBreakpointInfo");
assert_eq!(request["arguments"], json!({ "name": "x", "variablesReference": 4 }));
respond(&workbench, cx, &request, true, json!({ "dataId": "d1", "description": "x", "accessTypes": ["read", "write"], "canPersist": false }));
let titles = workbench.update_in(cx, |workbench, _, _| {
let menu = workbench.context_menu.take().expect("the menu opens after the answer");
menu.levels[0].actions.iter().filter_map(|action| match action {
MenuAction::Command { title, .. } => Some(title.clone()),
_ => None,
}).collect::<Vec<_>>()
});
assert_eq!(titles, ["Copy Value", "Break on Value Read", "Break on Value Change"]);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.breakWhenValueChanges", Vec::new(), window, cx)));
let added = workbench.read_with(cx, |workbench, _| workbench.debug.model.data_breakpoints.iter().map(|breakpoint| (breakpoint.data_id.clone(), breakpoint.access_type.clone(), breakpoint.description.clone())).collect::<Vec<_>>());
assert_eq!(added, [("d1".to_owned(), "write".to_owned(), "x".to_owned())]);
}
/// debug.contribution.ts COPY_VALUE_ID, watchExpressionsView.ts CopyExpression and debugCommands.ts
/// `debug.setVariable`, EDIT_EXPRESSION_COMMAND_ID and REMOVE_EXPRESSION_COMMAND_ID from their keys on the clicked row.
#[gpui::test]
fn the_variable_and_watch_keys_act_on_the_clicked_row(cx: &mut TestAppContext) {
let (workbench, cx, host) = stopped_session(cx, json!({ "supportsSetVariable": true }));
let id = workbench.update(cx, |workbench, cx| {
workbench.debug.scopes = vec![Variable { name: "Local".into(), variables_reference: 4, ..Variable::default() }];
workbench.debug.children.insert(("s".into(), 4), vec![variable("x", "1", Some("obj.x"))]);
workbench.debug_view.expand_first_scope = true;
workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), std::env::temp_dir().join("vsrustium-variable-keys/keybindings.json"));
workbench.debug.model.add_watch_expression("a + b");
workbench.show_debug_view(cx);
workbench.debug.model.watch_expressions[0].id.clone()
});
let click = |key: &'static str, cx: &mut gpui::VisualTestContext| {
cx.update(|window, cx| drop(window.draw(cx)));
let row = cx.debug_bounds(key).unwrap_or_else(|| panic!("the {key} row"));
cx.simulate_click(row.center(), gpui::Modifiers::none());
};
let clipboard = |cx: &mut gpui::VisualTestContext| cx.read_from_clipboard().and_then(|item| item.text());
let stop_editing = |cx: &mut gpui::VisualTestContext| workbench.update(cx, |workbench, _| workbench.debug_view.editing.take());
click("scope/Local/x", cx);
cx.run_until_parked();
host.try_iter().for_each(drop);
cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-c"));
cx.run_until_parked();
let request = sent_request(&host, "evaluate");
assert_eq!(request["arguments"], json!({ "expression": "obj.x", "frameId": 9, "context": "variables" }));
respond(&workbench, cx, &request, true, json!({ "result": "1", "variablesReference": 0 }));
assert_eq!(clipboard(cx).as_deref(), Some("1"));
cx.simulate_keystrokes("enter");
assert_eq!(stop_editing(cx), Some(Editing::Variable { session: "s".into(), parent_reference: 4, name: "x".into(), watch: false }));
click(format!("watch/{id}").leak(), cx);
cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-alt-c"));
assert_eq!(clipboard(cx).as_deref(), Some("a + b"));
cx.simulate_keystrokes("enter");
assert_eq!(stop_editing(cx), Some(Editing::Watch(id)));
workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.debug_view.list_focus[WATCH_VIEW], cx));
cx.simulate_keystrokes(if matches!(crate::keybindings::OS, crate::keybindings::Os::Macintosh) { "cmd-backspace" } else { "delete" });
assert!(workbench.read_with(cx, |workbench, _| workbench.debug.model.watch_expressions.is_empty()));
}
pub(in crate::workbench) fn stopped_session(cx: &mut TestAppContext, capabilities: Value) -> (gpui::Entity<Workbench>, &mut gpui::VisualTestContext, std::sync::mpsc::Receiver<HostMessage>) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
let (sender, host) = std::sync::mpsc::channel::<HostMessage>();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
workbench.update_in(cx, |workbench, _, _| {
let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
session.initialized = true;
session.capabilities = capabilities;
workbench.debug.sessions.push(session);
workbench.debug.focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };
});
(workbench, cx, host)
}
fn menu_titles(workbench: &gpui::Entity<Workbench>, row: VariableMenuRow, cx: &mut gpui::VisualTestContext) -> Vec<String> {
workbench.update_in(cx, |workbench, window, cx| {
workbench.show_variable_menu(row, Bounds::default(), window, cx);
let Some(menu) = workbench.context_menu.take() else { return Vec::new() };
menu.levels[0].actions.iter().map(|action| match action {
MenuAction::Command { title, .. } => title.clone(),
_ => "-".to_owned(),
}).collect()
})
}
pub(in crate::workbench) fn sent_request(host: &std::sync::mpsc::Receiver<HostMessage>, command: &str) -> Value {
host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).find(|request| request["command"] == command).unwrap_or_else(|| panic!("a {command} request"))
}
pub(in crate::workbench) fn respond(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext, request: &Value, success: bool, body: Value) {
let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": success, "command": request["command"], "message": body["error"]["format"], "body": body });
let accept = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), response] };
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept, window, cx)));
cx.run_until_parked();
}
}