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 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(mut 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 if let Some(remote_shell) = remote_shell && task.resolved.shell == Shell::System {
1029 task.resolved.shell = Shell::Program(remote_shell);
1030 }
1031
1032 let builder = ShellBuilder::new(&task.resolved.shell);
1033 let command_label = builder.command_label(task.resolved.command.as_deref().unwrap_or(""));
1034 let (command, args) =
1035 builder.build(task.resolved.command.clone(), &task.resolved.args);
1036
1037 let task_with_shell = SpawnInTerminal {
1038 command_label,
1039 command: Some(command),
1040 args,
1041 ..task.resolved.clone()
1042 };
1043 let terminal = project
1044 .update(cx, |project, cx| {
1045 project.create_terminal_task(
1046 task_with_shell.clone(),
1047 cx,
1048 )
1049 })?.await?;
1050
1051 let terminal_view = cx.new_window_entity(|window, cx| {
1052 TerminalView::new(
1053 terminal.clone(),
1054 weak_workspace,
1055 None,
1056 weak_project,
1057 window,
1058 cx,
1059 )
1060 })?;
1061
1062 this.update_in(cx, |this, window, cx| {
1063 this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1064 this.debug_terminal.update(cx, |debug_terminal, cx| {
1065 debug_terminal.terminal = Some(terminal_view);
1066 cx.notify();
1067 });
1068 })?;
1069
1070 let exit_status = terminal
1071 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1072 .await
1073 .context("Failed to wait for completed task")?;
1074
1075 if !exit_status.success() {
1076 anyhow::bail!("Build failed");
1077 }
1078 Some((task.resolved.clone(), locator_name, extra_config))
1079 } else {
1080 None
1081 };
1082
1083 if config_is_valid {
1084 } else if let Some((task, locator_name, extra_config)) = build_output {
1085 let locator_name =
1086 locator_name.with_context(|| {
1087 format!("Could not find a valid locator for a build task and configure is invalid with error: {}", request_type.err()
1088 .map(|err| err.to_string())
1089 .unwrap_or_default())
1090 })?;
1091 let request = dap_store
1092 .update(cx, |this, cx| {
1093 this.run_debug_locator(&locator_name, task, cx)
1094 })?
1095 .await?;
1096
1097 let zed_config = ZedDebugConfig {
1098 label: label.clone(),
1099 adapter: adapter.clone(),
1100 request,
1101 stop_on_entry: None,
1102 };
1103
1104 let scenario = dap_registry
1105 .adapter(&adapter)
1106 .with_context(|| anyhow!("{}: is not a valid adapter name", &adapter))?.config_from_zed_format(zed_config)
1107 .await?;
1108 config = scenario.config;
1109 util::merge_non_null_json_value_into(extra_config, &mut config);
1110
1111 Self::substitute_variables_in_config(&mut config, &task_context);
1112 } else {
1113 let Err(e) = request_type else {
1114 unreachable!();
1115 };
1116 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}");
1117 };
1118
1119 Ok(DebugTaskDefinition {
1120 label,
1121 adapter: DebugAdapterName(adapter),
1122 config,
1123 tcp_connection,
1124 })
1125 })
1126 }
1127
1128 fn handle_run_in_terminal(
1129 &self,
1130 request: &RunInTerminalRequestArguments,
1131 mut sender: mpsc::Sender<Result<u32>>,
1132 window: &mut Window,
1133 cx: &mut Context<Self>,
1134 ) -> Task<Result<()>> {
1135 let running = cx.entity();
1136 let Ok(project) = self
1137 .workspace
1138 .read_with(cx, |workspace, _| workspace.project().clone())
1139 else {
1140 return Task::ready(Err(anyhow!("no workspace")));
1141 };
1142 let session = self.session.read(cx);
1143
1144 let cwd = (!request.cwd.is_empty())
1145 .then(|| PathBuf::from(&request.cwd))
1146 .or_else(|| session.binary().unwrap().cwd.clone());
1147
1148 let mut envs: HashMap<String, String> =
1149 self.session.read(cx).task_context().project_env.clone();
1150 if let Some(Value::Object(env)) = &request.env {
1151 for (key, value) in env {
1152 let value_str = match (key.as_str(), value) {
1153 (_, Value::String(value)) => value,
1154 _ => continue,
1155 };
1156
1157 envs.insert(key.clone(), value_str.clone());
1158 }
1159 }
1160
1161 let mut args = request.args.clone();
1162 let command = if envs.contains_key("VSCODE_INSPECTOR_OPTIONS") {
1163 // Handle special case for NodeJS debug adapter
1164 // If the Node binary path is provided (possibly with arguments like --experimental-network-inspection),
1165 // we set the command to None
1166 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1167 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1168 // This allows the NodeJS debug client to attach correctly
1169 if args
1170 .iter()
1171 .filter(|arg| !arg.starts_with("--"))
1172 .collect::<Vec<_>>()
1173 .len()
1174 > 1
1175 {
1176 Some(args.remove(0))
1177 } else {
1178 None
1179 }
1180 } else if !args.is_empty() {
1181 Some(args.remove(0))
1182 } else {
1183 None
1184 };
1185
1186 let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1187 let title = request
1188 .title
1189 .clone()
1190 .filter(|title| !title.is_empty())
1191 .or_else(|| command.clone())
1192 .unwrap_or_else(|| "Debug terminal".to_string());
1193 let kind = task::SpawnInTerminal {
1194 id: task::TaskId("debug".to_string()),
1195 full_label: title.clone(),
1196 label: title.clone(),
1197 command,
1198 args,
1199 command_label: title,
1200 cwd,
1201 env: envs,
1202 use_new_terminal: true,
1203 allow_concurrent_runs: true,
1204 reveal: task::RevealStrategy::NoFocus,
1205 reveal_target: task::RevealTarget::Dock,
1206 hide: task::HideStrategy::Never,
1207 shell,
1208 show_summary: false,
1209 show_command: false,
1210 show_rerun: false,
1211 };
1212
1213 let workspace = self.workspace.clone();
1214 let weak_project = project.downgrade();
1215
1216 let terminal_task =
1217 project.update(cx, |project, cx| project.create_terminal_task(kind, cx));
1218 let terminal_task = cx.spawn_in(window, async move |_, cx| {
1219 let terminal = terminal_task.await?;
1220
1221 let terminal_view = cx.new_window_entity(|window, cx| {
1222 TerminalView::new(terminal.clone(), workspace, None, weak_project, window, cx)
1223 })?;
1224
1225 running.update_in(cx, |running, window, cx| {
1226 running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1227 running.debug_terminal.update(cx, |debug_terminal, cx| {
1228 debug_terminal.terminal = Some(terminal_view);
1229 cx.notify();
1230 });
1231 })?;
1232
1233 terminal.read_with(cx, |terminal, _| {
1234 terminal
1235 .pid()
1236 .map(|pid| pid.as_u32())
1237 .context("Terminal was spawned but PID was not available")
1238 })?
1239 });
1240
1241 cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1242 }
1243
1244 fn create_sub_view(
1245 &self,
1246 item_kind: DebuggerPaneItem,
1247 _pane: &Entity<Pane>,
1248 cx: &mut Context<Self>,
1249 ) -> Box<dyn ItemHandle> {
1250 match item_kind {
1251 DebuggerPaneItem::Console => Box::new(SubView::console(self.console.clone(), cx)),
1252 DebuggerPaneItem::Variables => Box::new(SubView::new(
1253 self.variable_list.focus_handle(cx),
1254 self.variable_list.clone().into(),
1255 item_kind,
1256 cx,
1257 )),
1258 DebuggerPaneItem::BreakpointList => {
1259 Box::new(SubView::breakpoint_list(self.breakpoint_list.clone(), cx))
1260 }
1261 DebuggerPaneItem::Frames => Box::new(SubView::new(
1262 self.stack_frame_list.focus_handle(cx),
1263 self.stack_frame_list.clone().into(),
1264 item_kind,
1265 cx,
1266 )),
1267 DebuggerPaneItem::Modules => Box::new(SubView::new(
1268 self.module_list.focus_handle(cx),
1269 self.module_list.clone().into(),
1270 item_kind,
1271 cx,
1272 )),
1273 DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1274 self.loaded_sources_list.focus_handle(cx),
1275 self.loaded_sources_list.clone().into(),
1276 item_kind,
1277 cx,
1278 )),
1279 DebuggerPaneItem::Terminal => Box::new(SubView::new(
1280 self.debug_terminal.focus_handle(cx),
1281 self.debug_terminal.clone().into(),
1282 item_kind,
1283 cx,
1284 )),
1285 DebuggerPaneItem::MemoryView => Box::new(SubView::new(
1286 self.memory_view.focus_handle(cx),
1287 self.memory_view.clone().into(),
1288 item_kind,
1289 cx,
1290 )),
1291 }
1292 }
1293
1294 pub(crate) fn ensure_pane_item(
1295 &mut self,
1296 item_kind: DebuggerPaneItem,
1297 window: &mut Window,
1298 cx: &mut Context<Self>,
1299 ) {
1300 if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1301 return;
1302 };
1303 let pane = self.panes.last_pane();
1304 let sub_view = self.create_sub_view(item_kind, &pane, cx);
1305
1306 pane.update(cx, |pane, cx| {
1307 pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1308 })
1309 }
1310
1311 pub(crate) fn add_pane_item(
1312 &mut self,
1313 item_kind: DebuggerPaneItem,
1314 position: Point<Pixels>,
1315 window: &mut Window,
1316 cx: &mut Context<Self>,
1317 ) {
1318 debug_assert!(
1319 item_kind.is_supported(self.session.read(cx).capabilities()),
1320 "We should only allow adding supported item kinds"
1321 );
1322
1323 if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1324 let sub_view = self.create_sub_view(item_kind, pane, cx);
1325
1326 pane.update(cx, |pane, cx| {
1327 pane.add_item(sub_view, false, false, None, window, cx);
1328 })
1329 }
1330 }
1331
1332 pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1333 let caps = self.session.read(cx).capabilities();
1334 let mut pane_item_status = IndexMap::from_iter(
1335 DebuggerPaneItem::all()
1336 .iter()
1337 .filter(|kind| kind.is_supported(caps))
1338 .map(|kind| (*kind, false)),
1339 );
1340 self.panes.panes().iter().for_each(|pane| {
1341 pane.read(cx)
1342 .items()
1343 .filter_map(|item| item.act_as::<SubView>(cx))
1344 .for_each(|view| {
1345 pane_item_status.insert(view.read(cx).kind, true);
1346 });
1347 });
1348
1349 pane_item_status
1350 }
1351
1352 pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1353 if self._schedule_serialize.is_none() {
1354 self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1355 cx.background_executor()
1356 .timer(Duration::from_millis(100))
1357 .await;
1358
1359 let Some((adapter_name, pane_layout)) = this
1360 .read_with(cx, |this, cx| {
1361 let adapter_name = this.session.read(cx).adapter();
1362 (
1363 adapter_name,
1364 persistence::build_serialized_layout(
1365 &this.panes.root,
1366 this.dock_axis,
1367 cx,
1368 ),
1369 )
1370 })
1371 .ok()
1372 else {
1373 return;
1374 };
1375
1376 persistence::serialize_pane_layout(adapter_name, pane_layout)
1377 .await
1378 .log_err();
1379
1380 this.update(cx, |this, _| {
1381 this._schedule_serialize.take();
1382 })
1383 .ok();
1384 }));
1385 }
1386 }
1387
1388 pub(crate) fn handle_pane_event(
1389 this: &mut RunningState,
1390 source_pane: &Entity<Pane>,
1391 event: &Event,
1392 window: &mut Window,
1393 cx: &mut Context<RunningState>,
1394 ) {
1395 this.serialize_layout(window, cx);
1396 match event {
1397 Event::Remove { .. } => {
1398 let _did_find_pane = this.panes.remove(source_pane).is_ok();
1399 debug_assert!(_did_find_pane);
1400 cx.notify();
1401 }
1402 Event::Focus => {
1403 this.active_pane = source_pane.clone();
1404 }
1405 _ => {}
1406 }
1407 }
1408
1409 pub(crate) fn activate_pane_in_direction(
1410 &mut self,
1411 direction: SplitDirection,
1412 window: &mut Window,
1413 cx: &mut Context<Self>,
1414 ) {
1415 let active_pane = self.active_pane.clone();
1416 if let Some(pane) = self
1417 .panes
1418 .find_pane_in_direction(&active_pane, direction, cx)
1419 {
1420 pane.update(cx, |pane, cx| {
1421 pane.focus_active_item(window, cx);
1422 })
1423 } else {
1424 self.workspace
1425 .update(cx, |workspace, cx| {
1426 workspace.activate_pane_in_direction(direction, window, cx)
1427 })
1428 .ok();
1429 }
1430 }
1431
1432 pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1433 if self.thread_id.is_some() {
1434 self.stack_frame_list
1435 .update(cx, |list, cx| {
1436 let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1437 return Task::ready(Ok(()));
1438 };
1439 list.go_to_stack_frame(stack_frame_id, window, cx)
1440 })
1441 .detach();
1442 }
1443 }
1444
1445 pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1446 self.variable_list.read(cx).has_open_context_menu()
1447 }
1448
1449 pub fn session(&self) -> &Entity<Session> {
1450 &self.session
1451 }
1452
1453 pub fn session_id(&self) -> SessionId {
1454 self.session_id
1455 }
1456
1457 pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1458 self.stack_frame_list.read(cx).opened_stack_frame_id()
1459 }
1460
1461 pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1462 &self.stack_frame_list
1463 }
1464
1465 #[cfg(test)]
1466 pub fn console(&self) -> &Entity<Console> {
1467 &self.console
1468 }
1469
1470 #[cfg(test)]
1471 pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1472 &self.module_list
1473 }
1474
1475 pub(crate) fn activate_item(
1476 &mut self,
1477 item: DebuggerPaneItem,
1478 window: &mut Window,
1479 cx: &mut Context<Self>,
1480 ) {
1481 self.ensure_pane_item(item, window, cx);
1482
1483 let (variable_list_position, pane) = self
1484 .panes
1485 .panes()
1486 .into_iter()
1487 .find_map(|pane| {
1488 pane.read(cx)
1489 .items_of_type::<SubView>()
1490 .position(|view| view.read(cx).view_kind() == item)
1491 .map(|view| (view, pane))
1492 })
1493 .unwrap();
1494
1495 pane.update(cx, |this, cx| {
1496 this.activate_item(variable_list_position, true, true, window, cx);
1497 });
1498 }
1499
1500 #[cfg(test)]
1501 pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1502 &self.variable_list
1503 }
1504
1505 #[cfg(test)]
1506 pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1507 persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1508 }
1509
1510 pub fn capabilities(&self, cx: &App) -> Capabilities {
1511 self.session().read(cx).capabilities().clone()
1512 }
1513
1514 pub fn select_current_thread(
1515 &mut self,
1516 threads: &Vec<(Thread, ThreadStatus)>,
1517 window: &mut Window,
1518 cx: &mut Context<Self>,
1519 ) {
1520 let selected_thread = self
1521 .thread_id
1522 .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1523 .or_else(|| threads.first());
1524
1525 let Some((selected_thread, _)) = selected_thread else {
1526 return;
1527 };
1528
1529 if Some(ThreadId(selected_thread.id)) != self.thread_id {
1530 self.select_thread(ThreadId(selected_thread.id), window, cx);
1531 }
1532 }
1533
1534 pub fn selected_thread_id(&self) -> Option<ThreadId> {
1535 self.thread_id
1536 }
1537
1538 pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1539 self.thread_id
1540 .map(|id| self.session().read(cx).thread_status(id))
1541 }
1542
1543 pub(crate) fn select_thread(
1544 &mut self,
1545 thread_id: ThreadId,
1546 window: &mut Window,
1547 cx: &mut Context<Self>,
1548 ) {
1549 if self.thread_id.is_some_and(|id| id == thread_id) {
1550 return;
1551 }
1552
1553 self.thread_id = Some(thread_id);
1554
1555 self.stack_frame_list
1556 .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1557 }
1558
1559 pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1560 let Some(thread_id) = self.thread_id else {
1561 return;
1562 };
1563
1564 self.session().update(cx, |state, cx| {
1565 state.continue_thread(thread_id, cx);
1566 });
1567 }
1568
1569 pub fn step_over(&mut self, cx: &mut Context<Self>) {
1570 let Some(thread_id) = self.thread_id else {
1571 return;
1572 };
1573
1574 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1575
1576 self.session().update(cx, |state, cx| {
1577 state.step_over(thread_id, granularity, cx);
1578 });
1579 }
1580
1581 pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1582 let Some(thread_id) = self.thread_id else {
1583 return;
1584 };
1585
1586 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1587
1588 self.session().update(cx, |state, cx| {
1589 state.step_in(thread_id, granularity, cx);
1590 });
1591 }
1592
1593 pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1594 let Some(thread_id) = self.thread_id else {
1595 return;
1596 };
1597
1598 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1599
1600 self.session().update(cx, |state, cx| {
1601 state.step_out(thread_id, granularity, cx);
1602 });
1603 }
1604
1605 pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1606 let Some(thread_id) = self.thread_id else {
1607 return;
1608 };
1609
1610 let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1611
1612 self.session().update(cx, |state, cx| {
1613 state.step_back(thread_id, granularity, cx);
1614 });
1615 }
1616
1617 pub fn rerun_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1618 if let Some((scenario, context)) = self.scenario.take().zip(self.scenario_context.take())
1619 && scenario.build.is_some()
1620 {
1621 let DebugScenarioContext {
1622 task_context,
1623 active_buffer,
1624 worktree_id,
1625 } = context;
1626 let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
1627
1628 self.workspace
1629 .update(cx, |workspace, cx| {
1630 workspace.start_debug_session(
1631 scenario,
1632 task_context,
1633 active_buffer,
1634 worktree_id,
1635 window,
1636 cx,
1637 )
1638 })
1639 .ok();
1640 } else {
1641 self.restart_session(cx);
1642 }
1643 }
1644
1645 pub fn restart_session(&self, cx: &mut Context<Self>) {
1646 self.session().update(cx, |state, cx| {
1647 state.restart(None, cx);
1648 });
1649 }
1650
1651 pub fn pause_thread(&self, cx: &mut Context<Self>) {
1652 let Some(thread_id) = self.thread_id else {
1653 return;
1654 };
1655
1656 self.session().update(cx, |state, cx| {
1657 state.pause_thread(thread_id, cx);
1658 });
1659 }
1660
1661 pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1662 self.workspace
1663 .update(cx, |workspace, cx| {
1664 workspace
1665 .project()
1666 .read(cx)
1667 .breakpoint_store()
1668 .update(cx, |store, cx| {
1669 store.remove_active_position(Some(self.session_id), cx)
1670 })
1671 })
1672 .log_err();
1673
1674 let is_building = self.session.update(cx, |session, cx| {
1675 session.shutdown(cx).detach();
1676 matches!(session.mode, session::SessionState::Booting(_))
1677 });
1678
1679 if is_building {
1680 self.debug_terminal.update(cx, |terminal, cx| {
1681 if let Some(view) = terminal.terminal.as_ref() {
1682 view.update(cx, |view, cx| {
1683 view.terminal()
1684 .update(cx, |terminal, _| terminal.kill_active_task())
1685 })
1686 }
1687 })
1688 }
1689 }
1690
1691 pub fn stop_thread(&self, cx: &mut Context<Self>) {
1692 let Some(thread_id) = self.thread_id else {
1693 return;
1694 };
1695
1696 self.workspace
1697 .update(cx, |workspace, cx| {
1698 workspace
1699 .project()
1700 .read(cx)
1701 .breakpoint_store()
1702 .update(cx, |store, cx| {
1703 store.remove_active_position(Some(self.session_id), cx)
1704 })
1705 })
1706 .log_err();
1707
1708 self.session().update(cx, |state, cx| {
1709 state.terminate_threads(Some(vec![thread_id; 1]), cx);
1710 });
1711 }
1712
1713 pub fn detach_client(&self, cx: &mut Context<Self>) {
1714 self.session().update(cx, |state, cx| {
1715 state.disconnect_client(cx);
1716 });
1717 }
1718
1719 pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1720 self.session.update(cx, |session, cx| {
1721 session.toggle_ignore_breakpoints(cx).detach();
1722 });
1723 }
1724
1725 fn default_pane_layout(
1726 project: Entity<Project>,
1727 workspace: &WeakEntity<Workspace>,
1728 stack_frame_list: &Entity<StackFrameList>,
1729 variable_list: &Entity<VariableList>,
1730 console: &Entity<Console>,
1731 breakpoints: &Entity<BreakpointList>,
1732 debug_terminal: &Entity<DebugTerminal>,
1733 dock_axis: Axis,
1734 subscriptions: &mut HashMap<EntityId, Subscription>,
1735 window: &mut Window,
1736 cx: &mut Context<'_, RunningState>,
1737 ) -> Member {
1738 let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1739 leftmost_pane.update(cx, |this, cx| {
1740 this.add_item(
1741 Box::new(SubView::new(
1742 this.focus_handle(cx),
1743 stack_frame_list.clone().into(),
1744 DebuggerPaneItem::Frames,
1745 cx,
1746 )),
1747 true,
1748 false,
1749 None,
1750 window,
1751 cx,
1752 );
1753 this.add_item(
1754 Box::new(SubView::breakpoint_list(breakpoints.clone(), cx)),
1755 true,
1756 false,
1757 None,
1758 window,
1759 cx,
1760 );
1761 this.activate_item(0, false, false, window, cx);
1762 });
1763 let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1764
1765 center_pane.update(cx, |this, cx| {
1766 let view = SubView::console(console.clone(), cx);
1767
1768 this.add_item(Box::new(view), true, false, None, window, cx);
1769
1770 this.add_item(
1771 Box::new(SubView::new(
1772 variable_list.focus_handle(cx),
1773 variable_list.clone().into(),
1774 DebuggerPaneItem::Variables,
1775 cx,
1776 )),
1777 true,
1778 false,
1779 None,
1780 window,
1781 cx,
1782 );
1783 this.activate_item(0, false, false, window, cx);
1784 });
1785
1786 let rightmost_pane = new_debugger_pane(workspace.clone(), project, window, cx);
1787 rightmost_pane.update(cx, |this, cx| {
1788 this.add_item(
1789 Box::new(SubView::new(
1790 debug_terminal.focus_handle(cx),
1791 debug_terminal.clone().into(),
1792 DebuggerPaneItem::Terminal,
1793 cx,
1794 )),
1795 false,
1796 false,
1797 None,
1798 window,
1799 cx,
1800 );
1801 });
1802
1803 subscriptions.extend(
1804 [&leftmost_pane, ¢er_pane, &rightmost_pane]
1805 .into_iter()
1806 .map(|entity| {
1807 (
1808 entity.entity_id(),
1809 cx.subscribe_in(entity, window, Self::handle_pane_event),
1810 )
1811 }),
1812 );
1813
1814 let group_root = workspace::PaneAxis::new(
1815 dock_axis.invert(),
1816 [leftmost_pane, center_pane, rightmost_pane]
1817 .into_iter()
1818 .map(workspace::Member::Pane)
1819 .collect(),
1820 );
1821
1822 Member::Axis(group_root)
1823 }
1824
1825 pub(crate) fn invert_axies(&mut self) {
1826 self.dock_axis = self.dock_axis.invert();
1827 self.panes.invert_axies();
1828 }
1829}
1830
1831impl Focusable for RunningState {
1832 fn focus_handle(&self, _: &App) -> FocusHandle {
1833 self.focus_handle.clone()
1834 }
1835}