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 anyhow::{Context as _, Result, anyhow};
18use breakpoint_list::BreakpointList;
19use collections::{HashMap, IndexMap};
20use console::Console;
21use dap::{
22 Capabilities, DapRegistry, RunInTerminalRequestArguments, Thread,
23 adapters::{DebugAdapterName, DebugTaskDefinition},
24 client::SessionId,
25 debugger_settings::DebuggerSettings,
26};
27use futures::{SinkExt, channel::mpsc};
28use gpui::{
29 Action as _, AnyView, AppContext, Axis, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
30 NoAction, Pixels, Point, Subscription, Task, WeakEntity,
31};
32use language::Buffer;
33use loaded_source_list::LoadedSourceList;
34use module_list::ModuleList;
35use project::{
36 DebugScenarioContext, Project, WorktreeId,
37 debugger::session::{self, Session, SessionEvent, SessionStateEvent, ThreadId, ThreadStatus},
38};
39use rpc::proto::ViewId;
40use serde_json::Value;
41use settings::Settings;
42use stack_frame_list::StackFrameList;
43use task::{
44 BuildTaskDefinition, DebugScenario, Shell, ShellBuilder, SpawnInTerminal, TaskContext,
45 ZedDebugConfig, substitute_variables_in_str,
46};
47use terminal_view::TerminalView;
48use ui::{
49 FluentBuilder, IntoElement, Render, StatefulInteractiveElement, Tab, Tooltip, VisibleOnHover,
50 VisualContext, prelude::*,
51};
52use util::ResultExt;
53use variable_list::VariableList;
54use workspace::{
55 ActivePaneDecorator, DraggedTab, Item, ItemHandle, Member, Pane, PaneGroup, SplitDirection,
56 Workspace, item::TabContentParams, move_item, pane::Event,
57};
58
59pub struct RunningState {
60 session: Entity<Session>,
61 thread_id: Option<ThreadId>,
62 focus_handle: FocusHandle,
63 _remote_id: Option<ViewId>,
64 workspace: WeakEntity<Workspace>,
65 session_id: SessionId,
66 variable_list: Entity<variable_list::VariableList>,
67 _subscriptions: Vec<Subscription>,
68 stack_frame_list: Entity<stack_frame_list::StackFrameList>,
69 loaded_sources_list: Entity<LoadedSourceList>,
70 pub debug_terminal: Entity<DebugTerminal>,
71 module_list: Entity<module_list::ModuleList>,
72 console: Entity<Console>,
73 breakpoint_list: Entity<BreakpointList>,
74 panes: PaneGroup,
75 active_pane: Entity<Pane>,
76 pane_close_subscriptions: HashMap<EntityId, Subscription>,
77 dock_axis: Axis,
78 _schedule_serialize: Option<Task<()>>,
79 pub(crate) scenario: Option<DebugScenario>,
80 pub(crate) scenario_context: Option<DebugScenarioContext>,
81 memory_view: Entity<MemoryView>,
82}
83
84impl RunningState {
85 pub(crate) fn thread_id(&self) -> Option<ThreadId> {
86 self.thread_id
87 }
88
89 pub(crate) fn active_pane(&self) -> &Entity<Pane> {
90 &self.active_pane
91 }
92}
93
94impl Render for RunningState {
95 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
96 let zoomed_pane = self
97 .panes
98 .panes()
99 .into_iter()
100 .find(|pane| pane.read(cx).is_zoomed());
101
102 let active = self.panes.panes().into_iter().next();
103 let pane = if let Some(zoomed_pane) = zoomed_pane {
104 zoomed_pane.update(cx, |pane, cx| pane.render(window, cx).into_any_element())
105 } else if let Some(active) = active {
106 self.panes
107 .render(
108 None,
109 &ActivePaneDecorator::new(active, &self.workspace),
110 window,
111 cx,
112 )
113 .into_any_element()
114 } else {
115 div().into_any_element()
116 };
117 let thread_status = self
118 .thread_id
119 .map(|thread_id| self.session.read(cx).thread_status(thread_id))
120 .unwrap_or(ThreadStatus::Exited);
121
122 self.variable_list.update(cx, |this, cx| {
123 this.disabled(thread_status != ThreadStatus::Stopped, cx);
124 });
125 v_flex()
126 .size_full()
127 .key_context("DebugSessionItem")
128 .track_focus(&self.focus_handle(cx))
129 .child(h_flex().flex_1().child(pane))
130 }
131}
132
133pub(crate) struct SubView {
134 inner: AnyView,
135 item_focus_handle: FocusHandle,
136 kind: DebuggerPaneItem,
137 show_indicator: Box<dyn Fn(&App) -> bool>,
138 actions: Option<Box<dyn FnMut(&mut Window, &mut App) -> AnyElement>>,
139 hovered: bool,
140}
141
142impl SubView {
143 pub(crate) fn new(
144 item_focus_handle: FocusHandle,
145 view: AnyView,
146 kind: DebuggerPaneItem,
147 cx: &mut App,
148 ) -> Entity<Self> {
149 cx.new(|_| Self {
150 kind,
151 inner: view,
152 item_focus_handle,
153 show_indicator: Box::new(|_| false),
154 actions: None,
155 hovered: false,
156 })
157 }
158
159 pub(crate) fn stack_frame_list(
160 stack_frame_list: Entity<StackFrameList>,
161 cx: &mut App,
162 ) -> Entity<Self> {
163 let weak_list = stack_frame_list.downgrade();
164 let this = Self::new(
165 stack_frame_list.focus_handle(cx),
166 stack_frame_list.into(),
167 DebuggerPaneItem::Frames,
168 cx,
169 );
170
171 this.update(cx, |this, _| {
172 this.with_actions(Box::new(move |_, cx| {
173 weak_list
174 .update(cx, |this, _| this.render_control_strip())
175 .unwrap_or_else(|_| div().into_any_element())
176 }));
177 });
178
179 this
180 }
181
182 pub(crate) fn console(console: Entity<Console>, cx: &mut App) -> Entity<Self> {
183 let weak_console = console.downgrade();
184 let this = Self::new(
185 console.focus_handle(cx),
186 console.into(),
187 DebuggerPaneItem::Console,
188 cx,
189 );
190 this.update(cx, |this, _| {
191 this.with_indicator(Box::new(move |cx| {
192 weak_console
193 .read_with(cx, |console, cx| console.show_indicator(cx))
194 .unwrap_or_default()
195 }))
196 });
197 this
198 }
199
200 pub(crate) fn breakpoint_list(list: Entity<BreakpointList>, cx: &mut App) -> Entity<Self> {
201 let weak_list = list.downgrade();
202 let focus_handle = list.focus_handle(cx);
203 let this = Self::new(
204 focus_handle,
205 list.into(),
206 DebuggerPaneItem::BreakpointList,
207 cx,
208 );
209
210 this.update(cx, |this, _| {
211 this.with_actions(Box::new(move |_, cx| {
212 weak_list
213 .update(cx, |this, _| this.render_control_strip())
214 .unwrap_or_else(|_| div().into_any_element())
215 }));
216 });
217 this
218 }
219
220 pub(crate) fn view_kind(&self) -> DebuggerPaneItem {
221 self.kind
222 }
223 pub(crate) fn with_indicator(&mut self, indicator: Box<dyn Fn(&App) -> bool>) {
224 self.show_indicator = indicator;
225 }
226 pub(crate) fn with_actions(
227 &mut self,
228 actions: Box<dyn FnMut(&mut Window, &mut App) -> AnyElement>,
229 ) {
230 self.actions = Some(actions);
231 }
232}
233impl Focusable for SubView {
234 fn focus_handle(&self, _: &App) -> FocusHandle {
235 self.item_focus_handle.clone()
236 }
237}
238impl EventEmitter<()> for SubView {}
239impl Item for SubView {
240 type Event = ();
241
242 /// This is used to serialize debugger pane layouts
243 /// A SharedString gets converted to a enum and back during serialization/deserialization.
244 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
245 self.kind.to_shared_string()
246 }
247
248 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
249 Some(self.kind.tab_tooltip())
250 }
251
252 fn tab_content(
253 &self,
254 params: workspace::item::TabContentParams,
255 _: &Window,
256 cx: &App,
257 ) -> AnyElement {
258 let label = Label::new(self.kind.to_shared_string())
259 .size(ui::LabelSize::Small)
260 .color(params.text_color())
261 .line_height_style(ui::LineHeightStyle::UiLabel);
262
263 if !params.selected && self.show_indicator.as_ref()(cx) {
264 return h_flex()
265 .justify_between()
266 .child(ui::Indicator::dot())
267 .gap_2()
268 .child(label)
269 .into_any_element();
270 }
271
272 label.into_any_element()
273 }
274}
275
276impl Render for SubView {
277 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
278 v_flex()
279 .id(SharedString::from(format!(
280 "subview-container-{}",
281 self.kind.to_shared_string()
282 )))
283 .on_hover(cx.listener(|this, hovered, _, cx| {
284 this.hovered = *hovered;
285 cx.notify();
286 }))
287 .size_full()
288 // Add border unconditionally to prevent layout shifts on focus changes.
289 .border_1()
290 .when(self.item_focus_handle.contains_focused(window, cx), |el| {
291 el.border_color(cx.theme().colors().pane_focused_border)
292 })
293 .child(self.inner.clone())
294 }
295}
296
297pub(crate) fn new_debugger_pane(
298 workspace: WeakEntity<Workspace>,
299 project: Entity<Project>,
300 window: &mut Window,
301 cx: &mut Context<RunningState>,
302) -> Entity<Pane> {
303 let weak_running = cx.weak_entity();
304 let custom_drop_handle = {
305 let workspace = workspace.clone();
306 let project = project.downgrade();
307 let weak_running = weak_running.clone();
308 move |pane: &mut Pane, any: &dyn Any, window: &mut Window, cx: &mut Context<Pane>| {
309 let Some(tab) = any.downcast_ref::<DraggedTab>() else {
310 return ControlFlow::Break(());
311 };
312 let Some(project) = project.upgrade() else {
313 return ControlFlow::Break(());
314 };
315 let this_pane = cx.entity();
316 let item = if tab.pane == this_pane {
317 pane.item_for_index(tab.ix)
318 } else {
319 tab.pane.read(cx).item_for_index(tab.ix)
320 };
321 let Some(item) = item.filter(|item| item.downcast::<SubView>().is_some()) else {
322 return ControlFlow::Break(());
323 };
324
325 let source = tab.pane.clone();
326 let item_id_to_move = item.item_id();
327
328 let Ok(new_split_pane) = pane
329 .drag_split_direction()
330 .map(|split_direction| {
331 weak_running.update(cx, |running, cx| {
332 let new_pane =
333 new_debugger_pane(workspace.clone(), project.clone(), window, cx);
334 let _previous_subscription = running.pane_close_subscriptions.insert(
335 new_pane.entity_id(),
336 cx.subscribe_in(&new_pane, window, RunningState::handle_pane_event),
337 );
338 debug_assert!(_previous_subscription.is_none());
339 running
340 .panes
341 .split(&this_pane, &new_pane, split_direction)?;
342 anyhow::Ok(new_pane)
343 })
344 })
345 .transpose()
346 else {
347 return ControlFlow::Break(());
348 };
349
350 match new_split_pane.transpose() {
351 // Source pane may be the one currently updated, so defer the move.
352 Ok(Some(new_pane)) => cx
353 .spawn_in(window, async move |_, cx| {
354 cx.update(|window, cx| {
355 move_item(
356 &source,
357 &new_pane,
358 item_id_to_move,
359 new_pane.read(cx).active_item_index(),
360 true,
361 window,
362 cx,
363 );
364 })
365 .ok();
366 })
367 .detach(),
368 // If we drop into existing pane or current pane,
369 // regular pane drop handler will take care of it,
370 // using the right tab index for the operation.
371 Ok(None) => return ControlFlow::Continue(()),
372 err @ Err(_) => {
373 err.log_err();
374 return ControlFlow::Break(());
375 }
376 };
377
378 ControlFlow::Break(())
379 }
380 };
381
382 cx.new(move |cx| {
383 let mut pane = Pane::new(
384 workspace.clone(),
385 project.clone(),
386 Default::default(),
387 None,
388 NoAction.boxed_clone(),
389 true,
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 is_windows = project.read(cx).path_style(cx).is_windows();
942 let remote_shell = project
943 .read(cx)
944 .remote_client()
945 .as_ref()
946 .and_then(|remote| remote.read(cx).shell());
947
948 cx.spawn_in(window, async move |this, cx| {
949 let DebugScenario {
950 adapter,
951 label,
952 build,
953 mut config,
954 tcp_connection,
955 } = scenario;
956 Self::relativize_paths(None, &mut config, &task_context);
957 Self::substitute_variables_in_config(&mut config, &task_context);
958
959 let request_type = match dap_registry
960 .adapter(&adapter)
961 .with_context(|| format!("{}: is not a valid adapter name", &adapter)) {
962 Ok(adapter) => adapter.request_kind(&config).await,
963 Err(e) => Err(e)
964 };
965
966
967 let config_is_valid = request_type.is_ok();
968 let mut extra_config = Value::Null;
969 let build_output = if let Some(build) = build {
970 let (task_template, locator_name) = match build {
971 BuildTaskDefinition::Template {
972 task_template,
973 locator_name,
974 } => (task_template, locator_name),
975 BuildTaskDefinition::ByName(ref label) => {
976 let task = task_store.update(cx, |this, cx| {
977 this.task_inventory().map(|inventory| {
978 inventory.read(cx).task_template_by_label(
979 buffer,
980 worktree_id,
981 label,
982 cx,
983 )
984 })
985 })?;
986 let task = match task {
987 Some(task) => task.await,
988 None => None,
989 }.with_context(|| format!("Couldn't find task template for {build:?}"))?;
990 (task, None)
991 }
992 };
993 let Some(mut task) = task_template.resolve_task("debug-build-task", &task_context) else {
994 anyhow::bail!("Could not resolve task variables within a debug scenario");
995 };
996
997 let locator_name = if let Some(locator_name) = locator_name {
998 extra_config = config.clone();
999 debug_assert!(!config_is_valid);
1000 Some(locator_name)
1001 } else if !config_is_valid {
1002 let task = dap_store
1003 .update(cx, |this, cx| {
1004 this.debug_scenario_for_build_task(
1005 task.original_task().clone(),
1006 adapter.clone().into(),
1007 task.display_label().to_owned().into(),
1008 cx,
1009 )
1010
1011 });
1012 if let Ok(t) = task {
1013 t.await.and_then(|scenario| {
1014 extra_config = scenario.config;
1015 match scenario.build {
1016 Some(BuildTaskDefinition::Template {
1017 locator_name, ..
1018 }) => locator_name,
1019 _ => None,
1020 }
1021 })
1022 } else {
1023 None
1024 }
1025
1026 } else {
1027 None
1028 };
1029
1030 if let Some(remote_shell) = remote_shell && task.resolved.shell == Shell::System {
1031 task.resolved.shell = Shell::Program(remote_shell);
1032 }
1033
1034 let builder = ShellBuilder::new(&task.resolved.shell, is_windows);
1035 let command_label = builder.command_label(task.resolved.command.as_deref().unwrap_or(""));
1036 let (command, args) =
1037 builder.build(task.resolved.command.clone(), &task.resolved.args);
1038
1039 let task_with_shell = SpawnInTerminal {
1040 command_label,
1041 command: Some(command),
1042 args,
1043 ..task.resolved.clone()
1044 };
1045 let terminal = project
1046 .update(cx, |project, cx| {
1047 project.create_terminal_task(
1048 task_with_shell.clone(),
1049 cx,
1050 )
1051 })?.await?;
1052
1053 let terminal_view = cx.new_window_entity(|window, cx| {
1054 TerminalView::new(
1055 terminal.clone(),
1056 weak_workspace,
1057 None,
1058 weak_project,
1059 window,
1060 cx,
1061 )
1062 })?;
1063
1064 this.update_in(cx, |this, window, cx| {
1065 this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1066 this.debug_terminal.update(cx, |debug_terminal, cx| {
1067 debug_terminal.terminal = Some(terminal_view);
1068 cx.notify();
1069 });
1070 })?;
1071
1072 let exit_status = terminal
1073 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1074 .await
1075 .context("Failed to wait for completed task")?;
1076
1077 if !exit_status.success() {
1078 anyhow::bail!("Build failed");
1079 }
1080 Some((task.resolved.clone(), locator_name, extra_config))
1081 } else {
1082 None
1083 };
1084
1085 if config_is_valid {
1086 } else if let Some((task, locator_name, extra_config)) = build_output {
1087 let locator_name =
1088 locator_name.with_context(|| {
1089 format!("Could not find a valid locator for a build task and configure is invalid with error: {}", request_type.err()
1090 .map(|err| err.to_string())
1091 .unwrap_or_default())
1092 })?;
1093 let request = dap_store
1094 .update(cx, |this, cx| {
1095 this.run_debug_locator(&locator_name, task, cx)
1096 })?
1097 .await?;
1098
1099 let zed_config = ZedDebugConfig {
1100 label: label.clone(),
1101 adapter: adapter.clone(),
1102 request,
1103 stop_on_entry: None,
1104 };
1105
1106 let scenario = dap_registry
1107 .adapter(&adapter)
1108 .with_context(|| anyhow!("{}: is not a valid adapter name", &adapter))?.config_from_zed_format(zed_config)
1109 .await?;
1110 config = scenario.config;
1111 util::merge_non_null_json_value_into(extra_config, &mut config);
1112
1113 Self::substitute_variables_in_config(&mut config, &task_context);
1114 } else {
1115 let Err(e) = request_type else {
1116 unreachable!();
1117 };
1118 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}");
1119 };
1120
1121 Ok(DebugTaskDefinition {
1122 label,
1123 adapter: DebugAdapterName(adapter),
1124 config,
1125 tcp_connection,
1126 })
1127 })
1128 }
1129
1130 fn handle_run_in_terminal(
1131 &self,
1132 request: &RunInTerminalRequestArguments,
1133 mut sender: mpsc::Sender<Result<u32>>,
1134 window: &mut Window,
1135 cx: &mut Context<Self>,
1136 ) -> Task<Result<()>> {
1137 let running = cx.entity();
1138 let Ok(project) = self
1139 .workspace
1140 .read_with(cx, |workspace, _| workspace.project().clone())
1141 else {
1142 return Task::ready(Err(anyhow!("no workspace")));
1143 };
1144 let session = self.session.read(cx);
1145
1146 let cwd = (!request.cwd.is_empty())
1147 .then(|| PathBuf::from(&request.cwd))
1148 .or_else(|| session.binary().unwrap().cwd.clone());
1149
1150 let mut envs: HashMap<String, String> =
1151 self.session.read(cx).task_context().project_env.clone();
1152 if let Some(Value::Object(env)) = &request.env {
1153 for (key, value) in env {
1154 let value_str = match (key.as_str(), value) {
1155 (_, Value::String(value)) => value,
1156 _ => continue,
1157 };
1158
1159 envs.insert(key.clone(), value_str.clone());
1160 }
1161 }
1162
1163 let mut args = request.args.clone();
1164 let command = if envs.contains_key("VSCODE_INSPECTOR_OPTIONS") {
1165 // Handle special case for NodeJS debug adapter
1166 // If the Node binary path is provided (possibly with arguments like --experimental-network-inspection),
1167 // we set the command to None
1168 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1169 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1170 // This allows the NodeJS debug client to attach correctly
1171 if args
1172 .iter()
1173 .filter(|arg| !arg.starts_with("--"))
1174 .collect::<Vec<_>>()
1175 .len()
1176 > 1
1177 {
1178 Some(args.remove(0))
1179 } else {
1180 None
1181 }
1182 } else if !args.is_empty() {
1183 Some(args.remove(0))
1184 } else {
1185 None
1186 };
1187
1188 let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1189 let title = request
1190 .title
1191 .clone()
1192 .filter(|title| !title.is_empty())
1193 .or_else(|| command.clone())
1194 .unwrap_or_else(|| "Debug terminal".to_string());
1195 let kind = task::SpawnInTerminal {
1196 id: task::TaskId("debug".to_string()),
1197 full_label: title.clone(),
1198 label: title.clone(),
1199 command,
1200 args,
1201 command_label: title,
1202 cwd,
1203 env: envs,
1204 use_new_terminal: true,
1205 allow_concurrent_runs: true,
1206 reveal: task::RevealStrategy::NoFocus,
1207 reveal_target: task::RevealTarget::Dock,
1208 hide: task::HideStrategy::Never,
1209 shell,
1210 show_summary: false,
1211 show_command: false,
1212 show_rerun: false,
1213 };
1214
1215 let workspace = self.workspace.clone();
1216 let weak_project = project.downgrade();
1217
1218 let terminal_task =
1219 project.update(cx, |project, cx| project.create_terminal_task(kind, cx));
1220 let terminal_task = cx.spawn_in(window, async move |_, cx| {
1221 let terminal = terminal_task.await?;
1222
1223 let terminal_view = cx.new_window_entity(|window, cx| {
1224 TerminalView::new(terminal.clone(), workspace, None, weak_project, window, cx)
1225 })?;
1226
1227 running.update_in(cx, |running, window, cx| {
1228 running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1229 running.debug_terminal.update(cx, |debug_terminal, cx| {
1230 debug_terminal.terminal = Some(terminal_view);
1231 cx.notify();
1232 });
1233 })?;
1234
1235 terminal.read_with(cx, |terminal, _| {
1236 terminal
1237 .pid()
1238 .map(|pid| pid.as_u32())
1239 .context("Terminal was spawned but PID was not available")
1240 })?
1241 });
1242
1243 cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1244 }
1245
1246 fn create_sub_view(
1247 &self,
1248 item_kind: DebuggerPaneItem,
1249 _pane: &Entity<Pane>,
1250 cx: &mut Context<Self>,
1251 ) -> Box<dyn ItemHandle> {
1252 match item_kind {
1253 DebuggerPaneItem::Console => Box::new(SubView::console(self.console.clone(), cx)),
1254 DebuggerPaneItem::Variables => Box::new(SubView::new(
1255 self.variable_list.focus_handle(cx),
1256 self.variable_list.clone().into(),
1257 item_kind,
1258 cx,
1259 )),
1260 DebuggerPaneItem::BreakpointList => {
1261 Box::new(SubView::breakpoint_list(self.breakpoint_list.clone(), cx))
1262 }
1263 DebuggerPaneItem::Frames => Box::new(SubView::new(
1264 self.stack_frame_list.focus_handle(cx),
1265 self.stack_frame_list.clone().into(),
1266 item_kind,
1267 cx,
1268 )),
1269 DebuggerPaneItem::Modules => Box::new(SubView::new(
1270 self.module_list.focus_handle(cx),
1271 self.module_list.clone().into(),
1272 item_kind,
1273 cx,
1274 )),
1275 DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1276 self.loaded_sources_list.focus_handle(cx),
1277 self.loaded_sources_list.clone().into(),
1278 item_kind,
1279 cx,
1280 )),
1281 DebuggerPaneItem::Terminal => Box::new(SubView::new(
1282 self.debug_terminal.focus_handle(cx),
1283 self.debug_terminal.clone().into(),
1284 item_kind,
1285 cx,
1286 )),
1287 DebuggerPaneItem::MemoryView => Box::new(SubView::new(
1288 self.memory_view.focus_handle(cx),
1289 self.memory_view.clone().into(),
1290 item_kind,
1291 cx,
1292 )),
1293 }
1294 }
1295
1296 pub(crate) fn ensure_pane_item(
1297 &mut self,
1298 item_kind: DebuggerPaneItem,
1299 window: &mut Window,
1300 cx: &mut Context<Self>,
1301 ) {
1302 if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1303 return;
1304 };
1305 let pane = self.panes.last_pane();
1306 let sub_view = self.create_sub_view(item_kind, &pane, cx);
1307
1308 pane.update(cx, |pane, cx| {
1309 pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1310 })
1311 }
1312
1313 pub(crate) fn add_pane_item(
1314 &mut self,
1315 item_kind: DebuggerPaneItem,
1316 position: Point<Pixels>,
1317 window: &mut Window,
1318 cx: &mut Context<Self>,
1319 ) {
1320 debug_assert!(
1321 item_kind.is_supported(self.session.read(cx).capabilities()),
1322 "We should only allow adding supported item kinds"
1323 );
1324
1325 if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1326 let sub_view = self.create_sub_view(item_kind, pane, cx);
1327
1328 pane.update(cx, |pane, cx| {
1329 pane.add_item(sub_view, false, false, None, window, cx);
1330 })
1331 }
1332 }
1333
1334 pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1335 let caps = self.session.read(cx).capabilities();
1336 let mut pane_item_status = IndexMap::from_iter(
1337 DebuggerPaneItem::all()
1338 .iter()
1339 .filter(|kind| kind.is_supported(caps))
1340 .map(|kind| (*kind, false)),
1341 );
1342 self.panes.panes().iter().for_each(|pane| {
1343 pane.read(cx)
1344 .items()
1345 .filter_map(|item| item.act_as::<SubView>(cx))
1346 .for_each(|view| {
1347 pane_item_status.insert(view.read(cx).kind, true);
1348 });
1349 });
1350
1351 pane_item_status
1352 }
1353
1354 pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1355 if self._schedule_serialize.is_none() {
1356 self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1357 cx.background_executor()
1358 .timer(Duration::from_millis(100))
1359 .await;
1360
1361 let Some((adapter_name, pane_layout)) = this
1362 .read_with(cx, |this, cx| {
1363 let adapter_name = this.session.read(cx).adapter();
1364 (
1365 adapter_name,
1366 persistence::build_serialized_layout(
1367 &this.panes.root,
1368 this.dock_axis,
1369 cx,
1370 ),
1371 )
1372 })
1373 .ok()
1374 else {
1375 return;
1376 };
1377
1378 persistence::serialize_pane_layout(adapter_name, pane_layout)
1379 .await
1380 .log_err();
1381
1382 this.update(cx, |this, _| {
1383 this._schedule_serialize.take();
1384 })
1385 .ok();
1386 }));
1387 }
1388 }
1389
1390 pub(crate) fn handle_pane_event(
1391 this: &mut RunningState,
1392 source_pane: &Entity<Pane>,
1393 event: &Event,
1394 window: &mut Window,
1395 cx: &mut Context<RunningState>,
1396 ) {
1397 this.serialize_layout(window, cx);
1398 match event {
1399 Event::Remove { .. } => {
1400 let _did_find_pane = this.panes.remove(source_pane).is_ok();
1401 debug_assert!(_did_find_pane);
1402 cx.notify();
1403 }
1404 Event::Focus => {
1405 this.active_pane = source_pane.clone();
1406 }
1407 _ => {}
1408 }
1409 }
1410
1411 pub(crate) fn activate_pane_in_direction(
1412 &mut self,
1413 direction: SplitDirection,
1414 window: &mut Window,
1415 cx: &mut Context<Self>,
1416 ) {
1417 let active_pane = self.active_pane.clone();
1418 if let Some(pane) = self
1419 .panes
1420 .find_pane_in_direction(&active_pane, direction, cx)
1421 {
1422 pane.update(cx, |pane, cx| {
1423 pane.focus_active_item(window, cx);
1424 })
1425 } else {
1426 self.workspace
1427 .update(cx, |workspace, cx| {
1428 workspace.activate_pane_in_direction(direction, window, cx)
1429 })
1430 .ok();
1431 }
1432 }
1433
1434 pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1435 if self.thread_id.is_some() {
1436 self.stack_frame_list
1437 .update(cx, |list, cx| {
1438 let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1439 return Task::ready(Ok(()));
1440 };
1441 list.go_to_stack_frame(stack_frame_id, window, cx)
1442 })
1443 .detach();
1444 }
1445 }
1446
1447 pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1448 self.variable_list.read(cx).has_open_context_menu()
1449 }
1450
1451 pub fn session(&self) -> &Entity<Session> {
1452 &self.session
1453 }
1454
1455 pub fn session_id(&self) -> SessionId {
1456 self.session_id
1457 }
1458
1459 pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1460 self.stack_frame_list.read(cx).opened_stack_frame_id()
1461 }
1462
1463 pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1464 &self.stack_frame_list
1465 }
1466
1467 #[cfg(test)]
1468 pub fn console(&self) -> &Entity<Console> {
1469 &self.console
1470 }
1471
1472 #[cfg(test)]
1473 pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1474 &self.module_list
1475 }
1476
1477 pub(crate) fn activate_item(
1478 &mut self,
1479 item: DebuggerPaneItem,
1480 window: &mut Window,
1481 cx: &mut Context<Self>,
1482 ) {
1483 self.ensure_pane_item(item, window, cx);
1484
1485 let (variable_list_position, pane) = self
1486 .panes
1487 .panes()
1488 .into_iter()
1489 .find_map(|pane| {
1490 pane.read(cx)
1491 .items_of_type::<SubView>()
1492 .position(|view| view.read(cx).view_kind() == item)
1493 .map(|view| (view, pane))
1494 })
1495 .unwrap();
1496
1497 pane.update(cx, |this, cx| {
1498 this.activate_item(variable_list_position, true, true, window, cx);
1499 });
1500 }
1501
1502 #[cfg(test)]
1503 pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1504 &self.variable_list
1505 }
1506
1507 #[cfg(test)]
1508 pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1509 persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1510 }
1511
1512 pub fn capabilities(&self, cx: &App) -> Capabilities {
1513 self.session().read(cx).capabilities().clone()
1514 }
1515
1516 pub fn select_current_thread(
1517 &mut self,
1518 threads: &Vec<(Thread, ThreadStatus)>,
1519 window: &mut Window,
1520 cx: &mut Context<Self>,
1521 ) {
1522 let selected_thread = self
1523 .thread_id
1524 .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1525 .or_else(|| threads.first());
1526
1527 let Some((selected_thread, _)) = selected_thread else {
1528 return;
1529 };
1530
1531 if Some(ThreadId(selected_thread.id)) != self.thread_id {
1532 self.select_thread(ThreadId(selected_thread.id), window, cx);
1533 }
1534 }
1535
1536 pub fn selected_thread_id(&self) -> Option<ThreadId> {
1537 self.thread_id
1538 }
1539
1540 pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1541 self.thread_id
1542 .map(|id| self.session().read(cx).thread_status(id))
1543 }
1544
1545 pub(crate) fn select_thread(
1546 &mut self,
1547 thread_id: ThreadId,
1548 window: &mut Window,
1549 cx: &mut Context<Self>,
1550 ) {
1551 if self.thread_id.is_some_and(|id| id == thread_id) {
1552 return;
1553 }
1554
1555 self.thread_id = Some(thread_id);
1556
1557 self.stack_frame_list
1558 .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1559 }
1560
1561 pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1562 let Some(thread_id) = self.thread_id else {
1563 return;
1564 };
1565
1566 self.session().update(cx, |state, cx| {
1567 state.continue_thread(thread_id, cx);
1568 });
1569 }
1570
1571 pub fn step_over(&mut self, cx: &mut Context<Self>) {
1572 let Some(thread_id) = self.thread_id else {
1573 return;
1574 };
1575
1576 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1577
1578 self.session().update(cx, |state, cx| {
1579 state.step_over(thread_id, granularity, cx);
1580 });
1581 }
1582
1583 pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1584 let Some(thread_id) = self.thread_id else {
1585 return;
1586 };
1587
1588 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1589
1590 self.session().update(cx, |state, cx| {
1591 state.step_in(thread_id, granularity, cx);
1592 });
1593 }
1594
1595 pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1596 let Some(thread_id) = self.thread_id else {
1597 return;
1598 };
1599
1600 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1601
1602 self.session().update(cx, |state, cx| {
1603 state.step_out(thread_id, granularity, cx);
1604 });
1605 }
1606
1607 pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1608 let Some(thread_id) = self.thread_id else {
1609 return;
1610 };
1611
1612 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1613
1614 self.session().update(cx, |state, cx| {
1615 state.step_back(thread_id, granularity, cx);
1616 });
1617 }
1618
1619 pub fn rerun_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1620 if let Some((scenario, context)) = self.scenario.take().zip(self.scenario_context.take())
1621 && scenario.build.is_some()
1622 {
1623 let DebugScenarioContext {
1624 task_context,
1625 active_buffer,
1626 worktree_id,
1627 } = context;
1628 let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
1629
1630 self.workspace
1631 .update(cx, |workspace, cx| {
1632 workspace.start_debug_session(
1633 scenario,
1634 task_context,
1635 active_buffer,
1636 worktree_id,
1637 window,
1638 cx,
1639 )
1640 })
1641 .ok();
1642 } else {
1643 self.restart_session(cx);
1644 }
1645 }
1646
1647 pub fn restart_session(&self, cx: &mut Context<Self>) {
1648 self.session().update(cx, |state, cx| {
1649 state.restart(None, cx);
1650 });
1651 }
1652
1653 pub fn pause_thread(&self, cx: &mut Context<Self>) {
1654 let Some(thread_id) = self.thread_id else {
1655 return;
1656 };
1657
1658 self.session().update(cx, |state, cx| {
1659 state.pause_thread(thread_id, cx);
1660 });
1661 }
1662
1663 pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1664 self.workspace
1665 .update(cx, |workspace, cx| {
1666 workspace
1667 .project()
1668 .read(cx)
1669 .breakpoint_store()
1670 .update(cx, |store, cx| {
1671 store.remove_active_position(Some(self.session_id), cx)
1672 })
1673 })
1674 .log_err();
1675
1676 let is_building = self.session.update(cx, |session, cx| {
1677 session.shutdown(cx).detach();
1678 matches!(session.mode, session::SessionState::Booting(_))
1679 });
1680
1681 if is_building {
1682 self.debug_terminal.update(cx, |terminal, cx| {
1683 if let Some(view) = terminal.terminal.as_ref() {
1684 view.update(cx, |view, cx| {
1685 view.terminal()
1686 .update(cx, |terminal, _| terminal.kill_active_task())
1687 })
1688 }
1689 })
1690 }
1691 }
1692
1693 pub fn stop_thread(&self, cx: &mut Context<Self>) {
1694 let Some(thread_id) = self.thread_id else {
1695 return;
1696 };
1697
1698 self.workspace
1699 .update(cx, |workspace, cx| {
1700 workspace
1701 .project()
1702 .read(cx)
1703 .breakpoint_store()
1704 .update(cx, |store, cx| {
1705 store.remove_active_position(Some(self.session_id), cx)
1706 })
1707 })
1708 .log_err();
1709
1710 self.session().update(cx, |state, cx| {
1711 state.terminate_threads(Some(vec![thread_id; 1]), cx);
1712 });
1713 }
1714
1715 pub fn detach_client(&self, cx: &mut Context<Self>) {
1716 self.session().update(cx, |state, cx| {
1717 state.disconnect_client(cx);
1718 });
1719 }
1720
1721 pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1722 self.session.update(cx, |session, cx| {
1723 session.toggle_ignore_breakpoints(cx).detach();
1724 });
1725 }
1726
1727 fn default_pane_layout(
1728 project: Entity<Project>,
1729 workspace: &WeakEntity<Workspace>,
1730 stack_frame_list: &Entity<StackFrameList>,
1731 variable_list: &Entity<VariableList>,
1732 console: &Entity<Console>,
1733 breakpoints: &Entity<BreakpointList>,
1734 debug_terminal: &Entity<DebugTerminal>,
1735 dock_axis: Axis,
1736 subscriptions: &mut HashMap<EntityId, Subscription>,
1737 window: &mut Window,
1738 cx: &mut Context<'_, RunningState>,
1739 ) -> Member {
1740 let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1741 leftmost_pane.update(cx, |this, cx| {
1742 this.add_item(
1743 Box::new(SubView::new(
1744 this.focus_handle(cx),
1745 stack_frame_list.clone().into(),
1746 DebuggerPaneItem::Frames,
1747 cx,
1748 )),
1749 true,
1750 false,
1751 None,
1752 window,
1753 cx,
1754 );
1755 this.add_item(
1756 Box::new(SubView::breakpoint_list(breakpoints.clone(), cx)),
1757 true,
1758 false,
1759 None,
1760 window,
1761 cx,
1762 );
1763 this.activate_item(0, false, false, window, cx);
1764 });
1765 let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1766
1767 center_pane.update(cx, |this, cx| {
1768 let view = SubView::console(console.clone(), cx);
1769
1770 this.add_item(Box::new(view), true, false, None, window, cx);
1771
1772 this.add_item(
1773 Box::new(SubView::new(
1774 variable_list.focus_handle(cx),
1775 variable_list.clone().into(),
1776 DebuggerPaneItem::Variables,
1777 cx,
1778 )),
1779 true,
1780 false,
1781 None,
1782 window,
1783 cx,
1784 );
1785 this.activate_item(0, false, false, window, cx);
1786 });
1787
1788 let rightmost_pane = new_debugger_pane(workspace.clone(), project, window, cx);
1789 rightmost_pane.update(cx, |this, cx| {
1790 this.add_item(
1791 Box::new(SubView::new(
1792 debug_terminal.focus_handle(cx),
1793 debug_terminal.clone().into(),
1794 DebuggerPaneItem::Terminal,
1795 cx,
1796 )),
1797 false,
1798 false,
1799 None,
1800 window,
1801 cx,
1802 );
1803 });
1804
1805 subscriptions.extend(
1806 [&leftmost_pane, ¢er_pane, &rightmost_pane]
1807 .into_iter()
1808 .map(|entity| {
1809 (
1810 entity.entity_id(),
1811 cx.subscribe_in(entity, window, Self::handle_pane_event),
1812 )
1813 }),
1814 );
1815
1816 let group_root = workspace::PaneAxis::new(
1817 dock_axis.invert(),
1818 [leftmost_pane, center_pane, rightmost_pane]
1819 .into_iter()
1820 .map(workspace::Member::Pane)
1821 .collect(),
1822 );
1823
1824 Member::Axis(group_root)
1825 }
1826
1827 pub(crate) fn invert_axies(&mut self) {
1828 self.dock_axis = self.dock_axis.invert();
1829 self.panes.invert_axies();
1830 }
1831}
1832
1833impl Focusable for RunningState {
1834 fn focus_handle(&self, _: &App) -> FocusHandle {
1835 self.focus_handle.clone()
1836 }
1837}