Skip to content

Visual Studio Code, rebuilt in Rust

Rust
53.7 KB
Raw Blame
//! Breakpoints in the editor: the glyph margin decorations, hint, clicks and context menu of
//! breakpointEditorContribution.ts, the call stack line decorations of callStackEditorContribution.ts, and the
//! breakpoint widget (breakpointWidget.ts) that edits a condition, hit count or log message in a zone below the line.

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

use super::Workbench;
use super::input_box_view::{InputId, InputLook};
use crate::commands::Outcome;
use crate::debug::{Breakpoint, BreakpointData, DebugModel};
use crate::editor::injected_text::{InjectedText, InjectionOwner, WrapWidth};
use crate::editor::{OpenEditor, Position};
use crate::input_box::InputBox;
use crate::menus::MenuAction;

/// breakpointWidget.ts `Context`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WidgetContext {
    Condition,
    HitCount,
    LogMessage,
    TriggerPoint,
}

pub struct BreakpointWidget {
    pub model_uri: String,
    pub uri: Value,
    /// 1-based line and the zone that shows the widget below it.
    pub line: u32,
    /// The column a new breakpoint takes: an inline breakpoint widget's context menu adds at its column.
    pub column: Option<u32>,
    pub zone_id: u32,
    pub breakpoint: Option<String>,
    pub context: WidgetContext,
    pub input: InputBox,
    /// The values typed for the other contexts before switching (`conditionInput`, `hitCountInput`, `logMessageInput`).
    pub condition: String,
    pub hit_count: String,
    pub log_message: String,
    /// `triggeredByBreakpointInput`: the breakpoint picked in the Wait for Breakpoint select box.
    pub triggered_by: Option<String>,
}

/// getBreakpointMessageAndIcon for a source breakpoint: the icon id and the hover message.
pub fn breakpoint_icon(breakpoint: &Breakpoint, model: &DebugModel, debug_active: bool, dirty: bool) -> (&'static str, String) {
    let log = breakpoint.base.log_message.is_some();
    if !breakpoint.base.enabled || !model.breakpoints_activated {
        let icon = if log { "debug-breakpoint-log-disabled" } else { "debug-breakpoint-disabled" };
        return (icon, if log { "Disabled Logpoint".into() } else { "Disabled Breakpoint".into() });
    }
    if debug_active && breakpoint.pending() {
        return ("debug-breakpoint-pending", String::new());
    }
    if debug_active && !breakpoint.verified(dirty) {
        let icon = if log { "debug-breakpoint-log-unverified" } else { "debug-breakpoint-unverified" };
        let message = breakpoint.message(dirty).unwrap_or_else(|| if log { "Unverified Logpoint".into() } else { "Unverified Breakpoint".into() });
        return (icon, message);
    }
    let triggering = breakpoint.triggered_by.as_deref().and_then(|id| model.breakpoint(id));
    let append = |text: String| match breakpoint.message(dirty) {
        Some(message) => format!("{text}, {message}"),
        None => text,
    };
    if log || breakpoint.base.condition.is_some() || breakpoint.base.hit_condition.is_some() || triggering.is_some() {
        let mut messages = Vec::new();
        let mut icon = if log { "debug-breakpoint-log" } else { "debug-breakpoint-conditional" };
        if !breakpoint.supported() {
            icon = "debug-breakpoint-unsupported";
            messages.push("Breakpoints of this type are not supported by the debugger".to_owned());
        }
        if let Some(message) = &breakpoint.base.log_message {
            messages.push(format!("Log Message: {message}"));
        }
        if let Some(condition) = &breakpoint.base.condition {
            messages.push(format!("Condition: {condition}"));
        }
        if let Some(hit_condition) = &breakpoint.base.hit_condition {
            messages.push(format!("Hit Count: {hit_condition}"));
        }
        if let Some(trigger) = triggering {
            let name = trigger.uri["path"].as_str().and_then(|path| path.rsplit('/').next()).unwrap_or_default();
            messages.push(format!("Hit after breakpoint: {name}: {}", trigger.line_number()));
        }
        return (icon, append(messages.join("\n")));
    }
    let message = breakpoint.message(dirty).unwrap_or_else(|| breakpoint.uri["path"].as_str().unwrap_or_default().to_owned());
    ("debug-breakpoint", message)
}

/// breakpointEditorContribution.ts and debug.contribution.css: the color of the dot a stack frame glyph draws over a
/// plain or conditional breakpoint; the frame's own color rule comes last, so only the plain one's dot stays red.
fn stack_frame_dot(breakpoint_icon: &str, frame_icon: &str) -> Option<&'static str> {
    match breakpoint_icon {
        "debug-breakpoint" => Some("debugIcon.breakpointForeground"),
        "debug-breakpoint-conditional" => Some(icon_file_and_color(frame_icon).1),
        _ => None,
    }
}

/// The codicon file of a debug icon id (codiconsLibrary.ts aliases) and the color debug.contribution's rules give it.
pub fn icon_file_and_color(icon: &str) -> (&'static str, &'static str) {
    match icon {
        "debug-breakpoint" => ("circle-filled", "debugIcon.breakpointForeground"),
        "debug-breakpoint-disabled" => ("circle-filled", "debugIcon.breakpointDisabledForeground"),
        "debug-breakpoint-unverified" => ("circle", "debugIcon.breakpointUnverifiedForeground"),
        "debug-breakpoint-pending" => ("circle-small-filled", "debugIcon.breakpointForeground"),
        "debug-hint" => ("circle-filled", "debugIcon.breakpointForeground"),
        "debug-breakpoint-conditional" => ("debug-breakpoint-conditional", "debugIcon.breakpointForeground"),
        "debug-breakpoint-conditional-disabled" => ("debug-breakpoint-conditional", "debugIcon.breakpointDisabledForeground"),
        "debug-breakpoint-conditional-unverified" => ("debug-breakpoint-conditional-unverified", "debugIcon.breakpointUnverifiedForeground"),
        "debug-breakpoint-log" => ("debug-breakpoint-log", "debugIcon.breakpointForeground"),
        "debug-breakpoint-log-disabled" => ("debug-breakpoint-log", "debugIcon.breakpointDisabledForeground"),
        "debug-breakpoint-log-unverified" => ("debug-breakpoint-log-unverified", "debugIcon.breakpointUnverifiedForeground"),
        "debug-breakpoint-function" => ("debug-breakpoint-function", "debugIcon.breakpointForeground"),
        "debug-breakpoint-function-disabled" => ("debug-breakpoint-function", "debugIcon.breakpointDisabledForeground"),
        "debug-breakpoint-function-unverified" => ("debug-breakpoint-function-unverified", "debugIcon.breakpointUnverifiedForeground"),
        "debug-breakpoint-unsupported" => ("debug-breakpoint-unsupported", "debugIcon.breakpointForeground"),
        "debug-stackframe" => ("debug-stackframe", "debugIcon.breakpointCurrentStackframeForeground"),
        "debug-stackframe-focused" => ("debug-stackframe", "debugIcon.breakpointStackframeForeground"),
        _ => ("circle-filled", "debugIcon.breakpointForeground"),
    }
}

/// breakpointWidget.ts placeholders, by context.
fn placeholder(context: WidgetContext) -> &'static str {
    match context {
        WidgetContext::Condition | WidgetContext::TriggerPoint => "Break when expression evaluates to true. 'Enter' to accept, 'esc' to cancel.",
        WidgetContext::HitCount => "Break when hit count condition is met. 'Enter' to accept, 'esc' to cancel.",
        WidgetContext::LogMessage => "Message to log when breakpoint is hit. Expressions within {} are interpolated. 'Enter' to accept, 'esc' to cancel.",
    }
}

const CONTEXT_LABELS: [(WidgetContext, &str); 4] = [(WidgetContext::Condition, "Expression"), (WidgetContext::HitCount, "Hit Count"), (WidgetContext::LogMessage, "Log Message"), (WidgetContext::TriggerPoint, "Wait for Breakpoint")];

impl Workbench {
    pub(super) fn register_breakpoint_widget_commands(&mut self) {
        self.commands.register("breakpointWidget.action.acceptInput", |workbench, _, window, cx| {
            workbench.accept_breakpoint_widget(window, cx);
            Outcome::done()
        });
        self.commands.register("closeBreakpointWidget", |workbench, _, window, cx| {
            workbench.close_breakpoint_widget(window, cx);
            Outcome::done()
        });
        self.commands.register("_debug.breakpointWidget.selectTrigger", |workbench, args, window, cx| {
            if let Some(widget) = workbench.breakpoint_widget.as_mut() {
                widget.triggered_by = args.first().and_then(Value::as_str).map(str::to_owned);
            }
            window.focus(&workbench.debug_view.widget_focus, cx);
            cx.notify();
            Outcome::done()
        });
        // The glyph margin and inline breakpoint context menus' actions, with `[uri, line, column?]` arguments.
        self.commands.register("_debug.gutter.addBreakpoint", |workbench, args, _, cx| {
            let (uri, line, column) = gutter_args(&args);
            let change = workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData { column, ..BreakpointData::at(line) }]);
            workbench.breakpoints_changed(change, true, cx);
            Outcome::done()
        });
        let adds = [("_debug.gutter.addConditionalBreakpoint", WidgetContext::Condition), ("_debug.gutter.addLogpoint", WidgetContext::LogMessage), ("_debug.gutter.addTriggeredBreakpoint", WidgetContext::TriggerPoint)];
        for (id, context) in adds {
            self.commands.register(id, move |workbench, args, window, cx| {
                let (_, line, column) = gutter_args(&args);
                workbench.show_breakpoint_widget(line, column, None, context, window, cx);
                Outcome::done()
            });
        }
        self.commands.register("_debug.gutter.runToLine", |workbench, args, window, cx| {
            let (uri, line, _) = gutter_args(&args);
            workbench.run_to_line(&uri, line, None, window, cx);
            Outcome::done()
        });
        // The actions on one breakpoint, with its id as the argument.
        self.commands.register("_debug.gutter.editBreakpoint", |workbench, args, window, cx| {
            let Some(breakpoint) = args.first().and_then(Value::as_str).and_then(|id| workbench.debug.model.breakpoint(id)) else { return Outcome::done() };
            let (line, id) = (breakpoint.line_number(), breakpoint.id().to_owned());
            workbench.show_breakpoint_widget(line, None, Some(id), WidgetContext::Condition, window, cx);
            Outcome::done()
        });
        self.commands.register("_debug.gutter.removeBreakpoint", |workbench, args, _, cx| {
            let ids: Vec<String> = args.first().and_then(Value::as_str).map(str::to_owned).into_iter().collect();
            let change = workbench.debug.model.remove_breakpoints(&ids);
            workbench.breakpoints_changed(change, true, cx);
            Outcome::done()
        });
        self.commands.register("_debug.gutter.toggleBreakpoint", |workbench, args, _, cx| {
            let Some(breakpoint) = args.first().and_then(Value::as_str).and_then(|id| workbench.debug.model.breakpoint(id)) else { return Outcome::done() };
            let (id, enabled) = (breakpoint.id().to_owned(), breakpoint.base.enabled);
            let change = workbench.debug.model.set_enablement(&id, !enabled);
            workbench.breakpoints_changed(change, true, cx);
            Outcome::done()
        });
    }

    /// breakpointEditorContribution.ts's gutter actions generator, the line-number menu's `2_debug` group: the
    /// `getContextMenuActions` of the line's breakpoints.
    pub(super) fn debug_gutter_actions(&mut self, line: u32) -> Vec<MenuAction> {
        let Some(editor) = self.editors.active() else { return Vec::new() };
        if self.debug.debuggers.is_empty() || !self.can_set_breakpoints_in(editor) {
            return Vec::new();
        }
        let uri = editor.document().uri();
        let breakpoints: Vec<Breakpoint> = self.debug.model.breakpoints_in(&editor.document().uri_string()).filter(|breakpoint| breakpoint.line_number() == line).cloned().collect();
        self.breakpoint_menu_actions(breakpoints, uri, line, None)
    }

    /// `getContextMenuActions`: add actions (at `column` when given) without breakpoints, else actions on the one
    /// breakpoint or submenus per breakpoint, then Run to Line while stopped.
    pub(super) fn breakpoint_menu_actions(&mut self, mut breakpoints: Vec<Breakpoint>, uri: Value, line: u32, column: Option<u32>) -> Vec<MenuAction> {
        let mut actions = Vec::new();
        let action = |workbench: &mut Self, title: String, command: &str, args: Vec<Value>| MenuAction::Command { id: workbench.bound_command(command, args), title, enabled: true, checked: false, alt: None };
        match breakpoints.as_slice() {
            [] => {
                let mut line_args = vec![uri.clone(), json!(line)];
                line_args.extend(column.map(|column| json!(column)));
                for (title, command) in [("Add Breakpoint", "_debug.gutter.addBreakpoint"), ("Add Conditional Breakpoint...", "_debug.gutter.addConditionalBreakpoint"), ("Add Logpoint...", "_debug.gutter.addLogpoint"), ("Add Triggered Breakpoint...", "_debug.gutter.addTriggeredBreakpoint")] {
                    actions.push(action(self, title.into(), command, line_args.clone()));
                }
            }
            [breakpoint] => {
                let kind = if breakpoint.base.log_message.is_some() { "Logpoint" } else { "Breakpoint" };
                let toggle = if breakpoint.base.enabled { format!("Disable {kind}") } else { format!("Enable {kind}") };
                let id = vec![json!(breakpoint.id())];
                actions.push(action(self, format!("Remove {kind}"), "_debug.gutter.removeBreakpoint", id.clone()));
                actions.push(action(self, format!("Edit {kind}..."), "_debug.gutter.editBreakpoint", id.clone()));
                actions.push(action(self, toggle, "_debug.gutter.toggleBreakpoint", id));
            }
            _ => {
                breakpoints.sort_by(|first, second| match (first.column(), second.column()) {
                    (Some(first), Some(second)) => first.cmp(&second),
                    _ => std::cmp::Ordering::Equal,
                });
                let (mut remove, mut edit, mut toggle) = (Vec::new(), Vec::new(), Vec::new());
                for breakpoint in &breakpoints {
                    let id = vec![json!(breakpoint.id())];
                    let (remove_title, edit_title, toggle_title) = match (breakpoint.column(), breakpoint.base.enabled) {
                        (Some(column), true) => (format!("Remove Inline Breakpoint on Column {column}"), format!("Edit Inline Breakpoint on Column {column}"), format!("Disable Inline Breakpoint on Column {column}")),
                        (Some(column), false) => (format!("Remove Inline Breakpoint on Column {column}"), format!("Edit Inline Breakpoint on Column {column}"), format!("Enable Inline Breakpoint on Column {column}")),
                        (None, enabled) => ("Remove Line Breakpoint".into(), "Edit Line Breakpoint".into(), if enabled { "Disable Line Breakpoint".into() } else { "Enable Line Breakpoint".into() }),
                    };
                    remove.push(action(self, remove_title, "_debug.gutter.removeBreakpoint", id.clone()));
                    edit.push(action(self, edit_title, "_debug.gutter.editBreakpoint", id.clone()));
                    toggle.push(action(self, toggle_title, "_debug.gutter.toggleBreakpoint", id));
                }
                actions.push(MenuAction::Submenu { title: "Remove Breakpoints".into(), actions: remove, checked: false });
                actions.push(MenuAction::Submenu { title: "Edit Breakpoints".into(), actions: edit, checked: false });
                actions.push(MenuAction::Submenu { title: "Enable/Disable Breakpoints".into(), actions: toggle, checked: false });
            }
        }
        if self.debug.state() == crate::debug::session::State::Stopped {
            actions.push(MenuAction::Separator);
            actions.push(action(self, "Run to Line".into(), "_debug.gutter.runToLine", vec![uri, json!(line)]));
        }
        actions
    }

    fn line_breakpoints(&self, uri: &Value, line: u32) -> Vec<String> {
        let uri = crate::debug::uri_string(uri);
        self.debug.model.breakpoints_in(&uri).filter(|breakpoint| breakpoint.line_number() == line).map(|breakpoint| breakpoint.id().to_owned()).collect()
    }

    /// The glyph margin of one line: its breakpoint, the stack frame arrow, or the hint under the pointer.
    pub(super) fn breakpoint_glyph_margin(&self, editor: &OpenEditor, index: usize, width: f32, line_height: f32, cx: &mut Context<Self>) -> AnyElement {
        let line = index as u32 + 1;
        let uri_string = editor.document().uri_string();
        let model = &self.debug.model;
        let debug_active = matches!(self.debug.state(), crate::debug::session::State::Running | crate::debug::session::State::Stopped);
        let dirty = editor.is_dirty();
        let breakpoint = model.breakpoints_in(&uri_string).find(|breakpoint| breakpoint.line_number() == line);
        let mut cell = div().id(("glyph-margin", index)).relative().w(px(width)).h(px(line_height)).flex_none().flex().items_center().justify_center();
        let frame = self.stack_frame_glyph(editor, line);
        let mut dot = None;
        match (breakpoint, frame) {
            // The breakpoint and frame decorations share one glyph element: codicon.css draws debug-stackframe's `::before`
            // (registered after the breakpoints') and debug.contribution.css adds a dot `::after` to the plain ones.
            // shortcut: debug-breakpoint-unsupported, registered after debug-stackframe, keeps its own glyph upstream; draw it if a debugger reports one.
            (Some(breakpoint), Some(frame)) => dot = stack_frame_dot(breakpoint_icon(breakpoint, model, debug_active, dirty).0, frame),
            (Some(breakpoint), None) => {
                let (icon, _) = breakpoint_icon(breakpoint, model, debug_active, dirty);
                cell = cell.child(div().absolute().inset_0().flex().items_center().justify_center().child(self.breakpoint_icon(icon, 16.)));
            }
            // breakpointEditorContribution.ts `onMouseMove`: the hint only where breakpoints can be set.
            (None, None) if self.debug_view_hint_line() == Some((uri_string.clone(), index)) && self.can_set_breakpoints_in(editor) => {
                cell = cell.child(div().absolute().inset_0().flex().items_center().justify_center().opacity(0.4).child(self.breakpoint_icon("debug-hint", 16.)));
            }
            (None, None) => cell = cell.children(self.test_glyph(editor, line, cx)),
            (None, Some(_)) => {}
        }
        if let Some(icon) = frame {
            cell = cell.child(div().absolute().inset_0().flex().items_center().justify_center().child(self.breakpoint_icon(icon, 16.)));
        }
        if let Some(color) = dot {
            cell = cell.child(div().absolute().inset_0().flex().items_center().justify_center().child(self.icon("debug-stackframe-dot", 16., 16., self.color(color))));
        }
        let uri = editor.document().uri();
        let hover_uri = uri_string.clone();
        cell.cursor_pointer()
            .on_hover(cx.listener(move |workbench, hovered: &bool, _, cx| {
                let hint = &mut workbench.debug_view.hint;
                match hovered {
                    true => *hint = Some((hover_uri.clone(), index)),
                    false if hint.as_ref() == Some(&(hover_uri.clone(), index)) => *hint = None,
                    false => return,
                }
                cx.notify();
            }))
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                // macOS takes Ctrl+click for a right click, which editorLineNumberMenu.ts `doShow` handles.
                if event.modifiers.control {
                    workbench.show_line_number_context_menu(index, event.position, false, window, cx);
                    return;
                }
                workbench.glyph_margin_clicked(&uri, line, event.modifiers.shift, window, cx);
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                workbench.show_line_number_context_menu(index, event.position, false, window, cx);
            }))
            .into_any_element()
    }

    fn debug_view_hint_line(&self) -> Option<(String, usize)> {
        self.debug_view.hint.clone()
    }

    /// callStackEditorContribution.ts: the top frame of each stopped thread in this file, and the focused frame.
    fn stack_frames_in(&self, editor: &OpenEditor) -> Vec<(u32, bool, bool)> {
        // callStackWidget.ts `setupEditorAfterModel`: a call stack frame's editor shows its own line, no glyph.
        if let Some(frame) = self.call_stack_frame(editor) {
            return vec![(frame.line as u32, true, false)];
        }
        let path = editor.document().path.to_string_lossy().into_owned();
        let mut frames = Vec::new();
        for session in &self.debug.sessions {
            let session_focused = self.debug.focus.session.as_deref() == Some(session.id.as_str());
            for thread in session.threads.iter().filter(|thread| thread.stopped) {
                let Some(top) = thread.frames.first() else { continue };
                let focused = thread.frames.iter().find(|frame| session_focused && Some(frame.id) == self.debug.focus.frame && frame.id != top.id);
                for (frame, is_top) in focused.map(|frame| (frame, false)).into_iter().chain([(top, true)]) {
                    if frame.path() == Some(&*path) && editor.document().scheme == "file" {
                        frames.push((frame.line, is_top, session_focused));
                    }
                }
            }
        }
        frames
    }

    pub(super) fn stack_frame_glyph(&self, editor: &OpenEditor, line: u32) -> Option<&'static str> {
        let frames = self.stack_frames_in(editor);
        let (_, is_top, _) = frames.into_iter().find(|(frame_line, _, session_focused)| *frame_line == line && *session_focused)?;
        Some(if is_top { "debug-stackframe" } else { "debug-stackframe-focused" })
    }

    /// The whole-line background of a top or focused stack frame (`debug-top-stack-frame-line`).
    pub(super) fn stack_frame_line(&self, editor: &OpenEditor, index: usize) -> Option<Div> {
        let (_, is_top, _) = self.stack_frames_in(editor).into_iter().find(|(line, ..)| *line == index as u32 + 1)?;
        let color = if is_top { "editor.stackFrameHighlightBackground" } else { "editor.focusedStackFrameHighlightBackground" };
        Some(div().absolute().inset_0().bg(self.color(color)))
    }

    /// `makeStackFrameColumnDecoration` in every editor, run on every render: `\uEB8B` before each stopped thread's
    /// top frame's column past 1, `width: 0.9em` of the 16px codicon plus `margin-right: 4px` wide, or no room with
    /// nothing but whitespace before it (`.start-of-line` is absolute).
    pub(super) fn sync_stack_frame_columns(&mut self) {
        let char_width = self.editors.viewport.char_width;
        let wanted: Vec<Vec<InjectedText>> = self.editors.all_editors().map(|editor| self.stack_frame_columns(editor, char_width)).collect();
        for (editor, injections) in self.editors.all_editors_mut().zip(wanted) {
            let current = editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::StackFrameColumn);
            if !current.eq(injections.iter()) {
                editor.set_injected_text(InjectionOwner::StackFrameColumn, injections);
            }
        }
    }

    fn stack_frame_columns(&self, editor: &OpenEditor, char_width: f32) -> Vec<InjectedText> {
        let document = editor.document();
        if document.scheme != "file" {
            return Vec::new();
        }
        let path = document.path.to_string_lossy();
        let mut injections = Vec::new();
        for thread in self.debug.sessions.iter().flat_map(|session| &session.threads).filter(|thread| thread.stopped) {
            let Some(top) = thread.frames.first().filter(|frame| frame.column > 1 && frame.path() == Some(&*path)) else { continue };
            // An adapter's line out of the model (callStackEditorContribution.ts warns and skips it).
            let Some((index, line)) = (top.line as usize).checked_sub(1).and_then(|index| Some((index, document.lines.get(index)?))) else { continue };
            let injection = stack_frame_column(line, index, top.column as usize, char_width);
            if !injections.iter().any(|injected: &InjectedText| injected.position == injection.position) {
                injections.push(injection);
            }
        }
        injections.sort_by_key(|injection| injection.position);
        injections
    }

    /// `.debug-top-stack-frame-column`: the codicon 1px up, or `.start-of-line` 17px left of the column, centered, in
    /// `debugIcon.breakpointCurrentStackframeForeground` (breakpointEditorContribution.ts theming participant).
    pub(super) fn stack_frame_column_element(&self, start_of_line: bool, left: f32, line_height: f32) -> AnyElement {
        let icon = self.icon("debug-stackframe", 16., 16., self.color("debugIcon.breakpointCurrentStackframeForeground"));
        let (left, top) = if start_of_line { (left - 17., 0.) } else { (left, -1.) };
        div().absolute().top(px(top)).left(px(left)).h(px(line_height)).flex().items_center().child(icon).into_any_element()
    }

    /// breakpointEditorContribution.ts `onEditorMouseDown` on the glyph margin: Shift toggles enablement, a click
    /// removes (asking first when a condition would be lost) or adds a breakpoint.
    fn glyph_margin_clicked(&mut self, uri: &Value, line: u32, shift: bool, window: &mut Window, cx: &mut Context<Self>) {
        let ids = self.line_breakpoints(uri, line);
        if ids.is_empty() {
            if self.can_set_breakpoints_in_active_editor() {
                let change = self.debug.model.add_breakpoints(uri, vec![BreakpointData::at(line)]);
                self.breakpoints_changed(change, true, cx);
            }
            return;
        }
        let breakpoints: Vec<Breakpoint> = ids.iter().filter_map(|id| self.debug.model.breakpoint(id).cloned()).collect();
        let enabled = breakpoints.iter().any(|breakpoint| breakpoint.base.enabled);
        if shift {
            let mut change = crate::debug::BreakpointsChange::default();
            for id in &ids {
                change.changed.extend(self.debug.model.set_enablement(id, !enabled).changed);
            }
            self.breakpoints_changed(change, true, cx);
            return;
        }
        let has_condition = breakpoints.iter().any(|breakpoint| breakpoint.base.condition.is_some() || breakpoint.base.log_message.is_some() || breakpoint.base.hit_condition.is_some() || breakpoint.triggered_by.is_some());
        if !has_condition {
            let change = self.debug.model.remove_breakpoints(&ids);
            self.breakpoints_changed(change, true, cx);
            return;
        }
        let kind = if breakpoints.iter().all(|breakpoint| breakpoint.base.log_message.is_some()) { "Logpoint" } else { "Breakpoint" };
        let (message, toggle) = match enabled {
            true => {
                let detail = if breakpoints.iter().any(|breakpoint| breakpoint.base.log_message.is_some()) { "log message" } else if breakpoints.iter().any(|breakpoint| breakpoint.base.condition.is_some()) { "condition" } else { "hit count" };
                (format!("This {} has a {detail} that will get lost on remove. Consider disabling the {} instead.", kind.to_lowercase(), kind.to_lowercase()), format!("Disable {kind}"))
            }
            false => (format!("Removing a disabled {} will lose its condition. Consider enabling the {} instead.", kind.to_lowercase(), kind.to_lowercase()), format!("Enable {kind}")),
        };
        let remove = format!("Remove {kind}");
        let answer = crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, gpui::PromptLevel::Warning, &message, None, &[&remove, &toggle, "Cancel"], None, cx);
        cx.spawn_in(window, async move |this, cx| {
            let Ok((choice, _)) = answer.await else { return };
            let _ = this.update(cx, |workbench, cx| {
                let change = match choice {
                    0 => workbench.debug.model.remove_breakpoints(&ids),
                    1 => {
                        let mut change = crate::debug::BreakpointsChange::default();
                        for id in &ids {
                            change.changed.extend(workbench.debug.model.set_enablement(id, !enabled).changed);
                        }
                        change
                    }
                    _ => return,
                };
                workbench.breakpoints_changed(change, true, cx);
            });
        })
        .detach();
    }

    /// breakpointEditorContribution.ts `getContextMenuActions`.
    /// `BreakpointWidget.show`: a zone of two lines below the line, the input focused with the breakpoint's value.
    pub(crate) fn show_breakpoint_widget(&mut self, line: u32, column: Option<u32>, breakpoint: Option<String>, context: WidgetContext, window: &mut Window, cx: &mut Context<Self>) {
        self.close_breakpoint_widget(window, cx);
        let viewport = self.editors.viewport;
        let Some(editor) = self.editors.active_mut() else { return };
        let existing = breakpoint.as_deref().and_then(|id| self.debug.model.breakpoint(id));
        let text = |value: Option<&String>| value.cloned().unwrap_or_default();
        let (condition, hit_count, log_message) = (text(existing.and_then(|bp| bp.base.condition.as_ref())), text(existing.and_then(|bp| bp.base.hit_condition.as_ref())), text(existing.and_then(|bp| bp.base.log_message.as_ref())));
        // breakpointWidget.ts: an existing logpoint opens on its message, a hit count without a condition on it, a
        // triggered breakpoint on Wait for Breakpoint.
        let context = match (existing, context) {
            (Some(_), _) if !log_message.is_empty() => WidgetContext::LogMessage,
            (Some(_), _) if condition.is_empty() && !hit_count.is_empty() => WidgetContext::HitCount,
            (Some(existing), _) if existing.triggered_by.is_some() => WidgetContext::TriggerPoint,
            (_, context) => context,
        };
        // `createTriggerBreakpointInput`: the breakpoint's trigger, else the first candidate for a breakpoint without one.
        let candidates = trigger_candidates(&self.debug.model, breakpoint.as_deref());
        let triggered_by = match existing.and_then(|existing| existing.triggered_by.as_ref()) {
            Some(id) => candidates.iter().find(|candidate| candidate.id() == id),
            None => candidates.first(),
        }
        .map(|candidate| candidate.id().to_owned());
        let zone_id = editor.add_view_zone(Some(Position::new(line as usize - 1, 0)), 2. * viewport.line_height);
        let mut input = InputBox::default();
        input.set_value(match context {
            WidgetContext::Condition | WidgetContext::TriggerPoint => condition.clone(),
            WidgetContext::HitCount => hit_count.clone(),
            WidgetContext::LogMessage => log_message.clone(),
        });
        let uri = editor.document().uri();
        self.breakpoint_widget = Some(BreakpointWidget { model_uri: editor.document().uri_string(), uri, line, column, zone_id, breakpoint, context, input, condition, hit_count, log_message, triggered_by });
        self.debug_view.widget_view.reset();
        window.focus(&self.debug_view.widget_focus, cx);
        cx.notify();
    }

    pub(crate) fn close_breakpoint_widget(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(widget) = self.breakpoint_widget.take() else { return };
        if let Some(editor) = self.editors.all_tabs_mut().find(|editor| editor.document().uri_string() == widget.model_uri) {
            editor.remove_view_zone(widget.zone_id);
        }
        window.focus(&self.editor_focus, cx);
        cx.notify();
    }

    /// `BreakpointWidget.close(success: true)`: the typed values update the breakpoint or add one.
    fn accept_breakpoint_widget(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(widget) = self.breakpoint_widget.as_mut() else { return };
        widget.remember_input();
        let some = |text: &String| (!text.is_empty()).then(|| text.clone());
        let trigger_point = widget.context == WidgetContext::TriggerPoint;
        // Trigger points take no other conditions.
        let (condition, hit_condition, log_message, triggered_by) = match trigger_point {
            true => (None, None, None, widget.triggered_by.clone()),
            false => (some(&widget.condition), some(&widget.hit_count), some(&widget.log_message), None),
        };
        let (uri, line, column, breakpoint) = (widget.uri.clone(), widget.line, widget.column, widget.breakpoint.clone());
        let change = match breakpoint {
            Some(id) => {
                let mut update = serde_json::Map::new();
                update.insert("condition".into(), json!(condition));
                update.insert("hitCondition".into(), json!(hit_condition));
                update.insert("logMessage".into(), json!(log_message));
                update.insert("triggeredBy".into(), json!(triggered_by));
                self.debug.model.update_breakpoints(&[(id, update)])
            }
            None if trigger_point || condition.is_some() || hit_condition.is_some() || log_message.is_some() => self.debug.model.add_breakpoints(&uri, vec![BreakpointData { column, condition, hit_condition, log_message, triggered_by, ..BreakpointData::at(line) }]),
            None => crate::debug::BreakpointsChange::default(),
        };
        self.breakpoints_changed(change, true, cx);
        self.close_breakpoint_widget(window, cx);
    }

    fn switch_breakpoint_widget_context(&mut self, context: WidgetContext, window: &mut Window, cx: &mut Context<Self>) {
        let Some(widget) = self.breakpoint_widget.as_mut() else { return };
        widget.remember_input();
        widget.context = context;
        let next = match context {
            WidgetContext::Condition | WidgetContext::TriggerPoint => widget.condition.clone(),
            WidgetContext::HitCount => widget.hit_count.clone(),
            WidgetContext::LogMessage => widget.log_message.clone(),
        };
        widget.input = InputBox::default();
        widget.input.set_value(next);
        window.focus(&self.debug_view.widget_focus, cx);
        cx.notify();
    }

    /// The widget over its zone: the context select box, then the input (breakpointWidget.css, zone frame in
    /// `editor.foreground`-less `peekView.border`-style top and bottom borders of `debugIcon.breakpointForeground`).
    pub(super) fn breakpoint_widget_element(&self, editor: &OpenEditor, content_left: f32, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let widget = self.breakpoint_widget.as_ref().filter(|widget| widget.model_uri == editor.document().uri_string())?;
        let viewport = self.editors.viewport;
        let top = editor.view_zone_top(widget.zone_id, viewport)? - editor.scroll.top;
        let border: Rgba = self.color("debugIcon.breakpointForeground");
        let focused = self.debug_view.widget_focus.is_focused(window);
        let label = CONTEXT_LABELS.iter().find(|(context, _)| *context == widget.context).map(|(_, label)| *label).unwrap_or_default();
        let select = div()
            .id("breakpoint-widget-select")
            .flex_none()
            .h(px(22.))
            .ml(px(content_left.max(10.) - 10.))
            .px(px(6.))
            .flex()
            .items_center()
            .gap(px(4.))
            .rounded(px(4.))
            .border_1()
            .border_color(self.color("dropdown.border"))
            .bg(self.color("dropdown.background"))
            .text_color(self.color("dropdown.foreground"))
            .cursor_pointer()
            .child(label)
            .child(self.icon("chevron-down", 16., 14., self.color("dropdown.foreground")))
            .on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
                let Some(widget) = workbench.breakpoint_widget.as_ref() else { return };
                let next = match widget.context {
                    WidgetContext::Condition => WidgetContext::HitCount,
                    WidgetContext::HitCount => WidgetContext::LogMessage,
                    WidgetContext::LogMessage => WidgetContext::TriggerPoint,
                    WidgetContext::TriggerPoint => WidgetContext::Condition,
                };
                workbench.switch_breakpoint_widget_context(next, window, cx);
            }));
        let content = match widget.context {
            WidgetContext::TriggerPoint => self.trigger_breakpoint_select(widget, cx),
            _ => self.breakpoint_widget_input(widget, focused, cx),
        };
        Some(
            div()
                .absolute()
                .left_0()
                .right(px(14.))
                .top(px(top))
                .h(px(2. * viewport.line_height))
                .border_t_2()
                .border_b_2()
                .border_color(border)
                .bg(self.color("editor.background"))
                .flex()
                .items_center()
                .child(select)
                .child(content)
                .into_any_element(),
        )
    }

    fn breakpoint_widget_input(&self, widget: &BreakpointWidget, focused: bool, cx: &mut Context<Self>) -> AnyElement {
        div()
            .flex_1()
            .h(px(22.))
            .ml(px(8.))
            .mr(px(20.))
            .px(px(4.))
            .flex()
            .bg(self.color("input.background"))
            .on_key_down(cx.listener(|workbench, event: &KeyDownEvent, window, cx| match event.keystroke.key.as_str() {
                "enter" => workbench.accept_breakpoint_widget(window, cx),
                "escape" => workbench.close_breakpoint_widget(window, cx),
                _ => {}
            }))
            .child(self.input_text(InputId::BreakpointWidget, InputLook { password: false, placeholder: Some(placeholder(widget.context).into()), focused }, cx))
            .into_any_element()
    }

    /// `createTriggerBreakpointInput`: a 300px select box of the candidates after a disabled None, then an OK button
    /// that accepts (breakpointWidget.css `.select-breakpoint-container`).
    fn trigger_breakpoint_select(&self, widget: &BreakpointWidget, cx: &mut Context<Self>) -> AnyElement {
        let selected = widget.triggered_by.as_deref().and_then(|id| self.debug.model.breakpoint(id)).map_or_else(|| "None".to_owned(), |breakpoint| self.trigger_label(breakpoint));
        let select = div()
            .id("breakpoint-widget-trigger-select")
            .w(px(300.))
            .h(px(22.))
            .px(px(6.))
            .flex()
            .items_center()
            .justify_between()
            .rounded(px(4.))
            .border_1()
            .border_color(self.color("dropdown.border"))
            .bg(self.color("dropdown.background"))
            .text_color(self.color("dropdown.foreground"))
            .cursor_pointer()
            .child(div().truncate().child(selected))
            .child(self.icon("chevron-down", 16., 14., self.color("dropdown.foreground")))
            .on_mouse_down(MouseButton::Left, cx.listener(|workbench, event: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                workbench.show_trigger_breakpoint_options(event.position, window, cx);
            }));
        let ok = self.comment_form_button("breakpoint-widget-ok".into(), "OK".into(), true, true, |workbench, window, cx| workbench.accept_breakpoint_widget(window, cx), cx);
        div().flex_1().ml(px(8.)).flex().items_center().gap(px(10.)).child(select).child(ok).into_any_element()
    }

    /// `buildBreakpointOptions`: `{relative path}: {line}`.
    fn trigger_label(&self, breakpoint: &Breakpoint) -> String {
        let path = crate::uri::json_fs_path(&breakpoint.uri);
        format!("{}: {}", crate::quick_input::path_label(std::path::Path::new(&path), self.workspace()), breakpoint.line_number())
    }

    fn show_trigger_breakpoint_options(&mut self, position: gpui::Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(widget) = self.breakpoint_widget.as_ref() else { return };
        let candidates: Vec<(String, String)> = trigger_candidates(&self.debug.model, widget.breakpoint.as_deref()).into_iter().map(|breakpoint| (breakpoint.id().to_owned(), self.trigger_label(breakpoint))).collect();
        let selected = widget.triggered_by.clone();
        let mut actions = vec![MenuAction::Command { id: "_debug.breakpointWidget.selectTrigger".into(), title: "None".into(), enabled: false, checked: selected.is_none(), alt: None }];
        for (id, label) in candidates {
            let checked = selected.as_deref() == Some(id.as_str());
            actions.push(MenuAction::Command { id: self.bound_command("_debug.breakpointWidget.selectTrigger", vec![json!(id)]), title: label, enabled: true, checked, alt: None });
        }
        let anchor = gpui::Bounds { origin: position, size: gpui::size(px(0.), px(0.)) };
        let context = self.key_context(window);
        self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
    }

    pub(super) fn edit_breakpoint_widget_input(&mut self, edit: impl FnOnce(&mut InputBox), cx: &mut Context<Self>) {
        if let Some(widget) = self.breakpoint_widget.as_mut() {
            edit(&mut widget.input);
        }
        cx.notify();
    }
}

impl BreakpointWidget {
    /// `rememberInput`: the input's value for its text context.
    fn remember_input(&mut self) {
        let value = self.input.value.clone();
        match self.context {
            WidgetContext::Condition => self.condition = value,
            WidgetContext::HitCount => self.hit_count = value,
            WidgetContext::LogMessage => self.log_message = value,
            WidgetContext::TriggerPoint => {}
        }
    }
}

/// `makeStackFrameColumnDecoration` before 1-based `column` of `line`, line `index` of its model.
pub(super) fn stack_frame_column(line: &str, index: usize, column: usize, char_width: f32) -> InjectedText {
    let column = column.saturating_sub(1).min(line.chars().count());
    // `getLineFirstNonWhitespaceColumn() >= startColumn`.
    let start_of_line = line.chars().take(column).all(|c| c == ' ' || c == '\t');
    let columns = if start_of_line { 0. } else { (0.9 * 16. + 4.) / char_width };
    InjectedText { position: Position::new(index, column), columns, content: "\u{EB8B}".into(), wrap: WrapWidth::Fixed, owner: InjectionOwner::StackFrameColumn, id: usize::from(start_of_line), at_range_start: true }
}

/// breakpointWidget.ts `availableBreakpoints`: the source breakpoints but the edited one and logpoints.
fn trigger_candidates<'a>(model: &'a DebugModel, own: Option<&str>) -> Vec<&'a Breakpoint> {
    model.breakpoints.iter().filter(|breakpoint| Some(breakpoint.id()) != own && breakpoint.base.log_message.is_none()).collect()
}

fn gutter_args(args: &[Value]) -> (Value, u32, Option<u32>) {
    (args.first().cloned().unwrap_or_default(), args.get(1).and_then(Value::as_u64).unwrap_or(1) as u32, args.get(2).and_then(Value::as_u64).map(|column| column as u32))
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use gpui::TestAppContext;
    use serde_json::json;

    use super::super::Workbench;
    use super::super::testing_gutter::tests::{command_titled, titles, workbench_with_tests};
    use super::WidgetContext;
    use crate::debug::BreakpointData;
    use crate::debug::session::Session;

    /// debug.contribution.css: a plain breakpoint under the stopped frame draws the frame's glyph with a dot, not its circle.
    #[gpui::test]
    fn a_breakpoint_under_the_stopped_frame_draws_the_stack_frame_dot(cx: &mut TestAppContext) {
        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 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, "x\n".repeat(10)).unwrap();
        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(std::sync::mpsc::channel().0), cx));
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.model.add_breakpoints(&json!({ "scheme": "file", "path": file.to_string_lossy() }), vec![BreakpointData::at(2)]);
            let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            let thread = session.thread_mut(1).unwrap();
            thread.stopped = true;
            thread.frames = vec![crate::debug::session::StackFrame { id: 3, source: json!({ "path": file.to_string_lossy() }), line: 2, column: 1, ..Default::default() }];
            workbench.debug.sessions = vec![session];
            let focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(3) };
            workbench.set_debug_focus(focus, super::super::debug_service::Reveal::TakingFocus, window, cx);
        });
        cx.run_until_parked();
        assert!(cx.debug_bounds("codicon-debug-stackframe").is_some(), "the frame's glyph");
        assert!(cx.debug_bounds("codicon-debug-stackframe-dot").is_some(), "the breakpoint's dot over it");
        assert!(cx.debug_bounds("codicon-circle-filled").is_none(), "no breakpoint circle");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// callStackEditorContribution.ts `makeStackFrameColumnDecoration`: a top frame past column 1 injects the arrow
    /// before its column, 18.4px wide after code; after only whitespace it takes no room.
    #[gpui::test]
    fn a_top_frame_past_column_1_injects_the_column_arrow(cx: &mut TestAppContext) {
        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 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, "let a = f();\n  g();\n").unwrap();
        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(std::sync::mpsc::channel().0), cx));
        let stop_at = |line: u32, column: u32, workbench: &mut Workbench| {
            let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            let thread = session.thread_mut(1).unwrap();
            thread.stopped = true;
            thread.frames = vec![crate::debug::session::StackFrame { id: 3, source: json!({ "path": file.to_string_lossy() }), line, column, ..Default::default() }];
            workbench.debug.sessions = vec![session];
        };
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.open_file(file.clone(), true, window, cx);
            stop_at(1, 9, workbench);
        });
        cx.run_until_parked();
        let injected = |workbench: &Workbench| workbench.editors.active().unwrap().injected_text.iter().map(|injection| (injection.position.line, injection.position.column, injection.columns * workbench.editors.viewport.char_width)).collect::<Vec<_>>();
        let first = workbench.read_with(cx, |workbench, _| injected(workbench));
        assert_eq!(first.len(), 1);
        assert_eq!((first[0].0, first[0].1), (0, 8));
        assert!((first[0].2 - 18.4).abs() < 0.01, "{first:?}");
        assert!(cx.debug_bounds("codicon-debug-stackframe").is_some(), "the arrow draws");

        workbench.update(cx, |workbench, cx| {
            stop_at(2, 3, workbench);
            cx.notify();
        });
        cx.run_until_parked();
        assert_eq!(workbench.read_with(cx, |workbench, _| injected(workbench)), [(1, 2, 0.)]);

        workbench.update(cx, |workbench, cx| {
            workbench.debug.sessions.clear();
            cx.notify();
        });
        cx.run_until_parked();
        assert!(workbench.read_with(cx, |workbench, _| injected(workbench)).is_empty());
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A debugger and an extension taking breakpoints in the open document's language.
    fn add_debugger(workbench: &mut Workbench) {
        workbench.debug.debuggers.push(crate::debug::configuration::Debugger { debug_type: "node".into(), contribution: json!({}), extension_id: "a.node".into() });
        let language = workbench.editors.active().unwrap().document().language_id.clone();
        let description = json!({ "contributes": { "breakpoints": [{ "language": language }] } });
        workbench.extensions.push(exthost::scan::ScannedExtension { id: "a.node".into(), location: "/node".into(), description });
    }

    fn line_menu(workbench: &gpui::Entity<Workbench>, line: usize, cx: &mut gpui::VisualTestContext) -> Vec<crate::menus::MenuAction> {
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.show_line_number_context_menu(line, gpui::point(gpui::px(10.), gpui::px(40.)), false, window, cx);
            let actions = workbench.context_menu.as_ref().expect("a context menu shows").levels[0].actions.clone();
            workbench.hide_context_menu(window, cx);
            actions
        })
    }

    /// editorLineNumberMenu.ts `doShow`: the debug generator's `2_debug` group follows the tests' `1_testing` one; Add
    /// Triggered Breakpoint... opens the widget on Wait for Breakpoint, which adds a breakpoint triggered by the first
    /// other one.
    #[gpui::test]
    fn the_gutter_menu_adds_a_triggered_breakpoint_after_the_tests_actions(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = workbench_with_tests("debug-gutter-menu", &[("c\0t", "t", 1)], cx);
        let uri = workbench.update(cx, |workbench, _| {
            add_debugger(workbench);
            let uri = workbench.editors.active().unwrap().document().uri();
            workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData::at(3)]);
            uri
        });
        let actions = line_menu(&workbench, 0, cx);
        assert_eq!(titles(&actions), ["Run Test", "Debug Test", "Execute Using Profile...", "Reveal in Test Explorer", "---", "Add Breakpoint", "Add Conditional Breakpoint...", "Add Logpoint...", "Add Triggered Breakpoint..."]);
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(&command_titled(&actions, "Add Triggered Breakpoint..."), Vec::new(), window, cx)));
        cx.run_until_parked();
        let trigger = workbench.read_with(cx, |workbench, _| {
            let widget = workbench.breakpoint_widget.as_ref().expect("the widget shows");
            assert_eq!(widget.context, WidgetContext::TriggerPoint);
            widget.triggered_by.clone().expect("the first candidate")
        });
        workbench.update_in(cx, |workbench, window, cx| workbench.accept_breakpoint_widget(window, cx));
        let added = workbench.read_with(cx, |workbench, _| workbench.debug.model.breakpoints_in(&crate::debug::uri_string(&uri)).find(|breakpoint| breakpoint.line_number() == 1).map(|breakpoint| breakpoint.triggered_by.clone()));
        assert_eq!(added, Some(Some(trigger)));
    }

    /// `getContextMenuActions`: one breakpoint's actions, submenus for several, Run to Line while stopped.
    #[gpui::test]
    fn the_gutter_menu_acts_on_the_lines_breakpoints(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = workbench_with_tests("debug-gutter-breakpoints", &[], cx);
        workbench.update(cx, |workbench, _| {
            add_debugger(workbench);
            let uri = workbench.editors.active().unwrap().document().uri();
            workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData { log_message: Some("m".into()), ..BreakpointData::at(1) }]);
            workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData { column: Some(9), ..BreakpointData::at(3) }, BreakpointData { column: Some(1), ..BreakpointData::at(3) }]);
        });
        assert_eq!(titles(&line_menu(&workbench, 0, cx)), ["Remove Logpoint", "Edit Logpoint...", "Disable Logpoint"]);
        let several = line_menu(&workbench, 2, cx);
        assert_eq!(titles(&several), ["Remove Breakpoints >", "Edit Breakpoints >", "Enable/Disable Breakpoints >"]);
        let crate::menus::MenuAction::Submenu { actions, .. } = &several[0] else { panic!("a submenu") };
        assert_eq!(titles(actions), ["Remove Inline Breakpoint on Column 1", "Remove Inline Breakpoint on Column 9"]);

        workbench.update_in(cx, |workbench, window, cx| {
            let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            session.thread_mut(1).unwrap().stopped = true;
            session.initialized = true;
            workbench.debug.sessions = vec![session];
            let focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: None };
            workbench.set_debug_focus(focus, super::super::debug_service::Reveal::No, window, cx);
        });
        assert_eq!(titles(&line_menu(&workbench, 1, cx)), ["Add Breakpoint", "Add Conditional Breakpoint...", "Add Logpoint...", "Add Triggered Breakpoint...", "---", "Run to Line"]);
    }
}