1pub(crate) mod breakpoint_list;
2pub(crate) mod console;
3pub(crate) mod loaded_source_list;
4pub(crate) mod memory_view;
5pub(crate) mod module_list;
6pub mod stack_frame_list;
7pub mod variable_list;
8use std::{any::Any, ops::ControlFlow, path::PathBuf, sync::Arc, time::Duration};
9
10use crate::{
11 ToggleExpandItem,
12 new_process_modal::resolve_path,
13 persistence::{self, DebuggerPaneItem, SerializedLayout},
14 session::running::memory_view::MemoryView,
15};
16
17use super::DebugPanelItemEvent;
18use anyhow::{Context as _, Result, anyhow};
19use breakpoint_list::BreakpointList;
20use collections::{HashMap, IndexMap};
21use console::Console;
22use dap::{
23 Capabilities, DapRegistry, RunInTerminalRequestArguments, Thread,
24 adapters::{DebugAdapterName, DebugTaskDefinition},
25 client::SessionId,
26 debugger_settings::DebuggerSettings,
27};
28use futures::{SinkExt, channel::mpsc};
29use gpui::{
30 Action as _, AnyView, AppContext, Axis, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
31 NoAction, Pixels, Point, Subscription, Task, WeakEntity,
32};
33use language::Buffer;
34use loaded_source_list::LoadedSourceList;
35use module_list::ModuleList;
36use project::{
37 DebugScenarioContext, Project, WorktreeId,
38 debugger::session::{self, Session, SessionEvent, SessionStateEvent, ThreadId, ThreadStatus},
39};
40use rpc::proto::ViewId;
41use serde_json::Value;
42use settings::Settings;
43use stack_frame_list::StackFrameList;
44use task::{
45 BuildTaskDefinition, DebugScenario, ShellBuilder, SpawnInTerminal, TaskContext, ZedDebugConfig,
46 substitute_variables_in_str,
47};
48use terminal_view::TerminalView;
49use ui::{
50 FluentBuilder, IntoElement, Render, StatefulInteractiveElement, Tab, Tooltip, VisibleOnHover,
51 VisualContext, prelude::*,
52};
53use util::ResultExt;
54use variable_list::VariableList;
55use workspace::{
56 ActivePaneDecorator, DraggedTab, Item, ItemHandle, Member, Pane, PaneGroup, SplitDirection,
57 Workspace, item::TabContentParams, move_item, pane::Event,
58};
59
60pub struct RunningState {
61 session: Entity<Session>,
62 thread_id: Option<ThreadId>,
63 focus_handle: FocusHandle,
64 _remote_id: Option<ViewId>,
65 workspace: WeakEntity<Workspace>,
66 session_id: SessionId,
67 variable_list: Entity<variable_list::VariableList>,
68 _subscriptions: Vec<Subscription>,
69 stack_frame_list: Entity<stack_frame_list::StackFrameList>,
70 loaded_sources_list: Entity<LoadedSourceList>,
71 pub debug_terminal: Entity<DebugTerminal>,
72 module_list: Entity<module_list::ModuleList>,
73 console: Entity<Console>,
74 breakpoint_list: Entity<BreakpointList>,
75 panes: PaneGroup,
76 active_pane: Entity<Pane>,
77 pane_close_subscriptions: HashMap<EntityId, Subscription>,
78 dock_axis: Axis,
79 _schedule_serialize: Option<Task<()>>,
80 pub(crate) scenario: Option<DebugScenario>,
81 pub(crate) scenario_context: Option<DebugScenarioContext>,
82 memory_view: Entity<MemoryView>,
83}
84
85impl RunningState {
86 pub(crate) fn thread_id(&self) -> Option<ThreadId> {
87 self.thread_id
88 }
89
90 pub(crate) fn active_pane(&self) -> &Entity<Pane> {
91 &self.active_pane
92 }
93}
94
95impl Render for RunningState {
96 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
97 let zoomed_pane = self
98 .panes
99 .panes()
100 .into_iter()
101 .find(|pane| pane.read(cx).is_zoomed());
102
103 let active = self.panes.panes().into_iter().next();
104 let pane = if let Some(zoomed_pane) = zoomed_pane {
105 zoomed_pane.update(cx, |pane, cx| pane.render(window, cx).into_any_element())
106 } else if let Some(active) = active {
107 self.panes
108 .render(
109 None,
110 &ActivePaneDecorator::new(active, &self.workspace),
111 window,
112 cx,
113 )
114 .into_any_element()
115 } else {
116 div().into_any_element()
117 };
118 let thread_status = self
119 .thread_id
120 .map(|thread_id| self.session.read(cx).thread_status(thread_id))
121 .unwrap_or(ThreadStatus::Exited);
122
123 self.variable_list.update(cx, |this, cx| {
124 this.disabled(thread_status != ThreadStatus::Stopped, cx);
125 });
126 v_flex()
127 .size_full()
128 .key_context("DebugSessionItem")
129 .track_focus(&self.focus_handle(cx))
130 .child(h_flex().flex_1().child(pane))
131 }
132}
133
134pub(crate) struct SubView {
135 inner: AnyView,
136 item_focus_handle: FocusHandle,
137 kind: DebuggerPaneItem,
138 show_indicator: Box<dyn Fn(&App) -> bool>,
139 actions: Option<Box<dyn FnMut(&mut Window, &mut App) -> AnyElement>>,
140 hovered: bool,
141}
142
143impl SubView {
144 pub(crate) fn new(
145 item_focus_handle: FocusHandle,
146 view: AnyView,
147 kind: DebuggerPaneItem,
148 cx: &mut App,
149 ) -> Entity<Self> {
150 cx.new(|_| Self {
151 kind,
152 inner: view,
153 item_focus_handle,
154 show_indicator: Box::new(|_| false),
155 actions: None,
156 hovered: false,
157 })
158 }
159
160 pub(crate) fn stack_frame_list(
161 stack_frame_list: Entity<StackFrameList>,
162 cx: &mut App,
163 ) -> Entity<Self> {
164 let weak_list = stack_frame_list.downgrade();
165 let this = Self::new(
166 stack_frame_list.focus_handle(cx),
167 stack_frame_list.into(),
168 DebuggerPaneItem::Frames,
169 cx,
170 );
171
172 this.update(cx, |this, _| {
173 this.with_actions(Box::new(move |_, cx| {
174 weak_list
175 .update(cx, |this, _| this.render_control_strip())
176 .unwrap_or_else(|_| div().into_any_element())
177 }));
178 });
179
180 this
181 }
182
183 pub(crate) fn console(console: Entity<Console>, cx: &mut App) -> Entity<Self> {
184 let weak_console = console.downgrade();
185 let this = Self::new(
186 console.focus_handle(cx),
187 console.into(),
188 DebuggerPaneItem::Console,
189 cx,
190 );
191 this.update(cx, |this, _| {
192 this.with_indicator(Box::new(move |cx| {
193 weak_console
194 .read_with(cx, |console, cx| console.show_indicator(cx))
195 .unwrap_or_default()
196 }))
197 });
198 this
199 }
200
201 pub(crate) fn breakpoint_list(list: Entity<BreakpointList>, cx: &mut App) -> Entity<Self> {
202 let weak_list = list.downgrade();
203 let focus_handle = list.focus_handle(cx);
204 let this = Self::new(
205 focus_handle,
206 list.into(),
207 DebuggerPaneItem::BreakpointList,
208 cx,
209 );
210
211 this.update(cx, |this, _| {
212 this.with_actions(Box::new(move |_, cx| {
213 weak_list
214 .update(cx, |this, _| this.render_control_strip())
215 .unwrap_or_else(|_| div().into_any_element())
216 }));
217 });
218 this
219 }
220
221 pub(crate) fn view_kind(&self) -> DebuggerPaneItem {
222 self.kind
223 }
224 pub(crate) fn with_indicator(&mut self, indicator: Box<dyn Fn(&App) -> bool>) {
225 self.show_indicator = indicator;
226 }
227 pub(crate) fn with_actions(
228 &mut self,
229 actions: Box<dyn FnMut(&mut Window, &mut App) -> AnyElement>,
230 ) {
231 self.actions = Some(actions);
232 }
233}
234impl Focusable for SubView {
235 fn focus_handle(&self, _: &App) -> FocusHandle {
236 self.item_focus_handle.clone()
237 }
238}
239impl EventEmitter<()> for SubView {}
240impl Item for SubView {
241 type Event = ();
242
243 /// This is used to serialize debugger pane layouts
244 /// A SharedString gets converted to a enum and back during serialization/deserialization.
245 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
246 self.kind.to_shared_string()
247 }
248
249 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
250 Some(self.kind.tab_tooltip())
251 }
252
253 fn tab_content(
254 &self,
255 params: workspace::item::TabContentParams,
256 _: &Window,
257 cx: &App,
258 ) -> AnyElement {
259 let label = Label::new(self.kind.to_shared_string())
260 .size(ui::LabelSize::Small)
261 .color(params.text_color())
262 .line_height_style(ui::LineHeightStyle::UiLabel);
263
264 if !params.selected && self.show_indicator.as_ref()(cx) {
265 return h_flex()
266 .justify_between()
267 .child(ui::Indicator::dot())
268 .gap_2()
269 .child(label)
270 .into_any_element();
271 }
272
273 label.into_any_element()
274 }
275}
276
277impl Render for SubView {
278 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
279 v_flex()
280 .id(SharedString::from(format!(
281 "subview-container-{}",
282 self.kind.to_shared_string()
283 )))
284 .on_hover(cx.listener(|this, hovered, _, cx| {
285 this.hovered = *hovered;
286 cx.notify();
287 }))
288 .size_full()
289 // Add border unconditionally to prevent layout shifts on focus changes.
290 .border_1()
291 .when(self.item_focus_handle.contains_focused(window, cx), |el| {
292 el.border_color(cx.theme().colors().pane_focused_border)
293 })
294 .child(self.inner.clone())
295 }
296}
297
298pub(crate) fn new_debugger_pane(
299 workspace: WeakEntity<Workspace>,
300 project: Entity<Project>,
301 window: &mut Window,
302 cx: &mut Context<RunningState>,
303) -> Entity<Pane> {
304 let weak_running = cx.weak_entity();
305 let custom_drop_handle = {
306 let workspace = workspace.clone();
307 let project = project.downgrade();
308 let weak_running = weak_running.clone();
309 move |pane: &mut Pane, any: &dyn Any, window: &mut Window, cx: &mut Context<Pane>| {
310 let Some(tab) = any.downcast_ref::<DraggedTab>() else {
311 return ControlFlow::Break(());
312 };
313 let Some(project) = project.upgrade() else {
314 return ControlFlow::Break(());
315 };
316 let this_pane = cx.entity();
317 let item = if tab.pane == this_pane {
318 pane.item_for_index(tab.ix)
319 } else {
320 tab.pane.read(cx).item_for_index(tab.ix)
321 };
322 let Some(item) = item.filter(|item| item.downcast::<SubView>().is_some()) else {
323 return ControlFlow::Break(());
324 };
325
326 let source = tab.pane.clone();
327 let item_id_to_move = item.item_id();
328
329 let Ok(new_split_pane) = pane
330 .drag_split_direction()
331 .map(|split_direction| {
332 weak_running.update(cx, |running, cx| {
333 let new_pane =
334 new_debugger_pane(workspace.clone(), project.clone(), window, cx);
335 let _previous_subscription = running.pane_close_subscriptions.insert(
336 new_pane.entity_id(),
337 cx.subscribe_in(&new_pane, window, RunningState::handle_pane_event),
338 );
339 debug_assert!(_previous_subscription.is_none());
340 running
341 .panes
342 .split(&this_pane, &new_pane, split_direction)?;
343 anyhow::Ok(new_pane)
344 })
345 })
346 .transpose()
347 else {
348 return ControlFlow::Break(());
349 };
350
351 match new_split_pane.transpose() {
352 // Source pane may be the one currently updated, so defer the move.
353 Ok(Some(new_pane)) => cx
354 .spawn_in(window, async move |_, cx| {
355 cx.update(|window, cx| {
356 move_item(
357 &source,
358 &new_pane,
359 item_id_to_move,
360 new_pane.read(cx).active_item_index(),
361 true,
362 window,
363 cx,
364 );
365 })
366 .ok();
367 })
368 .detach(),
369 // If we drop into existing pane or current pane,
370 // regular pane drop handler will take care of it,
371 // using the right tab index for the operation.
372 Ok(None) => return ControlFlow::Continue(()),
373 err @ Err(_) => {
374 err.log_err();
375 return ControlFlow::Break(());
376 }
377 };
378
379 ControlFlow::Break(())
380 }
381 };
382
383 cx.new(move |cx| {
384 let mut pane = Pane::new(
385 workspace.clone(),
386 project.clone(),
387 Default::default(),
388 None,
389 NoAction.boxed_clone(),
390 window,
391 cx,
392 );
393 let focus_handle = pane.focus_handle(cx);
394 pane.set_can_split(Some(Arc::new({
395 let weak_running = weak_running.clone();
396 move |pane, dragged_item, _window, cx| {
397 if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
398 let is_current_pane = tab.pane == cx.entity();
399 let Some(can_drag_away) = weak_running
400 .read_with(cx, |running_state, _| {
401 let current_panes = running_state.panes.panes();
402 !current_panes.contains(&&tab.pane)
403 || current_panes.len() > 1
404 || (!is_current_pane || pane.items_len() > 1)
405 })
406 .ok()
407 else {
408 return false;
409 };
410 if can_drag_away {
411 let item = if is_current_pane {
412 pane.item_for_index(tab.ix)
413 } else {
414 tab.pane.read(cx).item_for_index(tab.ix)
415 };
416 if let Some(item) = item {
417 return item.downcast::<SubView>().is_some();
418 }
419 }
420 }
421 false
422 }
423 })));
424 pane.set_can_toggle_zoom(false, cx);
425 pane.display_nav_history_buttons(None);
426 pane.set_custom_drop_handle(cx, custom_drop_handle);
427 pane.set_should_display_tab_bar(|_, _| true);
428 pane.set_render_tab_bar_buttons(cx, |_, _, _| (None, None));
429 pane.set_render_tab_bar(cx, {
430 move |pane, window, cx| {
431 let active_pane_item = pane.active_item();
432 let pane_group_id: SharedString =
433 format!("pane-zoom-button-hover-{}", cx.entity_id()).into();
434 let as_subview = active_pane_item
435 .as_ref()
436 .and_then(|item| item.downcast::<SubView>());
437 let is_hovered = as_subview
438 .as_ref()
439 .is_some_and(|item| item.read(cx).hovered);
440
441 h_flex()
442 .track_focus(&focus_handle)
443 .group(pane_group_id.clone())
444 .pl_1p5()
445 .pr_1()
446 .justify_between()
447 .border_b_1()
448 .border_color(cx.theme().colors().border)
449 .bg(cx.theme().colors().tab_bar_background)
450 .on_action(|_: &menu::Cancel, window, cx| {
451 if cx.stop_active_drag(window) {
452 } else {
453 cx.propagate();
454 }
455 })
456 .child(
457 h_flex()
458 .w_full()
459 .gap_1()
460 .h(Tab::container_height(cx))
461 .drag_over::<DraggedTab>(|bar, _, _, cx| {
462 bar.bg(cx.theme().colors().drop_target_background)
463 })
464 .on_drop(cx.listener(
465 move |this, dragged_tab: &DraggedTab, window, cx| {
466 this.drag_split_direction = None;
467 this.handle_tab_drop(dragged_tab, this.items_len(), window, cx)
468 },
469 ))
470 .children(pane.items().enumerate().map(|(ix, item)| {
471 let selected = active_pane_item
472 .as_ref()
473 .is_some_and(|active| active.item_id() == item.item_id());
474 let deemphasized = !pane.has_focus(window, cx);
475 let item_ = item.boxed_clone();
476 div()
477 .id(SharedString::from(format!(
478 "debugger_tab_{}",
479 item.item_id().as_u64()
480 )))
481 .p_1()
482 .rounded_md()
483 .cursor_pointer()
484 .when_some(item.tab_tooltip_text(cx), |this, tooltip| {
485 this.tooltip(Tooltip::text(tooltip))
486 })
487 .map(|this| {
488 let theme = cx.theme();
489 if selected {
490 let color = theme.colors().tab_active_background;
491 let color = if deemphasized {
492 color.opacity(0.5)
493 } else {
494 color
495 };
496 this.bg(color)
497 } else {
498 let hover_color = theme.colors().element_hover;
499 this.hover(|style| style.bg(hover_color))
500 }
501 })
502 .on_click(cx.listener(move |this, _, window, cx| {
503 let index = this.index_for_item(&*item_);
504 if let Some(index) = index {
505 this.activate_item(index, true, true, window, cx);
506 }
507 }))
508 .child(item.tab_content(
509 TabContentParams {
510 selected,
511 deemphasized,
512 ..Default::default()
513 },
514 window,
515 cx,
516 ))
517 .on_drop(cx.listener(
518 move |this, dragged_tab: &DraggedTab, window, cx| {
519 this.drag_split_direction = None;
520 this.handle_tab_drop(dragged_tab, ix, window, cx)
521 },
522 ))
523 .on_drag(
524 DraggedTab {
525 item: item.boxed_clone(),
526 pane: cx.entity(),
527 detail: 0,
528 is_active: selected,
529 ix,
530 },
531 |tab, _, _, cx| cx.new(|_| tab.clone()),
532 )
533 })),
534 )
535 .child({
536 let zoomed = pane.is_zoomed();
537
538 h_flex()
539 .visible_on_hover(pane_group_id)
540 .when(is_hovered, |this| this.visible())
541 .when_some(as_subview.as_ref(), |this, subview| {
542 subview.update(cx, |view, cx| {
543 let Some(additional_actions) = view.actions.as_mut() else {
544 return this;
545 };
546 this.child(additional_actions(window, cx))
547 })
548 })
549 .child(
550 IconButton::new(
551 SharedString::from(format!(
552 "debug-toggle-zoom-{}",
553 cx.entity_id()
554 )),
555 if zoomed {
556 IconName::Minimize
557 } else {
558 IconName::Maximize
559 },
560 )
561 .icon_size(IconSize::Small)
562 .on_click(cx.listener(move |pane, _, _, cx| {
563 let is_zoomed = pane.is_zoomed();
564 pane.set_zoomed(!is_zoomed, cx);
565 cx.notify();
566 }))
567 .tooltip({
568 let focus_handle = focus_handle.clone();
569 move |window, cx| {
570 let zoomed_text =
571 if zoomed { "Minimize" } else { "Expand" };
572 Tooltip::for_action_in(
573 zoomed_text,
574 &ToggleExpandItem,
575 &focus_handle,
576 window,
577 cx,
578 )
579 }
580 }),
581 )
582 })
583 .into_any_element()
584 }
585 });
586 pane
587 })
588}
589
590pub struct DebugTerminal {
591 pub terminal: Option<Entity<TerminalView>>,
592 focus_handle: FocusHandle,
593 _subscriptions: [Subscription; 1],
594}
595
596impl DebugTerminal {
597 fn empty(window: &mut Window, cx: &mut Context<Self>) -> Self {
598 let focus_handle = cx.focus_handle();
599 let focus_subscription = cx.on_focus(&focus_handle, window, |this, window, cx| {
600 if let Some(terminal) = this.terminal.as_ref() {
601 terminal.focus_handle(cx).focus(window);
602 }
603 });
604
605 Self {
606 terminal: None,
607 focus_handle,
608 _subscriptions: [focus_subscription],
609 }
610 }
611}
612
613impl gpui::Render for DebugTerminal {
614 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
615 div()
616 .track_focus(&self.focus_handle)
617 .size_full()
618 .bg(cx.theme().colors().editor_background)
619 .children(self.terminal.clone())
620 }
621}
622impl Focusable for DebugTerminal {
623 fn focus_handle(&self, _cx: &App) -> FocusHandle {
624 self.focus_handle.clone()
625 }
626}
627
628impl RunningState {
629 // todo(debugger) move this to util and make it so you pass a closure to it that converts a string
630 pub(crate) fn substitute_variables_in_config(
631 config: &mut serde_json::Value,
632 context: &TaskContext,
633 ) {
634 match config {
635 serde_json::Value::Object(obj) => {
636 obj.values_mut()
637 .for_each(|value| Self::substitute_variables_in_config(value, context));
638 }
639 serde_json::Value::Array(array) => {
640 array
641 .iter_mut()
642 .for_each(|value| Self::substitute_variables_in_config(value, context));
643 }
644 serde_json::Value::String(s) => {
645 // Some built-in zed tasks wrap their arguments in quotes as they might contain spaces.
646 if s.starts_with("\"$ZED_") && s.ends_with('"') {
647 *s = s[1..s.len() - 1].to_string();
648 }
649 if let Some(substituted) = substitute_variables_in_str(s, context) {
650 *s = substituted;
651 }
652 }
653 _ => {}
654 }
655 }
656
657 pub(crate) fn relativize_paths(
658 key: Option<&str>,
659 config: &mut serde_json::Value,
660 context: &TaskContext,
661 ) {
662 match config {
663 serde_json::Value::Object(obj) => {
664 obj.iter_mut()
665 .for_each(|(key, value)| Self::relativize_paths(Some(key), value, context));
666 }
667 serde_json::Value::Array(array) => {
668 array
669 .iter_mut()
670 .for_each(|value| Self::relativize_paths(None, value, context));
671 }
672 serde_json::Value::String(s) if key == Some("program") || key == Some("cwd") => {
673 // Some built-in zed tasks wrap their arguments in quotes as they might contain spaces.
674 if s.starts_with("\"$ZED_") && s.ends_with('"') {
675 *s = s[1..s.len() - 1].to_string();
676 }
677 resolve_path(s);
678
679 if let Some(substituted) = substitute_variables_in_str(s, context) {
680 *s = substituted;
681 }
682 }
683 _ => {}
684 }
685 }
686
687 pub(crate) fn new(
688 session: Entity<Session>,
689 project: Entity<Project>,
690 workspace: WeakEntity<Workspace>,
691 parent_terminal: Option<Entity<DebugTerminal>>,
692 serialized_pane_layout: Option<SerializedLayout>,
693 dock_axis: Axis,
694 window: &mut Window,
695 cx: &mut Context<Self>,
696 ) -> Self {
697 let focus_handle = cx.focus_handle();
698 let session_id = session.read(cx).session_id();
699 let weak_state = cx.weak_entity();
700 let stack_frame_list = cx.new(|cx| {
701 StackFrameList::new(
702 workspace.clone(),
703 session.clone(),
704 weak_state.clone(),
705 window,
706 cx,
707 )
708 });
709
710 let debug_terminal =
711 parent_terminal.unwrap_or_else(|| cx.new(|cx| DebugTerminal::empty(window, cx)));
712 let memory_view = cx.new(|cx| {
713 MemoryView::new(
714 session.clone(),
715 workspace.clone(),
716 stack_frame_list.downgrade(),
717 window,
718 cx,
719 )
720 });
721 let variable_list = cx.new(|cx| {
722 VariableList::new(
723 session.clone(),
724 stack_frame_list.clone(),
725 memory_view.clone(),
726 weak_state.clone(),
727 window,
728 cx,
729 )
730 });
731
732 let module_list = cx.new(|cx| ModuleList::new(session.clone(), workspace.clone(), cx));
733
734 let loaded_source_list = cx.new(|cx| LoadedSourceList::new(session.clone(), cx));
735
736 let console = cx.new(|cx| {
737 Console::new(
738 session.clone(),
739 stack_frame_list.clone(),
740 variable_list.clone(),
741 window,
742 cx,
743 )
744 });
745
746 let breakpoint_list = BreakpointList::new(
747 Some(session.clone()),
748 workspace.clone(),
749 &project,
750 window,
751 cx,
752 );
753
754 let _subscriptions = vec![
755 cx.on_app_quit(move |this, cx| {
756 let shutdown = this
757 .session
758 .update(cx, |session, cx| session.on_app_quit(cx));
759 let terminal = this.debug_terminal.clone();
760 async move {
761 shutdown.await;
762 drop(terminal)
763 }
764 }),
765 cx.observe(&module_list, |_, _, cx| cx.notify()),
766 cx.subscribe_in(&session, window, |this, _, event, window, cx| {
767 match event {
768 SessionEvent::Stopped(thread_id) => {
769 let panel = this
770 .workspace
771 .update(cx, |workspace, cx| {
772 workspace.open_panel::<crate::DebugPanel>(window, cx);
773 workspace.panel::<crate::DebugPanel>(cx)
774 })
775 .log_err()
776 .flatten();
777
778 if let Some(thread_id) = thread_id {
779 this.select_thread(*thread_id, window, cx);
780 }
781 if let Some(panel) = panel {
782 let id = this.session_id;
783 window.defer(cx, move |window, cx| {
784 panel.update(cx, |this, cx| {
785 this.activate_session_by_id(id, window, cx);
786 })
787 })
788 }
789 }
790 SessionEvent::Threads => {
791 let threads = this.session.update(cx, |this, cx| this.threads(cx));
792 this.select_current_thread(&threads, window, cx);
793 }
794 SessionEvent::CapabilitiesLoaded => {
795 let capabilities = this.capabilities(cx);
796 if !capabilities.supports_modules_request.unwrap_or(false) {
797 this.remove_pane_item(DebuggerPaneItem::Modules, window, cx);
798 }
799 if !capabilities
800 .supports_loaded_sources_request
801 .unwrap_or(false)
802 {
803 this.remove_pane_item(DebuggerPaneItem::LoadedSources, window, cx);
804 }
805 }
806 SessionEvent::RunInTerminal { request, sender } => this
807 .handle_run_in_terminal(request, sender.clone(), window, cx)
808 .detach_and_log_err(cx),
809
810 _ => {}
811 }
812 cx.notify()
813 }),
814 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
815 this.serialize_layout(window, cx);
816 }),
817 cx.subscribe(
818 &session,
819 |this, session, event: &SessionStateEvent, cx| match event {
820 SessionStateEvent::Shutdown if session.read(cx).is_building() => {
821 this.shutdown(cx);
822 }
823 _ => {}
824 },
825 ),
826 ];
827
828 let mut pane_close_subscriptions = HashMap::default();
829 let panes = if let Some(root) = serialized_pane_layout.and_then(|serialized_layout| {
830 persistence::deserialize_pane_layout(
831 serialized_layout.panes,
832 dock_axis != serialized_layout.dock_axis,
833 &workspace,
834 &project,
835 &stack_frame_list,
836 &variable_list,
837 &module_list,
838 &console,
839 &breakpoint_list,
840 &loaded_source_list,
841 &debug_terminal,
842 &memory_view,
843 &mut pane_close_subscriptions,
844 window,
845 cx,
846 )
847 }) {
848 workspace::PaneGroup::with_root(root)
849 } else {
850 pane_close_subscriptions.clear();
851
852 let root = Self::default_pane_layout(
853 project,
854 &workspace,
855 &stack_frame_list,
856 &variable_list,
857 &console,
858 &breakpoint_list,
859 &debug_terminal,
860 dock_axis,
861 &mut pane_close_subscriptions,
862 window,
863 cx,
864 );
865
866 workspace::PaneGroup::with_root(root)
867 };
868 let active_pane = panes.first_pane();
869
870 Self {
871 memory_view,
872 session,
873 workspace,
874 focus_handle,
875 variable_list,
876 _subscriptions,
877 thread_id: None,
878 _remote_id: None,
879 stack_frame_list,
880 session_id,
881 panes,
882 active_pane,
883 module_list,
884 console,
885 breakpoint_list,
886 loaded_sources_list: loaded_source_list,
887 pane_close_subscriptions,
888 debug_terminal,
889 dock_axis,
890 _schedule_serialize: None,
891 scenario: None,
892 scenario_context: None,
893 }
894 }
895
896 pub(crate) fn remove_pane_item(
897 &mut self,
898 item_kind: DebuggerPaneItem,
899 window: &mut Window,
900 cx: &mut Context<Self>,
901 ) {
902 if let Some((pane, item_id)) = self.panes.panes().iter().find_map(|pane| {
903 Some(pane).zip(
904 pane.read(cx)
905 .items()
906 .find(|item| {
907 item.act_as::<SubView>(cx)
908 .is_some_and(|view| view.read(cx).kind == item_kind)
909 })
910 .map(|item| item.item_id()),
911 )
912 }) {
913 pane.update(cx, |pane, cx| {
914 pane.remove_item(item_id, false, true, window, cx)
915 })
916 }
917 }
918
919 pub(crate) fn has_pane_at_position(&self, position: Point<Pixels>) -> bool {
920 self.panes.pane_at_pixel_position(position).is_some()
921 }
922
923 pub(crate) fn resolve_scenario(
924 &self,
925 scenario: DebugScenario,
926 task_context: TaskContext,
927 buffer: Option<Entity<Buffer>>,
928 worktree_id: Option<WorktreeId>,
929 window: &Window,
930 cx: &mut Context<Self>,
931 ) -> Task<Result<DebugTaskDefinition>> {
932 let Some(workspace) = self.workspace.upgrade() else {
933 return Task::ready(Err(anyhow!("no workspace")));
934 };
935 let project = workspace.read(cx).project().clone();
936 let dap_store = project.read(cx).dap_store().downgrade();
937 let dap_registry = cx.global::<DapRegistry>().clone();
938 let task_store = project.read(cx).task_store().downgrade();
939 let weak_project = project.downgrade();
940 let weak_workspace = workspace.downgrade();
941 let remote_shell = project
942 .read(cx)
943 .remote_client()
944 .as_ref()
945 .and_then(|remote| remote.read(cx).shell());
946
947 cx.spawn_in(window, async move |this, cx| {
948 let DebugScenario {
949 adapter,
950 label,
951 build,
952 mut config,
953 tcp_connection,
954 } = scenario;
955 Self::relativize_paths(None, &mut config, &task_context);
956 Self::substitute_variables_in_config(&mut config, &task_context);
957
958 let request_type = match dap_registry
959 .adapter(&adapter)
960 .with_context(|| format!("{}: is not a valid adapter name", &adapter)) {
961 Ok(adapter) => adapter.request_kind(&config).await,
962 Err(e) => Err(e)
963 };
964
965
966 let config_is_valid = request_type.is_ok();
967 let mut extra_config = Value::Null;
968 let build_output = if let Some(build) = build {
969 let (task_template, locator_name) = match build {
970 BuildTaskDefinition::Template {
971 task_template,
972 locator_name,
973 } => (task_template, locator_name),
974 BuildTaskDefinition::ByName(ref label) => {
975 let task = task_store.update(cx, |this, cx| {
976 this.task_inventory().map(|inventory| {
977 inventory.read(cx).task_template_by_label(
978 buffer,
979 worktree_id,
980 label,
981 cx,
982 )
983 })
984 })?;
985 let task = match task {
986 Some(task) => task.await,
987 None => None,
988 }.with_context(|| format!("Couldn't find task template for {build:?}"))?;
989 (task, None)
990 }
991 };
992 let Some(task) = task_template.resolve_task("debug-build-task", &task_context) else {
993 anyhow::bail!("Could not resolve task variables within a debug scenario");
994 };
995
996 let locator_name = if let Some(locator_name) = locator_name {
997 extra_config = config.clone();
998 debug_assert!(!config_is_valid);
999 Some(locator_name)
1000 } else if !config_is_valid {
1001 let task = dap_store
1002 .update(cx, |this, cx| {
1003 this.debug_scenario_for_build_task(
1004 task.original_task().clone(),
1005 adapter.clone().into(),
1006 task.display_label().to_owned().into(),
1007 cx,
1008 )
1009
1010 });
1011 if let Ok(t) = task {
1012 t.await.and_then(|scenario| {
1013 extra_config = scenario.config;
1014 match scenario.build {
1015 Some(BuildTaskDefinition::Template {
1016 locator_name, ..
1017 }) => locator_name,
1018 _ => None,
1019 }
1020 })
1021 } else {
1022 None
1023 }
1024
1025 } else {
1026 None
1027 };
1028
1029 let builder = ShellBuilder::new(remote_shell.as_deref(), &task.resolved.shell);
1030 let command_label = builder.command_label(&task.resolved.command_label);
1031 let (command, args) =
1032 builder.build(task.resolved.command.clone(), &task.resolved.args);
1033
1034 let task_with_shell = SpawnInTerminal {
1035 command_label,
1036 command: Some(command),
1037 args,
1038 ..task.resolved.clone()
1039 };
1040 let terminal = project
1041 .update(cx, |project, cx| {
1042 project.create_terminal_task(
1043 task_with_shell.clone(),
1044 cx,
1045 )
1046 })?.await?;
1047
1048 let terminal_view = cx.new_window_entity(|window, cx| {
1049 TerminalView::new(
1050 terminal.clone(),
1051 weak_workspace,
1052 None,
1053 weak_project,
1054 window,
1055 cx,
1056 )
1057 })?;
1058
1059 this.update_in(cx, |this, window, cx| {
1060 this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1061 this.debug_terminal.update(cx, |debug_terminal, cx| {
1062 debug_terminal.terminal = Some(terminal_view);
1063 cx.notify();
1064 });
1065 })?;
1066
1067 let exit_status = terminal
1068 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1069 .await
1070 .context("Failed to wait for completed task")?;
1071
1072 if !exit_status.success() {
1073 anyhow::bail!("Build failed");
1074 }
1075 Some((task.resolved.clone(), locator_name, extra_config))
1076 } else {
1077 None
1078 };
1079
1080 if config_is_valid {
1081 } else if let Some((task, locator_name, extra_config)) = build_output {
1082 let locator_name =
1083 locator_name.with_context(|| {
1084 format!("Could not find a valid locator for a build task and configure is invalid with error: {}", request_type.err()
1085 .map(|err| err.to_string())
1086 .unwrap_or_default())
1087 })?;
1088 let request = dap_store
1089 .update(cx, |this, cx| {
1090 this.run_debug_locator(&locator_name, task, cx)
1091 })?
1092 .await?;
1093
1094 let zed_config = ZedDebugConfig {
1095 label: label.clone(),
1096 adapter: adapter.clone(),
1097 request,
1098 stop_on_entry: None,
1099 };
1100
1101 let scenario = dap_registry
1102 .adapter(&adapter)
1103 .with_context(|| anyhow!("{}: is not a valid adapter name", &adapter))?.config_from_zed_format(zed_config)
1104 .await?;
1105 config = scenario.config;
1106 util::merge_non_null_json_value_into(extra_config, &mut config);
1107
1108 Self::substitute_variables_in_config(&mut config, &task_context);
1109 } else {
1110 let Err(e) = request_type else {
1111 unreachable!();
1112 };
1113 anyhow::bail!("Zed cannot determine how to run this debug scenario. `build` field was not provided and Debug Adapter won't accept provided configuration because: {e}");
1114 };
1115
1116 Ok(DebugTaskDefinition {
1117 label,
1118 adapter: DebugAdapterName(adapter),
1119 config,
1120 tcp_connection,
1121 })
1122 })
1123 }
1124
1125 fn handle_run_in_terminal(
1126 &self,
1127 request: &RunInTerminalRequestArguments,
1128 mut sender: mpsc::Sender<Result<u32>>,
1129 window: &mut Window,
1130 cx: &mut Context<Self>,
1131 ) -> Task<Result<()>> {
1132 let running = cx.entity();
1133 let Ok(project) = self
1134 .workspace
1135 .read_with(cx, |workspace, _| workspace.project().clone())
1136 else {
1137 return Task::ready(Err(anyhow!("no workspace")));
1138 };
1139 let session = self.session.read(cx);
1140
1141 let cwd = (!request.cwd.is_empty())
1142 .then(|| PathBuf::from(&request.cwd))
1143 .or_else(|| session.binary().unwrap().cwd.clone());
1144
1145 let mut envs: HashMap<String, String> =
1146 self.session.read(cx).task_context().project_env.clone();
1147 if let Some(Value::Object(env)) = &request.env {
1148 for (key, value) in env {
1149 let value_str = match (key.as_str(), value) {
1150 (_, Value::String(value)) => value,
1151 _ => continue,
1152 };
1153
1154 envs.insert(key.clone(), value_str.clone());
1155 }
1156 }
1157
1158 let mut args = request.args.clone();
1159 let command = if envs.contains_key("VSCODE_INSPECTOR_OPTIONS") {
1160 // Handle special case for NodeJS debug adapter
1161 // If the Node binary path is provided (possibly with arguments like --experimental-network-inspection),
1162 // we set the command to None
1163 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1164 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1165 // This allows the NodeJS debug client to attach correctly
1166 if args
1167 .iter()
1168 .filter(|arg| !arg.starts_with("--"))
1169 .collect::<Vec<_>>()
1170 .len()
1171 > 1
1172 {
1173 Some(args.remove(0))
1174 } else {
1175 None
1176 }
1177 } else if !args.is_empty() {
1178 Some(args.remove(0))
1179 } else {
1180 None
1181 };
1182
1183 let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1184 let title = request
1185 .title
1186 .clone()
1187 .filter(|title| !title.is_empty())
1188 .or_else(|| command.clone())
1189 .unwrap_or_else(|| "Debug terminal".to_string());
1190 let kind = task::SpawnInTerminal {
1191 id: task::TaskId("debug".to_string()),
1192 full_label: title.clone(),
1193 label: title.clone(),
1194 command,
1195 args,
1196 command_label: title,
1197 cwd,
1198 env: envs,
1199 use_new_terminal: true,
1200 allow_concurrent_runs: true,
1201 reveal: task::RevealStrategy::NoFocus,
1202 reveal_target: task::RevealTarget::Dock,
1203 hide: task::HideStrategy::Never,
1204 shell,
1205 show_summary: false,
1206 show_command: false,
1207 show_rerun: false,
1208 };
1209
1210 let workspace = self.workspace.clone();
1211 let weak_project = project.downgrade();
1212
1213 let terminal_task =
1214 project.update(cx, |project, cx| project.create_terminal_task(kind, cx));
1215 let terminal_task = cx.spawn_in(window, async move |_, cx| {
1216 let terminal = terminal_task.await?;
1217
1218 let terminal_view = cx.new_window_entity(|window, cx| {
1219 TerminalView::new(terminal.clone(), workspace, None, weak_project, window, cx)
1220 })?;
1221
1222 running.update_in(cx, |running, window, cx| {
1223 running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1224 running.debug_terminal.update(cx, |debug_terminal, cx| {
1225 debug_terminal.terminal = Some(terminal_view);
1226 cx.notify();
1227 });
1228 })?;
1229
1230 terminal.read_with(cx, |terminal, _| {
1231 terminal
1232 .pty_info
1233 .pid()
1234 .map(|pid| pid.as_u32())
1235 .context("Terminal was spawned but PID was not available")
1236 })?
1237 });
1238
1239 cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1240 }
1241
1242 fn create_sub_view(
1243 &self,
1244 item_kind: DebuggerPaneItem,
1245 _pane: &Entity<Pane>,
1246 cx: &mut Context<Self>,
1247 ) -> Box<dyn ItemHandle> {
1248 match item_kind {
1249 DebuggerPaneItem::Console => Box::new(SubView::console(self.console.clone(), cx)),
1250 DebuggerPaneItem::Variables => Box::new(SubView::new(
1251 self.variable_list.focus_handle(cx),
1252 self.variable_list.clone().into(),
1253 item_kind,
1254 cx,
1255 )),
1256 DebuggerPaneItem::BreakpointList => {
1257 Box::new(SubView::breakpoint_list(self.breakpoint_list.clone(), cx))
1258 }
1259 DebuggerPaneItem::Frames => Box::new(SubView::new(
1260 self.stack_frame_list.focus_handle(cx),
1261 self.stack_frame_list.clone().into(),
1262 item_kind,
1263 cx,
1264 )),
1265 DebuggerPaneItem::Modules => Box::new(SubView::new(
1266 self.module_list.focus_handle(cx),
1267 self.module_list.clone().into(),
1268 item_kind,
1269 cx,
1270 )),
1271 DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1272 self.loaded_sources_list.focus_handle(cx),
1273 self.loaded_sources_list.clone().into(),
1274 item_kind,
1275 cx,
1276 )),
1277 DebuggerPaneItem::Terminal => Box::new(SubView::new(
1278 self.debug_terminal.focus_handle(cx),
1279 self.debug_terminal.clone().into(),
1280 item_kind,
1281 cx,
1282 )),
1283 DebuggerPaneItem::MemoryView => Box::new(SubView::new(
1284 self.memory_view.focus_handle(cx),
1285 self.memory_view.clone().into(),
1286 item_kind,
1287 cx,
1288 )),
1289 }
1290 }
1291
1292 pub(crate) fn ensure_pane_item(
1293 &mut self,
1294 item_kind: DebuggerPaneItem,
1295 window: &mut Window,
1296 cx: &mut Context<Self>,
1297 ) {
1298 if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1299 return;
1300 };
1301 let pane = self.panes.last_pane();
1302 let sub_view = self.create_sub_view(item_kind, &pane, cx);
1303
1304 pane.update(cx, |pane, cx| {
1305 pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1306 })
1307 }
1308
1309 pub(crate) fn add_pane_item(
1310 &mut self,
1311 item_kind: DebuggerPaneItem,
1312 position: Point<Pixels>,
1313 window: &mut Window,
1314 cx: &mut Context<Self>,
1315 ) {
1316 debug_assert!(
1317 item_kind.is_supported(self.session.read(cx).capabilities()),
1318 "We should only allow adding supported item kinds"
1319 );
1320
1321 if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1322 let sub_view = self.create_sub_view(item_kind, pane, cx);
1323
1324 pane.update(cx, |pane, cx| {
1325 pane.add_item(sub_view, false, false, None, window, cx);
1326 })
1327 }
1328 }
1329
1330 pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1331 let caps = self.session.read(cx).capabilities();
1332 let mut pane_item_status = IndexMap::from_iter(
1333 DebuggerPaneItem::all()
1334 .iter()
1335 .filter(|kind| kind.is_supported(caps))
1336 .map(|kind| (*kind, false)),
1337 );
1338 self.panes.panes().iter().for_each(|pane| {
1339 pane.read(cx)
1340 .items()
1341 .filter_map(|item| item.act_as::<SubView>(cx))
1342 .for_each(|view| {
1343 pane_item_status.insert(view.read(cx).kind, true);
1344 });
1345 });
1346
1347 pane_item_status
1348 }
1349
1350 pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1351 if self._schedule_serialize.is_none() {
1352 self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1353 cx.background_executor()
1354 .timer(Duration::from_millis(100))
1355 .await;
1356
1357 let Some((adapter_name, pane_layout)) = this
1358 .read_with(cx, |this, cx| {
1359 let adapter_name = this.session.read(cx).adapter();
1360 (
1361 adapter_name,
1362 persistence::build_serialized_layout(
1363 &this.panes.root,
1364 this.dock_axis,
1365 cx,
1366 ),
1367 )
1368 })
1369 .ok()
1370 else {
1371 return;
1372 };
1373
1374 persistence::serialize_pane_layout(adapter_name, pane_layout)
1375 .await
1376 .log_err();
1377
1378 this.update(cx, |this, _| {
1379 this._schedule_serialize.take();
1380 })
1381 .ok();
1382 }));
1383 }
1384 }
1385
1386 pub(crate) fn handle_pane_event(
1387 this: &mut RunningState,
1388 source_pane: &Entity<Pane>,
1389 event: &Event,
1390 window: &mut Window,
1391 cx: &mut Context<RunningState>,
1392 ) {
1393 this.serialize_layout(window, cx);
1394 match event {
1395 Event::Remove { .. } => {
1396 let _did_find_pane = this.panes.remove(source_pane).is_ok();
1397 debug_assert!(_did_find_pane);
1398 cx.notify();
1399 }
1400 Event::Focus => {
1401 this.active_pane = source_pane.clone();
1402 }
1403 _ => {}
1404 }
1405 }
1406
1407 pub(crate) fn activate_pane_in_direction(
1408 &mut self,
1409 direction: SplitDirection,
1410 window: &mut Window,
1411 cx: &mut Context<Self>,
1412 ) {
1413 let active_pane = self.active_pane.clone();
1414 if let Some(pane) = self
1415 .panes
1416 .find_pane_in_direction(&active_pane, direction, cx)
1417 {
1418 pane.update(cx, |pane, cx| {
1419 pane.focus_active_item(window, cx);
1420 })
1421 } else {
1422 self.workspace
1423 .update(cx, |workspace, cx| {
1424 workspace.activate_pane_in_direction(direction, window, cx)
1425 })
1426 .ok();
1427 }
1428 }
1429
1430 pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1431 if self.thread_id.is_some() {
1432 self.stack_frame_list
1433 .update(cx, |list, cx| {
1434 let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1435 return Task::ready(Ok(()));
1436 };
1437 list.go_to_stack_frame(stack_frame_id, window, cx)
1438 })
1439 .detach();
1440 }
1441 }
1442
1443 pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1444 self.variable_list.read(cx).has_open_context_menu()
1445 }
1446
1447 pub fn session(&self) -> &Entity<Session> {
1448 &self.session
1449 }
1450
1451 pub fn session_id(&self) -> SessionId {
1452 self.session_id
1453 }
1454
1455 pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1456 self.stack_frame_list.read(cx).opened_stack_frame_id()
1457 }
1458
1459 pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1460 &self.stack_frame_list
1461 }
1462
1463 #[cfg(test)]
1464 pub fn console(&self) -> &Entity<Console> {
1465 &self.console
1466 }
1467
1468 #[cfg(test)]
1469 pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1470 &self.module_list
1471 }
1472
1473 pub(crate) fn activate_item(
1474 &mut self,
1475 item: DebuggerPaneItem,
1476 window: &mut Window,
1477 cx: &mut Context<Self>,
1478 ) {
1479 self.ensure_pane_item(item, window, cx);
1480
1481 let (variable_list_position, pane) = self
1482 .panes
1483 .panes()
1484 .into_iter()
1485 .find_map(|pane| {
1486 pane.read(cx)
1487 .items_of_type::<SubView>()
1488 .position(|view| view.read(cx).view_kind() == item)
1489 .map(|view| (view, pane))
1490 })
1491 .unwrap();
1492
1493 pane.update(cx, |this, cx| {
1494 this.activate_item(variable_list_position, true, true, window, cx);
1495 });
1496 }
1497
1498 #[cfg(test)]
1499 pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1500 &self.variable_list
1501 }
1502
1503 #[cfg(test)]
1504 pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1505 persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1506 }
1507
1508 pub fn capabilities(&self, cx: &App) -> Capabilities {
1509 self.session().read(cx).capabilities().clone()
1510 }
1511
1512 pub fn select_current_thread(
1513 &mut self,
1514 threads: &Vec<(Thread, ThreadStatus)>,
1515 window: &mut Window,
1516 cx: &mut Context<Self>,
1517 ) {
1518 let selected_thread = self
1519 .thread_id
1520 .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1521 .or_else(|| threads.first());
1522
1523 let Some((selected_thread, _)) = selected_thread else {
1524 return;
1525 };
1526
1527 if Some(ThreadId(selected_thread.id)) != self.thread_id {
1528 self.select_thread(ThreadId(selected_thread.id), window, cx);
1529 }
1530 }
1531
1532 pub fn selected_thread_id(&self) -> Option<ThreadId> {
1533 self.thread_id
1534 }
1535
1536 pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1537 self.thread_id
1538 .map(|id| self.session().read(cx).thread_status(id))
1539 }
1540
1541 pub(crate) fn select_thread(
1542 &mut self,
1543 thread_id: ThreadId,
1544 window: &mut Window,
1545 cx: &mut Context<Self>,
1546 ) {
1547 if self.thread_id.is_some_and(|id| id == thread_id) {
1548 return;
1549 }
1550
1551 self.thread_id = Some(thread_id);
1552
1553 self.stack_frame_list
1554 .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1555 }
1556
1557 pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1558 let Some(thread_id) = self.thread_id else {
1559 return;
1560 };
1561
1562 self.session().update(cx, |state, cx| {
1563 state.continue_thread(thread_id, cx);
1564 });
1565 }
1566
1567 pub fn step_over(&mut self, cx: &mut Context<Self>) {
1568 let Some(thread_id) = self.thread_id else {
1569 return;
1570 };
1571
1572 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1573
1574 self.session().update(cx, |state, cx| {
1575 state.step_over(thread_id, granularity, cx);
1576 });
1577 }
1578
1579 pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1580 let Some(thread_id) = self.thread_id else {
1581 return;
1582 };
1583
1584 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1585
1586 self.session().update(cx, |state, cx| {
1587 state.step_in(thread_id, granularity, cx);
1588 });
1589 }
1590
1591 pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1592 let Some(thread_id) = self.thread_id else {
1593 return;
1594 };
1595
1596 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1597
1598 self.session().update(cx, |state, cx| {
1599 state.step_out(thread_id, granularity, cx);
1600 });
1601 }
1602
1603 pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1604 let Some(thread_id) = self.thread_id else {
1605 return;
1606 };
1607
1608 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1609
1610 self.session().update(cx, |state, cx| {
1611 state.step_back(thread_id, granularity, cx);
1612 });
1613 }
1614
1615 pub fn rerun_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1616 if let Some((scenario, context)) = self.scenario.take().zip(self.scenario_context.take())
1617 && scenario.build.is_some()
1618 {
1619 let DebugScenarioContext {
1620 task_context,
1621 active_buffer,
1622 worktree_id,
1623 } = context;
1624 let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
1625
1626 self.workspace
1627 .update(cx, |workspace, cx| {
1628 workspace.start_debug_session(
1629 scenario,
1630 task_context,
1631 active_buffer,
1632 worktree_id,
1633 window,
1634 cx,
1635 )
1636 })
1637 .ok();
1638 } else {
1639 self.restart_session(cx);
1640 }
1641 }
1642
1643 pub fn restart_session(&self, cx: &mut Context<Self>) {
1644 self.session().update(cx, |state, cx| {
1645 state.restart(None, cx);
1646 });
1647 }
1648
1649 pub fn pause_thread(&self, cx: &mut Context<Self>) {
1650 let Some(thread_id) = self.thread_id else {
1651 return;
1652 };
1653
1654 self.session().update(cx, |state, cx| {
1655 state.pause_thread(thread_id, cx);
1656 });
1657 }
1658
1659 pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1660 self.workspace
1661 .update(cx, |workspace, cx| {
1662 workspace
1663 .project()
1664 .read(cx)
1665 .breakpoint_store()
1666 .update(cx, |store, cx| {
1667 store.remove_active_position(Some(self.session_id), cx)
1668 })
1669 })
1670 .log_err();
1671
1672 let is_building = self.session.update(cx, |session, cx| {
1673 session.shutdown(cx).detach();
1674 matches!(session.mode, session::SessionState::Booting(_))
1675 });
1676
1677 if is_building {
1678 self.debug_terminal.update(cx, |terminal, cx| {
1679 if let Some(view) = terminal.terminal.as_ref() {
1680 view.update(cx, |view, cx| {
1681 view.terminal()
1682 .update(cx, |terminal, _| terminal.kill_active_task())
1683 })
1684 }
1685 })
1686 }
1687 }
1688
1689 pub fn stop_thread(&self, cx: &mut Context<Self>) {
1690 let Some(thread_id) = self.thread_id else {
1691 return;
1692 };
1693
1694 self.workspace
1695 .update(cx, |workspace, cx| {
1696 workspace
1697 .project()
1698 .read(cx)
1699 .breakpoint_store()
1700 .update(cx, |store, cx| {
1701 store.remove_active_position(Some(self.session_id), cx)
1702 })
1703 })
1704 .log_err();
1705
1706 self.session().update(cx, |state, cx| {
1707 state.terminate_threads(Some(vec![thread_id; 1]), cx);
1708 });
1709 }
1710
1711 pub fn detach_client(&self, cx: &mut Context<Self>) {
1712 self.session().update(cx, |state, cx| {
1713 state.disconnect_client(cx);
1714 });
1715 }
1716
1717 pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1718 self.session.update(cx, |session, cx| {
1719 session.toggle_ignore_breakpoints(cx).detach();
1720 });
1721 }
1722
1723 fn default_pane_layout(
1724 project: Entity<Project>,
1725 workspace: &WeakEntity<Workspace>,
1726 stack_frame_list: &Entity<StackFrameList>,
1727 variable_list: &Entity<VariableList>,
1728 console: &Entity<Console>,
1729 breakpoints: &Entity<BreakpointList>,
1730 debug_terminal: &Entity<DebugTerminal>,
1731 dock_axis: Axis,
1732 subscriptions: &mut HashMap<EntityId, Subscription>,
1733 window: &mut Window,
1734 cx: &mut Context<'_, RunningState>,
1735 ) -> Member {
1736 let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1737 leftmost_pane.update(cx, |this, cx| {
1738 this.add_item(
1739 Box::new(SubView::new(
1740 this.focus_handle(cx),
1741 stack_frame_list.clone().into(),
1742 DebuggerPaneItem::Frames,
1743 cx,
1744 )),
1745 true,
1746 false,
1747 None,
1748 window,
1749 cx,
1750 );
1751 this.add_item(
1752 Box::new(SubView::breakpoint_list(breakpoints.clone(), cx)),
1753 true,
1754 false,
1755 None,
1756 window,
1757 cx,
1758 );
1759 this.activate_item(0, false, false, window, cx);
1760 });
1761 let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1762
1763 center_pane.update(cx, |this, cx| {
1764 let view = SubView::console(console.clone(), cx);
1765
1766 this.add_item(Box::new(view), true, false, None, window, cx);
1767
1768 this.add_item(
1769 Box::new(SubView::new(
1770 variable_list.focus_handle(cx),
1771 variable_list.clone().into(),
1772 DebuggerPaneItem::Variables,
1773 cx,
1774 )),
1775 true,
1776 false,
1777 None,
1778 window,
1779 cx,
1780 );
1781 this.activate_item(0, false, false, window, cx);
1782 });
1783
1784 let rightmost_pane = new_debugger_pane(workspace.clone(), project, window, cx);
1785 rightmost_pane.update(cx, |this, cx| {
1786 this.add_item(
1787 Box::new(SubView::new(
1788 debug_terminal.focus_handle(cx),
1789 debug_terminal.clone().into(),
1790 DebuggerPaneItem::Terminal,
1791 cx,
1792 )),
1793 false,
1794 false,
1795 None,
1796 window,
1797 cx,
1798 );
1799 });
1800
1801 subscriptions.extend(
1802 [&leftmost_pane, ¢er_pane, &rightmost_pane]
1803 .into_iter()
1804 .map(|entity| {
1805 (
1806 entity.entity_id(),
1807 cx.subscribe_in(entity, window, Self::handle_pane_event),
1808 )
1809 }),
1810 );
1811
1812 let group_root = workspace::PaneAxis::new(
1813 dock_axis.invert(),
1814 [leftmost_pane, center_pane, rightmost_pane]
1815 .into_iter()
1816 .map(workspace::Member::Pane)
1817 .collect(),
1818 );
1819
1820 Member::Axis(group_root)
1821 }
1822
1823 pub(crate) fn invert_axies(&mut self) {
1824 self.dock_axis = self.dock_axis.invert();
1825 self.panes.invert_axies();
1826 }
1827}
1828
1829impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1830
1831impl Focusable for RunningState {
1832 fn focus_handle(&self, _: &App) -> FocusHandle {
1833 self.focus_handle.clone()
1834 }
1835}