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