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                Self::substitute_variables_in_config(&mut config, &task_context);
 931            } else {
 932                anyhow::bail!("No request or build provided");
 933            };
 934
 935            Ok(DebugTaskDefinition {
 936                label,
 937                adapter: DebugAdapterName(adapter),
 938                config,
 939                tcp_connection,
 940            })
 941        })
 942    }
 943
 944    fn handle_run_in_terminal(
 945        &self,
 946        request: &RunInTerminalRequestArguments,
 947        mut sender: mpsc::Sender<Result<u32>>,
 948        window: &mut Window,
 949        cx: &mut Context<Self>,
 950    ) -> Task<Result<()>> {
 951        let running = cx.entity();
 952        let Ok(project) = self
 953            .workspace
 954            .update(cx, |workspace, _| workspace.project().clone())
 955        else {
 956            return Task::ready(Err(anyhow!("no workspace")));
 957        };
 958        let session = self.session.read(cx);
 959
 960        let cwd = Some(&request.cwd)
 961            .filter(|cwd| cwd.len() > 0)
 962            .map(PathBuf::from)
 963            .or_else(|| session.binary().cwd.clone());
 964
 965        let mut args = request.args.clone();
 966
 967        // Handle special case for NodeJS debug adapter
 968        // If only the Node binary path is provided, we set the command to None
 969        // This prevents the NodeJS REPL from appearing, which is not the desired behavior
 970        // The expected usage is for users to provide their own Node command, e.g., `node test.js`
 971        // This allows the NodeJS debug client to attach correctly
 972        let command = if args.len() > 1 {
 973            Some(args.remove(0))
 974        } else {
 975            None
 976        };
 977
 978        let mut envs: HashMap<String, String> = Default::default();
 979        if let Some(Value::Object(env)) = &request.env {
 980            for (key, value) in env {
 981                let value_str = match (key.as_str(), value) {
 982                    (_, Value::String(value)) => value,
 983                    _ => continue,
 984                };
 985
 986                envs.insert(key.clone(), value_str.clone());
 987            }
 988        }
 989
 990        let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
 991        let kind = if let Some(command) = command {
 992            let title = request.title.clone().unwrap_or(command.clone());
 993            TerminalKind::Task(task::SpawnInTerminal {
 994                id: task::TaskId("debug".to_string()),
 995                full_label: title.clone(),
 996                label: title.clone(),
 997                command: command.clone(),
 998                args,
 999                command_label: title.clone(),
1000                cwd,
1001                env: envs,
1002                use_new_terminal: true,
1003                allow_concurrent_runs: true,
1004                reveal: task::RevealStrategy::NoFocus,
1005                reveal_target: task::RevealTarget::Dock,
1006                hide: task::HideStrategy::Never,
1007                shell,
1008                show_summary: false,
1009                show_command: false,
1010                show_rerun: false,
1011            })
1012        } else {
1013            TerminalKind::Shell(cwd.map(|c| c.to_path_buf()))
1014        };
1015
1016        let workspace = self.workspace.clone();
1017        let weak_project = project.downgrade();
1018
1019        let terminal_task = project.update(cx, |project, cx| {
1020            project.create_terminal(kind, window.window_handle(), cx)
1021        });
1022        let terminal_task = cx.spawn_in(window, async move |_, cx| {
1023            let terminal = terminal_task.await?;
1024
1025            let terminal_view = cx.new_window_entity(|window, cx| {
1026                TerminalView::new(
1027                    terminal.clone(),
1028                    workspace,
1029                    None,
1030                    weak_project,
1031                    false,
1032                    window,
1033                    cx,
1034                )
1035            })?;
1036
1037            running.update_in(cx, |running, window, cx| {
1038                running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1039                running.debug_terminal.update(cx, |debug_terminal, cx| {
1040                    debug_terminal.terminal = Some(terminal_view);
1041                    cx.notify();
1042                });
1043            })?;
1044
1045            terminal.read_with(cx, |terminal, _| {
1046                terminal
1047                    .pty_info
1048                    .pid()
1049                    .map(|pid| pid.as_u32())
1050                    .context("Terminal was spawned but PID was not available")
1051            })?
1052        });
1053
1054        cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1055    }
1056
1057    fn create_sub_view(
1058        &self,
1059        item_kind: DebuggerPaneItem,
1060        _pane: &Entity<Pane>,
1061        cx: &mut Context<Self>,
1062    ) -> Box<dyn ItemHandle> {
1063        match item_kind {
1064            DebuggerPaneItem::Console => {
1065                let weak_console = self.console.clone().downgrade();
1066
1067                Box::new(SubView::new(
1068                    self.console.focus_handle(cx),
1069                    self.console.clone().into(),
1070                    item_kind,
1071                    Some(Box::new(move |cx| {
1072                        weak_console
1073                            .read_with(cx, |console, cx| console.show_indicator(cx))
1074                            .unwrap_or_default()
1075                    })),
1076                    cx,
1077                ))
1078            }
1079            DebuggerPaneItem::Variables => Box::new(SubView::new(
1080                self.variable_list.focus_handle(cx),
1081                self.variable_list.clone().into(),
1082                item_kind,
1083                None,
1084                cx,
1085            )),
1086            DebuggerPaneItem::BreakpointList => Box::new(SubView::new(
1087                self.breakpoint_list.focus_handle(cx),
1088                self.breakpoint_list.clone().into(),
1089                item_kind,
1090                None,
1091                cx,
1092            )),
1093            DebuggerPaneItem::Frames => Box::new(SubView::new(
1094                self.stack_frame_list.focus_handle(cx),
1095                self.stack_frame_list.clone().into(),
1096                item_kind,
1097                None,
1098                cx,
1099            )),
1100            DebuggerPaneItem::Modules => Box::new(SubView::new(
1101                self.module_list.focus_handle(cx),
1102                self.module_list.clone().into(),
1103                item_kind,
1104                None,
1105                cx,
1106            )),
1107            DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1108                self.loaded_sources_list.focus_handle(cx),
1109                self.loaded_sources_list.clone().into(),
1110                item_kind,
1111                None,
1112                cx,
1113            )),
1114            DebuggerPaneItem::Terminal => Box::new(SubView::new(
1115                self.debug_terminal.focus_handle(cx),
1116                self.debug_terminal.clone().into(),
1117                item_kind,
1118                None,
1119                cx,
1120            )),
1121        }
1122    }
1123
1124    pub(crate) fn ensure_pane_item(
1125        &mut self,
1126        item_kind: DebuggerPaneItem,
1127        window: &mut Window,
1128        cx: &mut Context<Self>,
1129    ) {
1130        if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1131            return;
1132        };
1133        let pane = self.panes.last_pane();
1134        let sub_view = self.create_sub_view(item_kind, &pane, cx);
1135
1136        pane.update(cx, |pane, cx| {
1137            pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1138        })
1139    }
1140
1141    pub(crate) fn add_pane_item(
1142        &mut self,
1143        item_kind: DebuggerPaneItem,
1144        position: Point<Pixels>,
1145        window: &mut Window,
1146        cx: &mut Context<Self>,
1147    ) {
1148        debug_assert!(
1149            item_kind.is_supported(self.session.read(cx).capabilities()),
1150            "We should only allow adding supported item kinds"
1151        );
1152
1153        if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1154            let sub_view = self.create_sub_view(item_kind, pane, cx);
1155
1156            pane.update(cx, |pane, cx| {
1157                pane.add_item(sub_view, false, false, None, window, cx);
1158            })
1159        }
1160    }
1161
1162    pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1163        let caps = self.session.read(cx).capabilities();
1164        let mut pane_item_status = IndexMap::from_iter(
1165            DebuggerPaneItem::all()
1166                .iter()
1167                .filter(|kind| kind.is_supported(&caps))
1168                .map(|kind| (*kind, false)),
1169        );
1170        self.panes.panes().iter().for_each(|pane| {
1171            pane.read(cx)
1172                .items()
1173                .filter_map(|item| item.act_as::<SubView>(cx))
1174                .for_each(|view| {
1175                    pane_item_status.insert(view.read(cx).kind, true);
1176                });
1177        });
1178
1179        pane_item_status
1180    }
1181
1182    pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1183        if self._schedule_serialize.is_none() {
1184            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1185                cx.background_executor()
1186                    .timer(Duration::from_millis(100))
1187                    .await;
1188
1189                let Some((adapter_name, pane_layout)) = this
1190                    .read_with(cx, |this, cx| {
1191                        let adapter_name = this.session.read(cx).adapter();
1192                        (
1193                            adapter_name,
1194                            persistence::build_serialized_layout(
1195                                &this.panes.root,
1196                                this.dock_axis,
1197                                cx,
1198                            ),
1199                        )
1200                    })
1201                    .ok()
1202                else {
1203                    return;
1204                };
1205
1206                persistence::serialize_pane_layout(adapter_name, pane_layout)
1207                    .await
1208                    .log_err();
1209
1210                this.update(cx, |this, _| {
1211                    this._schedule_serialize.take();
1212                })
1213                .ok();
1214            }));
1215        }
1216    }
1217
1218    pub(crate) fn handle_pane_event(
1219        this: &mut RunningState,
1220        source_pane: &Entity<Pane>,
1221        event: &Event,
1222        window: &mut Window,
1223        cx: &mut Context<RunningState>,
1224    ) {
1225        this.serialize_layout(window, cx);
1226        match event {
1227            Event::Remove { .. } => {
1228                let _did_find_pane = this.panes.remove(&source_pane).is_ok();
1229                debug_assert!(_did_find_pane);
1230                cx.notify();
1231            }
1232            Event::Focus => {
1233                this.active_pane = Some(source_pane.clone());
1234            }
1235            Event::ZoomIn => {
1236                source_pane.update(cx, |pane, cx| {
1237                    pane.set_zoomed(true, cx);
1238                });
1239                cx.notify();
1240            }
1241            Event::ZoomOut => {
1242                source_pane.update(cx, |pane, cx| {
1243                    pane.set_zoomed(false, cx);
1244                });
1245                cx.notify();
1246            }
1247            _ => {}
1248        }
1249    }
1250
1251    pub(crate) fn activate_pane_in_direction(
1252        &mut self,
1253        direction: SplitDirection,
1254        window: &mut Window,
1255        cx: &mut Context<Self>,
1256    ) {
1257        if let Some(pane) = self
1258            .active_pane
1259            .as_ref()
1260            .and_then(|pane| self.panes.find_pane_in_direction(pane, direction, cx))
1261        {
1262            pane.update(cx, |pane, cx| {
1263                pane.focus_active_item(window, cx);
1264            })
1265        } else {
1266            self.workspace
1267                .update(cx, |workspace, cx| {
1268                    workspace.activate_pane_in_direction(direction, window, cx)
1269                })
1270                .ok();
1271        }
1272    }
1273
1274    pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1275        if self.thread_id.is_some() {
1276            self.stack_frame_list
1277                .update(cx, |list, cx| {
1278                    let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1279                        return Task::ready(Ok(()));
1280                    };
1281                    list.go_to_stack_frame(stack_frame_id, window, cx)
1282                })
1283                .detach();
1284        }
1285    }
1286
1287    pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1288        self.variable_list.read(cx).has_open_context_menu()
1289    }
1290
1291    pub fn session(&self) -> &Entity<Session> {
1292        &self.session
1293    }
1294
1295    pub fn session_id(&self) -> SessionId {
1296        self.session_id
1297    }
1298
1299    pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1300        self.stack_frame_list.read(cx).opened_stack_frame_id()
1301    }
1302
1303    pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1304        &self.stack_frame_list
1305    }
1306
1307    #[cfg(test)]
1308    pub fn console(&self) -> &Entity<Console> {
1309        &self.console
1310    }
1311
1312    #[cfg(test)]
1313    pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1314        &self.module_list
1315    }
1316
1317    pub(crate) fn activate_item(&self, item: DebuggerPaneItem, window: &mut Window, cx: &mut App) {
1318        let (variable_list_position, pane) = self
1319            .panes
1320            .panes()
1321            .into_iter()
1322            .find_map(|pane| {
1323                pane.read(cx)
1324                    .items_of_type::<SubView>()
1325                    .position(|view| view.read(cx).view_kind() == item)
1326                    .map(|view| (view, pane))
1327            })
1328            .unwrap();
1329        pane.update(cx, |this, cx| {
1330            this.activate_item(variable_list_position, true, true, window, cx);
1331        })
1332    }
1333
1334    #[cfg(test)]
1335    pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1336        &self.variable_list
1337    }
1338
1339    #[cfg(test)]
1340    pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1341        persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1342    }
1343
1344    pub fn capabilities(&self, cx: &App) -> Capabilities {
1345        self.session().read(cx).capabilities().clone()
1346    }
1347
1348    pub fn select_current_thread(
1349        &mut self,
1350        threads: &Vec<(Thread, ThreadStatus)>,
1351        window: &mut Window,
1352        cx: &mut Context<Self>,
1353    ) {
1354        let selected_thread = self
1355            .thread_id
1356            .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1357            .or_else(|| threads.first());
1358
1359        let Some((selected_thread, _)) = selected_thread else {
1360            return;
1361        };
1362
1363        if Some(ThreadId(selected_thread.id)) != self.thread_id {
1364            self.select_thread(ThreadId(selected_thread.id), window, cx);
1365        }
1366    }
1367
1368    pub(crate) fn selected_thread_id(&self) -> Option<ThreadId> {
1369        self.thread_id
1370    }
1371
1372    pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1373        self.thread_id
1374            .map(|id| self.session().read(cx).thread_status(id))
1375    }
1376
1377    pub(crate) fn select_thread(
1378        &mut self,
1379        thread_id: ThreadId,
1380        window: &mut Window,
1381        cx: &mut Context<Self>,
1382    ) {
1383        if self.thread_id.is_some_and(|id| id == thread_id) {
1384            return;
1385        }
1386
1387        self.thread_id = Some(thread_id);
1388
1389        self.stack_frame_list
1390            .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1391    }
1392
1393    pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1394        let Some(thread_id) = self.thread_id else {
1395            return;
1396        };
1397
1398        self.session().update(cx, |state, cx| {
1399            state.continue_thread(thread_id, cx);
1400        });
1401    }
1402
1403    pub fn step_over(&mut self, cx: &mut Context<Self>) {
1404        let Some(thread_id) = self.thread_id else {
1405            return;
1406        };
1407
1408        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1409
1410        self.session().update(cx, |state, cx| {
1411            state.step_over(thread_id, granularity, cx);
1412        });
1413    }
1414
1415    pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1416        let Some(thread_id) = self.thread_id else {
1417            return;
1418        };
1419
1420        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1421
1422        self.session().update(cx, |state, cx| {
1423            state.step_in(thread_id, granularity, cx);
1424        });
1425    }
1426
1427    pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1428        let Some(thread_id) = self.thread_id else {
1429            return;
1430        };
1431
1432        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1433
1434        self.session().update(cx, |state, cx| {
1435            state.step_out(thread_id, granularity, cx);
1436        });
1437    }
1438
1439    pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1440        let Some(thread_id) = self.thread_id else {
1441            return;
1442        };
1443
1444        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1445
1446        self.session().update(cx, |state, cx| {
1447            state.step_back(thread_id, granularity, cx);
1448        });
1449    }
1450
1451    pub fn restart_session(&self, cx: &mut Context<Self>) {
1452        self.session().update(cx, |state, cx| {
1453            state.restart(None, cx);
1454        });
1455    }
1456
1457    pub fn pause_thread(&self, cx: &mut Context<Self>) {
1458        let Some(thread_id) = self.thread_id else {
1459            return;
1460        };
1461
1462        self.session().update(cx, |state, cx| {
1463            state.pause_thread(thread_id, cx);
1464        });
1465    }
1466
1467    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1468        self.workspace
1469            .update(cx, |workspace, cx| {
1470                workspace
1471                    .project()
1472                    .read(cx)
1473                    .breakpoint_store()
1474                    .update(cx, |store, cx| {
1475                        store.remove_active_position(Some(self.session_id), cx)
1476                    })
1477            })
1478            .log_err();
1479
1480        self.session.update(cx, |session, cx| {
1481            session.shutdown(cx).detach();
1482        })
1483    }
1484
1485    pub fn stop_thread(&self, cx: &mut Context<Self>) {
1486        let Some(thread_id) = self.thread_id else {
1487            return;
1488        };
1489
1490        self.workspace
1491            .update(cx, |workspace, cx| {
1492                workspace
1493                    .project()
1494                    .read(cx)
1495                    .breakpoint_store()
1496                    .update(cx, |store, cx| {
1497                        store.remove_active_position(Some(self.session_id), cx)
1498                    })
1499            })
1500            .log_err();
1501
1502        self.session().update(cx, |state, cx| {
1503            state.terminate_threads(Some(vec![thread_id; 1]), cx);
1504        });
1505    }
1506
1507    pub fn detach_client(&self, cx: &mut Context<Self>) {
1508        self.session().update(cx, |state, cx| {
1509            state.disconnect_client(cx);
1510        });
1511    }
1512
1513    pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1514        self.session.update(cx, |session, cx| {
1515            session.toggle_ignore_breakpoints(cx).detach();
1516        });
1517    }
1518
1519    fn default_pane_layout(
1520        project: Entity<Project>,
1521        workspace: &WeakEntity<Workspace>,
1522        stack_frame_list: &Entity<StackFrameList>,
1523        variable_list: &Entity<VariableList>,
1524        console: &Entity<Console>,
1525        breakpoints: &Entity<BreakpointList>,
1526        debug_terminal: &Entity<DebugTerminal>,
1527        dock_axis: Axis,
1528        subscriptions: &mut HashMap<EntityId, Subscription>,
1529        window: &mut Window,
1530        cx: &mut Context<'_, RunningState>,
1531    ) -> Member {
1532        let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1533        leftmost_pane.update(cx, |this, cx| {
1534            this.add_item(
1535                Box::new(SubView::new(
1536                    this.focus_handle(cx),
1537                    stack_frame_list.clone().into(),
1538                    DebuggerPaneItem::Frames,
1539                    None,
1540                    cx,
1541                )),
1542                true,
1543                false,
1544                None,
1545                window,
1546                cx,
1547            );
1548            this.add_item(
1549                Box::new(SubView::new(
1550                    breakpoints.focus_handle(cx),
1551                    breakpoints.clone().into(),
1552                    DebuggerPaneItem::BreakpointList,
1553                    None,
1554                    cx,
1555                )),
1556                true,
1557                false,
1558                None,
1559                window,
1560                cx,
1561            );
1562            this.activate_item(0, false, false, window, cx);
1563        });
1564        let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1565
1566        center_pane.update(cx, |this, cx| {
1567            let weak_console = console.downgrade();
1568            this.add_item(
1569                Box::new(SubView::new(
1570                    console.focus_handle(cx),
1571                    console.clone().into(),
1572                    DebuggerPaneItem::Console,
1573                    Some(Box::new(move |cx| {
1574                        weak_console
1575                            .read_with(cx, |console, cx| console.show_indicator(cx))
1576                            .unwrap_or_default()
1577                    })),
1578                    cx,
1579                )),
1580                true,
1581                false,
1582                None,
1583                window,
1584                cx,
1585            );
1586
1587            this.add_item(
1588                Box::new(SubView::new(
1589                    variable_list.focus_handle(cx),
1590                    variable_list.clone().into(),
1591                    DebuggerPaneItem::Variables,
1592                    None,
1593                    cx,
1594                )),
1595                true,
1596                false,
1597                None,
1598                window,
1599                cx,
1600            );
1601            this.activate_item(0, false, false, window, cx);
1602        });
1603
1604        let rightmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1605        rightmost_pane.update(cx, |this, cx| {
1606            this.add_item(
1607                Box::new(SubView::new(
1608                    debug_terminal.focus_handle(cx),
1609                    debug_terminal.clone().into(),
1610                    DebuggerPaneItem::Terminal,
1611                    None,
1612                    cx,
1613                )),
1614                false,
1615                false,
1616                None,
1617                window,
1618                cx,
1619            );
1620        });
1621
1622        subscriptions.extend(
1623            [&leftmost_pane, &center_pane, &rightmost_pane]
1624                .into_iter()
1625                .map(|entity| {
1626                    (
1627                        entity.entity_id(),
1628                        cx.subscribe_in(entity, window, Self::handle_pane_event),
1629                    )
1630                }),
1631        );
1632
1633        let group_root = workspace::PaneAxis::new(
1634            dock_axis.invert(),
1635            [leftmost_pane, center_pane, rightmost_pane]
1636                .into_iter()
1637                .map(workspace::Member::Pane)
1638                .collect(),
1639        );
1640
1641        Member::Axis(group_root)
1642    }
1643
1644    pub(crate) fn invert_axies(&mut self) {
1645        self.dock_axis = self.dock_axis.invert();
1646        self.panes.invert_axies();
1647    }
1648}
1649
1650impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1651
1652impl Focusable for RunningState {
1653    fn focus_handle(&self, _: &App) -> FocusHandle {
1654        self.focus_handle.clone()
1655    }
1656}