Visual Studio Code, rebuilt in Rust
Rust
fix(debug): select and copy text in the Debug Console (#108)
Artur Rokd13eb24d42bf
diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rsindex ac6dcc955d0..d30c5fa64a2 100644--- a/native/crates/app/src/menus.rs+++ b/native/crates/app/src/menus.rs@@ -165,6 +165,8 @@ pub enum MenuId {DebugVariablesContext,/// `MenuId.DebugWatchContext`: a Watch row's context menu.DebugWatchContext,+ /// `MenuId.DebugConsoleContext`: a Debug Console row's context menu.+ DebugConsoleContext,/// `MenuId.DebugHoverContext`: a debug hover tree row's context menu.DebugHoverContext,/// `MenuId.DebugToolBar`: the floating debug toolbar's actions.@@ -571,6 +573,13 @@ const WORKBENCH_MENUS: &[Row] = &[(MenuId::ExtensionContext, None, "workbench.extensions.action.downloadSpecificVersion", "Download Specific Version VSIX...", "", 2., Some("!extensionDisallowInstall && isGalleryExtension"), None),(MenuId::ExtensionContext, None, "workbench.extensions.action.removeExtensionFromWorkspaceRecommendations", "Remove from Workspace Recommendations", "3_recommendations", 2., Some("workbenchState != 'empty' && !isBuiltinExtension && isExtensionWorkspaceRecommended"), None),(MenuId::ViewContainerTitle, None, "workbench.action.debug.selectandstart", "Start Additional Session", "", 10., Some("viewContainer == 'workbench.view.debug' && debugState != 'inactive' && (config.debug.toolBarLocation == 'docked' || config.debug.hideLauncherWhileDebugging)"), None),+ // repl.ts's actions in `MenuId.DebugConsoleContext`.+ (MenuId::DebugConsoleContext, None, "debug.replCopy", "Copy", "2_cutcopypaste", 10., None, None),+ (MenuId::DebugConsoleContext, None, "workbench.debug.action.copyAll", "Copy All", "2_cutcopypaste", 20., None, None),+ (MenuId::DebugConsoleContext, None, "debug.replPaste", "Paste", "2_cutcopypaste", 30., None, Some("debugState != 'inactive'")),+ (MenuId::DebugConsoleContext, None, "debug.collapseRepl", "Collapse All", "z_commands", 10., None, None),+ (MenuId::DebugConsoleContext, None, "workbench.debug.panel.action.clearReplAction", "Clear Console", "z_commands", 20., None, None),+ (MenuId::DebugConsoleContext, None, "repl.action.find", "Debug Console: Focus Find", "z_commands", 25., None, None),// debug.contribution.ts `registerDebugViewMenuItem(MenuId.DebugVariablesContext/DebugHoverContext/DebugWatchContext, ...)`.(MenuId::DebugVariablesContext, None, "workbench.debug.viewlet.action.viewMemory", "View Binary Data", "inline", 15., Some("canViewMemory"), Some("inDebugMode")),(MenuId::DebugHoverContext, None, "workbench.debug.viewlet.action.viewMemory", "View Binary Data", "inline", 15., Some("canViewMemory"), Some("inDebugMode")),diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex e90e443d752..1dfa1a86229 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -123,6 +123,7 @@ mod keybindings_editor_view;mod keyboard;mod markdown_document;mod markdown_view;+mod text_selection;mod empty_view;mod layout;mod list_scroll;@@ -432,7 +433,7 @@ pub struct Workbench {marker_navigation: marker_navigation::MarkerNavigation,goto_symbol: goto_symbol::GotoSymbol,definition_link: goto_definition_link::DefinitionLink,- markdown_selection: markdown_view::MarkdownSelection,+ text_selection: text_selection::TextSelection,document_highlights: document_highlights::DocumentHighlights,document_symbols: document_symbols::DocumentSymbols,references_peek: references_peek::ReferencesPeek,@@ -844,7 +845,7 @@ impl Workbench {marker_navigation: Default::default(),goto_symbol: Default::default(),definition_link: Default::default(),- markdown_selection: Default::default(),+ text_selection: Default::default(),document_highlights: Default::default(),document_symbols: Default::default(),references_peek: references_peek::ReferencesPeek::new(cx),diff --git a/native/crates/app/src/workbench/debug_console.rs b/native/crates/app/src/workbench/debug_console.rsindex 3e64e6e7f71..6173fde15a7 100644--- a/native/crates/app/src/workbench/debug_console.rs+++ b/native/crates/app/src/workbench/debug_console.rs@@ -5,8 +5,8 @@ use std::cell::Cell;use std::collections::HashSet;use std::rc::Rc;-use gpui::{Bounds, ClickEvent, Context, Div, FocusHandle, Pixels, Task, Window, div, prelude::*, px};-use serde_json::json;+use gpui::{Bounds, ClickEvent, Context, Div, FocusHandle, MouseButton, MouseDownEvent, Pixels, SharedString, StyledText, Task, Window, div, prelude::*, px};+use serde_json::{Value, json};use super::Workbench;use super::debug_commands::REPL_VIEW_ID;@@ -16,6 +16,7 @@ use crate::commands::Outcome;use crate::debug::ansi::AnsiColor;use crate::debug::session::{ReplElement, Severity, Variable};use super::panel::PanelView;+use super::text_selection::TextSurface;use super::view_filter::ViewFilter;use crate::history::HistoryNavigator;use crate::input_box::InputBox;@@ -28,6 +29,9 @@ const HISTORY_STORAGE_KEY: &str = "debug.repl.history";const FILTER_HISTORY_STORAGE_KEY: &str = "debug.repl.filterHistory";const FILTER_VALUE_STORAGE_KEY: &str = "debug.repl.filterValue";+/// The console's texts in the window's `TextSelection` (repl.css `user-select: text`).+const REPL_TEXTS: TextSurface = "repl";+pub struct DebugConsole {pub focus: FocusHandle,pub input_focus: FocusHandle,@@ -378,6 +382,28 @@ impl Workbench {workbench.open_repl_find(window, cx);Outcome::done()});+ for id in ["repl.action.copyAll", "workbench.debug.action.copyAll"] {+ self.commands.register(id, |workbench, _, _, cx| {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(workbench.repl_visible_content()));+ Outcome::done()+ });+ }+ self.commands.register("debug.replCopy", |workbench, args, window, cx| {+ workbench.copy_repl_row(args, window, cx);+ Outcome::done()+ });+ self.commands.register("debug.replPaste", |workbench, _, window, cx| {+ let Some(pasted) = cx.read_from_clipboard().and_then(|item| item.text()).filter(|text| !text.is_empty()) else { return Outcome::done() };+ let value = format!("{}{pasted}", workbench.debug_console.input.value);+ workbench.edit_debug_console_input(|input| input.set_value(value), cx);+ window.focus(&workbench.debug_console.input_focus, cx);+ Outcome::done()+ });+ // repl.ts `debug.collapseRepl`: the port's console rows do not expand, so only `view.focus()` is left.+ self.commands.register("debug.collapseRepl", |workbench, _, window, cx| {+ window.focus(&workbench.debug_console.input_focus, cx);+ Outcome::done()+ });self.commands.register("repl.action.acceptInput", |workbench, _, window, cx| {let expression = std::mem::take(&mut workbench.debug_console.input).value;if expression.trim().is_empty() {@@ -446,6 +472,7 @@ impl Workbench {let font_size = 12.;let line_height = (font_size * 1.4_f32).round();let padding = if self.debug_console.find.open { FIND_PADDING } else { 0. };+ self.text_selection.begin(REPL_TEXTS);let mut rows = div().id("repl-tree").debug_selector(|| "repl-tree".into()).px(px(10.)).pt(px(4. + padding)).pb(px(4.)).flex().flex_col();let shown = self.shown_repl_session();let mut shown_elements = Vec::new();@@ -455,10 +482,21 @@ impl Workbench {}shown_elements.push(element);if self.repl_find_keeps(element) {- rows = rows.child(self.repl_element(index, element, line_height, cx));+ // `flex_none`: once the rows overflow, a shrinking row would stop at its `min_h` and a wrapped output+ // would draw over the row below (issue #82).+ rows = rows.child(self.repl_element(index, element, line_height, cx).flex_none().debug_selector(move || format!("repl-element-{index}")));}}- let tree = div().relative().flex_1().min_h_0().child(self.scrollable("repl-tree", None, rows, cx).size_full()).children(self.repl_find_widget(&shown_elements, window, cx));+ let list = self+ .text_selection_root(REPL_TEXTS, self.scrollable("repl-tree", None, rows, cx).size_full(), cx)+ .on_mouse_down(MouseButton::Left, cx.listener(|workbench, _, window, cx| window.focus(&workbench.debug_console.focus, cx)))+ // repl.ts `tree.onMouseClick`: the input takes the focus unless the click selected text or find is open.+ .on_mouse_up(MouseButton::Left, cx.listener(|workbench, _, window, cx| {+ if workbench.text_selection.is_collapsed() && !workbench.debug_console.find.open {+ window.focus(&workbench.debug_console.input_focus, cx);+ }+ }));+ let tree = div().relative().flex_1().min_h_0().child(list).children(self.repl_find_widget(&shown_elements, window, cx));let focused = self.debug_console.input_focus.is_focused(window);let prompt_color = self.color("debugConsoleInputIcon.foreground");let input = div()@@ -468,6 +506,7 @@ impl Workbench {.items_center().border_t_1().border_color(self.color("panel.border"))+ .on_mouse_down(MouseButton::Left, cx.listener(|workbench, _, window, cx| window.focus(&workbench.debug_console.input_focus, cx))).child(self.icon("chevron-right", 20., 16., prompt_color)).child(div().flex_1().h(px(line_height)).flex().child(self.input_text(InputId::DebugConsole, InputLook { password: false, placeholder: None, focused }, cx)));let console = div()@@ -479,7 +518,6 @@ impl Workbench {.font_family("Menlo").text_size(px(font_size)).line_height(px(line_height))- .on_mouse_down(gpui::MouseButton::Left, cx.listener(|workbench, _, window, cx| window.focus(&workbench.debug_console.input_focus, cx))).child(tree).child(input);div()@@ -523,7 +561,7 @@ impl Workbench {(text, highlights)}- fn repl_element(&self, index: usize, element: &ReplElement, line_height: f32, cx: &mut Context<Self>) -> gpui::AnyElement {+ fn repl_element(&self, index: usize, element: &ReplElement, line_height: f32, cx: &mut Context<Self>) -> Div {let severity_color = |severity: Severity| match severity {Severity::Warning => self.color("debugConsole.warningForeground"),Severity::Error => self.color("debugConsole.errorForeground"),@@ -533,11 +571,14 @@ impl Workbench {match element {ReplElement::Output { value, severity, source, count, .. } => {let (text, highlights) = self.ansi_output(value.strip_suffix('\n').unwrap_or(value));- let mut row = div().flex().items_start().min_h(px(line_height));+ let mut row = self.repl_menu_row(index, false, cx).flex().items_start().min_h(px(line_height));if *count > 1 {row = row.child(div().flex_none().mr(px(6.)).px(px(4.)).rounded(px(8.)).bg(self.color("badge.background")).text_color(self.color("badge.foreground")).child(count.to_string()));}- row = row.child(div().flex_1().min_w_0().text_color(severity_color(*severity)).whitespace_normal().child(gpui::StyledText::new(text).with_highlights(highlights)));+ let text = SharedString::from(text);+ let styled = StyledText::new(text.clone()).with_highlights(highlights);+ let selection = self.selectable_text(REPL_TEXTS, styled.layout(), text, "\n");+ row = row.child(div().relative().flex_1().min_w_0().text_color(severity_color(*severity)).whitespace_normal().child(selection).child(styled));if let Some((path, line)) = source {let name = path.rsplit('/').next().unwrap_or_default().to_owned();let (path, line) = (std::path::PathBuf::from(path), *line as usize);@@ -551,31 +592,129 @@ impl Workbench {.hover(|source| source.underline()).child(format!("{name}:{line}")).on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {+ // replOutputElementRenderer's `e.stopPropagation()`: the input does not take the focus back.+ cx.stop_propagation();workbench.open_file(path.clone(), true, window, cx);workbench.select_range(&path, crate::anything_quick_access::TextRange { start_line_number: line, start_column: 1, end_line_number: line, end_column: 1 }, cx);})),);}- row.into_any_element()+ row}ReplElement::Variable { variable, severity, .. } => {- let mut label = self.expression_label(variable, &self.repl_find_name_highlights(variable), None);+ let mut label = self.expression_label_in(variable, &self.repl_find_name_highlights(variable), None, Some(REPL_TEXTS));if variable.name.is_empty() {label = label.text_color(severity_color(*severity));}- div().flex().min_h(px(line_height)).child(self.icon(if variable.has_children() { "chevron-right" } else { "blank" }, 16., 16., self.foreground_or("icon.foreground"))).child(label).into_any_element()+ self.repl_menu_row(index, false, cx).flex().min_h(px(line_height)).child(self.icon(if variable.has_children() { "chevron-right" } else { "blank" }, 16., 16., self.foreground_or("icon.foreground"))).child(label)}ReplElement::Evaluation { input, result, .. } => {let icon = self.foreground_or("icon.foreground");- let mut rows = div().flex().flex_col().child(div().flex().items_center().min_h(px(line_height)).child(self.icon("arrow-small-right", 16., 16., icon)).child(self.repl_input_label(input)));+ let styled = self.repl_input_label(input);+ let selection = self.selectable_text(REPL_TEXTS, styled.layout(), input.clone().into(), "\n");+ let input_row = self.repl_menu_row(index, false, cx).flex().items_center().min_h(px(line_height)).child(self.icon("arrow-small-right", 16., 16., icon)).child(div().relative().child(selection).child(styled));+ let mut rows = div().flex().flex_col().child(input_row);if let Some(result) = result {let shown = Variable { name: String::new(), ..result.clone() };- rows = rows.child(div().flex().items_center().min_h(px(line_height)).child(self.icon("chevron-left", 16., 16., icon)).child(self.expression_label(&shown, &[], None)));+ rows = rows.child(self.repl_menu_row(index, true, cx).flex().items_center().min_h(px(line_height)).child(self.icon("chevron-left", 16., 16., icon)).child(self.expression_label_in(&shown, &[], None, Some(REPL_TEXTS))));}- rows.into_any_element()+ rows}}}++ /// A tree row whose context menu is `MenuId.DebugConsoleContext`, its commands given the element's index and whether+ /// the row is an evaluation's result, as `getActionsContext` gives them the element.+ fn repl_menu_row(&self, index: usize, result: bool, cx: &mut Context<Self>) -> Div {+ div().on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {+ let context = workbench.key_context(window);+ workbench.show_context_menu(crate::menus::MenuId::DebugConsoleContext, &context, Bounds::new(event.position, Default::default()), vec![json!(index), json!(result)], window, cx);+ }))+ }++ /// The row's `IReplElement.toString()`, and for an evaluation's result the expression it evaluated.+ fn repl_row_text(&self, index: usize, result: bool) -> Option<(String, Option<&str>)> {+ match self.debug.repl.get(index)? {+ ReplElement::Output { value, count, .. } => Some((repl_output_text(value, *count), None)),+ ReplElement::Variable { variable, .. } => Some((variable_text(variable), None)),+ ReplElement::Evaluation { input, result: Some(evaluated), .. } if result => Some((evaluated.value.clone(), Some(input))),+ ReplElement::Evaluation { input, .. } => Some((input.clone(), None)),+ }+ }++ /// repl.ts `getVisibleContent`: the shown elements' text, each trimmed at its end, one per line.+ fn repl_visible_content(&self) -> String {+ let mut content = String::new();+ let mut push = |text: &str| {+ content.push_str(text.trim_end());+ content.push('\n');+ };+ for element in self.shown_repl_elements() {+ if !self.repl_element_visible(element) || !self.repl_find_keeps(element) {+ continue;+ }+ match element {+ ReplElement::Output { value, count, .. } => push(&repl_output_text(value, *count)),+ ReplElement::Variable { variable, .. } => push(&variable_text(variable)),+ ReplElement::Evaluation { input, result, .. } => {+ push(input);+ if let Some(result) = result {+ push(&result.value);+ }+ }+ }+ }+ content+ }++ /// repl.ts `debug.replCopy`: the selected text, else the row's; an evaluation's result is evaluated again with+ /// the `clipboard` context when the adapter `supportsClipboardContext` (`tryEvaluateAndCopy`).+ fn copy_repl_row(&mut self, args: Vec<Value>, window: &mut Window, cx: &mut Context<Self>) {+ let selected = self.text_selection.to_text();+ if !selected.is_empty() {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(selected));+ return;+ }+ let (Some(index), result) = (args.first().and_then(Value::as_u64), args.get(1) == Some(&json!(true))) else { return };+ let Some((text, expression)) = self.repl_row_text(index as usize, result) else { return };+ let text = strip_ansi(&text);+ let expression = expression.map(str::to_owned);+ let session_id = self.debug.focus.session.clone();+ let supported = session_id.as_deref().and_then(|id| self.debug.session(id)).is_some_and(|session| session.capabilities["supportsClipboardContext"] == true);+ let (Some(expression), Some(session_id), Some(frame), true) = (expression, session_id, self.debug.focus.frame, supported) else {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));+ return;+ };+ let reply = self.dap_request(&session_id, "evaluate", json!({ "expression": expression, "frameId": frame, "context": "clipboard" }));+ cx.spawn_in(window, async move |_, cx| {+ let copied = match reply.await {+ Ok(Ok(body)) => body["result"].as_str().map_or(text, str::to_owned),+ _ => text,+ };+ cx.update(|_, cx| cx.write_to_clipboard(gpui::ClipboardItem::new_string(copied))).ok();+ })+ .detach();+ }+}++/// debugModel.ts `Variable.toString`: `name: value`, the value alone without a name.+fn variable_text(variable: &Variable) -> String {+ match variable.name.is_empty() {+ true => variable.value.clone(),+ false => format!("{}: {}", variable.name, variable.value),+ }+}++/// replModel.ts `SimpleReplElement.toString`: the value once per time it was output in a row.+fn repl_output_text(value: &str, count: u32) -> String {+ let mut text = value.to_owned();+ for _ in 1..count {+ if !text.ends_with('\n') {+ text.push('\n');+ }+ text.push_str(value);+ }+ text}pub(super) fn repl_element_session(element: &ReplElement) -> &str {@@ -877,4 +1016,101 @@ mod tests {assert!(starts.is_empty());workbench.update(cx, |workbench, _| assert!(workbench.debug.repl.is_empty()));}++ /// repl.css `user-select: text`: a drag across the rows selects their text and Copy copies it; a click without a+ /// drag gives the input the focus (repl.ts `tree.onMouseClick`).+ #[gpui::test]+ fn a_drag_selects_the_consoles_text_and_copy_copies_it(cx: &mut TestAppContext) {+ let (workbench, cx) = workbench(cx);+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.debug.repl = vec![output("s", "first line\n"), ReplElement::Evaluation { session_id: "s".into(), input: "1 + 1".into(), result: Some(Variable { value: "2".into(), ..Default::default() }) }];+ workbench.debug_console.selected_session = Some("s".into());+ workbench.open_debug_console(true, window, cx);+ });+ cx.run_until_parked();+ let first = cx.debug_bounds("repl-element-0").expect("drawn");+ let evaluation = cx.debug_bounds("repl-element-1").expect("drawn");+ let none = gpui::Modifiers::none();+ cx.simulate_mouse_down(first.origin + gpui::point(px(1.), px(8.)), gpui::MouseButton::Left, none);+ cx.simulate_mouse_move(evaluation.bottom_right() - gpui::point(px(1.), px(4.)), gpui::MouseButton::Left, none);+ cx.simulate_mouse_up(evaluation.bottom_right() - gpui::point(px(1.), px(4.)), gpui::MouseButton::Left, none);+ workbench.update_in(cx, |workbench, window, _| {+ assert_eq!(workbench.text_selection.to_text(), "first line\n1 + 1\n2");+ assert!(workbench.debug_console.focus.is_focused(window), "a selection keeps the focus off the input");+ });+ // The test workbench loads no keybindings: Cmd+C runs this command.+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("editor.action.clipboardCopyAction", Vec::new(), window, cx)));+ assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("first line\n1 + 1\n2"));+ cx.simulate_click(first.origin + gpui::point(px(30.), px(8.)), none);+ workbench.update_in(cx, |workbench, window, _| {+ assert_eq!(workbench.text_selection.to_text(), "");+ assert!(workbench.debug_console.input_focus.is_focused(window));+ });+ }++ /// repl.ts's `MenuId.DebugConsoleContext` actions: Copy copies the row without its escape sequences when nothing+ /// is selected, Copy All the shown rows (`getVisibleContent`).+ #[gpui::test]+ fn the_context_menu_copies_the_row_or_every_shown_row(cx: &mut TestAppContext) {+ let (workbench, cx) = workbench(cx);+ workbench.update_in(cx, |workbench, window, cx| {+ let repeated = ReplElement::Output { session_id: "s".into(), value: "again".into(), severity: Severity::Info, source: None, count: 2 };+ workbench.debug.repl = vec![output("s", "\u{1b}[31mred\u{1b}[0m \n"), output("other", "hidden"), repeated];+ workbench.debug_console.selected_session = Some("s".into());+ workbench.open_debug_console(true, window, cx);+ });+ cx.run_until_parked();+ let first = cx.debug_bounds("repl-element-0").expect("drawn");+ cx.simulate_mouse_down(first.center(), gpui::MouseButton::Right, gpui::Modifiers::none());+ let (titles, args) = workbench.read_with(cx, |workbench, _| {+ let menu = workbench.context_menu.as_ref().expect("a context menu shows");+ let title = |action: &crate::menus::MenuAction| match action {+ crate::menus::MenuAction::Command { title, enabled: true, .. } => title.clone(),+ crate::menus::MenuAction::Command { title, .. } => format!("({title})"),+ _ => "---".into(),+ };+ (menu.levels[0].actions.iter().map(title).collect::<Vec<_>>(), menu.args.clone())+ });+ assert_eq!(titles, ["Copy", "Copy All", "(Paste)", "---", "Collapse All", "Clear Console", "Debug Console: Focus Find"]);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.replCopy", args, window, cx)));+ assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("red \n"));+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.debug.action.copyAll", Vec::new(), window, cx)));+ assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("\u{1b}[31mred\u{1b}[0m\nagain\nagain\n"));+ }++ /// repl.ts `tryEvaluateAndCopy`: Copy on an evaluation's result evaluates its expression again with the+ /// `clipboard` context when the adapter supports it.+ #[gpui::test]+ fn copy_on_a_result_evaluates_it_for_the_clipboard(cx: &mut TestAppContext) {+ let (workbench, receiver, cx) = workbench_with_host(cx);+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.debug.sessions = vec![running(json!({ "supportsClipboardContext": true }))];+ workbench.debug.focus = super::super::debug_service::DebugFocus { session: Some("a".into()), thread: Some(1), frame: Some(3) };+ workbench.debug.repl = vec![ReplElement::Evaluation { session_id: "a".into(), input: "user".into(), result: Some(Variable { value: "{…}".into(), ..Default::default() }) }];+ drop(workbench.execute_command("debug.replCopy", vec![json!(0), json!(true)], window, cx));+ });+ cx.run_until_parked();+ let (requests, _) = adapter_traffic(&receiver);+ let evaluate = requests.iter().find(|request| request["command"] == "evaluate").expect("an evaluate request");+ assert_eq!(evaluate["arguments"], json!({ "expression": "user", "frameId": 3, "context": "clipboard" }));+ }++ /// repl.css `.word-wrap .monaco-tl-contents`: a long output wraps, and the row below starts under its last line,+ /// also once the rows overflow the panel (a flex item shrinks to its `min-height` there).+ #[gpui::test]+ fn a_wrapped_output_pushes_the_next_row_down(cx: &mut TestAppContext) {+ let (workbench, cx) = workbench(cx);+ cx.simulate_resize(gpui::size(px(1024.), px(768.)));+ let long = "Another exception was thrown: Assertion failed: file:///Volumes/Dados/Dev/flutter_bin/flutter/packages/flutter/lib/src/widgets/framework.dart:5940:12\n";+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.debug.repl = [long, "next\n"].repeat(20).into_iter().map(|value| output("s", value)).collect();+ workbench.debug_console.selected_session = Some("s".into());+ workbench.open_debug_console(true, window, cx);+ });+ cx.run_until_parked();+ let long = cx.debug_bounds("repl-element-0").expect("drawn");+ let next = cx.debug_bounds("repl-element-1").expect("drawn");+ assert!(long.size.height >= px(17.) * 2., "the long output wraps: {long:?}");+ assert!(next.top() >= long.bottom(), "{next:?} under {long:?}");+ }}diff --git a/native/crates/app/src/workbench/debug_view.rs b/native/crates/app/src/workbench/debug_view.rsindex ca842ad6ae2..b46840e04cf 100644--- a/native/crates/app/src/workbench/debug_view.rs+++ b/native/crates/app/src/workbench/debug_view.rs@@ -524,6 +524,11 @@ impl Workbench {/// `name: value` of a variable, watch or REPL result row; a lazy row's button sits between them.pub(super) fn expression_label(&self, variable: &Variable, highlights: &[std::ops::Range<usize>], lazy_button: Option<gpui::AnyElement>) -> Div {+ self.expression_label_in(variable, highlights, lazy_button, None)+ }++ /// `expression_label` whose name and value take part in `selectable`'s text selection.+ pub(super) fn expression_label_in(&self, variable: &Variable, highlights: &[std::ops::Range<usize>], lazy_button: Option<gpui::AnyElement>, selectable: Option<super::text_selection::TextSurface>) -> Div {let mut label = div().flex().min_w_0().overflow_hidden().whitespace_nowrap();if !variable.name.is_empty() {// debugExpressionRenderer.ts `renderVariable`: the name label is `name =`; debug.contribution.css puts the value 6px after it.@@ -537,9 +542,16 @@ impl Workbench {let color = self.color("list.highlightForeground");let byte = |chars: usize| name.char_indices().nth(chars).map_or(name.len(), |(byte, _)| byte);let styles: Vec<_> = highlights.iter().map(|range| (byte(range.start)..byte(range.end), gpui::HighlightStyle { color: Some(color.into()), ..Default::default() })).collect();- label = label.child(div().text_color(self.color("debugTokenExpression.name")).when(dimmed, |name| name.opacity(0.5)).child(gpui::StyledText::new(name).with_highlights(styles)));+ let name = gpui::SharedString::from(name);+ let text = gpui::StyledText::new(name.clone()).with_highlights(styles);+ let selection = selectable.map(|surface| self.selectable_text(surface, text.layout(), name, "\n"));+ label = label.child(div().relative().text_color(self.color("debugTokenExpression.name")).when(dimmed, |name| name.opacity(0.5)).children(selection).child(text));}- label.children(lazy_button).child(div().when(!variable.name.is_empty(), |value| value.ml(px(6.))).text_color(self.value_color(variable)).overflow_hidden().text_ellipsis().child(variable.value.clone()))+ let value = gpui::SharedString::from(variable.value.clone());+ let text = gpui::StyledText::new(value.clone());+ let separator = if variable.name.is_empty() { "\n" } else { "" };+ let selection = selectable.map(|surface| self.selectable_text(surface, text.layout(), value, separator));+ label.children(lazy_button).child(div().relative().when(!variable.name.is_empty(), |value| value.ml(px(6.))).text_color(self.value_color(variable)).overflow_hidden().text_ellipsis().children(selection).child(text))}/// baseDebugView.ts `lazyButton`: `$(eye)` 3px after the name, debug.contribution.css's 5px corners anddiff --git a/native/crates/app/src/workbench/editor_commands.rs b/native/crates/app/src/workbench/editor_commands.rsindex 6ce6b3e39df..61d7a0ba6b3 100644--- a/native/crates/app/src/workbench/editor_commands.rs+++ b/native/crates/app/src/workbench/editor_commands.rs@@ -439,8 +439,8 @@ impl Workbench {if let Some(outcome) = self.input_text_command(command, window, cx) {return outcome;}- // The browser's copy of the selected markdown text; a cut of it, which cannot be edited, does nothing.- let selected = self.markdown_selected_text();+ // The browser's copy of the selected text; a cut of it, which cannot be edited, does nothing.+ let selected = self.text_selection.to_text();if !cut && !selected.is_empty() {cx.write_to_clipboard(gpui::ClipboardItem::new_string(selected));}diff --git a/native/crates/app/src/workbench/markdown_view.rs b/native/crates/app/src/workbench/markdown_view.rsindex 27c03e47dd3..1a545866216 100644--- a/native/crates/app/src/workbench/markdown_view.rs+++ b/native/crates/app/src/workbench/markdown_view.rs@@ -1,13 +1,11 @@//! markdownRenderer.ts and editorMarkdownCodeBlockRenderer.ts from the parsed blocks: paragraphs, headings and//! lists in the UI font, code blocks tokenized in the editor font, links that open or run their command.-use std::cell::{Cell, RefCell};-use std::rc::Rc;--use gpui::{AnyElement, BorderStyle, Bounds, Context, Div, FontStyle, FontWeight, InteractiveElement, InteractiveText, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, Rgba, StrikethroughStyle, Styled, StyledText, TextLayout, TextRun, Window, canvas, div, point, px};+use gpui::{AnyElement, BorderStyle, Context, Div, FontStyle, FontWeight, InteractiveElement, InteractiveText, IntoElement, MouseButton, ParentElement, Rgba, StrikethroughStyle, Styled, StyledText, TextRun, Window, canvas, div, px};use serde_json::Value;use super::Workbench;+use super::text_selection::{TextSurface, text_rows};use crate::markdown::{Block, Inline};const UI_FONT: &str = ".SystemUIFont";@@ -27,30 +25,12 @@ pub(super) struct MarkdownStyle {/// A `code` span's background: `textCodeBlock.background` only in hovers, suggest details and parameter hints/// (hover.css, suggest.css, parameterHints.css).pub code_background: Option<Rgba>,- /// `userSelect: text`: the text takes the window's one `MarkdownSelection`.+ /// `userSelect: text`: the text takes part in the window's one `TextSelection`.pub selectable: bool,}-/// The text selection of the selectable markdown, one per window as the browser's: its texts in document order as-/// last drawn, and the selection's anchor and head as (text, byte offset).-#[derive(Default)]-pub(super) struct MarkdownSelection {- texts: RefCell<Vec<SelectableText>>,- anchor: (usize, usize),- head: (usize, usize),- selecting: bool,-}--struct SelectableText {- layout: TextLayout,- text: String,- /// Its bounds as last drawn; none for a text not drawn yet.- bounds: Rc<Cell<Option<Bounds<Pixels>>>>,- /// What a copy puts between it and the text before it, as Chrome's selection `toString`: nothing inside a- /// paragraph drawn word by word, `\n` between a code block's lines, `\n\n` between blocks.- /// shortcut: list items take `\n\n` where Chrome's tight `li` gives `\n`, refine when a list message needs it.- separator: &'static str,-}+/// The selectable markdown's texts in the window's `TextSelection`.+pub(super) const MARKDOWN_TEXTS: TextSurface = "markdown";impl Workbench {/// The blocks stacked with `p, .code, ul` 8px apart (hoverWidget.css `margin: 8px 0`, none at the ends); a code/// block without a language takes `model_language` (`editor.getModel().getLanguageId()`).@@ -111,7 +91,7 @@ impl Workbench {let runs = tokens.token_styles(&self.theme, &lines, index, 4);let content = crate::editor::expand_tabs(&lines[index], 4);let line = StyledText::new(content.clone()).with_highlights(runs);- let selection = selectable.then(|| self.selectable_text(line.layout(), &content, separator));+ let selection = selectable.then(|| self.selectable_text(MARKDOWN_TEXTS, line.layout(), content.clone().into(), separator));code = code.child(div().relative().min_h(px(line_height)).children(selection).child(line));}div().child(code)@@ -209,7 +189,7 @@ impl Workbench {let targets: Vec<String> = links.into_iter().map(|(_, target)| target).collect();let text = StyledText::new(inline.text.clone()).with_runs(runs);let layout = text.layout().clone();- let selection = style.selectable.then(|| self.selectable_text(&layout, &inline.text, if joined { "" } else { "\n\n" }));+ let selection = style.selectable.then(|| self.selectable_text(MARKDOWN_TEXTS, &layout, inline.text.clone().into(), if joined { "" } else { "\n\n" }));let workbench = cx.entity().downgrade();let open = style.action_handler.unwrap_or(Workbench::open_markdown_link);let text = InteractiveText::new(id.to_owned(), text).on_click(ranges, move |index, window, cx| {@@ -237,140 +217,16 @@ impl Workbench {div().relative().children(selection).child(text).children(outline).into_any_element()}- /// `blocks` with `userSelect: text` (testResultsOutput.ts `MarkdownTestMessagePeek`): a press places the selection,- /// two select the word and three the text, a drag or a shift press moves its head, a press elsewhere clears it.+ /// `blocks` with `userSelect: text` (testResultsOutput.ts `MarkdownTestMessagePeek`).pub(super) fn selectable_markdown_blocks(&mut self, id: &str, blocks: &[Block], style: MarkdownStyle, cx: &mut Context<Self>) -> Div {- self.markdown_selection.texts.get_mut().clear();+ self.text_selection.begin(MARKDOWN_TEXTS);let root = self.markdown_blocks(id, blocks, MarkdownStyle { selectable: true, ..style }, "", cx);- let workbench = cx.entity();- let selecting = self.markdown_selection.selecting;- // The drag goes on outside the text, as the browser's.- let drag = canvas(- |_, _, _| (),- move |_, _, window, _| {- if !selecting {- return;- }- let moved = workbench.clone();- window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {- if phase == gpui::DispatchPhase::Capture && event.pressed_button == Some(MouseButton::Left) {- moved.update(cx, |workbench, cx| workbench.move_markdown_selection(event.position, cx));- }- });- let released = workbench.clone();- window.on_mouse_event(move |_: &gpui::MouseUpEvent, phase, _, cx| {- if phase == gpui::DispatchPhase::Capture {- released.update(cx, |workbench, _| workbench.markdown_selection.selecting = false);- }- });- },- )- .absolute()- .size_0();let selector = id.to_owned();- root.child(drag)- .debug_selector(move || selector.clone())- .on_mouse_down(MouseButton::Left, cx.listener(|workbench, event: &MouseDownEvent, window, cx| {- // A press on text that cannot be focused takes the focus from the editor, so Copy copies the text.- window.blur(cx);- workbench.press_markdown_selection(event.position, event.click_count, event.modifiers.shift, cx);- }))- .on_mouse_down_out(cx.listener(|workbench, _: &MouseDownEvent, _, cx| {- let selection = &mut workbench.markdown_selection;- if selection.anchor != selection.head {- selection.anchor = selection.head;- cx.notify();- }- }))- }-- fn press_markdown_selection(&mut self, position: Point<Pixels>, click_count: usize, shift: bool, cx: &mut Context<Self>) {- let Some(at) = self.markdown_selection_at(position) else { return };- let texts = self.markdown_selection.texts.borrow();- let text = &texts[at.0].text;- let (anchor, head) = match click_count {- 1 if shift => (self.markdown_selection.anchor, at),- 1 => (at, at),- 2 => {- let word = word_at(text, at.1);- ((at.0, word.start), (at.0, word.end))- }- _ => ((at.0, 0), (at.0, text.len())),- };- drop(texts);- let selection = &mut self.markdown_selection;- (selection.anchor, selection.head, selection.selecting) = (anchor, head, true);- cx.notify();- }-- fn move_markdown_selection(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {- let Some(at) = self.markdown_selection_at(position).filter(|at| *at != self.markdown_selection.head) else { return };- self.markdown_selection.head = at;- cx.notify();- }-- /// The text and the character boundary at `position`: the drawn text nearest to it, vertically first.- fn markdown_selection_at(&self, position: Point<Pixels>) -> Option<(usize, usize)> {- let texts = self.markdown_selection.texts.borrow();- let distance = |bounds: Bounds<Pixels>| {- let away = |low: Pixels, high: Pixels, at: Pixels| (low - at).max(at - high).max(px(0.));- (away(bounds.top(), bounds.bottom(), position.y), away(bounds.left(), bounds.right(), position.x))- };- let mut nearest: Option<(usize, (Pixels, Pixels))> = None;- for (index, text) in texts.iter().enumerate() {- let Some(bounds) = text.bounds.get() else { continue };- if nearest.is_none_or(|(_, best)| distance(bounds) < best) {- nearest = Some((index, distance(bounds)));- }- }- let (index, _) = nearest?;- Some((index, closest_index(&texts[index].layout, position)))- }-- /// The selected text: the texts of a paragraph drawn word by word run on, blocks go on a new line.- pub(super) fn markdown_selected_text(&self) -> String {- let (start, end) = self.markdown_selection.ordered();- let mut selected = String::new();- for (index, text) in self.markdown_selection.texts.borrow().iter().enumerate().take(end.0 + 1).skip(start.0) {- let from = if index == start.0 { start.1 } else { 0 };- let to = if index == end.0 { end.1 } else { text.text.len() };- if index > start.0 {- selected.push_str(text.separator);- }- selected.push_str(&text.text[from..to]);- }- selected- }-- /// Takes `layout` into the selection as its next text, and paints the selection's part of it behind it in- /// `selection.background`, else Chrome's `::selection` default as measured with the blue accent: #B0D4FB light, #567BA1 dark.- fn selectable_text(&self, layout: &TextLayout, text: &str, separator: &'static str) -> gpui::Canvas<()> {- let bounds = Rc::new(Cell::new(None));- let mut texts = self.markdown_selection.texts.borrow_mut();- let index = texts.len();- texts.push(SelectableText { layout: layout.clone(), text: text.to_owned(), bounds: bounds.clone(), separator });- let (start, end) = self.markdown_selection.ordered();- let color = match self.theme.color("selection.background") {- Some(_) => self.color("selection.background"),- None if self.theme.kind.is_light() => gpui::rgb(0xb0d4fb).into(),- None => gpui::rgb(0x567ba1).into(),- };- let layout = layout.clone();- canvas(- move |drawn, _, _| bounds.set(Some(drawn)),- move |_, _, window, _| {- if index < start.0 || index > end.0 {- return;- }- let from = if index == start.0 { start.1 } else { 0 };- let to = if index == end.0 { end.1 } else { layout.len() };- for row in text_rows(&layout, from..to) {- window.paint_quad(gpui::fill(row, color));- }- },- )- .absolute()- .inset_0()+ let root = root.debug_selector(move || selector.clone()).on_mouse_down(MouseButton::Left, |_, window, cx| {+ // A press on text that cannot be focused takes the focus from the editor, so Copy copies the text.+ window.blur(cx);+ });+ self.text_selection_root(MARKDOWN_TEXTS, root, cx)}/// `openerService.open` of a rendered link: `command:` runs the command with the JSON arguments of its query,@@ -396,68 +252,6 @@ impl Workbench {}}-/// The box of `range` on each row of the laid out text. `position_for_index` puts a wrap boundary at the end of the-/// row before it, so a row ends where the next index moves down.-fn text_rows(layout: &TextLayout, range: std::ops::Range<usize>) -> Vec<Bounds<Pixels>> {- let line_height = layout.line_height();- let left = layout.bounds().origin.x;- let text = layout.text();- let indices = text[range.clone()].char_indices().map(|(index, _)| range.start + index).chain([range.end]);- let mut rows = Vec::new();- let mut row: Option<(gpui::Point<Pixels>, Pixels)> = None;- for index in indices {- let Some(position) = layout.position_for_index(index) else { continue };- row = match row {- Some((start, _)) if start.y == position.y => Some((start, position.x)),- Some((start, right)) => {- rows.push(Bounds::from_corners(start, point(right, start.y + line_height)));- Some((point(left, position.y), position.x))- }- None => Some((position, position.x)),- };- }- rows.extend(row.map(|(start, right)| Bounds::from_corners(start, point(right, start.y + line_height))));- rows.retain(|bounds| bounds.size.width > px(0.));- rows-}--impl MarkdownSelection {- /// The selection's start and end, the anchor or the head first.- fn ordered(&self) -> ((usize, usize), (usize, usize)) {- (self.anchor.min(self.head), self.anchor.max(self.head))- }-}--/// The character boundary of the drawn text nearest to `position`: on its row, or the row it is level with.-fn closest_index(layout: &TextLayout, position: Point<Pixels>) -> usize {- let line_height = layout.line_height();- let mut origin = layout.bounds().origin;- let mut start = 0;- for line in layout.line_layouts() {- let bottom = origin.y + line.size(line_height).height;- if position.y < bottom {- let within = point(position.x - origin.x, (position.y - origin.y).max(px(0.)));- return start + line.closest_index_for_position(within, line_height).unwrap_or_else(|index| index);- }- origin.y = bottom;- start += line.len() + 1;- }- layout.len()-}--/// The word around the boundary `at` for a double click: a run of letters, digits and `_`, else the character there.-fn word_at(text: &str, at: usize) -> std::ops::Range<usize> {- let is_word = |c: char| c.is_alphanumeric() || c == '_';- let Some(here) = text[at..].chars().next().or_else(|| text[..at].chars().next_back()) else { return at..at };- if !is_word(here) {- let start = if at == text.len() { at - here.len_utf8() } else { at };- return start..start + here.len_utf8();- }- let start = text[..at].char_indices().rev().take_while(|(_, c)| is_word(*c)).last().map_or(at, |(index, _)| index);- let end = text[at..].char_indices().find(|(_, c)| !is_word(*c)).map_or(text.len(), |(index, _)| at + index);- start..end-}-/// The text and spans of `inline` within `range`, shifted to start at 0.fn inline_slice(inline: &Inline, range: std::ops::Range<usize>) -> Inline {let mut spans = Vec::new();diff --git a/native/crates/app/src/workbench/testing_results.rs b/native/crates/app/src/workbench/testing_results.rsindex c4c4b17bc37..d9a53e6b881 100644--- a/native/crates/app/src/workbench/testing_results.rs+++ b/native/crates/app/src/workbench/testing_results.rs@@ -671,7 +671,7 @@ impl Workbench {/// testResultsViewContent.ts `reveal`: the subject's content and its call stack.pub(super) fn show_results_subject(&mut self, subject: InspectSubject) {self.testing_view.results_subject = Some(subject);- self.markdown_selection = Default::default();+ self.text_selection.collapse_in(super::markdown_view::MARKDOWN_TEXTS);self.show_message_editor();self.show_call_stack();}diff --git a/native/crates/app/src/workbench/testing_results/tests.rs b/native/crates/app/src/workbench/testing_results/tests.rsindex 7aa79d1b40b..73a4a89070e 100644--- a/native/crates/app/src/workbench/testing_results/tests.rs+++ b/native/crates/app/src/workbench/testing_results/tests.rs@@ -159,12 +159,12 @@ fn a_markdown_messages_text_can_be_selected_and_copied(cx: &mut TestAppContext)cx.simulate_mouse_down(first_row, gpui::MouseButton::Left, gpui::Modifiers::none());cx.simulate_mouse_move(text.origin + gpui::point(gpui::px(400.), gpui::px(45.)), gpui::MouseButton::Left, gpui::Modifiers::none());cx.simulate_mouse_up(text.origin + gpui::point(gpui::px(400.), gpui::px(45.)), gpui::MouseButton::Left, gpui::Modifiers::none());- workbench.read_with(cx, |workbench, _| assert_eq!(workbench.markdown_selected_text(), "The sum failed\n\nsecond"));+ workbench.read_with(cx, |workbench, _| assert_eq!(workbench.text_selection.to_text(), "The sum failed\n\nsecond"));workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.clipboardCopyAction", Vec::new(), window, cx));assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("The sum failed\n\nsecond"));cx.simulate_event(gpui::MouseDownEvent { button: gpui::MouseButton::Left, position: first_row, modifiers: gpui::Modifiers::none(), click_count: 2, first_mouse: false });cx.simulate_mouse_up(first_row, gpui::MouseButton::Left, gpui::Modifiers::none());- workbench.read_with(cx, |workbench, _| assert_eq!(workbench.markdown_selected_text(), "The"));+ workbench.read_with(cx, |workbench, _| assert_eq!(workbench.text_selection.to_text(), "The"));}/// testResultsViewContent.ts `setCallStackFrames` and callStackWidget.ts: a message's stack trace lists after it, adiff --git a/native/crates/app/src/workbench/text_selection.rs b/native/crates/app/src/workbench/text_selection.rsnew file mode 100644index 00000000000..87b654a10e8--- /dev/null+++ b/native/crates/app/src/workbench/text_selection.rs@@ -0,0 +1,266 @@+//! The browser's text selection over text drawn with `user-select: text`: the Test Results markdown message and the+//! Debug Console (repl.css). One selection per window, as the browser's; each surface keeps its own texts, so a part+//! that redraws alone (part_view.rs) replaces only its own.++use std::cell::{Cell, RefCell};+use std::rc::Rc;++use gpui::{Bounds, Context, InteractiveElement, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, SharedString, Styled, TextLayout, canvas, point, px};++use super::Workbench;++/// A surface whose texts can be selected.+pub(super) type TextSurface = &'static str;++/// The texts of each surface in document order as last drawn, and the selection's surface, anchor and head as+/// (text, byte offset).+#[derive(Default)]+pub(super) struct TextSelection {+ surfaces: RefCell<Vec<(TextSurface, Vec<SelectableText>)>>,+ surface: TextSurface,+ anchor: (usize, usize),+ head: (usize, usize),+ selecting: bool,+}++struct SelectableText {+ layout: TextLayout,+ text: SharedString,+ /// Its bounds as last drawn; none for a text not drawn yet.+ bounds: Rc<Cell<Option<Bounds<Pixels>>>>,+ /// What a copy puts between it and the text before it, as Chrome's selection `toString`: nothing inside a+ /// paragraph drawn word by word, `\n` between a code block's lines or the console's rows, `\n\n` between blocks.+ /// shortcut: list items take `\n\n` where Chrome's tight `li` gives `\n`, refine when a list message needs it.+ separator: &'static str,+}++impl TextSelection {+ /// The selection's start and end, the anchor or the head first.+ fn ordered(&self) -> ((usize, usize), (usize, usize)) {+ (self.anchor.min(self.head), self.anchor.max(self.head))+ }++ pub(super) fn is_collapsed(&self) -> bool {+ self.anchor == self.head+ }++ /// Drops the selection when it is in `surface`, whose content changed under it.+ pub(super) fn collapse_in(&mut self, surface: TextSurface) {+ if self.surface == surface {+ self.head = self.anchor;+ }+ }++ /// Starts drawing `surface` again: its texts are the ones taken from here on.+ pub(super) fn begin(&self, surface: TextSurface) {+ let mut surfaces = self.surfaces.borrow_mut();+ match surfaces.iter_mut().find(|(drawn, _)| *drawn == surface) {+ Some((_, texts)) => texts.clear(),+ None => surfaces.push((surface, Vec::new())),+ }+ }++ fn with_texts<R>(&self, surface: TextSurface, read: impl FnOnce(&[SelectableText]) -> R) -> R {+ let surfaces = self.surfaces.borrow();+ let texts = surfaces.iter().find(|(drawn, _)| *drawn == surface).map_or(&[][..], |(_, texts)| texts.as_slice());+ read(texts)+ }++ /// The selected text: each text after the separator it takes.+ pub(super) fn to_text(&self) -> String {+ let mut selected = String::new();+ if self.is_collapsed() {+ return selected;+ }+ let (start, end) = self.ordered();+ self.with_texts(self.surface, |texts| {+ for (index, text) in texts.iter().enumerate().take(end.0 + 1).skip(start.0) {+ let from = if index == start.0 { start.1 } else { 0 };+ let to = if index == end.0 { end.1 } else { text.text.len() };+ if index > start.0 {+ selected.push_str(text.separator);+ }+ selected.push_str(&text.text[from..to]);+ }+ });+ selected+ }+}++impl Workbench {+ /// `root` as the box of `surface`'s texts: a press places the selection, two select the word and three the text, a+ /// drag or a shift press moves its head, a press elsewhere clears it.+ pub(super) fn text_selection_root<E: ParentElement + InteractiveElement>(&self, surface: TextSurface, root: E, cx: &mut Context<Self>) -> E {+ let workbench = cx.entity();+ let selecting = self.text_selection.selecting && self.text_selection.surface == surface;+ // The drag goes on outside the text, as the browser's.+ let drag = canvas(+ |_, _, _| (),+ move |_, _, window, _| {+ if !selecting {+ return;+ }+ let moved = workbench.clone();+ window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {+ if phase == gpui::DispatchPhase::Capture && event.pressed_button == Some(MouseButton::Left) {+ moved.update(cx, |workbench, cx| workbench.move_text_selection(event.position, cx));+ }+ });+ let released = workbench.clone();+ window.on_mouse_event(move |_: &gpui::MouseUpEvent, phase, _, cx| {+ if phase == gpui::DispatchPhase::Capture {+ released.update(cx, |workbench, _| workbench.text_selection.selecting = false);+ }+ });+ },+ )+ .absolute()+ .size_0();+ root.child(drag)+ .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, cx| {+ workbench.press_text_selection(surface, event.position, event.click_count, event.modifiers.shift, cx);+ }))+ .on_mouse_down_out(cx.listener(move |workbench, _: &MouseDownEvent, _, cx| {+ // A press in a context menu opened on the text keeps the selection, as the browser's native menu does.+ let selection = &mut workbench.text_selection;+ if selection.surface == surface && !selection.is_collapsed() && workbench.context_menu.is_none() {+ selection.anchor = selection.head;+ cx.notify();+ }+ }))+ }++ fn press_text_selection(&mut self, surface: TextSurface, position: Point<Pixels>, click_count: usize, shift: bool, cx: &mut Context<Self>) {+ let Some(at) = self.text_selection_at(surface, position) else { return };+ let same_surface = self.text_selection.surface == surface;+ let (anchor, head) = self.text_selection.with_texts(surface, |texts| {+ let text = &texts[at.0].text;+ match click_count {+ 1 if shift && same_surface => (self.text_selection.anchor, at),+ 1 => (at, at),+ 2 => {+ let word = word_at(text, at.1);+ ((at.0, word.start), (at.0, word.end))+ }+ _ => ((at.0, 0), (at.0, text.len())),+ }+ });+ let selection = &mut self.text_selection;+ (selection.surface, selection.anchor, selection.head, selection.selecting) = (surface, anchor, head, true);+ cx.notify();+ }++ fn move_text_selection(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {+ let Some(at) = self.text_selection_at(self.text_selection.surface, position).filter(|at| *at != self.text_selection.head) else { return };+ self.text_selection.head = at;+ cx.notify();+ }++ /// The text and the character boundary at `position`: the drawn text nearest to it, vertically first.+ fn text_selection_at(&self, surface: TextSurface, position: Point<Pixels>) -> Option<(usize, usize)> {+ let distance = |bounds: Bounds<Pixels>| {+ let away = |low: Pixels, high: Pixels, at: Pixels| (low - at).max(at - high).max(px(0.));+ (away(bounds.top(), bounds.bottom(), position.y), away(bounds.left(), bounds.right(), position.x))+ };+ self.text_selection.with_texts(surface, |texts| {+ let mut nearest: Option<(usize, (Pixels, Pixels))> = None;+ for (index, text) in texts.iter().enumerate() {+ let Some(bounds) = text.bounds.get() else { continue };+ if nearest.is_none_or(|(_, best)| distance(bounds) < best) {+ nearest = Some((index, distance(bounds)));+ }+ }+ let (index, _) = nearest?;+ Some((index, closest_index(&texts[index].layout, position)))+ })+ }++ /// Takes `layout` into `surface` as its next text, and paints the selection's part of it behind it in+ /// `selection.background`, else Chrome's `::selection` default as measured with the blue accent: #B0D4FB light, #567BA1 dark.+ pub(super) fn selectable_text(&self, surface: TextSurface, layout: &TextLayout, text: SharedString, separator: &'static str) -> gpui::Canvas<()> {+ let bounds = Rc::new(Cell::new(None));+ let mut surfaces = self.text_selection.surfaces.borrow_mut();+ let texts = &mut surfaces.iter_mut().find(|(drawn, _)| *drawn == surface).expect("`TextSelection::begin` starts the surface").1;+ let index = texts.len();+ texts.push(SelectableText { layout: layout.clone(), text, bounds: bounds.clone(), separator });+ let selection = &self.text_selection;+ let (start, end) = selection.ordered();+ let painted = selection.surface == surface && !selection.is_collapsed() && (start.0..=end.0).contains(&index);+ let color = match self.theme.color("selection.background") {+ Some(_) => self.color("selection.background"),+ None if self.theme.kind.is_light() => gpui::rgb(0xb0d4fb),+ None => gpui::rgb(0x567ba1),+ };+ let layout = layout.clone();+ canvas(+ move |drawn, _, _| bounds.set(Some(drawn)),+ move |_, _, window, _| {+ if !painted {+ return;+ }+ let from = if index == start.0 { start.1 } else { 0 };+ let to = if index == end.0 { end.1 } else { layout.len() };+ for row in text_rows(&layout, from..to) {+ window.paint_quad(gpui::fill(row, color));+ }+ },+ )+ .absolute()+ .inset_0()+ }+}++/// The box of `range` on each row of the laid out text. `position_for_index` puts a wrap boundary at the end of the+/// row before it, so a row ends where the next index moves down.+pub(super) fn text_rows(layout: &TextLayout, range: std::ops::Range<usize>) -> Vec<Bounds<Pixels>> {+ let line_height = layout.line_height();+ let left = layout.bounds().origin.x;+ let text = layout.text();+ let indices = text[range.clone()].char_indices().map(|(index, _)| range.start + index).chain([range.end]);+ let mut rows = Vec::new();+ let mut row: Option<(gpui::Point<Pixels>, Pixels)> = None;+ for index in indices {+ let Some(position) = layout.position_for_index(index) else { continue };+ row = match row {+ Some((start, _)) if start.y == position.y => Some((start, position.x)),+ Some((start, right)) => {+ rows.push(Bounds::from_corners(start, point(right, start.y + line_height)));+ Some((point(left, position.y), position.x))+ }+ None => Some((position, position.x)),+ };+ }+ rows.extend(row.map(|(start, right)| Bounds::from_corners(start, point(right, start.y + line_height))));+ rows.retain(|bounds| bounds.size.width > px(0.));+ rows+}++/// The character boundary of the drawn text nearest to `position`: on its row, or the row it is level with.+fn closest_index(layout: &TextLayout, position: Point<Pixels>) -> usize {+ let line_height = layout.line_height();+ let mut origin = layout.bounds().origin;+ let mut start = 0;+ for line in layout.line_layouts() {+ let bottom = origin.y + line.size(line_height).height;+ if position.y < bottom {+ let within = point(position.x - origin.x, (position.y - origin.y).max(px(0.)));+ return start + line.closest_index_for_position(within, line_height).unwrap_or_else(|index| index);+ }+ origin.y = bottom;+ start += line.len() + 1;+ }+ layout.len()+}++/// The word around the boundary `at` for a double click: a run of letters, digits and `_`, else the character there.+fn word_at(text: &str, at: usize) -> std::ops::Range<usize> {+ let is_word = |c: char| c.is_alphanumeric() || c == '_';+ let Some(here) = text[at..].chars().next().or_else(|| text[..at].chars().next_back()) else { return at..at };+ if !is_word(here) {+ let start = if at == text.len() { at - here.len_utf8() } else { at };+ return start..start + here.len_utf8();+ }+ let start = text[..at].char_indices().rev().take_while(|(_, c)| is_word(*c)).last().map_or(at, |(index, _)| index);+ let end = text[at..].char_indices().find(|(_, c)| !is_word(*c)).map_or(text.len(), |(index, _)| at + index);+ start..end+}diff --git a/port/notes.md b/port/notes.mdindex cc84fa63f38..462f3387510 100644--- a/port/notes.md+++ b/port/notes.md@@ -888,14 +888,15 @@ Scope as in the M19 Work row of port/ledger.md.- Test Explorer title (testExplorerActions.ts, `testing_view.rs`): the navigation actions end with Show Output (`terminal`, disabled until a result exists); the "..." holds View as List/Tree, Sort by Status/Location/Duration (workspace storage `testing.viewMode` and `testing.viewSorting`, as testingExplorerView.ts) and Collapse All Tests, Clear All Results. Shortcut: View as List lists the tests the collection has resolved; listProjection.ts also asks the controller to resolve every level (`expandElement(root, Infinity)`), which the port does not send.- Test Results tree (`workbench/testing_results.rs`; testResultsTree.ts `OutputPeekTree`): rows drawn as the workbench tree rows (4px inset, rounded, `list_row_selection`, indent guides, listCommands.ts keys while focused); a new run selects and focuses its first task without taking the focus (`revealItem` with `preserveFocus`). Decision: the task row always shows its twistie when it has children. The reference renders the task row while the task is still childless (`onNewTask`), and abstractTree.ts `renderTreeElement` redraws a twistie only on a collapse state change, so the reference shows no twistie until the row is toggled or rendered again; the port draws the state a fresh render gives.- Test resolution timing: treeProjection.ts `storeItem` expands only depth-0 items, the controller roots; a single root's children show on the explorer's top level collapsed (index.ts `getChildrenForParent`, `depth > 0`) and resolve only when the user expands them, and testService.ts `testsInFile` yields an open file's item without expanding it. The port expanded those file items at publish, so the tests-provider fixture's `resolveHandler` ran for every file and Run All ran each test, where the reference's run handler finds the unresolved file item and runs it as one test (`math.test.js` without children in the results). `TestCollection::apply` now answers only the roots.-- Test Results content editors (`workbench/testing_results.rs`; testResultsOutput.ts content providers): the view's code editors live in `TEST_RESULTS_GROUP`, a group outside the grid like the Output view's `PANEL_GROUP` (`is_panel_group`), so they select, copy and take the editor keys through the same code; `PlainTextMessagePeek` opens a plain text message's `messageUri` model (`vscode-test-data://results/<result>/message/<task>/<message>/TestFailureMessage?<test>`) there read-only, without line numbers, glyph margin, minimap or `scrollBeyondLastLine` (`commonEditorOptions`). testMessageColorizer.ts `colorizeTestMessageInEditor` (`testing_message_colorizer.rs`): the model holds the text without its escapes (strings.ts `removeAnsiEscapeCodes`) and each styled run is a text decoration keyed by its space-joined `tstm-ansidec-*` classes; only single-number SGR codes change the state (`colorAttrRe`, so `\x1b[1;31m` does nothing), and only `bg30`-`bg37` and `bg100`-`bg107` have a fill, as testMessageColorizer.css has rules for those alone. `DiffContentProvider` opens a diffable message (an error with string `expected` and `actual`) as an embedded diff of its `ExpectedOutput` and `ActualOutput` models (`DiffInput.embedded`): `diffEditorOptions` fixes the options (side by side, no overview ruler, `ignoreTrimWhitespace` false, unchanged regions shown) instead of reading `diffEditor.*`, line numbers turn on when either side is multiline, and a 20px zone above line 1 holds the "Expected" and "Actual" titles (testingDecorations.ts `TitleLensContentWidget`). The editors are built outside a text editor part, so `lineNumbersMinChars` is the default 5, and only the original side has a glyph margin (`_adjustOptionsForLeftHandSide`). The diff's `diff_part_width` moved to the group state, since the results diff and an editor area diff lay out at once. ui-pair port/fixtures/testing-messages (`compare.test.js`): gutters, fills and titles match; the content and tree split about 2:1 in both: testResultsViewContent.ts adds them with `Sizing.Distribute` to a split view of size 0, so they start at their minimums (200 and 100) and the proportional layout keeps that ratio, which the port gives as flex weights 2 and 1 over those minimum widths. `MarkdownTestMessagePeek` renders a markdown message through `markdown_view.rs` in testing.css `.preview-text` (8px 12px 8px 20px padding, paragraphs 1em apart at `line-height: normal`, 15px here), and its results row reads the rendered text (`renderTestMessageAsText`). ui-pair of a `markdown "..."` test (tests-provider): text box 240x77 at the same left in both, 1px lower in the reference. The text is selectable (testResultsOutput.ts `userSelect: text`): GPUI text has no selection, so `markdown_view.rs` `selectable_markdown_blocks` keeps each text's layout and bounds in `MarkdownSelection`, drags and double clicks select across the blocks, and Copy takes the selection when no editor or input has the focus, with Chrome's `\n\n` between blocks. Without `selection.background` it paints Chrome's `::selection` default as measured (#567BA1 dark, #B0D4FB light). ui-pair of a drag over both paragraphs: the same copied text and highlight, except Chrome's highlight of the line break past a paragraph's last character. `TerminalMessagePeek` writes a task's output, a test's output or an output message's range into a detached terminal (`TerminalView.detached`: an `extension_pty` instance with ids counting down from `u32::MAX`, kept out of the terminal list), appending when the earlier text is its prefix and resetting with `\x1bc` otherwise; an empty finished output writes the `formatMessageForTerminal` notice. It attaches with `enableGpu: false`, so the DomRenderer lays the cells out on the unrounded advance (Menlo 12: 7.2px, `CellMetrics.dom_cell_width`), not the WebGL renderer's whole device pixels. ui-pair of the `markdown "..."` test's output: the line is 385px wide in the reference and 384px in the port, at the same origin. A message's `stackTrace` (testResultsSubject.ts `MessageSubject.stack`) shows as callStackWidget.ts `CallStackWidget`: a 24px header per frame (collapse button, label, toolbar), the message's frame first with `MenuId.TestCallStack` (Rerun Test, Debug Test by the test's capabilities), then each frame with a readable source as a read-only peek editor in `TEST_RESULTS_GROUP` (`PeekOwner::CallStackFrame`, kept out of host sync) showing its line and 2 around it through hidden areas, the line highlighted as the top stack frame and its column marked, with `MenuId.DebugCallStackToolbar`'s Open File; a frame without a source shows its label, `:line` and "Line N column M". The frame editors take only `ClickToLocationContribution` upstream, so no test glyphs, overview ruler or scrollbars, and `lineNumbersMinChars` 5. The column marker's width is in columns of the measured font: the results group copies an editor-less main group's viewport with no `char_width`, so the view marks the columns itself (`sync_call_stack_frame_columns`). ui-pair of `stack.test.js` (tests-provider sets `stackTrace` on a `stack` line): headers, labels, gutter and the frame line match; Cmd+click on a word in a frame editor (`ClickToLocationContribution`) underlines it as a link without a definition lookup and opens the frame's file with the cursor at the word's start, to the side with the side-by-side modifier (`goto_definition_link.rs` `open_call_stack_word`). The results group draws through `swapped_group_body`, whose guard keeps unpressed moves from a group that is not active, so the press links the word itself. That guard focused the group in its own capture listener, painted after the body, so a frame editor's capture took the focus in the wrong group first and the row's press read the message editor's lines (an index panic); the body's capture listener focuses the group now. A press that focuses a frame's editor makes it the active one, so the message row draws its editor as an unfocused code editor (`embedded_code_editor`) rather than the active one. ui-pair cannot hold Cmd through a press (cua's `modifier` reaches neither app as a held key, no link shows in the reference either), so `cmd_click_on_a_word_in_a_frame_opens_its_file_there` is the evidence; a plain press in the frame matches the reference.+- Test Results content editors (`workbench/testing_results.rs`; testResultsOutput.ts content providers): the view's code editors live in `TEST_RESULTS_GROUP`, a group outside the grid like the Output view's `PANEL_GROUP` (`is_panel_group`), so they select, copy and take the editor keys through the same code; `PlainTextMessagePeek` opens a plain text message's `messageUri` model (`vscode-test-data://results/<result>/message/<task>/<message>/TestFailureMessage?<test>`) there read-only, without line numbers, glyph margin, minimap or `scrollBeyondLastLine` (`commonEditorOptions`). testMessageColorizer.ts `colorizeTestMessageInEditor` (`testing_message_colorizer.rs`): the model holds the text without its escapes (strings.ts `removeAnsiEscapeCodes`) and each styled run is a text decoration keyed by its space-joined `tstm-ansidec-*` classes; only single-number SGR codes change the state (`colorAttrRe`, so `\x1b[1;31m` does nothing), and only `bg30`-`bg37` and `bg100`-`bg107` have a fill, as testMessageColorizer.css has rules for those alone. `DiffContentProvider` opens a diffable message (an error with string `expected` and `actual`) as an embedded diff of its `ExpectedOutput` and `ActualOutput` models (`DiffInput.embedded`): `diffEditorOptions` fixes the options (side by side, no overview ruler, `ignoreTrimWhitespace` false, unchanged regions shown) instead of reading `diffEditor.*`, line numbers turn on when either side is multiline, and a 20px zone above line 1 holds the "Expected" and "Actual" titles (testingDecorations.ts `TitleLensContentWidget`). The editors are built outside a text editor part, so `lineNumbersMinChars` is the default 5, and only the original side has a glyph margin (`_adjustOptionsForLeftHandSide`). The diff's `diff_part_width` moved to the group state, since the results diff and an editor area diff lay out at once. ui-pair port/fixtures/testing-messages (`compare.test.js`): gutters, fills and titles match; the content and tree split about 2:1 in both: testResultsViewContent.ts adds them with `Sizing.Distribute` to a split view of size 0, so they start at their minimums (200 and 100) and the proportional layout keeps that ratio, which the port gives as flex weights 2 and 1 over those minimum widths. `MarkdownTestMessagePeek` renders a markdown message through `markdown_view.rs` in testing.css `.preview-text` (8px 12px 8px 20px padding, paragraphs 1em apart at `line-height: normal`, 15px here), and its results row reads the rendered text (`renderTestMessageAsText`). ui-pair of a `markdown "..."` test (tests-provider): text box 240x77 at the same left in both, 1px lower in the reference. The text is selectable (testResultsOutput.ts `userSelect: text`): GPUI text has no selection, so `markdown_view.rs` `selectable_markdown_blocks` keeps each text's layout and bounds in the window's `TextSelection` (`text_selection.rs`), drags and double clicks select across the blocks, and Copy takes the selection when no editor or input has the focus, with Chrome's `\n\n` between blocks. Without `selection.background` it paints Chrome's `::selection` default as measured (#567BA1 dark, #B0D4FB light). ui-pair of a drag over both paragraphs: the same copied text and highlight, except Chrome's highlight of the line break past a paragraph's last character. `TerminalMessagePeek` writes a task's output, a test's output or an output message's range into a detached terminal (`TerminalView.detached`: an `extension_pty` instance with ids counting down from `u32::MAX`, kept out of the terminal list), appending when the earlier text is its prefix and resetting with `\x1bc` otherwise; an empty finished output writes the `formatMessageForTerminal` notice. It attaches with `enableGpu: false`, so the DomRenderer lays the cells out on the unrounded advance (Menlo 12: 7.2px, `CellMetrics.dom_cell_width`), not the WebGL renderer's whole device pixels. ui-pair of the `markdown "..."` test's output: the line is 385px wide in the reference and 384px in the port, at the same origin. A message's `stackTrace` (testResultsSubject.ts `MessageSubject.stack`) shows as callStackWidget.ts `CallStackWidget`: a 24px header per frame (collapse button, label, toolbar), the message's frame first with `MenuId.TestCallStack` (Rerun Test, Debug Test by the test's capabilities), then each frame with a readable source as a read-only peek editor in `TEST_RESULTS_GROUP` (`PeekOwner::CallStackFrame`, kept out of host sync) showing its line and 2 around it through hidden areas, the line highlighted as the top stack frame and its column marked, with `MenuId.DebugCallStackToolbar`'s Open File; a frame without a source shows its label, `:line` and "Line N column M". The frame editors take only `ClickToLocationContribution` upstream, so no test glyphs, overview ruler or scrollbars, and `lineNumbersMinChars` 5. The column marker's width is in columns of the measured font: the results group copies an editor-less main group's viewport with no `char_width`, so the view marks the columns itself (`sync_call_stack_frame_columns`). ui-pair of `stack.test.js` (tests-provider sets `stackTrace` on a `stack` line): headers, labels, gutter and the frame line match; Cmd+click on a word in a frame editor (`ClickToLocationContribution`) underlines it as a link without a definition lookup and opens the frame's file with the cursor at the word's start, to the side with the side-by-side modifier (`goto_definition_link.rs` `open_call_stack_word`). The results group draws through `swapped_group_body`, whose guard keeps unpressed moves from a group that is not active, so the press links the word itself. That guard focused the group in its own capture listener, painted after the body, so a frame editor's capture took the focus in the wrong group first and the row's press read the message editor's lines (an index panic); the body's capture listener focuses the group now. A press that focuses a frame's editor makes it the active one, so the message row draws its editor as an unfocused code editor (`embedded_code_editor`) rather than the active one. ui-pair cannot hold Cmd through a press (cua's `modifier` reaches neither app as a held key, no link shows in the reference either), so `cmd_click_on_a_word_in_a_frame_opens_its_file_there` is the evidence; a plain press in the frame matches the reference.- Continuous run (`workbench/testing_continuous.rs`): the view title's dropdown of `getContinuousRunDropdown` runs plain actions upstream; the port's context menu runs commands, so each profile item is an internal `_testing.toggleContinuousRunProfile.<controller>.<profile>` command registered when the menu shows. testingExplorerView.ts re-sorts a parent when a continuous run changes, but `TreeSorter` has no continuous run criterion in 1.147.0, so the order does not change; the port draws rows from the run state each frame and needs no re-sort. The unattended restart participant `testing.continuousRun` waits on the unattended restart service (ledger row workbench/services/lifecycle).- Inline values (`workbench/debug_inline_values.rs`; debugEditorContribution.ts): `debug.inlineValues` `on` or `auto` with a provider shows the focused frame's values as `InjectionOwner::DebugInlineValue` text after the lines, `editor.inlineValuesForeground` on `editor.inlineValuesBackground`. Shortcuts: only the active editor shows them, where upstream decorates every editor on the frame's file; the scopes and variables are fetched again, not shared with the Variables view's cache; the text area width stands in for `layoutInfo.width` in the line length cut.- Debug hover (`workbench/debug_hover.rs`; debugHover.ts, debugEditorContribution.ts hover handling): while stopped, the expression at the mouse in the focused frame's file (the first `EvaluatableExpressionProvider` through `$provideEvaluatableExpression`, else `getExactExpressionStartAndEnd`) is evaluated with `context: "hover"` (or looked up in the cheap scopes without `supportsEvaluateForHovers`) after the doubled `editor.hover.delay`, the editor hover off meanwhile; Alt swaps it for the editor hover; Cmd+K Cmd+I shows it at the cursor. The focused tree takes listWidget.ts's and abstractTree.ts's keys through the `list.*` commands (Up, Down, Page Up, Page Down, Home, End, Left, Right, Space, Enter, type navigation by name), Escape clears a selection before it hides the widget; `layoutTree` sizes the tree to its rows plus 10px, at most max(266px, 55% of the editor) and the hovered line's top less 22px. The visualizers are a ledger gap of workbench/contrib/debug; the context menu is under Variable menus. The glyph margin lifts the editor hover lockout; the hovered position is the nearer edge of the character under the mouse, a tab's middle included. Lazy rows (`presentationHint.lazy`) draw the `$(eye)` button after the name in the hover, Variables and Watch trees; a lazy watch, hover or REPL result is evaluated at once (debugModel.ts `evaluateExpression` without `keepLazyVars`). A click on an expandable row focuses and toggles it; with Alt the descendants whose children are loaded follow, the others stay collapsed (indexTreeModel.ts `_setNodeCollapseState` recursive, asyncDataTree.ts collapsing a stale node a deep expand reaches). `list.find` (Cmd+Alt+F, F3) on the focused tree opens abstractTree.ts's find widget over 30px of padding: highlight or filter mode and fuzzy or contiguous match by `workbench.list.defaultFindMode` and `defaultFindMatchType` and the widget's toggles, the filter keeps a collapsed parent of a loaded match, "No results found.", the focus to the first match from the focused row; it outlives each shown value like the tree, and Escape hides the hover and runs `list.closeFind` after it. ui-pair on `port/fixtures/debug-node` (Cmd+K Cmd+I on `numbers` and `greeting`) matches the reference's placement, tree indent and focus outline.- Call Stack selection (`workbench/debug_view.rs` `call_stack_selects_focus`; callStackView.ts `updateTreeSelection`): the view builds its tree in `renderBody` and selects the focused frame only on a focus change it sees, so a view first shown by `openOnDebugBreak` after the stop has no selected row until the next focus change. Measured with `port/tools/ref-dom` on `port/fixtures/debug-node` app.js: the first stop leaves no `.monaco-list-row.selected`; after Continue to a second breakpoint `global.main app.js 5:2` is selected; with the Run and Debug view shown before the start the first stop selects it too.- Inline breakpoints (`workbench/inline_breakpoints.rs`; breakpointEditorContribution.ts `setDecorations`, `InlineBreakpointWidget`): a column breakpoint past the line's first column, or sharing its line, draws its icon after a `0.9em` placeholder; with `debug.showInlineBreakpointCandidates` and a focused session that `supportsBreakpointLocationsRequest`, each breakpoint line's `breakpointLocations` answer draws disabled dots (not at the first column without another breakpoint on the line, not past the last). A click adds, removes or enables; a right click shows `getContextMenuActions` at the column. Upstream asks again on every `setDecorations`; the port asks when the focused session, the debug state or a model's breakpoint lines change, keeping the previous dots until the answer (the 500 ms race has no flicker to avoid). Tests: `cargo test -p app inline_breakpoints`.- Variable menus (`workbench/variable_menu.rs`; variablesView.ts `openContextMenuForVariableTreeElement`, watchExpressionsView.ts `onContextMenu`, debugContext.ts `getContextForVariable`): a right-click on a Variables, Watch or hover row opens `DebugVariablesContext`, `DebugWatchContext` or `DebugHoverContext` over the row's keys (`variableEvaluateNamePresent`, `variableIsReadonly`, `variableType`, `watchItemType`, `debugType`), with `{ sessionId, container, variable }` for a variable and `{ watchExpressionId, name }` for a watch expression. Copy Value evaluates `evaluateName || value` again with the `clipboard` context when the debugger supports it, else `variables` or `watch`, and falls back to the shown value. Set Value, View Binary Data and the Break on Value items are left out until their requests are ported (ledger debug row); `canViewMemory` is always false.-- Debug Console find (`workbench/debug_console_find.rs`; repl.ts `FindReplAction`, `openFind`): `repl.action.find` (Cmd+Alt+F, the title's `search` before the session picker and Clear Console) opens the tree find widget of the debug hover (`TreeFind`) over the console with 30px of padding; elements are found by `IReplElement.toString(true)`, an evaluation by its input or its result, filter mode drops the elements without a match, evaluation inputs and variable names highlight the matched chars, "No results found." when nothing matches, the pattern is kept for the next open. Shortcuts: the port's console has no row focus, so highlight mode moves no focus to the first match; the item in `MenuId.DebugConsoleContext` waits on that menu, which the port does not have (cargo test -p app the_find_widget_filters_the_console).+- Debug Console find (`workbench/debug_console_find.rs`; repl.ts `FindReplAction`, `openFind`): `repl.action.find` (Cmd+Alt+F, the title's `search` before the session picker and Clear Console) opens the tree find widget of the debug hover (`TreeFind`) over the console with 30px of padding; elements are found by `IReplElement.toString(true)`, an evaluation by its input or its result, filter mode drops the elements without a match, evaluation inputs and variable names highlight the matched chars, "No results found." when nothing matches, the pattern is kept for the next open. Shortcuts: the port's console has no row focus, so highlight mode moves no focus to the first match (cargo test -p app the_find_widget_filters_the_console).+- Debug Console text selection and copy (issue #82; repl.css `user-select: text`, repl.ts): the rows' texts (output, evaluation input and result, variable name and value) take part in the window's one `TextSelection` (`workbench/text_selection.rs`, moved out of `markdown_view.rs`, which the Test Results markdown message also uses), each surface keeping its own texts so a cached part that redraws alone replaces only its own. A press, a drag, a double or triple click and a shift press select as in the browser; a click that selects nothing gives the input the focus (`tree.onMouseClick`); Cmd+C (`editor.action.clipboardCopyAction` outside an editor or input) copies the selection, rows joined by `\n`. The row context menu is `MenuId.DebugConsoleContext`: Copy (`debug.replCopy`: the selection, else the row without its escape sequences, an evaluation's result evaluated again with `context: "clipboard"` when the adapter `supportsClipboardContext`), Copy All (`workbench.debug.action.copyAll`, also `repl.action.copyAll`: `getVisibleContent`), Paste, Collapse All, Clear Console, Find. Shortcuts: Collapse All only focuses the input, as the port's console rows do not expand; a filter or find change shifts a selection to the texts now at its indices, where the browser keeps it on its nodes (cargo test -p app a_drag_selects_the_consoles_text_and_copy_copies_it the_context_menu_copies_the_row_or_every_shown_row). Trap, same issue: the console's rows are `flex_none`; a flex item shrinks to its explicit `min_h` (17px) once its column overflows, where upstream's list rows sit in no flex column, so a wrapped output kept one line of height and drew over the row below (cargo test -p app a_wrapped_output_pushes_the_next_row_down).- Extension host debugging (`extensionHost` launch type; rawDebugSession.ts `launchVsCode`, localProcessExtensionHost.ts `attachSession`, debugService.ts `onAttachSession`): js-debug's `launchVSCode` opens the Extension Development Host window (or reloads the one on the same extension path) with `--debugId`, `--inspect-brk-extensions` and `--extensionEnvironment`; the host it starts has the session attach to the inspector port on a new adapter. Decision: a host with an inspector port runs on Node, since Bun has no V8 inspector; a host without one stays on Bun, and there is no 5870 default port (environmentService.ts gives one to a build from source, which would put every checkout run on Node). The window closes with its current host's exit and at the end of a 'Run Without Debugging' session; a restart reloads it. Check: `cargo test -p app workbench::host::`, ui-pair `debug/extension-host.json` with `FOLDER=port/fixtures/debug-extension` (stops at the breakpoint in `activate`).- Debug visualizers (`workbench/debug_visualizers.rs`): a visualizer contributed with a Uri `iconPath` draws an empty button in the reference too: variablesView.ts builds the action with `class: v.iconClass || 'debug-viz-icon'`, reads no `iconPath`, and no stylesheet of 1.147.0 names `debug-viz-icon` (cargo test -p app debug_visualizers).- View Binary Data (`workbench/debug_memory.rs`; variablesView.ts `VIEW_MEMORY_ID`, debugMemory.ts): the `vscode-debug-memory` provider lives in the workbench, and `exthost/src/main_thread_files.rs` asks it through `ask_workbench`. The answer waits on the workbench's own `readMemory` to js-debug, so `Session::ask_workbench` flushes the workbench's queued host calls while it waits; before that the hex editor's read hung on its LOADING placeholders. The provider has only `FileOpenReadWriteClose`, so upstream's file service reads with `read`, which ends the file at the first unreadable byte; the port's `readFile` returns that prefix. The range comes from an extension: it must be ordered, end at most at 2^53-1 and span at most 16 MiB. Inline row buttons show on hover or focus through `hidden()`/`flex()`: a `group_hover` display change skips prepaint and panics. ui-pair `debug/memory.json` needs `ms-vscode.hexeditor` 1.11.1 from Open VSX in `<dir>`, `ARGS="--extensions-dir <dir>"` and `FOLDER=port/fixtures/debug-node`. The hex editor's breadcrumbs are `3 > memory.bin` (breadcrumbsControl.ts takes a custom editor's resource of any scheme with a file system provider, `custom_editor_resource`): a resource of a scheme other than `file` and `vscode-userdata` has no workspace folder or `~` item, and its pickers list nothing, as debugMemory.ts `stat` makes every folder a file (cargo test -p app a_custom_editor_on_a_debug_memory_resource_has_breadcrumbs). shortcut: Space on its file item opens the resource as a text file without the session authority, which cannot be read; upgrade when breadcrumb elements keep the URI.