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 cx,
577 )
578 }
579 }),
580 )
581 })
582 .into_any_element()
583 }
584 });
585 pane
586 })
587}
588
589pub struct DebugTerminal {
590 pub terminal: Option<Entity<TerminalView>>,
591 focus_handle: FocusHandle,
592 _subscriptions: [Subscription; 1],
593}
594
595impl DebugTerminal {
596 fn empty(window: &mut Window, cx: &mut Context<Self>) -> Self {
597 let focus_handle = cx.focus_handle();
598 let focus_subscription = cx.on_focus(&focus_handle, window, |this, window, cx| {
599 if let Some(terminal) = this.terminal.as_ref() {
600 terminal.focus_handle(cx).focus(window);
601 }
602 });
603
604 Self {
605 terminal: None,
606 focus_handle,
607 _subscriptions: [focus_subscription],
608 }
609 }
610}
611
612impl gpui::Render for DebugTerminal {
613 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
614 div()
615 .track_focus(&self.focus_handle)
616 .size_full()
617 .bg(cx.theme().colors().editor_background)
618 .children(self.terminal.clone())
619 }
620}
621impl Focusable for DebugTerminal {
622 fn focus_handle(&self, _cx: &App) -> FocusHandle {
623 self.focus_handle.clone()
624 }
625}
626
627impl RunningState {
628 // todo(debugger) move this to util and make it so you pass a closure to it that converts a string
629 pub(crate) fn substitute_variables_in_config(
630 config: &mut serde_json::Value,
631 context: &TaskContext,
632 ) {
633 match config {
634 serde_json::Value::Object(obj) => {
635 obj.values_mut()
636 .for_each(|value| Self::substitute_variables_in_config(value, context));
637 }
638 serde_json::Value::Array(array) => {
639 array
640 .iter_mut()
641 .for_each(|value| Self::substitute_variables_in_config(value, context));
642 }
643 serde_json::Value::String(s) => {
644 // Some built-in zed tasks wrap their arguments in quotes as they might contain spaces.
645 if s.starts_with("\"$ZED_") && s.ends_with('"') {
646 *s = s[1..s.len() - 1].to_string();
647 }
648 if let Some(substituted) = substitute_variables_in_str(s, context) {
649 *s = substituted;
650 }
651 }
652 _ => {}
653 }
654 }
655
656 pub(crate) fn relativize_paths(
657 key: Option<&str>,
658 config: &mut serde_json::Value,
659 context: &TaskContext,
660 ) {
661 match config {
662 serde_json::Value::Object(obj) => {
663 obj.iter_mut()
664 .for_each(|(key, value)| Self::relativize_paths(Some(key), value, context));
665 }
666 serde_json::Value::Array(array) => {
667 array
668 .iter_mut()
669 .for_each(|value| Self::relativize_paths(None, value, context));
670 }
671 serde_json::Value::String(s) if key == Some("program") || key == Some("cwd") => {
672 // Some built-in zed tasks wrap their arguments in quotes as they might contain spaces.
673 if s.starts_with("\"$ZED_") && s.ends_with('"') {
674 *s = s[1..s.len() - 1].to_string();
675 }
676 resolve_path(s);
677
678 if let Some(substituted) = substitute_variables_in_str(s, context) {
679 *s = substituted;
680 }
681 }
682 _ => {}
683 }
684 }
685
686 pub(crate) fn new(
687 session: Entity<Session>,
688 project: Entity<Project>,
689 workspace: WeakEntity<Workspace>,
690 parent_terminal: Option<Entity<DebugTerminal>>,
691 serialized_pane_layout: Option<SerializedLayout>,
692 dock_axis: Axis,
693 window: &mut Window,
694 cx: &mut Context<Self>,
695 ) -> Self {
696 let focus_handle = cx.focus_handle();
697 let session_id = session.read(cx).session_id();
698 let weak_state = cx.weak_entity();
699 let stack_frame_list = cx.new(|cx| {
700 StackFrameList::new(
701 workspace.clone(),
702 session.clone(),
703 weak_state.clone(),
704 window,
705 cx,
706 )
707 });
708
709 let debug_terminal =
710 parent_terminal.unwrap_or_else(|| cx.new(|cx| DebugTerminal::empty(window, cx)));
711 let memory_view = cx.new(|cx| {
712 MemoryView::new(
713 session.clone(),
714 workspace.clone(),
715 stack_frame_list.downgrade(),
716 window,
717 cx,
718 )
719 });
720 let variable_list = cx.new(|cx| {
721 VariableList::new(
722 session.clone(),
723 stack_frame_list.clone(),
724 memory_view.clone(),
725 weak_state.clone(),
726 window,
727 cx,
728 )
729 });
730
731 let module_list = cx.new(|cx| ModuleList::new(session.clone(), workspace.clone(), cx));
732
733 let loaded_source_list = cx.new(|cx| LoadedSourceList::new(session.clone(), cx));
734
735 let console = cx.new(|cx| {
736 Console::new(
737 session.clone(),
738 stack_frame_list.clone(),
739 variable_list.clone(),
740 window,
741 cx,
742 )
743 });
744
745 let breakpoint_list = BreakpointList::new(
746 Some(session.clone()),
747 workspace.clone(),
748 &project,
749 window,
750 cx,
751 );
752
753 let _subscriptions = vec![
754 cx.on_app_quit(move |this, cx| {
755 let shutdown = this
756 .session
757 .update(cx, |session, cx| session.on_app_quit(cx));
758 let terminal = this.debug_terminal.clone();
759 async move {
760 shutdown.await;
761 drop(terminal)
762 }
763 }),
764 cx.observe(&module_list, |_, _, cx| cx.notify()),
765 cx.subscribe_in(&session, window, |this, _, event, window, cx| {
766 match event {
767 SessionEvent::Stopped(thread_id) => {
768 let panel = this
769 .workspace
770 .update(cx, |workspace, cx| {
771 workspace.open_panel::<crate::DebugPanel>(window, cx);
772 workspace.panel::<crate::DebugPanel>(cx)
773 })
774 .log_err()
775 .flatten();
776
777 if let Some(thread_id) = thread_id {
778 this.select_thread(*thread_id, window, cx);
779 }
780 if let Some(panel) = panel {
781 let id = this.session_id;
782 window.defer(cx, move |window, cx| {
783 panel.update(cx, |this, cx| {
784 this.activate_session_by_id(id, window, cx);
785 })
786 })
787 }
788 }
789 SessionEvent::Threads => {
790 let threads = this.session.update(cx, |this, cx| this.threads(cx));
791 this.select_current_thread(&threads, window, cx);
792 }
793 SessionEvent::CapabilitiesLoaded => {
794 let capabilities = this.capabilities(cx);
795 if !capabilities.supports_modules_request.unwrap_or(false) {
796 this.remove_pane_item(DebuggerPaneItem::Modules, window, cx);
797 }
798 if !capabilities
799 .supports_loaded_sources_request
800 .unwrap_or(false)
801 {
802 this.remove_pane_item(DebuggerPaneItem::LoadedSources, window, cx);
803 }
804 }
805 SessionEvent::RunInTerminal { request, sender } => this
806 .handle_run_in_terminal(request, sender.clone(), window, cx)
807 .detach_and_log_err(cx),
808
809 _ => {}
810 }
811 cx.notify()
812 }),
813 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
814 this.serialize_layout(window, cx);
815 }),
816 cx.subscribe(
817 &session,
818 |this, session, event: &SessionStateEvent, cx| match event {
819 SessionStateEvent::Shutdown if session.read(cx).is_building() => {
820 this.shutdown(cx);
821 }
822 _ => {}
823 },
824 ),
825 ];
826
827 let mut pane_close_subscriptions = HashMap::default();
828 let panes = if let Some(root) = serialized_pane_layout.and_then(|serialized_layout| {
829 persistence::deserialize_pane_layout(
830 serialized_layout.panes,
831 dock_axis != serialized_layout.dock_axis,
832 &workspace,
833 &project,
834 &stack_frame_list,
835 &variable_list,
836 &module_list,
837 &console,
838 &breakpoint_list,
839 &loaded_source_list,
840 &debug_terminal,
841 &memory_view,
842 &mut pane_close_subscriptions,
843 window,
844 cx,
845 )
846 }) {
847 workspace::PaneGroup::with_root(root)
848 } else {
849 pane_close_subscriptions.clear();
850
851 let root = Self::default_pane_layout(
852 project,
853 &workspace,
854 &stack_frame_list,
855 &variable_list,
856 &console,
857 &breakpoint_list,
858 &debug_terminal,
859 dock_axis,
860 &mut pane_close_subscriptions,
861 window,
862 cx,
863 );
864
865 workspace::PaneGroup::with_root(root)
866 };
867 let active_pane = panes.first_pane();
868
869 Self {
870 memory_view,
871 session,
872 workspace,
873 focus_handle,
874 variable_list,
875 _subscriptions,
876 thread_id: None,
877 _remote_id: None,
878 stack_frame_list,
879 session_id,
880 panes,
881 active_pane,
882 module_list,
883 console,
884 breakpoint_list,
885 loaded_sources_list: loaded_source_list,
886 pane_close_subscriptions,
887 debug_terminal,
888 dock_axis,
889 _schedule_serialize: None,
890 scenario: None,
891 scenario_context: None,
892 }
893 }
894
895 pub(crate) fn remove_pane_item(
896 &mut self,
897 item_kind: DebuggerPaneItem,
898 window: &mut Window,
899 cx: &mut Context<Self>,
900 ) {
901 if let Some((pane, item_id)) = self.panes.panes().iter().find_map(|pane| {
902 Some(pane).zip(
903 pane.read(cx)
904 .items()
905 .find(|item| {
906 item.act_as::<SubView>(cx)
907 .is_some_and(|view| view.read(cx).kind == item_kind)
908 })
909 .map(|item| item.item_id()),
910 )
911 }) {
912 pane.update(cx, |pane, cx| {
913 pane.remove_item(item_id, false, true, window, cx)
914 })
915 }
916 }
917
918 pub(crate) fn has_pane_at_position(&self, position: Point<Pixels>) -> bool {
919 self.panes.pane_at_pixel_position(position).is_some()
920 }
921
922 pub(crate) fn resolve_scenario(
923 &self,
924 scenario: DebugScenario,
925 task_context: TaskContext,
926 buffer: Option<Entity<Buffer>>,
927 worktree_id: Option<WorktreeId>,
928 window: &Window,
929 cx: &mut Context<Self>,
930 ) -> Task<Result<DebugTaskDefinition>> {
931 let Some(workspace) = self.workspace.upgrade() else {
932 return Task::ready(Err(anyhow!("no workspace")));
933 };
934 let project = workspace.read(cx).project().clone();
935 let dap_store = project.read(cx).dap_store().downgrade();
936 let dap_registry = cx.global::<DapRegistry>().clone();
937 let task_store = project.read(cx).task_store().downgrade();
938 let weak_project = project.downgrade();
939 let weak_workspace = workspace.downgrade();
940 let is_windows = project.read(cx).path_style(cx).is_windows();
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(mut task) = task_template.resolve_task("debug-build-task",&|| remote_shell.clone(), &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 if task.resolved.shell == Shell::System && let Some(remote_shell) = remote_shell.clone() {
1030 task.resolved.shell = Shell::Program(remote_shell);
1031 }
1032
1033 let builder = ShellBuilder::new(&task.resolved.shell, is_windows);
1034 let command_label = builder.command_label(task.resolved.command.as_deref().unwrap_or(""));
1035 let (command, args) =
1036 builder.build(task.resolved.command.clone(), &task.resolved.args);
1037
1038 let task_with_shell = SpawnInTerminal {
1039 command_label,
1040 command: Some(command),
1041 args,
1042 ..task.resolved.clone()
1043 };
1044 let terminal = project
1045 .update(cx, |project, cx| {
1046 project.create_terminal_task(
1047 task_with_shell.clone(),
1048 cx,
1049 )
1050 })?.await?;
1051
1052 let terminal_view = cx.new_window_entity(|window, cx| {
1053 TerminalView::new(
1054 terminal.clone(),
1055 weak_workspace,
1056 None,
1057 weak_project,
1058 window,
1059 cx,
1060 )
1061 })?;
1062
1063 this.update_in(cx, |this, window, cx| {
1064 this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1065 this.debug_terminal.update(cx, |debug_terminal, cx| {
1066 debug_terminal.terminal = Some(terminal_view);
1067 cx.notify();
1068 });
1069 })?;
1070
1071 let exit_status = terminal
1072 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1073 .await
1074 .context("Failed to wait for completed task")?;
1075
1076 if !exit_status.success() {
1077 anyhow::bail!("Build failed");
1078 }
1079 Some((task.resolved.clone(), locator_name, extra_config))
1080 } else {
1081 None
1082 };
1083
1084 if config_is_valid {
1085 } else if let Some((task, locator_name, extra_config)) = build_output {
1086 let locator_name =
1087 locator_name.with_context(|| {
1088 format!("Could not find a valid locator for a build task and configure is invalid with error: {}", request_type.err()
1089 .map(|err| err.to_string())
1090 .unwrap_or_default())
1091 })?;
1092 let request = dap_store
1093 .update(cx, |this, cx| {
1094 this.run_debug_locator(&locator_name, task, cx)
1095 })?
1096 .await?;
1097
1098 let zed_config = ZedDebugConfig {
1099 label: label.clone(),
1100 adapter: adapter.clone(),
1101 request,
1102 stop_on_entry: None,
1103 };
1104
1105 let scenario = dap_registry
1106 .adapter(&adapter)
1107 .with_context(|| anyhow!("{}: is not a valid adapter name", &adapter))?.config_from_zed_format(zed_config)
1108 .await?;
1109 config = scenario.config;
1110 util::merge_non_null_json_value_into(extra_config, &mut config);
1111
1112 Self::substitute_variables_in_config(&mut config, &task_context);
1113 } else {
1114 let Err(e) = request_type else {
1115 unreachable!();
1116 };
1117 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}");
1118 };
1119
1120 Ok(DebugTaskDefinition {
1121 label,
1122 adapter: DebugAdapterName(adapter),
1123 config,
1124 tcp_connection,
1125 })
1126 })
1127 }
1128
1129 fn handle_run_in_terminal(
1130 &self,
1131 request: &RunInTerminalRequestArguments,
1132 mut sender: mpsc::Sender<Result<u32>>,
1133 window: &mut Window,
1134 cx: &mut Context<Self>,
1135 ) -> Task<Result<()>> {
1136 let running = cx.entity();
1137 let Ok(project) = self
1138 .workspace
1139 .read_with(cx, |workspace, _| workspace.project().clone())
1140 else {
1141 return Task::ready(Err(anyhow!("no workspace")));
1142 };
1143 let session = self.session.read(cx);
1144
1145 let cwd = (!request.cwd.is_empty())
1146 .then(|| PathBuf::from(&request.cwd))
1147 .or_else(|| session.binary().unwrap().cwd.clone());
1148
1149 let mut envs: HashMap<String, String> =
1150 self.session.read(cx).task_context().project_env.clone();
1151 if let Some(Value::Object(env)) = &request.env {
1152 for (key, value) in env {
1153 let value_str = match (key.as_str(), value) {
1154 (_, Value::String(value)) => value,
1155 _ => continue,
1156 };
1157
1158 envs.insert(key.clone(), value_str.clone());
1159 }
1160 }
1161
1162 let mut args = request.args.clone();
1163 let command = if envs.contains_key("VSCODE_INSPECTOR_OPTIONS") {
1164 // Handle special case for NodeJS debug adapter
1165 // If the Node binary path is provided (possibly with arguments like --experimental-network-inspection),
1166 // we set the command to None
1167 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1168 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1169 // This allows the NodeJS debug client to attach correctly
1170 if args
1171 .iter()
1172 .filter(|arg| !arg.starts_with("--"))
1173 .collect::<Vec<_>>()
1174 .len()
1175 > 1
1176 {
1177 Some(args.remove(0))
1178 } else {
1179 None
1180 }
1181 } else if !args.is_empty() {
1182 Some(args.remove(0))
1183 } else {
1184 None
1185 };
1186
1187 let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1188 let title = request
1189 .title
1190 .clone()
1191 .filter(|title| !title.is_empty())
1192 .or_else(|| command.clone())
1193 .unwrap_or_else(|| "Debug terminal".to_string());
1194 let kind = task::SpawnInTerminal {
1195 id: task::TaskId("debug".to_string()),
1196 full_label: title.clone(),
1197 label: title.clone(),
1198 command,
1199 args,
1200 command_label: title,
1201 cwd,
1202 env: envs,
1203 use_new_terminal: true,
1204 allow_concurrent_runs: true,
1205 reveal: task::RevealStrategy::NoFocus,
1206 reveal_target: task::RevealTarget::Dock,
1207 hide: task::HideStrategy::Never,
1208 shell,
1209 show_summary: false,
1210 show_command: false,
1211 show_rerun: false,
1212 };
1213
1214 let workspace = self.workspace.clone();
1215 let weak_project = project.downgrade();
1216
1217 let terminal_task =
1218 project.update(cx, |project, cx| project.create_terminal_task(kind, cx));
1219 let terminal_task = cx.spawn_in(window, async move |_, cx| {
1220 let terminal = terminal_task.await?;
1221
1222 let terminal_view = cx.new_window_entity(|window, cx| {
1223 TerminalView::new(terminal.clone(), workspace, None, weak_project, window, cx)
1224 })?;
1225
1226 running.update_in(cx, |running, window, cx| {
1227 running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1228 running.debug_terminal.update(cx, |debug_terminal, cx| {
1229 debug_terminal.terminal = Some(terminal_view);
1230 cx.notify();
1231 });
1232 })?;
1233
1234 terminal.read_with(cx, |terminal, _| {
1235 terminal
1236 .pid()
1237 .map(|pid| pid.as_u32())
1238 .context("Terminal was spawned but PID was not available")
1239 })?
1240 });
1241
1242 cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1243 }
1244
1245 fn create_sub_view(
1246 &self,
1247 item_kind: DebuggerPaneItem,
1248 _pane: &Entity<Pane>,
1249 cx: &mut Context<Self>,
1250 ) -> Box<dyn ItemHandle> {
1251 match item_kind {
1252 DebuggerPaneItem::Console => Box::new(SubView::console(self.console.clone(), cx)),
1253 DebuggerPaneItem::Variables => Box::new(SubView::new(
1254 self.variable_list.focus_handle(cx),
1255 self.variable_list.clone().into(),
1256 item_kind,
1257 cx,
1258 )),
1259 DebuggerPaneItem::BreakpointList => {
1260 Box::new(SubView::breakpoint_list(self.breakpoint_list.clone(), cx))
1261 }
1262 DebuggerPaneItem::Frames => Box::new(SubView::new(
1263 self.stack_frame_list.focus_handle(cx),
1264 self.stack_frame_list.clone().into(),
1265 item_kind,
1266 cx,
1267 )),
1268 DebuggerPaneItem::Modules => Box::new(SubView::new(
1269 self.module_list.focus_handle(cx),
1270 self.module_list.clone().into(),
1271 item_kind,
1272 cx,
1273 )),
1274 DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1275 self.loaded_sources_list.focus_handle(cx),
1276 self.loaded_sources_list.clone().into(),
1277 item_kind,
1278 cx,
1279 )),
1280 DebuggerPaneItem::Terminal => Box::new(SubView::new(
1281 self.debug_terminal.focus_handle(cx),
1282 self.debug_terminal.clone().into(),
1283 item_kind,
1284 cx,
1285 )),
1286 DebuggerPaneItem::MemoryView => Box::new(SubView::new(
1287 self.memory_view.focus_handle(cx),
1288 self.memory_view.clone().into(),
1289 item_kind,
1290 cx,
1291 )),
1292 }
1293 }
1294
1295 pub(crate) fn ensure_pane_item(
1296 &mut self,
1297 item_kind: DebuggerPaneItem,
1298 window: &mut Window,
1299 cx: &mut Context<Self>,
1300 ) {
1301 if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1302 return;
1303 };
1304 let pane = self.panes.last_pane();
1305 let sub_view = self.create_sub_view(item_kind, &pane, cx);
1306
1307 pane.update(cx, |pane, cx| {
1308 pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1309 })
1310 }
1311
1312 pub(crate) fn add_pane_item(
1313 &mut self,
1314 item_kind: DebuggerPaneItem,
1315 position: Point<Pixels>,
1316 window: &mut Window,
1317 cx: &mut Context<Self>,
1318 ) {
1319 debug_assert!(
1320 item_kind.is_supported(self.session.read(cx).capabilities()),
1321 "We should only allow adding supported item kinds"
1322 );
1323
1324 if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1325 let sub_view = self.create_sub_view(item_kind, pane, cx);
1326
1327 pane.update(cx, |pane, cx| {
1328 pane.add_item(sub_view, false, false, None, window, cx);
1329 })
1330 }
1331 }
1332
1333 pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1334 let caps = self.session.read(cx).capabilities();
1335 let mut pane_item_status = IndexMap::from_iter(
1336 DebuggerPaneItem::all()
1337 .iter()
1338 .filter(|kind| kind.is_supported(caps))
1339 .map(|kind| (*kind, false)),
1340 );
1341 self.panes.panes().iter().for_each(|pane| {
1342 pane.read(cx)
1343 .items()
1344 .filter_map(|item| item.act_as::<SubView>(cx))
1345 .for_each(|view| {
1346 pane_item_status.insert(view.read(cx).kind, true);
1347 });
1348 });
1349
1350 pane_item_status
1351 }
1352
1353 pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1354 if self._schedule_serialize.is_none() {
1355 self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1356 cx.background_executor()
1357 .timer(Duration::from_millis(100))
1358 .await;
1359
1360 let Some((adapter_name, pane_layout)) = this
1361 .read_with(cx, |this, cx| {
1362 let adapter_name = this.session.read(cx).adapter();
1363 (
1364 adapter_name,
1365 persistence::build_serialized_layout(
1366 &this.panes.root,
1367 this.dock_axis,
1368 cx,
1369 ),
1370 )
1371 })
1372 .ok()
1373 else {
1374 return;
1375 };
1376
1377 persistence::serialize_pane_layout(adapter_name, pane_layout)
1378 .await
1379 .log_err();
1380
1381 this.update(cx, |this, _| {
1382 this._schedule_serialize.take();
1383 })
1384 .ok();
1385 }));
1386 }
1387 }
1388
1389 pub(crate) fn handle_pane_event(
1390 this: &mut RunningState,
1391 source_pane: &Entity<Pane>,
1392 event: &Event,
1393 window: &mut Window,
1394 cx: &mut Context<RunningState>,
1395 ) {
1396 this.serialize_layout(window, cx);
1397 match event {
1398 Event::Remove { .. } => {
1399 let _did_find_pane = this.panes.remove(source_pane).is_ok();
1400 debug_assert!(_did_find_pane);
1401 cx.notify();
1402 }
1403 Event::Focus => {
1404 this.active_pane = source_pane.clone();
1405 }
1406 _ => {}
1407 }
1408 }
1409
1410 pub(crate) fn activate_pane_in_direction(
1411 &mut self,
1412 direction: SplitDirection,
1413 window: &mut Window,
1414 cx: &mut Context<Self>,
1415 ) {
1416 let active_pane = self.active_pane.clone();
1417 if let Some(pane) = self
1418 .panes
1419 .find_pane_in_direction(&active_pane, direction, cx)
1420 {
1421 pane.update(cx, |pane, cx| {
1422 pane.focus_active_item(window, cx);
1423 })
1424 } else {
1425 self.workspace
1426 .update(cx, |workspace, cx| {
1427 workspace.activate_pane_in_direction(direction, window, cx)
1428 })
1429 .ok();
1430 }
1431 }
1432
1433 pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1434 if self.thread_id.is_some() {
1435 self.stack_frame_list
1436 .update(cx, |list, cx| {
1437 let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1438 return Task::ready(Ok(()));
1439 };
1440 list.go_to_stack_frame(stack_frame_id, window, cx)
1441 })
1442 .detach();
1443 }
1444 }
1445
1446 pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1447 self.variable_list.read(cx).has_open_context_menu()
1448 }
1449
1450 pub fn session(&self) -> &Entity<Session> {
1451 &self.session
1452 }
1453
1454 pub fn session_id(&self) -> SessionId {
1455 self.session_id
1456 }
1457
1458 pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1459 self.stack_frame_list.read(cx).opened_stack_frame_id()
1460 }
1461
1462 pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1463 &self.stack_frame_list
1464 }
1465
1466 #[cfg(test)]
1467 pub fn console(&self) -> &Entity<Console> {
1468 &self.console
1469 }
1470
1471 #[cfg(test)]
1472 pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1473 &self.module_list
1474 }
1475
1476 pub(crate) fn activate_item(
1477 &mut self,
1478 item: DebuggerPaneItem,
1479 window: &mut Window,
1480 cx: &mut Context<Self>,
1481 ) {
1482 self.ensure_pane_item(item, window, cx);
1483
1484 let (variable_list_position, pane) = self
1485 .panes
1486 .panes()
1487 .into_iter()
1488 .find_map(|pane| {
1489 pane.read(cx)
1490 .items_of_type::<SubView>()
1491 .position(|view| view.read(cx).view_kind() == item)
1492 .map(|view| (view, pane))
1493 })
1494 .unwrap();
1495
1496 pane.update(cx, |this, cx| {
1497 this.activate_item(variable_list_position, true, true, window, cx);
1498 });
1499 }
1500
1501 #[cfg(test)]
1502 pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1503 &self.variable_list
1504 }
1505
1506 #[cfg(test)]
1507 pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1508 persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1509 }
1510
1511 pub fn capabilities(&self, cx: &App) -> Capabilities {
1512 self.session().read(cx).capabilities().clone()
1513 }
1514
1515 pub fn select_current_thread(
1516 &mut self,
1517 threads: &Vec<(Thread, ThreadStatus)>,
1518 window: &mut Window,
1519 cx: &mut Context<Self>,
1520 ) {
1521 let selected_thread = self
1522 .thread_id
1523 .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1524 .or_else(|| threads.first());
1525
1526 let Some((selected_thread, _)) = selected_thread else {
1527 return;
1528 };
1529
1530 if Some(ThreadId(selected_thread.id)) != self.thread_id {
1531 self.select_thread(ThreadId(selected_thread.id), window, cx);
1532 }
1533 }
1534
1535 pub fn selected_thread_id(&self) -> Option<ThreadId> {
1536 self.thread_id
1537 }
1538
1539 pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1540 self.thread_id
1541 .map(|id| self.session().read(cx).thread_status(id))
1542 }
1543
1544 pub(crate) fn select_thread(
1545 &mut self,
1546 thread_id: ThreadId,
1547 window: &mut Window,
1548 cx: &mut Context<Self>,
1549 ) {
1550 if self.thread_id.is_some_and(|id| id == thread_id) {
1551 return;
1552 }
1553
1554 self.thread_id = Some(thread_id);
1555
1556 self.stack_frame_list
1557 .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1558 }
1559
1560 pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1561 let Some(thread_id) = self.thread_id else {
1562 return;
1563 };
1564
1565 self.session().update(cx, |state, cx| {
1566 state.continue_thread(thread_id, cx);
1567 });
1568 }
1569
1570 pub fn step_over(&mut self, cx: &mut Context<Self>) {
1571 let Some(thread_id) = self.thread_id else {
1572 return;
1573 };
1574
1575 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1576
1577 self.session().update(cx, |state, cx| {
1578 state.step_over(thread_id, granularity, cx);
1579 });
1580 }
1581
1582 pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1583 let Some(thread_id) = self.thread_id else {
1584 return;
1585 };
1586
1587 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1588
1589 self.session().update(cx, |state, cx| {
1590 state.step_in(thread_id, granularity, cx);
1591 });
1592 }
1593
1594 pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1595 let Some(thread_id) = self.thread_id else {
1596 return;
1597 };
1598
1599 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1600
1601 self.session().update(cx, |state, cx| {
1602 state.step_out(thread_id, granularity, cx);
1603 });
1604 }
1605
1606 pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1607 let Some(thread_id) = self.thread_id else {
1608 return;
1609 };
1610
1611 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1612
1613 self.session().update(cx, |state, cx| {
1614 state.step_back(thread_id, granularity, cx);
1615 });
1616 }
1617
1618 pub fn rerun_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1619 if let Some((scenario, context)) = self.scenario.take().zip(self.scenario_context.take())
1620 && scenario.build.is_some()
1621 {
1622 let DebugScenarioContext {
1623 task_context,
1624 active_buffer,
1625 worktree_id,
1626 } = context;
1627 let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
1628
1629 self.workspace
1630 .update(cx, |workspace, cx| {
1631 workspace.start_debug_session(
1632 scenario,
1633 task_context,
1634 active_buffer,
1635 worktree_id,
1636 window,
1637 cx,
1638 )
1639 })
1640 .ok();
1641 } else {
1642 self.restart_session(cx);
1643 }
1644 }
1645
1646 pub fn restart_session(&self, cx: &mut Context<Self>) {
1647 self.session().update(cx, |state, cx| {
1648 state.restart(None, cx);
1649 });
1650 }
1651
1652 pub fn pause_thread(&self, cx: &mut Context<Self>) {
1653 let Some(thread_id) = self.thread_id else {
1654 return;
1655 };
1656
1657 self.session().update(cx, |state, cx| {
1658 state.pause_thread(thread_id, cx);
1659 });
1660 }
1661
1662 pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1663 self.workspace
1664 .update(cx, |workspace, cx| {
1665 workspace
1666 .project()
1667 .read(cx)
1668 .breakpoint_store()
1669 .update(cx, |store, cx| {
1670 store.remove_active_position(Some(self.session_id), cx)
1671 })
1672 })
1673 .log_err();
1674
1675 let is_building = self.session.update(cx, |session, cx| {
1676 session.shutdown(cx).detach();
1677 matches!(session.mode, session::SessionState::Booting(_))
1678 });
1679
1680 if is_building {
1681 self.debug_terminal.update(cx, |terminal, cx| {
1682 if let Some(view) = terminal.terminal.as_ref() {
1683 view.update(cx, |view, cx| {
1684 view.terminal()
1685 .update(cx, |terminal, _| terminal.kill_active_task())
1686 })
1687 }
1688 })
1689 }
1690 }
1691
1692 pub fn stop_thread(&self, cx: &mut Context<Self>) {
1693 let Some(thread_id) = self.thread_id else {
1694 return;
1695 };
1696
1697 self.workspace
1698 .update(cx, |workspace, cx| {
1699 workspace
1700 .project()
1701 .read(cx)
1702 .breakpoint_store()
1703 .update(cx, |store, cx| {
1704 store.remove_active_position(Some(self.session_id), cx)
1705 })
1706 })
1707 .log_err();
1708
1709 self.session().update(cx, |state, cx| {
1710 state.terminate_threads(Some(vec![thread_id; 1]), cx);
1711 });
1712 }
1713
1714 pub fn detach_client(&self, cx: &mut Context<Self>) {
1715 self.session().update(cx, |state, cx| {
1716 state.disconnect_client(cx);
1717 });
1718 }
1719
1720 pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1721 self.session.update(cx, |session, cx| {
1722 session.toggle_ignore_breakpoints(cx).detach();
1723 });
1724 }
1725
1726 fn default_pane_layout(
1727 project: Entity<Project>,
1728 workspace: &WeakEntity<Workspace>,
1729 stack_frame_list: &Entity<StackFrameList>,
1730 variable_list: &Entity<VariableList>,
1731 console: &Entity<Console>,
1732 breakpoints: &Entity<BreakpointList>,
1733 debug_terminal: &Entity<DebugTerminal>,
1734 dock_axis: Axis,
1735 subscriptions: &mut HashMap<EntityId, Subscription>,
1736 window: &mut Window,
1737 cx: &mut Context<'_, RunningState>,
1738 ) -> Member {
1739 let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1740 leftmost_pane.update(cx, |this, cx| {
1741 this.add_item(
1742 Box::new(SubView::new(
1743 this.focus_handle(cx),
1744 stack_frame_list.clone().into(),
1745 DebuggerPaneItem::Frames,
1746 cx,
1747 )),
1748 true,
1749 false,
1750 None,
1751 window,
1752 cx,
1753 );
1754 this.add_item(
1755 Box::new(SubView::breakpoint_list(breakpoints.clone(), cx)),
1756 true,
1757 false,
1758 None,
1759 window,
1760 cx,
1761 );
1762 this.activate_item(0, false, false, window, cx);
1763 });
1764 let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1765
1766 center_pane.update(cx, |this, cx| {
1767 let view = SubView::console(console.clone(), cx);
1768
1769 this.add_item(Box::new(view), true, false, None, window, cx);
1770
1771 this.add_item(
1772 Box::new(SubView::new(
1773 variable_list.focus_handle(cx),
1774 variable_list.clone().into(),
1775 DebuggerPaneItem::Variables,
1776 cx,
1777 )),
1778 true,
1779 false,
1780 None,
1781 window,
1782 cx,
1783 );
1784 this.activate_item(0, false, false, window, cx);
1785 });
1786
1787 let rightmost_pane = new_debugger_pane(workspace.clone(), project, window, cx);
1788 rightmost_pane.update(cx, |this, cx| {
1789 this.add_item(
1790 Box::new(SubView::new(
1791 debug_terminal.focus_handle(cx),
1792 debug_terminal.clone().into(),
1793 DebuggerPaneItem::Terminal,
1794 cx,
1795 )),
1796 false,
1797 false,
1798 None,
1799 window,
1800 cx,
1801 );
1802 });
1803
1804 subscriptions.extend(
1805 [&leftmost_pane, ¢er_pane, &rightmost_pane]
1806 .into_iter()
1807 .map(|entity| {
1808 (
1809 entity.entity_id(),
1810 cx.subscribe_in(entity, window, Self::handle_pane_event),
1811 )
1812 }),
1813 );
1814
1815 let group_root = workspace::PaneAxis::new(
1816 dock_axis.invert(),
1817 [leftmost_pane, center_pane, rightmost_pane]
1818 .into_iter()
1819 .map(workspace::Member::Pane)
1820 .collect(),
1821 );
1822
1823 Member::Axis(group_root)
1824 }
1825
1826 pub(crate) fn invert_axies(&mut self) {
1827 self.dock_axis = self.dock_axis.invert();
1828 self.panes.invert_axies();
1829 }
1830}
1831
1832impl Focusable for RunningState {
1833 fn focus_handle(&self, _: &App) -> FocusHandle {
1834 self.focus_handle.clone()
1835 }
1836}