running.rs

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