Visual Studio Code, rebuilt in Rust
Rust
//! 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, App, ClickEvent, Context, Div, FocusHandle, ListAlignment, ListOffset, ListState, MouseButton, 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>>,
/// The table's focus and its focused and selected rows, by address (`identityProvider`) so loads keep them.
focus: FocusHandle,
focused: Option<u64>,
selected: Option<u64>,
hovered: bool,
}
impl DisassemblyView {
pub fn new(cx: &mut App) -> Self {
Self { model: Disassembly::default(), list: ListState::new(0, ListAlignment::Top, px(200.)), loading: false, last_top: 0, hovered_glyph: None, sources: HashMap::new(), focus: cx.focus_handle(), focused: None, selected: None, hovered: false }
}
}
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, window, 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) {
let view = &mut self.disassembly_view;
view.model.clear();
view.list.reset(0);
(view.focused, view.selected) = (None, None);
}
/// `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 and focused on it.
fn reload_disassembly(&mut self, reference: String, offset: i64, window: &mut Window, 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_in(window, async move |workbench, cx| {
load.await;
let _ = workbench.update_in(cx, |workbench, window, 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.) });
// "Always focus the target address on reload, or arrow key navigation would look terrible".
view.focused = view.model.entries.get(target).map(|entry| entry.address);
window.focus(&view.focus.clone(), cx);
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. A click focuses the table without moving its focused row
/// (`mouseSupport: false`).
pub(super) fn disassembly_editor_body(&self, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
let line_height = self.disassembly_line_height();
let view = &self.disassembly_view;
let body = div()
.id("disassembly-view")
.relative()
.flex_1()
.min_h_0()
.flex()
.flex_col()
.bg(self.color("editor.background"))
.text_color(self.color("foreground"))
.track_focus(&view.focus)
.on_mouse_down(MouseButton::Left, cx.listener(|workbench, _, window, cx| window.focus(&workbench.disassembly_view.focus.clone(), cx)))
.on_hover(cx.listener(|workbench, hovered: &bool, _, cx| {
workbench.disassembly_view.hovered = *hovered;
cx.notify();
}));
if 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(view.list.clone(), cx.processor(|workbench: &mut Workbench, index: usize, window, cx| workbench.disassembly_row(index, window, cx))).size_full();
// table.css: the disabled sash after the fixed breakpoint column draws the column border on hover.
let border = (view.hovered || self.is_motion_reduced()).then(|| self.theme.color("tree.tableColumnsBorder")).flatten();
body.child(rows).when_some(border, |body, border| body.child(div().absolute().top(px(1.)).bottom_0().left(px(line_height)).w(px(1.)).bg(border)))
}
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, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let line_height = self.disassembly_line_height();
let view = &self.disassembly_view;
let entry = &view.model.entries[index];
let address = entry.address;
let table_focused = view.focus.is_focused(window);
let row_focused = view.focused == Some(address);
let row_selected = view.selected == Some(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)));
// listWidget.ts styles: the selection active or inactive by the table's focus, the focus outline only while
// the table has focus, the hover on rows neither focused nor selected.
let selection = match (row_selected, table_focused) {
(false, _) => None,
(true, true) => Some((self.color("list.activeSelectionBackground"), self.theme.color("list.activeSelectionForeground"))),
(true, false) => Some((self.color("list.inactiveSelectionBackground"), self.theme.color("list.inactiveSelectionForeground"))),
};
let outline = self.theme.color("list.focusOutline").filter(|_| row_focused && table_focused);
let hover = self.color("list.hoverBackground");
div()
.id(("disassembly-row", index))
.relative()
.w_full()
.flex()
.when(!row_focused && !row_selected, |row| row.hover(move |row| row.bg(hover)))
.when_some(selection, |row, (background, foreground)| row.bg(background).when_some(foreground, |row, foreground| row.text_color(foreground)))
.child(self.disassembly_glyph(index, address, focused_top, focused, line_height, cx))
.child(column)
.when_some(outline, |row, outline| row.child(div().absolute().inset_0().border_1().border_color(outline)))
.into_any_element()
}
/// The row heights `DisassemblyView`'s delegate gives: the instruction's line and its source lines.
fn disassembly_row_heights(&self) -> Vec<f32> {
let line_height = self.disassembly_line_height();
self.disassembly_view.model.entries.iter().map(|entry| line_height * (1 + self.disassembly_source_lines(entry).map_or(0, |lines| lines.len())) as f32).collect()
}
/// list.contribution.ts `listFocus` and `listHasSelectionOrFocus` while the table has focus.
pub(super) fn disassembly_list_context(&self, window: &Window, context: &mut HashMap<String, Value>) {
let view = &self.disassembly_view;
if view.focus.is_focused(window) {
context.insert("listFocus".into(), json!(true));
context.insert("listHasSelectionOrFocus".into(), json!(view.focused.is_some() || view.selected.is_some()));
}
}
/// The list commands on the focused table (`multipleSelectionSupport: false`): the focus moves and reveals,
/// `list.select` selects the focused row, `list.clear` drops selection and focus.
pub(super) fn disassembly_list_command(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
if !self.disassembly_view.focus.is_focused(window) {
return false;
}
let heights = self.disassembly_row_heights();
let view = &mut self.disassembly_view;
let count = view.model.entries.len();
if count == 0 {
return true;
}
let focus = view.focused.and_then(|address| view.model.index_of_address(address));
let last = count - 1;
let next = match id {
"list.focusDown" | "list.focusAnyDown" => focus.map_or(0, |index| (index + 1).min(last)),
"list.focusUp" | "list.focusAnyUp" => focus.map_or(0, |index| index.saturating_sub(1)),
"list.focusFirst" | "list.focusAnyFirst" => 0,
"list.focusLast" | "list.focusAnyLast" => last,
"list.focusPageDown" | "list.focusPageUp" => {
let top = view.list.logical_scroll_top();
let scroll_top = heights[..top.item_ix].iter().sum::<f32>() + f32::from(top.offset_in_item);
let viewport = f32::from(view.list.viewport_bounds().size.height);
let Some((target, scroll_top)) = crate::list_tree::page_focus_rows(&heights, viewport, scroll_top, id == "list.focusPageDown", focus) else { return true };
view.list.scroll_to(list_offset(&heights, scroll_top));
target
}
"list.select" => {
view.selected = view.focused;
cx.notify();
return true;
}
"list.clear" => {
(view.focused, view.selected) = (None, None);
cx.notify();
return true;
}
_ => return true,
};
view.focused = Some(view.model.entries[next].address);
view.list.scroll_to_reveal_item(next);
cx.notify();
true
}
/// `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 row and the offset in it at `scroll_top`.
fn list_offset(heights: &[f32], scroll_top: f32) -> ListOffset {
let mut top = 0.;
for (item_ix, height) in heights.iter().enumerate() {
if top + height > scroll_top {
return ListOffset { item_ix, offset_in_item: px(scroll_top - top) };
}
top += height;
}
ListOffset { item_ix: heights.len(), offset_in_item: px(0.) }
}
/// 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]);
let table = |cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, _| (workbench.disassembly_view.focus.is_focused(window), workbench.disassembly_view.focused, workbench.disassembly_view.selected, workbench.key_context(window).get("listFocus").cloned()));
assert_eq!(table(cx), (true, Some(0x1000), None, Some(json!(true))), "the reload focuses the table on the frame's row");
let run = |id: &str, cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(id, Vec::new(), window, cx)));
run("list.focusDown", cx);
run("list.select", cx);
assert_eq!(table(cx), (true, Some(0x1004), Some(0x1004), Some(json!(true))));
run("list.focusFirst", cx);
assert_eq!(table(cx), (true, Some(0xffc), Some(0x1004), Some(json!(true))), "the focus moves without the selection");
run("list.clear", cx);
assert_eq!(table(cx), (true, None, None, Some(json!(true))));
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");
}
}