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