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