1use crate::debugger::breakpoint_store::BreakpointSessionState;
2
3use super::breakpoint_store::{
4 BreakpointStore, BreakpointStoreEvent, BreakpointUpdatedReason, SourceBreakpoint,
5};
6use super::dap_command::{
7 self, Attach, ConfigurationDone, ContinueCommand, DapCommand, DisconnectCommand,
8 EvaluateCommand, Initialize, Launch, LoadedSourcesCommand, LocalDapCommand, LocationsCommand,
9 ModulesCommand, NextCommand, PauseCommand, RestartCommand, RestartStackFrameCommand,
10 ScopesCommand, SetExceptionBreakpoints, SetVariableValueCommand, StackTraceCommand,
11 StepBackCommand, StepCommand, StepInCommand, StepOutCommand, TerminateCommand,
12 TerminateThreadsCommand, ThreadsCommand, VariablesCommand,
13};
14use super::dap_store::DapStore;
15use anyhow::{Context as _, Result, anyhow};
16use collections::{HashMap, HashSet, IndexMap};
17use dap::adapters::{DebugAdapterBinary, DebugAdapterName};
18use dap::messages::Response;
19use dap::requests::{Request, RunInTerminal, StartDebugging};
20use dap::{
21 Capabilities, ContinueArguments, EvaluateArgumentsContext, Module, Source, StackFrameId,
22 SteppingGranularity, StoppedEvent, VariableReference,
23 client::{DebugAdapterClient, SessionId},
24 messages::{Events, Message},
25};
26use dap::{
27 ExceptionBreakpointsFilter, ExceptionFilterOptions, OutputEvent, OutputEventCategory,
28 RunInTerminalRequestArguments, StackFramePresentationHint, StartDebuggingRequestArguments,
29 StartDebuggingRequestArgumentsRequest, VariablePresentationHint,
30};
31use futures::SinkExt;
32use futures::channel::mpsc::UnboundedSender;
33use futures::channel::{mpsc, oneshot};
34use futures::{FutureExt, future::Shared};
35use gpui::{
36 App, AppContext, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, SharedString,
37 Task, WeakEntity,
38};
39
40use rpc::ErrorExt;
41use serde_json::Value;
42use smol::stream::StreamExt;
43use std::any::TypeId;
44use std::collections::BTreeMap;
45use std::u64;
46use std::{
47 any::Any,
48 collections::hash_map::Entry,
49 hash::{Hash, Hasher},
50 path::Path,
51 sync::Arc,
52};
53use task::TaskContext;
54use text::{PointUtf16, ToPointUtf16};
55use util::ResultExt;
56use worktree::Worktree;
57
58#[derive(Debug, Copy, Clone, Hash, PartialEq, PartialOrd, Ord, Eq)]
59#[repr(transparent)]
60pub struct ThreadId(pub u64);
61
62impl ThreadId {
63 pub const MIN: ThreadId = ThreadId(u64::MIN);
64 pub const MAX: ThreadId = ThreadId(u64::MAX);
65}
66
67impl From<u64> for ThreadId {
68 fn from(id: u64) -> Self {
69 Self(id)
70 }
71}
72
73#[derive(Clone, Debug)]
74pub struct StackFrame {
75 pub dap: dap::StackFrame,
76 pub scopes: Vec<dap::Scope>,
77}
78
79impl From<dap::StackFrame> for StackFrame {
80 fn from(stack_frame: dap::StackFrame) -> Self {
81 Self {
82 scopes: vec![],
83 dap: stack_frame,
84 }
85 }
86}
87
88#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
89pub enum ThreadStatus {
90 #[default]
91 Running,
92 Stopped,
93 Stepping,
94 Exited,
95 Ended,
96}
97
98impl ThreadStatus {
99 pub fn label(&self) -> &'static str {
100 match self {
101 ThreadStatus::Running => "Running",
102 ThreadStatus::Stopped => "Stopped",
103 ThreadStatus::Stepping => "Stepping",
104 ThreadStatus::Exited => "Exited",
105 ThreadStatus::Ended => "Ended",
106 }
107 }
108}
109
110#[derive(Debug)]
111pub struct Thread {
112 dap: dap::Thread,
113 stack_frames: Vec<StackFrame>,
114 stack_frames_error: Option<anyhow::Error>,
115 _has_stopped: bool,
116}
117
118impl From<dap::Thread> for Thread {
119 fn from(dap: dap::Thread) -> Self {
120 Self {
121 dap,
122 stack_frames: Default::default(),
123 stack_frames_error: None,
124 _has_stopped: false,
125 }
126 }
127}
128
129#[derive(Debug, Clone, PartialEq)]
130pub struct Watcher {
131 pub expression: SharedString,
132 pub value: SharedString,
133 pub variables_reference: u64,
134 pub presentation_hint: Option<VariablePresentationHint>,
135}
136
137pub enum Mode {
138 Building,
139 Running(RunningMode),
140}
141
142#[derive(Clone)]
143pub struct RunningMode {
144 client: Arc<DebugAdapterClient>,
145 binary: DebugAdapterBinary,
146 tmp_breakpoint: Option<SourceBreakpoint>,
147 worktree: WeakEntity<Worktree>,
148 executor: BackgroundExecutor,
149 is_started: bool,
150 has_ever_stopped: bool,
151 messages_tx: UnboundedSender<Message>,
152}
153
154fn client_source(abs_path: &Path) -> dap::Source {
155 dap::Source {
156 name: abs_path
157 .file_name()
158 .map(|filename| filename.to_string_lossy().to_string()),
159 path: Some(abs_path.to_string_lossy().to_string()),
160 source_reference: None,
161 presentation_hint: None,
162 origin: None,
163 sources: None,
164 adapter_data: None,
165 checksums: None,
166 }
167}
168
169impl RunningMode {
170 async fn new(
171 session_id: SessionId,
172 parent_session: Option<Entity<Session>>,
173 worktree: WeakEntity<Worktree>,
174 binary: DebugAdapterBinary,
175 messages_tx: futures::channel::mpsc::UnboundedSender<Message>,
176 cx: &mut AsyncApp,
177 ) -> Result<Self> {
178 let message_handler = Box::new({
179 let messages_tx = messages_tx.clone();
180 move |message| {
181 messages_tx.unbounded_send(message).ok();
182 }
183 });
184
185 let client = if let Some(client) = parent_session
186 .and_then(|session| cx.update(|cx| session.read(cx).adapter_client()).ok())
187 .flatten()
188 {
189 client
190 .create_child_connection(session_id, binary.clone(), message_handler, cx)
191 .await?
192 } else {
193 DebugAdapterClient::start(session_id, binary.clone(), message_handler, cx).await?
194 };
195
196 Ok(Self {
197 client: Arc::new(client),
198 worktree,
199 tmp_breakpoint: None,
200 binary,
201 executor: cx.background_executor().clone(),
202 is_started: false,
203 has_ever_stopped: false,
204 messages_tx,
205 })
206 }
207
208 pub(crate) fn worktree(&self) -> &WeakEntity<Worktree> {
209 &self.worktree
210 }
211
212 fn unset_breakpoints_from_paths(&self, paths: &Vec<Arc<Path>>, cx: &mut App) -> Task<()> {
213 let tasks: Vec<_> = paths
214 .into_iter()
215 .map(|path| {
216 self.request(dap_command::SetBreakpoints {
217 source: client_source(path),
218 source_modified: None,
219 breakpoints: vec![],
220 })
221 })
222 .collect();
223
224 cx.background_spawn(async move {
225 futures::future::join_all(tasks)
226 .await
227 .iter()
228 .for_each(|res| match res {
229 Ok(_) => {}
230 Err(err) => {
231 log::warn!("Set breakpoints request failed: {}", err);
232 }
233 });
234 })
235 }
236
237 fn send_breakpoints_from_path(
238 &self,
239 abs_path: Arc<Path>,
240 reason: BreakpointUpdatedReason,
241 breakpoint_store: &Entity<BreakpointStore>,
242 cx: &mut App,
243 ) -> Task<()> {
244 let breakpoints =
245 breakpoint_store
246 .read(cx)
247 .source_breakpoints_from_path(&abs_path, cx)
248 .into_iter()
249 .filter(|bp| bp.state.is_enabled())
250 .chain(self.tmp_breakpoint.iter().filter_map(|breakpoint| {
251 breakpoint.path.eq(&abs_path).then(|| breakpoint.clone())
252 }))
253 .map(Into::into)
254 .collect();
255
256 let raw_breakpoints = breakpoint_store
257 .read(cx)
258 .breakpoints_from_path(&abs_path)
259 .into_iter()
260 .filter(|bp| bp.bp.state.is_enabled())
261 .collect::<Vec<_>>();
262
263 let task = self.request(dap_command::SetBreakpoints {
264 source: client_source(&abs_path),
265 source_modified: Some(matches!(reason, BreakpointUpdatedReason::FileSaved)),
266 breakpoints,
267 });
268 let session_id = self.client.id();
269 let breakpoint_store = breakpoint_store.downgrade();
270 cx.spawn(async move |cx| match cx.background_spawn(task).await {
271 Ok(breakpoints) => {
272 let breakpoints =
273 breakpoints
274 .into_iter()
275 .zip(raw_breakpoints)
276 .filter_map(|(dap_bp, zed_bp)| {
277 Some((
278 zed_bp,
279 BreakpointSessionState {
280 id: dap_bp.id?,
281 verified: dap_bp.verified,
282 },
283 ))
284 });
285 breakpoint_store
286 .update(cx, |this, _| {
287 this.mark_breakpoints_verified(session_id, &abs_path, breakpoints);
288 })
289 .ok();
290 }
291 Err(err) => log::warn!("Set breakpoints request failed for path: {}", err),
292 })
293 }
294
295 fn send_exception_breakpoints(
296 &self,
297 filters: Vec<ExceptionBreakpointsFilter>,
298 supports_filter_options: bool,
299 ) -> Task<Result<Vec<dap::Breakpoint>>> {
300 let arg = if supports_filter_options {
301 SetExceptionBreakpoints::WithOptions {
302 filters: filters
303 .into_iter()
304 .map(|filter| ExceptionFilterOptions {
305 filter_id: filter.filter,
306 condition: None,
307 mode: None,
308 })
309 .collect(),
310 }
311 } else {
312 SetExceptionBreakpoints::Plain {
313 filters: filters.into_iter().map(|filter| filter.filter).collect(),
314 }
315 };
316 self.request(arg)
317 }
318
319 fn send_source_breakpoints(
320 &self,
321 ignore_breakpoints: bool,
322 breakpoint_store: &Entity<BreakpointStore>,
323 cx: &App,
324 ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
325 let mut breakpoint_tasks = Vec::new();
326 let breakpoints = breakpoint_store.read(cx).all_source_breakpoints(cx);
327 let mut raw_breakpoints = breakpoint_store.read_with(cx, |this, _| this.all_breakpoints());
328 debug_assert_eq!(raw_breakpoints.len(), breakpoints.len());
329 let session_id = self.client.id();
330 for (path, breakpoints) in breakpoints {
331 let breakpoints = if ignore_breakpoints {
332 vec![]
333 } else {
334 breakpoints
335 .into_iter()
336 .filter(|bp| bp.state.is_enabled())
337 .map(Into::into)
338 .collect()
339 };
340
341 let raw_breakpoints = raw_breakpoints
342 .remove(&path)
343 .unwrap_or_default()
344 .into_iter()
345 .filter(|bp| bp.bp.state.is_enabled());
346 let error_path = path.clone();
347 let send_request = self
348 .request(dap_command::SetBreakpoints {
349 source: client_source(&path),
350 source_modified: Some(false),
351 breakpoints,
352 })
353 .map(|result| result.map_err(move |e| (error_path, e)));
354
355 let task = cx.spawn({
356 let breakpoint_store = breakpoint_store.downgrade();
357 async move |cx| {
358 let breakpoints = cx.background_spawn(send_request).await?;
359
360 let breakpoints = breakpoints.into_iter().zip(raw_breakpoints).filter_map(
361 |(dap_bp, zed_bp)| {
362 Some((
363 zed_bp,
364 BreakpointSessionState {
365 id: dap_bp.id?,
366 verified: dap_bp.verified,
367 },
368 ))
369 },
370 );
371 breakpoint_store
372 .update(cx, |this, _| {
373 this.mark_breakpoints_verified(session_id, &path, breakpoints);
374 })
375 .ok();
376
377 Ok(())
378 }
379 });
380 breakpoint_tasks.push(task);
381 }
382
383 cx.background_spawn(async move {
384 futures::future::join_all(breakpoint_tasks)
385 .await
386 .into_iter()
387 .filter_map(Result::err)
388 .collect::<HashMap<_, _>>()
389 })
390 }
391
392 fn initialize_sequence(
393 &self,
394 capabilities: &Capabilities,
395 initialized_rx: oneshot::Receiver<()>,
396 dap_store: WeakEntity<DapStore>,
397 cx: &mut Context<Session>,
398 ) -> Task<Result<()>> {
399 let raw = self.binary.request_args.clone();
400
401 // Of relevance: https://github.com/microsoft/vscode/issues/4902#issuecomment-368583522
402 let launch = match raw.request {
403 dap::StartDebuggingRequestArgumentsRequest::Launch => self.request(Launch {
404 raw: raw.configuration,
405 }),
406 dap::StartDebuggingRequestArgumentsRequest::Attach => self.request(Attach {
407 raw: raw.configuration,
408 }),
409 };
410
411 let configuration_done_supported = ConfigurationDone::is_supported(capabilities);
412 let exception_filters = capabilities
413 .exception_breakpoint_filters
414 .as_ref()
415 .map(|exception_filters| {
416 exception_filters
417 .iter()
418 .filter(|filter| filter.default == Some(true))
419 .cloned()
420 .collect::<Vec<_>>()
421 })
422 .unwrap_or_default();
423 let supports_exception_filters = capabilities
424 .supports_exception_filter_options
425 .unwrap_or_default();
426 let this = self.clone();
427 let worktree = self.worktree().clone();
428 let configuration_sequence = cx.spawn({
429 async move |_, cx| {
430 let breakpoint_store =
431 dap_store.read_with(cx, |dap_store, _| dap_store.breakpoint_store().clone())?;
432 initialized_rx.await?;
433 let errors_by_path = cx
434 .update(|cx| this.send_source_breakpoints(false, &breakpoint_store, cx))?
435 .await;
436
437 dap_store.update(cx, |_, cx| {
438 let Some(worktree) = worktree.upgrade() else {
439 return;
440 };
441
442 for (path, error) in &errors_by_path {
443 log::error!("failed to set breakpoints for {path:?}: {error}");
444 }
445
446 if let Some(failed_path) = errors_by_path.keys().next() {
447 let failed_path = failed_path
448 .strip_prefix(worktree.read(cx).abs_path())
449 .unwrap_or(failed_path)
450 .display();
451 let message = format!(
452 "Failed to set breakpoints for {failed_path}{}",
453 match errors_by_path.len() {
454 0 => unreachable!(),
455 1 => "".into(),
456 2 => " and 1 other path".into(),
457 n => format!(" and {} other paths", n - 1),
458 }
459 );
460 cx.emit(super::dap_store::DapStoreEvent::Notification(message));
461 }
462 })?;
463
464 this.send_exception_breakpoints(exception_filters, supports_exception_filters)
465 .await
466 .ok();
467 let ret = if configuration_done_supported {
468 this.request(ConfigurationDone {})
469 } else {
470 Task::ready(Ok(()))
471 }
472 .await;
473 ret
474 }
475 });
476
477 let task = cx.background_spawn(futures::future::try_join(launch, configuration_sequence));
478
479 cx.spawn(async move |this, cx| {
480 let result = task.await;
481
482 this.update(cx, |this, cx| {
483 if let Some(this) = this.as_running_mut() {
484 this.is_started = true;
485 cx.notify();
486 }
487 })
488 .ok();
489
490 result?;
491 anyhow::Ok(())
492 })
493 }
494
495 fn reconnect_for_ssh(&self, cx: &mut AsyncApp) -> Option<Task<Result<()>>> {
496 let client = self.client.clone();
497 let messages_tx = self.messages_tx.clone();
498 let message_handler = Box::new(move |message| {
499 messages_tx.unbounded_send(message).ok();
500 });
501 if client.should_reconnect_for_ssh() {
502 Some(cx.spawn(async move |cx| {
503 client.connect(message_handler, cx).await?;
504 anyhow::Ok(())
505 }))
506 } else {
507 None
508 }
509 }
510
511 fn request<R: LocalDapCommand>(&self, request: R) -> Task<Result<R::Response>>
512 where
513 <R::DapRequest as dap::requests::Request>::Response: 'static,
514 <R::DapRequest as dap::requests::Request>::Arguments: 'static + Send,
515 {
516 let request = Arc::new(request);
517
518 let request_clone = request.clone();
519 let connection = self.client.clone();
520 self.executor.spawn(async move {
521 let args = request_clone.to_dap();
522 let response = connection.request::<R::DapRequest>(args).await?;
523 request.response_from_dap(response)
524 })
525 }
526}
527
528impl Mode {
529 pub(super) fn request_dap<R: DapCommand>(&self, request: R) -> Task<Result<R::Response>>
530 where
531 <R::DapRequest as dap::requests::Request>::Response: 'static,
532 <R::DapRequest as dap::requests::Request>::Arguments: 'static + Send,
533 {
534 match self {
535 Mode::Running(debug_adapter_client) => debug_adapter_client.request(request),
536 Mode::Building => Task::ready(Err(anyhow!(
537 "no adapter running to send request: {request:?}"
538 ))),
539 }
540 }
541
542 /// Did this debug session stop at least once?
543 pub(crate) fn has_ever_stopped(&self) -> bool {
544 match self {
545 Mode::Building => false,
546 Mode::Running(running_mode) => running_mode.has_ever_stopped,
547 }
548 }
549
550 fn stopped(&mut self) {
551 if let Mode::Running(running) = self {
552 running.has_ever_stopped = true;
553 }
554 }
555}
556
557#[derive(Default)]
558struct ThreadStates {
559 global_state: Option<ThreadStatus>,
560 known_thread_states: IndexMap<ThreadId, ThreadStatus>,
561}
562
563impl ThreadStates {
564 fn stop_all_threads(&mut self) {
565 self.global_state = Some(ThreadStatus::Stopped);
566 self.known_thread_states.clear();
567 }
568
569 fn exit_all_threads(&mut self) {
570 self.global_state = Some(ThreadStatus::Exited);
571 self.known_thread_states.clear();
572 }
573
574 fn continue_all_threads(&mut self) {
575 self.global_state = Some(ThreadStatus::Running);
576 self.known_thread_states.clear();
577 }
578
579 fn stop_thread(&mut self, thread_id: ThreadId) {
580 self.known_thread_states
581 .insert(thread_id, ThreadStatus::Stopped);
582 }
583
584 fn continue_thread(&mut self, thread_id: ThreadId) {
585 self.known_thread_states
586 .insert(thread_id, ThreadStatus::Running);
587 }
588
589 fn process_step(&mut self, thread_id: ThreadId) {
590 self.known_thread_states
591 .insert(thread_id, ThreadStatus::Stepping);
592 }
593
594 fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
595 self.thread_state(thread_id)
596 .unwrap_or(ThreadStatus::Running)
597 }
598
599 fn thread_state(&self, thread_id: ThreadId) -> Option<ThreadStatus> {
600 self.known_thread_states
601 .get(&thread_id)
602 .copied()
603 .or(self.global_state)
604 }
605
606 fn exit_thread(&mut self, thread_id: ThreadId) {
607 self.known_thread_states
608 .insert(thread_id, ThreadStatus::Exited);
609 }
610
611 fn any_stopped_thread(&self) -> bool {
612 self.global_state
613 .is_some_and(|state| state == ThreadStatus::Stopped)
614 || self
615 .known_thread_states
616 .values()
617 .any(|status| *status == ThreadStatus::Stopped)
618 }
619}
620const MAX_TRACKED_OUTPUT_EVENTS: usize = 5000;
621
622type IsEnabled = bool;
623
624#[derive(Copy, Clone, Default, Debug, PartialEq, PartialOrd, Eq, Ord)]
625pub struct OutputToken(pub usize);
626/// Represents a current state of a single debug adapter and provides ways to mutate it.
627pub struct Session {
628 pub mode: Mode,
629 id: SessionId,
630 label: SharedString,
631 adapter: DebugAdapterName,
632 pub(super) capabilities: Capabilities,
633 child_session_ids: HashSet<SessionId>,
634 parent_session: Option<Entity<Session>>,
635 modules: Vec<dap::Module>,
636 loaded_sources: Vec<dap::Source>,
637 output_token: OutputToken,
638 output: Box<circular_buffer::CircularBuffer<MAX_TRACKED_OUTPUT_EVENTS, dap::OutputEvent>>,
639 threads: IndexMap<ThreadId, Thread>,
640 thread_states: ThreadStates,
641 watchers: HashMap<SharedString, Watcher>,
642 variables: HashMap<VariableReference, Vec<dap::Variable>>,
643 stack_frames: IndexMap<StackFrameId, StackFrame>,
644 locations: HashMap<u64, dap::LocationsResponse>,
645 is_session_terminated: bool,
646 requests: HashMap<TypeId, HashMap<RequestSlot, Shared<Task<Option<()>>>>>,
647 pub(crate) breakpoint_store: Entity<BreakpointStore>,
648 ignore_breakpoints: bool,
649 exception_breakpoints: BTreeMap<String, (ExceptionBreakpointsFilter, IsEnabled)>,
650 background_tasks: Vec<Task<()>>,
651 task_context: TaskContext,
652}
653
654trait CacheableCommand: Any + Send + Sync {
655 fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool;
656 fn dyn_hash(&self, hasher: &mut dyn Hasher);
657 fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
658}
659
660impl<T> CacheableCommand for T
661where
662 T: DapCommand + PartialEq + Eq + Hash,
663{
664 fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool {
665 (rhs as &dyn Any)
666 .downcast_ref::<Self>()
667 .map_or(false, |rhs| self == rhs)
668 }
669
670 fn dyn_hash(&self, mut hasher: &mut dyn Hasher) {
671 T::hash(self, &mut hasher);
672 }
673
674 fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
675 self
676 }
677}
678
679pub(crate) struct RequestSlot(Arc<dyn CacheableCommand>);
680
681impl<T: DapCommand + PartialEq + Eq + Hash> From<T> for RequestSlot {
682 fn from(request: T) -> Self {
683 Self(Arc::new(request))
684 }
685}
686
687impl PartialEq for RequestSlot {
688 fn eq(&self, other: &Self) -> bool {
689 self.0.dyn_eq(other.0.as_ref())
690 }
691}
692
693impl Eq for RequestSlot {}
694
695impl Hash for RequestSlot {
696 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
697 self.0.dyn_hash(state);
698 (&*self.0 as &dyn Any).type_id().hash(state)
699 }
700}
701
702#[derive(Debug, Clone, Hash, PartialEq, Eq)]
703pub struct CompletionsQuery {
704 pub query: String,
705 pub column: u64,
706 pub line: Option<u64>,
707 pub frame_id: Option<u64>,
708}
709
710impl CompletionsQuery {
711 pub fn new(
712 buffer: &language::Buffer,
713 cursor_position: language::Anchor,
714 frame_id: Option<u64>,
715 ) -> Self {
716 let PointUtf16 { row, column } = cursor_position.to_point_utf16(&buffer.snapshot());
717 Self {
718 query: buffer.text(),
719 column: column as u64,
720 frame_id,
721 line: Some(row as u64),
722 }
723 }
724}
725
726#[derive(Debug)]
727pub enum SessionEvent {
728 Modules,
729 LoadedSources,
730 Stopped(Option<ThreadId>),
731 StackTrace,
732 Variables,
733 Watchers,
734 Threads,
735 InvalidateInlineValue,
736 CapabilitiesLoaded,
737 RunInTerminal {
738 request: RunInTerminalRequestArguments,
739 sender: mpsc::Sender<Result<u32>>,
740 },
741 ConsoleOutput,
742}
743
744#[derive(Clone, Debug, PartialEq, Eq)]
745pub enum SessionStateEvent {
746 Running,
747 Shutdown,
748 Restart,
749 SpawnChildSession {
750 request: StartDebuggingRequestArguments,
751 },
752}
753
754impl EventEmitter<SessionEvent> for Session {}
755impl EventEmitter<SessionStateEvent> for Session {}
756
757// local session will send breakpoint updates to DAP for all new breakpoints
758// remote side will only send breakpoint updates when it is a breakpoint created by that peer
759// BreakpointStore notifies session on breakpoint changes
760impl Session {
761 pub(crate) fn new(
762 breakpoint_store: Entity<BreakpointStore>,
763 session_id: SessionId,
764 parent_session: Option<Entity<Session>>,
765 label: SharedString,
766 adapter: DebugAdapterName,
767 task_context: TaskContext,
768 cx: &mut App,
769 ) -> Entity<Self> {
770 cx.new::<Self>(|cx| {
771 cx.subscribe(&breakpoint_store, |this, store, event, cx| match event {
772 BreakpointStoreEvent::BreakpointsUpdated(path, reason) => {
773 if let Some(local) = (!this.ignore_breakpoints)
774 .then(|| this.as_running_mut())
775 .flatten()
776 {
777 local
778 .send_breakpoints_from_path(path.clone(), *reason, &store, cx)
779 .detach();
780 };
781 }
782 BreakpointStoreEvent::BreakpointsCleared(paths) => {
783 if let Some(local) = (!this.ignore_breakpoints)
784 .then(|| this.as_running_mut())
785 .flatten()
786 {
787 local.unset_breakpoints_from_paths(paths, cx).detach();
788 }
789 }
790 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
791 })
792 .detach();
793 // cx.on_app_quit(Self::on_app_quit).detach();
794
795 let this = Self {
796 mode: Mode::Building,
797 id: session_id,
798 child_session_ids: HashSet::default(),
799 parent_session,
800 capabilities: Capabilities::default(),
801 watchers: HashMap::default(),
802 variables: Default::default(),
803 stack_frames: Default::default(),
804 thread_states: ThreadStates::default(),
805 output_token: OutputToken(0),
806 output: circular_buffer::CircularBuffer::boxed(),
807 requests: HashMap::default(),
808 modules: Vec::default(),
809 loaded_sources: Vec::default(),
810 threads: IndexMap::default(),
811 background_tasks: Vec::default(),
812 locations: Default::default(),
813 is_session_terminated: false,
814 ignore_breakpoints: false,
815 breakpoint_store,
816 exception_breakpoints: Default::default(),
817 label,
818 adapter,
819 task_context,
820 };
821
822 this
823 })
824 }
825
826 pub fn task_context(&self) -> &TaskContext {
827 &self.task_context
828 }
829
830 pub fn worktree(&self) -> Option<Entity<Worktree>> {
831 match &self.mode {
832 Mode::Building => None,
833 Mode::Running(local_mode) => local_mode.worktree.upgrade(),
834 }
835 }
836
837 pub fn boot(
838 &mut self,
839 binary: DebugAdapterBinary,
840 worktree: Entity<Worktree>,
841 dap_store: WeakEntity<DapStore>,
842 cx: &mut Context<Self>,
843 ) -> Task<Result<()>> {
844 let (message_tx, mut message_rx) = futures::channel::mpsc::unbounded();
845 let (initialized_tx, initialized_rx) = futures::channel::oneshot::channel();
846
847 let background_tasks = vec![cx.spawn(async move |this: WeakEntity<Session>, cx| {
848 let mut initialized_tx = Some(initialized_tx);
849 while let Some(message) = message_rx.next().await {
850 if let Message::Event(event) = message {
851 if let Events::Initialized(_) = *event {
852 if let Some(tx) = initialized_tx.take() {
853 tx.send(()).ok();
854 }
855 } else {
856 let Ok(_) = this.update(cx, |session, cx| {
857 session.handle_dap_event(event, cx);
858 }) else {
859 break;
860 };
861 }
862 } else if let Message::Request(request) = message {
863 let Ok(_) = this.update(cx, |this, cx| {
864 if request.command == StartDebugging::COMMAND {
865 this.handle_start_debugging_request(request, cx)
866 .detach_and_log_err(cx);
867 } else if request.command == RunInTerminal::COMMAND {
868 this.handle_run_in_terminal_request(request, cx)
869 .detach_and_log_err(cx);
870 }
871 }) else {
872 break;
873 };
874 }
875 }
876 })];
877 self.background_tasks = background_tasks;
878 let id = self.id;
879 let parent_session = self.parent_session.clone();
880
881 cx.spawn(async move |this, cx| {
882 let mode = RunningMode::new(
883 id,
884 parent_session,
885 worktree.downgrade(),
886 binary.clone(),
887 message_tx,
888 cx,
889 )
890 .await?;
891 this.update(cx, |this, cx| {
892 this.mode = Mode::Running(mode);
893 cx.emit(SessionStateEvent::Running);
894 })?;
895
896 this.update(cx, |session, cx| session.request_initialize(cx))?
897 .await?;
898
899 let result = this
900 .update(cx, |session, cx| {
901 session.initialize_sequence(initialized_rx, dap_store.clone(), cx)
902 })?
903 .await;
904
905 if result.is_err() {
906 let mut console = this.update(cx, |session, cx| session.console_output(cx))?;
907
908 console
909 .send(format!(
910 "Tried to launch debugger with: {}",
911 serde_json::to_string_pretty(&binary.request_args.configuration)
912 .unwrap_or_default(),
913 ))
914 .await
915 .ok();
916 }
917
918 result
919 })
920 }
921
922 pub fn session_id(&self) -> SessionId {
923 self.id
924 }
925
926 pub fn child_session_ids(&self) -> HashSet<SessionId> {
927 self.child_session_ids.clone()
928 }
929
930 pub fn add_child_session_id(&mut self, session_id: SessionId) {
931 self.child_session_ids.insert(session_id);
932 }
933
934 pub fn remove_child_session_id(&mut self, session_id: SessionId) {
935 self.child_session_ids.remove(&session_id);
936 }
937
938 pub fn parent_id(&self, cx: &App) -> Option<SessionId> {
939 self.parent_session
940 .as_ref()
941 .map(|session| session.read(cx).id)
942 }
943
944 pub fn parent_session(&self) -> Option<&Entity<Self>> {
945 self.parent_session.as_ref()
946 }
947
948 pub fn on_app_quit(&mut self, cx: &mut Context<Self>) -> Task<()> {
949 let Some(client) = self.adapter_client() else {
950 return Task::ready(());
951 };
952
953 let supports_terminate = self
954 .capabilities
955 .support_terminate_debuggee
956 .unwrap_or(false);
957
958 cx.background_spawn(async move {
959 if supports_terminate {
960 client
961 .request::<dap::requests::Terminate>(dap::TerminateArguments {
962 restart: Some(false),
963 })
964 .await
965 .ok();
966 } else {
967 client
968 .request::<dap::requests::Disconnect>(dap::DisconnectArguments {
969 restart: Some(false),
970 terminate_debuggee: Some(true),
971 suspend_debuggee: Some(false),
972 })
973 .await
974 .ok();
975 }
976 })
977 }
978
979 pub fn capabilities(&self) -> &Capabilities {
980 &self.capabilities
981 }
982
983 pub fn binary(&self) -> Option<&DebugAdapterBinary> {
984 match &self.mode {
985 Mode::Building => None,
986 Mode::Running(running_mode) => Some(&running_mode.binary),
987 }
988 }
989
990 pub fn adapter(&self) -> DebugAdapterName {
991 self.adapter.clone()
992 }
993
994 pub fn label(&self) -> SharedString {
995 self.label.clone()
996 }
997
998 pub fn is_terminated(&self) -> bool {
999 self.is_session_terminated
1000 }
1001
1002 pub fn console_output(&mut self, cx: &mut Context<Self>) -> mpsc::UnboundedSender<String> {
1003 let (tx, mut rx) = mpsc::unbounded();
1004
1005 cx.spawn(async move |this, cx| {
1006 while let Some(output) = rx.next().await {
1007 this.update(cx, |this, cx| {
1008 let event = dap::OutputEvent {
1009 category: None,
1010 output,
1011 group: None,
1012 variables_reference: None,
1013 source: None,
1014 line: None,
1015 column: None,
1016 data: None,
1017 location_reference: None,
1018 };
1019 this.push_output(event, cx);
1020 })?;
1021 }
1022 anyhow::Ok(())
1023 })
1024 .detach();
1025
1026 return tx;
1027 }
1028
1029 pub fn is_started(&self) -> bool {
1030 match &self.mode {
1031 Mode::Building => false,
1032 Mode::Running(running) => running.is_started,
1033 }
1034 }
1035
1036 pub fn is_building(&self) -> bool {
1037 matches!(self.mode, Mode::Building)
1038 }
1039
1040 pub fn is_running(&self) -> bool {
1041 matches!(self.mode, Mode::Running(_))
1042 }
1043
1044 pub fn as_running_mut(&mut self) -> Option<&mut RunningMode> {
1045 match &mut self.mode {
1046 Mode::Running(local_mode) => Some(local_mode),
1047 Mode::Building => None,
1048 }
1049 }
1050
1051 pub fn as_running(&self) -> Option<&RunningMode> {
1052 match &self.mode {
1053 Mode::Running(local_mode) => Some(local_mode),
1054 Mode::Building => None,
1055 }
1056 }
1057
1058 fn handle_start_debugging_request(
1059 &mut self,
1060 request: dap::messages::Request,
1061 cx: &mut Context<Self>,
1062 ) -> Task<Result<()>> {
1063 let request_seq = request.seq;
1064
1065 let launch_request: Option<Result<StartDebuggingRequestArguments, _>> = request
1066 .arguments
1067 .as_ref()
1068 .map(|value| serde_json::from_value(value.clone()));
1069
1070 let mut success = true;
1071 if let Some(Ok(request)) = launch_request {
1072 cx.emit(SessionStateEvent::SpawnChildSession { request });
1073 } else {
1074 log::error!(
1075 "Failed to parse launch request arguments: {:?}",
1076 request.arguments
1077 );
1078 success = false;
1079 }
1080
1081 cx.spawn(async move |this, cx| {
1082 this.update(cx, |this, cx| {
1083 this.respond_to_client(
1084 request_seq,
1085 success,
1086 StartDebugging::COMMAND.to_string(),
1087 None,
1088 cx,
1089 )
1090 })?
1091 .await
1092 })
1093 }
1094
1095 fn handle_run_in_terminal_request(
1096 &mut self,
1097 request: dap::messages::Request,
1098 cx: &mut Context<Self>,
1099 ) -> Task<Result<()>> {
1100 let request_args = match serde_json::from_value::<RunInTerminalRequestArguments>(
1101 request.arguments.unwrap_or_default(),
1102 ) {
1103 Ok(args) => args,
1104 Err(error) => {
1105 return cx.spawn(async move |session, cx| {
1106 let error = serde_json::to_value(dap::ErrorResponse {
1107 error: Some(dap::Message {
1108 id: request.seq,
1109 format: error.to_string(),
1110 variables: None,
1111 send_telemetry: None,
1112 show_user: None,
1113 url: None,
1114 url_label: None,
1115 }),
1116 })
1117 .ok();
1118
1119 session
1120 .update(cx, |this, cx| {
1121 this.respond_to_client(
1122 request.seq,
1123 false,
1124 StartDebugging::COMMAND.to_string(),
1125 error,
1126 cx,
1127 )
1128 })?
1129 .await?;
1130
1131 Err(anyhow!("Failed to parse RunInTerminalRequestArguments"))
1132 });
1133 }
1134 };
1135
1136 let seq = request.seq;
1137
1138 let (tx, mut rx) = mpsc::channel::<Result<u32>>(1);
1139 cx.emit(SessionEvent::RunInTerminal {
1140 request: request_args,
1141 sender: tx,
1142 });
1143 cx.notify();
1144
1145 cx.spawn(async move |session, cx| {
1146 let result = util::maybe!(async move {
1147 rx.next().await.ok_or_else(|| {
1148 anyhow!("failed to receive response from spawn terminal".to_string())
1149 })?
1150 })
1151 .await;
1152 let (success, body) = match result {
1153 Ok(pid) => (
1154 true,
1155 serde_json::to_value(dap::RunInTerminalResponse {
1156 process_id: None,
1157 shell_process_id: Some(pid as u64),
1158 })
1159 .ok(),
1160 ),
1161 Err(error) => (
1162 false,
1163 serde_json::to_value(dap::ErrorResponse {
1164 error: Some(dap::Message {
1165 id: seq,
1166 format: error.to_string(),
1167 variables: None,
1168 send_telemetry: None,
1169 show_user: None,
1170 url: None,
1171 url_label: None,
1172 }),
1173 })
1174 .ok(),
1175 ),
1176 };
1177
1178 session
1179 .update(cx, |session, cx| {
1180 session.respond_to_client(
1181 seq,
1182 success,
1183 RunInTerminal::COMMAND.to_string(),
1184 body,
1185 cx,
1186 )
1187 })?
1188 .await
1189 })
1190 }
1191
1192 pub(super) fn request_initialize(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1193 let adapter_id = self.adapter().to_string();
1194 let request = Initialize { adapter_id };
1195
1196 let Mode::Running(running) = &self.mode else {
1197 return Task::ready(Err(anyhow!(
1198 "Cannot send initialize request, task still building"
1199 )));
1200 };
1201 let mut response = running.request(request.clone());
1202
1203 cx.spawn(async move |this, cx| {
1204 loop {
1205 let capabilities = response.await;
1206 match capabilities {
1207 Err(e) => {
1208 let Ok(Some(reconnect)) = this.update(cx, |this, cx| {
1209 this.as_running()
1210 .and_then(|running| running.reconnect_for_ssh(&mut cx.to_async()))
1211 }) else {
1212 return Err(e);
1213 };
1214 log::info!("Failed to connect to debug adapter: {}, retrying...", e);
1215 reconnect.await?;
1216
1217 let Ok(Some(r)) = this.update(cx, |this, _| {
1218 this.as_running()
1219 .map(|running| running.request(request.clone()))
1220 }) else {
1221 return Err(e);
1222 };
1223 response = r
1224 }
1225 Ok(capabilities) => {
1226 this.update(cx, |session, cx| {
1227 session.capabilities = capabilities;
1228 let filters = session
1229 .capabilities
1230 .exception_breakpoint_filters
1231 .clone()
1232 .unwrap_or_default();
1233 for filter in filters {
1234 let default = filter.default.unwrap_or_default();
1235 session
1236 .exception_breakpoints
1237 .entry(filter.filter.clone())
1238 .or_insert_with(|| (filter, default));
1239 }
1240 cx.emit(SessionEvent::CapabilitiesLoaded);
1241 })?;
1242 return Ok(());
1243 }
1244 }
1245 }
1246 })
1247 }
1248
1249 pub(super) fn initialize_sequence(
1250 &mut self,
1251 initialize_rx: oneshot::Receiver<()>,
1252 dap_store: WeakEntity<DapStore>,
1253 cx: &mut Context<Self>,
1254 ) -> Task<Result<()>> {
1255 match &self.mode {
1256 Mode::Running(local_mode) => {
1257 local_mode.initialize_sequence(&self.capabilities, initialize_rx, dap_store, cx)
1258 }
1259 Mode::Building => Task::ready(Err(anyhow!("cannot initialize, still building"))),
1260 }
1261 }
1262
1263 pub fn run_to_position(
1264 &mut self,
1265 breakpoint: SourceBreakpoint,
1266 active_thread_id: ThreadId,
1267 cx: &mut Context<Self>,
1268 ) {
1269 match &mut self.mode {
1270 Mode::Running(local_mode) => {
1271 if !matches!(
1272 self.thread_states.thread_state(active_thread_id),
1273 Some(ThreadStatus::Stopped)
1274 ) {
1275 return;
1276 };
1277 let path = breakpoint.path.clone();
1278 local_mode.tmp_breakpoint = Some(breakpoint);
1279 let task = local_mode.send_breakpoints_from_path(
1280 path,
1281 BreakpointUpdatedReason::Toggled,
1282 &self.breakpoint_store,
1283 cx,
1284 );
1285
1286 cx.spawn(async move |this, cx| {
1287 task.await;
1288 this.update(cx, |this, cx| {
1289 this.continue_thread(active_thread_id, cx);
1290 })
1291 })
1292 .detach();
1293 }
1294 Mode::Building => {}
1295 }
1296 }
1297
1298 pub fn has_new_output(&self, last_update: OutputToken) -> bool {
1299 self.output_token.0.checked_sub(last_update.0).unwrap_or(0) != 0
1300 }
1301
1302 pub fn output(
1303 &self,
1304 since: OutputToken,
1305 ) -> (impl Iterator<Item = &dap::OutputEvent>, OutputToken) {
1306 if self.output_token.0 == 0 {
1307 return (self.output.range(0..0), OutputToken(0));
1308 };
1309
1310 let events_since = self.output_token.0.checked_sub(since.0).unwrap_or(0);
1311
1312 let clamped_events_since = events_since.clamp(0, self.output.len());
1313 (
1314 self.output
1315 .range(self.output.len() - clamped_events_since..),
1316 self.output_token,
1317 )
1318 }
1319
1320 pub fn respond_to_client(
1321 &self,
1322 request_seq: u64,
1323 success: bool,
1324 command: String,
1325 body: Option<serde_json::Value>,
1326 cx: &mut Context<Self>,
1327 ) -> Task<Result<()>> {
1328 let Some(local_session) = self.as_running() else {
1329 unreachable!("Cannot respond to remote client");
1330 };
1331 let client = local_session.client.clone();
1332
1333 cx.background_spawn(async move {
1334 client
1335 .send_message(Message::Response(Response {
1336 body,
1337 success,
1338 command,
1339 seq: request_seq + 1,
1340 request_seq,
1341 message: None,
1342 }))
1343 .await
1344 })
1345 }
1346
1347 fn handle_stopped_event(&mut self, event: StoppedEvent, cx: &mut Context<Self>) {
1348 self.mode.stopped();
1349 // todo(debugger): Find a clean way to get around the clone
1350 let breakpoint_store = self.breakpoint_store.clone();
1351 if let Some((local, path)) = self.as_running_mut().and_then(|local| {
1352 let breakpoint = local.tmp_breakpoint.take()?;
1353 let path = breakpoint.path.clone();
1354 Some((local, path))
1355 }) {
1356 local
1357 .send_breakpoints_from_path(
1358 path,
1359 BreakpointUpdatedReason::Toggled,
1360 &breakpoint_store,
1361 cx,
1362 )
1363 .detach();
1364 };
1365
1366 if event.all_threads_stopped.unwrap_or_default() || event.thread_id.is_none() {
1367 self.thread_states.stop_all_threads();
1368 self.invalidate_command_type::<StackTraceCommand>();
1369 }
1370
1371 // Event if we stopped all threads we still need to insert the thread_id
1372 // to our own data
1373 if let Some(thread_id) = event.thread_id {
1374 self.thread_states.stop_thread(ThreadId(thread_id));
1375
1376 self.invalidate_state(
1377 &StackTraceCommand {
1378 thread_id,
1379 start_frame: None,
1380 levels: None,
1381 }
1382 .into(),
1383 );
1384 }
1385
1386 self.invalidate_generic();
1387 self.threads.clear();
1388 self.variables.clear();
1389 cx.emit(SessionEvent::Stopped(
1390 event
1391 .thread_id
1392 .map(Into::into)
1393 .filter(|_| !event.preserve_focus_hint.unwrap_or(false)),
1394 ));
1395 cx.emit(SessionEvent::InvalidateInlineValue);
1396 cx.notify();
1397 }
1398
1399 pub(crate) fn handle_dap_event(&mut self, event: Box<Events>, cx: &mut Context<Self>) {
1400 match *event {
1401 Events::Initialized(_) => {
1402 debug_assert!(
1403 false,
1404 "Initialized event should have been handled in LocalMode"
1405 );
1406 }
1407 Events::Stopped(event) => self.handle_stopped_event(event, cx),
1408 Events::Continued(event) => {
1409 if event.all_threads_continued.unwrap_or_default() {
1410 self.thread_states.continue_all_threads();
1411 self.breakpoint_store.update(cx, |store, cx| {
1412 store.remove_active_position(Some(self.session_id()), cx)
1413 });
1414 } else {
1415 self.thread_states
1416 .continue_thread(ThreadId(event.thread_id));
1417 }
1418 // todo(debugger): We should be able to get away with only invalidating generic if all threads were continued
1419 self.invalidate_generic();
1420 }
1421 Events::Exited(_event) => {
1422 self.clear_active_debug_line(cx);
1423 }
1424 Events::Terminated(_) => {
1425 self.shutdown(cx).detach();
1426 }
1427 Events::Thread(event) => {
1428 let thread_id = ThreadId(event.thread_id);
1429
1430 match event.reason {
1431 dap::ThreadEventReason::Started => {
1432 self.thread_states.continue_thread(thread_id);
1433 }
1434 dap::ThreadEventReason::Exited => {
1435 self.thread_states.exit_thread(thread_id);
1436 }
1437 reason => {
1438 log::error!("Unhandled thread event reason {:?}", reason);
1439 }
1440 }
1441 self.invalidate_state(&ThreadsCommand.into());
1442 cx.notify();
1443 }
1444 Events::Output(event) => {
1445 if event
1446 .category
1447 .as_ref()
1448 .is_some_and(|category| *category == OutputEventCategory::Telemetry)
1449 {
1450 return;
1451 }
1452
1453 self.push_output(event, cx);
1454 cx.notify();
1455 }
1456 Events::Breakpoint(event) => self.breakpoint_store.update(cx, |store, _| {
1457 store.update_session_breakpoint(self.session_id(), event.reason, event.breakpoint);
1458 }),
1459 Events::Module(event) => {
1460 match event.reason {
1461 dap::ModuleEventReason::New => {
1462 self.modules.push(event.module);
1463 }
1464 dap::ModuleEventReason::Changed => {
1465 if let Some(module) = self
1466 .modules
1467 .iter_mut()
1468 .find(|other| event.module.id == other.id)
1469 {
1470 *module = event.module;
1471 }
1472 }
1473 dap::ModuleEventReason::Removed => {
1474 self.modules.retain(|other| event.module.id != other.id);
1475 }
1476 }
1477
1478 // todo(debugger): We should only send the invalidate command to downstream clients.
1479 // self.invalidate_state(&ModulesCommand.into());
1480 }
1481 Events::LoadedSource(_) => {
1482 self.invalidate_state(&LoadedSourcesCommand.into());
1483 }
1484 Events::Capabilities(event) => {
1485 self.capabilities = self.capabilities.merge(event.capabilities);
1486 cx.notify();
1487 }
1488 Events::Memory(_) => {}
1489 Events::Process(_) => {}
1490 Events::ProgressEnd(_) => {}
1491 Events::ProgressStart(_) => {}
1492 Events::ProgressUpdate(_) => {}
1493 Events::Invalidated(_) => {}
1494 Events::Other(_) => {}
1495 }
1496 }
1497
1498 /// Ensure that there's a request in flight for the given command, and if not, send it. Use this to run requests that are idempotent.
1499 fn fetch<T: DapCommand + PartialEq + Eq + Hash>(
1500 &mut self,
1501 request: T,
1502 process_result: impl FnOnce(&mut Self, Result<T::Response>, &mut Context<Self>) + 'static,
1503 cx: &mut Context<Self>,
1504 ) {
1505 const {
1506 assert!(
1507 T::CACHEABLE,
1508 "Only requests marked as cacheable should invoke `fetch`"
1509 );
1510 }
1511
1512 if !self.thread_states.any_stopped_thread()
1513 && request.type_id() != TypeId::of::<ThreadsCommand>()
1514 || self.is_session_terminated
1515 {
1516 return;
1517 }
1518
1519 let request_map = self
1520 .requests
1521 .entry(std::any::TypeId::of::<T>())
1522 .or_default();
1523
1524 if let Entry::Vacant(vacant) = request_map.entry(request.into()) {
1525 let command = vacant.key().0.clone().as_any_arc().downcast::<T>().unwrap();
1526
1527 let task = Self::request_inner::<Arc<T>>(
1528 &self.capabilities,
1529 &self.mode,
1530 command,
1531 |this, result, cx| {
1532 process_result(this, result, cx);
1533 None
1534 },
1535 cx,
1536 );
1537 let task = cx
1538 .background_executor()
1539 .spawn(async move {
1540 let _ = task.await?;
1541 Some(())
1542 })
1543 .shared();
1544
1545 vacant.insert(task);
1546 cx.notify();
1547 }
1548 }
1549
1550 fn request_inner<T: DapCommand + PartialEq + Eq + Hash>(
1551 capabilities: &Capabilities,
1552 mode: &Mode,
1553 request: T,
1554 process_result: impl FnOnce(
1555 &mut Self,
1556 Result<T::Response>,
1557 &mut Context<Self>,
1558 ) -> Option<T::Response>
1559 + 'static,
1560 cx: &mut Context<Self>,
1561 ) -> Task<Option<T::Response>> {
1562 if !T::is_supported(&capabilities) {
1563 log::warn!(
1564 "Attempted to send a DAP request that isn't supported: {:?}",
1565 request
1566 );
1567 let error = Err(anyhow::Error::msg(
1568 "Couldn't complete request because it's not supported",
1569 ));
1570 return cx.spawn(async move |this, cx| {
1571 this.update(cx, |this, cx| process_result(this, error, cx))
1572 .ok()
1573 .flatten()
1574 });
1575 }
1576
1577 let request = mode.request_dap(request);
1578 cx.spawn(async move |this, cx| {
1579 let result = request.await;
1580 this.update(cx, |this, cx| process_result(this, result, cx))
1581 .ok()
1582 .flatten()
1583 })
1584 }
1585
1586 fn request<T: DapCommand + PartialEq + Eq + Hash>(
1587 &self,
1588 request: T,
1589 process_result: impl FnOnce(
1590 &mut Self,
1591 Result<T::Response>,
1592 &mut Context<Self>,
1593 ) -> Option<T::Response>
1594 + 'static,
1595 cx: &mut Context<Self>,
1596 ) -> Task<Option<T::Response>> {
1597 Self::request_inner(&self.capabilities, &self.mode, request, process_result, cx)
1598 }
1599
1600 fn invalidate_command_type<Command: DapCommand>(&mut self) {
1601 self.requests.remove(&std::any::TypeId::of::<Command>());
1602 }
1603
1604 fn invalidate_generic(&mut self) {
1605 self.invalidate_command_type::<ModulesCommand>();
1606 self.invalidate_command_type::<LoadedSourcesCommand>();
1607 self.invalidate_command_type::<ThreadsCommand>();
1608 }
1609
1610 fn invalidate_state(&mut self, key: &RequestSlot) {
1611 self.requests
1612 .entry((&*key.0 as &dyn Any).type_id())
1613 .and_modify(|request_map| {
1614 request_map.remove(&key);
1615 });
1616 }
1617
1618 fn push_output(&mut self, event: OutputEvent, cx: &mut Context<Self>) {
1619 self.output.push_back(event);
1620 self.output_token.0 += 1;
1621 cx.emit(SessionEvent::ConsoleOutput);
1622 }
1623
1624 pub fn any_stopped_thread(&self) -> bool {
1625 self.thread_states.any_stopped_thread()
1626 }
1627
1628 pub fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
1629 self.thread_states.thread_status(thread_id)
1630 }
1631
1632 pub fn threads(&mut self, cx: &mut Context<Self>) -> Vec<(dap::Thread, ThreadStatus)> {
1633 self.fetch(
1634 dap_command::ThreadsCommand,
1635 |this, result, cx| {
1636 let Some(result) = result.log_err() else {
1637 return;
1638 };
1639
1640 this.threads = result
1641 .into_iter()
1642 .map(|thread| (ThreadId(thread.id), Thread::from(thread.clone())))
1643 .collect();
1644
1645 this.invalidate_command_type::<StackTraceCommand>();
1646 cx.emit(SessionEvent::Threads);
1647 cx.notify();
1648 },
1649 cx,
1650 );
1651
1652 self.threads
1653 .values()
1654 .map(|thread| {
1655 (
1656 thread.dap.clone(),
1657 self.thread_states.thread_status(ThreadId(thread.dap.id)),
1658 )
1659 })
1660 .collect()
1661 }
1662
1663 pub fn modules(&mut self, cx: &mut Context<Self>) -> &[Module] {
1664 self.fetch(
1665 dap_command::ModulesCommand,
1666 |this, result, cx| {
1667 let Some(result) = result.log_err() else {
1668 return;
1669 };
1670
1671 this.modules = result;
1672 cx.emit(SessionEvent::Modules);
1673 cx.notify();
1674 },
1675 cx,
1676 );
1677
1678 &self.modules
1679 }
1680
1681 pub fn ignore_breakpoints(&self) -> bool {
1682 self.ignore_breakpoints
1683 }
1684
1685 pub fn toggle_ignore_breakpoints(
1686 &mut self,
1687 cx: &mut App,
1688 ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
1689 self.set_ignore_breakpoints(!self.ignore_breakpoints, cx)
1690 }
1691
1692 pub(crate) fn set_ignore_breakpoints(
1693 &mut self,
1694 ignore: bool,
1695 cx: &mut App,
1696 ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
1697 if self.ignore_breakpoints == ignore {
1698 return Task::ready(HashMap::default());
1699 }
1700
1701 self.ignore_breakpoints = ignore;
1702
1703 if let Some(local) = self.as_running() {
1704 local.send_source_breakpoints(ignore, &self.breakpoint_store, cx)
1705 } else {
1706 // todo(debugger): We need to propagate this change to downstream sessions and send a message to upstream sessions
1707 unimplemented!()
1708 }
1709 }
1710
1711 pub fn exception_breakpoints(
1712 &self,
1713 ) -> impl Iterator<Item = &(ExceptionBreakpointsFilter, IsEnabled)> {
1714 self.exception_breakpoints.values()
1715 }
1716
1717 pub fn toggle_exception_breakpoint(&mut self, id: &str, cx: &App) {
1718 if let Some((_, is_enabled)) = self.exception_breakpoints.get_mut(id) {
1719 *is_enabled = !*is_enabled;
1720 self.send_exception_breakpoints(cx);
1721 }
1722 }
1723
1724 fn send_exception_breakpoints(&mut self, cx: &App) {
1725 if let Some(local) = self.as_running() {
1726 let exception_filters = self
1727 .exception_breakpoints
1728 .values()
1729 .filter_map(|(filter, is_enabled)| is_enabled.then(|| filter.clone()))
1730 .collect();
1731
1732 let supports_exception_filters = self
1733 .capabilities
1734 .supports_exception_filter_options
1735 .unwrap_or_default();
1736 local
1737 .send_exception_breakpoints(exception_filters, supports_exception_filters)
1738 .detach_and_log_err(cx);
1739 } else {
1740 debug_assert!(false, "Not implemented");
1741 }
1742 }
1743
1744 pub fn breakpoints_enabled(&self) -> bool {
1745 self.ignore_breakpoints
1746 }
1747
1748 pub fn loaded_sources(&mut self, cx: &mut Context<Self>) -> &[Source] {
1749 self.fetch(
1750 dap_command::LoadedSourcesCommand,
1751 |this, result, cx| {
1752 let Some(result) = result.log_err() else {
1753 return;
1754 };
1755 this.loaded_sources = result;
1756 cx.emit(SessionEvent::LoadedSources);
1757 cx.notify();
1758 },
1759 cx,
1760 );
1761
1762 &self.loaded_sources
1763 }
1764
1765 fn fallback_to_manual_restart(
1766 &mut self,
1767 res: Result<()>,
1768 cx: &mut Context<Self>,
1769 ) -> Option<()> {
1770 if res.log_err().is_none() {
1771 cx.emit(SessionStateEvent::Restart);
1772 return None;
1773 }
1774 Some(())
1775 }
1776
1777 fn empty_response(&mut self, res: Result<()>, _cx: &mut Context<Self>) -> Option<()> {
1778 res.log_err()?;
1779 Some(())
1780 }
1781
1782 fn on_step_response<T: DapCommand + PartialEq + Eq + Hash>(
1783 thread_id: ThreadId,
1784 ) -> impl FnOnce(&mut Self, Result<T::Response>, &mut Context<Self>) -> Option<T::Response> + 'static
1785 {
1786 move |this, response, cx| match response.log_err() {
1787 Some(response) => {
1788 this.breakpoint_store.update(cx, |store, cx| {
1789 store.remove_active_position(Some(this.session_id()), cx)
1790 });
1791 Some(response)
1792 }
1793 None => {
1794 this.thread_states.stop_thread(thread_id);
1795 cx.notify();
1796 None
1797 }
1798 }
1799 }
1800
1801 fn clear_active_debug_line_response(
1802 &mut self,
1803 response: Result<()>,
1804 cx: &mut Context<Session>,
1805 ) -> Option<()> {
1806 response.log_err()?;
1807 self.clear_active_debug_line(cx);
1808 Some(())
1809 }
1810
1811 fn clear_active_debug_line(&mut self, cx: &mut Context<Session>) {
1812 self.breakpoint_store.update(cx, |store, cx| {
1813 store.remove_active_position(Some(self.id), cx)
1814 });
1815 }
1816
1817 pub fn pause_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
1818 self.request(
1819 PauseCommand {
1820 thread_id: thread_id.0,
1821 },
1822 Self::empty_response,
1823 cx,
1824 )
1825 .detach();
1826 }
1827
1828 pub fn restart_stack_frame(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) {
1829 self.request(
1830 RestartStackFrameCommand { stack_frame_id },
1831 Self::empty_response,
1832 cx,
1833 )
1834 .detach();
1835 }
1836
1837 pub fn restart(&mut self, args: Option<Value>, cx: &mut Context<Self>) {
1838 if self.capabilities.supports_restart_request.unwrap_or(false) && !self.is_terminated() {
1839 self.request(
1840 RestartCommand {
1841 raw: args.unwrap_or(Value::Null),
1842 },
1843 Self::fallback_to_manual_restart,
1844 cx,
1845 )
1846 .detach();
1847 } else {
1848 cx.emit(SessionStateEvent::Restart);
1849 }
1850 }
1851
1852 pub fn shutdown(&mut self, cx: &mut Context<Self>) -> Task<()> {
1853 if self.is_session_terminated {
1854 return Task::ready(());
1855 }
1856
1857 self.is_session_terminated = true;
1858 self.thread_states.exit_all_threads();
1859 cx.notify();
1860
1861 let task = if self
1862 .capabilities
1863 .supports_terminate_request
1864 .unwrap_or_default()
1865 {
1866 self.request(
1867 TerminateCommand {
1868 restart: Some(false),
1869 },
1870 Self::clear_active_debug_line_response,
1871 cx,
1872 )
1873 } else {
1874 self.request(
1875 DisconnectCommand {
1876 restart: Some(false),
1877 terminate_debuggee: Some(true),
1878 suspend_debuggee: Some(false),
1879 },
1880 Self::clear_active_debug_line_response,
1881 cx,
1882 )
1883 };
1884
1885 cx.emit(SessionStateEvent::Shutdown);
1886
1887 cx.spawn(async move |_, _| {
1888 task.await;
1889 })
1890 }
1891
1892 pub fn completions(
1893 &mut self,
1894 query: CompletionsQuery,
1895 cx: &mut Context<Self>,
1896 ) -> Task<Result<Vec<dap::CompletionItem>>> {
1897 let task = self.request(query, |_, result, _| result.log_err(), cx);
1898
1899 cx.background_executor().spawn(async move {
1900 anyhow::Ok(
1901 task.await
1902 .map(|response| response.targets)
1903 .context("failed to fetch completions")?,
1904 )
1905 })
1906 }
1907
1908 pub fn continue_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
1909 self.thread_states.continue_thread(thread_id);
1910 self.request(
1911 ContinueCommand {
1912 args: ContinueArguments {
1913 thread_id: thread_id.0,
1914 single_thread: Some(true),
1915 },
1916 },
1917 Self::on_step_response::<ContinueCommand>(thread_id),
1918 cx,
1919 )
1920 .detach();
1921 }
1922
1923 pub fn adapter_client(&self) -> Option<Arc<DebugAdapterClient>> {
1924 match self.mode {
1925 Mode::Running(ref local) => Some(local.client.clone()),
1926 Mode::Building => None,
1927 }
1928 }
1929
1930 pub fn has_ever_stopped(&self) -> bool {
1931 self.mode.has_ever_stopped()
1932 }
1933 pub fn step_over(
1934 &mut self,
1935 thread_id: ThreadId,
1936 granularity: SteppingGranularity,
1937 cx: &mut Context<Self>,
1938 ) {
1939 let supports_single_thread_execution_requests =
1940 self.capabilities.supports_single_thread_execution_requests;
1941 let supports_stepping_granularity = self
1942 .capabilities
1943 .supports_stepping_granularity
1944 .unwrap_or_default();
1945
1946 let command = NextCommand {
1947 inner: StepCommand {
1948 thread_id: thread_id.0,
1949 granularity: supports_stepping_granularity.then(|| granularity),
1950 single_thread: supports_single_thread_execution_requests,
1951 },
1952 };
1953
1954 self.thread_states.process_step(thread_id);
1955 self.request(
1956 command,
1957 Self::on_step_response::<NextCommand>(thread_id),
1958 cx,
1959 )
1960 .detach();
1961 }
1962
1963 pub fn step_in(
1964 &mut self,
1965 thread_id: ThreadId,
1966 granularity: SteppingGranularity,
1967 cx: &mut Context<Self>,
1968 ) {
1969 let supports_single_thread_execution_requests =
1970 self.capabilities.supports_single_thread_execution_requests;
1971 let supports_stepping_granularity = self
1972 .capabilities
1973 .supports_stepping_granularity
1974 .unwrap_or_default();
1975
1976 let command = StepInCommand {
1977 inner: StepCommand {
1978 thread_id: thread_id.0,
1979 granularity: supports_stepping_granularity.then(|| granularity),
1980 single_thread: supports_single_thread_execution_requests,
1981 },
1982 };
1983
1984 self.thread_states.process_step(thread_id);
1985 self.request(
1986 command,
1987 Self::on_step_response::<StepInCommand>(thread_id),
1988 cx,
1989 )
1990 .detach();
1991 }
1992
1993 pub fn step_out(
1994 &mut self,
1995 thread_id: ThreadId,
1996 granularity: SteppingGranularity,
1997 cx: &mut Context<Self>,
1998 ) {
1999 let supports_single_thread_execution_requests =
2000 self.capabilities.supports_single_thread_execution_requests;
2001 let supports_stepping_granularity = self
2002 .capabilities
2003 .supports_stepping_granularity
2004 .unwrap_or_default();
2005
2006 let command = StepOutCommand {
2007 inner: StepCommand {
2008 thread_id: thread_id.0,
2009 granularity: supports_stepping_granularity.then(|| granularity),
2010 single_thread: supports_single_thread_execution_requests,
2011 },
2012 };
2013
2014 self.thread_states.process_step(thread_id);
2015 self.request(
2016 command,
2017 Self::on_step_response::<StepOutCommand>(thread_id),
2018 cx,
2019 )
2020 .detach();
2021 }
2022
2023 pub fn step_back(
2024 &mut self,
2025 thread_id: ThreadId,
2026 granularity: SteppingGranularity,
2027 cx: &mut Context<Self>,
2028 ) {
2029 let supports_single_thread_execution_requests =
2030 self.capabilities.supports_single_thread_execution_requests;
2031 let supports_stepping_granularity = self
2032 .capabilities
2033 .supports_stepping_granularity
2034 .unwrap_or_default();
2035
2036 let command = StepBackCommand {
2037 inner: StepCommand {
2038 thread_id: thread_id.0,
2039 granularity: supports_stepping_granularity.then(|| granularity),
2040 single_thread: supports_single_thread_execution_requests,
2041 },
2042 };
2043
2044 self.thread_states.process_step(thread_id);
2045
2046 self.request(
2047 command,
2048 Self::on_step_response::<StepBackCommand>(thread_id),
2049 cx,
2050 )
2051 .detach();
2052 }
2053
2054 pub fn stack_frames(
2055 &mut self,
2056 thread_id: ThreadId,
2057 cx: &mut Context<Self>,
2058 ) -> Result<Vec<StackFrame>> {
2059 if self.thread_states.thread_status(thread_id) == ThreadStatus::Stopped
2060 && self.requests.contains_key(&ThreadsCommand.type_id())
2061 && self.threads.contains_key(&thread_id)
2062 // ^ todo(debugger): We need a better way to check that we're not querying stale data
2063 // We could still be using an old thread id and have sent a new thread's request
2064 // This isn't the biggest concern right now because it hasn't caused any issues outside of tests
2065 // But it very well could cause a minor bug in the future that is hard to track down
2066 {
2067 self.fetch(
2068 super::dap_command::StackTraceCommand {
2069 thread_id: thread_id.0,
2070 start_frame: None,
2071 levels: None,
2072 },
2073 move |this, stack_frames, cx| {
2074 let entry =
2075 this.threads
2076 .entry(thread_id)
2077 .and_modify(|thread| match &stack_frames {
2078 Ok(stack_frames) => {
2079 thread.stack_frames = stack_frames
2080 .iter()
2081 .cloned()
2082 .map(StackFrame::from)
2083 .collect();
2084 thread.stack_frames_error = None;
2085 }
2086 Err(error) => {
2087 thread.stack_frames.clear();
2088 thread.stack_frames_error = Some(error.cloned());
2089 }
2090 });
2091 debug_assert!(
2092 matches!(entry, indexmap::map::Entry::Occupied(_)),
2093 "Sent request for thread_id that doesn't exist"
2094 );
2095 if let Ok(stack_frames) = stack_frames {
2096 this.stack_frames.extend(
2097 stack_frames
2098 .into_iter()
2099 .filter(|frame| {
2100 // Workaround for JavaScript debug adapter sending out "fake" stack frames for delineating await points. This is fine,
2101 // except that they always use an id of 0 for it, which collides with other (valid) stack frames.
2102 !(frame.id == 0
2103 && frame.line == 0
2104 && frame.column == 0
2105 && frame.presentation_hint
2106 == Some(StackFramePresentationHint::Label))
2107 })
2108 .map(|frame| (frame.id, StackFrame::from(frame))),
2109 );
2110 }
2111
2112 this.invalidate_command_type::<ScopesCommand>();
2113 this.invalidate_command_type::<VariablesCommand>();
2114
2115 cx.emit(SessionEvent::StackTrace);
2116 },
2117 cx,
2118 );
2119 }
2120
2121 match self.threads.get(&thread_id) {
2122 Some(thread) => {
2123 if let Some(error) = &thread.stack_frames_error {
2124 Err(error.cloned())
2125 } else {
2126 Ok(thread.stack_frames.clone())
2127 }
2128 }
2129 None => Ok(Vec::new()),
2130 }
2131 }
2132
2133 pub fn scopes(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) -> &[dap::Scope] {
2134 if self.requests.contains_key(&TypeId::of::<ThreadsCommand>())
2135 && self
2136 .requests
2137 .contains_key(&TypeId::of::<StackTraceCommand>())
2138 {
2139 self.fetch(
2140 ScopesCommand { stack_frame_id },
2141 move |this, scopes, cx| {
2142 let Some(scopes) = scopes.log_err() else {
2143 return
2144 };
2145
2146 for scope in scopes.iter() {
2147 this.variables(scope.variables_reference, cx);
2148 }
2149
2150 let entry = this
2151 .stack_frames
2152 .entry(stack_frame_id)
2153 .and_modify(|stack_frame| {
2154 stack_frame.scopes = scopes;
2155 });
2156
2157 cx.emit(SessionEvent::Variables);
2158
2159 debug_assert!(
2160 matches!(entry, indexmap::map::Entry::Occupied(_)),
2161 "Sent scopes request for stack_frame_id that doesn't exist or hasn't been fetched"
2162 );
2163 },
2164 cx,
2165 );
2166 }
2167
2168 self.stack_frames
2169 .get(&stack_frame_id)
2170 .map(|frame| frame.scopes.as_slice())
2171 .unwrap_or_default()
2172 }
2173
2174 pub fn variables_by_stack_frame_id(
2175 &self,
2176 stack_frame_id: StackFrameId,
2177 globals: bool,
2178 locals: bool,
2179 ) -> Vec<dap::Variable> {
2180 let Some(stack_frame) = self.stack_frames.get(&stack_frame_id) else {
2181 return Vec::new();
2182 };
2183
2184 stack_frame
2185 .scopes
2186 .iter()
2187 .filter(|scope| {
2188 (scope.name.to_lowercase().contains("local") && locals)
2189 || (scope.name.to_lowercase().contains("global") && globals)
2190 })
2191 .filter_map(|scope| self.variables.get(&scope.variables_reference))
2192 .flatten()
2193 .cloned()
2194 .collect()
2195 }
2196
2197 pub fn watchers(&self) -> &HashMap<SharedString, Watcher> {
2198 &self.watchers
2199 }
2200
2201 pub fn add_watcher(
2202 &mut self,
2203 expression: SharedString,
2204 frame_id: u64,
2205 cx: &mut Context<Self>,
2206 ) -> Task<Result<()>> {
2207 let request = self.mode.request_dap(EvaluateCommand {
2208 expression: expression.to_string(),
2209 context: Some(EvaluateArgumentsContext::Watch),
2210 frame_id: Some(frame_id),
2211 source: None,
2212 });
2213
2214 cx.spawn(async move |this, cx| {
2215 let response = request.await?;
2216
2217 this.update(cx, |session, cx| {
2218 session.watchers.insert(
2219 expression.clone(),
2220 Watcher {
2221 expression,
2222 value: response.result.into(),
2223 variables_reference: response.variables_reference,
2224 presentation_hint: response.presentation_hint,
2225 },
2226 );
2227 cx.emit(SessionEvent::Watchers);
2228 })
2229 })
2230 }
2231
2232 pub fn refresh_watchers(&mut self, frame_id: u64, cx: &mut Context<Self>) {
2233 let watches = self.watchers.clone();
2234 for (_, watch) in watches.into_iter() {
2235 self.add_watcher(watch.expression.clone(), frame_id, cx)
2236 .detach();
2237 }
2238 }
2239
2240 pub fn remove_watcher(&mut self, expression: SharedString) {
2241 self.watchers.remove(&expression);
2242 }
2243
2244 pub fn variables(
2245 &mut self,
2246 variables_reference: VariableReference,
2247 cx: &mut Context<Self>,
2248 ) -> Vec<dap::Variable> {
2249 let command = VariablesCommand {
2250 variables_reference,
2251 filter: None,
2252 start: None,
2253 count: None,
2254 format: None,
2255 };
2256
2257 self.fetch(
2258 command,
2259 move |this, variables, cx| {
2260 let Some(variables) = variables.log_err() else {
2261 return;
2262 };
2263
2264 this.variables.insert(variables_reference, variables);
2265
2266 cx.emit(SessionEvent::Variables);
2267 cx.emit(SessionEvent::InvalidateInlineValue);
2268 },
2269 cx,
2270 );
2271
2272 self.variables
2273 .get(&variables_reference)
2274 .cloned()
2275 .unwrap_or_default()
2276 }
2277
2278 pub fn set_variable_value(
2279 &mut self,
2280 stack_frame_id: u64,
2281 variables_reference: u64,
2282 name: String,
2283 value: String,
2284 cx: &mut Context<Self>,
2285 ) {
2286 if self.capabilities.supports_set_variable.unwrap_or_default() {
2287 self.request(
2288 SetVariableValueCommand {
2289 name,
2290 value,
2291 variables_reference,
2292 },
2293 move |this, response, cx| {
2294 let response = response.log_err()?;
2295 this.invalidate_command_type::<VariablesCommand>();
2296 this.refresh_watchers(stack_frame_id, cx);
2297 cx.emit(SessionEvent::Variables);
2298 Some(response)
2299 },
2300 cx,
2301 )
2302 .detach();
2303 }
2304 }
2305
2306 pub fn evaluate(
2307 &mut self,
2308 expression: String,
2309 context: Option<EvaluateArgumentsContext>,
2310 frame_id: Option<u64>,
2311 source: Option<Source>,
2312 cx: &mut Context<Self>,
2313 ) -> Task<()> {
2314 let event = dap::OutputEvent {
2315 category: None,
2316 output: format!("> {expression}"),
2317 group: None,
2318 variables_reference: None,
2319 source: None,
2320 line: None,
2321 column: None,
2322 data: None,
2323 location_reference: None,
2324 };
2325 self.push_output(event, cx);
2326 let request = self.mode.request_dap(EvaluateCommand {
2327 expression,
2328 context,
2329 frame_id,
2330 source,
2331 });
2332 cx.spawn(async move |this, cx| {
2333 let response = request.await;
2334 this.update(cx, |this, cx| {
2335 match response {
2336 Ok(response) => {
2337 let event = dap::OutputEvent {
2338 category: None,
2339 output: format!("< {}", &response.result),
2340 group: None,
2341 variables_reference: Some(response.variables_reference),
2342 source: None,
2343 line: None,
2344 column: None,
2345 data: None,
2346 location_reference: None,
2347 };
2348 this.push_output(event, cx);
2349 }
2350 Err(e) => {
2351 let event = dap::OutputEvent {
2352 category: None,
2353 output: format!("{}", e),
2354 group: None,
2355 variables_reference: None,
2356 source: None,
2357 line: None,
2358 column: None,
2359 data: None,
2360 location_reference: None,
2361 };
2362 this.push_output(event, cx);
2363 }
2364 };
2365 cx.notify();
2366 })
2367 .ok();
2368 })
2369 }
2370
2371 pub fn location(
2372 &mut self,
2373 reference: u64,
2374 cx: &mut Context<Self>,
2375 ) -> Option<dap::LocationsResponse> {
2376 self.fetch(
2377 LocationsCommand { reference },
2378 move |this, response, _| {
2379 let Some(response) = response.log_err() else {
2380 return;
2381 };
2382 this.locations.insert(reference, response);
2383 },
2384 cx,
2385 );
2386 self.locations.get(&reference).cloned()
2387 }
2388
2389 pub fn is_attached(&self) -> bool {
2390 let Mode::Running(local_mode) = &self.mode else {
2391 return false;
2392 };
2393 local_mode.binary.request_args.request == StartDebuggingRequestArgumentsRequest::Attach
2394 }
2395
2396 pub fn disconnect_client(&mut self, cx: &mut Context<Self>) {
2397 let command = DisconnectCommand {
2398 restart: Some(false),
2399 terminate_debuggee: Some(false),
2400 suspend_debuggee: Some(false),
2401 };
2402
2403 self.request(command, Self::empty_response, cx).detach()
2404 }
2405
2406 pub fn terminate_threads(&mut self, thread_ids: Option<Vec<ThreadId>>, cx: &mut Context<Self>) {
2407 if self
2408 .capabilities
2409 .supports_terminate_threads_request
2410 .unwrap_or_default()
2411 {
2412 self.request(
2413 TerminateThreadsCommand {
2414 thread_ids: thread_ids.map(|ids| ids.into_iter().map(|id| id.0).collect()),
2415 },
2416 Self::clear_active_debug_line_response,
2417 cx,
2418 )
2419 .detach();
2420 } else {
2421 self.shutdown(cx).detach();
2422 }
2423 }
2424
2425 pub fn thread_state(&self, thread_id: ThreadId) -> Option<ThreadStatus> {
2426 self.thread_states.thread_state(thread_id)
2427 }
2428}