1use super::{
2 breakpoint_store::BreakpointStore,
3 dap_command::EvaluateCommand,
4 locators,
5 session::{self, Session, SessionStateEvent},
6};
7use crate::{
8 InlayHint, InlayHintLabel, ProjectEnvironment, ResolveState,
9 debugger::session::SessionQuirks,
10 project_settings::{DapBinary, ProjectSettings},
11 worktree_store::WorktreeStore,
12};
13use anyhow::{Context as _, Result, anyhow};
14use async_trait::async_trait;
15use collections::HashMap;
16use dap::{
17 Capabilities, DapRegistry, DebugRequest, EvaluateArgumentsContext, StackFrameId,
18 adapters::{
19 DapDelegate, DebugAdapterBinary, DebugAdapterName, DebugTaskDefinition, TcpArguments,
20 },
21 client::SessionId,
22 inline_value::VariableLookupKind,
23 messages::Message,
24};
25use fs::Fs;
26use futures::{
27 StreamExt,
28 channel::mpsc::{self, UnboundedSender},
29 future::{Shared, join_all},
30};
31use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
32use http_client::HttpClient;
33use language::{Buffer, LanguageToolchainStore};
34use node_runtime::NodeRuntime;
35use settings::InlayHintKind;
36
37use remote::RemoteClient;
38use rpc::{
39 AnyProtoClient, TypedEnvelope,
40 proto::{self},
41};
42use serde::{Deserialize, Serialize};
43use settings::{Settings, SettingsLocation, WorktreeId};
44use std::{
45 borrow::Borrow,
46 collections::BTreeMap,
47 ffi::OsStr,
48 net::Ipv4Addr,
49 path::{Path, PathBuf},
50 sync::{Arc, Once},
51};
52use task::{DebugScenario, SpawnInTerminal, TaskContext, TaskTemplate};
53use util::{ResultExt as _, rel_path::RelPath};
54use worktree::Worktree;
55
56#[derive(Debug)]
57pub enum DapStoreEvent {
58 DebugClientStarted(SessionId),
59 DebugSessionInitialized(SessionId),
60 DebugClientShutdown(SessionId),
61 DebugClientEvent {
62 session_id: SessionId,
63 message: Message,
64 },
65 Notification(String),
66 RemoteHasInitialized,
67}
68
69enum DapStoreMode {
70 Local(LocalDapStore),
71 Remote(RemoteDapStore),
72 Collab,
73}
74
75pub struct LocalDapStore {
76 fs: Arc<dyn Fs>,
77 node_runtime: NodeRuntime,
78 http_client: Arc<dyn HttpClient>,
79 environment: Entity<ProjectEnvironment>,
80 toolchain_store: Arc<dyn LanguageToolchainStore>,
81}
82
83pub struct RemoteDapStore {
84 remote_client: Entity<RemoteClient>,
85 upstream_client: AnyProtoClient,
86 upstream_project_id: u64,
87}
88
89pub struct DapStore {
90 mode: DapStoreMode,
91 downstream_client: Option<(AnyProtoClient, u64)>,
92 breakpoint_store: Entity<BreakpointStore>,
93 worktree_store: Entity<WorktreeStore>,
94 sessions: BTreeMap<SessionId, Entity<Session>>,
95 next_session_id: u32,
96 adapter_options: BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>>,
97}
98
99impl EventEmitter<DapStoreEvent> for DapStore {}
100
101#[derive(Clone, Serialize, Deserialize)]
102pub struct PersistedExceptionBreakpoint {
103 pub enabled: bool,
104}
105
106/// Represents best-effort serialization of adapter state during last session (e.g. watches)
107#[derive(Clone, Default, Serialize, Deserialize)]
108pub struct PersistedAdapterOptions {
109 /// Which exception breakpoints were enabled during the last session with this adapter?
110 pub exception_breakpoints: BTreeMap<String, PersistedExceptionBreakpoint>,
111}
112
113impl DapStore {
114 pub fn init(client: &AnyProtoClient, cx: &mut App) {
115 static ADD_LOCATORS: Once = Once::new();
116 ADD_LOCATORS.call_once(|| {
117 let registry = DapRegistry::global(cx);
118 registry.add_locator(Arc::new(locators::cargo::CargoLocator {}));
119 registry.add_locator(Arc::new(locators::go::GoLocator {}));
120 registry.add_locator(Arc::new(locators::node::NodeLocator));
121 registry.add_locator(Arc::new(locators::python::PythonLocator));
122 });
123 client.add_entity_request_handler(Self::handle_run_debug_locator);
124 client.add_entity_request_handler(Self::handle_get_debug_adapter_binary);
125 client.add_entity_message_handler(Self::handle_log_to_debug_console);
126 }
127
128 #[expect(clippy::too_many_arguments)]
129 pub fn new_local(
130 http_client: Arc<dyn HttpClient>,
131 node_runtime: NodeRuntime,
132 fs: Arc<dyn Fs>,
133 environment: Entity<ProjectEnvironment>,
134 toolchain_store: Arc<dyn LanguageToolchainStore>,
135 worktree_store: Entity<WorktreeStore>,
136 breakpoint_store: Entity<BreakpointStore>,
137 cx: &mut Context<Self>,
138 ) -> Self {
139 let mode = DapStoreMode::Local(LocalDapStore {
140 fs,
141 environment,
142 http_client,
143 node_runtime,
144 toolchain_store,
145 });
146
147 Self::new(mode, breakpoint_store, worktree_store, cx)
148 }
149
150 pub fn new_remote(
151 project_id: u64,
152 remote_client: Entity<RemoteClient>,
153 breakpoint_store: Entity<BreakpointStore>,
154 worktree_store: Entity<WorktreeStore>,
155 cx: &mut Context<Self>,
156 ) -> Self {
157 let mode = DapStoreMode::Remote(RemoteDapStore {
158 upstream_client: remote_client.read(cx).proto_client(),
159 remote_client,
160 upstream_project_id: project_id,
161 });
162
163 Self::new(mode, breakpoint_store, worktree_store, cx)
164 }
165
166 pub fn new_collab(
167 _project_id: u64,
168 _upstream_client: AnyProtoClient,
169 breakpoint_store: Entity<BreakpointStore>,
170 worktree_store: Entity<WorktreeStore>,
171 cx: &mut Context<Self>,
172 ) -> Self {
173 Self::new(DapStoreMode::Collab, breakpoint_store, worktree_store, cx)
174 }
175
176 fn new(
177 mode: DapStoreMode,
178 breakpoint_store: Entity<BreakpointStore>,
179 worktree_store: Entity<WorktreeStore>,
180 _cx: &mut Context<Self>,
181 ) -> Self {
182 Self {
183 mode,
184 next_session_id: 0,
185 downstream_client: None,
186 breakpoint_store,
187 worktree_store,
188 sessions: Default::default(),
189 adapter_options: Default::default(),
190 }
191 }
192
193 pub fn get_debug_adapter_binary(
194 &mut self,
195 definition: DebugTaskDefinition,
196 session_id: SessionId,
197 worktree: &Entity<Worktree>,
198 console: UnboundedSender<String>,
199 cx: &mut Context<Self>,
200 ) -> Task<Result<DebugAdapterBinary>> {
201 match &self.mode {
202 DapStoreMode::Local(_) => {
203 let Some(adapter) = DapRegistry::global(cx).adapter(&definition.adapter) else {
204 return Task::ready(Err(anyhow!("Failed to find a debug adapter")));
205 };
206
207 let settings_location = SettingsLocation {
208 worktree_id: worktree.read(cx).id(),
209 path: RelPath::empty(),
210 };
211 let dap_settings = ProjectSettings::get(Some(settings_location), cx)
212 .dap
213 .get(&adapter.name());
214 let user_installed_path = dap_settings.and_then(|s| match &s.binary {
215 DapBinary::Default => None,
216 DapBinary::Custom(binary) => Some(PathBuf::from(binary)),
217 });
218 let user_args = dap_settings.map(|s| s.args.clone());
219
220 let delegate = self.delegate(worktree, console, cx);
221 let cwd: Arc<Path> = worktree.read(cx).abs_path().as_ref().into();
222
223 cx.spawn(async move |this, cx| {
224 let mut binary = adapter
225 .get_binary(&delegate, &definition, user_installed_path, user_args, cx)
226 .await?;
227
228 let env = this
229 .update(cx, |this, cx| {
230 this.as_local()
231 .unwrap()
232 .environment
233 .update(cx, |environment, cx| {
234 environment.get_directory_environment(cwd, cx)
235 })
236 })?
237 .await;
238
239 if let Some(mut env) = env {
240 env.extend(std::mem::take(&mut binary.envs));
241 binary.envs = env;
242 }
243
244 Ok(binary)
245 })
246 }
247 DapStoreMode::Remote(remote) => {
248 let request = remote
249 .upstream_client
250 .request(proto::GetDebugAdapterBinary {
251 session_id: session_id.to_proto(),
252 project_id: remote.upstream_project_id,
253 worktree_id: worktree.read(cx).id().to_proto(),
254 definition: Some(definition.to_proto()),
255 });
256 let remote = remote.remote_client.clone();
257
258 cx.spawn(async move |_, cx| {
259 let response = request.await?;
260 let binary = DebugAdapterBinary::from_proto(response)?;
261
262 let port_forwarding;
263 let connection;
264 if let Some(c) = binary.connection {
265 let host = Ipv4Addr::LOCALHOST;
266 let port;
267 if remote.read_with(cx, |remote, _cx| remote.shares_network_interface())? {
268 port = c.port;
269 port_forwarding = None;
270 } else {
271 port = dap::transport::TcpTransport::unused_port(host).await?;
272 port_forwarding = Some((port, c.host.to_string(), c.port));
273 }
274 connection = Some(TcpArguments {
275 port,
276 host,
277 timeout: c.timeout,
278 })
279 } else {
280 port_forwarding = None;
281 connection = None;
282 }
283
284 let command = remote.read_with(cx, |remote, _cx| {
285 remote.build_command(
286 binary.command,
287 &binary.arguments,
288 &binary.envs,
289 binary.cwd.map(|path| path.display().to_string()),
290 port_forwarding,
291 )
292 })??;
293
294 Ok(DebugAdapterBinary {
295 command: Some(command.program),
296 arguments: command.args,
297 envs: command.env,
298 cwd: None,
299 connection,
300 request_args: binary.request_args,
301 })
302 })
303 }
304 DapStoreMode::Collab => {
305 Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
306 }
307 }
308 }
309
310 pub fn debug_scenario_for_build_task(
311 &self,
312 build: TaskTemplate,
313 adapter: DebugAdapterName,
314 label: SharedString,
315 cx: &mut App,
316 ) -> Task<Option<DebugScenario>> {
317 let locators = DapRegistry::global(cx).locators();
318
319 cx.background_spawn(async move {
320 for locator in locators.values() {
321 if let Some(scenario) = locator.create_scenario(&build, &label, &adapter).await {
322 return Some(scenario);
323 }
324 }
325 None
326 })
327 }
328
329 pub fn run_debug_locator(
330 &mut self,
331 locator_name: &str,
332 build_command: SpawnInTerminal,
333 cx: &mut Context<Self>,
334 ) -> Task<Result<DebugRequest>> {
335 match &self.mode {
336 DapStoreMode::Local(_) => {
337 // Pre-resolve args with existing environment.
338 let locators = DapRegistry::global(cx).locators();
339 let locator = locators.get(locator_name);
340
341 if let Some(locator) = locator.cloned() {
342 cx.background_spawn(async move {
343 let result = locator
344 .run(build_command.clone())
345 .await
346 .log_with_level(log::Level::Error);
347 if let Some(result) = result {
348 return Ok(result);
349 }
350
351 anyhow::bail!(
352 "None of the locators for task `{}` completed successfully",
353 build_command.label
354 )
355 })
356 } else {
357 Task::ready(Err(anyhow!(
358 "Couldn't find any locator for task `{}`. Specify the `attach` or `launch` arguments in your debug scenario definition",
359 build_command.label
360 )))
361 }
362 }
363 DapStoreMode::Remote(remote) => {
364 let request = remote.upstream_client.request(proto::RunDebugLocators {
365 project_id: remote.upstream_project_id,
366 build_command: Some(build_command.to_proto()),
367 locator: locator_name.to_owned(),
368 });
369 cx.background_spawn(async move {
370 let response = request.await?;
371 DebugRequest::from_proto(response)
372 })
373 }
374 DapStoreMode::Collab => {
375 Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
376 }
377 }
378 }
379
380 fn as_local(&self) -> Option<&LocalDapStore> {
381 match &self.mode {
382 DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
383 _ => None,
384 }
385 }
386
387 pub fn new_session(
388 &mut self,
389 label: Option<SharedString>,
390 adapter: DebugAdapterName,
391 task_context: TaskContext,
392 parent_session: Option<Entity<Session>>,
393 quirks: SessionQuirks,
394 cx: &mut Context<Self>,
395 ) -> Entity<Session> {
396 let session_id = SessionId(util::post_inc(&mut self.next_session_id));
397
398 if let Some(session) = &parent_session {
399 session.update(cx, |session, _| {
400 session.add_child_session_id(session_id);
401 });
402 }
403
404 let session = Session::new(
405 self.breakpoint_store.clone(),
406 session_id,
407 parent_session,
408 label,
409 adapter,
410 task_context,
411 quirks,
412 cx,
413 );
414
415 self.sessions.insert(session_id, session.clone());
416 cx.notify();
417
418 cx.subscribe(&session, {
419 move |this: &mut DapStore, _, event: &SessionStateEvent, cx| match event {
420 SessionStateEvent::Shutdown => {
421 this.shutdown_session(session_id, cx).detach_and_log_err(cx);
422 }
423 SessionStateEvent::Restart | SessionStateEvent::SpawnChildSession { .. } => {}
424 SessionStateEvent::Running => {
425 cx.emit(DapStoreEvent::DebugClientStarted(session_id));
426 }
427 }
428 })
429 .detach();
430
431 session
432 }
433
434 pub fn boot_session(
435 &self,
436 session: Entity<Session>,
437 definition: DebugTaskDefinition,
438 worktree: Entity<Worktree>,
439 cx: &mut Context<Self>,
440 ) -> Task<Result<()>> {
441 let dap_store = cx.weak_entity();
442 let console = session.update(cx, |session, cx| session.console_output(cx));
443 let session_id = session.read(cx).session_id();
444
445 cx.spawn({
446 let session = session.clone();
447 async move |this, cx| {
448 let binary = this
449 .update(cx, |this, cx| {
450 this.get_debug_adapter_binary(
451 definition.clone(),
452 session_id,
453 &worktree,
454 console,
455 cx,
456 )
457 })?
458 .await?;
459 session
460 .update(cx, |session, cx| {
461 session.boot(binary, worktree, dap_store, cx)
462 })?
463 .await
464 }
465 })
466 }
467
468 pub fn session_by_id(
469 &self,
470 session_id: impl Borrow<SessionId>,
471 ) -> Option<Entity<session::Session>> {
472 let session_id = session_id.borrow();
473
474 self.sessions.get(session_id).cloned()
475 }
476 pub fn sessions(&self) -> impl Iterator<Item = &Entity<Session>> {
477 self.sessions.values()
478 }
479
480 pub fn capabilities_by_id(
481 &self,
482 session_id: impl Borrow<SessionId>,
483 cx: &App,
484 ) -> Option<Capabilities> {
485 let session_id = session_id.borrow();
486 self.sessions
487 .get(session_id)
488 .map(|client| client.read(cx).capabilities.clone())
489 }
490
491 pub fn breakpoint_store(&self) -> &Entity<BreakpointStore> {
492 &self.breakpoint_store
493 }
494
495 pub fn worktree_store(&self) -> &Entity<WorktreeStore> {
496 &self.worktree_store
497 }
498
499 #[allow(dead_code)]
500 async fn handle_ignore_breakpoint_state(
501 this: Entity<Self>,
502 envelope: TypedEnvelope<proto::IgnoreBreakpointState>,
503 mut cx: AsyncApp,
504 ) -> Result<()> {
505 let session_id = SessionId::from_proto(envelope.payload.session_id);
506
507 this.update(&mut cx, |this, cx| {
508 if let Some(session) = this.session_by_id(&session_id) {
509 session.update(cx, |session, cx| {
510 session.set_ignore_breakpoints(envelope.payload.ignore, cx)
511 })
512 } else {
513 Task::ready(HashMap::default())
514 }
515 })?
516 .await;
517
518 Ok(())
519 }
520
521 fn delegate(
522 &self,
523 worktree: &Entity<Worktree>,
524 console: UnboundedSender<String>,
525 cx: &mut App,
526 ) -> Arc<dyn DapDelegate> {
527 let Some(local_store) = self.as_local() else {
528 unimplemented!("Starting session on remote side");
529 };
530
531 Arc::new(DapAdapterDelegate::new(
532 local_store.fs.clone(),
533 worktree.read(cx).snapshot(),
534 console,
535 local_store.node_runtime.clone(),
536 local_store.http_client.clone(),
537 local_store.toolchain_store.clone(),
538 local_store.environment.update(cx, |env, cx| {
539 env.get_worktree_environment(worktree.clone(), cx)
540 }),
541 ))
542 }
543
544 pub fn resolve_inline_value_locations(
545 &self,
546 session: Entity<Session>,
547 stack_frame_id: StackFrameId,
548 buffer_handle: Entity<Buffer>,
549 inline_value_locations: Vec<dap::inline_value::InlineValueLocation>,
550 cx: &mut Context<Self>,
551 ) -> Task<Result<Vec<InlayHint>>> {
552 let snapshot = buffer_handle.read(cx).snapshot();
553 let local_variables =
554 session
555 .read(cx)
556 .variables_by_stack_frame_id(stack_frame_id, false, true);
557 let global_variables =
558 session
559 .read(cx)
560 .variables_by_stack_frame_id(stack_frame_id, true, false);
561
562 fn format_value(mut value: String) -> String {
563 const LIMIT: usize = 100;
564
565 if let Some(index) = value.find("\n") {
566 value.truncate(index);
567 value.push_str("…");
568 }
569
570 if value.len() > LIMIT {
571 let mut index = LIMIT;
572 // If index isn't a char boundary truncate will cause a panic
573 while !value.is_char_boundary(index) {
574 index -= 1;
575 }
576 value.truncate(index);
577 value.push_str("…");
578 }
579
580 format!(": {}", value)
581 }
582
583 cx.spawn(async move |_, cx| {
584 let mut inlay_hints = Vec::with_capacity(inline_value_locations.len());
585 for inline_value_location in inline_value_locations.iter() {
586 let point = snapshot.point_to_point_utf16(language::Point::new(
587 inline_value_location.row as u32,
588 inline_value_location.column as u32,
589 ));
590 let position = snapshot.anchor_after(point);
591
592 match inline_value_location.lookup {
593 VariableLookupKind::Variable => {
594 let variable_search =
595 if inline_value_location.scope
596 == dap::inline_value::VariableScope::Local
597 {
598 local_variables.iter().chain(global_variables.iter()).find(
599 |variable| variable.name == inline_value_location.variable_name,
600 )
601 } else {
602 global_variables.iter().find(|variable| {
603 variable.name == inline_value_location.variable_name
604 })
605 };
606
607 let Some(variable) = variable_search else {
608 continue;
609 };
610
611 inlay_hints.push(InlayHint {
612 position,
613 label: InlayHintLabel::String(format_value(variable.value.clone())),
614 kind: Some(InlayHintKind::Type),
615 padding_left: false,
616 padding_right: false,
617 tooltip: None,
618 resolve_state: ResolveState::Resolved,
619 });
620 }
621 VariableLookupKind::Expression => {
622 let Ok(eval_task) = session.read_with(cx, |session, _| {
623 session.mode.request_dap(EvaluateCommand {
624 expression: inline_value_location.variable_name.clone(),
625 frame_id: Some(stack_frame_id),
626 source: None,
627 context: Some(EvaluateArgumentsContext::Variables),
628 })
629 }) else {
630 continue;
631 };
632
633 if let Some(response) = eval_task.await.log_err() {
634 inlay_hints.push(InlayHint {
635 position,
636 label: InlayHintLabel::String(format_value(response.result)),
637 kind: Some(InlayHintKind::Type),
638 padding_left: false,
639 padding_right: false,
640 tooltip: None,
641 resolve_state: ResolveState::Resolved,
642 });
643 };
644 }
645 };
646 }
647
648 Ok(inlay_hints)
649 })
650 }
651
652 pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
653 let mut tasks = vec![];
654 for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
655 tasks.push(self.shutdown_session(session_id, cx));
656 }
657
658 cx.background_executor().spawn(async move {
659 futures::future::join_all(tasks).await;
660 })
661 }
662
663 pub fn shutdown_session(
664 &mut self,
665 session_id: SessionId,
666 cx: &mut Context<Self>,
667 ) -> Task<Result<()>> {
668 let Some(session) = self.sessions.remove(&session_id) else {
669 return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
670 };
671
672 let shutdown_children = session
673 .read(cx)
674 .child_session_ids()
675 .iter()
676 .map(|session_id| self.shutdown_session(*session_id, cx))
677 .collect::<Vec<_>>();
678
679 let shutdown_parent_task = if let Some(parent_session) = session
680 .read(cx)
681 .parent_id(cx)
682 .and_then(|session_id| self.session_by_id(session_id))
683 {
684 let shutdown_id = parent_session.update(cx, |parent_session, _| {
685 parent_session.remove_child_session_id(session_id);
686
687 if parent_session.child_session_ids().is_empty() {
688 Some(parent_session.session_id())
689 } else {
690 None
691 }
692 });
693
694 shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
695 } else {
696 None
697 };
698
699 let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
700
701 cx.emit(DapStoreEvent::DebugClientShutdown(session_id));
702
703 cx.background_spawn(async move {
704 if !shutdown_children.is_empty() {
705 let _ = join_all(shutdown_children).await;
706 }
707
708 shutdown_task.await;
709
710 if let Some(parent_task) = shutdown_parent_task {
711 parent_task.await?;
712 }
713
714 Ok(())
715 })
716 }
717
718 pub fn shared(
719 &mut self,
720 project_id: u64,
721 downstream_client: AnyProtoClient,
722 _: &mut Context<Self>,
723 ) {
724 self.downstream_client = Some((downstream_client, project_id));
725 }
726
727 pub fn unshared(&mut self, cx: &mut Context<Self>) {
728 self.downstream_client.take();
729
730 cx.notify();
731 }
732
733 async fn handle_run_debug_locator(
734 this: Entity<Self>,
735 envelope: TypedEnvelope<proto::RunDebugLocators>,
736 mut cx: AsyncApp,
737 ) -> Result<proto::DebugRequest> {
738 let task = envelope
739 .payload
740 .build_command
741 .context("missing definition")?;
742 let build_task = SpawnInTerminal::from_proto(task);
743 let locator = envelope.payload.locator;
744 let request = this
745 .update(&mut cx, |this, cx| {
746 this.run_debug_locator(&locator, build_task, cx)
747 })?
748 .await?;
749
750 Ok(request.to_proto())
751 }
752
753 async fn handle_get_debug_adapter_binary(
754 this: Entity<Self>,
755 envelope: TypedEnvelope<proto::GetDebugAdapterBinary>,
756 mut cx: AsyncApp,
757 ) -> Result<proto::DebugAdapterBinary> {
758 let definition = DebugTaskDefinition::from_proto(
759 envelope.payload.definition.context("missing definition")?,
760 )?;
761 let (tx, mut rx) = mpsc::unbounded();
762 let session_id = envelope.payload.session_id;
763 cx.spawn({
764 let this = this.clone();
765 async move |cx| {
766 while let Some(message) = rx.next().await {
767 this.read_with(cx, |this, _| {
768 if let Some((downstream, project_id)) = this.downstream_client.clone() {
769 downstream
770 .send(proto::LogToDebugConsole {
771 project_id,
772 session_id,
773 message,
774 })
775 .ok();
776 }
777 })
778 .ok();
779 }
780 }
781 })
782 .detach();
783
784 let worktree = this
785 .update(&mut cx, |this, cx| {
786 this.worktree_store
787 .read(cx)
788 .worktree_for_id(WorktreeId::from_proto(envelope.payload.worktree_id), cx)
789 })?
790 .context("Failed to find worktree with a given ID")?;
791 let binary = this
792 .update(&mut cx, |this, cx| {
793 this.get_debug_adapter_binary(
794 definition,
795 SessionId::from_proto(session_id),
796 &worktree,
797 tx,
798 cx,
799 )
800 })?
801 .await?;
802 Ok(binary.to_proto())
803 }
804
805 async fn handle_log_to_debug_console(
806 this: Entity<Self>,
807 envelope: TypedEnvelope<proto::LogToDebugConsole>,
808 mut cx: AsyncApp,
809 ) -> Result<()> {
810 let session_id = SessionId::from_proto(envelope.payload.session_id);
811 this.update(&mut cx, |this, cx| {
812 let Some(session) = this.sessions.get(&session_id) else {
813 return;
814 };
815 session.update(cx, |session, cx| {
816 session
817 .console_output(cx)
818 .unbounded_send(envelope.payload.message)
819 .ok();
820 })
821 })
822 }
823
824 pub fn sync_adapter_options(
825 &mut self,
826 session: &Entity<Session>,
827 cx: &App,
828 ) -> Arc<PersistedAdapterOptions> {
829 let session = session.read(cx);
830 let adapter = session.adapter();
831 let exceptions = session.exception_breakpoints();
832 let exception_breakpoints = exceptions
833 .map(|(exception, enabled)| {
834 (
835 exception.filter.clone(),
836 PersistedExceptionBreakpoint { enabled: *enabled },
837 )
838 })
839 .collect();
840 let options = Arc::new(PersistedAdapterOptions {
841 exception_breakpoints,
842 });
843 self.adapter_options.insert(adapter, options.clone());
844 options
845 }
846
847 pub fn set_adapter_options(
848 &mut self,
849 adapter: DebugAdapterName,
850 options: PersistedAdapterOptions,
851 ) {
852 self.adapter_options.insert(adapter, Arc::new(options));
853 }
854
855 pub fn adapter_options(&self, name: &str) -> Option<Arc<PersistedAdapterOptions>> {
856 self.adapter_options.get(name).cloned()
857 }
858
859 pub fn all_adapter_options(&self) -> &BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>> {
860 &self.adapter_options
861 }
862}
863
864#[derive(Clone)]
865pub struct DapAdapterDelegate {
866 fs: Arc<dyn Fs>,
867 console: mpsc::UnboundedSender<String>,
868 worktree: worktree::Snapshot,
869 node_runtime: NodeRuntime,
870 http_client: Arc<dyn HttpClient>,
871 toolchain_store: Arc<dyn LanguageToolchainStore>,
872 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
873}
874
875impl DapAdapterDelegate {
876 pub fn new(
877 fs: Arc<dyn Fs>,
878 worktree: worktree::Snapshot,
879 status: mpsc::UnboundedSender<String>,
880 node_runtime: NodeRuntime,
881 http_client: Arc<dyn HttpClient>,
882 toolchain_store: Arc<dyn LanguageToolchainStore>,
883 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
884 ) -> Self {
885 Self {
886 fs,
887 console: status,
888 worktree,
889 http_client,
890 node_runtime,
891 toolchain_store,
892 load_shell_env_task,
893 }
894 }
895}
896
897#[async_trait]
898impl dap::adapters::DapDelegate for DapAdapterDelegate {
899 fn worktree_id(&self) -> WorktreeId {
900 self.worktree.id()
901 }
902
903 fn worktree_root_path(&self) -> &Path {
904 self.worktree.abs_path()
905 }
906 fn http_client(&self) -> Arc<dyn HttpClient> {
907 self.http_client.clone()
908 }
909
910 fn node_runtime(&self) -> NodeRuntime {
911 self.node_runtime.clone()
912 }
913
914 fn fs(&self) -> Arc<dyn Fs> {
915 self.fs.clone()
916 }
917
918 fn output_to_console(&self, msg: String) {
919 self.console.unbounded_send(msg).ok();
920 }
921
922 #[cfg(not(target_os = "windows"))]
923 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
924 let worktree_abs_path = self.worktree.abs_path();
925 let shell_path = self.shell_env().await.get("PATH").cloned();
926 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
927 }
928
929 #[cfg(target_os = "windows")]
930 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
931 // On Windows, `PATH` is handled differently from Unix. Windows generally expects users to modify the `PATH` themselves,
932 // and every program loads it directly from the system at startup.
933 // There's also no concept of a default shell on Windows, and you can't really retrieve one, so trying to get shell environment variables
934 // from a specific directory doesn’t make sense on Windows.
935 which::which(command).ok()
936 }
937
938 async fn shell_env(&self) -> HashMap<String, String> {
939 let task = self.load_shell_env_task.clone();
940 task.await.unwrap_or_default()
941 }
942
943 fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
944 self.toolchain_store.clone()
945 }
946
947 async fn read_text_file(&self, path: &RelPath) -> Result<String> {
948 let entry = self
949 .worktree
950 .entry_for_path(path)
951 .with_context(|| format!("no worktree entry for path {path:?}"))?;
952 let abs_path = self.worktree.absolutize(&entry.path);
953
954 self.fs.load(&abs_path).await
955 }
956}