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