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