Skip to content

Visual Studio Code, rebuilt in Rust

Rust
19.1 KB
Raw Blame
//! breakpointEditorContribution.ts's inline breakpoints: the `InlineBreakpointWidget` before a column breakpoint
//! and the candidate dots the focused session's `breakpointLocations` answers on the breakpoints' lines.

use std::collections::HashMap;

use gpui::{AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, Window, div, prelude::*, px};
use serde_json::{Value, json};

use super::Workbench;
use super::breakpoint_widget::breakpoint_icon;
use crate::debug::session::State;
use crate::debug::{Breakpoint, BreakpointData};
use crate::editor::injected_text::{InjectedText, InjectionOwner, WrapWidth};
use crate::editor::{OpenEditor, Position};

/// One `InlineBreakpointWidget`: its 1-based decoration start, icon, and the breakpoint it toggles (none for a
/// candidate, which adds one).
#[derive(Clone, Debug, PartialEq)]
pub struct InlineWidget {
    pub line: u32,
    pub column: u32,
    pub icon: &'static str,
    pub breakpoint: Option<String>,
}

#[derive(Default)]
pub struct InlineBreakpoints {
    /// The widgets of each model URI; an injection's `id` indexes its model's.
    pub widgets: HashMap<String, Vec<InlineWidget>>,
    /// The session, debug state and breakpoint lines each model's candidates were asked for, and the 1-based
    /// positions answered.
    asked: HashMap<String, (String, State, Vec<u32>)>,
    candidates: HashMap<String, Vec<(u32, u32)>>,
}

/// A breakpoint decoration of `createBreakpointDecorations`: its 1-based start and whether it renders inline.
struct BreakpointDecoration<'a> {
    breakpoint: &'a Breakpoint,
    line: u32,
    column: u32,
    inline: bool,
}

impl Workbench {
    /// `setDecorations` in every editor, run on every render: the inline widgets of breakpoints and candidates, each
    /// after a `debug-breakpoint-placeholder` of `0.9em` when it has one.
    pub(super) fn sync_inline_breakpoints(&mut self, cx: &mut Context<Self>) {
        self.request_breakpoint_candidates(cx);
        let placeholder = 0.9 * super::editor_view::EDITOR_FONT_SIZE * self.editor_zoom.multiplier() / self.editors.viewport.char_width;
        let mut widgets = HashMap::new();
        let mut wanted = Vec::new();
        for editor in self.editors.all_editors() {
            let (editor_widgets, injections) = self.inline_breakpoints(editor, placeholder);
            if !editor_widgets.is_empty() {
                widgets.insert(editor.document().uri_string(), editor_widgets);
            }
            wanted.push(injections);
        }
        self.debug.inline_breakpoints.widgets = widgets;
        for (editor, injections) in self.editors.all_editors_mut().zip(wanted) {
            let current = editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::InlineBreakpoint);
            if !current.eq(injections.iter()) {
                editor.set_injected_text(InjectionOwner::InlineBreakpoint, injections);
            }
        }
    }

    fn inline_breakpoints(&self, editor: &OpenEditor, placeholder: f32) -> (Vec<InlineWidget>, Vec<InjectedText>) {
        let document = editor.document();
        let uri = document.uri_string();
        let lines = &document.lines;
        let debug_active = matches!(self.debug.state(), State::Running | State::Stopped);
        let icon = |breakpoint: &Breakpoint| breakpoint_icon(breakpoint, &self.debug.model, debug_active, editor.is_dirty()).0;
        let decorations = breakpoint_decorations(self.debug.model.breakpoints_in(&uri).collect(), lines);
        let mut widgets = Vec::new();
        let mut injections = Vec::new();
        let mut push = |widget: InlineWidget, columns: Option<f32>| {
            let index = widget.line as usize - 1;
            let position = Position::new(index, (widget.column as usize - 1).min(lines[index].chars().count()));
            let (content, columns) = columns.map_or((String::new(), 0.), |columns| ("\u{a0}".into(), columns));
            injections.push(InjectedText { position, columns, content, wrap: WrapWidth::Fixed, owner: InjectionOwner::InlineBreakpoint, id: widgets.len(), at_range_start: true });
            widgets.push(widget);
        };
        for decoration in decorations.iter().filter(|decoration| decoration.inline) {
            let widget = InlineWidget { line: decoration.line, column: decoration.column, icon: icon(decoration.breakpoint), breakpoint: Some(decoration.breakpoint.id().to_owned()) };
            push(widget, Some(placeholder));
        }
        // `createCandidateDecorations`.
        let candidates = self.debug.inline_breakpoints.candidates.get(&uri).map(Vec::as_slice).unwrap_or_default();
        for &(line, column) in candidates {
            let Some(text) = lines.get(line as usize - 1) else { continue };
            let (first, last) = (first_non_whitespace_column(text), last_non_whitespace_column(text));
            let later_on_line = decorations.iter().any(|decoration| decoration.line == line && decoration.column > first);
            // Not at the line's start without another breakpoint on the line, nor past its end.
            if (column <= first && !later_on_line) || column > last {
                continue;
            }
            let at_position = decorations.iter().find(|decoration| decoration.line == line && decoration.column == column);
            match at_position {
                // Space already occupied.
                Some(decoration) if decoration.inline => {}
                Some(decoration) => push(InlineWidget { line, column, icon: icon(decoration.breakpoint), breakpoint: Some(decoration.breakpoint.id().to_owned()) }, None),
                None => push(InlineWidget { line, column, icon: "debug-breakpoint-disabled", breakpoint: None }, Some(placeholder)),
            }
        }
        injections.sort_by_key(|injection| injection.position);
        (widgets, injections)
    }

    /// `requestBreakpointCandidateLocations` with `debug.showInlineBreakpointCandidates` on: the focused session's
    /// `breakpointLocations` for each breakpoint line of each model, asked again when the session, its state
    /// (`onDidChangeState`) or the lines change.
    fn request_breakpoint_candidates(&mut self, cx: &mut Context<Self>) {
        let session = self.debug.focused_session().filter(|session| session.capabilities["supportsBreakpointLocationsRequest"] == true).map(|session| session.id.clone());
        let Some(session_id) = session.filter(|_| self.setting("debug.showInlineBreakpointCandidates") == true) else {
            self.debug.inline_breakpoints.asked.clear();
            self.debug.inline_breakpoints.candidates.clear();
            return;
        };
        let mut asks = Vec::new();
        for editor in self.editors.all_editors() {
            let document = editor.document();
            let uri = document.uri_string();
            let mut lines: Vec<u32> = self.debug.model.breakpoints_in(&uri).map(Breakpoint::line_number).filter(|line| *line as usize <= document.lines.len()).collect();
            lines.sort();
            lines.dedup();
            let key = (session_id.clone(), self.debug.state(), lines);
            if self.debug.inline_breakpoints.asked.get(&uri) != Some(&key) {
                asks.push((uri, document.uri(), key));
            }
        }
        for (uri, document_uri, key) in asks {
            let source = super::debug_service::source_of_uri(&document_uri);
            let replies: Vec<_> = key.2.iter().map(|line| self.dap_request(&session_id, "breakpointLocations", json!({ "source": source, "line": line }))).collect();
            self.debug.inline_breakpoints.asked.insert(uri.clone(), key.clone());
            cx.spawn(async move |this, cx| {
                let mut positions = Vec::new();
                for reply in replies {
                    // A failed request has no positions.
                    let body = super::debug_service::answer(reply).await.unwrap_or_default();
                    for location in body["breakpoints"].as_array().into_iter().flatten() {
                        let position = (location["line"].as_u64().unwrap_or_default() as u32, location["column"].as_u64().unwrap_or(1) as u32);
                        if !positions.contains(&position) {
                            positions.push(position);
                        }
                    }
                }
                let _ = this.update(cx, |workbench, cx| {
                    let candidates = &mut workbench.debug.inline_breakpoints;
                    if candidates.asked.get(&uri) == Some(&key) {
                        candidates.candidates.insert(uri, positions);
                        cx.notify();
                    }
                });
            })
            .detach();
        }
    }

    /// `InlineBreakpointWidget`: `ceil(0.8 * lineHeight)` wide with a 4px left margin at the column before its
    /// decoration (`left: -8px` at the line's start); disabled-icon candidates at 0.7 opacity.
    pub(super) fn inline_breakpoint_element(&self, editor: &OpenEditor, id: usize, anchor: Option<f32>, line_height: f32, cx: &mut Context<Self>) -> Option<AnyElement> {
        let uri = editor.document().uri_string();
        let widget = self.debug.inline_breakpoints.widgets.get(&uri)?.get(id)?.clone();
        let icon = self.breakpoint_icon(widget.icon, 16.).when(widget.icon == "debug-breakpoint-disabled", |icon| icon.opacity(0.7));
        let left = anchor.unwrap_or(-8.) + 4.;
        let document_uri = editor.document().uri();
        let menu_widget = widget.clone();
        let menu_uri = document_uri.clone();
        let element = div()
            .id(("inline-breakpoint", id))
            .debug_selector(|| "inline-breakpoint-widget".into())
            .absolute()
            .top_0()
            .left(px(left))
            .w(px((0.8 * line_height).ceil()))
            .h(px(line_height))
            .flex()
            .items_center()
            .cursor_pointer()
            .child(icon)
            // `suppressMouseDown`: the editor does not take the press.
            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                workbench.show_inline_breakpoint_menu(&menu_uri, &menu_widget, event.position, window, cx);
            }))
            .on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| workbench.inline_breakpoint_clicked(&document_uri, &widget, cx)));
        Some(element.into_any_element())
    }

    /// The widget's click: a candidate adds a breakpoint at its column, an enabled breakpoint goes, a disabled one is enabled.
    fn inline_breakpoint_clicked(&mut self, uri: &Value, widget: &InlineWidget, cx: &mut Context<Self>) {
        let enabled = widget.breakpoint.as_deref().and_then(|id| self.debug.model.breakpoint(id)).map(|breakpoint| breakpoint.base.enabled);
        let change = match (enabled, &widget.breakpoint) {
            (Some(true), Some(id)) => self.debug.model.remove_breakpoints(std::slice::from_ref(id)),
            (Some(false), Some(id)) => self.debug.model.set_enablement(id, true),
            _ => self.debug.model.add_breakpoints(uri, vec![BreakpointData { column: Some(widget.column), ..BreakpointData::at(widget.line) }]),
        };
        self.breakpoints_changed(change, true, cx);
        cx.notify();
    }

    fn show_inline_breakpoint_menu(&mut self, uri: &Value, widget: &InlineWidget, pointer: gpui::Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let breakpoints: Vec<Breakpoint> = widget.breakpoint.as_deref().and_then(|id| self.debug.model.breakpoint(id)).cloned().into_iter().collect();
        let actions = self.breakpoint_menu_actions(breakpoints, uri.clone(), widget.line, Some(widget.column));
        let context = self.key_context(window);
        self.show_context_menu_actions(actions, &context, super::editor_menus::point_anchor(pointer), Vec::new(), window, cx);
    }
}

/// `createBreakpointDecorations`: each breakpoint at its column or the line's first non-whitespace one, inline when
/// it has a column past that or shares its line.
fn breakpoint_decorations<'a>(breakpoints: Vec<&'a Breakpoint>, lines: &[String]) -> Vec<BreakpointDecoration<'a>> {
    let mut decorations = Vec::new();
    for breakpoint in &breakpoints {
        let line = breakpoint.line_number();
        let Some(text) = lines.get(line as usize - 1) else { continue };
        let first = first_non_whitespace_column(text);
        let others = breakpoints.iter().any(|other| !std::ptr::eq(*other, *breakpoint) && other.line_number() == line);
        // `validateRange`: within 1 and the line's end column.
        let column = breakpoint.column().unwrap_or(first).clamp(1, text.chars().count() as u32 + 1);
        let inline = breakpoint.column().is_some_and(|column| others || column > first);
        decorations.push(BreakpointDecoration { breakpoint, line, column, inline });
    }
    decorations
}

/// `getLineFirstNonWhitespaceColumn`: 1-based, 0 for a blank line.
fn first_non_whitespace_column(text: &str) -> u32 {
    text.chars().position(|c| c != ' ' && c != '\t').map_or(0, |index| index as u32 + 1)
}

/// `getLineLastNonWhitespaceColumn`: the 1-based column after the last non-whitespace char, 0 for a blank line.
fn last_non_whitespace_column(text: &str) -> u32 {
    let chars: Vec<char> = text.chars().collect();
    chars.iter().rposition(|c| *c != ' ' && *c != '\t').map_or(0, |index| index as u32 + 2)
}

#[cfg(test)]
mod tests {
    use gpui::TestAppContext;

    use super::super::testing_gutter::tests::titles;
    use super::super::variable_menu::tests::{respond, sent_request, stopped_session};
    use super::*;

    fn open(workbench: &gpui::Entity<Workbench>, text: &str, cx: &mut gpui::VisualTestContext) -> (std::path::PathBuf, Value, String) {
        let dir = std::env::temp_dir().join(format!("vsrustium-{}", crate::test_name()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("a.js");
        std::fs::write(&file, text).unwrap();
        let (uri, uri_string) = workbench.update_in(cx, |workbench, window, cx| {
            workbench.open_file(file.clone(), true, window, cx);
            let document = workbench.editors.active().unwrap().document();
            (document.uri(), document.uri_string())
        });
        cx.run_until_parked();
        (dir, uri, uri_string)
    }

    fn widgets(workbench: &gpui::Entity<Workbench>, uri: &str, cx: &mut gpui::VisualTestContext) -> Vec<(u32, u32, &'static str, bool)> {
        workbench.read_with(cx, |workbench, _| workbench.debug.inline_breakpoints.widgets.get(uri).into_iter().flatten().map(|widget| (widget.line, widget.column, widget.icon, widget.breakpoint.is_some())).collect())
    }

    /// (column, width in px) of each placeholder on the active editor's first line.
    fn placeholders(workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext) -> Vec<(usize, f32)> {
        workbench.read_with(cx, |workbench, _| {
            let editor = workbench.editors.active().unwrap();
            editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::InlineBreakpoint).map(|injection| (injection.position.column, (injection.columns * workbench.editors.viewport.char_width * 10.).round() / 10.)).collect()
        })
    }

    fn click_widget(cx: &mut gpui::VisualTestContext) {
        let bounds = cx.debug_bounds("inline-breakpoint-widget").expect("an inline breakpoint widget draws");
        cx.simulate_click(bounds.center(), gpui::Modifiers::none());
        cx.run_until_parked();
    }

    /// `requestBreakpointCandidateLocations` and `createCandidateDecorations`: the breakpoint line's
    /// `breakpointLocations` answer a dot past the line's first column, not one at it or past its end; clicking the dot
    /// adds an inline breakpoint there, after which the line breakpoint's own position takes a widget too.
    #[gpui::test]
    fn candidate_dots_come_from_breakpoint_locations_and_add_a_breakpoint(cx: &mut TestAppContext) {
        let (workbench, cx, host) = stopped_session(cx, json!({ "supportsBreakpointLocationsRequest": true }));
        let (dir, uri, uri_string) = open(&workbench, "\tconsole.log(a, b);\n", cx);
        workbench.update(cx, |workbench, cx| {
            workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData::at(1)]);
            cx.notify();
        });
        cx.run_until_parked();
        let request = sent_request(&host, "breakpointLocations");
        assert_eq!(request["arguments"]["line"], 1);
        assert_eq!(request["arguments"]["source"]["name"], "a.js");
        respond(&workbench, cx, &request, true, json!({ "breakpoints": [{ "line": 1, "column": 2 }, { "line": 1, "column": 10 }, { "line": 1, "column": 10 }, { "line": 1, "column": 40 }] }));
        assert_eq!(widgets(&workbench, &uri_string, cx), [(1, 10, "debug-breakpoint-disabled", false)]);
        assert_eq!(placeholders(&workbench, cx), [(9, 10.8)]);

        click_widget(cx);
        let column = workbench.read_with(cx, |workbench, _| workbench.debug.model.breakpoints_in(&uri_string).filter_map(Breakpoint::column).collect::<Vec<_>>());
        assert_eq!(column, [10]);
        let mut drawn = widgets(&workbench, &uri_string, cx);
        drawn.sort();
        assert_eq!(drawn.iter().map(|(line, column, _, has_breakpoint)| (*line, *column, *has_breakpoint)).collect::<Vec<_>>(), [(1, 2, true), (1, 10, true)]);
        assert_eq!(placeholders(&workbench, cx), [(1, 0.), (9, 10.8)], "the line breakpoint's widget takes no room");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// `InlineBreakpointWidget`: a column breakpoint past the line's first column draws inline after a `0.9em`
    /// placeholder; its menu is the breakpoint's, a click enables it when disabled and removes it when enabled.
    #[gpui::test]
    fn a_column_breakpoint_draws_inline_and_toggles_on_click(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = stopped_session(cx, json!({}));
        let (dir, uri, uri_string) = open(&workbench, "let a = f();\n", cx);
        workbench.update(cx, |workbench, cx| {
            workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData { column: Some(9), enabled: false, ..BreakpointData::at(1) }]);
            cx.notify();
        });
        cx.run_until_parked();
        assert_eq!(widgets(&workbench, &uri_string, cx), [(1, 9, "debug-breakpoint-disabled", true)]);
        assert_eq!(placeholders(&workbench, cx), [(8, 10.8)]);

        let bounds = cx.debug_bounds("inline-breakpoint-widget").unwrap();
        let actions = workbench.update_in(cx, |workbench, window, cx| {
            let widget = workbench.debug.inline_breakpoints.widgets[&uri_string][0].clone();
            workbench.show_inline_breakpoint_menu(&uri, &widget, bounds.center(), window, cx);
            workbench.context_menu.take().expect("a context menu shows").levels[0].actions.clone()
        });
        assert_eq!(titles(&actions), ["Remove Breakpoint", "Edit Breakpoint...", "Enable Breakpoint"]);

        click_widget(cx);
        assert_eq!(widgets(&workbench, &uri_string, cx)[0].2, "debug-breakpoint");
        click_widget(cx);
        assert!(workbench.read_with(cx, |workbench, _| workbench.debug.model.breakpoints.is_empty()));
        assert!(placeholders(&workbench, cx).is_empty());
        std::fs::remove_dir_all(dir).unwrap();
    }
}