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