Visual Studio Code, rebuilt in Rust
Rust
feat(debug): port the Disassembly view and instruction breakpoints
rokartur9e7e55868e26
diff --git a/native/crates/app/src/debug.rs b/native/crates/app/src/debug.rsindex 5653ad3581b..1aab2722f7d 100644--- a/native/crates/app/src/debug.rs+++ b/native/crates/app/src/debug.rs@@ -4,6 +4,7 @@pub mod ansi;pub mod configuration;+pub mod disassembly;pub mod session;#[cfg(test)]mod tests;@@ -35,6 +36,7 @@ pub struct SessionData {pub supports_conditional: bool,pub supports_hit_conditional: bool,pub supports_function: bool,+ pub supports_instruction: bool,}impl SessionData {@@ -55,6 +57,7 @@ impl SessionData {supports_conditional: capabilities["supportsConditionalBreakpoints"] == true,supports_hit_conditional: capabilities["supportsHitConditionalBreakpoints"] == true,supports_function: capabilities["supportsFunctionBreakpoints"] == true,+ supports_instruction: capabilities["supportsInstructionBreakpoints"] == true,}}}@@ -308,6 +311,28 @@ pub struct DataBreakpoint {pub access_types: Option<Value>,}+/// `InstructionBreakpoint`: debugStorage.ts does not store these.+#[derive(Clone, Debug, PartialEq)]+pub struct InstructionBreakpoint {+ pub base: BaseBreakpoint,+ pub instruction_reference: String,+ pub offset: i64,+ pub address: u64,+}++impl InstructionBreakpoint {+ pub fn to_dap(&self) -> Value {+ let mut breakpoint = json!({ "instructionReference": self.instruction_reference, "condition": self.base.condition, "hitCondition": self.base.hit_condition, "mode": self.base.mode, "offset": self.offset });+ strip_nulls(&mut breakpoint);+ breakpoint+ }++ /// `supported`: true until a session answers.+ pub fn supported(&self) -> bool {+ self.base.data.as_ref().is_none_or(|data| data.supports_instruction)+ }+}+#[derive(Clone, Debug, PartialEq)]pub struct ExceptionBreakpoint {pub base: BaseBreakpoint,@@ -369,13 +394,14 @@ pub struct DebugModel {pub function_breakpoints: Vec<FunctionBreakpoint>,pub exception_breakpoints: Vec<ExceptionBreakpoint>,pub data_breakpoints: Vec<DataBreakpoint>,+ pub instruction_breakpoints: Vec<InstructionBreakpoint>,pub breakpoints_activated: bool,pub watch_expressions: Vec<WatchExpression>,}impl Default for DebugModel {fn default() -> Self {- DebugModel { breakpoints: Vec::new(), function_breakpoints: Vec::new(), exception_breakpoints: Vec::new(), data_breakpoints: Vec::new(), breakpoints_activated: true, watch_expressions: Vec::new() }+ DebugModel { breakpoints: Vec::new(), function_breakpoints: Vec::new(), exception_breakpoints: Vec::new(), data_breakpoints: Vec::new(), instruction_breakpoints: Vec::new(), breakpoints_activated: true, watch_expressions: Vec::new() }}}@@ -486,6 +512,13 @@ impl DebugModel {Some(None) => {}}}+ for breakpoint in &mut self.instruction_breakpoints {+ match find(&breakpoint.base.id) {+ None => breakpoint.base.set_session_data(session_id, None),+ Some(Some(found)) => breakpoint.base.set_session_data(session_id, Some(found)),+ Some(None) => {}+ }+ }BreakpointsChange { session_only: true, ..Default::default() }}@@ -529,7 +562,8 @@ impl DebugModel {let sources = self.breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);let functions = self.function_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);let data = self.data_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);- for base in sources.chain(functions).chain(data) {+ let instructions = self.instruction_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);+ for base in sources.chain(functions).chain(data).chain(instructions) {if base.enabled != enable {base.enabled = enable;changed.push(base.id.clone());@@ -546,7 +580,8 @@ impl DebugModel {let functions = self.function_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);let data = self.data_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);let exceptions = self.exception_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);- sources.chain(functions).chain(data).chain(exceptions)+ let instructions = self.instruction_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base);+ sources.chain(functions).chain(data).chain(exceptions).chain(instructions)}pub fn add_function_breakpoint(&mut self, name: &str, options: &Value, id: Option<String>) -> BreakpointsChange {@@ -574,6 +609,26 @@ impl DebugModel {BreakpointsChange { removed, ..Default::default() }}+ /// `addInstructionBreakpoint`: only the sessions hear of it.+ pub fn add_instruction_breakpoint(&mut self, instruction_reference: &str, offset: i64, address: u64, options: &Value) -> BreakpointsChange {+ let id = generate_uuid();+ self.instruction_breakpoints.push(InstructionBreakpoint { base: BaseBreakpoint::new(id.clone(), options), instruction_reference: instruction_reference.to_owned(), offset, address });+ BreakpointsChange { added: vec![id], session_only: true, ..Default::default() }+ }++ /// `removeInstructionBreakpoints`: by address, which stays when a new disassemble changes the reference;+ /// else by reference and offset; all of them with neither.+ pub fn remove_instruction_breakpoints(&mut self, instruction_reference: Option<&str>, offset: Option<i64>, address: Option<u64>) -> BreakpointsChange {+ let matches = |breakpoint: &InstructionBreakpoint| match (address, instruction_reference) {+ (Some(address), _) => breakpoint.address == address,+ (None, Some(reference)) if !reference.is_empty() => breakpoint.instruction_reference == reference && offset.is_none_or(|offset| breakpoint.offset == offset),+ _ => true,+ };+ let removed: Vec<String> = self.instruction_breakpoints.iter().filter(|breakpoint| matches(breakpoint)).map(|breakpoint| breakpoint.base.id.clone()).collect();+ self.instruction_breakpoints.retain(|breakpoint| !removed.contains(&breakpoint.base.id));+ BreakpointsChange { removed, ..Default::default() }+ }+/// `setExceptionBreakpointsForSession`: a filter no breakpoint matches yet becomes one, enabled when it is/// the adapter's default.pub fn set_exception_breakpoints_for_session(&mut self, session_id: &str, filters: &[Value]) -> bool {@@ -764,7 +819,7 @@ impl DebugModel {.collect();let watch_expressions = list(WATCH_EXPRESSIONS_KEY).iter().map(|value| WatchExpression { id: id(value), name: text(value, "name").unwrap_or_default() }).collect();let breakpoints_activated = get(BREAKPOINTS_ACTIVATED_KEY).is_none_or(|value| value != "false");- DebugModel { breakpoints, function_breakpoints, exception_breakpoints, data_breakpoints, breakpoints_activated, watch_expressions }+ DebugModel { breakpoints, function_breakpoints, exception_breakpoints, data_breakpoints, instruction_breakpoints: Vec::new(), breakpoints_activated, watch_expressions }}}diff --git a/native/crates/app/src/debug/disassembly.rs b/native/crates/app/src/debug/disassembly.rsnew file mode 100644index 00000000000..45da6bf78c4--- /dev/null+++ b/native/crates/app/src/debug/disassembly.rs@@ -0,0 +1,189 @@+//! The instruction list of disassemblyView.ts `DisassemblyView`: the DAP `disassemble` answers merged by address,+//! the address of each instruction reference, and which rows show their source location.++use std::collections::HashMap;++use serde_json::Value;++/// `DisassemblyView.NUM_INSTRUCTIONS_TO_LOAD`.+pub const INSTRUCTIONS_TO_LOAD: i64 = 50;++/// `IDisassembledInstructionEntry`, its breakpoint state left to the model.+#[derive(Clone, Debug, PartialEq)]+pub struct Entry {+ pub instruction_reference: String,+ /// The `offset` the request asked for, the basis of `instruction_offset`.+ pub reference_offset: i64,+ /// How many instructions from the reference and its offset this one is.+ pub instruction_offset: i64,+ /// The DAP `DisassembledInstruction`, its location filled forward.+ pub instruction: Value,+ pub address: u64,+ /// The first instruction of its source line.+ pub show_source_location: bool,+}++#[derive(Clone, Debug, Default)]+pub struct Disassembly {+ pub entries: Vec<Entry>,+ reference_addresses: HashMap<String, u64>,+}++impl Disassembly {+ /// `clear`: an empty list draws "Disassembly not available.".+ pub fn clear(&mut self) {+ self.entries.clear();+ self.reference_addresses.clear();+ }++ /// `getReferenceAddress`.+ pub fn reference_address(&self, instruction_reference: &str) -> Option<u64> {+ self.reference_addresses.get(instruction_reference).copied()+ }++ /// `getIndexFromAddress`.+ pub fn index_of_address(&self, address: u64) -> Option<usize> {+ self.entries.binary_search_by_key(&address, |entry| entry.address).ok()+ }++ /// `getAddressAndOffset`: the reference, the entry's distance from its address, and the address.+ pub fn address_and_offset(&self, entry: &Entry) -> (String, i64, u64) {+ let base = self.reference_address(&entry.instruction_reference).unwrap_or(entry.address);+ (entry.instruction_reference.clone(), entry.address.wrapping_sub(base) as i64, entry.address)+ }++ /// The body of `loadDisassembledInstructions` after the request: the instructions replace the ones in their+ /// address range; the range replaced and the count put in its place.+ pub fn merge(&mut self, instruction_reference: &str, offset: i64, instruction_offset: i64, instructions: &[Value]) -> (std::ops::Range<usize>, usize) {+ let mut new_entries = Vec::new();+ let mut last_location = Value::Null;+ let mut last_line = None;+ for (index, instruction) in instructions.iter().enumerate() {+ let mut instruction = instruction.clone();+ let this_offset = instruction_offset + index as i64;+ // The DAP spec fills a missing location forward; only the first instruction of a range keeps it.+ if !instruction["location"].is_null() {+ last_location = instruction["location"].clone();+ last_line = None;+ }+ if let Some(line) = instruction["line"].as_u64() {+ let number = |key: &str, default: u64| instruction[key].as_u64().unwrap_or(default);+ let range = Some((line, number("column", 0), number("endLine", line), number("endColumn", 0)));+ if range != last_line {+ last_line = range;+ instruction["location"] = last_location.clone();+ }+ }+ // An address that does not parse, or the adapter's -1, is no instruction.+ let Some(address) = instruction["address"].as_str().and_then(parse_address) else { continue };+ if offset == 0 && this_offset == 0 {+ self.reference_addresses.insert(instruction_reference.to_owned(), address);+ }+ new_entries.push(Entry { instruction_reference: instruction_reference.to_owned(), reference_offset: offset, instruction_offset: this_offset, instruction, address, show_source_location: false });+ }+ let (Some(first), Some(last)) = (new_entries.first(), new_entries.last()) else { return (0..0, 0) };+ let start = match self.entries.binary_search_by_key(&first.address, |entry| entry.address) {+ Ok(index) | Err(index) => index,+ };+ let end = match self.entries.binary_search_by_key(&last.address, |entry| entry.address) {+ Ok(index) => index + 1,+ Err(index) => index,+ };+ let end = end.max(start);+ // Rows group by source line: a location shows when it differs from the last one shown before it.+ let mut last_located = self.entries[..start].iter().rev().map(|entry| &entry.instruction).find(|instruction| !instruction["location"].is_null() && !instruction["line"].is_null()).cloned();+ for entry in &mut new_entries {+ let instruction = &entry.instruction;+ let shows = !instruction["line"].is_null()+ && !instruction["location"].is_null()+ && last_located.as_ref().is_none_or(|last| !sources_equal(&instruction["location"], &last["location"]) || instruction["line"] != last["line"]);+ if shows {+ entry.show_source_location = true;+ last_located = Some(instruction.clone());+ }+ }+ let inserted = new_entries.len();+ self.entries.splice(start..end, new_entries);+ (start..end, inserted)+ }+}++/// `BigInt(address)`: hex with `0x`, else decimal; a negative address is none.+fn parse_address(address: &str) -> Option<u64> {+ match address.strip_prefix("0x").or_else(|| address.strip_prefix("0X")) {+ Some(hex) => u64::from_str_radix(hex, 16).ok(),+ None => address.parse().ok(),+ }+}++/// debugUtils.ts `sourcesEqual`.+fn sources_equal(first: &Value, second: &Value) -> bool {+ first["name"] == second["name"] && first["path"] == second["path"] && first["sourceReference"] == second["sourceReference"]+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::*;++ fn instructions(addresses: std::ops::Range<u64>) -> Vec<Value> {+ addresses.map(|address| json!({ "address": format!("0x{address:x}"), "instruction": format!("nop {address}") })).collect()+ }++ /// `loadDisassembledInstructions`' answer: the rows added.+ fn load(disassembly: &mut Disassembly, offset: i64, instruction_offset: i64, answer: &[Value]) -> i64 {+ let (replaced, inserted) = disassembly.merge("ref", offset, instruction_offset, answer);+ inserted as i64 - replaced.len() as i64+ }++ fn addresses(disassembly: &Disassembly) -> Vec<u64> {+ disassembly.entries.iter().map(|entry| entry.address).collect()+ }++ #[test]+ fn the_first_instruction_at_offset_zero_gives_the_reference_its_address() {+ let mut disassembly = Disassembly::default();+ assert_eq!(load(&mut disassembly, 0, -2, &instructions(0x10..0x15)), 5);+ assert_eq!(disassembly.reference_address("ref"), Some(0x12));+ let entry = disassembly.entries[4].clone();+ assert_eq!(disassembly.address_and_offset(&entry), ("ref".to_owned(), 2, 0x14));+ }++ #[test]+ fn loads_above_and_below_join_by_address_and_replace_the_overlap() {+ let mut disassembly = Disassembly::default();+ disassembly.merge("ref", 0, 0, &instructions(0x20..0x30));+ assert_eq!(load(&mut disassembly, 0, -8, &instructions(0x18..0x22)), 8);+ assert_eq!(load(&mut disassembly, 0, 16, &instructions(0x30..0x34)), 4);+ assert_eq!(addresses(&disassembly), (0x18..0x34).collect::<Vec<_>>());+ assert_eq!(disassembly.index_of_address(0x20), Some(8));+ }++ #[test]+ fn the_adapters_invalid_addresses_are_skipped() {+ let mut disassembly = Disassembly::default();+ let answer = [json!({ "address": "-1", "instruction": "?" }), json!({ "address": "junk", "instruction": "?" }), json!({ "address": "4096", "instruction": "ret" })];+ assert_eq!(load(&mut disassembly, 0, -2, &answer), 1);+ assert_eq!(addresses(&disassembly), [4096]);+ }++ #[test]+ fn the_location_fills_forward_and_shows_once_per_line() {+ let mut disassembly = Disassembly::default();+ let source = json!({ "name": "a.c", "path": "/w/a.c" });+ let answer = [+ json!({ "address": "0x1", "instruction": "a", "location": source, "line": 3 }),+ json!({ "address": "0x2", "instruction": "b", "line": 3 }),+ json!({ "address": "0x3", "instruction": "c", "line": 4 }),+ json!({ "address": "0x4", "instruction": "d" }),+ ];+ disassembly.merge("ref", 0, 0, &answer);+ let shown: Vec<bool> = disassembly.entries.iter().map(|entry| entry.show_source_location).collect();+ assert_eq!(shown, [true, false, true, false]);+ assert_eq!(disassembly.entries[2].instruction["location"], source);+ // A later load below the line already shown does not show it again.+ disassembly.merge("ref", 0, 4, &[json!({ "address": "0x5", "instruction": "e", "location": source, "line": 4 })]);+ assert!(!disassembly.entries[4].show_source_location);+ }+}diff --git a/native/crates/app/src/debug/session.rs b/native/crates/app/src/debug/session.rsindex a1020eaabf8..a0bf1e0d96a 100644--- a/native/crates/app/src/debug/session.rs+++ b/native/crates/app/src/debug/session.rs@@ -43,6 +43,7 @@ pub struct StackFrame {pub end_column: u32,pub presentation_hint: Option<String>,pub can_restart: bool,+ pub instruction_pointer_reference: Option<String>,}impl StackFrame {@@ -76,6 +77,8 @@ pub struct Thread {pub frames: Vec<StackFrame>,/// `totalFrames` when the adapter reported more than were fetched.pub total_frames: Option<u64>,+ /// debugModel.ts `Thread.lastSteppingGranularity`: the granularity of the last step request.+ pub last_stepping_granularity: Option<&'static str>,}impl Thread {diff --git a/native/crates/app/src/debug/tests.rs b/native/crates/app/src/debug/tests.rsindex 87261872093..f0395c62e5c 100644--- a/native/crates/app/src/debug/tests.rs+++ b/native/crates/app/src/debug/tests.rs@@ -103,6 +103,47 @@ fn function_breakpoints() {assert!(model.function_breakpoints.is_empty());}+fn instruction_references(model: &DebugModel) -> Vec<(&str, i64)> {+ model.instruction_breakpoints.iter().map(|breakpoint| (breakpoint.instruction_reference.as_str(), breakpoint.offset)).collect()+}++#[test]+fn instruction_breakpoints() {+ let mut model = DebugModel::default();+ let change = model.add_instruction_breakpoint("0xCCCCFFFF", 0, 0, &json!({}));+ assert!(change.session_only);+ model.add_instruction_breakpoint("0xCCCCEEEE", 1, 0, &json!({}));+ assert_eq!(instruction_references(&model), [("0xCCCCFFFF", 0), ("0xCCCCEEEE", 1)]);+}++#[test]+fn remove_instruction_breakpoints_prefers_the_address_when_the_reference_changed() {+ let mut model = DebugModel::default();+ model.add_instruction_breakpoint("oldRef", 0, 0x1000, &json!({}));+ model.remove_instruction_breakpoints(Some("newRef"), Some(0), Some(0x1000));+ assert!(model.instruction_breakpoints.is_empty());+}++#[test]+fn remove_instruction_breakpoints_falls_back_to_reference_and_offset() {+ let mut model = DebugModel::default();+ model.add_instruction_breakpoint("ref", 4, 0x2000, &json!({}));+ model.remove_instruction_breakpoints(Some("other"), Some(4), None);+ assert_eq!(model.instruction_breakpoints.len(), 1);+ model.remove_instruction_breakpoints(Some("ref"), Some(4), None);+ assert!(model.instruction_breakpoints.is_empty());+}++#[test]+fn remove_instruction_breakpoints_by_address_leaves_the_others() {+ let mut model = DebugModel::default();+ model.add_instruction_breakpoint("refA", 0, 0x3000, &json!({}));+ model.add_instruction_breakpoint("refB", 0, 0x4000, &json!({}));+ model.remove_instruction_breakpoints(None, None, Some(0x3000));+ let remaining: Vec<u64> = model.instruction_breakpoints.iter().map(|breakpoint| breakpoint.address).collect();+ assert_eq!(remaining, [0x4000]);+}+#[test]fn multiple_sessions_verify_one_location() {let mut model = DebugModel::default();diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rsindex ecf64bc7736..f8cb9e8ccdc 100644--- a/native/crates/app/src/menus.rs+++ b/native/crates/app/src/menus.rs@@ -431,6 +431,8 @@ const WORKBENCH_MENUS: &[Row] = &[(MenuId::EditorContext, None, "editor.action.clipboardCutAction", "Cut", "9_cutcopypaste", 1., Some("!editorReadonly"), None),(MenuId::EditorContext, None, "editor.action.clipboardCopyAction", "Copy", "9_cutcopypaste", 2., None, None),(MenuId::EditorContext, None, "editor.action.clipboardPasteAction", "Paste", "9_cutcopypaste", 4., Some("!editorReadonly"), None),+ // debugEditorActions.ts `OpenDisassemblyViewAction`.+ (MenuId::EditorContext, None, "debug.action.openDisassemblyView", "Open Disassembly View", "debug", 5., Some("inDebugMode && !panelFocus && debugState == 'stopped' && editorTextFocus && disassembleRequestSupported && languageSupportsDisassembleRequest"), Some("focusedStackFrameHasInstructionReference")),(MenuId::EditorContext, None, "workbench.action.showCommands", "Command Palette...", "z_commands", 1., Some("!editorSimpleInput"), None),// output.contribution.ts and viewsService.ts `openCommandActionDescriptor.mnemonicTitle`(MenuId::EditorContext, None, "workbench.output.action.clearOutput", "Clear Output", "", 0., Some("inOutput"), None),diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex a6ad2774ff9..278ef83506d 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -35,6 +35,7 @@ mod debug_toolbar;pub(crate) mod debug_service;pub(crate) mod debug_task_runner;mod debug_view;+mod disassembly_view;mod testing_continuous;mod testing_item_menu;pub(crate) mod testing_service;@@ -411,6 +412,7 @@ pub struct Workbench {inlay_hints: inlay_hints::InlayHints,debug_inline_values: debug_inline_values::DebugInlineValues,debug_hover: debug_hover::DebugHover,+ disassembly_view: disassembly_view::DisassemblyView,color_detector: color_detector::ColorDetector,inline_completions: inline_completions::InlineCompletions,language_detection: language_detection::LanguageDetection,@@ -789,6 +791,7 @@ impl Workbench {inlay_hints: Default::default(),debug_inline_values: Default::default(),debug_hover: Default::default(),+ disassembly_view: Default::default(),color_detector: Default::default(),inline_completions: Default::default(),language_detection: Default::default(),diff --git a/native/crates/app/src/workbench/debug_commands.rs b/native/crates/app/src/workbench/debug_commands.rsindex 7f1704e3b86..e3a1dada361 100644--- a/native/crates/app/src/workbench/debug_commands.rs+++ b/native/crates/app/src/workbench/debug_commands.rs@@ -65,7 +65,7 @@ impl Workbench {workbench.remove_repl_expressions(&session_id);Outcome::Pending(workbench.restart_session(session_id, None, window, cx))});- for (id, command, granularity) in [+ for (id, command, step) in [("workbench.action.debug.continue", "continue", false),("workbench.action.debug.stepOver", "next", true),("workbench.action.debug.stepInto", "stepIn", true),@@ -73,7 +73,7 @@ impl Workbench {("workbench.action.debug.stepBack", "stepBack", true),("workbench.action.debug.reverseContinue", "reverseContinue", false),] {- self.commands.register(id, move |workbench, _, window, cx| workbench.run_thread_command(command, granularity, window, cx));+ self.commands.register(id, move |workbench, _, window, cx| workbench.run_thread_command(command, step, window, cx));}self.commands.register("workbench.action.debug.pause", |workbench, _, window, cx| {let (Some(session), thread) = (workbench.debug.focus.session.clone(), workbench.debug.focus.thread) else { return Outcome::done() };@@ -122,6 +122,7 @@ impl Workbench {let mut change = workbench.debug.model.remove_breakpoints(&ids);change.removed.extend(workbench.debug.model.remove_function_breakpoints(None).removed);change.removed.extend(workbench.debug.model.remove_data_breakpoints(None).removed);+ change.removed.extend(workbench.debug.model.remove_instruction_breakpoints(None, None, None).removed);workbench.breakpoints_changed(change, true, cx);Outcome::done()});@@ -174,6 +175,16 @@ impl Workbench {workbench.evaluate_in_repl(expression, window, cx);Outcome::done()});+ self.commands.register("debug.action.openDisassemblyView", |workbench, _, window, cx| {+ workbench.open_disassembly_view(window, cx);+ Outcome::done()+ });+ self.commands.register("debug.action.toggleDisassemblyViewSourceCode", |workbench, _, _, cx| {+ let shown = workbench.setting("debug.disassemblyView.showSourceCode") != json!(false);+ workbench.update_setting("debug.disassemblyView.showSourceCode", json!(!shown));+ cx.notify();+ Outcome::done()+ });self.commands.register("editor.debug.action.runToCursor", |workbench, _, window, cx| workbench.run_to_cursor(window, cx));self.commands.register("workbench.debug.action.toggleRepl", |workbench, _, window, cx| {match workbench.debug_console_visible() && workbench.debug_console.focus.is_focused(window) {@@ -222,15 +233,22 @@ impl Workbench {/// Continue and the step commands on the focused thread (debugSession.ts `next`, `stepIn`, `stepOut`):/// the thread runs again at once, before the adapter's `continued` event.- fn run_thread_command(&mut self, command: &str, granularity: bool, _window: &mut Window, cx: &mut Context<Self>) -> Outcome {+ fn run_thread_command(&mut self, command: &str, step: bool, _window: &mut Window, cx: &mut Context<Self>) -> Outcome {let (Some(session_id), Some(thread)) = (self.debug.focus.session.clone(), self.debug.focus.thread) else { return Outcome::done() };- self.thread_command(&session_id, thread, command, granularity, cx)+ self.thread_command(&session_id, thread, command, step, cx)}- fn thread_command(&mut self, session_id: &str, thread: i64, command: &str, granularity: bool, cx: &mut Context<Self>) -> Outcome {+ fn thread_command(&mut self, session_id: &str, thread: i64, command: &str, step: bool, cx: &mut Context<Self>) -> Outcome {let mut arguments = json!({ "threadId": thread });- if granularity && self.debug.session(session_id).is_some_and(|session| session.capabilities["supportsSteppingGranularity"] == true) {- arguments["granularity"] = json!("statement");+ // debugCommands.ts: a step from the disassembly view steps one instruction.+ let granularity = (step && self.disassembly_view_active()).then_some("instruction");+ if let Some(granularity) = granularity {+ arguments["granularity"] = json!(granularity);+ }+ if step+ && let Some(thread) = self.debug.session_mut(session_id).and_then(|session| session.threads.iter_mut().find(|candidate| candidate.id == thread))+ {+ thread.last_stepping_granularity = granularity;}let wait = self.debug.session(session_id).and_then(|session| session.wait_to_resume.clone());let reply = match wait {@@ -474,6 +492,11 @@ impl Workbench {context.insert("restartFrameSupported".into(), json!(focused.is_some_and(|session| session.capabilities["supportsRestartFrame"] == true)));let thread = focused.zip(self.debug.focus.thread).and_then(|(session, id)| session.thread(id));context.insert("threadHasMultipleStackFrames".into(), json!(thread.is_some_and(|thread| thread.frames.len() > 1 || thread.total_frames.is_some())));+ context.insert("disassembleRequestSupported".into(), json!(focused.is_some_and(|session| session.capabilities["supportsDisassembleRequest"] == true)));+ context.insert("focusedStackFrameHasInstructionReference".into(), json!(self.debug.focused_frame().is_some_and(|frame| frame.instruction_pointer_reference.is_some())));+ context.insert("disassemblyViewFocus".into(), json!(self.disassembly_view_active()));+ let language = self.editors.active().filter(|editor| editor.document().scheme == "file").map(|editor| editor.document().language_id.clone());+ context.insert("languageSupportsDisassembleRequest".into(), json!(language.is_some_and(|language| self.debug.debuggers.iter().any(|debugger| debugger.interested_in_language(&language)))));let simple = state == State::Inactive && !self.workspace_folders().iter().any(|folder| !self.folder_launch(folder).configurations.is_empty());context.insert("debugUx".into(), json!(if simple { "simple" } else { "default" }));context.insert(format!("viewContainer.{VIEWLET_ID}.enabled"), json!(true));@@ -650,4 +673,34 @@ mod tests {cx.run_until_parked();assert!(did_trigger(&workbench, cx).is_empty(), "a restart clears the session's triggers");}++ #[gpui::test]+ fn a_step_in_the_disassembly_view_steps_one_instruction(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 (sender, host) = std::sync::mpsc::channel();+ 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(sender), cx));+ workbench.update_in(cx, |workbench, _, _| {+ let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));+ session.initialized = true;+ session.capabilities = json!({ "supportsDisassembleRequest": true, "supportsSteppingGranularity": true });+ session.set_threads(&[json!({ "id": 1, "name": "main" })]);+ session.stop_threads(&json!({ "reason": "step", "threadId": 1 }));+ workbench.debug.sessions.push(session);+ workbench.debug.focus.session = Some("s".into());+ workbench.debug.focus.thread = Some(1);+ });+ let step = |cx: &mut gpui::VisualTestContext| {+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.run_thread_command("next", true, window, cx)));+ cx.run_until_parked();+ host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).find(|request| request["command"] == "next").unwrap()["arguments"]["granularity"].clone()+ };+ assert_eq!(step(cx), Value::Null, "a step in a text editor leaves the granularity to the adapter");+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.debug.sessions[0].stop_threads(&json!({ "reason": "step", "threadId": 1 }));+ workbench.open_disassembly_view(window, cx);+ });+ assert_eq!(step(cx), json!("instruction"));+ }}diff --git a/native/crates/app/src/workbench/debug_console.rs b/native/crates/app/src/workbench/debug_console.rsindex 9b695d4a0fe..ebd21e7bd7d 100644--- a/native/crates/app/src/workbench/debug_console.rs+++ b/native/crates/app/src/workbench/debug_console.rs@@ -323,7 +323,7 @@ impl Workbench {let child = children.iter().find(|session| session.state(None) == crate::debug::session::State::Stopped).or(children.first());let target = child.map_or(session_id.to_owned(), |session| session.id.clone());let focus = self.debug.focus_target(Some(&target), None);- self.set_debug_focus(focus, false, window, cx);+ self.set_debug_focus(focus, super::debug_service::Reveal::No, window, cx);}/// repl.ts `clearRepl`: empties the shown console; a cleared inactive session leaves the picker.diff --git a/native/crates/app/src/workbench/debug_hover/tests.rs b/native/crates/app/src/workbench/debug_hover/tests.rsindex d4f3e96346f..a3b3ff90b97 100644--- a/native/crates/app/src/workbench/debug_hover/tests.rs+++ b/native/crates/app/src/workbench/debug_hover/tests.rs@@ -64,7 +64,7 @@ fn workbench<'a>(cx: &'a mut TestAppContext, file: &Path, capabilities: Value) -let frame = StackFrame { id: 9, name: "f".into(), source: json!({ "path": file.to_string_lossy() }), line: 2, column: 3, end_line: 2, end_column: 3, ..Default::default() };session.thread_mut(1).unwrap().frames = vec![frame];workbench.debug.sessions.push(session);- workbench.set_debug_focus(DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) }, false, window, cx);+ workbench.set_debug_focus(DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) }, crate::workbench::debug_service::Reveal::No, window, cx);workbench});cx.run_until_parked();diff --git a/native/crates/app/src/workbench/debug_inline_values/tests.rs b/native/crates/app/src/workbench/debug_inline_values/tests.rsindex 054e2bf7418..d6134d4e2d4 100644--- a/native/crates/app/src/workbench/debug_inline_values/tests.rs+++ b/native/crates/app/src/workbench/debug_inline_values/tests.rs@@ -9,7 +9,7 @@ use serde_json::{Value, json};use super::*;use crate::host_sync::{HostMessage, HostSync};use crate::languages::Languages;-use crate::workbench::debug_service::DebugFocus;+use crate::workbench::debug_service::{DebugFocus, Reveal};#[test]fn hover_content_puts_each_pair_on_its_line_indented_past_its_equals() {@@ -92,7 +92,7 @@ fn the_focused_frame_shows_its_variables_after_the_lines_naming_them(cx: &mut Telet (workbench, host, cx) = workbench(cx, &file);workbench.update(cx, |workbench, _| drop(workbench.settings.lock().unwrap().update_value("debug.inlineValues", Some(&json!("on")), config::service::Target::User, None, &[]).unwrap()));let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };- workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, false, window, cx));+ workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, Reveal::No, window, cx));cx.run_until_parked();respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4, "expensive": false }] }))], cx);let variables = json!({ "variables": [{ "name": "a", "value": "1", "variablesReference": 0 }, { "name": "b", "value": "2", "variablesReference": 0 }] });@@ -124,12 +124,12 @@ fn auto_shows_the_providers_values_in_column_order(cx: &mut TestAppContext) {std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();let (workbench, host, cx) = workbench(cx, &file);let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };- workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus.clone(), false, window, cx));+ workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus.clone(), Reveal::No, window, cx));cx.run_until_parked();assert!(host.try_iter().all(|message| message.method != "$provideInlineValues"), "auto without a provider shows nothing");workbench.update_in(cx, |workbench, window, cx| {workbench.language_features.register(REGISTER, vec![json!(3), json!("*")]);- workbench.set_debug_focus(focus, false, window, cx);+ workbench.set_debug_focus(focus, Reveal::No, window, cx);});cx.run_until_parked();let range = |line: u64, start: u64, end: u64| json!({ "startLineNumber": line, "startColumn": start, "endLineNumber": line, "endColumn": end });diff --git a/native/crates/app/src/workbench/debug_service.rs b/native/crates/app/src/workbench/debug_service.rsindex 2768ea272d6..9803628b4b6 100644--- a/native/crates/app/src/workbench/debug_service.rs+++ b/native/crates/app/src/workbench/debug_service.rs@@ -37,6 +37,14 @@ pub struct ConfigurationProvider {pub has_resolve2: bool,}+/// Whether a focus change opens the frame, and with `focusStackFrame`'s `preserveFocus` or without it.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Reveal {+ No,+ PreservingFocus,+ TakingFocus,+}+/// The focus of debugViewModel.ts: a session, a thread of it and a frame of that thread.#[derive(Clone, Debug, Default, PartialEq)]pub struct DebugFocus {@@ -583,6 +591,9 @@ impl Workbench {let ids = enabled.iter().map(|breakpoint| breakpoint.base.id.clone()).collect();replies.push(self.send_breakpoint_request(session_id, "setDataBreakpoints", json!({ "breakpoints": breakpoints }), ids, cx));}+ if let Some(reply) = self.send_instruction_breakpoints(session_id, cx) {+ replies.push(reply);+ }// debugSession.ts `sendExceptionBreakpoints`: only once the adapter has filters.let session_filters: Vec<&crate::debug::ExceptionBreakpoint> = self.debug.model.exception_breakpoints_for(Some(session_id)).collect();if !session_filters.is_empty() {@@ -602,6 +613,29 @@ impl Workbench {replies}+ /// debugService.ts `sendInstructionBreakpoints` to one session: none unless the adapter supports them.+ pub(crate) fn send_instruction_breakpoints(&mut self, session_id: &str, cx: &mut Context<Self>) -> Option<Reply> {+ let session = self.debug.session(session_id)?;+ if session.capabilities["supportsInstructionBreakpoints"] != true || session.no_debug() || !session.initialized {+ return None;+ }+ let activated = self.debug.model.breakpoints_activated;+ let enabled: Vec<&crate::debug::InstructionBreakpoint> = self.debug.model.instruction_breakpoints.iter().filter(|breakpoint| breakpoint.base.enabled && activated).collect();+ let breakpoints: Vec<Value> = enabled.iter().map(|breakpoint| breakpoint.to_dap()).collect();+ let ids = enabled.iter().map(|breakpoint| breakpoint.base.id.clone()).collect();+ Some(self.send_breakpoint_request(session_id, "setInstructionBreakpoints", json!({ "breakpoints": breakpoints }), ids, cx))+ }++ /// debugService.ts `addInstructionBreakpoint` and `removeInstructionBreakpoints` after the model: every+ /// session gets the instruction breakpoints again.+ pub(crate) fn instruction_breakpoints_changed(&mut self, change: BreakpointsChange, cx: &mut Context<Self>) {+ self.breakpoints_changed(change, false, cx);+ let ids: Vec<String> = self.debug.sessions.iter().map(|session| session.id.clone()).collect();+ for id in ids {+ self.send_instruction_breakpoints(&id, cx);+ }+ }+/// debugSession.ts `sendBreakpoints`: the file's enabled breakpoints; the answer verifies them by position.pub(crate) fn send_breakpoints(&mut self, session_id: &str, uri: &str, source_modified: bool, cx: &mut Context<Self>) -> Reply {let activated = self.debug.model.breakpoints_activated;@@ -825,6 +859,7 @@ impl Workbench {end_column: frame["endColumn"].as_u64().map_or(column, |end| end as u32),presentation_hint: frame["presentationHint"].as_str().map(str::to_owned),can_restart: frame["canRestart"] == true,+ instruction_pointer_reference: frame["instructionPointerReference"].as_str().map(str::to_owned),}).collect();thread.total_frames = body["totalFrames"].as_u64().filter(|total| *total as usize > thread.frames.len());@@ -837,7 +872,9 @@ impl Workbench {let focused_is_running = self.debug.focused_session().is_none_or(|session| session.state(self.debug.focus.thread) != State::Stopped);if focused.is_none() || focused == Some(session_id) || focused_is_running {let target = self.debug.focus_target(Some(session_id), Some(thread_id));- self.set_debug_focus(target, true, window, cx);+ // debugSession.ts: `preserveFocus` is `!debug.focusEditorOnBreak`.+ let reveal = if self.setting("debug.focusEditorOnBreak") == json!(false) { Reveal::PreservingFocus } else { Reveal::TakingFocus };+ self.set_debug_focus(target, reveal, window, cx);}if self.setting("debug.openDebug") == "openOnDebugBreak" {self.show_debug_view(cx);@@ -863,7 +900,7 @@ impl Workbench {/// debugService.ts `focusStackFrame`: the view model's focus, the frame's file opened at its line, the/// variables and watches of the frame, and `$acceptStackFrameFocus` for the host.- pub(crate) fn set_debug_focus(&mut self, focus: DebugFocus, reveal: bool, window: &mut Window, cx: &mut Context<Self>) {+ pub(crate) fn set_debug_focus(&mut self, focus: DebugFocus, reveal: Reveal, window: &mut Window, cx: &mut Context<Self>) {let session_changed = focus.session != self.debug.focus.session;self.debug.focus = focus;if session_changed {@@ -875,8 +912,9 @@ impl Workbench {self.send_stack_frame_focus();self.debug.scopes.clear();self.debug.children.clear();- if reveal && let Some(frame) = self.debug.focused_frame().cloned() {- self.reveal_stack_frame(&frame, window, cx);+ self.disassembly_focus_changed(cx);+ if reveal != Reveal::No && let Some(frame) = self.debug.focused_frame().cloned() {+ self.reveal_stack_frame(&frame, reveal == Reveal::PreservingFocus, window, cx);}self.toggle_exception_widget(cx);self.update_debug_inline_values(cx);@@ -893,8 +931,18 @@ impl Workbench {self.host.send("ExtHostDebugService", "$acceptStackFrameFocus", vec![value]);}- /// `StackFrame.openInEditor`: the file at the frame's line, revealed in the center if outside the view.- fn reveal_stack_frame(&mut self, frame: &StackFrame, window: &mut Window, cx: &mut Context<Self>) {+ /// `StackFrame.openInEditor`: the file at the frame's line, revealed in the center if outside the view; the+ /// Disassembly view instead when it is active, or after an instruction breakpoint or instruction step.+ fn reveal_stack_frame(&mut self, frame: &StackFrame, preserve_focus: bool, window: &mut Window, cx: &mut Context<Self>) {+ if frame.instruction_pointer_reference.is_some() {+ let thread = self.debug.focused_session().zip(self.debug.focus.thread).and_then(|(session, id)| session.thread(id));+ let reason = thread.map(|thread| thread.stopped_details["reason"].clone()).unwrap_or_default();+ let stepped_instruction = reason == "step" && thread.is_some_and(|thread| thread.last_stepping_granularity == Some("instruction"));+ if self.disassembly_view_active() || (!preserve_focus && (reason == "instruction breakpoint" || stepped_instruction)) {+ self.open_disassembly_view(window, cx);+ return;+ }+ }let Some(path) = frame.path() else { return };let path = PathBuf::from(path);if !path.is_file() {@@ -1272,7 +1320,7 @@ fn set_one_session_data(model: &mut DebugModel, session_id: &str, capabilities:return;}let model_bases = model.function_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base).chain(model.data_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base));- let mut bases = model_bases.chain(model.exception_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base));+ let mut bases = model_bases.chain(model.exception_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base)).chain(model.instruction_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base));if let Some(base) = bases.find(|base| base.id == id) {base.set_session_data(session_id, Some(data));}@@ -1536,6 +1584,10 @@ async fn finish_session(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContexlet id = crate::debug::generate_uuid();workbench.debug.next_handle += 1;let session = Session::new(id.clone(), workbench.debug.next_handle, config.clone(), unresolved, folder_uri.clone(), options.clone());+ // disassemblyView.ts `onDidChangeState`: a debug run that starts clears the view.+ if workbench.debug.state() == State::Inactive {+ workbench.clear_disassembly();+ }workbench.debug.add_session(session);// debug.openDebug: the view opens on the first session start, not for Run Without Debugging.let open_debug = workbench.setting("debug.openDebug");@@ -1560,7 +1612,7 @@ async fn finish_session(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContexworkbench.host.send("ExtHostDebugService", "$acceptDebugSessionStarted", vec![dto]);if workbench.debug.focus.session.is_none() {let focus = workbench.debug.focus_target(Some(&session_id), None);- workbench.set_debug_focus(focus, false, window, cx);+ workbench.set_debug_focus(focus, Reveal::No, window, cx);}cx.notify();})?;@@ -1672,7 +1724,7 @@ async fn restart_flow(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext,}if should_focus || workbench.debug.focus.session.is_none() {let focus = workbench.debug.focus_target(Some(session_id), None);- workbench.set_debug_focus(focus, false, window, cx);+ workbench.set_debug_focus(focus, Reveal::No, window, cx);}cx.notify();})diff --git a/native/crates/app/src/workbench/debug_view.rs b/native/crates/app/src/workbench/debug_view.rsindex 42bc9ad199f..e7bc156bda8 100644--- a/native/crates/app/src/workbench/debug_view.rs+++ b/native/crates/app/src/workbench/debug_view.rs@@ -553,7 +553,7 @@ impl Workbench {.child(div().flex_none().mr(px(8.)).text_size(px(11.)).text_color(description).child(file)).on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {let focus = super::debug_service::DebugFocus { session: Some(session_id.clone()), thread: Some(thread_id), frame: Some(frame_id) };- workbench.set_debug_focus(focus, true, window, cx);+ workbench.set_debug_focus(focus, super::debug_service::Reveal::PreservingFocus, window, cx);}));rows.push(row.into_any_element());}@@ -627,6 +627,24 @@ impl Workbench {.into_any_element(),);}+ // breakpointsView.ts `renderInstructionBreakpoint`: the address, the regular icon unless disabled or unsupported.+ for breakpoint in &model.instruction_breakpoints {+ let id = breakpoint.base.id.clone();+ let icon = if !breakpoint.base.enabled || !model.breakpoints_activated {+ "debug-breakpoint-disabled"+ } else if !breakpoint.supported() {+ "debug-breakpoint-unverified"+ } else {+ "debug-breakpoint"+ };+ rows.push(+ self.debug_row(format!("instruction/{id}"), 0, None)+ .child(self.breakpoint_icon(icon, 16.))+ .child(self.debug_checkbox(&id, breakpoint.base.enabled, cx))+ .child(div().child(format!("0x{:x}", breakpoint.address)))+ .into_any_element(),+ );+ }rows}diff --git a/native/crates/app/src/workbench/disassembly_view.rs b/native/crates/app/src/workbench/disassembly_view.rsnew file mode 100644index 00000000000..3880978d603--- /dev/null+++ b/native/crates/app/src/workbench/disassembly_view.rs@@ -0,0 +1,451 @@+//! disassemblyView.ts: the Disassembly editor. One instance (`DisassemblyViewInput.instance`) lists the+//! instructions around the focused frame's instruction pointer, loads more as it scrolls, and sets and removes+//! instruction breakpoints from its breakpoint column.++use std::collections::HashMap;+use std::path::{Path, PathBuf};++use gpui::{AnyElement, ClickEvent, Context, Div, ListAlignment, ListOffset, ListState, Task, Window, div, list, prelude::*, px};+use serde_json::{Value, json};++use super::debug_service::answer;+use super::Workbench;+use crate::debug::disassembly::{Disassembly, INSTRUCTIONS_TO_LOAD};+use crate::editor::TextDocument;++pub const DISASSEMBLY_SCHEME: &str = "disassembly";+const DISASSEMBLY_PATH: &str = "Disassembly";+/// `InstructionRenderer.INSTRUCTION_ADDR_MIN_LENGTH` and `INSTRUCTION_BYTES_MIN_LENGTH`.+const ADDRESS_MIN_LENGTH: usize = 25;+const BYTES_MIN_LENGTH: usize = 30;++pub struct DisassemblyView {+ pub model: Disassembly,+ list: ListState,+ /// `_loadingLock`: no scroll loads while a load runs.+ loading: bool,+ /// The first visible row at the last scroll, to tell scrolling up from down.+ last_top: usize,+ hovered_glyph: Option<u64>,+ /// The lines of the source files the rows show, read when their instructions load.+ sources: HashMap<PathBuf, Vec<String>>,+}++impl Default for DisassemblyView {+ fn default() -> Self {+ Self { model: Disassembly::default(), list: ListState::new(0, ListAlignment::Top, px(200.)), loading: false, last_top: 0, hovered_glyph: None, sources: HashMap::new() }+ }+}++impl Workbench {+ /// `CONTEXT_DISASSEMBLY_VIEW_FOCUS`: the active editor is the Disassembly view.+ pub(super) fn disassembly_view_active(&self) -> bool {+ self.editors.active().is_some_and(|editor| editor.document().is(DISASSEMBLY_SCHEME, Path::new(DISASSEMBLY_PATH)))+ }++ fn disassembly_view_open(&self) -> bool {+ self.editors.editors.iter().any(|editor| editor.document().is(DISASSEMBLY_SCHEME, Path::new(DISASSEMBLY_PATH)))+ }++ /// `debug.action.openDisassemblyView`: the one Disassembly editor, pinned; a new one loads around the focused+ /// frame's instruction (`createEditor`).+ pub(super) fn open_disassembly_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ let path = PathBuf::from(DISASSEMBLY_PATH);+ self.leave_locked_group(DISASSEMBLY_SCHEME, &path);+ if let Some(index) = self.editors.editors.iter().position(|editor| editor.document().is(DISASSEMBLY_SCHEME, &path)) {+ self.editors.activate(index);+ } else {+ let document = TextDocument::from_text(DISASSEMBLY_SCHEME, &path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());+ self.editors.open(document, false);+ let workbench = cx.entity().downgrade();+ self.disassembly_view.list.set_scroll_handler(move |event, _, cx| {+ let _ = workbench.update(cx, |workbench, cx| workbench.disassembly_scrolled(event.visible_range.clone(), cx));+ });+ if let Some(reference) = self.focused_instruction_reference() {+ self.reload_disassembly(reference, 0, cx);+ }+ }+ self.editors_changed(cx);+ window.refresh();+ cx.notify();+ }++ fn focused_instruction_reference(&self) -> Option<String> {+ self.debug.focused_frame()?.instruction_pointer_reference.clone()+ }++ /// `onDidFocusStackFrame`: an open view goes to the new frame's instruction.+ pub(super) fn disassembly_focus_changed(&mut self, cx: &mut Context<Self>) {+ if !self.disassembly_view_open() {+ return;+ }+ if let Some(reference) = self.focused_instruction_reference() {+ self.go_to_instruction(reference, 0, cx);+ }+ }++ /// `onDidChangeState`: a new debug run starts with an empty view.+ pub(super) fn clear_disassembly(&mut self) {+ self.disassembly_view.model.clear();+ self.disassembly_view.list.reset(0);+ }++ /// `goToInstructionAndOffset`: an unknown reference loads the instructions around it first.+ fn go_to_instruction(&mut self, reference: String, offset: i64, cx: &mut Context<Self>) {+ if self.disassembly_view.model.reference_address(&reference).is_some() {+ self.reveal_instruction(&reference, offset);+ return;+ }+ let load = self.load_instructions(reference.clone(), 0, -INSTRUCTIONS_TO_LOAD, INSTRUCTIONS_TO_LOAD * 2, cx);+ cx.spawn(async move |workbench, cx| {+ load.await;+ let _ = workbench.update(cx, |workbench, cx| {+ workbench.reveal_instruction(&reference, offset);+ cx.notify();+ });+ })+ .detach();+ }++ /// `goToAddress`: the instruction's row comes into view.+ fn reveal_instruction(&self, reference: &str, offset: i64) {+ let view = &self.disassembly_view;+ let Some(address) = view.model.reference_address(reference).map(|base| base.wrapping_add_signed(offset)) else { return };+ if let Some(index) = view.model.index_of_address(address) {+ view.list.scroll_to_reveal_item(index);+ }+ }++ /// `reloadDisassembly`: the view empties and loads 400 instructions around the reference, centered on it.+ fn reload_disassembly(&mut self, reference: String, offset: i64, cx: &mut Context<Self>) {+ self.disassembly_view.loading = true;+ self.clear_disassembly();+ let load = self.load_instructions(reference.clone(), offset, -INSTRUCTIONS_TO_LOAD * 4, INSTRUCTIONS_TO_LOAD * 8, cx);+ cx.spawn(async move |workbench, cx| {+ load.await;+ let _ = workbench.update(cx, |workbench, cx| {+ let line_height = workbench.disassembly_line_height();+ let view = &mut workbench.disassembly_view;+ view.loading = false;+ let count = view.model.entries.len();+ if count == 0 {+ return;+ }+ let target = match view.model.reference_address(&reference) {+ Some(address) => view.model.entries.partition_point(|entry| entry.address < address),+ None => count / 2,+ };+ // `reveal(targetIndex, 0.5)`: the row in the middle of the view.+ let rows = (view.list.viewport_bounds().size.height / px(line_height)) as usize;+ view.list.scroll_to(ListOffset { item_ix: target.saturating_sub(rows / 2), offset_in_item: px(0.) });+ cx.notify();+ });+ })+ .detach();+ }++ /// `loadDisassembledInstructions`: the `disassemble` request, the reference's base address loaded first when+ /// the answer cannot give it, and the answer merged into the rows; the count of rows added.+ fn load_instructions(&mut self, reference: String, offset: i64, instruction_offset: i64, count: i64, cx: &mut Context<Self>) -> Task<i64> {+ let Some(session_id) = self.debug.focus.session.clone() else { return Task::ready(0) };+ let arguments = json!({ "memoryReference": reference, "offset": offset, "instructionOffset": instruction_offset, "instructionCount": count, "resolveSymbols": true });+ let reply = self.dap_request(&session_id, "disassemble", arguments);+ cx.spawn(async move |workbench, cx| {+ let instructions = answer(reply).await.ok().and_then(|body| body["instructions"].as_array().cloned());+ let needs_base = instruction_offset != 0 && workbench.read_with(cx, |workbench, _| workbench.disassembly_view.model.reference_address(&reference).is_none()).unwrap_or(false);+ if needs_base && let Ok(load) = workbench.update(cx, |workbench, cx| workbench.load_instructions(reference.clone(), 0, 0, INSTRUCTIONS_TO_LOAD, cx)) {+ load.await;+ }+ let Some(instructions) = instructions else { return 0 };+ let sources = cx.background_executor().spawn(read_sources(instructions.clone())).await;+ workbench+ .update(cx, |workbench, cx| {+ let view = &mut workbench.disassembly_view;+ view.sources.extend(sources);+ let (replaced, inserted) = view.model.merge(&reference, offset, instruction_offset, &instructions);+ view.list.splice(replaced.clone(), inserted);+ cx.notify();+ inserted as i64 - replaced.len() as i64+ })+ .unwrap_or(0)+ })+ }++ /// The `onDidScroll` loads: within a page of the top or the bottom, 50 more instructions that way.+ fn disassembly_scrolled(&mut self, visible: std::ops::Range<usize>, cx: &mut Context<Self>) {+ let view = &mut self.disassembly_view;+ let moved_up = visible.start < view.last_top;+ let moved_down = visible.start > view.last_top;+ view.last_top = visible.start;+ let page = visible.len();+ let count = view.model.entries.len();+ if view.loading || count == 0 {+ return;+ }+ let load = if moved_up && visible.start < page {+ let first = &view.model.entries[0];+ (first.instruction_reference.clone(), first.reference_offset, first.instruction_offset - INSTRUCTIONS_TO_LOAD)+ } else if moved_down && visible.end + page > count {+ let last = &view.model.entries[count - 1];+ (last.instruction_reference.clone(), last.reference_offset, last.instruction_offset + 1)+ } else {+ return;+ };+ view.loading = true;+ let (reference, offset, instruction_offset) = load;+ let load = self.load_instructions(reference, offset, instruction_offset, INSTRUCTIONS_TO_LOAD, cx);+ cx.spawn(async move |workbench, cx| {+ load.await;+ let _ = workbench.update(cx, |workbench, _| workbench.disassembly_view.loading = false);+ })+ .detach();+ }++ fn disassembly_line_height(&self) -> f32 {+ crate::editor::LINE_HEIGHT * self.editor_zoom.multiplier()+ }++ /// The instruction breakpoint at an address, its reference's base address known (`_instructionBpList`).+ fn instruction_breakpoint_at(&self, address: u64) -> Option<&crate::debug::InstructionBreakpoint> {+ let model = &self.disassembly_view.model;+ self.debug.model.instruction_breakpoints.iter().find(|breakpoint| model.reference_address(&breakpoint.instruction_reference).map(|base| base.wrapping_add_signed(breakpoint.offset)) == Some(address))+ }++ /// The top frames' and the focused frame's instruction addresses (`currentInstructionAddresses`,+ /// `focusedCurrentInstructionAddress`, `focusedInstructionAddress`).+ fn instruction_pointer_addresses(&self) -> (Vec<u64>, Option<u64>, Option<u64>) {+ let model = &self.disassembly_view.model;+ let address = |frame: Option<&crate::debug::session::StackFrame>| frame.and_then(|frame| frame.instruction_pointer_reference.as_deref()).and_then(|reference| model.reference_address(reference));+ let tops = self.debug.sessions.iter().flat_map(|session| &session.threads).filter_map(|thread| address(thread.frames.first())).collect();+ let focused_thread = self.debug.focused_session().zip(self.debug.focus.thread).and_then(|(session, id)| session.thread(id));+ (tops, address(focused_thread.and_then(|thread| thread.frames.first())), address(self.debug.focused_frame()))+ }++ /// The editor body: the breakpoint column and the instruction column of each row, or "Disassembly not+ /// available." while no instruction is loaded.+ pub(super) fn disassembly_editor_body(&self, cx: &mut Context<Self>) -> Div {+ let line_height = self.disassembly_line_height();+ let body = div().flex_1().min_h_0().flex().flex_col().bg(self.color("editor.background")).text_color(self.color("foreground"));+ if self.disassembly_view.model.entries.is_empty() {+ let row = div().h(px(line_height)).flex().child(div().w(px(line_height)).flex_none()).child(self.disassembly_text("Disassembly not available."));+ return body.child(row);+ }+ let rows = list(self.disassembly_view.list.clone(), cx.processor(|workbench: &mut Workbench, index: usize, _, cx| workbench.disassembly_row(index, cx))).size_full();+ body.child(rows)+ }++ fn disassembly_text(&self, text: impl Into<gpui::SharedString>) -> Div {+ let zoom = self.editor_zoom.multiplier();+ div().font_family(super::editor_view::EDITOR_FONT).text_size(px(super::editor_view::EDITOR_FONT_SIZE * zoom)).line_height(px(self.disassembly_line_height())).whitespace_nowrap().child(text.into())+ }++ fn disassembly_row(&mut self, index: usize, cx: &mut Context<Self>) -> AnyElement {+ let line_height = self.disassembly_line_height();+ let entry = &self.disassembly_view.model.entries[index];+ let address = entry.address;+ let (tops, focused_top, focused) = self.instruction_pointer_addresses();+ let source = self.disassembly_source_lines(entry);+ let instruction = instruction_text(&entry.instruction);+ let background = if tops.contains(&address) {+ Some(self.color("editor.stackFrameHighlightBackground"))+ } else if focused == Some(address) {+ Some(self.color("editor.focusedStackFrameHighlightBackground"))+ } else {+ None+ };+ let location = entry.instruction.clone();+ let mut column = div().flex_1().min_w_0().overflow_hidden().flex().flex_col();+ if let Some(source) = source {+ column = column.child(+ div()+ .id(("disassembly-source", index))+ .children(source.into_iter().map(|line| self.disassembly_text(line)))+ .on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {+ if event.click_count() == 2 {+ workbench.open_disassembly_source(&location, window, cx);+ }+ })),+ );+ }+ column = column.child(self.disassembly_text(instruction).when_some(background, |text, background| text.bg(background)));+ let hover = self.color("list.hoverBackground");+ div()+ .id(("disassembly-row", index))+ .w_full()+ .flex()+ .hover(move |row| row.bg(hover))+ .child(self.disassembly_glyph(index, address, focused_top, focused, line_height, cx))+ .child(column)+ .into_any_element()+ }++ /// `BreakpointRenderer`: the frame arrow, the breakpoint, or under the pointer the hint; a click removes the+ /// breakpoint by its address (#289678) or adds one.+ fn disassembly_glyph(&self, index: usize, address: u64, focused_top: Option<u64>, focused: Option<u64>, line_height: f32, cx: &mut Context<Self>) -> impl IntoElement {+ let breakpoint = self.instruction_breakpoint_at(address).map(|breakpoint| breakpoint.base.enabled);+ let mut icons = Vec::new();+ match breakpoint {+ Some(true) => icons.push(self.breakpoint_icon("debug-breakpoint", 16.)),+ Some(false) => icons.push(self.breakpoint_icon("debug-breakpoint-disabled", 16.)),+ None if self.disassembly_view.hovered_glyph == Some(address) => icons.push(self.breakpoint_icon("debug-hint", 16.).opacity(0.4)),+ None => {}+ }+ if focused_top == Some(address) {+ icons.push(self.breakpoint_icon("debug-stackframe", 16.));+ } else if focused == Some(address) {+ icons.push(self.breakpoint_icon("debug-stackframe-focused", 16.));+ }+ let column = div().w(px(line_height)).flex_none().flex().flex_col().justify_end();+ column.child(+ div()+ .id(("disassembly-glyph", index))+ .relative()+ .h(px(line_height))+ .cursor_pointer()+ .children(icons.into_iter().map(|icon| div().absolute().inset_0().flex().items_center().justify_center().child(icon)))+ .on_hover(cx.listener(move |workbench, hovered: &bool, _, cx| {+ workbench.disassembly_view.hovered_glyph = hovered.then_some(address);+ cx.notify();+ }))+ .on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| workbench.toggle_instruction_breakpoint(address, cx))),+ )+ }++ fn toggle_instruction_breakpoint(&mut self, address: u64, cx: &mut Context<Self>) {+ let model = &self.disassembly_view.model;+ let Some(entry) = model.index_of_address(address).map(|index| &model.entries[index]) else { return };+ let (reference, offset, address) = model.address_and_offset(entry);+ let change = match self.instruction_breakpoint_at(address) {+ Some(_) => self.debug.model.remove_instruction_breakpoints(Some(&reference), Some(offset), Some(address)),+ None => self.debug.model.add_instruction_breakpoint(&reference, offset, address, &json!({})),+ };+ self.instruction_breakpoints_changed(change, cx);+ }++ /// `renderElementInner`: " 12: text" for each line of the row's source range, when the row starts its line+ /// and `debug.disassemblyView.showSourceCode` is on.+ fn disassembly_source_lines(&self, entry: &crate::debug::disassembly::Entry) -> Option<Vec<String>> {+ let instruction = &entry.instruction;+ if !entry.show_source_location || self.setting("debug.disassemblyView.showSourceCode") == json!(false) {+ return None;+ }+ let path = source_path(instruction)?;+ let lines = self.disassembly_view.sources.get(&path)?;+ let first = instruction["line"].as_u64()? as usize;+ let last = instruction["endLine"].as_u64().map_or(first, |end| end as usize).max(first);+ let shown: Vec<String> = (first..=last).take_while(|line| *line >= 1 && *line <= lines.len()).map(|line| format!(" {line}: {}", lines[line - 1])).collect();+ Some(shown)+ }++ /// `openSourceCode`: a double click on the source lines opens the file at their range.+ fn open_disassembly_source(&mut self, instruction: &Value, window: &mut Window, cx: &mut Context<Self>) {+ let Some(path) = source_path(instruction) else { return };+ let Some(line) = instruction["line"].as_u64() else { return };+ let column = instruction["column"].as_u64().unwrap_or(1).max(1);+ let end_line = instruction["endLine"].as_u64().unwrap_or(line);+ let end_column = instruction["endColumn"].as_u64().unwrap_or(u32::MAX as u64);+ self.open_file(path.clone(), false, window, cx);+ let range = crate::anything_quick_access::TextRange { start_line_number: line as usize, start_column: column as usize, end_line_number: end_line as usize, end_column: end_column as usize };+ self.select_range(&path, range, cx);+ }+}++/// The address padded to 25 columns, the bytes to 30 (at least 10 spaces after each), then the instruction.+fn instruction_text(instruction: &Value) -> String {+ let mut text = String::new();+ let pad = |text: &mut String, value: &str, min: usize| {+ text.push_str(value);+ let spaces = if value.len() < min { min - value.len() } else { 10 };+ text.push_str(&" ".repeat(spaces));+ };+ if let Some(address) = instruction["address"].as_str().filter(|address| *address != "-1") {+ pad(&mut text, address, ADDRESS_MIN_LENGTH);+ }+ if let Some(bytes) = instruction["instructionBytes"].as_str().filter(|bytes| !bytes.is_empty()) {+ pad(&mut text, bytes, BYTES_MIN_LENGTH);+ }+ text.push_str(instruction["instruction"].as_str().unwrap_or_default());+ text+}++/// `getUriFromSource` for a file: an absolute path or a `file:` URI.+fn source_path(instruction: &Value) -> Option<PathBuf> {+ let path = instruction["location"]["path"].as_str()?;+ let path = PathBuf::from(path.strip_prefix("file://").unwrap_or(path));+ path.is_absolute().then_some(path)+}++/// The lines of each source file the instructions name.+async fn read_sources(instructions: Vec<Value>) -> HashMap<PathBuf, Vec<String>> {+ let mut sources = HashMap::new();+ for path in instructions.iter().filter_map(source_path) {+ if sources.contains_key(&path) {+ continue;+ }+ if let Ok(text) = std::fs::read_to_string(&path) {+ sources.insert(path, text.lines().map(str::to_owned).collect());+ }+ }+ sources+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_instruction_text_pads_the_address_and_the_bytes() {+ let instruction = json!({ "address": "0x1000", "instructionBytes": "55", "instruction": "push rbp" });+ assert_eq!(instruction_text(&instruction), format!("0x1000{}55{}push rbp", " ".repeat(19), " ".repeat(28)));+ let long = json!({ "address": "0x".to_owned() + &"f".repeat(24), "instruction": "ret" });+ assert_eq!(instruction_text(&long), format!("0x{}{}ret", "f".repeat(24), " ".repeat(10)));+ }++ #[gpui::test]+ fn the_view_loads_around_the_frame_and_a_glyph_click_sets_an_instruction_breakpoint(cx: &mut gpui::TestAppContext) {+ use crate::debug::session::{Session, StackFrame};+ use exthost::session::ForwardedRequest;++ 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 (sender, host) = std::sync::mpsc::channel();+ 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(sender), cx));+ workbench.update_in(cx, |workbench, window, cx| {+ let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "lldb", "request": "launch" }), json!({}), None, json!({}));+ session.initialized = true;+ session.capabilities = json!({ "supportsDisassembleRequest": true, "supportsInstructionBreakpoints": true });+ session.set_threads(&[json!({ "id": 1, "name": "main" })]);+ session.stop_threads(&json!({ "reason": "step", "threadId": 1 }));+ session.thread_mut(1).unwrap().frames = vec![StackFrame { id: 9, name: "f".into(), instruction_pointer_reference: Some("0x1000".into()), ..Default::default() }];+ workbench.debug.sessions.push(session);+ workbench.debug.focus.session = Some("s".into());+ workbench.debug.focus.thread = Some(1);+ workbench.debug.focus.frame = Some(9);+ workbench.open_disassembly_view(window, cx);+ });+ let requests = |host: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>| -> Vec<Value> { host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).collect() };+ let instruction = |address: &str| json!({ "address": address, "instruction": "nop" });+ for _ in 0..3 {+ cx.run_until_parked();+ for request in requests(&host).into_iter().filter(|request| request["command"] == "disassemble") {+ let instructions = match request["arguments"]["instructionOffset"].as_i64().unwrap() {+ 0 => vec![instruction("0x1000"), instruction("0x1004")],+ _ => vec![instruction("0xffc"), instruction("0x1000"), instruction("0x1004")],+ };+ let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": "disassemble", "body": { "instructions": instructions } });+ let accept = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), response] };+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept, window, cx)));+ }+ }+ let addresses = workbench.read_with(cx, |workbench, _| workbench.disassembly_view.model.entries.iter().map(|entry| entry.address).collect::<Vec<_>>());+ assert_eq!(addresses, vec![0xffc, 0x1000, 0x1004]);++ workbench.update(cx, |workbench, cx| workbench.toggle_instruction_breakpoint(0x1004, cx));+ cx.run_until_parked();+ let sent = requests(&host).into_iter().find(|request| request["command"] == "setInstructionBreakpoints").expect("the breakpoint is sent");+ assert_eq!((sent["arguments"]["breakpoints"][0]["instructionReference"].clone(), sent["arguments"]["breakpoints"][0]["offset"].clone()), (json!("0x1000"), json!(4)));+ workbench.update(cx, |workbench, cx| workbench.toggle_instruction_breakpoint(0x1004, cx));+ assert!(workbench.read_with(cx, |workbench, _| workbench.debug.model.instruction_breakpoints.is_empty()), "a second click removes it");+ }+}diff --git a/native/crates/app/src/workbench/editor_view.rs b/native/crates/app/src/workbench/editor_view.rsindex 7295fa8bf0b..0e787f1841b 100644--- a/native/crates/app/src/workbench/editor_view.rs+++ b/native/crates/app/src/workbench/editor_view.rs@@ -118,6 +118,7 @@ impl Workbench {super::modal_editor_group::PREFERENCES_EDITOR_SCHEME => part,super::extension_editor::EXTENSION_EDITOR_SCHEME => part.child(self.extension_editor_body(&editor.document().path, cx)),super::welcome_page::WALKTHROUGH_SCHEME => part.child(self.walkthrough_editor_body(&editor.document().path, window, cx)),+ super::disassembly_view::DISASSEMBLY_SCHEME => part.child(self.disassembly_editor_body(cx)),// searchEditor.ts draws its query widget where a text editor has its breadcrumbs.SEARCH_EDITOR_SCHEME if editor.document().open_error.is_some() => part,SEARCH_EDITOR_SCHEME => part.child(self.search_editor_query(window, cx)),@@ -130,7 +131,7 @@ impl Workbench {Some(diff) => part.child(self.diff_editor_body(diff, diff.modified_editor.as_ref().unwrap_or(editor), window, cx)),None if self.playground_active() => part,None if editor.document().scheme == super::modal_editor_group::PREFERENCES_EDITOR_SCHEME => part.children(preferences),- None if matches!(editor.document().scheme.as_str(), super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME) => part,+ None if matches!(editor.document().scheme.as_str(), super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME) => part,None if self.shows_webview(editor) => part.child(self.webview_editor_body(editor)),None if self.editors.active_tab().is_some_and(|tab| tab.document().scheme == crate::notebook::NOTEBOOK_EDITOR_SCHEME) => part.child(self.notebook_editor_body(window, cx)),None if self.editors.active_multi_diff().is_some() => part,@@ -154,7 +155,7 @@ impl Workbench {!self.playground_active()&& !(scheme == WEBVIEW_PANEL_SCHEME && self.webview_resource(&document.path).is_none())&& !self.active_notebook_resource().is_some_and(|(scheme, _)| scheme == "untitled")- && !matches!(scheme, super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | SEARCH_EDITOR_SCHEME | crate::output::OUTPUT_SCHEME | "untitled" | TERMINAL_EDITOR_SCHEME)+ && !matches!(scheme, super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME | SEARCH_EDITOR_SCHEME | crate::output::OUTPUT_SCHEME | "untitled" | TERMINAL_EDITOR_SCHEME)&& self.editors.active_multi_diff().is_none()&& self.editors.active_merge().is_none()}@@ -523,7 +524,7 @@ impl Workbench {// `getTitle(Verbosity.LONG)`: a search editor's and a webview's is its name.let title = match (self.editors.diffs.get(&editor.model_id), editor.document().scheme.as_str()) {(Some(diff), _) => diff.title(|side| crate::quick_input::path_label(crate::editor::split_query(&side.scheme, &side.path).0, None)),- (None, SEARCH_EDITOR_SCHEME | WEBVIEW_PANEL_SCHEME | super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | MULTI_DIFF_EDITOR_SCHEME | TERMINAL_EDITOR_SCHEME) => self.editor_name(editor),+ (None, SEARCH_EDITOR_SCHEME | WEBVIEW_PANEL_SCHEME | super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME | MULTI_DIFF_EDITOR_SCHEME | TERMINAL_EDITOR_SCHEME) => self.editor_name(editor),// labels.ts: an untitled label's title is its name and its path.(None, "untitled") if !editor.text_model().associated_file => match self.untitled_description(editor) {Some(path) => format!("{} \u{2022} {path}", self.editor_name(editor)),@@ -781,6 +782,10 @@ impl Workbench {let icon = self.app_root.join("src/vs/workbench/browser/media/code-icon.svg");return Some(div().flex().items_center().h(px(line_height)).child(gpui::img(icon).size(px(16.))));}+ // `DisassemblyViewInput.getIcon`.+ if document.scheme == super::disassembly_view::DISASSEMBLY_SCHEME {+ return self.predefined_file_icon("debug", line_height, foreground);+ }// `ExtensionsInput.getIcon`.if document.scheme == super::extension_editor::EXTENSION_EDITOR_SCHEME {return self.predefined_file_icon("extensions", line_height, foreground);@@ -2771,7 +2776,7 @@ impl Workbench {if let Some(crate::editor::OpenError::Binary(size)) = editor.document().open_error {items.push((super::media_preview::format_size(size), "", "", "status.editor.info"));}- } else if let Some(editor) = self.active_text_editor_control().filter(|editor| !self.shows_webview(editor) && !self.playground_active() && !matches!(editor.document().scheme.as_str(), super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | MULTI_DIFF_EDITOR_SCHEME | TERMINAL_EDITOR_SCHEME)) {+ } else if let Some(editor) = self.active_text_editor_control().filter(|editor| !self.shows_webview(editor) && !self.playground_active() && !matches!(editor.document().scheme.as_str(), super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME | MULTI_DIFF_EDITOR_SCHEME | TERMINAL_EDITOR_SCHEME)) {// WalkThroughPart has no `getControl`: its focused snippet gives the status bar no editor entries.let [selection, indentation, encoding, eol, language] = Self::editor_status_entries(editor, &self.languages);// `toEditorWithEncodingSupport` of a MultiDiffEditorInput is null: no encoding entry.diff --git a/native/crates/app/src/workbench/keyboard.rs b/native/crates/app/src/workbench/keyboard.rsindex 391c6443ad5..e979a82b390 100644--- a/native/crates/app/src/workbench/keyboard.rs+++ b/native/crates/app/src/workbench/keyboard.rs@@ -504,6 +504,7 @@ impl Workbench {let pane = match editor.document().scheme.as_str() {_ if self.playground_active() => "workbench.editor.walkThroughPart",super::welcome_page::WALKTHROUGH_SCHEME => "gettingStartedPage",+ super::disassembly_view::DISASSEMBLY_SCHEME => "workbench.debug.disassemblyView",_ if self.active_notebook_editor().is_some() => "workbench.editor.notebook",_ => "workbench.editor.files",};diff --git a/native/crates/app/src/workbench/quick_access/views.rs b/native/crates/app/src/workbench/quick_access/views.rsindex c3a693585e9..0f135f92098 100644--- a/native/crates/app/src/workbench/quick_access/views.rs+++ b/native/crates/app/src/workbench/quick_access/views.rs@@ -145,7 +145,7 @@ impl Workbench {ViewTarget::Command(id) => drop(self.execute_command(&id, Vec::new(), window, cx)),ViewTarget::DebugConsole(session) => {let focus = self.debug.focus_target(Some(&session), None);- self.set_debug_focus(focus, true, window, cx);+ self.set_debug_focus(focus, crate::workbench::debug_service::Reveal::PreservingFocus, window, cx);if !self.is_view_visible(REPL_VIEW_ID) {drop(self.execute_command(&format!("{REPL_VIEW_ID}.focus"), Vec::new(), window, cx));}diff --git a/native/crates/app/src/workbench/search_editor_view.rs b/native/crates/app/src/workbench/search_editor_view.rsindex 13cbc5efa89..fdade6ce542 100644--- a/native/crates/app/src/workbench/search_editor_view.rs+++ b/native/crates/app/src/workbench/search_editor_view.rs@@ -135,6 +135,7 @@ impl Workbench {}None if editor.document().scheme == super::extension_editor::EXTENSION_EDITOR_SCHEME => self.extension_editor_name(&editor.document().path),None if editor.document().scheme == super::welcome_page::WALKTHROUGH_SCHEME => self.walkthrough_editor_name(&editor.document().path),+ None if editor.document().scheme == super::disassembly_view::DISASSEMBLY_SCHEME => "Disassembly".into(),None if editor.document().scheme == super::terminal_editor::TERMINAL_EDITOR_SCHEME => self.terminal_editor_name(&editor.document().path),None if editor.document().scheme == super::modal_editor_group::PREFERENCES_EDITOR_SCHEME => match editor.document().path.to_str() {Some(super::modal_editor_group::SETTINGS_EDITOR_PATH) => "Settings".into(),diff --git a/port/ledger.md b/port/ledger.mdindex 8b9dfb3d8ec..ff3429e65ee 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -475,7 +475,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/contrib/commands | workbench contribution | M9 | verified | | runCommands (commands.rs register_run_commands): cargo test -p app commands::, argument checks, spread args, order, stop at a failure; argument errors and the failure notify (cargo test -p app run_commands_argument_errors_notify) || workbench/contrib/comments | workbench contribution | M13 | verified | | Done: a reply and an edit form per thread and comment, open together (commentReply.ts per CommentThreadWidget): cargo test -p app two_threads_keep_their_reply_forms_open_together; a zone sized by the drawn comment bodies: cargo test -p app a_wrapped_comment_body_grows_its_zone; next/previous thread and Focus Comment on Current Line focus the thread's comments (`commentFocused`, Up/Down between comments, Escape collapses and selects the range): cargo test -p app the_reached_thread_takes_the_focus. Done in diff editors: glyphs, commenting ranges (asked for every side of every multi diff file), range highlights and zones on both sides of the diff editor and of each multi diff file, the other side aligned by a diagonal fill (workbench/editor_view/diff_editor_view.rs, multi_diff_editor_view.rs, diff_editor.rs `additional_heights`): cargo test -p app diff comment; ui-pair `portComments.openDiff` modified, original and multi. Floating widgets on a diff's original side and on both sides of each multi diff file (comment_thread_floating.rs `FloatingHost`, multi_diff_editor_view.rs `multi_diff_floating_hosts`), with `FloatingWidgetRoom` growing a file below its last line (commentThreadFloatingWidgetRoom.ts, `FileDiff.room`): cargo test -p app floating room multi_diff; ui-pair `portComments.openDiff` original and multi with the floating style. Range decorations (commentThreadRangeDecorator.ts and the floating empty-range line, workbench/comment_thread_widget.rs `comment_range_highlights`): cargo test -p app comment_thread_floating. The floating thread style (`comments.thread.experimental.style: floating`; workbench/comment_thread_floating_layout.rs with commentThreadFloatingWidget.test.ts ported, workbench/comment_thread_floating.rs: placement beside the code or its lines in code order, the outline and connector, title drag, edge resize, double-click reset, the layout kept per thread, wheel to the editor): cargo test -p app comment_thread_floating, ui-pair steps-comment-floating.json (port/results/language-features.md Floating comment threads). Done: the Comments panel (workbench/comments_view.rs: resources, threads with author, relative time, first line, range and replies, the unresolved badge, a markdown preview's images as "Image: {alt}" (cargo test -p app a_markdown_comment_previews_its_first_rendered_block), the filter box with Show Resolved/Unresolved and Sort By, its history in the memento's `filterHistory`, Escape and Cmd+Down while `commentsFilterFocus` (cargo test -p app the_filter_keeps_its_history_and_escape_clears_it; no match highlights, as commentsTreeViewer.ts's renderers ignore the filter data), Collapse/Expand All, row selection and keys; hideIfEmpty; a thread row's `commentsView/commentThread/context` inline actions and context menu with the built-in Reply, which reveals the thread with its zone expanded and reply open: cargo test -p app the_thread_menu_replies_to_the_thread), the gutter glyph that toggles the thread (workbench/editor_view/comment_glyph.rs) and the thread widget (workbench/comment_thread_widget.rs: zone, state colors, head with `comments/commentThread/title` actions and Collapse, markdown comments with `code` spans on no `textCodeBlock.background` (cargo test -p app a_comment_s_code_span_draws_no_code_block_background), reply form with `comments/commentThread/context` buttons and Cmd+Enter), each comment (workbench/comment_node.rs: `comments/comment/title` actions, edit mode with `comments/comment/context` buttons, reactions and their picker), commenting ranges with the add glyph, Add Comment and template threads (workbench/commenting_ranges.rs), the comment commands (workbench/comment_navigation.rs: Collapse/Expand All, Expand Unresolved, Toggle Editor Commenting, Focus Comment on Current Line, Dismiss Comment, next/previous thread, commented range and commenting range, reached at the provider's columns unless it holds the cursor: cargo test -p app a_commenting_range_is_reached_at_its_columns_unless_it_holds_the_cursor) and the comments accessibility help: cargo test -p app comment; ui-pair port/results/language-features.md (Comments, Comment editing and commands); Escape keeps a new template open as the reference does (ui-pair steps-comment-escape-typed.json, cargo test -p app dismissing_a_new_template_keeps_it_open). The reply and edit inputs are code editors (simpleCommentEditor.ts: a `comment`-scheme markdown model, word wrap, no glyph margin, line numbers or folding, `scrollBeyondLastLine` false, 5 to 25 lines by `calculateEditorHeight`) that take the focus with `commentEditorFocused`, Cmd+Enter submits and Escape hides; the host gets the input's document and no text editor (workbench/comment_thread_widget.rs `open_comment_editor`, workbench/editor.rs `comment_editor`): cargo test -p app an_expanded_thread_shows_a_zone_and_replies_run_the_form_actions a_comment_switched_to_editing_runs_the_edit_actions; ui-pair steps-comment-reply-editor.json (reply-empty, reply-lines, reply-grown). Comments panel rows: 4px pane inset, 4px radius and the tree's indent guides as the Problems tree (cargo test -p app rows_sit_in_the_pane_s_inset_with_the_tree_s_indent_and_guides; ui-pair steps-comments.json: chevron, name and thread line at the reference's x and y) || workbench/contrib/customEditor | workbench contribution | M17 | verified | | Each editor of a custom text editor's resource, the one opened in another group and a split's copy, has a webview of its own (customEditorInput.ts: cargo test -p app each_group_s_custom_text_editor_has_its_own_webview); Opening a custom text editor with `options.selection` reveals it in the panel and leaves the text model's cursor (cargo test -p app a_custom_text_editor_s_navigation_drives_the_outline); A custom document open in another group moves to the active one, or with `supportsMultipleEditorsPerDocument` gets a second editor there (editorResolverService.ts `moveExistingEditorForResource`: cargo test -p app a_custom_document_open_in_another_group_moves_to_the_active_one a_custom_document_with_multiple_editors_opens_one_more_in_the_active_group); `workbench.editorAssociations` merged as editorResolverService.ts `getAllUserAssociationsForSetting`: the workspace's globs before the default's and user's (cargo test -p app a_workspace_association_wins_over_a_user_one_of_the_same_length); Reopen Editor With puts a closed custom or notebook editor's replacement in its place, pinned (editorGroupView.ts `replaceEditors`: cargo test -p app a_reopened_preview_keeps_its_tab_position); Two default editors for one resource warn once and remember the choice per extension glob (editorResolverService.ts `doHandleConflictingDefaults`: cargo test -p app two_default_editors_for_a_resource_ask_once_which_to_keep); the memento's custom editors until the extensions register (cargo test -p app markdown_editor_files_offer); editor resolution by `workbench.editorAssociations` and contributed selectors (editorResolverService.ts ranks), Reopen Editor With picker (`reopenActiveEditorWith`, `workbench.action.reopenWithEditor`), `_workbench.open`, `_workbench.openWith`; `FIXTURE=custom-editor-tests port/tools/webview-check` 8/8; cargo test -p app custom_editors |-| workbench/contrib/debug | workbench contribution | M16 | ported | [3 L] Disassembly view: not ported <br> [3 L] extensionHost launch type: not ported <br> [3 L] variable context menus: DebugVariablesContext, DebugWatchContext and DebugHoverContext (Copy Value, Copy as Expression, Add to Watch, Set Value, Break When Value Is Read/Changes/Is Accessed, View Binary Data) not ported <br> [3 L] debug visualizers: debugVisualizers.ts, `VisualizedExpression` rows in the Variables view and the hover not ported <br> [3 M] lazy variables: `presentationHint.lazy` rows and their reveal button (baseDebugView.ts `lazyButton`) not ported in the hover, Variables or Watch <br> [3 M] debug_hover.rs: Alt+click on an expandable hover row (abstractTree.ts `toggleCollapsed(location, recursive)`) expands one level, not the whole subtree <br> [3 M] debug_hover.rs: the hover tree has no find widget (abstractTree.ts `FindController`, `list.find`) | ui-pair port/fixtures/debug-node: gutter breakpoint, F5 stops at it, Variables (Local: main), Call Stack with folded deemphasized frames, Breakpoints, Debug Console REPL, toolbar, status bar entry; cargo test -p app debug; Breakpoints header `$(warning)` hint for the debugger's `strings.unverifiedBreakpoints` after breakpointsView.ts's 4s `hintDelayer`, restarted by every breakpoint change (cargo test -p app debug_view; ui-pair port/fixtures/ui-pair/debug/unverified-breakpoints.json with js-debug's unbound math.test.js breakpoint); preLaunchTask, postDebugTask, compound preLaunchTask and the restart tasks through debugTaskRunner.ts's runner with `debug.onTaskErrors`, the remembered task error choice and the slow task notification (cargo test -p app debug_task_runner); Run to Cursor's temporary breakpoint with debugService.ts `runTo`'s 2s verification wait, thread choice from the sessions that verified it, and removal at the next stop or session end (cargo test -p app debug_commands); Debug Console output styled by its SGR sequences with the theme's ANSI colors at contrast 4 (cargo test -p app debug_console debug::ansi); Debug Console filter box (replFilter.ts terms, "Showing N of M" badge, Cmd+F `repl.action.filter`, value and history in workspace storage) and session picker (consoles of the sessions with `hasSeparateRepl`, `mergeWithParent` children in the parent's, selection focuses the session or its stopped child), input history in workspace storage (`debug.repl.history`) (cargo test -p app debug_console); ended sessions stay inactive in the console picker with their output until Clear Console or a start of the same configuration (debugModel.ts `addSession`, repl.ts `sessionsToIgnore`; cargo test -p app an_ended_session_stays_in_the_picker_until_cleared_or_started_again); debugUtils.ts `saveAllBeforeDebugStart` before a start (not for a child session or with `suppressSaveBeforeStart`) and a restart, by `debug.saveBeforeStart` (cargo test -p app a_start_or_restart_saves_the_dirty_editors); triggered breakpoints: debugSession.ts `enableDependentBreakpoints` by `hitBreakpointIds` or the top frame's position sets `sessionsDidTrigger` and sends the files again, continue and the steps wait for it up to 1.5 s (`waitForTriggeredBreakpoints`), a restart clears it (cargo test -p app a_hit_breakpoint_enables_its_dependents); `debug.inlineValues` after the focused frame's lines: the `InlineValuesProvider`s' values (`$provideInlineValues`) or the most specific scopes' variables named on each line, their `formatHoverContent` hover, the 100ms removal on continue (cargo test -p app debug_inline_values); debugHover.ts in place of the editor hover while a frame is focused in the file: the `$provideEvaluatableExpression` range or the dotted path under the mouse, `hover` evaluation or the scopes' variable, Cmd+K Cmd+I focused, Alt for the editor hover, the tree's list keys and `layoutTree` height, the glyph margin's lockout release, the caret edge nearer the mouse (cargo test -p app debug_hover; ui-pair port/fixtures/debug-node `greeting` and `numbers` hovers); shortcuts in port/notes.md |+| workbench/contrib/debug | workbench contribution | M16 | ported | [3 M] disassembly_view.rs: the instruction table has no keyboard focus, selection or column sash (disassemblyView.ts WorkbenchTable) <br> [3 M] debug_view.rs: the Call Stack view has no context menu (DebugCallStackContext: the session and thread commands, Restart Frame, Copy Call Stack, Open Disassembly View) <br> [3 L] extensionHost launch type: not ported <br> [3 L] variable context menus: DebugVariablesContext, DebugWatchContext and DebugHoverContext (Copy Value, Copy as Expression, Add to Watch, Set Value, Break When Value Is Read/Changes/Is Accessed, View Binary Data) not ported <br> [3 L] debug visualizers: debugVisualizers.ts, `VisualizedExpression` rows in the Variables view and the hover not ported <br> [3 M] lazy variables: `presentationHint.lazy` rows and their reveal button (baseDebugView.ts `lazyButton`) not ported in the hover, Variables or Watch <br> [3 M] debug_hover.rs: Alt+click on an expandable hover row (abstractTree.ts `toggleCollapsed(location, recursive)`) expands one level, not the whole subtree <br> [3 M] debug_hover.rs: the hover tree has no find widget (abstractTree.ts `FindController`, `list.find`) | ui-pair port/fixtures/debug-node: gutter breakpoint, F5 stops at it, Variables (Local: main), Call Stack with folded deemphasized frames, Breakpoints, Debug Console REPL, toolbar, status bar entry; cargo test -p app debug; Breakpoints header `$(warning)` hint for the debugger's `strings.unverifiedBreakpoints` after breakpointsView.ts's 4s `hintDelayer`, restarted by every breakpoint change (cargo test -p app debug_view; ui-pair port/fixtures/ui-pair/debug/unverified-breakpoints.json with js-debug's unbound math.test.js breakpoint); preLaunchTask, postDebugTask, compound preLaunchTask and the restart tasks through debugTaskRunner.ts's runner with `debug.onTaskErrors`, the remembered task error choice and the slow task notification (cargo test -p app debug_task_runner); Run to Cursor's temporary breakpoint with debugService.ts `runTo`'s 2s verification wait, thread choice from the sessions that verified it, and removal at the next stop or session end (cargo test -p app debug_commands); Debug Console output styled by its SGR sequences with the theme's ANSI colors at contrast 4 (cargo test -p app debug_console debug::ansi); Debug Console filter box (replFilter.ts terms, "Showing N of M" badge, Cmd+F `repl.action.filter`, value and history in workspace storage) and session picker (consoles of the sessions with `hasSeparateRepl`, `mergeWithParent` children in the parent's, selection focuses the session or its stopped child), input history in workspace storage (`debug.repl.history`) (cargo test -p app debug_console); ended sessions stay inactive in the console picker with their output until Clear Console or a start of the same configuration (debugModel.ts `addSession`, repl.ts `sessionsToIgnore`; cargo test -p app an_ended_session_stays_in_the_picker_until_cleared_or_started_again); debugUtils.ts `saveAllBeforeDebugStart` before a start (not for a child session or with `suppressSaveBeforeStart`) and a restart, by `debug.saveBeforeStart` (cargo test -p app a_start_or_restart_saves_the_dirty_editors); triggered breakpoints: debugSession.ts `enableDependentBreakpoints` by `hitBreakpointIds` or the top frame's position sets `sessionsDidTrigger` and sends the files again, continue and the steps wait for it up to 1.5 s (`waitForTriggeredBreakpoints`), a restart clears it (cargo test -p app a_hit_breakpoint_enables_its_dependents); `debug.inlineValues` after the focused frame's lines: the `InlineValuesProvider`s' values (`$provideInlineValues`) or the most specific scopes' variables named on each line, their `formatHoverContent` hover, the 100ms removal on continue (cargo test -p app debug_inline_values); debugHover.ts in place of the editor hover while a frame is focused in the file: the `$provideEvaluatableExpression` range or the dotted path under the mouse, `hover` evaluation or the scopes' variable, Cmd+K Cmd+I focused, Alt for the editor hover, the tree's list keys and `layoutTree` height, the glyph margin's lockout release, the caret edge nearer the mouse (cargo test -p app debug_hover; ui-pair port/fixtures/debug-node `greeting` and `numbers` hovers); disassemblyView.ts: the `disassemble` requests around the focused frame's instruction pointer, the glyph click's instruction breakpoint (`setInstructionBreakpoints`), the Breakpoints view's instruction rows, `instruction` stepping granularity while the view is active (cargo test -p app disassembly a_step_in_the_disassembly_view debug::tests::instruction_breakpoints debug::tests::remove_instruction_breakpoints); shortcuts in port/notes.md || workbench/contrib/dropOrPasteInto | workbench contribution | M13 | verified | | commands.ts `configurePreferredPasteAction`/`configurePreferredDropAction`: the widgets' menus and the Paste As pick open user settings JSON at `editor.pasteAs.preferences` or `editor.dropIntoEditor.preferences` (workbench/paste_edits.rs); the `editor.pasteAs.*` and `editor.dropIntoEditor.*` settings come from core-settings.json; ui-pair paste-menu (port/results/language-features.md) || workbench/contrib/editSessions | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported || workbench/contrib/editTelemetry | workbench contribution | | removed | | no AI or Microsoft services by decision (port/notes.md); API stays inert |