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