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: 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) -> &Entity<Pane> {
  89        &self.active_pane
  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        let active_pane = panes.first_pane();
 707
 708        Self {
 709            session,
 710            workspace,
 711            focus_handle,
 712            variable_list,
 713            _subscriptions,
 714            thread_id: None,
 715            _remote_id: None,
 716            stack_frame_list,
 717            session_id,
 718            panes,
 719            active_pane,
 720            module_list,
 721            console,
 722            breakpoint_list,
 723            loaded_sources_list: loaded_source_list,
 724            pane_close_subscriptions,
 725            debug_terminal,
 726            dock_axis,
 727            _schedule_serialize: None,
 728        }
 729    }
 730
 731    pub(crate) fn remove_pane_item(
 732        &mut self,
 733        item_kind: DebuggerPaneItem,
 734        window: &mut Window,
 735        cx: &mut Context<Self>,
 736    ) {
 737        if let Some((pane, item_id)) = self.panes.panes().iter().find_map(|pane| {
 738            Some(pane).zip(
 739                pane.read(cx)
 740                    .items()
 741                    .find(|item| {
 742                        item.act_as::<SubView>(cx)
 743                            .is_some_and(|view| view.read(cx).kind == item_kind)
 744                    })
 745                    .map(|item| item.item_id()),
 746            )
 747        }) {
 748            pane.update(cx, |pane, cx| {
 749                pane.remove_item(item_id, false, true, window, cx)
 750            })
 751        }
 752    }
 753
 754    pub(crate) fn has_pane_at_position(&self, position: Point<Pixels>) -> bool {
 755        self.panes.pane_at_pixel_position(position).is_some()
 756    }
 757
 758    pub(crate) fn resolve_scenario(
 759        &self,
 760        scenario: DebugScenario,
 761        task_context: TaskContext,
 762        buffer: Option<Entity<Buffer>>,
 763        worktree_id: Option<WorktreeId>,
 764        window: &Window,
 765        cx: &mut Context<Self>,
 766    ) -> Task<Result<DebugTaskDefinition>> {
 767        let Some(workspace) = self.workspace.upgrade() else {
 768            return Task::ready(Err(anyhow!("no workspace")));
 769        };
 770        let project = workspace.read(cx).project().clone();
 771        let dap_store = project.read(cx).dap_store().downgrade();
 772        let dap_registry = cx.global::<DapRegistry>().clone();
 773        let task_store = project.read(cx).task_store().downgrade();
 774        let weak_project = project.downgrade();
 775        let weak_workspace = workspace.downgrade();
 776        let is_local = project.read(cx).is_local();
 777        cx.spawn_in(window, async move |this, cx| {
 778            let DebugScenario {
 779                adapter,
 780                label,
 781                build,
 782                mut config,
 783                tcp_connection,
 784            } = scenario;
 785            Self::relativlize_paths(None, &mut config, &task_context);
 786            Self::substitute_variables_in_config(&mut config, &task_context);
 787
 788            let request_type = dap_registry
 789                .adapter(&adapter)
 790                .ok_or_else(|| anyhow!("{}: is not a valid adapter name", &adapter))
 791                .and_then(|adapter| adapter.validate_config(&config));
 792
 793            let config_is_valid = request_type.is_ok();
 794
 795            let build_output = if let Some(build) = build {
 796                let (task, locator_name) = match build {
 797                    BuildTaskDefinition::Template {
 798                        task_template,
 799                        locator_name,
 800                    } => (task_template, locator_name),
 801                    BuildTaskDefinition::ByName(ref label) => {
 802                        let Some(task) = task_store.update(cx, |this, cx| {
 803                            this.task_inventory().and_then(|inventory| {
 804                                inventory.read(cx).task_template_by_label(
 805                                    buffer,
 806                                    worktree_id,
 807                                    &label,
 808                                    cx,
 809                                )
 810                            })
 811                        })?
 812                        else {
 813                            anyhow::bail!("Couldn't find task template for {:?}", build)
 814                        };
 815                        (task, None)
 816                    }
 817                };
 818                let Some(task) = task.resolve_task("debug-build-task", &task_context) else {
 819                    anyhow::bail!("Could not resolve task variables within a debug scenario");
 820                };
 821
 822                let locator_name = if let Some(locator_name) = locator_name {
 823                    debug_assert!(!config_is_valid);
 824                    Some(locator_name)
 825                } else if !config_is_valid {
 826                    dap_store
 827                        .update(cx, |this, cx| {
 828                            this.debug_scenario_for_build_task(
 829                                task.original_task().clone(),
 830                                adapter.clone().into(),
 831                                task.display_label().to_owned().into(),
 832                                cx,
 833                            )
 834                            .and_then(|scenario| {
 835                                match scenario.build {
 836                                    Some(BuildTaskDefinition::Template {
 837                                        locator_name, ..
 838                                    }) => locator_name,
 839                                    _ => None,
 840                                }
 841                            })
 842                        })
 843                        .ok()
 844                        .flatten()
 845                } else {
 846                    None
 847                };
 848
 849                let builder = ShellBuilder::new(is_local, &task.resolved.shell);
 850                let command_label = builder.command_label(&task.resolved.command_label);
 851                let (command, args) =
 852                    builder.build(task.resolved.command.clone(), &task.resolved.args);
 853
 854                let task_with_shell = SpawnInTerminal {
 855                    command_label,
 856                    command,
 857                    args,
 858                    ..task.resolved.clone()
 859                };
 860                let terminal = project
 861                    .update_in(cx, |project, window, cx| {
 862                        project.create_terminal(
 863                            TerminalKind::Task(task_with_shell.clone()),
 864                            window.window_handle(),
 865                            cx,
 866                        )
 867                    })?
 868                    .await?;
 869
 870                let terminal_view = cx.new_window_entity(|window, cx| {
 871                    TerminalView::new(
 872                        terminal.clone(),
 873                        weak_workspace,
 874                        None,
 875                        weak_project,
 876                        false,
 877                        window,
 878                        cx,
 879                    )
 880                })?;
 881
 882                this.update_in(cx, |this, window, cx| {
 883                    this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
 884                    this.debug_terminal.update(cx, |debug_terminal, cx| {
 885                        debug_terminal.terminal = Some(terminal_view);
 886                        cx.notify();
 887                    });
 888                })?;
 889
 890                let exit_status = terminal
 891                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
 892                    .await
 893                    .context("Failed to wait for completed task")?;
 894
 895                if !exit_status.success() {
 896                    anyhow::bail!("Build failed");
 897                }
 898                Some((task.resolved.clone(), locator_name))
 899            } else {
 900                None
 901            };
 902
 903            if config_is_valid {
 904                // Ok(DebugTaskDefinition {
 905                //     label,
 906                //     adapter: DebugAdapterName(adapter),
 907                //     config,
 908                //     tcp_connection,
 909                // })
 910            } else if let Some((task, locator_name)) = build_output {
 911                let locator_name =
 912                    locator_name.context("Could not find a valid locator for a build task")?;
 913                let request = dap_store
 914                    .update(cx, |this, cx| {
 915                        this.run_debug_locator(&locator_name, task, cx)
 916                    })?
 917                    .await?;
 918
 919                let zed_config = ZedDebugConfig {
 920                    label: label.clone(),
 921                    adapter: adapter.clone(),
 922                    request,
 923                    stop_on_entry: None,
 924                };
 925
 926                let scenario = dap_registry
 927                    .adapter(&adapter)
 928                    .ok_or_else(|| anyhow!("{}: is not a valid adapter name", &adapter))
 929                    .map(|adapter| adapter.config_from_zed_format(zed_config))??;
 930                config = scenario.config;
 931                Self::substitute_variables_in_config(&mut config, &task_context);
 932            } else {
 933                anyhow::bail!("No request or build provided");
 934            };
 935
 936            Ok(DebugTaskDefinition {
 937                label,
 938                adapter: DebugAdapterName(adapter),
 939                config,
 940                tcp_connection,
 941            })
 942        })
 943    }
 944
 945    fn handle_run_in_terminal(
 946        &self,
 947        request: &RunInTerminalRequestArguments,
 948        mut sender: mpsc::Sender<Result<u32>>,
 949        window: &mut Window,
 950        cx: &mut Context<Self>,
 951    ) -> Task<Result<()>> {
 952        let running = cx.entity();
 953        let Ok(project) = self
 954            .workspace
 955            .update(cx, |workspace, _| workspace.project().clone())
 956        else {
 957            return Task::ready(Err(anyhow!("no workspace")));
 958        };
 959        let session = self.session.read(cx);
 960
 961        let cwd = Some(&request.cwd)
 962            .filter(|cwd| cwd.len() > 0)
 963            .map(PathBuf::from)
 964            .or_else(|| session.binary().cwd.clone());
 965
 966        let mut args = request.args.clone();
 967
 968        // Handle special case for NodeJS debug adapter
 969        // If only the Node binary path is provided, we set the command to None
 970        // This prevents the NodeJS REPL from appearing, which is not the desired behavior
 971        // The expected usage is for users to provide their own Node command, e.g., `node test.js`
 972        // This allows the NodeJS debug client to attach correctly
 973        let command = if args.len() > 1 {
 974            Some(args.remove(0))
 975        } else {
 976            None
 977        };
 978
 979        let mut envs: HashMap<String, String> = Default::default();
 980        if let Some(Value::Object(env)) = &request.env {
 981            for (key, value) in env {
 982                let value_str = match (key.as_str(), value) {
 983                    (_, Value::String(value)) => value,
 984                    _ => continue,
 985                };
 986
 987                envs.insert(key.clone(), value_str.clone());
 988            }
 989        }
 990
 991        let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
 992        let kind = if let Some(command) = command {
 993            let title = request.title.clone().unwrap_or(command.clone());
 994            TerminalKind::Task(task::SpawnInTerminal {
 995                id: task::TaskId("debug".to_string()),
 996                full_label: title.clone(),
 997                label: title.clone(),
 998                command: command.clone(),
 999                args,
1000                command_label: title.clone(),
1001                cwd,
1002                env: envs,
1003                use_new_terminal: true,
1004                allow_concurrent_runs: true,
1005                reveal: task::RevealStrategy::NoFocus,
1006                reveal_target: task::RevealTarget::Dock,
1007                hide: task::HideStrategy::Never,
1008                shell,
1009                show_summary: false,
1010                show_command: false,
1011                show_rerun: false,
1012            })
1013        } else {
1014            TerminalKind::Shell(cwd.map(|c| c.to_path_buf()))
1015        };
1016
1017        let workspace = self.workspace.clone();
1018        let weak_project = project.downgrade();
1019
1020        let terminal_task = project.update(cx, |project, cx| {
1021            project.create_terminal(kind, window.window_handle(), cx)
1022        });
1023        let terminal_task = cx.spawn_in(window, async move |_, cx| {
1024            let terminal = terminal_task.await?;
1025
1026            let terminal_view = cx.new_window_entity(|window, cx| {
1027                TerminalView::new(
1028                    terminal.clone(),
1029                    workspace,
1030                    None,
1031                    weak_project,
1032                    false,
1033                    window,
1034                    cx,
1035                )
1036            })?;
1037
1038            running.update_in(cx, |running, window, cx| {
1039                running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1040                running.debug_terminal.update(cx, |debug_terminal, cx| {
1041                    debug_terminal.terminal = Some(terminal_view);
1042                    cx.notify();
1043                });
1044            })?;
1045
1046            terminal.read_with(cx, |terminal, _| {
1047                terminal
1048                    .pty_info
1049                    .pid()
1050                    .map(|pid| pid.as_u32())
1051                    .context("Terminal was spawned but PID was not available")
1052            })?
1053        });
1054
1055        cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1056    }
1057
1058    fn create_sub_view(
1059        &self,
1060        item_kind: DebuggerPaneItem,
1061        _pane: &Entity<Pane>,
1062        cx: &mut Context<Self>,
1063    ) -> Box<dyn ItemHandle> {
1064        match item_kind {
1065            DebuggerPaneItem::Console => {
1066                let weak_console = self.console.clone().downgrade();
1067
1068                Box::new(SubView::new(
1069                    self.console.focus_handle(cx),
1070                    self.console.clone().into(),
1071                    item_kind,
1072                    Some(Box::new(move |cx| {
1073                        weak_console
1074                            .read_with(cx, |console, cx| console.show_indicator(cx))
1075                            .unwrap_or_default()
1076                    })),
1077                    cx,
1078                ))
1079            }
1080            DebuggerPaneItem::Variables => Box::new(SubView::new(
1081                self.variable_list.focus_handle(cx),
1082                self.variable_list.clone().into(),
1083                item_kind,
1084                None,
1085                cx,
1086            )),
1087            DebuggerPaneItem::BreakpointList => Box::new(SubView::new(
1088                self.breakpoint_list.focus_handle(cx),
1089                self.breakpoint_list.clone().into(),
1090                item_kind,
1091                None,
1092                cx,
1093            )),
1094            DebuggerPaneItem::Frames => Box::new(SubView::new(
1095                self.stack_frame_list.focus_handle(cx),
1096                self.stack_frame_list.clone().into(),
1097                item_kind,
1098                None,
1099                cx,
1100            )),
1101            DebuggerPaneItem::Modules => Box::new(SubView::new(
1102                self.module_list.focus_handle(cx),
1103                self.module_list.clone().into(),
1104                item_kind,
1105                None,
1106                cx,
1107            )),
1108            DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1109                self.loaded_sources_list.focus_handle(cx),
1110                self.loaded_sources_list.clone().into(),
1111                item_kind,
1112                None,
1113                cx,
1114            )),
1115            DebuggerPaneItem::Terminal => Box::new(SubView::new(
1116                self.debug_terminal.focus_handle(cx),
1117                self.debug_terminal.clone().into(),
1118                item_kind,
1119                None,
1120                cx,
1121            )),
1122        }
1123    }
1124
1125    pub(crate) fn ensure_pane_item(
1126        &mut self,
1127        item_kind: DebuggerPaneItem,
1128        window: &mut Window,
1129        cx: &mut Context<Self>,
1130    ) {
1131        if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1132            return;
1133        };
1134        let pane = self.panes.last_pane();
1135        let sub_view = self.create_sub_view(item_kind, &pane, cx);
1136
1137        pane.update(cx, |pane, cx| {
1138            pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1139        })
1140    }
1141
1142    pub(crate) fn add_pane_item(
1143        &mut self,
1144        item_kind: DebuggerPaneItem,
1145        position: Point<Pixels>,
1146        window: &mut Window,
1147        cx: &mut Context<Self>,
1148    ) {
1149        debug_assert!(
1150            item_kind.is_supported(self.session.read(cx).capabilities()),
1151            "We should only allow adding supported item kinds"
1152        );
1153
1154        if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1155            let sub_view = self.create_sub_view(item_kind, pane, cx);
1156
1157            pane.update(cx, |pane, cx| {
1158                pane.add_item(sub_view, false, false, None, window, cx);
1159            })
1160        }
1161    }
1162
1163    pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1164        let caps = self.session.read(cx).capabilities();
1165        let mut pane_item_status = IndexMap::from_iter(
1166            DebuggerPaneItem::all()
1167                .iter()
1168                .filter(|kind| kind.is_supported(&caps))
1169                .map(|kind| (*kind, false)),
1170        );
1171        self.panes.panes().iter().for_each(|pane| {
1172            pane.read(cx)
1173                .items()
1174                .filter_map(|item| item.act_as::<SubView>(cx))
1175                .for_each(|view| {
1176                    pane_item_status.insert(view.read(cx).kind, true);
1177                });
1178        });
1179
1180        pane_item_status
1181    }
1182
1183    pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1184        if self._schedule_serialize.is_none() {
1185            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1186                cx.background_executor()
1187                    .timer(Duration::from_millis(100))
1188                    .await;
1189
1190                let Some((adapter_name, pane_layout)) = this
1191                    .read_with(cx, |this, cx| {
1192                        let adapter_name = this.session.read(cx).adapter();
1193                        (
1194                            adapter_name,
1195                            persistence::build_serialized_layout(
1196                                &this.panes.root,
1197                                this.dock_axis,
1198                                cx,
1199                            ),
1200                        )
1201                    })
1202                    .ok()
1203                else {
1204                    return;
1205                };
1206
1207                persistence::serialize_pane_layout(adapter_name, pane_layout)
1208                    .await
1209                    .log_err();
1210
1211                this.update(cx, |this, _| {
1212                    this._schedule_serialize.take();
1213                })
1214                .ok();
1215            }));
1216        }
1217    }
1218
1219    pub(crate) fn handle_pane_event(
1220        this: &mut RunningState,
1221        source_pane: &Entity<Pane>,
1222        event: &Event,
1223        window: &mut Window,
1224        cx: &mut Context<RunningState>,
1225    ) {
1226        this.serialize_layout(window, cx);
1227        match event {
1228            Event::Remove { .. } => {
1229                let _did_find_pane = this.panes.remove(&source_pane).is_ok();
1230                debug_assert!(_did_find_pane);
1231                cx.notify();
1232            }
1233            Event::Focus => {
1234                this.active_pane = source_pane.clone();
1235            }
1236            Event::ZoomIn => {
1237                source_pane.update(cx, |pane, cx| {
1238                    pane.set_zoomed(true, cx);
1239                });
1240                cx.notify();
1241            }
1242            Event::ZoomOut => {
1243                source_pane.update(cx, |pane, cx| {
1244                    pane.set_zoomed(false, cx);
1245                });
1246                cx.notify();
1247            }
1248            _ => {}
1249        }
1250    }
1251
1252    pub(crate) fn activate_pane_in_direction(
1253        &mut self,
1254        direction: SplitDirection,
1255        window: &mut Window,
1256        cx: &mut Context<Self>,
1257    ) {
1258        let active_pane = self.active_pane.clone();
1259        if let Some(pane) = self
1260            .panes
1261            .find_pane_in_direction(&active_pane, direction, cx)
1262        {
1263            pane.update(cx, |pane, cx| {
1264                pane.focus_active_item(window, cx);
1265            })
1266        } else {
1267            self.workspace
1268                .update(cx, |workspace, cx| {
1269                    workspace.activate_pane_in_direction(direction, window, cx)
1270                })
1271                .ok();
1272        }
1273    }
1274
1275    pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1276        if self.thread_id.is_some() {
1277            self.stack_frame_list
1278                .update(cx, |list, cx| {
1279                    let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1280                        return Task::ready(Ok(()));
1281                    };
1282                    list.go_to_stack_frame(stack_frame_id, window, cx)
1283                })
1284                .detach();
1285        }
1286    }
1287
1288    pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1289        self.variable_list.read(cx).has_open_context_menu()
1290    }
1291
1292    pub fn session(&self) -> &Entity<Session> {
1293        &self.session
1294    }
1295
1296    pub fn session_id(&self) -> SessionId {
1297        self.session_id
1298    }
1299
1300    pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1301        self.stack_frame_list.read(cx).opened_stack_frame_id()
1302    }
1303
1304    pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1305        &self.stack_frame_list
1306    }
1307
1308    #[cfg(test)]
1309    pub fn console(&self) -> &Entity<Console> {
1310        &self.console
1311    }
1312
1313    #[cfg(test)]
1314    pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1315        &self.module_list
1316    }
1317
1318    pub(crate) fn activate_item(&self, item: DebuggerPaneItem, window: &mut Window, cx: &mut App) {
1319        let (variable_list_position, pane) = self
1320            .panes
1321            .panes()
1322            .into_iter()
1323            .find_map(|pane| {
1324                pane.read(cx)
1325                    .items_of_type::<SubView>()
1326                    .position(|view| view.read(cx).view_kind() == item)
1327                    .map(|view| (view, pane))
1328            })
1329            .unwrap();
1330        pane.update(cx, |this, cx| {
1331            this.activate_item(variable_list_position, true, true, window, cx);
1332        })
1333    }
1334
1335    #[cfg(test)]
1336    pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1337        &self.variable_list
1338    }
1339
1340    #[cfg(test)]
1341    pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1342        persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1343    }
1344
1345    pub fn capabilities(&self, cx: &App) -> Capabilities {
1346        self.session().read(cx).capabilities().clone()
1347    }
1348
1349    pub fn select_current_thread(
1350        &mut self,
1351        threads: &Vec<(Thread, ThreadStatus)>,
1352        window: &mut Window,
1353        cx: &mut Context<Self>,
1354    ) {
1355        let selected_thread = self
1356            .thread_id
1357            .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1358            .or_else(|| threads.first());
1359
1360        let Some((selected_thread, _)) = selected_thread else {
1361            return;
1362        };
1363
1364        if Some(ThreadId(selected_thread.id)) != self.thread_id {
1365            self.select_thread(ThreadId(selected_thread.id), window, cx);
1366        }
1367    }
1368
1369    pub(crate) fn selected_thread_id(&self) -> Option<ThreadId> {
1370        self.thread_id
1371    }
1372
1373    pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1374        self.thread_id
1375            .map(|id| self.session().read(cx).thread_status(id))
1376    }
1377
1378    pub(crate) fn select_thread(
1379        &mut self,
1380        thread_id: ThreadId,
1381        window: &mut Window,
1382        cx: &mut Context<Self>,
1383    ) {
1384        if self.thread_id.is_some_and(|id| id == thread_id) {
1385            return;
1386        }
1387
1388        self.thread_id = Some(thread_id);
1389
1390        self.stack_frame_list
1391            .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1392    }
1393
1394    pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1395        let Some(thread_id) = self.thread_id else {
1396            return;
1397        };
1398
1399        self.session().update(cx, |state, cx| {
1400            state.continue_thread(thread_id, cx);
1401        });
1402    }
1403
1404    pub fn step_over(&mut self, cx: &mut Context<Self>) {
1405        let Some(thread_id) = self.thread_id else {
1406            return;
1407        };
1408
1409        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1410
1411        self.session().update(cx, |state, cx| {
1412            state.step_over(thread_id, granularity, cx);
1413        });
1414    }
1415
1416    pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1417        let Some(thread_id) = self.thread_id else {
1418            return;
1419        };
1420
1421        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1422
1423        self.session().update(cx, |state, cx| {
1424            state.step_in(thread_id, granularity, cx);
1425        });
1426    }
1427
1428    pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1429        let Some(thread_id) = self.thread_id else {
1430            return;
1431        };
1432
1433        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1434
1435        self.session().update(cx, |state, cx| {
1436            state.step_out(thread_id, granularity, cx);
1437        });
1438    }
1439
1440    pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1441        let Some(thread_id) = self.thread_id else {
1442            return;
1443        };
1444
1445        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1446
1447        self.session().update(cx, |state, cx| {
1448            state.step_back(thread_id, granularity, cx);
1449        });
1450    }
1451
1452    pub fn restart_session(&self, cx: &mut Context<Self>) {
1453        self.session().update(cx, |state, cx| {
1454            state.restart(None, cx);
1455        });
1456    }
1457
1458    pub fn pause_thread(&self, cx: &mut Context<Self>) {
1459        let Some(thread_id) = self.thread_id else {
1460            return;
1461        };
1462
1463        self.session().update(cx, |state, cx| {
1464            state.pause_thread(thread_id, cx);
1465        });
1466    }
1467
1468    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1469        self.workspace
1470            .update(cx, |workspace, cx| {
1471                workspace
1472                    .project()
1473                    .read(cx)
1474                    .breakpoint_store()
1475                    .update(cx, |store, cx| {
1476                        store.remove_active_position(Some(self.session_id), cx)
1477                    })
1478            })
1479            .log_err();
1480
1481        self.session.update(cx, |session, cx| {
1482            session.shutdown(cx).detach();
1483        })
1484    }
1485
1486    pub fn stop_thread(&self, cx: &mut Context<Self>) {
1487        let Some(thread_id) = self.thread_id else {
1488            return;
1489        };
1490
1491        self.workspace
1492            .update(cx, |workspace, cx| {
1493                workspace
1494                    .project()
1495                    .read(cx)
1496                    .breakpoint_store()
1497                    .update(cx, |store, cx| {
1498                        store.remove_active_position(Some(self.session_id), cx)
1499                    })
1500            })
1501            .log_err();
1502
1503        self.session().update(cx, |state, cx| {
1504            state.terminate_threads(Some(vec![thread_id; 1]), cx);
1505        });
1506    }
1507
1508    pub fn detach_client(&self, cx: &mut Context<Self>) {
1509        self.session().update(cx, |state, cx| {
1510            state.disconnect_client(cx);
1511        });
1512    }
1513
1514    pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1515        self.session.update(cx, |session, cx| {
1516            session.toggle_ignore_breakpoints(cx).detach();
1517        });
1518    }
1519
1520    fn default_pane_layout(
1521        project: Entity<Project>,
1522        workspace: &WeakEntity<Workspace>,
1523        stack_frame_list: &Entity<StackFrameList>,
1524        variable_list: &Entity<VariableList>,
1525        console: &Entity<Console>,
1526        breakpoints: &Entity<BreakpointList>,
1527        debug_terminal: &Entity<DebugTerminal>,
1528        dock_axis: Axis,
1529        subscriptions: &mut HashMap<EntityId, Subscription>,
1530        window: &mut Window,
1531        cx: &mut Context<'_, RunningState>,
1532    ) -> Member {
1533        let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1534        leftmost_pane.update(cx, |this, cx| {
1535            this.add_item(
1536                Box::new(SubView::new(
1537                    this.focus_handle(cx),
1538                    stack_frame_list.clone().into(),
1539                    DebuggerPaneItem::Frames,
1540                    None,
1541                    cx,
1542                )),
1543                true,
1544                false,
1545                None,
1546                window,
1547                cx,
1548            );
1549            this.add_item(
1550                Box::new(SubView::new(
1551                    breakpoints.focus_handle(cx),
1552                    breakpoints.clone().into(),
1553                    DebuggerPaneItem::BreakpointList,
1554                    None,
1555                    cx,
1556                )),
1557                true,
1558                false,
1559                None,
1560                window,
1561                cx,
1562            );
1563            this.activate_item(0, false, false, window, cx);
1564        });
1565        let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1566
1567        center_pane.update(cx, |this, cx| {
1568            let weak_console = console.downgrade();
1569            this.add_item(
1570                Box::new(SubView::new(
1571                    console.focus_handle(cx),
1572                    console.clone().into(),
1573                    DebuggerPaneItem::Console,
1574                    Some(Box::new(move |cx| {
1575                        weak_console
1576                            .read_with(cx, |console, cx| console.show_indicator(cx))
1577                            .unwrap_or_default()
1578                    })),
1579                    cx,
1580                )),
1581                true,
1582                false,
1583                None,
1584                window,
1585                cx,
1586            );
1587
1588            this.add_item(
1589                Box::new(SubView::new(
1590                    variable_list.focus_handle(cx),
1591                    variable_list.clone().into(),
1592                    DebuggerPaneItem::Variables,
1593                    None,
1594                    cx,
1595                )),
1596                true,
1597                false,
1598                None,
1599                window,
1600                cx,
1601            );
1602            this.activate_item(0, false, false, window, cx);
1603        });
1604
1605        let rightmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1606        rightmost_pane.update(cx, |this, cx| {
1607            this.add_item(
1608                Box::new(SubView::new(
1609                    debug_terminal.focus_handle(cx),
1610                    debug_terminal.clone().into(),
1611                    DebuggerPaneItem::Terminal,
1612                    None,
1613                    cx,
1614                )),
1615                false,
1616                false,
1617                None,
1618                window,
1619                cx,
1620            );
1621        });
1622
1623        subscriptions.extend(
1624            [&leftmost_pane, &center_pane, &rightmost_pane]
1625                .into_iter()
1626                .map(|entity| {
1627                    (
1628                        entity.entity_id(),
1629                        cx.subscribe_in(entity, window, Self::handle_pane_event),
1630                    )
1631                }),
1632        );
1633
1634        let group_root = workspace::PaneAxis::new(
1635            dock_axis.invert(),
1636            [leftmost_pane, center_pane, rightmost_pane]
1637                .into_iter()
1638                .map(workspace::Member::Pane)
1639                .collect(),
1640        );
1641
1642        Member::Axis(group_root)
1643    }
1644
1645    pub(crate) fn invert_axies(&mut self) {
1646        self.dock_axis = self.dock_axis.invert();
1647        self.panes.invert_axies();
1648    }
1649}
1650
1651impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1652
1653impl Focusable for RunningState {
1654    fn focus_handle(&self, _: &App) -> FocusHandle {
1655        self.focus_handle.clone()
1656    }
1657}