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