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