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