1use crate::persistence::DebuggerPaneItem;
2use crate::session::DebugSession;
3use crate::session::running::RunningState;
4use crate::{
5 ClearAllBreakpoints, Continue, CopyDebugAdapterArguments, Detach, FocusBreakpointList,
6 FocusConsole, FocusFrames, FocusLoadedSources, FocusModules, FocusTerminal, FocusVariables,
7 NewProcessModal, NewProcessMode, Pause, Restart, StepInto, StepOut, StepOver, Stop,
8 ToggleExpandItem, ToggleSessionPicker, ToggleThreadPicker, persistence, spawn_task_or_modal,
9};
10use anyhow::Result;
11use dap::adapters::DebugAdapterName;
12use dap::debugger_settings::DebugPanelDockPosition;
13use dap::{
14 ContinuedEvent, LoadedSourceEvent, ModuleEvent, OutputEvent, StoppedEvent, ThreadEvent,
15 client::SessionId, debugger_settings::DebuggerSettings,
16};
17use dap::{DapRegistry, StartDebuggingRequestArguments};
18use gpui::{
19 Action, App, AsyncWindowContext, ClipboardItem, Context, DismissEvent, Entity, EntityId,
20 EventEmitter, FocusHandle, Focusable, MouseButton, MouseDownEvent, Point, Subscription, Task,
21 WeakEntity, actions, anchored, deferred,
22};
23
24use language::Buffer;
25use project::debugger::session::{Session, SessionStateEvent};
26use project::{Fs, WorktreeId};
27use project::{Project, debugger::session::ThreadStatus};
28use rpc::proto::{self};
29use settings::Settings;
30use std::sync::Arc;
31use task::{DebugScenario, TaskContext};
32use ui::{ContextMenu, Divider, PopoverMenuHandle, Tooltip, prelude::*};
33use util::maybe;
34use workspace::SplitDirection;
35use workspace::{
36 Pane, Workspace,
37 dock::{DockPosition, Panel, PanelEvent},
38};
39
40pub enum DebugPanelEvent {
41 Exited(SessionId),
42 Terminated(SessionId),
43 Stopped {
44 client_id: SessionId,
45 event: StoppedEvent,
46 go_to_stack_frame: bool,
47 },
48 Thread((SessionId, ThreadEvent)),
49 Continued((SessionId, ContinuedEvent)),
50 Output((SessionId, OutputEvent)),
51 Module((SessionId, ModuleEvent)),
52 LoadedSource((SessionId, LoadedSourceEvent)),
53 ClientShutdown(SessionId),
54 CapabilitiesChanged(SessionId),
55}
56
57actions!(debug_panel, [ToggleFocus]);
58
59pub struct DebugPanel {
60 size: Pixels,
61 sessions: Vec<Entity<DebugSession>>,
62 active_session: Option<Entity<DebugSession>>,
63 project: Entity<Project>,
64 workspace: WeakEntity<Workspace>,
65 focus_handle: FocusHandle,
66 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
67 debug_scenario_scheduled_last: bool,
68 pub(crate) thread_picker_menu_handle: PopoverMenuHandle<ContextMenu>,
69 pub(crate) session_picker_menu_handle: PopoverMenuHandle<ContextMenu>,
70 fs: Arc<dyn Fs>,
71 is_zoomed: bool,
72 _subscriptions: [Subscription; 1],
73}
74
75impl DebugPanel {
76 pub fn new(
77 workspace: &Workspace,
78 window: &mut Window,
79 cx: &mut Context<Workspace>,
80 ) -> Entity<Self> {
81 cx.new(|cx| {
82 let project = workspace.project().clone();
83 let focus_handle = cx.focus_handle();
84 let thread_picker_menu_handle = PopoverMenuHandle::default();
85 let session_picker_menu_handle = PopoverMenuHandle::default();
86
87 let focus_subscription = cx.on_focus(
88 &focus_handle,
89 window,
90 |this: &mut DebugPanel, window, cx| {
91 this.focus_active_item(window, cx);
92 },
93 );
94
95 Self {
96 size: px(300.),
97 sessions: vec![],
98 active_session: None,
99 focus_handle,
100 project,
101 workspace: workspace.weak_handle(),
102 context_menu: None,
103 fs: workspace.app_state().fs.clone(),
104 thread_picker_menu_handle,
105 session_picker_menu_handle,
106 is_zoomed: false,
107 _subscriptions: [focus_subscription],
108 debug_scenario_scheduled_last: true,
109 }
110 })
111 }
112
113 pub(crate) fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
114 let Some(session) = self.active_session.clone() else {
115 return;
116 };
117 let active_pane = session
118 .read(cx)
119 .running_state()
120 .read(cx)
121 .active_pane()
122 .clone();
123 active_pane.update(cx, |pane, cx| {
124 pane.focus_active_item(window, cx);
125 });
126 }
127
128 pub(crate) fn sessions(&self) -> Vec<Entity<DebugSession>> {
129 self.sessions.clone()
130 }
131
132 pub fn active_session(&self) -> Option<Entity<DebugSession>> {
133 self.active_session.clone()
134 }
135
136 pub(crate) fn running_state(&self, cx: &mut App) -> Option<Entity<RunningState>> {
137 self.active_session()
138 .map(|session| session.read(cx).running_state().clone())
139 }
140
141 pub fn load(
142 workspace: WeakEntity<Workspace>,
143 cx: &mut AsyncWindowContext,
144 ) -> Task<Result<Entity<Self>>> {
145 cx.spawn(async move |cx| {
146 workspace.update_in(cx, |workspace, window, cx| {
147 let debug_panel = DebugPanel::new(workspace, window, cx);
148
149 workspace.register_action(|workspace, _: &ClearAllBreakpoints, _, cx| {
150 workspace.project().read(cx).breakpoint_store().update(
151 cx,
152 |breakpoint_store, cx| {
153 breakpoint_store.clear_breakpoints(cx);
154 },
155 )
156 });
157
158 workspace.set_debugger_provider(DebuggerProvider(debug_panel.clone()));
159
160 debug_panel
161 })
162 })
163 }
164
165 pub fn start_session(
166 &mut self,
167 scenario: DebugScenario,
168 task_context: TaskContext,
169 active_buffer: Option<Entity<Buffer>>,
170 worktree_id: Option<WorktreeId>,
171 window: &mut Window,
172 cx: &mut Context<Self>,
173 ) {
174 let dap_store = self.project.read(cx).dap_store();
175 let session = dap_store.update(cx, |dap_store, cx| {
176 dap_store.new_session(
177 scenario.label.clone(),
178 DebugAdapterName(scenario.adapter.clone()),
179 task_context.clone(),
180 None,
181 cx,
182 )
183 });
184 let worktree = worktree_id.or_else(|| {
185 active_buffer
186 .as_ref()
187 .and_then(|buffer| buffer.read(cx).file())
188 .map(|f| f.worktree_id(cx))
189 });
190 let Some(worktree) = worktree
191 .and_then(|id| self.project.read(cx).worktree_for_id(id, cx))
192 .or_else(|| self.project.read(cx).visible_worktrees(cx).next())
193 else {
194 log::debug!("Could not find a worktree to spawn the debug session in");
195 return;
196 };
197 self.debug_scenario_scheduled_last = true;
198 if let Some(inventory) = self
199 .project
200 .read(cx)
201 .task_store()
202 .read(cx)
203 .task_inventory()
204 .cloned()
205 {
206 inventory.update(cx, |inventory, _| {
207 inventory.scenario_scheduled(scenario.clone());
208 })
209 }
210 let task = cx.spawn_in(window, {
211 let session = session.clone();
212 async move |this, cx| {
213 let debug_session =
214 Self::register_session(this.clone(), session.clone(), true, cx).await?;
215 let definition = debug_session
216 .update_in(cx, |debug_session, window, cx| {
217 debug_session.running_state().update(cx, |running, cx| {
218 running.resolve_scenario(
219 scenario,
220 task_context,
221 active_buffer,
222 worktree_id,
223 window,
224 cx,
225 )
226 })
227 })?
228 .await?;
229 dap_store
230 .update(cx, |dap_store, cx| {
231 dap_store.boot_session(session.clone(), definition, worktree, cx)
232 })?
233 .await
234 }
235 });
236
237 cx.spawn(async move |_, cx| {
238 if let Err(error) = task.await {
239 log::error!("{error}");
240 session
241 .update(cx, |session, cx| {
242 session
243 .console_output(cx)
244 .unbounded_send(format!("error: {}", error))
245 .ok();
246 session.shutdown(cx)
247 })?
248 .await;
249 }
250 anyhow::Ok(())
251 })
252 .detach_and_log_err(cx);
253 }
254
255 pub(crate) fn rerun_last_session(
256 &mut self,
257 workspace: &mut Workspace,
258 window: &mut Window,
259 cx: &mut Context<Self>,
260 ) {
261 let task_store = workspace.project().read(cx).task_store().clone();
262 let Some(task_inventory) = task_store.read(cx).task_inventory() else {
263 return;
264 };
265 let workspace = self.workspace.clone();
266 let Some(scenario) = task_inventory.read(cx).last_scheduled_scenario().cloned() else {
267 window.defer(cx, move |window, cx| {
268 workspace
269 .update(cx, |workspace, cx| {
270 NewProcessModal::show(workspace, window, NewProcessMode::Debug, None, cx);
271 })
272 .ok();
273 });
274 return;
275 };
276
277 cx.spawn_in(window, async move |this, cx| {
278 let task_contexts = workspace
279 .update_in(cx, |workspace, window, cx| {
280 tasks_ui::task_contexts(workspace, window, cx)
281 })?
282 .await;
283
284 let task_context = task_contexts.active_context().cloned().unwrap_or_default();
285 let worktree_id = task_contexts.worktree();
286
287 this.update_in(cx, |this, window, cx| {
288 this.start_session(
289 scenario.clone(),
290 task_context,
291 None,
292 worktree_id,
293 window,
294 cx,
295 );
296 })
297 })
298 .detach();
299 }
300
301 pub(crate) async fn register_session(
302 this: WeakEntity<Self>,
303 session: Entity<Session>,
304 focus: bool,
305 cx: &mut AsyncWindowContext,
306 ) -> Result<Entity<DebugSession>> {
307 let debug_session = register_session_inner(&this, session, cx).await?;
308
309 let workspace = this.update_in(cx, |this, window, cx| {
310 if focus {
311 this.activate_session(debug_session.clone(), window, cx);
312 }
313
314 this.workspace.clone()
315 })?;
316 workspace.update_in(cx, |workspace, window, cx| {
317 workspace.focus_panel::<Self>(window, cx);
318 })?;
319 Ok(debug_session)
320 }
321
322 pub(crate) fn handle_restart_request(
323 &mut self,
324 mut curr_session: Entity<Session>,
325 window: &mut Window,
326 cx: &mut Context<Self>,
327 ) {
328 while let Some(parent_session) = curr_session.read(cx).parent_session().cloned() {
329 curr_session = parent_session;
330 }
331
332 let Some(worktree) = curr_session.read(cx).worktree() else {
333 log::error!("Attempted to restart a non-running session");
334 return;
335 };
336
337 let dap_store_handle = self.project.read(cx).dap_store().clone();
338 let label = curr_session.read(cx).label().clone();
339 let adapter = curr_session.read(cx).adapter().clone();
340 let binary = curr_session.read(cx).binary().cloned().unwrap();
341 let task = curr_session.update(cx, |session, cx| session.shutdown(cx));
342 let task_context = curr_session.read(cx).task_context().clone();
343
344 cx.spawn_in(window, async move |this, cx| {
345 task.await;
346
347 let (session, task) = dap_store_handle.update(cx, |dap_store, cx| {
348 let session = dap_store.new_session(label, adapter, task_context, None, cx);
349
350 let task = session.update(cx, |session, cx| {
351 session.boot(binary, worktree, dap_store_handle.downgrade(), cx)
352 });
353 (session, task)
354 })?;
355 Self::register_session(this.clone(), session.clone(), true, cx).await?;
356
357 if let Err(error) = task.await {
358 session
359 .update(cx, |session, cx| {
360 session
361 .console_output(cx)
362 .unbounded_send(format!(
363 "Session failed to restart with error: {}",
364 error
365 ))
366 .ok();
367 session.shutdown(cx)
368 })?
369 .await;
370
371 return Err(error);
372 };
373
374 Ok(())
375 })
376 .detach_and_log_err(cx);
377 }
378
379 pub fn handle_start_debugging_request(
380 &mut self,
381 request: &StartDebuggingRequestArguments,
382 parent_session: Entity<Session>,
383 window: &mut Window,
384 cx: &mut Context<Self>,
385 ) {
386 let Some(worktree) = parent_session.read(cx).worktree() else {
387 log::error!("Attempted to start a child-session from a non-running session");
388 return;
389 };
390
391 let dap_store_handle = self.project.read(cx).dap_store().clone();
392 let label = self.label_for_child_session(&parent_session, request, cx);
393 let adapter = parent_session.read(cx).adapter().clone();
394 let Some(mut binary) = parent_session.read(cx).binary().cloned() else {
395 log::error!("Attempted to start a child-session without a binary");
396 return;
397 };
398 let task_context = parent_session.read(cx).task_context().clone();
399 binary.request_args = request.clone();
400 cx.spawn_in(window, async move |this, cx| {
401 let (session, task) = dap_store_handle.update(cx, |dap_store, cx| {
402 let session = dap_store.new_session(
403 label,
404 adapter,
405 task_context,
406 Some(parent_session.clone()),
407 cx,
408 );
409
410 let task = session.update(cx, |session, cx| {
411 session.boot(binary, worktree, dap_store_handle.downgrade(), cx)
412 });
413 (session, task)
414 })?;
415 // Focus child sessions if the parent has never emitted a stopped event;
416 // this improves our JavaScript experience, as it always spawns a "main" session that then spawns subsessions.
417 let parent_ever_stopped =
418 parent_session.update(cx, |this, _| this.has_ever_stopped())?;
419 Self::register_session(this, session, !parent_ever_stopped, cx).await?;
420 task.await
421 })
422 .detach_and_log_err(cx);
423 }
424
425 pub(crate) fn close_session(
426 &mut self,
427 entity_id: EntityId,
428 window: &mut Window,
429 cx: &mut Context<Self>,
430 ) {
431 let Some(session) = self
432 .sessions
433 .iter()
434 .find(|other| entity_id == other.entity_id())
435 .cloned()
436 else {
437 return;
438 };
439 session.update(cx, |this, cx| {
440 this.running_state().update(cx, |this, cx| {
441 this.serialize_layout(window, cx);
442 });
443 });
444 let session_id = session.update(cx, |this, cx| this.session_id(cx));
445 let should_prompt = self
446 .project
447 .update(cx, |this, cx| {
448 let session = this.dap_store().read(cx).session_by_id(session_id);
449 session.map(|session| !session.read(cx).is_terminated())
450 })
451 .unwrap_or_default();
452
453 cx.spawn_in(window, async move |this, cx| {
454 if should_prompt {
455 let response = cx.prompt(
456 gpui::PromptLevel::Warning,
457 "This Debug Session is still running. Are you sure you want to terminate it?",
458 None,
459 &["Yes", "No"],
460 );
461 if response.await == Ok(1) {
462 return;
463 }
464 }
465 session.update(cx, |session, cx| session.shutdown(cx)).ok();
466 this.update(cx, |this, cx| {
467 this.sessions.retain(|other| entity_id != other.entity_id());
468
469 if let Some(active_session_id) = this
470 .active_session
471 .as_ref()
472 .map(|session| session.entity_id())
473 {
474 if active_session_id == entity_id {
475 this.active_session = this.sessions.first().cloned();
476 }
477 }
478 cx.notify()
479 })
480 .ok();
481 })
482 .detach();
483 }
484
485 pub(crate) fn deploy_context_menu(
486 &mut self,
487 position: Point<Pixels>,
488 window: &mut Window,
489 cx: &mut Context<Self>,
490 ) {
491 if let Some(running_state) = self
492 .active_session
493 .as_ref()
494 .map(|session| session.read(cx).running_state().clone())
495 {
496 let pane_items_status = running_state.read(cx).pane_items_status(cx);
497 let this = cx.weak_entity();
498
499 let context_menu = ContextMenu::build(window, cx, |mut menu, _window, _cx| {
500 for (item_kind, is_visible) in pane_items_status.into_iter() {
501 menu = menu.toggleable_entry(item_kind, is_visible, IconPosition::End, None, {
502 let this = this.clone();
503 move |window, cx| {
504 this.update(cx, |this, cx| {
505 if let Some(running_state) = this
506 .active_session
507 .as_ref()
508 .map(|session| session.read(cx).running_state().clone())
509 {
510 running_state.update(cx, |state, cx| {
511 if is_visible {
512 state.remove_pane_item(item_kind, window, cx);
513 } else {
514 state.add_pane_item(item_kind, position, window, cx);
515 }
516 })
517 }
518 })
519 .ok();
520 }
521 });
522 }
523
524 menu
525 });
526
527 window.focus(&context_menu.focus_handle(cx));
528 let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
529 this.context_menu.take();
530 cx.notify();
531 });
532 self.context_menu = Some((context_menu, position, subscription));
533 }
534 }
535
536 fn copy_debug_adapter_arguments(
537 &mut self,
538 _: &CopyDebugAdapterArguments,
539 _window: &mut Window,
540 cx: &mut Context<Self>,
541 ) {
542 let content = maybe!({
543 let mut session = self.active_session()?.read(cx).session(cx);
544 while let Some(parent) = session.read(cx).parent_session().cloned() {
545 session = parent;
546 }
547 let binary = session.read(cx).binary()?;
548 let content = serde_json::to_string_pretty(&binary).ok()?;
549 Some(content)
550 });
551 if let Some(content) = content {
552 cx.write_to_clipboard(ClipboardItem::new_string(content));
553 }
554 }
555
556 pub(crate) fn top_controls_strip(
557 &mut self,
558 window: &mut Window,
559 cx: &mut Context<Self>,
560 ) -> Option<Div> {
561 let active_session = self.active_session.clone();
562 let focus_handle = self.focus_handle.clone();
563 let is_side = self.position(window, cx).axis() == gpui::Axis::Horizontal;
564 let div = if is_side { v_flex() } else { h_flex() };
565
566 let new_session_button = || {
567 IconButton::new("debug-new-session", IconName::Plus)
568 .icon_size(IconSize::Small)
569 .on_click({
570 move |_, window, cx| window.dispatch_action(crate::Start.boxed_clone(), cx)
571 })
572 .tooltip({
573 let focus_handle = focus_handle.clone();
574 move |window, cx| {
575 Tooltip::for_action_in(
576 "Start Debug Session",
577 &crate::Start,
578 &focus_handle,
579 window,
580 cx,
581 )
582 }
583 })
584 };
585 let documentation_button = || {
586 IconButton::new("debug-open-documentation", IconName::CircleHelp)
587 .icon_size(IconSize::Small)
588 .on_click(move |_, _, cx| cx.open_url("https://zed.dev/docs/debugger"))
589 .tooltip(Tooltip::text("Open Documentation"))
590 };
591
592 Some(
593 div.border_b_1()
594 .border_color(cx.theme().colors().border)
595 .p_1()
596 .justify_between()
597 .w_full()
598 .when(is_side, |this| this.gap_1())
599 .child(
600 h_flex()
601 .child(
602 h_flex().gap_2().w_full().when_some(
603 active_session
604 .as_ref()
605 .map(|session| session.read(cx).running_state()),
606 |this, running_state| {
607 let thread_status =
608 running_state.read(cx).thread_status(cx).unwrap_or(
609 project::debugger::session::ThreadStatus::Exited,
610 );
611 let capabilities = running_state.read(cx).capabilities(cx);
612 let supports_detach =
613 running_state.read(cx).session().read(cx).is_attached();
614 this.map(|this| {
615 if thread_status == ThreadStatus::Running {
616 this.child(
617 IconButton::new(
618 "debug-pause",
619 IconName::DebugPause,
620 )
621 .icon_size(IconSize::XSmall)
622 .shape(ui::IconButtonShape::Square)
623 .on_click(window.listener_for(
624 &running_state,
625 |this, _, _window, cx| {
626 this.pause_thread(cx);
627 },
628 ))
629 .tooltip({
630 let focus_handle = focus_handle.clone();
631 move |window, cx| {
632 Tooltip::for_action_in(
633 "Pause program",
634 &Pause,
635 &focus_handle,
636 window,
637 cx,
638 )
639 }
640 }),
641 )
642 } else {
643 this.child(
644 IconButton::new(
645 "debug-continue",
646 IconName::DebugContinue,
647 )
648 .icon_size(IconSize::XSmall)
649 .shape(ui::IconButtonShape::Square)
650 .on_click(window.listener_for(
651 &running_state,
652 |this, _, _window, cx| this.continue_thread(cx),
653 ))
654 .disabled(thread_status != ThreadStatus::Stopped)
655 .tooltip({
656 let focus_handle = focus_handle.clone();
657 move |window, cx| {
658 Tooltip::for_action_in(
659 "Continue program",
660 &Continue,
661 &focus_handle,
662 window,
663 cx,
664 )
665 }
666 }),
667 )
668 }
669 })
670 .child(
671 IconButton::new("debug-step-over", IconName::ArrowRight)
672 .icon_size(IconSize::XSmall)
673 .shape(ui::IconButtonShape::Square)
674 .on_click(window.listener_for(
675 &running_state,
676 |this, _, _window, cx| {
677 this.step_over(cx);
678 },
679 ))
680 .disabled(thread_status != ThreadStatus::Stopped)
681 .tooltip({
682 let focus_handle = focus_handle.clone();
683 move |window, cx| {
684 Tooltip::for_action_in(
685 "Step over",
686 &StepOver,
687 &focus_handle,
688 window,
689 cx,
690 )
691 }
692 }),
693 )
694 .child(
695 IconButton::new("debug-step-out", IconName::ArrowUpRight)
696 .icon_size(IconSize::XSmall)
697 .shape(ui::IconButtonShape::Square)
698 .on_click(window.listener_for(
699 &running_state,
700 |this, _, _window, cx| {
701 this.step_out(cx);
702 },
703 ))
704 .disabled(thread_status != ThreadStatus::Stopped)
705 .tooltip({
706 let focus_handle = focus_handle.clone();
707 move |window, cx| {
708 Tooltip::for_action_in(
709 "Step out",
710 &StepOut,
711 &focus_handle,
712 window,
713 cx,
714 )
715 }
716 }),
717 )
718 .child(
719 IconButton::new(
720 "debug-step-into",
721 IconName::ArrowDownRight,
722 )
723 .icon_size(IconSize::XSmall)
724 .shape(ui::IconButtonShape::Square)
725 .on_click(window.listener_for(
726 &running_state,
727 |this, _, _window, cx| {
728 this.step_in(cx);
729 },
730 ))
731 .disabled(thread_status != ThreadStatus::Stopped)
732 .tooltip({
733 let focus_handle = focus_handle.clone();
734 move |window, cx| {
735 Tooltip::for_action_in(
736 "Step in",
737 &StepInto,
738 &focus_handle,
739 window,
740 cx,
741 )
742 }
743 }),
744 )
745 .child(Divider::vertical())
746 .child(
747 IconButton::new("debug-restart", IconName::DebugRestart)
748 .icon_size(IconSize::XSmall)
749 .on_click(window.listener_for(
750 &running_state,
751 |this, _, _window, cx| {
752 this.restart_session(cx);
753 },
754 ))
755 .tooltip({
756 let focus_handle = focus_handle.clone();
757 move |window, cx| {
758 Tooltip::for_action_in(
759 "Restart",
760 &Restart,
761 &focus_handle,
762 window,
763 cx,
764 )
765 }
766 }),
767 )
768 .child(
769 IconButton::new("debug-stop", IconName::Power)
770 .icon_size(IconSize::XSmall)
771 .on_click(window.listener_for(
772 &running_state,
773 |this, _, _window, cx| {
774 this.stop_thread(cx);
775 },
776 ))
777 .disabled(
778 thread_status != ThreadStatus::Stopped
779 && thread_status != ThreadStatus::Running,
780 )
781 .tooltip({
782 let focus_handle = focus_handle.clone();
783 let label = if capabilities
784 .supports_terminate_threads_request
785 .unwrap_or_default()
786 {
787 "Terminate Thread"
788 } else {
789 "Terminate All Threads"
790 };
791 move |window, cx| {
792 Tooltip::for_action_in(
793 label,
794 &Stop,
795 &focus_handle,
796 window,
797 cx,
798 )
799 }
800 }),
801 )
802 .when(
803 supports_detach,
804 |div| {
805 div.child(
806 IconButton::new(
807 "debug-disconnect",
808 IconName::DebugDetach,
809 )
810 .disabled(
811 thread_status != ThreadStatus::Stopped
812 && thread_status != ThreadStatus::Running,
813 )
814 .icon_size(IconSize::XSmall)
815 .on_click(window.listener_for(
816 &running_state,
817 |this, _, _, cx| {
818 this.detach_client(cx);
819 },
820 ))
821 .tooltip({
822 let focus_handle = focus_handle.clone();
823 move |window, cx| {
824 Tooltip::for_action_in(
825 "Detach",
826 &Detach,
827 &focus_handle,
828 window,
829 cx,
830 )
831 }
832 }),
833 )
834 },
835 )
836 },
837 ),
838 )
839 .justify_around()
840 .when(is_side, |this| {
841 this.child(new_session_button())
842 .child(documentation_button())
843 }),
844 )
845 .child(
846 h_flex()
847 .gap_2()
848 .when(is_side, |this| this.justify_between())
849 .child(
850 h_flex().when_some(
851 active_session
852 .as_ref()
853 .map(|session| session.read(cx).running_state())
854 .cloned(),
855 |this, running_state| {
856 this.children({
857 let running_state = running_state.clone();
858 let threads =
859 running_state.update(cx, |running_state, cx| {
860 let session = running_state.session();
861 session
862 .update(cx, |session, cx| session.threads(cx))
863 });
864
865 self.render_thread_dropdown(
866 &running_state,
867 threads,
868 window,
869 cx,
870 )
871 })
872 .when(!is_side, |this| this.gap_2().child(Divider::vertical()))
873 },
874 ),
875 )
876 .child(
877 h_flex()
878 .children(self.render_session_menu(
879 self.active_session(),
880 self.running_state(cx),
881 window,
882 cx,
883 ))
884 .when(!is_side, |this| {
885 this.child(new_session_button())
886 .child(documentation_button())
887 }),
888 ),
889 ),
890 )
891 }
892
893 pub(crate) fn activate_pane_in_direction(
894 &mut self,
895 direction: SplitDirection,
896 window: &mut Window,
897 cx: &mut Context<Self>,
898 ) {
899 if let Some(session) = self.active_session() {
900 session.update(cx, |session, cx| {
901 session.running_state().update(cx, |running, cx| {
902 running.activate_pane_in_direction(direction, window, cx);
903 })
904 });
905 }
906 }
907
908 pub(crate) fn activate_item(
909 &mut self,
910 item: DebuggerPaneItem,
911 window: &mut Window,
912 cx: &mut Context<Self>,
913 ) {
914 if let Some(session) = self.active_session() {
915 session.update(cx, |session, cx| {
916 session.running_state().update(cx, |running, cx| {
917 running.activate_item(item, window, cx);
918 });
919 });
920 }
921 }
922
923 pub(crate) fn activate_session_by_id(
924 &mut self,
925 session_id: SessionId,
926 window: &mut Window,
927 cx: &mut Context<Self>,
928 ) {
929 if let Some(session) = self
930 .sessions
931 .iter()
932 .find(|session| session.read(cx).session_id(cx) == session_id)
933 {
934 self.activate_session(session.clone(), window, cx);
935 }
936 }
937
938 pub(crate) fn activate_session(
939 &mut self,
940 session_item: Entity<DebugSession>,
941 window: &mut Window,
942 cx: &mut Context<Self>,
943 ) {
944 debug_assert!(self.sessions.contains(&session_item));
945 session_item.focus_handle(cx).focus(window);
946 session_item.update(cx, |this, cx| {
947 this.running_state().update(cx, |this, cx| {
948 this.go_to_selected_stack_frame(window, cx);
949 });
950 });
951 self.active_session = Some(session_item);
952 cx.notify();
953 }
954
955 // TODO: restore once we have proper comment preserving file edits
956 // pub(crate) fn save_scenario(
957 // &self,
958 // scenario: &DebugScenario,
959 // worktree_id: WorktreeId,
960 // window: &mut Window,
961 // cx: &mut App,
962 // ) -> Task<Result<ProjectPath>> {
963 // self.workspace
964 // .update(cx, |workspace, cx| {
965 // let Some(mut path) = workspace.absolute_path_of_worktree(worktree_id, cx) else {
966 // return Task::ready(Err(anyhow!("Couldn't get worktree path")));
967 // };
968
969 // let serialized_scenario = serde_json::to_value(scenario);
970
971 // cx.spawn_in(window, async move |workspace, cx| {
972 // let serialized_scenario = serialized_scenario?;
973 // let fs =
974 // workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
975
976 // path.push(paths::local_settings_folder_relative_path());
977 // if !fs.is_dir(path.as_path()).await {
978 // fs.create_dir(path.as_path()).await?;
979 // }
980 // path.pop();
981
982 // path.push(paths::local_debug_file_relative_path());
983 // let path = path.as_path();
984
985 // if !fs.is_file(path).await {
986 // fs.create_file(path, Default::default()).await?;
987 // fs.write(
988 // path,
989 // initial_local_debug_tasks_content().to_string().as_bytes(),
990 // )
991 // .await?;
992 // }
993
994 // let content = fs.load(path).await?;
995 // let mut values =
996 // serde_json_lenient::from_str::<Vec<serde_json::Value>>(&content)?;
997 // values.push(serialized_scenario);
998 // fs.save(
999 // path,
1000 // &serde_json_lenient::to_string_pretty(&values).map(Into::into)?,
1001 // Default::default(),
1002 // )
1003 // .await?;
1004
1005 // workspace.update(cx, |workspace, cx| {
1006 // workspace
1007 // .project()
1008 // .read(cx)
1009 // .project_path_for_absolute_path(&path, cx)
1010 // .context(
1011 // "Couldn't get project path for .zed/debug.json in active worktree",
1012 // )
1013 // })?
1014 // })
1015 // })
1016 // .unwrap_or_else(|err| Task::ready(Err(err)))
1017 // }
1018
1019 pub(crate) fn toggle_thread_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1020 self.thread_picker_menu_handle.toggle(window, cx);
1021 }
1022
1023 pub(crate) fn toggle_session_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1024 self.session_picker_menu_handle.toggle(window, cx);
1025 }
1026
1027 fn toggle_zoom(
1028 &mut self,
1029 _: &workspace::ToggleZoom,
1030 window: &mut Window,
1031 cx: &mut Context<Self>,
1032 ) {
1033 if self.is_zoomed {
1034 cx.emit(PanelEvent::ZoomOut);
1035 } else {
1036 if !self.focus_handle(cx).contains_focused(window, cx) {
1037 cx.focus_self(window);
1038 }
1039 cx.emit(PanelEvent::ZoomIn);
1040 }
1041 }
1042
1043 fn label_for_child_session(
1044 &self,
1045 parent_session: &Entity<Session>,
1046 request: &StartDebuggingRequestArguments,
1047 cx: &mut Context<'_, Self>,
1048 ) -> SharedString {
1049 let adapter = parent_session.read(cx).adapter();
1050 if let Some(adapter) = DapRegistry::global(cx).adapter(&adapter) {
1051 if let Some(label) = adapter.label_for_child_session(request) {
1052 return label.into();
1053 }
1054 }
1055 let mut label = parent_session.read(cx).label().clone();
1056 if !label.ends_with("(child)") {
1057 label = format!("{label} (child)").into();
1058 }
1059 label
1060 }
1061}
1062
1063async fn register_session_inner(
1064 this: &WeakEntity<DebugPanel>,
1065 session: Entity<Session>,
1066 cx: &mut AsyncWindowContext,
1067) -> Result<Entity<DebugSession>> {
1068 let adapter_name = session.read_with(cx, |session, _| session.adapter())?;
1069 this.update_in(cx, |_, window, cx| {
1070 cx.subscribe_in(
1071 &session,
1072 window,
1073 move |this, session, event: &SessionStateEvent, window, cx| match event {
1074 SessionStateEvent::Restart => {
1075 this.handle_restart_request(session.clone(), window, cx);
1076 }
1077 SessionStateEvent::SpawnChildSession { request } => {
1078 this.handle_start_debugging_request(request, session.clone(), window, cx);
1079 }
1080 _ => {}
1081 },
1082 )
1083 .detach();
1084 })
1085 .ok();
1086 let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
1087 let debug_session = this.update_in(cx, |this, window, cx| {
1088 let parent_session = this
1089 .sessions
1090 .iter()
1091 .find(|p| Some(p.read(cx).session_id(cx)) == session.read(cx).parent_id(cx))
1092 .cloned();
1093 this.sessions.retain(|session| {
1094 !session
1095 .read(cx)
1096 .running_state()
1097 .read(cx)
1098 .session()
1099 .read(cx)
1100 .is_terminated()
1101 });
1102
1103 let debug_session = DebugSession::running(
1104 this.project.clone(),
1105 this.workspace.clone(),
1106 parent_session.map(|p| p.read(cx).running_state().read(cx).debug_terminal.clone()),
1107 session,
1108 serialized_layout,
1109 this.position(window, cx).axis(),
1110 window,
1111 cx,
1112 );
1113
1114 // We might want to make this an event subscription and only notify when a new thread is selected
1115 // This is used to filter the command menu correctly
1116 cx.observe(
1117 &debug_session.read(cx).running_state().clone(),
1118 |_, _, cx| cx.notify(),
1119 )
1120 .detach();
1121
1122 this.sessions.push(debug_session.clone());
1123
1124 debug_session
1125 })?;
1126 Ok(debug_session)
1127}
1128
1129impl EventEmitter<PanelEvent> for DebugPanel {}
1130impl EventEmitter<DebugPanelEvent> for DebugPanel {}
1131
1132impl Focusable for DebugPanel {
1133 fn focus_handle(&self, _: &App) -> FocusHandle {
1134 self.focus_handle.clone()
1135 }
1136}
1137
1138impl Panel for DebugPanel {
1139 fn persistent_name() -> &'static str {
1140 "DebugPanel"
1141 }
1142
1143 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1144 match DebuggerSettings::get_global(cx).dock {
1145 DebugPanelDockPosition::Left => DockPosition::Left,
1146 DebugPanelDockPosition::Bottom => DockPosition::Bottom,
1147 DebugPanelDockPosition::Right => DockPosition::Right,
1148 }
1149 }
1150
1151 fn position_is_valid(&self, _: DockPosition) -> bool {
1152 true
1153 }
1154
1155 fn set_position(
1156 &mut self,
1157 position: DockPosition,
1158 window: &mut Window,
1159 cx: &mut Context<Self>,
1160 ) {
1161 if position.axis() != self.position(window, cx).axis() {
1162 self.sessions.iter().for_each(|session_item| {
1163 session_item.update(cx, |item, cx| {
1164 item.running_state()
1165 .update(cx, |state, _| state.invert_axies())
1166 })
1167 });
1168 }
1169
1170 settings::update_settings_file::<DebuggerSettings>(
1171 self.fs.clone(),
1172 cx,
1173 move |settings, _| {
1174 let dock = match position {
1175 DockPosition::Left => DebugPanelDockPosition::Left,
1176 DockPosition::Bottom => DebugPanelDockPosition::Bottom,
1177 DockPosition::Right => DebugPanelDockPosition::Right,
1178 };
1179 settings.dock = dock;
1180 },
1181 );
1182 }
1183
1184 fn size(&self, _window: &Window, _: &App) -> Pixels {
1185 self.size
1186 }
1187
1188 fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1189 self.size = size.unwrap_or(px(300.));
1190 }
1191
1192 fn remote_id() -> Option<proto::PanelId> {
1193 Some(proto::PanelId::DebugPanel)
1194 }
1195
1196 fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
1197 Some(IconName::Debug)
1198 }
1199
1200 fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
1201 if DebuggerSettings::get_global(cx).button {
1202 Some("Debug Panel")
1203 } else {
1204 None
1205 }
1206 }
1207
1208 fn toggle_action(&self) -> Box<dyn Action> {
1209 Box::new(ToggleFocus)
1210 }
1211
1212 fn pane(&self) -> Option<Entity<Pane>> {
1213 None
1214 }
1215
1216 fn activation_priority(&self) -> u32 {
1217 9
1218 }
1219
1220 fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
1221
1222 fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1223 self.is_zoomed
1224 }
1225
1226 fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1227 self.is_zoomed = zoomed;
1228 cx.notify();
1229 }
1230}
1231
1232impl Render for DebugPanel {
1233 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1234 let has_sessions = self.sessions.len() > 0;
1235 let this = cx.weak_entity();
1236 debug_assert_eq!(has_sessions, self.active_session.is_some());
1237
1238 if self
1239 .active_session
1240 .as_ref()
1241 .map(|session| session.read(cx).running_state())
1242 .map(|state| state.read(cx).has_open_context_menu(cx))
1243 .unwrap_or(false)
1244 {
1245 self.context_menu.take();
1246 }
1247
1248 v_flex()
1249 .size_full()
1250 .key_context("DebugPanel")
1251 .child(h_flex().children(self.top_controls_strip(window, cx)))
1252 .track_focus(&self.focus_handle(cx))
1253 .on_action({
1254 let this = this.clone();
1255 move |_: &workspace::ActivatePaneLeft, window, cx| {
1256 this.update(cx, |this, cx| {
1257 this.activate_pane_in_direction(SplitDirection::Left, window, cx);
1258 })
1259 .ok();
1260 }
1261 })
1262 .on_action({
1263 let this = this.clone();
1264 move |_: &workspace::ActivatePaneRight, window, cx| {
1265 this.update(cx, |this, cx| {
1266 this.activate_pane_in_direction(SplitDirection::Right, window, cx);
1267 })
1268 .ok();
1269 }
1270 })
1271 .on_action({
1272 let this = this.clone();
1273 move |_: &workspace::ActivatePaneUp, window, cx| {
1274 this.update(cx, |this, cx| {
1275 this.activate_pane_in_direction(SplitDirection::Up, window, cx);
1276 })
1277 .ok();
1278 }
1279 })
1280 .on_action({
1281 let this = this.clone();
1282 move |_: &workspace::ActivatePaneDown, window, cx| {
1283 this.update(cx, |this, cx| {
1284 this.activate_pane_in_direction(SplitDirection::Down, window, cx);
1285 })
1286 .ok();
1287 }
1288 })
1289 .on_action({
1290 let this = this.clone();
1291 move |_: &FocusConsole, window, cx| {
1292 this.update(cx, |this, cx| {
1293 this.activate_item(DebuggerPaneItem::Console, window, cx);
1294 })
1295 .ok();
1296 }
1297 })
1298 .on_action({
1299 let this = this.clone();
1300 move |_: &FocusVariables, window, cx| {
1301 this.update(cx, |this, cx| {
1302 this.activate_item(DebuggerPaneItem::Variables, window, cx);
1303 })
1304 .ok();
1305 }
1306 })
1307 .on_action({
1308 let this = this.clone();
1309 move |_: &FocusBreakpointList, window, cx| {
1310 this.update(cx, |this, cx| {
1311 this.activate_item(DebuggerPaneItem::BreakpointList, window, cx);
1312 })
1313 .ok();
1314 }
1315 })
1316 .on_action({
1317 let this = this.clone();
1318 move |_: &FocusFrames, window, cx| {
1319 this.update(cx, |this, cx| {
1320 this.activate_item(DebuggerPaneItem::Frames, window, cx);
1321 })
1322 .ok();
1323 }
1324 })
1325 .on_action({
1326 let this = this.clone();
1327 move |_: &FocusModules, window, cx| {
1328 this.update(cx, |this, cx| {
1329 this.activate_item(DebuggerPaneItem::Modules, window, cx);
1330 })
1331 .ok();
1332 }
1333 })
1334 .on_action({
1335 let this = this.clone();
1336 move |_: &FocusLoadedSources, window, cx| {
1337 this.update(cx, |this, cx| {
1338 this.activate_item(DebuggerPaneItem::LoadedSources, window, cx);
1339 })
1340 .ok();
1341 }
1342 })
1343 .on_action({
1344 let this = this.clone();
1345 move |_: &FocusTerminal, window, cx| {
1346 this.update(cx, |this, cx| {
1347 this.activate_item(DebuggerPaneItem::Terminal, window, cx);
1348 })
1349 .ok();
1350 }
1351 })
1352 .on_action({
1353 let this = this.clone();
1354 move |_: &ToggleThreadPicker, window, cx| {
1355 this.update(cx, |this, cx| {
1356 this.toggle_thread_picker(window, cx);
1357 })
1358 .ok();
1359 }
1360 })
1361 .on_action({
1362 let this = this.clone();
1363 move |_: &ToggleSessionPicker, window, cx| {
1364 this.update(cx, |this, cx| {
1365 this.toggle_session_picker(window, cx);
1366 })
1367 .ok();
1368 }
1369 })
1370 .on_action(cx.listener(Self::toggle_zoom))
1371 .on_action(cx.listener(|panel, _: &ToggleExpandItem, _, cx| {
1372 let Some(session) = panel.active_session() else {
1373 return;
1374 };
1375 let active_pane = session
1376 .read(cx)
1377 .running_state()
1378 .read(cx)
1379 .active_pane()
1380 .clone();
1381 active_pane.update(cx, |pane, cx| {
1382 let is_zoomed = pane.is_zoomed();
1383 pane.set_zoomed(!is_zoomed, cx);
1384 });
1385 cx.notify();
1386 }))
1387 .on_action(cx.listener(Self::copy_debug_adapter_arguments))
1388 .when(self.active_session.is_some(), |this| {
1389 this.on_mouse_down(
1390 MouseButton::Right,
1391 cx.listener(|this, event: &MouseDownEvent, window, cx| {
1392 if this
1393 .active_session
1394 .as_ref()
1395 .map(|session| {
1396 let state = session.read(cx).running_state();
1397 state.read(cx).has_pane_at_position(event.position)
1398 })
1399 .unwrap_or(false)
1400 {
1401 this.deploy_context_menu(event.position, window, cx);
1402 }
1403 }),
1404 )
1405 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1406 deferred(
1407 anchored()
1408 .position(*position)
1409 .anchor(gpui::Corner::TopLeft)
1410 .child(menu.clone()),
1411 )
1412 .with_priority(1)
1413 }))
1414 })
1415 .map(|this| {
1416 if has_sessions {
1417 this.children(self.active_session.clone())
1418 } else {
1419 this.child(
1420 v_flex()
1421 .h_full()
1422 .gap_1()
1423 .items_center()
1424 .justify_center()
1425 .child(
1426 h_flex().child(
1427 Label::new("No Debugging Sessions")
1428 .size(LabelSize::Small)
1429 .color(Color::Muted),
1430 ),
1431 )
1432 .child(
1433 h_flex().flex_shrink().child(
1434 Button::new("spawn-new-session-empty-state", "New Session")
1435 .size(ButtonSize::Large)
1436 .on_click(|_, window, cx| {
1437 window.dispatch_action(crate::Start.boxed_clone(), cx);
1438 }),
1439 ),
1440 ),
1441 )
1442 }
1443 })
1444 .into_any()
1445 }
1446}
1447
1448struct DebuggerProvider(Entity<DebugPanel>);
1449
1450impl workspace::DebuggerProvider for DebuggerProvider {
1451 fn start_session(
1452 &self,
1453 definition: DebugScenario,
1454 context: TaskContext,
1455 buffer: Option<Entity<Buffer>>,
1456 window: &mut Window,
1457 cx: &mut App,
1458 ) {
1459 self.0.update(cx, |_, cx| {
1460 cx.defer_in(window, |this, window, cx| {
1461 this.start_session(definition, context, buffer, None, window, cx);
1462 })
1463 })
1464 }
1465
1466 fn spawn_task_or_modal(
1467 &self,
1468 workspace: &mut Workspace,
1469 action: &tasks_ui::Spawn,
1470 window: &mut Window,
1471 cx: &mut Context<Workspace>,
1472 ) {
1473 spawn_task_or_modal(workspace, action, window, cx);
1474 }
1475
1476 fn debug_scenario_scheduled(&self, cx: &mut App) {
1477 self.0.update(cx, |this, _| {
1478 this.debug_scenario_scheduled_last = true;
1479 });
1480 }
1481
1482 fn task_scheduled(&self, cx: &mut App) {
1483 self.0.update(cx, |this, _| {
1484 this.debug_scenario_scheduled_last = false;
1485 })
1486 }
1487
1488 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool {
1489 self.0.read(cx).debug_scenario_scheduled_last
1490 }
1491
1492 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus> {
1493 let session = self.0.read(cx).active_session()?;
1494 let thread = session.read(cx).running_state().read(cx).thread_id()?;
1495 session.read(cx).session(cx).read(cx).thread_state(thread)
1496 }
1497}