Visual Studio Code, rebuilt in Rust
Rust
//! debugHover.ts and the hover handling of debugEditorContribution.ts: while a session is stopped, the value of the
//! expression under the mouse in the focused frame's file takes the place of the editor hover; Alt switches back.
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::HashSet;
use std::ops::Range;
use std::rc::Rc;
use std::sync::LazyLock;
use std::time::Duration;
use gpui::{
Animation, AnimationExt, AnyElement, AsyncWindowContext, Bounds, BoxShadow, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, Point, ScrollHandle, Size, Task, WeakEntity, Window,
canvas, deferred, div, point, prelude::*, px, rgba,
};
use regex::Regex;
use serde_json::{Value, json};
use super::Workbench;
use super::content_hover::{Anchor, HoverSource, MouseTarget, anchor_at};
use super::debug_service::{answer, evaluate_lazy, on_workbench};
use super::debug_visualizers::RowKey;
use super::explorer_find::{TreeFindLook, label_matches};
use super::find_widget::HISTORY_LIMIT;
use super::input_box_view::{InputId, InputView};
use super::variable_menu::VariableMenuRow;
use crate::history::HistoryNavigator;
use crate::input_box::InputBox;
use crate::debug::session::{State, Variable};
use crate::editor::{LINE_HEIGHT, OpenEditor, Position, column_x, utf16_column};
use crate::language_features::Candidate;
use crate::menus::MenuId;
#[cfg(test)]
mod tests;
const REGISTER: &str = "$registerEvaluatableExpressionProvider";
const EDITOR_FONT: &str = "Menlo";
const EDITOR_FONT_SIZE: f32 = 12.;
/// debugHover.ts `DebugHoverDelegate.getHeight`.
const ROW_HEIGHT: f32 = 18.;
const INDENT: f32 = 8.;
/// contentWidgets.ts: a widget keeps 22px from the page's top and bottom.
const PAGE_PADDING: f32 = 22.;
const FIND_PADDING: f32 = 30.;
/// The find input's width in the reference's debug hover, 19px wider than in a view pane (ui-pair `debug/hover-find.json`).
const FIND_INPUT_WIDTH: f32 = 174.5;
pub(super) struct DebugHover {
/// `hoverPosition`: the empty anchor under the mouse and the mouse there.
position: Option<(Anchor, Point<f32>)>,
/// `showHoverScheduler`.
scheduled: Option<Task<()>>,
/// `showCancellationSource`: the show in flight; dropping it cancels it.
showing: Option<Task<()>>,
/// DebugHoverComputer `_current`: the expression's range last computed.
current: Option<Anchor>,
pub(super) shown: Option<ShownValue>,
/// `defaultHoverLockout`: the editor hover is off while set.
pub(super) lockout: bool,
alt_pressed: bool,
pub(super) widget_bounds: Rc<Cell<Option<Bounds<f32>>>>,
/// The tree's expanded rows by their path; `setInput` starts each value collapsed.
pub(super) expanded: HashSet<String>,
/// The tree's focused and selected rows by their path.
focused: Option<String>,
selected: Option<String>,
/// The row under the mouse, whose action bar shows.
hovered: Option<String>,
tree_scroll: ScrollHandle,
focus_on_show: bool,
/// Restarts the fade-in of each new value.
shows: usize,
/// The tree's `FindController`; like the tree, it outlives each shown value.
pub(super) find: TreeFind,
}
/// abstractTree.ts `FindController` of a tree whose rows are all loaded: the debug hover's and the Debug Console's.
pub(super) struct TreeFind {
pub focus: FocusHandle,
pub view: InputView,
pub input: InputBox,
pub(super) history: HistoryNavigator,
pub(super) open: bool,
pub(super) previous_pattern: String,
/// The Filter and Fuzzy Match toggles; unset follows `workbench.list.defaultFindMode` and `defaultFindMatchType`.
pub(super) filter_mode: Option<bool>,
pub(super) fuzzy: Option<bool>,
}
impl TreeFind {
pub fn new(cx: &mut gpui::App) -> Self {
TreeFind {
focus: cx.focus_handle(),
view: InputView::default(),
input: InputBox::default(),
history: HistoryNavigator::new(Vec::new(), HISTORY_LIMIT),
open: false,
previous_pattern: String::new(),
filter_mode: None,
fuzzy: None,
}
}
}
/// The open find widget's pattern the rows are matched against.
pub(super) struct FindQuery {
pub(super) pattern: String,
pub(super) fuzzy: bool,
pub(super) filter_mode: bool,
}
impl DebugHover {
pub fn new(cx: &mut gpui::App) -> Self {
let find = TreeFind::new(cx);
DebugHover {
position: None,
scheduled: None,
showing: None,
current: None,
shown: None,
lockout: false,
alt_pressed: false,
widget_bounds: Rc::default(),
expanded: HashSet::new(),
focused: None,
selected: None,
hovered: None,
tree_scroll: ScrollHandle::new(),
focus_on_show: false,
shows: 0,
find,
}
}
}
pub(super) struct ShownValue {
pub range: Anchor,
pub session_id: String,
pub value: Variable,
/// `safeTriangle`'s origin: the mouse that showed it.
origin: Option<Point<f32>>,
/// `positionPreference` after `afterRender`: where the editor placed the widget, kept while it shows (#109226).
above: Cell<Option<bool>>,
/// The editor's scroll when shown: `onDidScrollChange` hides it.
scroll: (f32, f32),
}
struct TreeRow<'a> {
/// The names from the shown value down, joined by `/`.
key: String,
depth: usize,
parent_reference: i64,
/// A visualized item's label and description stand in for its name and value.
variable: Cow<'a, Variable>,
source: RowSource,
children: HoverChildren,
expanded: bool,
/// The find pattern's matched chars in the name.
highlights: Vec<Range<usize>>,
}
/// The tree element a row draws: a `Variable`, or a `VisualizedExpression` whose `original` (only the visualized
/// variable, not the tree's children) shows Remove Visualizer.
enum RowSource {
Variable,
Visualized { original: Option<RowKey> },
}
/// Where an expanded row's children come from.
#[derive(Clone)]
enum HoverChildren {
None,
Variables(i64),
Visualized(String, i64),
}
#[derive(Debug, PartialEq)]
enum ShowResult {
Shown,
NotChanged,
NotAvailable,
}
impl Workbench {
/// `onEditorMouseMove`: over the text the hover shows for the position after `hoverDelay`, the editor hover off
/// meanwhile; over the widget (or on the way to it) a sticky or complex hover stays; elsewhere it hides.
pub(super) fn debug_hover_mouse_moved(&mut self, target: MouseTarget, mouse: Point<gpui::Pixels>, modifiers: Modifiers, pressed: bool, window: &mut Window, cx: &mut Context<Self>) {
if self.debug.state() != State::Stopped {
return;
}
let mouse = mouse.map(f32::from);
let in_triangle = self.in_debug_hover_safe_triangle(mouse);
if matches!(target, MouseTarget::Widget) || in_triangle {
let sticky = self.editors.active().is_none_or(|editor| self.hover_settings(editor).sticky);
let complex = self.debug_hover.shown.as_ref().is_some_and(|shown| shown.value.has_children());
if sticky || complex || modifiers.platform {
return;
}
}
let text_position = match target {
MouseTarget::Text { line, visible } => self.editors.active().and_then(|editor| hover_position(editor, line, visible)),
MouseTarget::Widget | MouseTarget::Other => None,
};
let Some(position) = text_position else {
// #64620: a press usually means a selection, which should not close the hover.
if !pressed {
self.hide_debug_hover_widget(window, cx);
}
return;
};
if self.debug_hover.position.is_some_and(|(shown, _)| shown == position) || in_triangle {
return;
}
self.debug_hover.position = Some((position, mouse));
self.prevent_default_editor_hover(cx);
let delay = self.debug_hover_delay();
self.debug_hover.scheduled = Some(cx.spawn_in(window, async move |workbench, cx| {
cx.background_executor().timer(delay).await;
let _ = workbench.update_in(cx, |workbench, window, cx| {
workbench.debug_hover.scheduled = None;
if let Some((position, mouse)) = workbench.debug_hover.position
&& !workbench.debug_hover.alt_pressed
{
workbench.show_debug_hover(position, false, Some(mouse), window, cx);
}
});
}));
}
/// `onEditorMouseMove` on `GUTTER_GLYPH_MARGIN` without Alt: the glyph hover may show, so the lockout clears,
/// a held button included; the editor's own listener then hides the debug hover.
pub(super) fn debug_hover_glyph_margin_moved(&mut self) {
if self.debug.state() == State::Stopped && !self.debug_hover.alt_pressed {
self.debug_hover.lockout = false;
}
}
/// `onMouseLeave`: leaving the editor for anywhere but the widget hides it.
pub(super) fn debug_hover_mouse_left(&mut self, mouse: Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let mouse = mouse.map(f32::from);
if self.debug_hover.shown.is_some() && self.debug_hover.widget_bounds.get().is_some_and(|bounds| bounds.contains(&mouse)) {
return;
}
self.hide_debug_hover_widget(window, cx);
}
/// `onEditorMouseDown`: a press anywhere but on the widget hides it.
pub(super) fn debug_hover_mouse_down(&mut self, mouse: Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
self.debug_hover_mouse_left(mouse, window, cx);
}
/// `onKeyDown`: any key of the editor hides it; Ctrl/Cmd and Alt alone send no key down.
pub(super) fn debug_hover_key_down(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.hide_debug_hover_widget(window, cx);
}
/// `applyDocumentListeners`' Alt listener, with the focused frame in the active editor's file: Alt swaps a shown
/// debug hover for the editor hover, and its release turns the editor hover off again.
pub(super) fn debug_hover_modifiers_changed(&mut self, modifiers: Modifiers, window: &mut Window, cx: &mut Context<Self>) {
if modifiers.alt == self.debug_hover.alt_pressed {
return;
}
if !modifiers.alt {
self.debug_hover.alt_pressed = false;
self.prevent_default_editor_hover(cx);
return;
}
if !self.editors.active().is_some_and(|editor| self.focused_frame_in(editor.model_id)) {
return;
}
self.debug_hover.alt_pressed = true;
let was_visible = self.debug_hover.shown.is_some();
self.hide_debug_hover(window, cx);
self.debug_hover.lockout = false;
if was_visible && let Some((position, _)) = self.debug_hover.position {
self.show_editor_hover(position, false, cx);
}
}
/// `ShowDebugHoverAction` (`editor.debug.action.showDebugHover`): the hover at the cursor, focused.
pub(super) fn register_debug_hover_commands(&mut self) {
self.commands.register("editor.debug.action.showDebugHover", |workbench, _, window, cx| {
if workbench.debug.state() != State::Inactive
&& let Some(editor) = workbench.editors.active()
{
let head = editor.selection().head;
let position = Anchor { model_id: editor.model_id, line: head.line, start: head.column, end: head.column };
workbench.show_debug_hover(position, true, None, window, cx);
}
crate::commands::Outcome::done()
});
}
/// The scroll of the hover's editor moved, it switched models, or the focused frame changed: `hideHoverWidget`.
pub(super) fn follow_debug_hover_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(shown) = &self.debug_hover.shown else { return };
let scroll = self.editors.active().filter(|editor| editor.model_id == shown.range.model_id).map(|editor| (editor.scroll.top, editor.scroll.left));
// `onFocusStackFrame`: a frame in another file, or none, hides it.
if scroll != Some(shown.scroll) || !self.focused_frame_in(shown.range.model_id) {
self.hide_debug_hover_widget(window, cx);
}
if self.debug_hover.focus_on_show && self.debug_hover.shown.is_some() {
self.debug_hover.focus_on_show = false;
window.focus(&self.debug_hover_focus, cx);
}
}
/// `hideHoverWidget`.
pub(super) fn hide_debug_hover_widget(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.hide_debug_hover(window, cx);
self.debug_hover.scheduled = None;
self.debug_hover.lockout = false;
}
/// `DebugHoverWidget.hide`: a focused widget gives the focus back to the editor.
pub(super) fn hide_debug_hover(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.debug_hover.showing = None;
if self.debug_hover.shown.take().is_none() {
return;
}
if self.debug_hover_focus.contains_focused(window, cx) {
window.focus(&self.editor_focus, cx);
}
self.debug_hover.widget_bounds.set(None);
self.clear_debug_hover_tree();
cx.notify();
}
fn clear_debug_hover_tree(&mut self) {
self.debug_hover.expanded.clear();
self.debug_hover.focused = None;
self.debug_hover.selected = None;
self.debug_hover.tree_scroll.set_offset(point(px(0.), px(0.)));
}
/// `preventDefaultEditorHover`: the editor hover hides and stays off until the lockout clears.
fn prevent_default_editor_hover(&mut self, cx: &mut Context<Self>) {
let off = self.editors.active().is_some_and(|editor| self.hover_settings(editor).enabled == "off");
if self.debug_hover.lockout || off {
return;
}
self.hide_content_hover(cx);
self.debug_hover.lockout = true;
}
/// `showEditorHover`: the lockout clears, else the editor hover would hide at the next mouse move (#193149).
fn show_editor_hover(&mut self, position: Anchor, focus: bool, cx: &mut Context<Self>) {
self.debug_hover.lockout = false;
self.show_content_hover_at(Position::new(position.line, position.start), HoverSource::Mouse, focus, cx);
}
/// `hoverDelay`: `editor.hover.delay` times 2 at 300ms and less, down to times 1 at 900ms and more (#180621).
fn debug_hover_delay(&self) -> Duration {
let base = self.editors.active().map_or(300, |editor| self.hover_settings(editor).delay) as f64;
let factor = (2. - (base - 300.) / 600.).clamp(1., 2.);
Duration::from_millis((base * factor) as u64)
}
/// The focused frame's file is the editor's.
fn focused_frame_in(&self, model_id: u32) -> bool {
let (Some(frame), Some(editor)) = (self.debug.focused_frame(), self.editors.editor_by_id(model_id)) else { return false };
let document = editor.document();
document.scheme == "file" && frame.path() == Some(&*document.path.to_string_lossy())
}
/// `isInSafeTriangle`: the mouse is between where it showed the hover and the widget.
fn in_debug_hover_safe_triangle(&self, mouse: Point<f32>) -> bool {
let Some(origin) = self.debug_hover.shown.as_ref().and_then(|shown| shown.origin) else { return false };
let Some(bounds) = self.debug_hover.widget_bounds.get() else { return false };
in_safe_triangle(origin, bounds, mouse)
}
/// debugEditorContribution.ts `showHover`: the debug hover with the focused frame in the editor's file, else (or
/// with nothing to show there) the editor hover.
fn show_debug_hover(&mut self, position: Anchor, focus: bool, mouse: Option<Point<f32>>, window: &mut Window, cx: &mut Context<Self>) {
self.prevent_default_editor_hover(cx);
if !self.focused_frame_in(position.model_id) {
self.show_editor_hover(position, focus, cx);
return;
}
self.debug_hover.showing = Some(cx.spawn_in(window, async move |workbench, cx| {
let result = show_at(&workbench, cx, position, focus, mouse).await;
let _ = on_workbench(&workbench, cx, |workbench, window, cx| {
if result == ShowResult::NotAvailable {
workbench.hide_debug_hover(window, cx);
workbench.show_editor_hover(position, focus, cx);
}
});
}));
}
/// `doShow`: the value, and the children of a complex one, with the range highlighted.
#[allow(clippy::too_many_arguments, reason = "doShow's inputs")]
fn set_debug_hover_value(&mut self, range: Anchor, session_id: String, value: Variable, focus: bool, mouse: Option<Point<f32>>, window: &mut Window, cx: &mut Context<Self>) {
let scroll = self.editors.editor_by_id(range.model_id).map_or((0., 0.), |editor| (editor.scroll.top, editor.scroll.left));
if value.has_children() {
self.fetch_children(&session_id, value.variables_reference, window, cx);
}
self.clear_debug_hover_tree();
self.debug_hover.widget_bounds.set(None);
self.debug_hover.shows += 1;
self.debug_hover.shown = Some(ShownValue { range, session_id, value, origin: mouse, above: Cell::new(None), scroll });
self.debug_hover.focus_on_show = focus;
cx.notify();
}
/// The `hoverHighlight` decoration of the shown expression's range on model line `index`.
pub(super) fn debug_hover_highlight(&self, editor: &OpenEditor, index: usize, char_width: f32) -> Option<Div> {
let range = self.debug_hover.shown.as_ref().map(|shown| shown.range).filter(|range| range.model_id == editor.model_id && range.line == index)?;
let (left, right) = editor.line_layout(index).range(range.start, range.end);
Some(div().absolute().top_0().h_full().left(px(left * char_width)).w(px((right - left) * char_width)).bg(self.color("editor.hoverHighlightBackground")))
}
/// `DebugHoverWidget` as a content widget at the range's start, above the line when it fits, else below.
pub(super) fn debug_hover_widget(&self, editor: &OpenEditor, content_left: f32, char_width: f32, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let shown = self.debug_hover.shown.as_ref().filter(|shown| shown.range.model_id == editor.model_id)?;
let range = shown.range;
if range.line >= editor.document().lines.len() || editor.folding.is_hidden(range.line) {
return None;
}
let view_line = editor.position_view_line(Position::new(range.line, range.start), false);
let segment = editor.segment(view_line);
// The measuring canvas fills the padding box: add the 1px border on each side.
let measured = self.debug_hover.widget_bounds.get().map(|bounds| Size { width: bounds.size.width + 2., height: bounds.size.height + 2. });
let size = measured.unwrap_or(Size { width: 0., height: 0. });
let editor_bounds = self.text_area_bounds.get();
let window_size = window.viewport_size().map(f32::from);
let left = editor.segment_pixel_left(segment, range.start, char_width) - editor.scroll.left + content_left;
let left = super::editor_message::horizontal_in_page(left, size.width, editor_bounds, window_size);
let anchor_top = editor.line_top(view_line, self.editors.viewport) - editor.scroll.top;
let fits_above = editor_bounds.origin.y + anchor_top - size.height >= PAGE_PADDING;
let fits_below = editor_bounds.origin.y + anchor_top + LINE_HEIGHT + size.height <= window_size.height - PAGE_PADDING;
let above = match shown.above.get() {
Some(above) => above,
None => fits_above || !fits_below,
};
if measured.is_some() {
shown.above.set(Some(above));
}
// contentWidgets.ts `_layoutBoxInPage` with `fixedOverflowWidgets`: above stays 22px under the page's top.
let top = match above {
true => (anchor_top - size.height).max(PAGE_PADDING - editor_bounds.origin.y),
false => anchor_top + LINE_HEIGHT,
};
let widget_bounds = self.debug_hover.widget_bounds.clone();
let measure = canvas(
move |bounds, window, cx| {
let bounds: Bounds<f32> = bounds.map(f32::from);
if widget_bounds.get().map(|old| old.size) != Some(bounds.size) {
super::part_view::redraw_after_frame(window, cx);
}
widget_bounds.set(Some(bounds));
},
|_, _, _, _| (),
)
.absolute()
.inset_0();
let contents = match shown.value.has_children() {
true => self.debug_hover_complex_value(shown, editor_bounds.size.height, editor_bounds.origin.y - self.active_group_top(), anchor_top, window, cx),
false => self.debug_hover_simple_value(&shown.value, editor_bounds.size.width),
};
let radius = super::content_hover_view::RADIUS;
let widget = div()
.id("debug-hover")
.debug_selector(|| "debug-hover".into())
.track_focus(&self.debug_hover_focus)
.absolute()
.left(px(left))
.top(px(top))
.border_1()
.border_color(self.color("editorHoverWidget.border"))
.rounded(px(radius))
.bg(self.color("editorHoverWidget.background"))
.text_color(self.foreground_or("editorHoverWidget.foreground"))
.font_family(EDITOR_FONT)
.text_size(px(EDITOR_FONT_SIZE))
.cursor_default()
.occlude()
.when(measured.is_none(), |widget| widget.invisible())
// --vscode-shadow-lg.
.shadow(vec![BoxShadow { color: rgba(0x00000024).into(), offset: point(px(0.), px(0.)), blur_radius: px(12.), spread_radius: px(0.), inset: false }])
.on_mouse_move(cx.listener(|workbench, event: &MouseMoveEvent, window, cx| {
workbench.debug_hover_mouse_moved(MouseTarget::Widget, event.position, event.modifiers, event.pressed_button.is_some(), window, cx);
}))
.on_any_mouse_down(cx.listener(|_, _: &MouseDownEvent, _, cx| cx.stop_propagation()))
// abstractTree.ts `onSpace` with Alt: no keybinding matches alt+space, the tree's own listener toggles recursively.
.on_key_down(cx.listener(|workbench, event: &KeyDownEvent, window, cx| {
let modifiers = event.keystroke.modifiers;
if event.keystroke.key == "space" && modifiers.alt && !modifiers.control && !modifiers.platform && !modifiers.shift {
cx.stop_propagation();
workbench.toggle_focused_debug_hover_row_recursively(window, cx);
}
}))
// The widget is in the editor's DOM: leaving it for outside the editor is the editor's `onMouseLeave`.
.on_hover(cx.listener(|workbench, hovered: &bool, window, cx| {
if !*hovered && !workbench.text_area_bounds.get().contains(&window.mouse_position().map(f32::from)) {
workbench.debug_hover_mouse_left(window.mouse_position(), window, cx);
}
}))
.child(measure)
.child(contents)
// workbench.css `[tabindex="0"]:focus` on a simple value's container; a complex value focuses the tree, no outline.
.when(!shown.value.has_children() && self.debug_hover_focus.is_focused(window), |widget| widget.child(div().absolute().inset_0().rounded(px(radius - 1.)).border_1().border_color(self.color("focusBorder"))))
.with_animation(("debug-hover-fade-in", self.debug_hover.shows), Animation::new(Duration::from_millis(150)), |widget, delta| widget.opacity(delta));
Some(deferred(widget).with_priority(1).into_any_element())
}
/// `.value`: a value without children, colored by its kind.
fn debug_hover_simple_value(&self, value: &Variable, max_width: f32) -> AnyElement {
div()
.id("debug-hover-value")
.max_w(px(max_width))
.max_h(px(500.))
.overflow_y_scroll()
.px(px(5.))
.py(px(4.))
.line_height(px(LINE_HEIGHT))
.text_color(self.value_color(value))
.child(value.value.clone())
.into_any_element()
}
/// `.complex-value`: the value as the title, its children as a tree, and the Alt tip.
fn debug_hover_complex_value(&self, shown: &ShownValue, editor_height: f32, editor_top: f32, hovered_line_top: f32, window: &Window, cx: &mut Context<Self>) -> AnyElement {
let mut rule = self.color("editorHoverWidget.foreground");
(rule.r, rule.g, rule.b, rule.a) = (128. / 255., 128. / 255., 128. / 255., 0.35);
let caption = |text: Div| text.h(px(ROW_HEIGHT)).pl(px(15.)).pr(px(2.)).text_size(px(11.)).line_height(px(ROW_HEIGHT)).overflow_hidden().whitespace_nowrap().text_ellipsis();
let tree_rows = self.debug_hover_tree_rows(shown);
let find_open = self.debug_hover.find.open;
// abstractTree.ts `AbstractFindController.open`: `paddingTop: 30` over the rows while the widget shows.
// shortcut: the list keys' reveal ignores the padding, a revealed last row can sit 30px short; fix with ListScroll padding.
let padding = if find_open { FIND_PADDING } else { 0. };
let height = tree_height(editor_height, editor_top, tree_rows.len(), padding, hovered_line_top);
let tree_focused = self.debug_hover_focus.is_focused(window);
let rows = tree_rows.into_iter().map(|row| self.debug_hover_row(row, &shown.session_id, tree_focused, window, cx));
let rows = div()
.id("debug-hover-tree")
.debug_selector(|| "debug-hover-tree".into())
.flex()
.flex_col()
.pt(px(padding))
.cursor_pointer()
.children(rows);
let rows = self.scrollable("debug-hover-tree", Some(&self.debug_hover.tree_scroll), rows, cx).h(px(height));
let find = find_open.then(|| {
let look = TreeFindLook { input: InputId::DebugHoverFind, message: self.debug_hover_find_message(), filter_mode: self.debug_hover_find_filter_mode(), fuzzy: self.debug_hover_find_fuzzy(), input_width: FIND_INPUT_WIDTH };
self.tree_find_widget(look, |workbench, window, cx| workbench.close_debug_hover_find(window, cx), window, cx)
});
let tree = div().relative().child(rows).children(find);
div()
.min_w(px(400.))
.max_w(px(550.))
.flex()
.flex_col()
.child(caption(div()).border_b_1().border_color(rule).text_color(self.value_color(&shown.value)).child(shown.value.value.clone()))
.child(tree)
.child(caption(div()).border_t_1().border_color(rule).opacity(0.5).child("Hold Option key to switch to editor language hover"))
.into_any_element()
}
/// The tree's visible rows: the shown value's children, with the expanded ones' children under them.
fn debug_hover_tree_rows(&self, shown: &ShownValue) -> Vec<TreeRow<'_>> {
let mut rows = Vec::new();
let query = self.debug_hover_find_query();
self.collect_debug_hover_rows(&shown.session_id, shown.value.variables_reference, "hover", 0, query.as_ref(), &mut rows);
rows
}
fn collect_debug_hover_rows<'a>(&'a self, session: &str, reference: i64, parent: &str, depth: usize, query: Option<&FindQuery>, rows: &mut Vec<TreeRow<'a>>) {
let Some(children) = self.debug.children.get(&(session.to_owned(), reference)) else { return };
for variable in children {
let highlights = query.and_then(|query| label_matches(&query.pattern, &variable.name, query.fuzzy));
// abstractTree.ts `FindFilter` in filter mode: `TreeVisibility.Recurse` for a row that does not match.
let hidden = match query {
Some(query) if query.filter_mode && highlights.is_none() => !self.debug_hover_descendant_matches(session, variable, query, &mut HashSet::new()),
_ => false,
};
if hidden {
continue;
}
let key = format!("{parent}/{}", variable.name);
let original: RowKey = (session.to_owned(), reference, variable.name.clone());
if let Some(visualized) = self.debug.visualizers.visualized.get(&original) {
self.collect_visualized_hover_rows(&visualized.tree_id, &visualized.item, Some(original), key, depth, rows);
continue;
}
let expanded = variable.has_children() && self.debug_hover.expanded.contains(&key);
let children = if variable.has_children() { HoverChildren::Variables(variable.variables_reference) } else { HoverChildren::None };
let row = TreeRow { key: key.clone(), depth, parent_reference: reference, variable: Cow::Borrowed(variable), source: RowSource::Variable, children, expanded, highlights: highlights.unwrap_or_default() };
rows.push(row);
if expanded {
self.collect_debug_hover_rows(session, variable.variables_reference, &key, depth + 1, query, rows);
}
}
}
/// debugHover.ts registers `VisualizedVariableRenderer`: a visualized row, then its expanded tree children.
fn collect_visualized_hover_rows<'a>(&'a self, tree_id: &str, item: &Value, original: Option<RowKey>, key: String, depth: usize, rows: &mut Vec<TreeRow<'a>>) {
let item_id = item["id"].as_i64().unwrap_or_default();
// DebugTreeItemCollapsibleState.None
let expandable = item["collapsibleState"].as_u64().unwrap_or_default() != 0;
let expanded = expandable && self.debug_hover.expanded.contains(&key);
let variable = Variable { name: item["label"].as_str().unwrap_or_default().to_owned(), value: item["description"].as_str().unwrap_or_default().to_owned(), ..Variable::default() };
let children = if expandable { HoverChildren::Visualized(tree_id.to_owned(), item_id) } else { HoverChildren::None };
rows.push(TreeRow { key: key.clone(), depth, parent_reference: 0, variable: Cow::Owned(variable), source: RowSource::Visualized { original }, children, expanded, highlights: Vec::new() });
if !expanded {
return;
}
let Some(children) = self.debug.visualizers.tree_children.get(&(tree_id.to_owned(), item_id)) else { return };
for child in children {
let child_key = format!("{key}/{}", child["id"].as_i64().unwrap_or_default());
self.collect_visualized_hover_rows(tree_id, child, None, child_key, depth + 1, rows);
}
}
/// indexTreeModel.ts `_updateNodeAfterFilterChange`: the loaded children are filtered, collapsed or not.
/// `visited` stops at a reference an adapter hands out twice.
fn debug_hover_descendant_matches(&self, session: &str, variable: &Variable, query: &FindQuery, visited: &mut HashSet<i64>) -> bool {
if !variable.has_children() || !visited.insert(variable.variables_reference) {
return false;
}
let Some(children) = self.debug.children.get(&(session.to_owned(), variable.variables_reference)) else { return false };
children.iter().any(|child| label_matches(&query.pattern, &child.name, query.fuzzy).is_some() || self.debug_hover_descendant_matches(session, child, query, visited))
}
fn debug_hover_find_query(&self) -> Option<FindQuery> {
let find = &self.debug_hover.find;
if !find.open || find.input.value.is_empty() {
return None;
}
Some(FindQuery { pattern: find.input.value.clone(), fuzzy: self.debug_hover_find_fuzzy(), filter_mode: self.debug_hover_find_filter_mode() })
}
fn debug_hover_find_filter_mode(&self) -> bool {
self.debug_hover.find.filter_mode.unwrap_or_else(|| self.setting("workbench.list.defaultFindMode") == json!("filter"))
}
fn debug_hover_find_fuzzy(&self) -> bool {
self.debug_hover.find.fuzzy.unwrap_or_else(|| self.setting("workbench.list.defaultFindMatchType") != json!("contiguous"))
}
/// `AbstractFindController.open` (`list.find` while the tree has the focus): the widget shows with the last
/// pattern selected, or an open one takes the focus.
pub(super) fn open_debug_hover_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let find = &mut self.debug_hover.find;
window.focus(&find.focus.clone(), cx);
if !find.open {
find.open = true;
find.input.set_value(find.previous_pattern.clone());
self.apply_debug_hover_find_pattern(cx);
}
let find = &mut self.debug_hover.find;
find.input.select_all();
find.history.add_to_history(&find.input.value, true);
self.blink_caret(InputId::DebugHoverFind, window, cx);
cx.notify();
}
/// `AbstractFindController.close`: the pattern is kept for the next open, and the tree takes the focus.
pub(super) fn close_debug_hover_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let find = &mut self.debug_hover.find;
if !find.open {
return;
}
find.open = false;
find.previous_pattern = std::mem::take(&mut find.input.value);
find.input = InputBox::default();
find.view.reset();
self.apply_debug_hover_find_pattern(cx);
if self.debug_hover.shown.is_some() {
window.focus(&self.debug_hover_focus, cx);
}
}
/// `FindController.mode` and `matchType`: the rows refilter, the focus stays.
pub(super) fn toggle_debug_hover_find(&mut self, mode: bool, cx: &mut Context<Self>) {
match mode {
true => self.debug_hover.find.filter_mode = Some(!self.debug_hover_find_filter_mode()),
false => self.debug_hover.find.fuzzy = Some(!self.debug_hover_find_fuzzy()),
}
cx.notify();
}
pub(super) fn edit_debug_hover_find_input(&mut self, edit: impl FnOnce(&mut InputBox), cx: &mut Context<Self>) {
let input = &mut self.debug_hover.find.input;
let before = input.value.clone();
edit(input);
cx.notify();
if input.value != before {
self.apply_debug_hover_find_pattern(cx);
}
}
/// `FindWidget`'s keydown: Enter returns to the tree, Up and Down walk the history, Down past its end returns to
/// the tree; Escape is the tree's.
pub(super) fn debug_hover_find_input_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
let modifiers = keystroke.modifiers;
if modifiers.platform || modifiers.alt || modifiers.shift || modifiers.control {
return false;
}
let find = &mut self.debug_hover.find;
match keystroke.key.as_str() {
"escape" => self.debug_hover_escape(window, cx),
"enter" | "down" if keystroke.key == "enter" || find.history.is_last() || find.history.is_nowhere() => {
find.history.add_to_history(&find.input.value, false);
window.focus(&self.debug_hover_focus, cx);
}
"down" => {
let value = find.history.show_next_value(&find.input.value);
self.edit_debug_hover_find_input(|input| input.set_value(value), cx);
}
"up" => {
if let Some(value) = find.history.show_previous_value(&find.input.value) {
self.edit_debug_hover_find_input(|input| input.set_value(value), cx);
}
}
_ => return false,
}
cx.notify();
true
}
/// `FindController.applyPattern`: `focusNext(0, true)` from the focused row to the first one whose name matches;
/// without a match the focus stays.
fn apply_debug_hover_find_pattern(&mut self, cx: &mut Context<Self>) {
cx.notify();
let Some(query) = self.debug_hover_find_query() else { return };
let Some(shown) = self.debug_hover.shown.as_ref() else { return };
let rows = self.debug_hover_tree_rows(shown);
let start = self.debug_hover.focused.as_ref().and_then(|focused| rows.iter().position(|row| row.key == *focused)).unwrap_or(0);
let Some(index) = (0..rows.len()).map(|offset| (start + offset) % rows.len()).find(|&index| label_matches(&query.pattern, &rows[index].variable.name, query.fuzzy).is_some()) else { return };
let key = rows[index].key.clone();
let list = self.debug_hover_list_scroll(rows.len());
self.focus_debug_hover_row(&key, index, list, cx);
}
/// `FindController.render`: "No results found." when no loaded row matches.
fn debug_hover_find_message(&self) -> Option<String> {
let query = self.debug_hover_find_query()?;
let shown = self.debug_hover.shown.as_ref()?;
let found = self.debug_hover_descendant_matches(&shown.session_id, &shown.value, &query, &mut HashSet::new());
let any_rows = self.debug.children.get(&(shown.session_id.clone(), shown.value.variables_reference)).is_some_and(|children| !children.is_empty());
(!found && any_rows).then(|| "No results found.".to_owned())
}
/// A `VariablesRenderer` row; a click toggles an expandable one without focusing the tree (`mouseSupport: false`).
fn debug_hover_row(&self, row: TreeRow<'_>, session: &str, tree_focused: bool, window: &Window, cx: &mut Context<Self>) -> AnyElement {
let expandable = !matches!(row.children, HoverChildren::None);
let foreground = self.foreground_or("icon.foreground");
// tree.css `.monaco-tl-twistie`: 16px wide, `padding-right: 6px`, the chevron moved 3px right.
let twistie = div().id("twistie").w(px(22.)).pl(px(3.)).pr(px(3.)).flex_none().when(expandable, |twistie| {
twistie.child(self.icon(if row.expanded { "chevron-down" } else { "chevron-right" }, 16., 16., foreground))
});
let (key, session_id, children, expanded) = (row.key.clone(), session.to_owned(), row.children.clone(), row.expanded);
// abstractTree.ts `onViewPointer`: a twistie click only toggles, a row click toggles and then focuses and selects.
let twistie = twistie.when(expandable, |twistie| {
let (key, session_id, children) = (key.clone(), session_id.clone(), children.clone());
twistie.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
cx.stop_propagation();
workbench.toggle_debug_hover_row(&key, &session_id, &children, !expanded, event.modifiers().alt, window, cx);
}))
});
// abstractTree.ts `TreeRenderer.DefaultIndent` (8px) plus `workbench.tree.indent` per level.
let indent = 8. + INDENT * row.depth as f32;
let lazy_button = row.variable.is_lazy().then(|| self.lazy_button(session, row.parent_reference, &row.variable, &row.key, cx));
let shows_actions = [&self.debug_hover.focused, &self.debug_hover.hovered].contains(&&Some(row.key.clone()));
let menu_row = matches!(row.source, RowSource::Variable).then(|| VariableMenuRow::Variable { menu: MenuId::DebugHoverContext, session: session.to_owned(), parent_reference: row.parent_reference, variable: row.variable.clone().into_owned() });
let actions = match (&row.source, &menu_row) {
(RowSource::Variable, Some(menu_row)) => {
let visualizers = self.visualizer_actions(&(session.to_owned(), row.parent_reference, row.variable.name.clone()), cx);
Some(self.row_action_bar(shows_actions).child(self.variable_inline_actions(menu_row, window, cx)).children(visualizers).into_any_element())
}
(RowSource::Visualized { original: Some(original) }, _) => Some(self.remove_visualizer_action(&row.key, original.clone(), shows_actions, cx)),
_ => None,
};
let label = self.expression_label(&row.variable, &row.highlights, lazy_button).font_family(super::debug_view::EXPRESSION_FONT).text_size(px(super::debug_view::EXPRESSION_FONT_SIZE));
let hovered = row.key.clone();
let mut element = div().id(gpui::SharedString::from(row.key.clone())).h(px(ROW_HEIGHT)).flex().items_center().pl(px(indent)).child(twistie).child(label).children(actions);
element = element.on_hover(cx.listener(move |workbench, entered: &bool, _, cx| {
super::debug_view::set_hovered(&mut workbench.debug_hover.hovered, &hovered, *entered);
cx.notify();
}));
element = element.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
if expandable {
workbench.toggle_debug_hover_row(&key, &session_id, &children, !expanded, event.modifiers().alt, window, cx);
}
workbench.debug_hover.focused = Some(key.clone());
workbench.debug_hover.selected = Some(key.clone());
cx.notify();
}));
if let Some(menu_row) = menu_row {
element = element.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
workbench.show_variable_menu(menu_row.clone(), Bounds::new(event.position, Default::default()), window, cx);
}));
}
let focused = self.debug_hover.focused.as_ref() == Some(&row.key);
let selected = self.debug_hover.selected.as_ref() == Some(&row.key);
// debugHover.css takes the hover background off the rows.
if focused || selected {
element = self.list_row_selection(element, selected, focused, tree_focused);
}
element.into_any_element()
}
/// abstractTree.ts `TreeMouseController.onViewPointer` on an expandable row: it takes the focus and toggles, with
/// Alt recursively.
#[allow(clippy::too_many_arguments, reason = "the row and the click")]
fn toggle_debug_hover_row(&mut self, key: &str, session: &str, children: &HoverChildren, expand: bool, recursive: bool, window: &mut Window, cx: &mut Context<Self>) {
self.debug_hover.focused = Some(key.to_owned());
self.set_debug_hover_row_expanded(key, session, children, expand, window, cx);
if let (true, HoverChildren::Variables(reference)) = (recursive, children) {
self.set_debug_hover_descendants_expanded(key, session, *reference, expand);
}
}
fn toggle_focused_debug_hover_row_recursively(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(shown) = self.focused_debug_hover_tree(window) else { return };
let session = shown.session_id.clone();
let Some(focused) = self.debug_hover.focused.clone() else { return };
let Some((children, expanded)) = self.debug_hover_tree_rows(shown).iter().find(|row| row.key == focused).map(|row| (row.children.clone(), row.expanded)) else { return };
if !matches!(children, HoverChildren::None) {
self.toggle_debug_hover_row(&focused, &session, &children, !expanded, true, window, cx);
}
}
/// indexTreeModel.ts `_setNodeCollapseState` with `recursive`: every descendant in the tree follows, and
/// asyncDataTree.ts `_onDidChangeCollapseState` collapses again a deep-expanded one whose children are not loaded.
fn set_debug_hover_descendants_expanded(&mut self, key: &str, session: &str, reference: i64, expand: bool) {
let mut parents = vec![(key.to_owned(), reference)];
while let Some((parent, reference)) = parents.pop() {
let Some(children) = self.debug.children.get(&(session.to_owned(), reference)) else { continue };
for child in children.iter().filter(|child| child.has_children()) {
let child_key = format!("{parent}/{}", child.name);
let loaded = self.debug.children.contains_key(&(session.to_owned(), child.variables_reference));
if expand && loaded {
self.debug_hover.expanded.insert(child_key.clone());
} else {
self.debug_hover.expanded.remove(&child_key);
}
parents.push((child_key, child.variables_reference));
}
}
}
fn set_debug_hover_row_expanded(&mut self, key: &str, session: &str, children: &HoverChildren, expand: bool, window: &mut Window, cx: &mut Context<Self>) {
if !expand {
self.debug_hover.expanded.remove(key);
} else if self.debug_hover.expanded.insert(key.to_owned()) {
match children {
HoverChildren::Variables(reference) => self.fetch_children(session, *reference, window, cx),
HoverChildren::Visualized(tree_id, item_id) => self.fetch_visualized_children(tree_id, *item_id, window, cx),
HoverChildren::None => {}
}
}
cx.notify();
}
/// The tree's keys while it has the focus: listWidget.ts `KeyboardController` and abstractTree.ts's arrows and
/// Space, plus the `list.*` keybindings.
pub(super) fn debug_hover_list_command(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
let Some(shown) = self.focused_debug_hover_tree(window) else { return false };
let session = shown.session_id.clone();
let rows: Vec<(String, usize, HoverChildren, bool)> = self.debug_hover_tree_rows(shown).iter().map(|row| (row.key.clone(), row.depth, row.children.clone(), row.expanded)).collect();
if rows.is_empty() {
return true;
}
let focus = self.debug_hover.focused.as_ref().and_then(|focused| rows.iter().position(|row| row.0 == *focused));
let last = rows.len() - 1;
let list = self.debug_hover_list_scroll(rows.len());
let target = match id {
"list.focusDown" => focus.map_or(0, |index| (index + 1).min(last)),
"list.focusUp" => focus.map_or(0, |index| index.saturating_sub(1)),
"list.focusFirst" => 0,
"list.focusLast" => last,
"list.focusPageDown" | "list.focusPageUp" => {
let Some((target, scroll_top)) = crate::list_tree::page_focus(list, id == "list.focusPageDown", focus) else { return true };
self.debug_hover.tree_scroll.set_offset(point(px(0.), px(-scroll_top)));
target
}
"list.select" => {
self.debug_hover.selected = self.debug_hover.focused.clone();
cx.notify();
return true;
}
"list.expand" | "list.collapse" | "list.toggleExpand" => {
let Some(index) = focus else { return true };
let (key, depth, children, expanded) = &rows[index];
let expandable = !matches!(children, HoverChildren::None);
match id {
"list.toggleExpand" if expandable => self.set_debug_hover_row_expanded(key, &session, children, !expanded, window, cx),
"list.expand" if expandable && !expanded => self.set_debug_hover_row_expanded(key, &session, children, true, window, cx),
"list.collapse" if *expanded => self.set_debug_hover_row_expanded(key, &session, children, false, window, cx),
"list.expand" if rows.get(index + 1).is_some_and(|child| child.1 > *depth) => self.focus_debug_hover_row(&rows[index + 1].0, index + 1, list, cx),
"list.collapse" => {
if let Some(parent) = rows[..index].iter().rposition(|parent| parent.1 < *depth) {
self.focus_debug_hover_row(&rows[parent].0, parent, list, cx);
}
}
_ => {}
}
return true;
}
_ => return false,
};
if let Some(row) = rows.get(target) {
self.focus_debug_hover_row(&row.0, target, list, cx);
}
true
}
fn focus_debug_hover_row(&mut self, key: &str, index: usize, list: crate::list_tree::ListScroll, cx: &mut Context<Self>) {
self.debug_hover.focused = Some(key.to_owned());
if let Some(scroll_top) = crate::list_tree::reveal_scroll_top(list, index, false) {
self.debug_hover.tree_scroll.set_offset(point(px(0.), px(-scroll_top)));
}
cx.notify();
}
/// The shown complex value while its tree has the focus.
pub(super) fn focused_debug_hover_tree(&self, window: &Window) -> Option<&ShownValue> {
self.debug_hover.shown.as_ref().filter(|shown| shown.value.has_children() && self.debug_hover_focus.is_focused(window))
}
/// The tree's `keyboardNavigationLabelProvider`: the variable's name.
pub(super) fn debug_hover_type_navigation(&mut self, word: &str, idle: bool, cx: &mut Context<Self>) {
let Some(shown) = self.debug_hover.shown.as_ref() else { return };
let rows = self.debug_hover_tree_rows(shown);
let labels: Vec<String> = rows.iter().map(|row| row.variable.name.clone()).collect();
let focus = self.debug_hover.focused.as_ref().and_then(|focused| rows.iter().position(|row| row.key == *focused));
let Some(index) = super::type_navigation::type_navigation_target(&labels, focus, word, idle) else { return };
let key = rows[index].key.clone();
let list = self.debug_hover_list_scroll(rows.len());
self.focus_debug_hover_row(&key, index, list, cx);
}
fn debug_hover_list_scroll(&self, count: usize) -> crate::list_tree::ListScroll {
let scroll = &self.debug_hover.tree_scroll;
crate::list_tree::ListScroll { count, row_height: ROW_HEIGHT, viewport: f32::from(scroll.bounds().size.height), scroll_top: -f32::from(scroll.offset().y) }
}
/// listWidget.ts `onEscape`: a selection clears first, then debugHover.ts's own listener hides the widget.
pub(super) fn debug_hover_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// listWidget.ts's keydown filter skips the find input's keys.
if !self.debug_hover.find.focus.is_focused(window) && self.debug_hover.selected.take().is_some() {
cx.notify();
return;
}
self.hide_debug_hover(window, cx);
// The keybinding service's `list.closeFind` (listFocus && treeFindOpen) runs after the widget's listener.
self.close_debug_hover_find(window, cx);
}
/// `WorkbenchAsyncDataTree`'s context keys while the hover's tree has the focus.
pub(super) fn debug_hover_context(&self, window: &Window, context: &mut std::collections::HashMap<String, serde_json::Value>) {
let find_focused = self.debug_hover.find.focus.is_focused(window);
let Some(shown) = self.debug_hover.shown.as_ref().filter(|shown| shown.value.has_children() && (find_focused || self.debug_hover_focus.is_focused(window))) else { return };
context.insert("listFocus".into(), json!(true));
context.insert("listSupportsFind".into(), json!(true));
context.insert("treeFindOpen".into(), json!(self.debug_hover.find.open));
if find_focused {
context.insert("inputFocus".into(), json!(true));
}
context.insert("listHasSelectionOrFocus".into(), json!(self.debug_hover.focused.is_some() || self.debug_hover.selected.is_some()));
let rows = self.debug_hover_tree_rows(shown);
let Some(index) = self.debug_hover.focused.as_ref().and_then(|focused| rows.iter().position(|row| row.key == *focused)) else { return };
let row = &rows[index];
let expandable = !matches!(row.children, HoverChildren::None);
context.insert("treeElementCanCollapse".into(), json!(expandable && row.expanded));
context.insert("treeElementCanExpand".into(), json!(expandable && !row.expanded));
context.insert("treeElementHasChild".into(), json!(rows.get(index + 1).is_some_and(|child| child.depth > row.depth)));
context.insert("treeElementHasParent".into(), json!(row.depth > 0));
}
}
/// `DebugHoverWidget.showAt`: the expression at `position`, unchanged when its range is the shown one, then its value.
async fn show_at(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, position: Anchor, focus: bool, mouse: Option<Point<f32>>) -> ShowResult {
let Ok(Some(session_id)) = on_workbench(workbench, cx, |workbench, _, _| workbench.debug.focus.session.clone()) else { return ShowResult::NotAvailable };
let Some((range, expression)) = evaluatable_expression_at(workbench, cx, position).await else { return ShowResult::NotAvailable };
let Ok(unchanged) = on_workbench(workbench, cx, |workbench, _, _| {
let unchanged = workbench.debug_hover.current == Some(range);
workbench.debug_hover.current = Some(range);
unchanged && workbench.debug_hover.shown.is_some()
}) else {
return ShowResult::NotAvailable;
};
if unchanged {
return ShowResult::NotChanged;
}
let Some(value) = evaluate_hover(workbench, cx, &session_id, range, &expression).await else { return ShowResult::NotAvailable };
let _ = on_workbench(workbench, cx, |workbench, window, cx| workbench.set_debug_hover_value(range, session_id, value, focus, mouse, window, cx));
ShowResult::Shown
}
/// debugUtils.ts `getEvaluatableExpressionAtPosition`: the first `EvaluatableExpressionProvider` answer, its text
/// the range's when it names no expression; without providers, the expression around the position on its line.
async fn evaluatable_expression_at(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, position: Anchor) -> Option<(Anchor, String)> {
let calls = on_workbench(workbench, cx, |workbench, _, _| {
let editor = workbench.editors.editor_by_id(position.model_id)?;
let document = editor.document();
let uri = document.uri();
let candidate = Candidate { uri: &uri, language: &document.language_id };
let column = utf16_column(&document.lines[position.line], position.start) + 1;
let at = json!({ "lineNumber": position.line + 1, "column": column });
let handles: Vec<u64> = workbench.language_features.ordered(REGISTER, &candidate).iter().map(|registration| registration.handle).collect();
Some(handles.into_iter().map(|handle| workbench.host.call_cancellable("ExtHostLanguageFeatures", "$provideEvaluatableExpression", vec![json!(handle), uri.clone(), at.clone()])).collect::<Vec<_>>())
})
.ok()??;
if calls.is_empty() {
let line = on_workbench(workbench, cx, |workbench, _, _| workbench.editors.editor_by_id(position.model_id).map(|editor| editor.document().lines[position.line].clone())).ok()??;
let (start, end) = exact_expression_start_and_end(&line, position.start + 1, position.start + 1);
let expression: String = line.chars().skip(start.max(1) - 1).take((end + 1).saturating_sub(start.max(1))).collect();
if start == 0 || expression.is_empty() {
return None;
}
let length = expression.chars().count();
return Some((Anchor { start: start - 1, end: start - 1 + length, ..position }, expression));
}
let mut answers = Vec::new();
for call in calls {
answers.push(call.await);
}
let found = answers.into_iter().find_map(|answer| answer.ok()?.ok().filter(|value| value["range"].is_object()))?;
on_workbench(workbench, cx, |workbench, _, _| {
let editor = workbench.editors.editor_by_id(position.model_id)?;
let (start, end) = super::host_requests::range(editor, &found["range"]);
let expression = match found["expression"].as_str().filter(|expression| !expression.is_empty()) {
Some(expression) => expression.to_owned(),
None => editor.document().lines[position.line].chars().skip(start.column).take(end.column.saturating_sub(start.column)).collect(),
};
let end_column = if end.line == start.line { end.column } else { editor.document().lines[start.line].chars().count() };
Some((Anchor { model_id: position.model_id, line: start.line, start: start.column, end: end_column }, expression))
})
.ok()?
}
/// DebugHoverComputer `evaluate`: with `supportsEvaluateForHovers` the `hover` evaluation at the range in the focused
/// frame, else the variable the dotted names reach in its scopes. `None` when it is not available.
async fn evaluate_hover(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, session_id: &str, range: Anchor, expression: &str) -> Option<Variable> {
let (frame, for_hovers, column) = on_workbench(workbench, cx, |workbench, _, _| {
let frame = workbench.debug.focused_frame()?.clone();
let for_hovers = workbench.debug.session(session_id)?.capabilities["supportsEvaluateForHovers"] == true;
let line = &workbench.editors.editor_by_id(range.model_id)?.document().lines[range.line];
Some((frame, for_hovers, utf16_column(line, range.start) + 1))
})
.ok()??;
if for_hovers {
let arguments = json!({ "expression": expression, "frameId": frame.id, "context": "hover", "line": range.line + 1, "column": column, "source": frame.source });
let reply = on_workbench(workbench, cx, |workbench, _, _| workbench.dap_request(session_id, "evaluate", arguments)).ok()?;
let body = answer(reply).await.ok().filter(|body| !body.is_null())?;
let mut value = Variable { name: expression.to_owned(), ..Variable::from_dap(&body) };
// debugModel.ts `evaluateExpression` without `keepLazyVars`.
if value.is_lazy() {
evaluate_lazy(workbench, cx, session_id, &mut value).await;
}
return Some(value);
}
let names: Vec<&str> = expression.split('.').map(str::trim).filter(|name| !name.is_empty()).collect();
find_expression_in_frame(workbench, cx, session_id, frame.id, &names).await
}
/// debugHover.ts `findExpressionInStackFrame`: in each scope that is not expensive, the variable named by the first
/// name, then its child named by the next; shown only when every scope that has it has the same value.
async fn find_expression_in_frame(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, session_id: &str, frame_id: i64, names: &[&str]) -> Option<Variable> {
let reply = on_workbench(workbench, cx, |workbench, _, _| workbench.dap_request(session_id, "scopes", json!({ "frameId": frame_id }))).ok()?;
let scopes = answer(reply).await.ok()?;
let mut found: Vec<Variable> = Vec::new();
for scope in scopes["scopes"].as_array().into_iter().flatten().filter(|scope| scope["expensive"] != true) {
let mut reference = scope["variablesReference"].as_i64().unwrap_or(0);
let mut variable = None;
for name in names {
let reply = on_workbench(workbench, cx, |workbench, _, _| workbench.dap_request(session_id, "variables", json!({ "variablesReference": reference }))).ok()?;
let body = answer(reply).await.unwrap_or_default();
let children: Vec<Variable> = body["variables"].as_array().into_iter().flatten().map(Variable::from_dap).filter(|child| child.name == *name).collect();
variable = match <[Variable; 1]>::try_from(children) {
Ok([child]) => Some(child),
Err(_) => None,
};
let Some(child) = &variable else { break };
reference = child.variables_reference;
}
found.extend(variable);
}
let first = found.first()?;
found.iter().all(|variable| variable.value == first.value).then(|| first.clone())
}
static EXPRESSION: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?:[^()\[\]{}<>\s+\-/%~#^;=|,`!]|->)+").expect("a valid pattern"));
/// JavaScript's `\w` is ASCII.
static SUB_EXPRESSION: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?:[0-9A-Za-z_]|\p{L})+").expect("a valid pattern"));
/// debugUtils.ts `getExactExpressionStartAndEnd`: the 1-based first and last column of the expression around
/// `loose_start..loose_end` (`a.b.c`, `a?.b`, `a->b`, `A::b`, `...a` as `a`), cut after the word under the end;
/// `(0, 0)` without one. Columns count chars where JavaScript counts UTF-16 units.
pub(super) fn exact_expression_start_and_end(line: &str, loose_start: usize, loose_end: usize) -> (usize, usize) {
let chars = |bytes: &str| bytes.chars().count();
let Some(found) = EXPRESSION.find_iter(line).find(|found| {
let start = chars(&line[..found.start()]) + 1;
start <= loose_start && start + chars(found.as_str()) >= loose_end
}) else {
return (0, 0);
};
let mut start = chars(&line[..found.start()]) + 1;
let mut expression = found.as_str();
if let Some(spread) = expression.strip_prefix("...").filter(|rest| !rest.is_empty()) {
expression = spread;
start += 3;
}
for sub in SUB_EXPRESSION.find_iter(expression) {
if chars(&expression[..sub.end()]) + start >= loose_end {
expression = &expression[..sub.end()];
break;
}
}
(start, start + chars(expression) - 1)
}
/// mouseTarget.ts `createMouseTargetFromHitTestPosition`'s position on the text: the caret position nearest the
/// mouse, the character's end once the mouse passes its middle, as the empty anchor there; `None` past the line's end.
fn hover_position(editor: &OpenEditor, line: usize, visible: f32) -> Option<Anchor> {
let under = anchor_at(editor, line, visible)?;
let text = &editor.document().lines[line];
let tab_size = editor.document().indentation.tab_size;
let (left, right) = (column_x(text, under.start, tab_size), column_x(text, under.end, tab_size));
let column = if visible - left < (right - left) / 2. { under.start } else { under.end };
Some(Anchor { start: column, end: column, ..under })
}
/// debugHover.ts `layoutTree`: max(266px, 55% of the editor), at most the rows and the 10px scrollbar, and at most
/// what keeps an above hover off the hovered line. The tree starts under the title and its 1px border; `editor_top`
/// is the editor's `offsetTop` in its group's `.split-view-view`: the group title and breadcrumbs above it.
fn tree_height(editor_height: f32, editor_top: f32, rows: usize, padding: f32, hovered_line_top: f32) -> f32 {
let container_top = ROW_HEIGHT + 1. + editor_top;
let avoid_cursor = if container_top < hovered_line_top { hovered_line_top + editor_top - PAGE_PADDING } else { f32::INFINITY };
266f32.max(editor_height * 0.55).min(padding + rows as f32 * ROW_HEIGHT + 10.).min(avoid_cursor)
}
/// dom.ts `SafeTriangle.contains`: the four triangles from the origin to the widget's corners, in its point order.
fn in_safe_triangle(origin: Point<f32>, bounds: Bounds<f32>, mouse: Point<f32>) -> bool {
let (left, top, right, bottom) = (bounds.origin.x, bounds.origin.y, bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height);
let corners = [point(left, top), point(right, top), point(left, bottom), point(right, bottom)];
(0..4).any(|index| is_point_within_triangle(mouse, origin, corners[index], corners[(index + 1) % 4]))
}
/// numbers.ts `isPointWithinTriangle`.
fn is_point_within_triangle(p: Point<f32>, a: Point<f32>, b: Point<f32>, c: Point<f32>) -> bool {
let (v0, v1, v2) = (c - a, b - a, p - a);
let dot = |u: Point<f32>, v: Point<f32>| u.x * v.x + u.y * v.y;
let (dot00, dot01, dot02, dot11, dot12) = (dot(v0, v0), dot(v0, v1), dot(v0, v2), dot(v1, v1), dot(v1, v2));
let inverse = 1. / (dot00 * dot11 - dot01 * dot01);
let u = (dot11 * dot02 - dot01 * dot12) * inverse;
let v = (dot00 * dot12 - dot01 * dot02) * inverse;
u >= 0. && v >= 0. && u + v < 1.
}