Skip to content

Visual Studio Code, rebuilt in Rust

Rust
51.2 KB
Raw Blame
//! The debug commands of debugCommands.ts, debugEditorActions.ts and the views' actions, with the context keys of
//! debug.ts that their keybindings and menus read.

use std::collections::HashMap;
use std::path::PathBuf;

use futures::channel::oneshot;
use gpui::{Context, Window};
use serde_json::{Value, json};

use super::Workbench;
use super::debug_task_runner::DebugTasks;
use super::search_view::SideBarView;
use crate::commands::Outcome;
use crate::debug::BreakpointData;
use crate::debug::session::State;

/// debug.ts `REPL_VIEW_ID` and `VIEWLET_ID`.
pub const REPL_VIEW_ID: &str = "workbench.panel.repl.view";
pub const VIEWLET_ID: &str = "workbench.view.debug";

impl Workbench {
    pub(super) fn register_debug_commands(&mut self) {
        self.register_variable_menu_commands();
        self.register_debug_memory_commands();
        let start = |no_debug: bool| {
            move |workbench: &mut Workbench, _: Vec<Value>, window: &mut Window, cx: &mut Context<Workbench>| {
                if let Some((folder, name, debug_type)) = workbench.selected_dynamic() {
                    workbench.start_dynamic(folder, name, debug_type, json!({ "noDebug": no_debug, "startedByUser": true }), window, cx);
                    return Outcome::done();
                }
                let (folder, name) = workbench.selected_launch();
                let target = name.map_or(Value::Null, Value::String);
                Outcome::Pending(workbench.start_debugging(folder, target, json!({ "noDebug": no_debug, "startedByUser": true }), DebugTasks::PreLaunch, window, cx))
            }
        };
        self.commands.register("workbench.action.debug.start", start(false));
        self.commands.register("workbench.action.debug.run", start(true));
        self.commands.register("debug.startFromConfig", |workbench, args, window, cx| {
            let config = args.into_iter().next().unwrap_or_default();
            Outcome::Pending(workbench.start_debugging(None, config, json!({}), DebugTasks::PreLaunch, window, cx))
        });
        // debugCommands.ts `debug.installAdditionalDebuggers`: the Extensions view searching the debuggers category.
        self.commands.register("debug.installAdditionalDebuggers", |workbench, args, window, cx| {
            let search = match args.first().and_then(Value::as_str) {
                Some(query) => format!("@category:debuggers {query}"),
                None => "@category:debuggers".to_owned(),
            };
            workbench.execute_command("workbench.extensions.search", vec![json!(search)], window, cx)
        });
        // debugCommands.ts FOCUS_SESSION_ID: the session, or its stopped or first child, and its frame's editor.
        self.commands.register("workbench.action.debug.focusProcess", |workbench, args, window, cx| {
            let Some(session) = args.first().and_then(Value::as_str) else { return Outcome::done() };
            let session = workbench.resolve_child_session(&session);
            let focus = workbench.debug.focus_target(Some(&session), None);
            workbench.set_debug_focus(focus, super::debug_service::Reveal::PreservingFocus, window, cx);
            Outcome::done()
        });
        self.commands.register("debug.openView", |workbench, _, _, cx| {
            workbench.show_debug_view(cx);
            Outcome::done()
        });
        self.commands.register(VIEWLET_ID, |workbench, _, _, cx| {
            workbench.show_debug_view(cx);
            Outcome::done()
        });
        // debugCommands.ts `stopHandler`: the context's or the focused session, the root of a child its parent manages; with none, all.
        for (id, disconnect, suspend) in [("workbench.action.debug.stop", false, false), ("workbench.action.debug.disconnect", true, false), ("workbench.action.debug.disconnectAndSuspend", true, true)] {
            self.commands.register(id, move |workbench, args, window, cx| {
                let session = workbench.context_session(&args);
                Outcome::Pending(workbench.stop_session(session, disconnect, suspend, window, cx))
            });
        }
        self.commands.register("workbench.action.debug.restart", move |workbench, args, window, cx| {
            let Some(mut session_id) = workbench.context_session(&args) else { return start(false)(workbench, args, window, cx) };
            // The restart goes to the root parent unless the toolbar shows sub-sessions.
            let show_sub_sessions = workbench.setting("debug.showSubSessionsInToolBar") == true;
            while !show_sub_sessions
                && let Some(session) = workbench.debug.session(&session_id)
                && session.options["lifecycleManagedByParent"] == true
                && let Some(parent) = session.parent.clone()
            {
                session_id = parent;
            }
            workbench.remove_repl_expressions(&session_id);
            Outcome::Pending(workbench.restart_session(session_id, None, window, cx))
        });
        for (id, command, step) in [
            ("workbench.action.debug.continue", "continue", false),
            ("workbench.action.debug.stepOver", "next", true),
            ("workbench.action.debug.stepInto", "stepIn", true),
            ("workbench.action.debug.stepOut", "stepOut", true),
            ("workbench.action.debug.stepBack", "stepBack", true),
            ("workbench.action.debug.reverseContinue", "reverseContinue", false),
        ] {
            self.commands.register(id, move |workbench, args, _, cx| {
                let Some((session, thread)) = workbench.context_thread(&args) else { return Outcome::done() };
                workbench.thread_command(&session, thread, command, step, cx)
            });
        }
        self.commands.register("workbench.action.debug.pause", |workbench, args, _, cx| {
            let Some((session, thread)) = workbench.context_thread(&args) else { return Outcome::done() };
            let reply = workbench.dap_request(&session, "pause", json!({ "threadId": thread }));
            cx.notify();
            Outcome::Pending(reply)
        });
        // debugModel.ts `Thread.terminate`.
        self.commands.register("workbench.action.debug.terminateThread", |workbench, args, _, _| {
            let Some((session, thread)) = workbench.context_thread(&args) else { return Outcome::done() };
            Outcome::Pending(workbench.dap_request(&session, "terminateThreads", json!({ "threadIds": [thread] })))
        });
        self.commands.register("workbench.action.debug.restartFrame", |workbench, args, _, cx| {
            let Some((session, thread, frame)) = workbench.context_frame(&args).map(|(session, thread, frame)| (session.id.clone(), thread.id, frame.id)) else { return Outcome::done() };
            workbench.resume_thread(&session, thread, "restartFrame", json!({ "frameId": frame }), cx)
        });
        self.commands.register("debug.copyStackTrace", |workbench, args, _, cx| {
            let Some((_, thread, _)) = workbench.context_frame(&args) else { return Outcome::done() };
            let text = thread.frames.iter().map(super::call_stack_menu::stack_frame_label).collect::<Vec<_>>().join("\n");
            cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
            Outcome::done()
        });
        self.commands.register("editor.debug.action.toggleBreakpoint", |workbench, _, _, cx| {
            let Some(editor) = workbench.editors.active() else { return Outcome::done() };
            let mut lines: Vec<u32> = editor.selections.iter().map(|selection| selection.head.line as u32 + 1).collect();
            lines.dedup();
            let uri = editor.document().uri();
            for line in lines {
                workbench.toggle_breakpoint(&uri, line, None, cx);
            }
            Outcome::done()
        });
        // debugEditorActions.ts TOGGLE_INLINE_BREAKPOINT: a breakpoint at the cursor's column.
        self.commands.register("editor.debug.action.toggleInlineBreakpoint", |workbench, _, _, cx| {
            let Some(editor) = workbench.editors.active() else { return Outcome::done() };
            let head = editor.selections[0].head;
            let uri = editor.document().uri();
            workbench.toggle_breakpoint(&uri, head.line as u32 + 1, Some(head.column as u32 + 1), cx);
            Outcome::done()
        });
        for (id, kind) in [("editor.debug.action.conditionalBreakpoint", super::breakpoint_widget::WidgetContext::Condition), ("editor.debug.action.addLogPoint", super::breakpoint_widget::WidgetContext::LogMessage)] {
            self.commands.register(id, move |workbench, _, window, cx| {
                let Some(editor) = workbench.editors.active() else { return Outcome::done() };
                let line = editor.selections[0].head.line as u32 + 1;
                workbench.show_breakpoint_widget(line, None, None, kind, window, cx);
                Outcome::done()
            });
        }
        self.commands.register("editor.debug.action.editBreakpoint", |workbench, _, window, cx| {
            let Some(editor) = workbench.editors.active() else { return Outcome::done() };
            let line = editor.selections[0].head.line as u32 + 1;
            let uri = editor.document().uri_string();
            let id = workbench.debug.model.breakpoints_in(&uri).find(|breakpoint| breakpoint.line_number() == line).map(|breakpoint| breakpoint.id().to_owned());
            workbench.show_breakpoint_widget(line, None, id, super::breakpoint_widget::WidgetContext::Condition, window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.debug.viewlet.action.removeAllBreakpoints", |workbench, _, _, cx| {
            let ids: Vec<String> = workbench.debug.model.breakpoints.iter().map(|breakpoint| breakpoint.id().to_owned()).collect();
            let mut change = workbench.debug.model.remove_breakpoints(&ids);
            change.removed.extend(workbench.debug.model.remove_function_breakpoints(None).removed);
            change.removed.extend(workbench.debug.model.remove_data_breakpoints(None).removed);
            change.removed.extend(workbench.debug.model.remove_instruction_breakpoints(None, None, None).removed);
            workbench.breakpoints_changed(change, true, cx);
            Outcome::done()
        });
        for (id, enable) in [("workbench.debug.viewlet.action.enableAllBreakpoints", true), ("workbench.debug.viewlet.action.disableAllBreakpoints", false)] {
            self.commands.register(id, move |workbench, _, _, cx| {
                let change = workbench.debug.model.enable_or_disable_all(enable);
                workbench.breakpoints_changed(change, true, cx);
                Outcome::done()
            });
        }
        self.commands.register("workbench.debug.viewlet.action.toggleBreakpointsActivatedAction", |workbench, _, _, cx| {
            workbench.debug.model.breakpoints_activated = !workbench.debug.model.breakpoints_activated;
            workbench.breakpoints_changed(crate::debug::BreakpointsChange::default(), true, cx);
            let ids: Vec<String> = workbench.debug.sessions.iter().map(|session| session.id.clone()).collect();
            for id in ids {
                workbench.send_all_breakpoints(&id, cx);
            }
            Outcome::done()
        });
        self.commands.register("workbench.debug.viewlet.action.addFunctionBreakpointAction", |workbench, _, _, cx| {
            workbench.debug_view.editing = Some(super::debug_view::Editing::NewFunctionBreakpoint);
            workbench.debug_view.input = crate::input_box::InputBox::default();
            workbench.show_debug_view(cx);
            Outcome::done()
        });
        self.commands.register("workbench.debug.viewlet.action.addWatchExpression", |workbench, _, _, cx| {
            workbench.debug_view.editing = Some(super::debug_view::Editing::NewWatch);
            workbench.debug_view.input = crate::input_box::InputBox::default();
            workbench.show_debug_view(cx);
            Outcome::done()
        });
        self.commands.register("workbench.debug.viewlet.action.removeAllWatchExpressions", |workbench, _, window, cx| {
            workbench.debug.model.remove_watch_expressions(None);
            workbench.store_debug_model();
            workbench.refresh_focus(window, cx);
            Outcome::done()
        });
        // debugEditorActions.ts SELECTION_TO_WATCH: the selection, or the word at the cursor.
        self.commands.register("editor.debug.action.selectionToWatch", |workbench, _, window, cx| {
            let Some(expression) = workbench.selected_expression() else { return Outcome::done() };
            workbench.debug.model.add_watch_expression(&expression);
            workbench.store_debug_model();
            workbench.show_debug_view(cx);
            workbench.refresh_focus(window, cx);
            Outcome::done()
        });
        self.commands.register("editor.debug.action.selectionToRepl", |workbench, _, window, cx| {
            let Some(expression) = workbench.selected_expression() else { return Outcome::done() };
            workbench.open_debug_console(true, window, cx);
            workbench.evaluate_in_repl(expression, window, cx);
            Outcome::done()
        });
        self.commands.register("debug.action.openDisassemblyView", |workbench, _, window, cx| {
            workbench.open_disassembly_view(window, cx);
            Outcome::done()
        });
        self.commands.register("debug.action.toggleDisassemblyViewSourceCode", |workbench, _, _, cx| {
            let shown = workbench.setting("debug.disassemblyView.showSourceCode") != json!(false);
            workbench.update_setting("debug.disassemblyView.showSourceCode", json!(!shown));
            cx.notify();
            Outcome::done()
        });
        self.commands.register("editor.debug.action.runToCursor", |workbench, _, window, cx| workbench.run_to_cursor(window, cx));
        self.commands.register("workbench.debug.action.toggleRepl", |workbench, _, window, cx| {
            match workbench.debug_console_visible() && workbench.debug_console.focus.is_focused(window) {
                true => workbench.close_debug_console(cx),
                false => workbench.open_debug_console(true, window, cx),
            }
            Outcome::done()
        });
        self.commands.register("workbench.debug.action.focusRepl", |workbench, _, window, cx| {
            workbench.open_debug_console(true, window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.debug.panel.action.clearReplAction", |workbench, _, _, cx| {
            workbench.clear_repl();
            cx.notify();
            Outcome::done()
        });
        // debugCommands.ts CONFIGURE / ADD_CONFIGURATION: launch.json of the selected folder, created when missing.
        self.commands.register("workbench.action.debug.configure", |workbench, _, window, cx| workbench.open_launch_json(window, cx));
        self.commands.register("debug.addConfiguration", |workbench, _, window, cx| workbench.open_launch_json(window, cx));
        self.commands.register("workbench.action.debug.selectandstart", |workbench, _, window, cx| {
            workbench.show_quick_access(super::quick_access::start_debug::PREFIX, false, false, window, cx);
            Outcome::done()
        });
    }

    /// `debugService.getConfigurationManager().selectedConfiguration`: the stored choice while it exists or is a
    /// dynamic one, else the first folder's first configuration.
    pub(crate) fn selected_launch(&self) -> (Option<PathBuf>, Option<String>) {
        if let Some((folder, name, _)) = self.selected_dynamic() {
            return (folder, Some(name));
        }
        let folders = self.workspace_folders();
        if let Some((root, name)) = &self.debug.selected {
            let folder = root.clone().or_else(|| folders.first().cloned());
            if let Some(folder) = &folder
                && self.folder_launch(folder).configuration_names().contains(name)
            {
                return (Some(folder.clone()), Some(name.clone()));
            }
        }
        for folder in &folders {
            if let Some(name) = self.folder_launch(folder).configuration_names().into_iter().next() {
                return (Some(folder.clone()), Some(name));
            }
        }
        (folders.first().cloned(), None)
    }

    /// Continue and the step commands (debugSession.ts `next`, `stepIn`, `stepOut`).
    fn thread_command(&mut self, session_id: &str, thread: i64, command: &str, step: bool, cx: &mut Context<Self>) -> Outcome {
        let mut arguments = json!({ "threadId": thread });
        // debugCommands.ts: a step from the disassembly view steps one instruction.
        let granularity = (step && self.disassembly_view_active()).then_some("instruction");
        if let Some(granularity) = granularity {
            arguments["granularity"] = json!(granularity);
        }
        if step
            && let Some(thread) = self.debug.session_mut(session_id).and_then(|session| session.threads.iter_mut().find(|candidate| candidate.id == thread))
        {
            thread.last_stepping_granularity = granularity;
        }
        self.resume_thread(session_id, thread, command, arguments, cx)
    }

    /// A request that runs the thread on: it runs again at once, before the adapter's `continued` event.
    fn resume_thread(&mut self, session_id: &str, thread: i64, command: &str, arguments: Value, cx: &mut Context<Self>) -> Outcome {
        let wait = self.debug.session(session_id).and_then(|session| session.wait_to_resume.clone());
        let reply = match wait {
            None => self.dap_request(session_id, command, arguments),
            Some(wait) => self.dap_request_after_triggered_breakpoints(wait, session_id, command, arguments, cx),
        };
        let all_threads = command == "continue";
        if let Some(session) = self.debug.session_mut(session_id) {
            session.continue_threads(if all_threads { None } else { Some(thread) });
        }
        self.debug.focus.frame = None;
        self.debug.scopes.clear();
        self.debug.children.clear();
        self.update_debug_inline_values(cx);
        cx.notify();
        Outcome::Pending(reply)
    }

    /// debugSession.ts `waitForTriggeredBreakpoints`: the request waits for the dependent breakpoints, at most 1.5 s.
    fn dap_request_after_triggered_breakpoints(&mut self, wait: futures::future::Shared<gpui::Task<()>>, session_id: &str, command: &str, arguments: Value, cx: &mut Context<Self>) -> oneshot::Receiver<Result<Value, Value>> {
        let (sender, receiver) = oneshot::channel();
        let (session_id, command) = (session_id.to_owned(), command.to_owned());
        let timeout = cx.background_executor().timer(std::time::Duration::from_millis(1500));
        cx.spawn(async move |this, cx| {
            futures::future::select(wait, timeout).await;
            let Ok(reply) = this.update(cx, |workbench, _| workbench.dap_request(&session_id, &command, arguments)) else { return };
            let _ = sender.send(reply.await.unwrap_or(Err(Value::Null)));
        })
        .detach();
        receiver
    }

    /// debugEditorActions.ts RunToCursorAction and debugService.ts `runTo`: a breakpoint at the cursor unless one is
    /// there (at the cursor's column on the focused frame's line), sent to the sessions; then the best thread
    /// continues, or with no session the selected configuration starts.
    fn run_to_cursor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let Some(editor) = self.editors.active() else { return Outcome::done() };
        let head = editor.selections[0].head;
        let line = head.line as u32 + 1;
        let (uri, path) = (editor.document().uri(), editor.document().path.clone());
        let on_focused_frame = self.debug.focused_frame().is_some_and(|frame| frame.line == line && frame.path().map(PathBuf::from) == Some(path.clone()));
        let column = on_focused_frame.then_some(head.column as u32 + 1);
        self.run_to_line(&uri, line, column, window, cx);
        Outcome::done()
    }

    /// debugService.ts `runTo`, from Run to Cursor and the gutter's Run to Line.
    pub(super) fn run_to_line(&mut self, uri: &Value, line: u32, column: Option<u32>, window: &mut Window, cx: &mut Context<Self>) {
        let uri_string = crate::debug::uri_string(uri);
        let path = PathBuf::from(crate::uri::json_fs_path(uri));
        let exists = self.debug.model.breakpoints_in(&uri_string).any(|breakpoint| breakpoint.line_number() == line && (column.is_none() || breakpoint.column() == column));
        let mut breakpoint = None;
        let mut sends = Vec::new();
        if !exists {
            let change = self.debug.model.add_breakpoints(uri, vec![BreakpointData { column, ..BreakpointData::at(line) }]);
            breakpoint = change.added.first().cloned();
            self.breakpoints_changed(change, false, cx);
            let sessions: Vec<String> = self.debug.sessions.iter().map(|session| session.id.clone()).collect();
            sends = sessions.iter().map(|session| self.send_breakpoints(session, &uri_string, false, cx)).collect();
        }
        cx.spawn_in(window, async move |this, cx| {
            for send in sends {
                let _ = send.await;
            }
            // addAndValidateBreakpoints: an unverified breakpoint gets 2 s to verify (`raceTimeout`), checked every 50 ms.
            if let Some(id) = &breakpoint {
                for _ in 0..40 {
                    let verified = this.read_with(cx, |workbench, _| workbench.debug.model.breakpoint(id).is_none_or(|breakpoint| breakpoint.base.verified()));
                    if !matches!(verified, Ok(false)) {
                        break;
                    }
                    cx.background_executor().timer(std::time::Duration::from_millis(50)).await;
                }
            }
            let _ = this.update_in(cx, |workbench, window, cx| workbench.run_to(breakpoint, &path, window, cx));
        })
        .detach();
    }

    /// The rest of `runTo` once the breakpoint is in place: it is removed at the next stop or end.
    fn run_to(&mut self, breakpoint: Option<String>, path: &std::path::Path, window: &mut Window, cx: &mut Context<Self>) {
        match self.debug.state() {
            State::Inactive => {
                self.debug_view.run_to_cursor = breakpoint;
                if let Some((folder, name, debug_type)) = self.selected_dynamic() {
                    return self.start_dynamic(folder, name, debug_type, json!({}), window, cx);
                }
                let (folder, name) = self.selected_launch();
                drop(self.start_debugging(folder, name.map_or(Value::Null, Value::String), json!({}), DebugTasks::PreLaunch, window, cx));
            }
            State::Stopped => {
                let Some((session, thread)) = self.thread_to_continue(breakpoint.as_deref(), path) else { return };
                if self.debug.focus.session.is_none() {
                    return;
                }
                self.debug_view.run_to_cursor = breakpoint;
                drop(self.thread_command(&session, thread, "continue", false, cx));
            }
            _ => {}
        }
    }

    /// addAndValidateBreakpoints's thread: of the sessions that verified the breakpoint, the focused thread when
    /// stopped there, else a thread paused in the file, else the first stopped thread; the focused thread otherwise.
    fn thread_to_continue(&self, breakpoint: Option<&str>, path: &std::path::Path) -> Option<(String, i64)> {
        let focused = self.debug.focus.session.clone().zip(self.debug.focus.thread);
        let Some(breakpoint) = breakpoint.and_then(|id| self.debug.model.breakpoint(id)) else { return focused };
        let (mut best, mut score) = (focused.clone(), 0);
        for session_id in breakpoint.base.sessions_that_verified() {
            let Some(session) = self.debug.session(session_id) else { continue };
            let threads: Vec<i64> = session.threads.iter().filter(|thread| thread.stopped).map(|thread| thread.id).collect();
            if score < 3 && let Some((focused_session, focused_thread)) = &focused && focused_session == session_id && threads.contains(focused_thread) {
                (best, score) = (focused.clone(), 3);
            }
            let in_file = session.threads.iter().filter(|thread| thread.stopped).find(|thread| thread.frames.first().and_then(|frame| frame.path()).map(PathBuf::from).as_deref() == Some(path));
            if score < 2 && let Some(thread) = in_file {
                (best, score) = (Some((session_id.to_owned(), thread.id)), 2);
            }
            // Upstream scores the first stopped thread as paused in the file too.
            if score < 1 {
                (best, score) = (threads.first().map(|thread| (session_id.to_owned(), *thread)), 2);
            }
        }
        best
    }

    /// `removeTempBreakPoint` on a stop or a session's end.
    pub(super) fn remove_run_to_cursor_breakpoint(&mut self, cx: &mut Context<Self>) {
        let Some(id) = self.debug_view.run_to_cursor.take() else { return };
        let change = self.debug.model.remove_breakpoints(&[id]);
        self.breakpoints_changed(change, true, cx);
    }

    /// TOGGLE_BREAKPOINT for one line (or one column): removes the line's breakpoints, else adds one when the
    /// language takes breakpoints.
    pub(crate) fn toggle_breakpoint(&mut self, uri: &Value, line: u32, column: Option<u32>, cx: &mut Context<Self>) {
        let uri_string = crate::debug::uri_string(uri);
        let existing: Vec<String> = self.debug.model.breakpoints_in(&uri_string).filter(|breakpoint| breakpoint.line_number() == line && (column.is_none() || breakpoint.column() == column)).map(|breakpoint| breakpoint.id().to_owned()).collect();
        let change = match existing.is_empty() {
            false => self.debug.model.remove_breakpoints(&existing),
            true if self.can_set_breakpoints_in_active_editor() => self.debug.model.add_breakpoints(uri, vec![BreakpointData { column, ..BreakpointData::at(line) }]),
            true => return,
        };
        self.breakpoints_changed(change, true, cx);
    }

    /// debugAdapterManager.ts `canSetBreakpointsIn`: languages of `contributes.breakpoints`, or everywhere with
    /// `debug.allowBreakpointsEverywhere`; never in jsonc or log files.
    pub(crate) fn can_set_breakpoints_in_active_editor(&self) -> bool {
        self.editors.active().is_some_and(|editor| self.can_set_breakpoints_in(editor))
    }

    pub(crate) fn can_set_breakpoints_in(&self, editor: &crate::editor::OpenEditor) -> bool {
        let language = editor.document().language_id.clone();
        let language = language.as_str();
        if language.is_empty() || language == "jsonc" || language == "log" {
            return false;
        }
        if self.setting("debug.allowBreakpointsEverywhere") == true {
            return true;
        }
        self.extensions.iter().any(|extension| extension.description["contributes"]["breakpoints"].as_array().is_some_and(|breakpoints| breakpoints.iter().any(|breakpoint| breakpoint["language"] == language)))
    }

    /// The selection of the active editor, else the word at its cursor (debugEditorActions.ts `getExpression`).
    fn selected_expression(&self) -> Option<String> {
        let editor = self.editors.active()?;
        let selection = editor.selections[0];
        if !selection.is_empty() {
            let (start, end) = if selection.anchor < selection.head { (selection.anchor, selection.head) } else { (selection.head, selection.anchor) };
            let lines = &editor.document().lines;
            let text: Vec<String> = (start.line..=end.line)
                .map(|line| {
                    let chars: Vec<char> = lines[line].chars().collect();
                    let from = if line == start.line { start.column } else { 0 };
                    let to = if line == end.line { end.column } else { chars.len() };
                    chars[from.min(chars.len())..to.min(chars.len())].iter().collect()
                })
                .collect();
            return Some(text.join("\n"));
        }
        let line: Vec<char> = editor.document().lines[selection.head.line].chars().collect();
        let is_word = |c: &char| c.is_alphanumeric() || *c == '_' || *c == '$';
        let mut start = selection.head.column.min(line.len());
        while start > 0 && is_word(&line[start - 1]) {
            start -= 1;
        }
        let mut end = selection.head.column.min(line.len());
        while end < line.len() && is_word(&line[end]) {
            end += 1;
        }
        (start < end).then(|| line[start..end].iter().collect())
    }

    /// debugCommands.ts CONFIGURE: the launch.json of the selected folder (`.vsrustium/` when the folder has one),
    /// created with the empty configuration list upstream writes without initial configurations.
    fn open_launch_json(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let (folder, _) = self.selected_launch();
        let Some(folder) = folder else { return Outcome::error("Open a folder or workspace to configure debugging.") };
        self.open_folder_launch_json(&folder, window, cx)
    }

    /// launch.ts `openConfigFile` of a folder's launch.json, created when missing.
    pub(super) fn open_folder_launch_json(&mut self, folder: &std::path::Path, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let file = config::service::folder_config_dir(&folder).join("launch.json");
        if !file.exists() {
            let content = "{\n\t// Use IntelliSense to learn about possible attributes.\n\t// Hover to view descriptions of existing attributes.\n\t// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n\t\"version\": \"0.2.0\",\n\t\"configurations\": []\n}";
            let written = file.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|_| std::fs::write(&file, content));
            if let Err(error) = written {
                return Outcome::error(format!("writing {}: {error}", file.display()));
            }
        }
        self.open_file(file, true, window, cx);
        Outcome::done()
    }

    /// debug.ts context keys.
    pub(super) fn debug_context(&self, window: &Window, context: &mut HashMap<String, Value>) {
        let state = self.debug.state();
        let focused = self.debug.focused_session();
        context.insert("debugState".into(), json!(state.context_value()));
        context.insert("inDebugMode".into(), json!(state != State::Inactive));
        context.insert("debuggersAvailable".into(), json!(!self.debug.debuggers.is_empty()));
        context.insert("debugType".into(), json!(focused.map(|session| session.session_type()).unwrap_or_default()));
        context.insert("focusedSessionIsAttach".into(), json!(focused.is_some_and(|session| session.configuration["request"] == "attach")));
        context.insert("multiSessionDebug".into(), json!(self.debug.multi_session_view));
        context.insert("focusedSessionIsNoDebug".into(), json!(focused.is_some_and(|session| session.configuration["noDebug"] == true)));
        for (key, capability) in [("terminateDebuggeeSupported", "supportTerminateDebuggee"), ("suspendDebuggeeSupported", "supportSuspendDebuggee"), ("terminateThreadsSupported", "supportsTerminateThreadsRequest"), ("debugSetVariableSupported", "supportsSetVariable"), ("debugSetExpressionSupported", "supportsSetExpression")] {
            context.insert(key.into(), json!(focused.is_some_and(|session| session.capabilities[capability] == true)));
        }
        context.insert("breakpointsExist".into(), json!(!self.debug.model.breakpoints.is_empty()));
        context.insert("watchExpressionsExist".into(), json!(!self.debug.model.watch_expressions.is_empty()));
        context.insert("variablesFocused".into(), json!(self.debug_view.list_focus[super::debug_view::VARIABLES_VIEW].is_focused(window)));
        context.insert("watchExpressionsFocused".into(), json!(self.debug_view.list_focus[super::debug_view::WATCH_VIEW].is_focused(window)));
        context.insert("expressionSelected".into(), json!(self.debug_view.editing.is_some()));
        context.insert("loadedScriptsSupported".into(), json!(focused.is_some_and(|session| session.capabilities["supportsLoadedSourcesRequest"] == true)));
        context.insert("stepBackSupported".into(), json!(focused.is_some_and(|session| session.capabilities["supportsStepBack"] == true)));
        context.insert("restartFrameSupported".into(), json!(focused.is_some_and(|session| session.capabilities["supportsRestartFrame"] == true)));
        let thread = focused.zip(self.debug.focus.thread).and_then(|(session, id)| session.thread(id));
        context.insert("threadHasMultipleStackFrames".into(), json!(thread.is_some_and(super::call_stack_menu::has_multiple_stack_frames)));
        context.insert("disassembleRequestSupported".into(), json!(focused.is_some_and(|session| session.capabilities["supportsDisassembleRequest"] == true)));
        context.insert("focusedStackFrameHasInstructionReference".into(), json!(self.debug.focused_frame().is_some_and(|frame| frame.instruction_pointer_reference.is_some())));
        context.insert("disassemblyViewFocus".into(), json!(self.disassembly_view_active()));
        self.disassembly_list_context(window, context);
        let language = self.editors.active().filter(|editor| editor.document().scheme == "file").map(|editor| editor.document().language_id.clone());
        context.insert("languageSupportsDisassembleRequest".into(), json!(language.is_some_and(|language| self.debug.debuggers.iter().any(|debugger| debugger.interested_in_language(&language)))));
        let simple = state == State::Inactive && !self.workspace_folders().iter().any(|folder| !self.folder_launch(folder).configurations.is_empty());
        context.insert("debugUx".into(), json!(if simple { "simple" } else { "default" }));
        for setting in ["debug.toolBarLocation", "debug.hideLauncherWhileDebugging"] {
            context.insert(format!("config.{setting}"), self.setting(setting));
        }
        context.insert(format!("viewContainer.{VIEWLET_ID}.enabled"), json!(true));
        context.insert(format!("{REPL_VIEW_ID}.active"), json!(true));
        context.insert("inDebugRepl".into(), json!(self.debug_console.focus.is_focused(window) || self.debug_console.input_focus.is_focused(window) || self.debug_console.find.focus.is_focused(window)));
        // repl.ts: the input is a code editor and a history navigation widget.
        if self.debug_console.input_focus.is_focused(window) {
            for key in ["textInputFocus", "inputFocus", "historyNavigationWidgetFocus", "historyNavigationForwardsEnabled", "historyNavigationBackwardsEnabled"] {
                context.insert(key.into(), json!(true));
            }
        }
        context.insert("breakpointWidgetVisible".into(), json!(self.breakpoint_widget.is_some()));
        context.insert("inBreakpointWidget".into(), json!(self.breakpoint_widget.is_some() && self.debug_view.widget_focus.is_focused(window)));
        if self.side_bar_view == SideBarView::Debug {
            context.insert("activeViewlet".into(), json!(VIEWLET_ID));
        }
    }
}

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

    use exthost::session::ForwardedRequest;
    use gpui::TestAppContext;

    use super::*;
    use crate::debug::session::Session;
    use crate::editor::{Position, Selection};

    #[gpui::test]
    fn run_to_cursor_continues_the_thread_that_verified_and_removes_its_breakpoint_at_the_stop(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-run-to-cursor-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("a.js");
        std::fs::write(&file, "1\n2\n3\n4\n5\n6\n7\n8\n").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| {
            for (id, handle, thread) in [("focused", 1, 1), ("other", 2, 5)] {
                let mut session = Session::new(id.into(), handle, json!({ "name": id, "type": "node", "request": "launch" }), json!({}), None, json!({}));
                session.initialized = true;
                session.set_threads(&[json!({ "id": thread, "name": "main" })]);
                session.stop_threads(&json!({ "reason": "pause", "threadId": thread }));
                workbench.debug.sessions.push(session);
            }
            workbench.debug.focus.session = Some("focused".into());
            workbench.debug.focus.thread = Some(1);
            workbench.open_file(file.clone(), true, window, cx);
            workbench.editors.active_mut().unwrap().selections = vec![Selection { anchor: Position::new(6, 0), head: Position::new(6, 0) }];
            drop(workbench.run_to_cursor(window, cx));
        });
        cx.run_until_parked();
        let requests = |host: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>| -> Vec<(Value, Value)> { host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| (message.args[0].clone(), message.args[1].clone())).collect() };
        let sent = requests(&host);
        assert!(!sent.iter().any(|(_, request)| request["command"] == "continue"), "the thread waits for the breakpoint");
        let accept = |handle: &Value, message: Value| ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![handle.clone(), message] };
        for (handle, request) in sent.iter().filter(|(_, request)| request["command"] == "setBreakpoints") {
            // Only the other session's adapter binds the breakpoint.
            let breakpoints = if *handle == 2 { json!([{ "verified": true, "line": 7 }]) } else { json!([]) };
            let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": "setBreakpoints", "body": { "breakpoints": breakpoints } });
            workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept(handle, response), window, cx)));
        }
        cx.run_until_parked();
        let continued: Vec<(Value, Value)> = requests(&host).into_iter().filter(|(_, request)| request["command"] == "continue").collect();
        assert_eq!(continued.len(), 1);
        assert_eq!((continued[0].0.clone(), continued[0].1["arguments"]["threadId"].clone()), (json!(2), json!(5)), "the stopped thread of the session that verified, not the focused one");
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug.model.breakpoints.len()), 1);

        let stopped = json!({ "type": "event", "seq": 0, "event": "stopped", "body": { "reason": "breakpoint", "threadId": 5 } });
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept(&json!(2), stopped), window, cx)));
        cx.run_until_parked();
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.debug.model.breakpoints.len()), 0, "the stop removes the breakpoint");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[gpui::test]
    fn a_start_or_restart_saves_the_dirty_editors_unless_a_child_session_or_suppressed(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-save-before-start-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("a.js");
        std::fs::write(&file, "").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| {
            workbench.debug.adapter_types.push("mock".into());
            workbench.open_file(file.clone(), true, window, cx);
        });
        let mut start = |options: Value, typed: &str| {
            cx.simulate_input(typed);
            workbench.update_in(cx, |workbench, window, cx| drop(workbench.start_debugging(None, json!({ "type": "mock", "request": "launch", "name": "Mock" }), options, DebugTasks::PreLaunch, window, cx)));
            for _ in 0..10 {
                cx.run_until_parked();
                for message in host.try_iter() {
                    if let Some(reply) = message.reply {
                        let _ = reply.send(Ok(Value::Null));
                    }
                }
            }
            std::fs::read_to_string(&file).unwrap()
        };
        assert_eq!(start(json!({ "parentSessionID": "parent" }), "a"), "", "a child session saves nothing");
        assert_eq!(start(json!({ "suppressSaveBeforeStart": true }), "b"), "");
        assert_eq!(start(json!({}), "c"), "abc");

        cx.simulate_input("d");
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.sessions.push(Session::new("s".into(), 1, json!({ "name": "Mock", "type": "mock", "request": "launch" }), json!({}), None, json!({})));
            drop(workbench.restart_session("s".into(), None, window, cx));
        });
        cx.run_until_parked();
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "abcd", "saveBeforeRestart");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[gpui::test]
    fn a_hit_breakpoint_enables_its_dependents_in_the_session_before_it_resumes(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let (sender, host) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
        let uri = crate::debug::uri_from_string("file:///tmp/a.js");
        let dependent = workbench.update_in(cx, |workbench, _, _| {
            let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.initialized = true;
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            workbench.debug.sessions.push(session);
            workbench.debug.focus.session = Some("s".into());
            workbench.debug.focus.thread = Some(1);
            let trigger = workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData::at(2)]).added[0].clone();
            let data = crate::debug::SessionData::from_dap(&json!({ "id": 7, "verified": true, "line": 2 }), &json!({}));
            workbench.debug.model.breakpoint_mut(&trigger).unwrap().set_session_data("s", Some(data));
            workbench.debug.model.add_breakpoints(&uri, vec![BreakpointData { triggered_by: Some(trigger), ..BreakpointData::at(5) }]).added[0].clone()
        });
        let accept = |message: Value| ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), message] };
        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 respond = |request: &Value, body: Value| accept(json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": request["command"], "body": body }));
        let did_trigger = |workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.debug.model.breakpoint(&dependent).unwrap().sessions_did_trigger.clone());

        let stopped = json!({ "type": "event", "seq": 0, "event": "stopped", "body": { "reason": "breakpoint", "threadId": 1, "hitBreakpointIds": [7] } });
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept(stopped), window, cx)));
        cx.run_until_parked();
        assert_eq!(did_trigger(&workbench, cx), vec!["s".to_owned()]);
        let sent = requests(&host);
        let set = sent.iter().find(|request| request["command"] == "setBreakpoints").expect("the file is sent again").clone();
        assert_eq!(set["arguments"]["lines"], json!([2, 5]));
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.debug.continue", Vec::new(), window, cx)));
        cx.run_until_parked();
        assert!(!requests(&host).iter().any(|request| request["command"] == "continue"), "continue waits for the dependent breakpoints");
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(respond(&set, json!({ "breakpoints": [] })), window, cx)));
        cx.run_until_parked();
        assert!(requests(&host).iter().any(|request| request["command"] == "continue"));

        // Without `hitBreakpointIds` the top frame's position finds the hit breakpoint.
        workbench.update(cx, |workbench, _| workbench.debug.model.breakpoints.iter_mut().for_each(|breakpoint| breakpoint.sessions_did_trigger.clear()));
        let stopped = json!({ "type": "event", "seq": 0, "event": "stopped", "body": { "reason": "breakpoint", "threadId": 1 } });
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept(stopped), window, cx)));
        for (command, body) in [("threads", json!({ "threads": [{ "id": 1, "name": "main" }] })), ("stackTrace", json!({ "stackFrames": [{ "id": 1, "name": "f", "line": 2, "column": 1, "source": { "path": "/tmp/a.js" } }] }))] {
            cx.run_until_parked();
            let request = requests(&host).into_iter().find(|request| request["command"] == command).unwrap();
            workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(respond(&request, body), window, cx)));
        }
        cx.run_until_parked();
        assert_eq!(did_trigger(&workbench, cx), vec!["s".to_owned()]);

        workbench.update_in(cx, |workbench, window, cx| drop(workbench.restart_session("s".into(), None, window, cx)));
        cx.run_until_parked();
        assert!(did_trigger(&workbench, cx).is_empty(), "a restart clears the session's triggers");
    }

    #[gpui::test]
    fn a_step_in_the_disassembly_view_steps_one_instruction(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let (sender, host) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
        workbench.update_in(cx, |workbench, _, _| {
            let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.initialized = true;
            session.capabilities = json!({ "supportsDisassembleRequest": true, "supportsSteppingGranularity": true });
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            session.stop_threads(&json!({ "reason": "step", "threadId": 1 }));
            workbench.debug.sessions.push(session);
            workbench.debug.focus.session = Some("s".into());
            workbench.debug.focus.thread = Some(1);
        });
        let step = |cx: &mut gpui::VisualTestContext| {
            workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.debug.stepOver", Vec::new(), window, cx)));
            cx.run_until_parked();
            host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).find(|request| request["command"] == "next").unwrap()["arguments"]["granularity"].clone()
        };
        assert_eq!(step(cx), Value::Null, "a step in a text editor leaves the granularity to the adapter");
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.sessions[0].stop_threads(&json!({ "reason": "step", "threadId": 1 }));
            workbench.open_disassembly_view(window, cx);
        });
        assert_eq!(step(cx), json!("instruction"));
    }

    #[gpui::test]
    fn a_stop_on_a_line_in_view_keeps_the_scroll(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-stop-scroll-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("a.js");
        std::fs::write(&file, "x\n".repeat(100)).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));
        let viewport = crate::editor::Viewport { width: 800., height: 100., char_width: 8., ..Default::default() };
        let scroll_top_at_stop = |line: u32, laid_out: bool, cx: &mut gpui::VisualTestContext| {
            workbench.update_in(cx, |workbench, window, cx| {
                workbench.editors.viewport = if laid_out { viewport } else { Default::default() };
                let mut session = Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
                session.set_threads(&[json!({ "id": 1, "name": "main" })]);
                let frame = crate::debug::session::StackFrame { id: 3, source: json!({ "path": file.to_string_lossy() }), line, column: 1, ..Default::default() };
                session.thread_mut(1).unwrap().frames = vec![frame];
                workbench.debug.sessions = vec![session];
                let focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(3) };
                workbench.set_debug_focus(focus, super::super::debug_service::Reveal::TakingFocus, window, cx);
                if !laid_out {
                    workbench.editor_laid_out(viewport, None, cx);
                }
                workbench.editors.active().unwrap().scroll.top
            })
        };
        assert_eq!(scroll_top_at_stop(5, true, cx), 0., "line 5 is in the 100px view");
        assert!(scroll_top_at_stop(80, true, cx) > 0., "line 80 is outside it and is centered");
        workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().scroll.top = 0.);
        assert_eq!(scroll_top_at_stop(5, false, cx), 0., "an editor not laid out yet reveals at its size");
        std::fs::remove_dir_all(dir).unwrap();
    }
}