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