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