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, ShellBuilder, SpawnInTerminal, TaskContext, ZedDebugConfig,
45 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 window,
390 cx,
391 );
392 let focus_handle = pane.focus_handle(cx);
393 pane.set_can_split(Some(Arc::new({
394 let weak_running = weak_running.clone();
395 move |pane, dragged_item, _window, cx| {
396 if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
397 let is_current_pane = tab.pane == cx.entity();
398 let Some(can_drag_away) = weak_running
399 .read_with(cx, |running_state, _| {
400 let current_panes = running_state.panes.panes();
401 !current_panes.contains(&&tab.pane)
402 || current_panes.len() > 1
403 || (!is_current_pane || pane.items_len() > 1)
404 })
405 .ok()
406 else {
407 return false;
408 };
409 if can_drag_away {
410 let item = if is_current_pane {
411 pane.item_for_index(tab.ix)
412 } else {
413 tab.pane.read(cx).item_for_index(tab.ix)
414 };
415 if let Some(item) = item {
416 return item.downcast::<SubView>().is_some();
417 }
418 }
419 }
420 false
421 }
422 })));
423 pane.set_can_toggle_zoom(false, cx);
424 pane.display_nav_history_buttons(None);
425 pane.set_custom_drop_handle(cx, custom_drop_handle);
426 pane.set_should_display_tab_bar(|_, _| true);
427 pane.set_render_tab_bar_buttons(cx, |_, _, _| (None, None));
428 pane.set_render_tab_bar(cx, {
429 move |pane, window, cx| {
430 let active_pane_item = pane.active_item();
431 let pane_group_id: SharedString =
432 format!("pane-zoom-button-hover-{}", cx.entity_id()).into();
433 let as_subview = active_pane_item
434 .as_ref()
435 .and_then(|item| item.downcast::<SubView>());
436 let is_hovered = as_subview
437 .as_ref()
438 .is_some_and(|item| item.read(cx).hovered);
439
440 h_flex()
441 .track_focus(&focus_handle)
442 .group(pane_group_id.clone())
443 .pl_1p5()
444 .pr_1()
445 .justify_between()
446 .border_b_1()
447 .border_color(cx.theme().colors().border)
448 .bg(cx.theme().colors().tab_bar_background)
449 .on_action(|_: &menu::Cancel, window, cx| {
450 if cx.stop_active_drag(window) {
451 } else {
452 cx.propagate();
453 }
454 })
455 .child(
456 h_flex()
457 .w_full()
458 .gap_1()
459 .h(Tab::container_height(cx))
460 .drag_over::<DraggedTab>(|bar, _, _, cx| {
461 bar.bg(cx.theme().colors().drop_target_background)
462 })
463 .on_drop(cx.listener(
464 move |this, dragged_tab: &DraggedTab, window, cx| {
465 this.drag_split_direction = None;
466 this.handle_tab_drop(dragged_tab, this.items_len(), window, cx)
467 },
468 ))
469 .children(pane.items().enumerate().map(|(ix, item)| {
470 let selected = active_pane_item
471 .as_ref()
472 .is_some_and(|active| active.item_id() == item.item_id());
473 let deemphasized = !pane.has_focus(window, cx);
474 let item_ = item.boxed_clone();
475 div()
476 .id(SharedString::from(format!(
477 "debugger_tab_{}",
478 item.item_id().as_u64()
479 )))
480 .p_1()
481 .rounded_md()
482 .cursor_pointer()
483 .when_some(item.tab_tooltip_text(cx), |this, tooltip| {
484 this.tooltip(Tooltip::text(tooltip))
485 })
486 .map(|this| {
487 let theme = cx.theme();
488 if selected {
489 let color = theme.colors().tab_active_background;
490 let color = if deemphasized {
491 color.opacity(0.5)
492 } else {
493 color
494 };
495 this.bg(color)
496 } else {
497 let hover_color = theme.colors().element_hover;
498 this.hover(|style| style.bg(hover_color))
499 }
500 })
501 .on_click(cx.listener(move |this, _, window, cx| {
502 let index = this.index_for_item(&*item_);
503 if let Some(index) = index {
504 this.activate_item(index, true, true, window, cx);
505 }
506 }))
507 .child(item.tab_content(
508 TabContentParams {
509 selected,
510 deemphasized,
511 ..Default::default()
512 },
513 window,
514 cx,
515 ))
516 .on_drop(cx.listener(
517 move |this, dragged_tab: &DraggedTab, window, cx| {
518 this.drag_split_direction = None;
519 this.handle_tab_drop(dragged_tab, ix, window, cx)
520 },
521 ))
522 .on_drag(
523 DraggedTab {
524 item: item.boxed_clone(),
525 pane: cx.entity(),
526 detail: 0,
527 is_active: selected,
528 ix,
529 },
530 |tab, _, _, cx| cx.new(|_| tab.clone()),
531 )
532 })),
533 )
534 .child({
535 let zoomed = pane.is_zoomed();
536
537 h_flex()
538 .visible_on_hover(pane_group_id)
539 .when(is_hovered, |this| this.visible())
540 .when_some(as_subview.as_ref(), |this, subview| {
541 subview.update(cx, |view, cx| {
542 let Some(additional_actions) = view.actions.as_mut() else {
543 return this;
544 };
545 this.child(additional_actions(window, cx))
546 })
547 })
548 .child(
549 IconButton::new(
550 SharedString::from(format!(
551 "debug-toggle-zoom-{}",
552 cx.entity_id()
553 )),
554 if zoomed {
555 IconName::Minimize
556 } else {
557 IconName::Maximize
558 },
559 )
560 .icon_size(IconSize::Small)
561 .on_click(cx.listener(move |pane, _, _, cx| {
562 let is_zoomed = pane.is_zoomed();
563 pane.set_zoomed(!is_zoomed, cx);
564 cx.notify();
565 }))
566 .tooltip({
567 let focus_handle = focus_handle.clone();
568 move |window, cx| {
569 let zoomed_text =
570 if zoomed { "Minimize" } else { "Expand" };
571 Tooltip::for_action_in(
572 zoomed_text,
573 &ToggleExpandItem,
574 &focus_handle,
575 window,
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 remote_shell = project
941 .read(cx)
942 .remote_client()
943 .as_ref()
944 .and_then(|remote| remote.read(cx).shell());
945
946 cx.spawn_in(window, async move |this, cx| {
947 let DebugScenario {
948 adapter,
949 label,
950 build,
951 mut config,
952 tcp_connection,
953 } = scenario;
954 Self::relativize_paths(None, &mut config, &task_context);
955 Self::substitute_variables_in_config(&mut config, &task_context);
956
957 let request_type = match dap_registry
958 .adapter(&adapter)
959 .with_context(|| format!("{}: is not a valid adapter name", &adapter)) {
960 Ok(adapter) => adapter.request_kind(&config).await,
961 Err(e) => Err(e)
962 };
963
964
965 let config_is_valid = request_type.is_ok();
966 let mut extra_config = Value::Null;
967 let build_output = if let Some(build) = build {
968 let (task_template, locator_name) = match build {
969 BuildTaskDefinition::Template {
970 task_template,
971 locator_name,
972 } => (task_template, locator_name),
973 BuildTaskDefinition::ByName(ref label) => {
974 let task = task_store.update(cx, |this, cx| {
975 this.task_inventory().map(|inventory| {
976 inventory.read(cx).task_template_by_label(
977 buffer,
978 worktree_id,
979 label,
980 cx,
981 )
982 })
983 })?;
984 let task = match task {
985 Some(task) => task.await,
986 None => None,
987 }.with_context(|| format!("Couldn't find task template for {build:?}"))?;
988 (task, None)
989 }
990 };
991 let Some(task) = task_template.resolve_task("debug-build-task", &task_context) else {
992 anyhow::bail!("Could not resolve task variables within a debug scenario");
993 };
994
995 let locator_name = if let Some(locator_name) = locator_name {
996 extra_config = config.clone();
997 debug_assert!(!config_is_valid);
998 Some(locator_name)
999 } else if !config_is_valid {
1000 let task = dap_store
1001 .update(cx, |this, cx| {
1002 this.debug_scenario_for_build_task(
1003 task.original_task().clone(),
1004 adapter.clone().into(),
1005 task.display_label().to_owned().into(),
1006 cx,
1007 )
1008
1009 });
1010 if let Ok(t) = task {
1011 t.await.and_then(|scenario| {
1012 extra_config = scenario.config;
1013 match scenario.build {
1014 Some(BuildTaskDefinition::Template {
1015 locator_name, ..
1016 }) => locator_name,
1017 _ => None,
1018 }
1019 })
1020 } else {
1021 None
1022 }
1023
1024 } else {
1025 None
1026 };
1027
1028 let builder = ShellBuilder::new(remote_shell.as_deref(), &task.resolved.shell);
1029 let command_label = builder.command_label(&task.resolved.command_label);
1030 let (command, args) =
1031 builder.build(task.resolved.command.clone(), &task.resolved.args);
1032
1033 let task_with_shell = SpawnInTerminal {
1034 command_label,
1035 command: Some(command),
1036 args,
1037 ..task.resolved.clone()
1038 };
1039 let terminal = project
1040 .update(cx, |project, cx| {
1041 project.create_terminal_task(
1042 task_with_shell.clone(),
1043 cx,
1044 )
1045 })?.await?;
1046
1047 let terminal_view = cx.new_window_entity(|window, cx| {
1048 TerminalView::new(
1049 terminal.clone(),
1050 weak_workspace,
1051 None,
1052 weak_project,
1053 window,
1054 cx,
1055 )
1056 })?;
1057
1058 this.update_in(cx, |this, window, cx| {
1059 this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1060 this.debug_terminal.update(cx, |debug_terminal, cx| {
1061 debug_terminal.terminal = Some(terminal_view);
1062 cx.notify();
1063 });
1064 })?;
1065
1066 let exit_status = terminal
1067 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1068 .await
1069 .context("Failed to wait for completed task")?;
1070
1071 if !exit_status.success() {
1072 anyhow::bail!("Build failed");
1073 }
1074 Some((task.resolved.clone(), locator_name, extra_config))
1075 } else {
1076 None
1077 };
1078
1079 if config_is_valid {
1080 } else if let Some((task, locator_name, extra_config)) = build_output {
1081 let locator_name =
1082 locator_name.with_context(|| {
1083 format!("Could not find a valid locator for a build task and configure is invalid with error: {}", request_type.err()
1084 .map(|err| err.to_string())
1085 .unwrap_or_default())
1086 })?;
1087 let request = dap_store
1088 .update(cx, |this, cx| {
1089 this.run_debug_locator(&locator_name, task, cx)
1090 })?
1091 .await?;
1092
1093 let zed_config = ZedDebugConfig {
1094 label: label.clone(),
1095 adapter: adapter.clone(),
1096 request,
1097 stop_on_entry: None,
1098 };
1099
1100 let scenario = dap_registry
1101 .adapter(&adapter)
1102 .with_context(|| anyhow!("{}: is not a valid adapter name", &adapter))?.config_from_zed_format(zed_config)
1103 .await?;
1104 config = scenario.config;
1105 util::merge_non_null_json_value_into(extra_config, &mut config);
1106
1107 Self::substitute_variables_in_config(&mut config, &task_context);
1108 } else {
1109 let Err(e) = request_type else {
1110 unreachable!();
1111 };
1112 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}");
1113 };
1114
1115 Ok(DebugTaskDefinition {
1116 label,
1117 adapter: DebugAdapterName(adapter),
1118 config,
1119 tcp_connection,
1120 })
1121 })
1122 }
1123
1124 fn handle_run_in_terminal(
1125 &self,
1126 request: &RunInTerminalRequestArguments,
1127 mut sender: mpsc::Sender<Result<u32>>,
1128 window: &mut Window,
1129 cx: &mut Context<Self>,
1130 ) -> Task<Result<()>> {
1131 let running = cx.entity();
1132 let Ok(project) = self
1133 .workspace
1134 .read_with(cx, |workspace, _| workspace.project().clone())
1135 else {
1136 return Task::ready(Err(anyhow!("no workspace")));
1137 };
1138 let session = self.session.read(cx);
1139
1140 let cwd = (!request.cwd.is_empty())
1141 .then(|| PathBuf::from(&request.cwd))
1142 .or_else(|| session.binary().unwrap().cwd.clone());
1143
1144 let mut envs: HashMap<String, String> =
1145 self.session.read(cx).task_context().project_env.clone();
1146 if let Some(Value::Object(env)) = &request.env {
1147 for (key, value) in env {
1148 let value_str = match (key.as_str(), value) {
1149 (_, Value::String(value)) => value,
1150 _ => continue,
1151 };
1152
1153 envs.insert(key.clone(), value_str.clone());
1154 }
1155 }
1156
1157 let mut args = request.args.clone();
1158 let command = if envs.contains_key("VSCODE_INSPECTOR_OPTIONS") {
1159 // Handle special case for NodeJS debug adapter
1160 // If the Node binary path is provided (possibly with arguments like --experimental-network-inspection),
1161 // we set the command to None
1162 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1163 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1164 // This allows the NodeJS debug client to attach correctly
1165 if args
1166 .iter()
1167 .filter(|arg| !arg.starts_with("--"))
1168 .collect::<Vec<_>>()
1169 .len()
1170 > 1
1171 {
1172 Some(args.remove(0))
1173 } else {
1174 None
1175 }
1176 } else if !args.is_empty() {
1177 Some(args.remove(0))
1178 } else {
1179 None
1180 };
1181
1182 let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1183 let title = request
1184 .title
1185 .clone()
1186 .filter(|title| !title.is_empty())
1187 .or_else(|| command.clone())
1188 .unwrap_or_else(|| "Debug terminal".to_string());
1189 let kind = task::SpawnInTerminal {
1190 id: task::TaskId("debug".to_string()),
1191 full_label: title.clone(),
1192 label: title.clone(),
1193 command,
1194 args,
1195 command_label: title,
1196 cwd,
1197 env: envs,
1198 use_new_terminal: true,
1199 allow_concurrent_runs: true,
1200 reveal: task::RevealStrategy::NoFocus,
1201 reveal_target: task::RevealTarget::Dock,
1202 hide: task::HideStrategy::Never,
1203 shell,
1204 show_summary: false,
1205 show_command: false,
1206 show_rerun: false,
1207 };
1208
1209 let workspace = self.workspace.clone();
1210 let weak_project = project.downgrade();
1211
1212 let terminal_task =
1213 project.update(cx, |project, cx| project.create_terminal_task(kind, cx));
1214 let terminal_task = cx.spawn_in(window, async move |_, cx| {
1215 let terminal = terminal_task.await?;
1216
1217 let terminal_view = cx.new_window_entity(|window, cx| {
1218 TerminalView::new(terminal.clone(), workspace, None, weak_project, window, cx)
1219 })?;
1220
1221 running.update_in(cx, |running, window, cx| {
1222 running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1223 running.debug_terminal.update(cx, |debug_terminal, cx| {
1224 debug_terminal.terminal = Some(terminal_view);
1225 cx.notify();
1226 });
1227 })?;
1228
1229 terminal.read_with(cx, |terminal, _| {
1230 terminal
1231 .pty_info
1232 .pid()
1233 .map(|pid| pid.as_u32())
1234 .context("Terminal was spawned but PID was not available")
1235 })?
1236 });
1237
1238 cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1239 }
1240
1241 fn create_sub_view(
1242 &self,
1243 item_kind: DebuggerPaneItem,
1244 _pane: &Entity<Pane>,
1245 cx: &mut Context<Self>,
1246 ) -> Box<dyn ItemHandle> {
1247 match item_kind {
1248 DebuggerPaneItem::Console => Box::new(SubView::console(self.console.clone(), cx)),
1249 DebuggerPaneItem::Variables => Box::new(SubView::new(
1250 self.variable_list.focus_handle(cx),
1251 self.variable_list.clone().into(),
1252 item_kind,
1253 cx,
1254 )),
1255 DebuggerPaneItem::BreakpointList => {
1256 Box::new(SubView::breakpoint_list(self.breakpoint_list.clone(), cx))
1257 }
1258 DebuggerPaneItem::Frames => Box::new(SubView::new(
1259 self.stack_frame_list.focus_handle(cx),
1260 self.stack_frame_list.clone().into(),
1261 item_kind,
1262 cx,
1263 )),
1264 DebuggerPaneItem::Modules => Box::new(SubView::new(
1265 self.module_list.focus_handle(cx),
1266 self.module_list.clone().into(),
1267 item_kind,
1268 cx,
1269 )),
1270 DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1271 self.loaded_sources_list.focus_handle(cx),
1272 self.loaded_sources_list.clone().into(),
1273 item_kind,
1274 cx,
1275 )),
1276 DebuggerPaneItem::Terminal => Box::new(SubView::new(
1277 self.debug_terminal.focus_handle(cx),
1278 self.debug_terminal.clone().into(),
1279 item_kind,
1280 cx,
1281 )),
1282 DebuggerPaneItem::MemoryView => Box::new(SubView::new(
1283 self.memory_view.focus_handle(cx),
1284 self.memory_view.clone().into(),
1285 item_kind,
1286 cx,
1287 )),
1288 }
1289 }
1290
1291 pub(crate) fn ensure_pane_item(
1292 &mut self,
1293 item_kind: DebuggerPaneItem,
1294 window: &mut Window,
1295 cx: &mut Context<Self>,
1296 ) {
1297 if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1298 return;
1299 };
1300 let pane = self.panes.last_pane();
1301 let sub_view = self.create_sub_view(item_kind, &pane, cx);
1302
1303 pane.update(cx, |pane, cx| {
1304 pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1305 })
1306 }
1307
1308 pub(crate) fn add_pane_item(
1309 &mut self,
1310 item_kind: DebuggerPaneItem,
1311 position: Point<Pixels>,
1312 window: &mut Window,
1313 cx: &mut Context<Self>,
1314 ) {
1315 debug_assert!(
1316 item_kind.is_supported(self.session.read(cx).capabilities()),
1317 "We should only allow adding supported item kinds"
1318 );
1319
1320 if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1321 let sub_view = self.create_sub_view(item_kind, pane, cx);
1322
1323 pane.update(cx, |pane, cx| {
1324 pane.add_item(sub_view, false, false, None, window, cx);
1325 })
1326 }
1327 }
1328
1329 pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1330 let caps = self.session.read(cx).capabilities();
1331 let mut pane_item_status = IndexMap::from_iter(
1332 DebuggerPaneItem::all()
1333 .iter()
1334 .filter(|kind| kind.is_supported(caps))
1335 .map(|kind| (*kind, false)),
1336 );
1337 self.panes.panes().iter().for_each(|pane| {
1338 pane.read(cx)
1339 .items()
1340 .filter_map(|item| item.act_as::<SubView>(cx))
1341 .for_each(|view| {
1342 pane_item_status.insert(view.read(cx).kind, true);
1343 });
1344 });
1345
1346 pane_item_status
1347 }
1348
1349 pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1350 if self._schedule_serialize.is_none() {
1351 self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1352 cx.background_executor()
1353 .timer(Duration::from_millis(100))
1354 .await;
1355
1356 let Some((adapter_name, pane_layout)) = this
1357 .read_with(cx, |this, cx| {
1358 let adapter_name = this.session.read(cx).adapter();
1359 (
1360 adapter_name,
1361 persistence::build_serialized_layout(
1362 &this.panes.root,
1363 this.dock_axis,
1364 cx,
1365 ),
1366 )
1367 })
1368 .ok()
1369 else {
1370 return;
1371 };
1372
1373 persistence::serialize_pane_layout(adapter_name, pane_layout)
1374 .await
1375 .log_err();
1376
1377 this.update(cx, |this, _| {
1378 this._schedule_serialize.take();
1379 })
1380 .ok();
1381 }));
1382 }
1383 }
1384
1385 pub(crate) fn handle_pane_event(
1386 this: &mut RunningState,
1387 source_pane: &Entity<Pane>,
1388 event: &Event,
1389 window: &mut Window,
1390 cx: &mut Context<RunningState>,
1391 ) {
1392 this.serialize_layout(window, cx);
1393 match event {
1394 Event::Remove { .. } => {
1395 let _did_find_pane = this.panes.remove(source_pane).is_ok();
1396 debug_assert!(_did_find_pane);
1397 cx.notify();
1398 }
1399 Event::Focus => {
1400 this.active_pane = source_pane.clone();
1401 }
1402 _ => {}
1403 }
1404 }
1405
1406 pub(crate) fn activate_pane_in_direction(
1407 &mut self,
1408 direction: SplitDirection,
1409 window: &mut Window,
1410 cx: &mut Context<Self>,
1411 ) {
1412 let active_pane = self.active_pane.clone();
1413 if let Some(pane) = self
1414 .panes
1415 .find_pane_in_direction(&active_pane, direction, cx)
1416 {
1417 pane.update(cx, |pane, cx| {
1418 pane.focus_active_item(window, cx);
1419 })
1420 } else {
1421 self.workspace
1422 .update(cx, |workspace, cx| {
1423 workspace.activate_pane_in_direction(direction, window, cx)
1424 })
1425 .ok();
1426 }
1427 }
1428
1429 pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1430 if self.thread_id.is_some() {
1431 self.stack_frame_list
1432 .update(cx, |list, cx| {
1433 let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1434 return Task::ready(Ok(()));
1435 };
1436 list.go_to_stack_frame(stack_frame_id, window, cx)
1437 })
1438 .detach();
1439 }
1440 }
1441
1442 pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1443 self.variable_list.read(cx).has_open_context_menu()
1444 }
1445
1446 pub fn session(&self) -> &Entity<Session> {
1447 &self.session
1448 }
1449
1450 pub fn session_id(&self) -> SessionId {
1451 self.session_id
1452 }
1453
1454 pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1455 self.stack_frame_list.read(cx).opened_stack_frame_id()
1456 }
1457
1458 pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1459 &self.stack_frame_list
1460 }
1461
1462 #[cfg(test)]
1463 pub fn console(&self) -> &Entity<Console> {
1464 &self.console
1465 }
1466
1467 #[cfg(test)]
1468 pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1469 &self.module_list
1470 }
1471
1472 pub(crate) fn activate_item(
1473 &mut self,
1474 item: DebuggerPaneItem,
1475 window: &mut Window,
1476 cx: &mut Context<Self>,
1477 ) {
1478 self.ensure_pane_item(item, window, cx);
1479
1480 let (variable_list_position, pane) = self
1481 .panes
1482 .panes()
1483 .into_iter()
1484 .find_map(|pane| {
1485 pane.read(cx)
1486 .items_of_type::<SubView>()
1487 .position(|view| view.read(cx).view_kind() == item)
1488 .map(|view| (view, pane))
1489 })
1490 .unwrap();
1491
1492 pane.update(cx, |this, cx| {
1493 this.activate_item(variable_list_position, true, true, window, cx);
1494 });
1495 }
1496
1497 #[cfg(test)]
1498 pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1499 &self.variable_list
1500 }
1501
1502 #[cfg(test)]
1503 pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1504 persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1505 }
1506
1507 pub fn capabilities(&self, cx: &App) -> Capabilities {
1508 self.session().read(cx).capabilities().clone()
1509 }
1510
1511 pub fn select_current_thread(
1512 &mut self,
1513 threads: &Vec<(Thread, ThreadStatus)>,
1514 window: &mut Window,
1515 cx: &mut Context<Self>,
1516 ) {
1517 let selected_thread = self
1518 .thread_id
1519 .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1520 .or_else(|| threads.first());
1521
1522 let Some((selected_thread, _)) = selected_thread else {
1523 return;
1524 };
1525
1526 if Some(ThreadId(selected_thread.id)) != self.thread_id {
1527 self.select_thread(ThreadId(selected_thread.id), window, cx);
1528 }
1529 }
1530
1531 pub fn selected_thread_id(&self) -> Option<ThreadId> {
1532 self.thread_id
1533 }
1534
1535 pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1536 self.thread_id
1537 .map(|id| self.session().read(cx).thread_status(id))
1538 }
1539
1540 pub(crate) fn select_thread(
1541 &mut self,
1542 thread_id: ThreadId,
1543 window: &mut Window,
1544 cx: &mut Context<Self>,
1545 ) {
1546 if self.thread_id.is_some_and(|id| id == thread_id) {
1547 return;
1548 }
1549
1550 self.thread_id = Some(thread_id);
1551
1552 self.stack_frame_list
1553 .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1554 }
1555
1556 pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1557 let Some(thread_id) = self.thread_id else {
1558 return;
1559 };
1560
1561 self.session().update(cx, |state, cx| {
1562 state.continue_thread(thread_id, cx);
1563 });
1564 }
1565
1566 pub fn step_over(&mut self, cx: &mut Context<Self>) {
1567 let Some(thread_id) = self.thread_id else {
1568 return;
1569 };
1570
1571 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1572
1573 self.session().update(cx, |state, cx| {
1574 state.step_over(thread_id, granularity, cx);
1575 });
1576 }
1577
1578 pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1579 let Some(thread_id) = self.thread_id else {
1580 return;
1581 };
1582
1583 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1584
1585 self.session().update(cx, |state, cx| {
1586 state.step_in(thread_id, granularity, cx);
1587 });
1588 }
1589
1590 pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1591 let Some(thread_id) = self.thread_id else {
1592 return;
1593 };
1594
1595 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1596
1597 self.session().update(cx, |state, cx| {
1598 state.step_out(thread_id, granularity, cx);
1599 });
1600 }
1601
1602 pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1603 let Some(thread_id) = self.thread_id else {
1604 return;
1605 };
1606
1607 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1608
1609 self.session().update(cx, |state, cx| {
1610 state.step_back(thread_id, granularity, cx);
1611 });
1612 }
1613
1614 pub fn rerun_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1615 if let Some((scenario, context)) = self.scenario.take().zip(self.scenario_context.take())
1616 && scenario.build.is_some()
1617 {
1618 let DebugScenarioContext {
1619 task_context,
1620 active_buffer,
1621 worktree_id,
1622 } = context;
1623 let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
1624
1625 self.workspace
1626 .update(cx, |workspace, cx| {
1627 workspace.start_debug_session(
1628 scenario,
1629 task_context,
1630 active_buffer,
1631 worktree_id,
1632 window,
1633 cx,
1634 )
1635 })
1636 .ok();
1637 } else {
1638 self.restart_session(cx);
1639 }
1640 }
1641
1642 pub fn restart_session(&self, cx: &mut Context<Self>) {
1643 self.session().update(cx, |state, cx| {
1644 state.restart(None, cx);
1645 });
1646 }
1647
1648 pub fn pause_thread(&self, cx: &mut Context<Self>) {
1649 let Some(thread_id) = self.thread_id else {
1650 return;
1651 };
1652
1653 self.session().update(cx, |state, cx| {
1654 state.pause_thread(thread_id, cx);
1655 });
1656 }
1657
1658 pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1659 self.workspace
1660 .update(cx, |workspace, cx| {
1661 workspace
1662 .project()
1663 .read(cx)
1664 .breakpoint_store()
1665 .update(cx, |store, cx| {
1666 store.remove_active_position(Some(self.session_id), cx)
1667 })
1668 })
1669 .log_err();
1670
1671 let is_building = self.session.update(cx, |session, cx| {
1672 session.shutdown(cx).detach();
1673 matches!(session.mode, session::SessionState::Booting(_))
1674 });
1675
1676 if is_building {
1677 self.debug_terminal.update(cx, |terminal, cx| {
1678 if let Some(view) = terminal.terminal.as_ref() {
1679 view.update(cx, |view, cx| {
1680 view.terminal()
1681 .update(cx, |terminal, _| terminal.kill_active_task())
1682 })
1683 }
1684 })
1685 }
1686 }
1687
1688 pub fn stop_thread(&self, cx: &mut Context<Self>) {
1689 let Some(thread_id) = self.thread_id else {
1690 return;
1691 };
1692
1693 self.workspace
1694 .update(cx, |workspace, cx| {
1695 workspace
1696 .project()
1697 .read(cx)
1698 .breakpoint_store()
1699 .update(cx, |store, cx| {
1700 store.remove_active_position(Some(self.session_id), cx)
1701 })
1702 })
1703 .log_err();
1704
1705 self.session().update(cx, |state, cx| {
1706 state.terminate_threads(Some(vec![thread_id; 1]), cx);
1707 });
1708 }
1709
1710 pub fn detach_client(&self, cx: &mut Context<Self>) {
1711 self.session().update(cx, |state, cx| {
1712 state.disconnect_client(cx);
1713 });
1714 }
1715
1716 pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1717 self.session.update(cx, |session, cx| {
1718 session.toggle_ignore_breakpoints(cx).detach();
1719 });
1720 }
1721
1722 fn default_pane_layout(
1723 project: Entity<Project>,
1724 workspace: &WeakEntity<Workspace>,
1725 stack_frame_list: &Entity<StackFrameList>,
1726 variable_list: &Entity<VariableList>,
1727 console: &Entity<Console>,
1728 breakpoints: &Entity<BreakpointList>,
1729 debug_terminal: &Entity<DebugTerminal>,
1730 dock_axis: Axis,
1731 subscriptions: &mut HashMap<EntityId, Subscription>,
1732 window: &mut Window,
1733 cx: &mut Context<'_, RunningState>,
1734 ) -> Member {
1735 let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1736 leftmost_pane.update(cx, |this, cx| {
1737 this.add_item(
1738 Box::new(SubView::new(
1739 this.focus_handle(cx),
1740 stack_frame_list.clone().into(),
1741 DebuggerPaneItem::Frames,
1742 cx,
1743 )),
1744 true,
1745 false,
1746 None,
1747 window,
1748 cx,
1749 );
1750 this.add_item(
1751 Box::new(SubView::breakpoint_list(breakpoints.clone(), cx)),
1752 true,
1753 false,
1754 None,
1755 window,
1756 cx,
1757 );
1758 this.activate_item(0, false, false, window, cx);
1759 });
1760 let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1761
1762 center_pane.update(cx, |this, cx| {
1763 let view = SubView::console(console.clone(), cx);
1764
1765 this.add_item(Box::new(view), true, false, None, window, cx);
1766
1767 this.add_item(
1768 Box::new(SubView::new(
1769 variable_list.focus_handle(cx),
1770 variable_list.clone().into(),
1771 DebuggerPaneItem::Variables,
1772 cx,
1773 )),
1774 true,
1775 false,
1776 None,
1777 window,
1778 cx,
1779 );
1780 this.activate_item(0, false, false, window, cx);
1781 });
1782
1783 let rightmost_pane = new_debugger_pane(workspace.clone(), project, window, cx);
1784 rightmost_pane.update(cx, |this, cx| {
1785 this.add_item(
1786 Box::new(SubView::new(
1787 debug_terminal.focus_handle(cx),
1788 debug_terminal.clone().into(),
1789 DebuggerPaneItem::Terminal,
1790 cx,
1791 )),
1792 false,
1793 false,
1794 None,
1795 window,
1796 cx,
1797 );
1798 });
1799
1800 subscriptions.extend(
1801 [&leftmost_pane, ¢er_pane, &rightmost_pane]
1802 .into_iter()
1803 .map(|entity| {
1804 (
1805 entity.entity_id(),
1806 cx.subscribe_in(entity, window, Self::handle_pane_event),
1807 )
1808 }),
1809 );
1810
1811 let group_root = workspace::PaneAxis::new(
1812 dock_axis.invert(),
1813 [leftmost_pane, center_pane, rightmost_pane]
1814 .into_iter()
1815 .map(workspace::Member::Pane)
1816 .collect(),
1817 );
1818
1819 Member::Axis(group_root)
1820 }
1821
1822 pub(crate) fn invert_axies(&mut self) {
1823 self.dock_axis = self.dock_axis.invert();
1824 self.panes.invert_axies();
1825 }
1826}
1827
1828impl Focusable for RunningState {
1829 fn focus_handle(&self, _: &App) -> FocusHandle {
1830 self.focus_handle.clone()
1831 }
1832}