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