Skip to content

Visual Studio Code, rebuilt in Rust

Rust
30.5 KB
Raw Blame
//! The floating debug toolbar (debugToolBar.ts): the `MenuId.DebugToolBar` actions over the window while a
//! session runs, dragged by its gripper and stored at `debug.actionswidgetposition`.

use gpui::{ClickEvent, Context, Div, MouseButton, MouseDownEvent, MouseMoveEvent, Window, div, prelude::*, px};

use std::collections::HashMap;

use serde_json::{Value, json};

use super::Workbench;
use crate::commands::Outcome;
use super::hover::{HoverContent, HoverOptions};
use crate::debug::session::State;
use crate::menus::{CommandIcon, MenuAction, MenuId, menu_actions};

const DEBUG_STATUS_ID: &str = "status.debug";
const POSITION_KEY: &str = "debug.actionswidgetposition";
const Y_KEY: &str = "debug.actionswidgety";
const HEIGHT: f32 = 28.;
const ACTION_WIDTH: f32 = 26.;
const DRAG_AREA_WIDTH: f32 = 20.;
/// dropdown.css: the chevron's 16px codicon pulled 3px into the primary button.
const STOP_DROPDOWN_WIDTH: f32 = 13.;
const FOCUS_SESSION_ID: &str = "workbench.action.debug.focusProcess";
const STOP_COMMANDS: [&str; 2] = ["workbench.action.debug.stop", "workbench.action.debug.disconnect"];

/// The drag that moves the toolbar: the pointer and the toolbar's x fraction and y where it started, and where
/// it is now; the position is stored when the button is released.
#[derive(Clone, Copy, Default)]
pub struct ToolbarDrag {
    origin: (f32, f32),
    start: (f32, f32),
    current: (f32, f32),
}

/// debugIcons.ts: the codicons of the toolbar's own commands.
const COMMAND_ICONS: [(&str, &str); 10] = [
    ("workbench.action.debug.continue", "debug-continue"),
    ("workbench.action.debug.pause", "debug-pause"),
    ("workbench.action.debug.stepOver", "debug-step-over"),
    ("workbench.action.debug.stepInto", "debug-step-into"),
    ("workbench.action.debug.stepOut", "debug-step-out"),
    ("workbench.action.debug.stepBack", "debug-step-back"),
    ("workbench.action.debug.reverseContinue", "debug-reverse-continue"),
    ("workbench.action.debug.restart", "debug-restart"),
    ("workbench.action.debug.stop", "debug-stop"),
    ("workbench.action.debug.disconnect", "debug-disconnect"),
];

/// debugColors.ts: the toolbar codicons' colors, by codicon.
const ICON_COLORS: [(&str, &str); 10] = [
    ("debug-continue", "debugIcon.continueForeground"),
    ("debug-pause", "debugIcon.pauseForeground"),
    ("debug-step-over", "debugIcon.stepOverForeground"),
    ("debug-step-into", "debugIcon.stepIntoForeground"),
    ("debug-step-out", "debugIcon.stepOutForeground"),
    ("debug-step-back", "debugIcon.stepBackForeground"),
    ("debug-reverse-continue", "debugIcon.reverseContinueForeground"),
    ("debug-restart", "debugIcon.restartForeground"),
    ("debug-stop", "debugIcon.stopForeground"),
    ("debug-disconnect", "debugIcon.disconnectForeground"),
];

impl Workbench {
    /// debugToolBar.ts: `getFlatActionBarActions` of `MenuId.DebugToolBar`, the workbench's and the extensions' items.
    /// menuEntryActionViewItem.ts `updateAltState`: with Alt held an item shows and runs its enabled alt command.
    fn debug_toolbar_actions(&self, context: &HashMap<String, Value>, alt_held: bool) -> Vec<(String, String, bool)> {
        let mut actions = Vec::new();
        for action in menu_actions(&self.menus, MenuId::DebugToolBar, context) {
            match action {
                MenuAction::Command { alt: Some((id, title)), .. } if alt_held => actions.push((id, title, true)),
                MenuAction::Command { id, title, enabled, .. } => actions.push((id, title, enabled)),
                _ => {}
            }
        }
        actions
    }

    /// The action's codicon colored as debugColors.ts colors it, an extension command's icon, else its title.
    fn debug_toolbar_icon(&self, id: &str, title: &str, enabled: bool) -> Div {
        let disabled = self.color("disabledForeground");
        if let Some((_, codicon)) = COMMAND_ICONS.iter().find(|(command, _)| *command == id) {
            let color = ICON_COLORS.iter().find(|(icon, _)| icon == codicon).map(|(_, color)| self.color(color)).expect("every toolbar codicon has a color");
            return self.icon(codicon, 22., 16., if enabled { color } else { disabled });
        }
        let foreground = if enabled { self.foreground_or("icon.foreground") } else { disabled };
        match self.command_icons.get(id) {
            Some(CommandIcon::Codicon(name)) => {
                let color = ICON_COLORS.iter().find(|(icon, _)| icon == name).filter(|_| enabled).map(|(_, color)| self.color(color)).unwrap_or(foreground);
                self.icon(name, 22., 16., color)
            }
            icon => self.command_icon(icon, title, foreground),
        }
    }

    fn debug_toolbar_position(&self) -> (f32, f32) {
        if let Some(drag) = self.debug_view.toolbar_drag {
            return drag.current;
        }
        let storage = self.profile_storage.lock().unwrap();
        let x = storage.get(POSITION_KEY).and_then(|value| value.parse::<f32>().ok()).filter(|x| !x.is_nan()).unwrap_or(0.5);
        let y = storage.get(Y_KEY).and_then(|value| value.parse::<f32>().ok()).unwrap_or_else(|| self.debug_toolbar_y_default());
        (x, y)
    }

    /// debugToolBar.ts `yDefault`: layout.ts `mainContainerOffset.top`, below the banner and the title bar.
    fn debug_toolbar_y_default(&self) -> f32 {
        self.banner_height() + self.title_bar_height(false)
    }

    /// debugToolBar.ts `yRange`: from the top to the bottom of the title bar and the editor tabs.
    fn debug_toolbar_y_max(&self) -> f32 {
        let title_bar = if self.setting("window.commandCenter") != Value::Bool(false) { 35. } else { 28. };
        let tabs = if self.setting("workbench.editor.showTabs") == "none" { 0. } else { 35. };
        title_bar + tabs
    }

    fn store_debug_toolbar_position(&mut self, x: f32, y: f32) {
        let mut storage = self.profile_storage.lock().unwrap();
        storage.set(POSITION_KEY, x.to_string());
        storage.set(Y_KEY, y.to_string());
    }

    /// The toolbar while a session runs and `debug.toolBarLocation` is `floating`.
    pub(super) fn debug_toolbar(&self, window: &Window, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
        if self.debug.state() == State::Inactive || self.setting("debug.toolBarLocation").as_str().unwrap_or("floating") != "floating" {
            return None;
        }
        if !self.debug.sessions.is_empty() && self.debug.sessions.iter().all(|session| session.options["suppressDebugToolbar"] == true) {
            return None;
        }
        let context = self.key_context(window);
        let actions = self.debug_toolbar_actions(&context, window.modifiers().alt);
        // debugToolBar.ts `createDisconnectMenuItemAction`: Stop or Disconnect gets a dropdown of `MenuId.DebugToolBarStop`.
        let stop_actions = menu_actions(&self.menus, MenuId::DebugToolBarStop, &context);
        let dropdown_width = if stop_actions.is_empty() { 0. } else { STOP_DROPDOWN_WIDTH };
        let mut width = 2. + DRAG_AREA_WIDTH + dropdown_width;
        for (command, ..) in &actions {
            width += match command.as_str() {
                FOCUS_SESSION_ID => self.focus_session_select_width(window) + 2.,
                _ => ACTION_WIDTH,
            };
        }
        let window_width = f32::from(window.viewport_size().width);
        let (x, y) = self.debug_toolbar_position();
        let y = y.clamp(0., self.debug_toolbar_y_max());
        let left = (x * window_width - width / 2.).clamp(0., (window_width - width).max(0.));
        let mut bar = div()
            .id("debug-toolbar")
            .debug_selector(|| "debug-toolbar".into())
            .absolute()
            .left(px(left))
            .top(px(y))
            .h(px(HEIGHT))
            .pl(px(2.))
            .flex()
            .items_center()
            .rounded(px(8.))
            .bg(self.color("debugToolBar.background"))
            .shadow(vec![gpui::BoxShadow { color: self.color("widget.shadow").into(), offset: gpui::point(px(0.), px(2.)), blur_radius: px(8.), spread_radius: px(0.), inset: false }])
            .when_some(self.theme.color("contrastBorder"), |bar, border| bar.border_1().border_color(border))
            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
            .child(
                self.icon("gripper", DRAG_AREA_WIDTH, 16., self.foreground_or("icon.foreground"))
                    .id("debug-toolbar-drag-area")
                    .opacity(0.5)
                    .cursor_grab()
                    .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, cx| {
                        cx.stop_propagation();
                        // Double click on the gripper centers the toolbar again (#8250).
                        if event.click_count == 2 {
                            workbench.store_debug_toolbar_position(0.5, workbench.debug_toolbar_y_default());
                            cx.notify();
                            return;
                        }
                        let (x, y) = workbench.debug_toolbar_position();
                        workbench.debug_view.toolbar_drag = Some(ToolbarDrag { origin: (f32::from(event.position.x), f32::from(event.position.y)), start: (x, y), current: (x, y) });
                    })),
            );
        for (command, title, enabled) in actions {
            // debugToolBar.css: 4px after each action item, the session select's own 2px.
            let margin = if command == FOCUS_SESSION_ID { 2. } else { 4. };
            bar = bar.child(div().flex().mr(px(margin)).child(self.debug_toolbar_item(command, title, enabled, &context, &stop_actions, window, cx)));
        }
        Some(bar)
    }

    /// debugToolBar.ts: with `debug.toolBarLocation` `commandCenter`, the `Debug` submenu of `MenuId.CommandCenterCenter`
    /// whose actions commandCenterControl.ts `CommandCenterCenterViewItem` shows as a toolbar before the search label.
    pub(super) fn command_center_debug_actions(&self, window: &Window, cx: &mut Context<Self>) -> Option<Div> {
        if self.debug.state() == State::Inactive || self.setting("debug.toolBarLocation") != "commandCenter" {
            return None;
        }
        let context = self.key_context(window);
        let actions = self.debug_toolbar_actions(&context, window.modifiers().alt);
        let mut bar = div().debug_selector(|| "command-center-debug".into()).flex().items_center().gap(px(4.)).on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation());
        for (command, title, enabled) in actions {
            bar = bar.child(self.debug_toolbar_item(command, title, enabled, &context, &[], window, cx));
        }
        Some(bar)
    }

    /// An item of the toolbar, floating or docked: the session select, Stop or Disconnect with its dropdown, else a button.
    pub(super) fn debug_toolbar_item(&self, command: String, title: String, enabled: bool, context: &HashMap<String, Value>, stop_actions: &[MenuAction], window: &Window, cx: &mut Context<Self>) -> gpui::AnyElement {
        if command == FOCUS_SESSION_ID {
            return self.focus_session_select(window, cx).into_any_element();
        }
        let tooltip = self.keybindings.resolver.append_keybinding(&title, &command, context);
        let dropdown = !stop_actions.is_empty() && STOP_COMMANDS.contains(&command.as_str());
        let item = self
            .debug_toolbar_icon(&command, &title, enabled)
            .id(gpui::SharedString::from(format!("debug-toolbar-{command}")))
            .rounded(px(4.))
            .child(self.hover_target(gpui::SharedString::from(format!("debug-toolbar-hover-{command}")), HoverContent::Text(tooltip), HoverOptions::mouse()))
            .when(enabled, |item| {
                item.cursor_pointer().when(!dropdown, |item| item.hover(|item| item.bg(self.color("toolbar.hoverBackground")))).on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                    workbench.execute_command(&command, Vec::new(), window, cx);
                }))
            });
        if !dropdown {
            return item.into_any_element();
        }
        self.debug_stop_dropdown(item, stop_actions.to_vec(), cx).into_any_element()
    }

    /// debugActionViewItems.ts `FocusSessionActionViewItem.getSessions`: child sessions only with `debug.showSubSessionsInToolBar`.
    pub(super) fn toolbar_sessions(&self) -> Vec<&crate::debug::session::Session> {
        let show_sub_sessions = self.setting("debug.showSubSessionsInToolBar") == true;
        self.debug.sessions.iter().filter(|session| show_sub_sessions || session.parent.is_none()).collect()
    }

    /// `mapFocusedSessionToSelected`: the focused session, or its top parent without sub sessions in the toolbar.
    fn toolbar_selected_session(&self) -> Option<String> {
        let show_sub_sessions = self.setting("debug.showSubSessionsInToolBar") == true;
        let mut session = self.debug.focused_session()?;
        while let Some(parent) = session.parent.as_deref().filter(|_| !show_sub_sessions).and_then(|parent| self.debug.session(parent)) {
            session = parent;
        }
        Some(session.id.clone())
    }

    /// debugToolBar.css `.select-container`: the label with 8px before and 24px after, 100px to 170px wide.
    fn focus_session_select_width(&self, window: &Window) -> f32 {
        let label = self.toolbar_selected_session().and_then(|id| self.debug.session(&id).map(|session| session.name.clone())).unwrap_or_default();
        let run = gpui::TextRun { len: label.len(), font: window.text_style().font(), color: gpui::black(), background_color: None, underline: None, strikethrough: None };
        let text = f32::from(window.text_system().shape_line(label.into(), px(11.), &[run], None).width);
        (text + 32.).clamp(100., 170.)
    }

    /// `FocusSessionActionViewItem`: a select box of the toolbar sessions, child sessions indented, which runs
    /// `workbench.action.debug.focusProcess` with the chosen one.
    fn focus_session_select(&self, window: &Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let selected = self.toolbar_selected_session();
        let label = selected.as_deref().and_then(|id| self.debug.session(id)).map(|session| session.name.clone()).unwrap_or_default();
        let foreground = self.foreground_or("dropdown.foreground");
        let tracked = self.debug_view.focus_session_bounds.clone();
        div()
            .id("debug-toolbar-focus-session")
            .debug_selector(|| "debug-toolbar-focus-session".into())
            .relative()
            .w(px(self.focus_session_select_width(window)))
            .h(px(24.))
            .flex()
            .items_center()
            .pl(px(8.))
            .pr(px(24.))
            .border_1()
            .rounded(px(4.))
            .cursor_pointer()
            .text_size(px(11.))
            .whitespace_nowrap()
            .overflow_hidden()
            .text_ellipsis()
            .bg(self.color("dropdown.background"))
            .border_color(self.color("dropdown.border"))
            .text_color(foreground)
            .child(label)
            .child(self.icon("chevron-down", 16., 16., foreground).absolute().right(px(4.)))
            .child(gpui::canvas(move |bounds, _, _| tracked.set(bounds), |_, _, _, _| {}).absolute().size_full())
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                workbench.show_focus_session_menu(selected.clone(), window, cx);
            }))
    }

    /// The select box's options, each running `workbench.action.debug.focusProcess` with its session.
    fn show_focus_session_menu(&mut self, selected: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
        let count = self.toolbar_sessions().len();
        while self.debug_view.focus_session_commands < count {
            let index = self.debug_view.focus_session_commands;
            self.commands.register(format!("{FOCUS_SESSION_ID}.{index}"), move |workbench, _, window, cx| {
                let Some(session) = workbench.toolbar_sessions().get(index).map(|session| session.id.clone()) else { return Outcome::done() };
                workbench.execute_command(FOCUS_SESSION_ID, vec![json!(session)], window, cx)
            });
            self.debug_view.focus_session_commands += 1;
        }
        let mut actions = Vec::new();
        for (index, session) in self.toolbar_sessions().into_iter().enumerate() {
            let title = match session.parent {
                Some(_) => format!("\u{a0}\u{a0}{}", session.name),
                None => session.name.clone(),
            };
            let checked = Some(&session.id) == selected.as_ref();
            actions.push(MenuAction::Command { id: format!("{FOCUS_SESSION_ID}.{index}"), title, enabled: true, checked, alt: None });
        }
        let context = self.key_context(window);
        let anchor = self.debug_view.focus_session_bounds.get();
        self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
    }

    /// dropdownWithPrimaryActionViewItem.ts: the primary button and a chevron opening the secondary actions, one
    /// hover background over both (dropdown.css `.monaco-dropdown-with-primary`).
    fn debug_stop_dropdown(&self, primary: gpui::Stateful<Div>, actions: Vec<MenuAction>, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let tracked = self.debug_view.stop_dropdown_bounds.clone();
        let chevron = self
            .icon("chevron-down", STOP_DROPDOWN_WIDTH, 16., self.foreground_or("icon.foreground"))
            .id("debug-toolbar-stop-dropdown")
            .debug_selector(|| "debug-toolbar-stop-dropdown".into())
            .relative()
            .cursor_pointer()
            .child(gpui::canvas(move |bounds, _, _| tracked.set(bounds), |_, _, _, _| {}).absolute().size_full())
            .child(self.hover_target("debug-toolbar-stop-dropdown-hover", HoverContent::Text("More...".into()), HoverOptions::mouse()))
            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                cx.stop_propagation();
                let context = workbench.key_context(window);
                let anchor = workbench.debug_view.stop_dropdown_bounds.get();
                workbench.show_context_menu_actions(actions.clone(), &context, anchor, Vec::new(), window, cx);
            }));
        div()
            .id("debug-toolbar-stop-actions")
            .flex()
            .items_center()
            .rounded(px(5.))
            .hover(|item| item.bg(self.color("toolbar.hoverBackground")))
            .child(primary)
            .child(chevron)
    }

    /// statusbarColorProvider.ts `update`: with the toolbar in the command center, its background while debugging.
    pub(super) fn command_center_debugging(&self) -> bool {
        self.setting("debug.toolBarLocation") == "commandCenter" && self.debug_in_status_bar_mode()
    }

    /// statusbarColorProvider.ts `isStatusbarInDebugMode`.
    fn debug_in_status_bar_mode(&self) -> bool {
        let state = self.debug.state();
        if state == State::Inactive || state == State::Initializing {
            return false;
        }
        !self.debug.sessions.iter().all(|session| session.options["suppressDebugStatusbar"] == true || session.configuration["noDebug"] == true)
    }

    /// statusbarColorProvider.ts `isStatusbarInDebugMode` with `debug.enableStatusBarColor`.
    pub(super) fn statusbar_in_debug_mode(&self) -> bool {
        self.setting("debug.enableStatusBarColor") != false && self.debug_in_status_bar_mode()
    }

    /// debugStatus.ts: the `status.debug` entry with the selected configuration, by `debug.showInStatusBar`.
    pub(crate) fn update_debug_status(&mut self) {
        let shown = self.status_entries.iter().any(|entry| entry.entry_id == DEBUG_STATUS_ID);
        let show = match self.setting("debug.showInStatusBar").as_str() {
            Some("always") => true,
            Some("never") => false,
            _ => shown || self.debug.first_session_started,
        };
        if !show {
            self.status_entries.retain(|entry| entry.entry_id != DEBUG_STATUS_ID);
            return;
        }
        let (folder, name) = self.selected_launch();
        let mut text = name.unwrap_or_default();
        // debugConfigurationManager.ts `getLaunches()` ends with the user settings launch, so it always counts more than one.
        if let Some(folder) = folder.filter(|_| !text.is_empty()) {
            text = format!("{text} ({})", folder.file_name().unwrap_or_default().to_string_lossy());
        }
        let entry = crate::main_thread_status_bar::StatusEntry {
            entry_id: DEBUG_STATUS_ID.into(),
            extension_id: None,
            id: DEBUG_STATUS_ID.into(),
            name: "Debug".into(),
            text: format!("$(debug-alt-small) {text}"),
            tooltip: Some("Select and Start Debug Configuration".into()),
            command: Some(serde_json::json!("workbench.action.debug.selectandstart")),
            color: None,
            background_color: None,
            kind: None,
            align_left: true,
            priority: 30.,
            secondary: 0,
            show_progress: false,
        };
        crate::main_thread_status_bar::set_or_update_entry(&mut self.status_entries, entry);
    }

    /// The pointer moves over the window while the gripper is held.
    pub(super) fn drag_debug_toolbar(&mut self, event: &MouseMoveEvent, window: &Window, cx: &mut Context<Self>) {
        if self.debug_view.toolbar_drag.is_none() {
            return;
        }
        if event.pressed_button != Some(MouseButton::Left) {
            self.end_debug_toolbar_drag();
            return;
        }
        let window_width = f32::from(window.viewport_size().width);
        let drag = self.debug_view.toolbar_drag.as_mut().expect("checked above");
        let x = drag.start.0 + (f32::from(event.position.x) - drag.origin.0) / window_width;
        let y = drag.start.1 + f32::from(event.position.y) - drag.origin.1;
        drag.current = (x.clamp(0., 1.), y.clamp(0., 28. + 35.));
        cx.notify();
    }

    pub(super) fn end_debug_toolbar_drag(&mut self) {
        let Some(drag) = self.debug_view.toolbar_drag.take() else { return };
        self.store_debug_toolbar_position(drag.current.0, drag.current.1);
    }
}

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

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

    use super::super::Workbench;
    use crate::menus::MenuAction;

    fn stopped(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut gpui::VisualTestContext) {
        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 (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, _, cx| {
            let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.initialized = true;
            session.capabilities = json!({ "supportTerminateDebuggee": true });
            workbench.debug.sessions.push(session);
            workbench.debug.focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: None };
            cx.notify();
        });
        cx.run_until_parked();
        (workbench, cx)
    }

    /// debugToolBar.ts `createDisconnectMenuItemAction`: the Stop button's chevron opens `MenuId.DebugToolBarStop` below it.
    #[gpui::test]
    fn the_stop_dropdown_opens_the_debug_toolbar_stop_menu(cx: &mut TestAppContext) {
        let (workbench, cx) = stopped(cx);
        let toolbar = cx.debug_bounds("debug-toolbar").expect("the toolbar floats by default");
        assert_eq!(toolbar.top(), gpui::px(35.), "debugToolBar.ts `yDefault`: below the title bar");
        let chevron = cx.debug_bounds("debug-toolbar-stop-dropdown").expect("Stop has a dropdown with terminateDebuggeeSupported");
        cx.simulate_click(chevron.center(), gpui::Modifiers::none());
        let (origin, ids) = workbench.read_with(cx, |workbench, _| {
            let level = &workbench.context_menu.as_ref().expect("the chevron opens its menu").levels[0];
            let ids: Vec<String> = level.actions.iter().filter_map(|action| match action {
                MenuAction::Command { id, .. } => Some(id.clone()),
                _ => None,
            }).collect();
            (level.origin, ids)
        });
        assert_eq!(origin, chevron.bottom_left());
        assert_eq!(ids, ["workbench.action.debug.disconnect"]);
    }

    /// debugService.ts `onDidChangeCallStack`: Run and Debug's activity badge counts the sessions without a parent.
    #[gpui::test]
    fn the_run_and_debug_activity_counts_the_root_sessions(cx: &mut TestAppContext) {
        let (workbench, cx) = stopped(cx);
        workbench.update(cx, |workbench, _| {
            let mut child = crate::debug::session::Session::new("c".into(), 2, json!({ "name": "c", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            child.parent = Some("s".into());
            workbench.debug.sessions.push(child);
        });
        let badges = workbench.read_with(cx, |workbench, _| workbench.container_badges("workbench.view.debug"));
        assert!(matches!(badges[..], [crate::workbench::activity::Badge::Number(1)]), "{badges:?}");
    }

    /// debugActionViewItems.ts `FocusSessionActionViewItem`: with two sessions the select lists them and focuses the chosen one.
    #[gpui::test]
    fn the_focus_session_select_focuses_the_chosen_session(cx: &mut TestAppContext) {
        let (workbench, cx) = stopped(cx);
        workbench.update_in(cx, |workbench, _, cx| {
            let mut session = crate::debug::session::Session::new("t".into(), 2, json!({ "name": "t", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.initialized = true;
            workbench.debug.sessions.push(session);
            workbench.debug.multi_session_view = true;
            cx.notify();
        });
        cx.run_until_parked();
        let select = cx.debug_bounds("debug-toolbar-focus-session").expect("multiSessionDebug shows the session select");
        cx.simulate_mouse_down(select.center(), gpui::MouseButton::Left, gpui::Modifiers::none());
        let items = workbench.read_with(cx, |workbench, _| {
            workbench.context_menu.as_ref().expect("the select opens its options").levels[0].actions.iter().filter_map(|action| match action {
                MenuAction::Command { id, title, checked, .. } => Some((id.clone(), title.clone(), *checked)),
                _ => None,
            }).collect::<Vec<_>>()
        });
        assert_eq!(items.iter().map(|(_, title, checked)| (title.as_str(), *checked)).collect::<Vec<_>>(), [("s", true), ("t", false)]);
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.execute_command(&items[1].0, Vec::new(), window, cx);
        });
        cx.run_until_parked();
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug.focus.session.clone()), Some("t".into()));
    }

    fn set_toolbar_location(workbench: &gpui::Entity<Workbench>, location: &str, cx: &mut gpui::VisualTestContext) {
        workbench.update_in(cx, |workbench, _, cx| {
            let user = std::env::temp_dir().join(format!("vsrustium-{}", crate::test_name()));
            let mut settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None);
            settings.update_value("debug.toolBarLocation", Some(&json!(location)), config::service::Target::User, None, &[]).unwrap();
            std::fs::remove_dir_all(&user).unwrap();
            *workbench.settings.lock().unwrap() = settings;
            workbench.show_debug_view(cx);
            cx.notify();
        });
        cx.run_until_parked();
    }

    /// debugToolBar.ts `debugViewTitleItems`: docked, the toolbar's items are the Run and Debug title's, not floating.
    #[gpui::test]
    fn a_docked_toolbar_draws_in_the_run_and_debug_title(cx: &mut TestAppContext) {
        let (workbench, cx) = stopped(cx);
        set_toolbar_location(&workbench, "docked", cx);
        assert!(cx.debug_bounds("debug-toolbar-stop-dropdown").is_some(), "Stop and its dropdown are in the title");
        let title = cx.debug_bounds("debug-title-actions").expect("the Run and Debug title draws");
        let stop = cx.debug_bounds("debug-toolbar-stop-dropdown").unwrap();
        assert!(title.contains(&stop.center()), "{title:?} {stop:?}");
        assert!(cx.debug_bounds("debug-toolbar").is_none(), "no floating toolbar");
    }

    /// debugToolBar.ts: with `commandCenter`, the command center shows the toolbar's actions before its label.
    #[gpui::test]
    fn the_command_center_location_draws_the_actions_in_the_command_center(cx: &mut TestAppContext) {
        let (workbench, cx) = stopped(cx);
        set_toolbar_location(&workbench, "commandCenter", cx);
        let actions = cx.debug_bounds("command-center-debug").expect("the command center shows the debug actions");
        let label = cx.debug_bounds("command-center-label").unwrap();
        let spacer = cx.debug_bounds("command-center-spacer").expect("commandCenterControl.ts's spacer between the groups");
        assert!(actions.right() <= spacer.left() && spacer.right() <= label.left(), "{actions:?} {spacer:?} {label:?}");
        assert_eq!(actions.size.width, label.size.width, "compact mode's toolbars share the width");
        assert!(workbench.read_with(cx, |workbench, _| workbench.command_center_debugging()), "statusbarColorProvider.ts colors the command center");
        assert!(cx.debug_bounds("debug-toolbar").is_none(), "no floating toolbar");
    }

    /// menuEntryActionViewItem.ts `updateAltState`: Alt shows Stop's alt, Disconnect.
    #[gpui::test]
    fn alt_swaps_stop_for_disconnect(cx: &mut TestAppContext) {
        let (workbench, cx) = stopped(cx);
        let ids = |alt: bool, cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, _| {
            let context = workbench.key_context(window);
            workbench.debug_toolbar_actions(&context, alt).into_iter().map(|(id, ..)| id).collect::<Vec<_>>()
        });
        let without_alt = ids(false, cx);
        assert!(without_alt.contains(&"workbench.action.debug.stop".to_owned()), "{without_alt:?}");
        let with_alt = ids(true, cx);
        assert!(with_alt.contains(&"workbench.action.debug.disconnect".to_owned()) && !with_alt.contains(&"workbench.action.debug.stop".to_owned()), "{with_alt:?}");
    }
}