Visual Studio Code, rebuilt in Rust
Rust
feat(debug): draw the debug toolbar from debug/toolBar and add debug/createConfiguration to Select Debugger
rokarturcf54a8227d6a
diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rsindex f4041a7f377..d590a11486b 100644--- a/native/crates/app/src/menus.rs+++ b/native/crates/app/src/menus.rs@@ -133,6 +133,10 @@ pub enum MenuId {DebugWatchContext,/// `MenuId.DebugHoverContext`: a debug hover tree row's context menu.DebugHoverContext,+ /// `MenuId.DebugToolBar`: the floating debug toolbar's actions.+ DebugToolBar,+ /// `MenuId.DebugCreateConfiguration`: items appended to the Select Debugger picker.+ DebugCreateConfiguration,/// timeline.contribution.ts "Filter Timeline": a toggle per timeline source.TimelineFilterSubMenu,ViewTitle,@@ -464,6 +468,17 @@ const WORKBENCH_MENUS: &[Row] = &[(MenuId::DebugCallStackContext, None, "workbench.action.debug.restartFrame", "Restart Frame", "navigation", 10., Some("callStackItemType == 'stackFrame' && restartFrameSupported"), Some("stackFrameSupportsRestart")),(MenuId::DebugCallStackContext, None, "debug.copyStackTrace", "Copy Call Stack", "3_modification", 20., Some("callStackItemType == 'stackFrame'"), None),(MenuId::DebugCallStackContext, None, "debug.action.openDisassemblyView", "Open Disassembly View", "z_commands", 50., Some("inDebugMode && debugState == 'stopped' && callStackItemType == 'stackFrame' && disassembleRequestSupported"), Some("focusedStackFrameHasInstructionReference")),+ // debugToolBar.ts `registerDebugToolBarItem`; Stop and Disconnect get their alts in `workbench_menus`.+ (MenuId::DebugToolBar, None, "workbench.action.debug.continue", "Continue", "navigation", 10., Some("debugState == 'stopped'"), None),+ (MenuId::DebugToolBar, None, "workbench.action.debug.pause", "Pause", "navigation", 10., Some("debugState != 'stopped'"), Some("debugState == 'running' && !focusedSessionIsNoDebug")),+ (MenuId::DebugToolBar, None, "workbench.action.debug.stop", "Stop", "navigation", 70., Some("!focusedSessionIsAttach"), None),+ (MenuId::DebugToolBar, None, "workbench.action.debug.disconnect", "Disconnect", "navigation", 70., Some("focusedSessionIsAttach"), None),+ (MenuId::DebugToolBar, None, "workbench.action.debug.stepOver", "Step Over", "navigation", 20., None, Some("debugState == 'stopped'")),+ (MenuId::DebugToolBar, None, "workbench.action.debug.stepInto", "Step Into", "navigation", 30., None, Some("debugState == 'stopped'")),+ (MenuId::DebugToolBar, None, "workbench.action.debug.stepOut", "Step Out", "navigation", 40., None, Some("debugState == 'stopped' && threadHasMultipleStackFrames")),+ (MenuId::DebugToolBar, None, "workbench.action.debug.restart", "Restart", "navigation", 60., None, None),+ (MenuId::DebugToolBar, None, "workbench.action.debug.stepBack", "Step Back", "navigation", 50., Some("stepBackSupported"), Some("debugState == 'stopped'")),+ (MenuId::DebugToolBar, None, "workbench.action.debug.reverseContinue", "Reverse", "navigation", 55., Some("stepBackSupported"), Some("debugState == 'stopped'")),// debugViewlet.ts: the Run and Debug container's title. shortcut: the docked toolbar's items (debugToolBar.ts) wait for `debug.toolBarLocation` docked (ledger debug row).(MenuId::ViewContainerTitle, None, "workbench.action.debug.start", "Start Debugging", "navigation", 10., Some("viewContainer == 'workbench.view.debug' && debugUx != 'simple' && workbenchState != 'empty' && (debugState == 'inactive' || config.debug.toolBarLocation != 'docked') && (!config.debug.hideLauncherWhileDebugging || !inDebugMode)"), Some("debugState != 'initializing'")),(MenuId::ViewContainerTitle, None, "workbench.action.debug.configure", "Open 'launch.json'", "navigation", 20., Some("viewContainer == 'workbench.view.debug' && debugUx != 'simple' && workbenchState != 'empty' && (debugState == 'inactive' || config.debug.toolBarLocation != 'docked')"), Some("debugUx != 'simple'")),@@ -764,7 +779,12 @@ pub fn workbench_menus() -> Vec<MenuItem> {Some(submenu) => Entry::Submenu { submenu, toggled: None },None => {// The Delete item runs Delete Permanently with Alt held.- let alt = (id == "moveFileToTrash").then(|| Alt { id: "deleteFile".into(), title: "Delete Permanently".into(), precondition: None });+ let alt = match (menu, id) {+ (_, "moveFileToTrash") => Some(Alt { id: "deleteFile".into(), title: "Delete Permanently".into(), precondition: None }),+ (MenuId::DebugToolBar, "workbench.action.debug.stop") => Some(Alt { id: "workbench.action.debug.disconnect".into(), title: "Disconnect".into(), precondition: Expr::deserialize("!focusedSessionIsAttach && terminateDebuggeeSupported") }),+ (MenuId::DebugToolBar, "workbench.action.debug.disconnect") => Some(Alt { id: "workbench.action.debug.stop".into(), title: "Stop".into(), precondition: Expr::deserialize("focusedSessionIsAttach && terminateDebuggeeSupported") }),+ _ => None,+ };Entry::Command { id: id.to_string(), precondition: precondition.and_then(Expr::deserialize), toggled: None, alt }}};@@ -909,7 +929,7 @@ pub fn workbench_menus() -> Vec<MenuItem> {/// menusExtensionPoint.ts `apiMenus`: the `contributes.menus` keys of the menus the port shows. `commandPalette`/// is read by `command_palette::menu`.-const API_MENUS: [(&str, MenuId); 49] = [+const API_MENUS: [(&str, MenuId); 51] = [("file/newFile", MenuId::NewFile),("editor/context", MenuId::EditorContext),("explorer/context", MenuId::ExplorerContext),@@ -942,6 +962,8 @@ const API_MENUS: [(&str, MenuId); 49] = [("debug/callstack/context", MenuId::DebugCallStackContext),("debug/variables/context", MenuId::DebugVariablesContext),("debug/watch/context", MenuId::DebugWatchContext),+ ("debug/toolBar", MenuId::DebugToolBar),+ ("debug/createConfiguration", MenuId::DebugCreateConfiguration),("view/title", MenuId::ViewTitle),("viewContainer/title", MenuId::ViewContainerTitle),("view/item/context", MenuId::ViewItemContext),@@ -1058,6 +1080,7 @@ pub fn extension_menus(extensions: &[ScannedExtension]) -> Vec<MenuItem> {// menusExtensionPoint.ts: the `proposed` menus need their API proposal.let proposal = match key.as_str() {"editor/content" => Some("contribEditorContentMenu"),+ "debug/createConfiguration" => Some("contribDebugCreateConfiguration"),"commentsView/commentThread/context" => Some("contribCommentsViewThreadMenus"),"scm/historyItemRef/context" => Some("contribSourceControlHistoryItemMenu"),"viewContainer/title" => Some("contribViewContainerTitle"),diff --git a/native/crates/app/src/menus/tests.rs b/native/crates/app/src/menus/tests.rsindex 9d78352187d..885132b2454 100644--- a/native/crates/app/src/menus/tests.rs+++ b/native/crates/app/src/menus/tests.rs@@ -379,3 +379,27 @@ fn refactor_and_source_action_show_for_the_kinds_the_providers_offer() {assert_eq!(shown("quickfix refactor.extract source.organizeImports"), ["editor.action.refactor", "editor.action.sourceAction"]);assert_eq!(shown("refactoring"), Vec::<String>::new(), "`\\b` ends the kind");}++/// debugToolBar.ts: the toolbar's own items in their order with their `when` and preconditions, and an+/// extension's `debug/toolBar` item among them; `debug/createConfiguration` needs its API proposal.+#[test]+fn the_debug_toolbar_and_create_configuration_menus_take_contributed_items() {+ let contributes = json!({+ "commands": [{ "command": "x.hotReload", "title": "Hot Reload" }, { "command": "x.create", "title": "Create a Configuration" }],+ "menus": { "debug/toolBar": [{ "command": "x.hotReload", "group": "navigation@65" }], "debug/createConfiguration": [{ "command": "x.create" }] }+ });+ let mut proposed = extension("debug-menus", contributes.clone());+ proposed.description["enabledApiProposals"] = json!(["contribDebugCreateConfiguration"]);+ let mut registry = workbench_menus();+ registry.extend(extension_menus(&[proposed]));+ let stopped = HashMap::from([("debugState".to_string(), json!("stopped")), ("terminateDebuggeeSupported".to_string(), json!(true))]);+ let actions = menu_actions(®istry, MenuId::DebugToolBar, &stopped);+ assert_eq!(+ ids(&actions),+ ["workbench.action.debug.continue", "workbench.action.debug.stepOver", "workbench.action.debug.stepInto", "workbench.action.debug.stepOut", "workbench.action.debug.restart", "x.hotReload", "workbench.action.debug.stop"]+ );+ assert!(matches!(&actions[3], MenuAction::Command { enabled: false, .. }), "one frame, no Step Out: {:?}", actions[3]);+ assert!(matches!(&actions[6], MenuAction::Command { alt: Some((alt, _)), .. } if alt == "workbench.action.debug.disconnect"), "{:?}", actions[6]);+ assert_eq!(ids(&menu_actions(®istry, MenuId::DebugCreateConfiguration, &no_context())), ["x.create"]);+ assert!(extension_menus(&[extension("debug-menus-unproposed", contributes)]).iter().all(|item| item.menu != MenuId::DebugCreateConfiguration));+}diff --git a/native/crates/app/src/workbench/debug_service.rs b/native/crates/app/src/workbench/debug_service.rsindex cfb96e66a2d..2a565c7ebee 100644--- a/native/crates/app/src/workbench/debug_service.rs+++ b/native/crates/app/src/workbench/debug_service.rs@@ -1598,32 +1598,42 @@ async fn guess_debugger(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContexlet activation = on_workbench(this, cx, |workbench, _, _| (workbench.host.activate_by_event("onDebugInitialConfigurations"), workbench.host.activate_by_event("onDebug")))?;let _ = activation.0.await;let _ = activation.1.await;- let candidates = on_workbench(this, cx, |workbench, window, _| {+ let (candidates, contributed, by_language) = on_workbench(this, cx, |workbench, window, _| {let context = workbench.key_context(window);+ let mut contributed = Vec::new();+ for action in crate::menus::menu_actions(&workbench.menus, crate::menus::MenuId::DebugCreateConfiguration, &context) {+ if let crate::menus::MenuAction::Command { id, title, .. } = action {+ contributed.push((id, title));+ }+ }let holds = |when: Option<&str>| when.and_then(crate::contextkey::Expr::deserialize).is_none_or(|when| when.evaluate(&context));let enabled: Vec<&Debugger> = workbench.debug.debuggers.iter().filter(|debugger| holds(debugger.when()) && workbench.debug.adapter_types.contains(&debugger.debug_type)).collect();let interested: Vec<&Debugger> = enabled.iter().copied().filter(|debugger| language.as_deref().is_some_and(|language| debugger.interested_in_language(language))).collect();let mut candidates: Vec<(String, String)> = match interested.len() {- 1 => return interested.iter().map(|debugger| (debugger.debug_type.clone(), debugger.label().to_owned())).collect(),+ 1 => return (vec![(interested[0].debug_type.clone(), interested[0].label().to_owned())], contributed, true),0 => enabled.iter().filter(|debugger| debugger.has_initial_configuration() || workbench.debug.providers.iter().any(|provider| provider.debug_type == debugger.debug_type)).map(|debugger| (debugger.debug_type.clone(), debugger.label().to_owned())).collect(),_ => interested.iter().map(|debugger| (debugger.debug_type.clone(), debugger.label().to_owned())).collect(),};candidates.retain(|(debug_type, _)| workbench.debug.debugger(debug_type).is_none_or(|debugger| !debugger.hidden_when().and_then(crate::contextkey::Expr::deserialize).is_some_and(|when| when.evaluate(&context))));candidates.sort_by(|first, second| first.1.cmp(&second.1));- candidates+ (candidates, contributed, false)})?;- let debug_type = match candidates.len() {- 0 => {+ let debug_type = if by_language {+ candidates[0].0.clone()+ } else {+ if candidates.is_empty() && contributed.is_empty() {on_workbench(this, cx, |workbench, _, _| workbench.notify_error("The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type."))?;return Ok(None);}- 1 => candidates[0].0.clone(),- _ => {- let items = candidates.iter().map(|(_, label)| (label.clone(), None)).collect();- let picked = on_workbench(this, cx, |workbench, window, cx| workbench.debug_pick("Select debugger", items, window, cx))?;- let Some(index) = picked.await.ok().flatten().and_then(|index| index.parse::<usize>().ok()) else { return Ok(None) };- candidates[index].0.clone()+ let items = candidates.iter().chain(&contributed).map(|(_, label)| (label.clone(), None)).collect();+ let picked = on_workbench(this, cx, |workbench, window, cx| workbench.debug_pick("Select debugger", items, window, cx))?;+ let Some(index) = picked.await.ok().flatten().and_then(|index| index.parse::<usize>().ok()) else { return Ok(None) };+ // debugAdapterManager.ts: a `MenuId.DebugCreateConfiguration` item runs its command and starts nothing.+ if let Some((command, _)) = index.checked_sub(candidates.len()).and_then(|index| contributed.get(index)) {+ on_workbench(this, cx, |workbench, window, cx| drop(workbench.execute_command(command, Vec::new(), window, cx)))?;+ return Ok(None);}+ candidates[index].0.clone()};if let Some(resource) = resource {on_workbench(this, cx, |workbench, _, _| {diff --git a/native/crates/app/src/workbench/debug_toolbar.rs b/native/crates/app/src/workbench/debug_toolbar.rsindex 96a02d7e4df..afd0ae016e5 100644--- a/native/crates/app/src/workbench/debug_toolbar.rs+++ b/native/crates/app/src/workbench/debug_toolbar.rs@@ -3,9 +3,14 @@use gpui::{ClickEvent, Context, Div, MouseButton, MouseDownEvent, MouseMoveEvent, Window, div, prelude::*, px};+use std::collections::HashMap;++use serde_json::Value;+use super::Workbench;-use super::hover::HoverOptions;+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";@@ -23,45 +28,61 @@ pub struct ToolbarDrag {current: (f32, f32),}-/// One `registerDebugToolBarItem` action.-struct ToolbarAction {- command: &'static str,- title: &'static str,- icon: &'static str,- color: &'static str,- enabled: bool,-}+/// 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 {- /// The toolbar's actions in their `order`, with their `when` and `precondition` evaluated.- fn debug_toolbar_actions(&self) -> Vec<ToolbarAction> {- let state = self.debug.state();- let stopped = state == State::Stopped;- let session = self.debug.focused_session();- let attach = session.is_some_and(|session| session.configuration["request"] == "attach");- let no_debug = session.is_some_and(|session| session.options["noDebug"] == true);- let step_back = session.is_some_and(|session| session.capabilities["supportsStepBack"] == true);- let thread = session.zip(self.debug.focus.thread).and_then(|(session, id)| session.thread(id));- let multiple_frames = thread.is_some_and(|thread| thread.frames.len() > 1 || thread.total_frames.is_some());- let action = |command, title, icon, color, enabled| ToolbarAction { command, title, icon, color, enabled };+ /// debugToolBar.ts: `getFlatActionBarActions` of `MenuId.DebugToolBar`, the workbench's and the extensions' items.+ fn debug_toolbar_actions(&self, context: &HashMap<String, Value>) -> Vec<(String, String, bool)> {let mut actions = Vec::new();- match stopped {- true => actions.push(action("workbench.action.debug.continue", "Continue", "debug-continue", "debugIcon.continueForeground", true)),- false => actions.push(action("workbench.action.debug.pause", "Pause", "debug-pause", "debugIcon.pauseForeground", state == State::Running && !no_debug)),+ for action in menu_actions(&self.menus, MenuId::DebugToolBar, context) {+ if let MenuAction::Command { id, title, enabled, .. } = action {+ actions.push((id, title, enabled));+ }}- actions.push(action("workbench.action.debug.stepOver", "Step Over", "debug-step-over", "debugIcon.stepOverForeground", stopped));- actions.push(action("workbench.action.debug.stepInto", "Step Into", "debug-step-into", "debugIcon.stepIntoForeground", stopped));- actions.push(action("workbench.action.debug.stepOut", "Step Out", "debug-step-out", "debugIcon.stepOutForeground", stopped && multiple_frames));- if step_back {- actions.push(action("workbench.action.debug.stepBack", "Step Back", "debug-step-back", "debugIcon.stepBackForeground", stopped));- actions.push(action("workbench.action.debug.reverseContinue", "Reverse", "debug-reverse-continue", "debugIcon.reverseContinueForeground", stopped));+ 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 });}- actions.push(action("workbench.action.debug.restart", "Restart", "debug-restart", "debugIcon.restartForeground", true));- match attach {- true => actions.push(action("workbench.action.debug.disconnect", "Disconnect", "debug-disconnect", "debugIcon.disconnectForeground", true)),- false => actions.push(action("workbench.action.debug.stop", "Stop", "debug-stop", "debugIcon.stopForeground", true)),+ 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),}- actions}fn debug_toolbar_position(&self) -> (f32, f32) {@@ -88,14 +109,14 @@ impl Workbench {if !self.debug.sessions.is_empty() && self.debug.sessions.iter().all(|session| session.options["suppressDebugToolbar"] == true) {return None;}- let actions = self.debug_toolbar_actions();+ let context = self.key_context(window);+ let actions = self.debug_toolbar_actions(&context);let width = 2. + DRAG_AREA_WIDTH + actions.len() as f32 * ACTION_WIDTH;let window_width = f32::from(window.viewport_size().width);let (x, y) = self.debug_toolbar_position();// debugToolBar.ts `yRange`: from the top to the bottom of the title bar and the editor tabs.let y = y.clamp(0., 28. + 35.);let left = (x * window_width - width / 2.).clamp(0., (window_width - width).max(0.));- let disabled = self.color("disabledForeground");let mut bar = div().id("debug-toolbar").absolute()@@ -127,20 +148,19 @@ impl Workbench {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 action in actions {- let color = if action.enabled { self.color(action.color) } else { disabled };- let command = action.command;+ for (command, title, enabled) in actions {+ let tooltip = self.keybindings.resolver.append_keybinding(&title, &command, &context);bar = bar.child(- self.icon(action.icon, 22., 16., color)- .id(command)+ self.debug_toolbar_icon(&command, &title, enabled)+ .id(gpui::SharedString::from(format!("debug-toolbar-{command}"))).mr(px(4.)).rounded(px(4.))- .when(action.enabled, |item| {+ .child(self.hover_target(gpui::SharedString::from(format!("debug-toolbar-hover-{command}")), HoverContent::Text(tooltip), HoverOptions::mouse()))+ .when(enabled, |item| {item.cursor_pointer().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);+ workbench.execute_command(&command, Vec::new(), window, cx);}))- })- .child(self.action_hover(action.title, command, HoverOptions::mouse())),+ }),);}Some(bar)diff --git a/native/crates/app/src/workbench/scm_view.rs b/native/crates/app/src/workbench/scm_view.rsindex cd19e5749cc..f03f1b25877 100644--- a/native/crates/app/src/workbench/scm_view.rs+++ b/native/crates/app/src/workbench/scm_view.rs@@ -1098,7 +1098,7 @@ impl Workbench {}/// A command's or submenu's icon in a toolbar: its codicon or image, else its title.- fn command_icon(&self, icon: Option<&CommandIcon>, title: &str, foreground: Rgba) -> Div {+ pub(in crate::workbench) fn command_icon(&self, icon: Option<&CommandIcon>, title: &str, foreground: Rgba) -> Div {match icon {Some(CommandIcon::Codicon(name)) => self.icon(name, 22., 16., foreground),Some(CommandIcon::Image(light, dark)) => {