running.rs

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