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